source: trunk/bin/user.cli.php @ 770

Last change on this file since 770 was 770, checked in by anonymous, 23 months ago

Minor fixes

  • Property svn:executable set to *
File size: 7.2 KB
Line 
1#!/usr/bin/env php
2<?php
3/**
4 * The Strangecode Codebase - a general application development framework for PHP
5 * For details visit the project site: <http://trac.strangecode.com/codebase/>
6 * Copyright 2001-2012 Strangecode, LLC
7 *
8 * This file is part of The Strangecode Codebase.
9 *
10 * The Strangecode Codebase is free software: you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License as published by the
12 * Free Software Foundation, either version 3 of the License, or (at your option)
13 * any later version.
14 *
15 * The Strangecode Codebase is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
18 * details.
19 *
20 * You should have received a copy of the GNU General Public License along with
21 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/*
25* user.cli.php
26*
27* @author   Quinn Comendant <quinn@strangecode.com>
28* @version  1.0
29* @since    02 May 2019 14:21:12
30*/
31
32/********************************************************************
33* CONFIG
34********************************************************************/
35
36// Find a _config.inc.php file and load it.
37$_config_file = false;
38$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
39$rii->setMaxDepth(1);
40foreach ($rii as $filename => $file) {
41    if (mb_strpos($filename, '/_config.inc.php') !== false
42    && preg_match('/^\$auth = new Auth/m', file_get_contents($filename))
43    && preg_match('/^\$(db|pdo) =/m', file_get_contents($filename))) {
44        $_config_file = $filename;
45        echo "Loading $_config_file\n";
46        break;
47    }
48}
49if (!$_config_file) {
50    echo "Error: could not find a satisfactory _config.inc.php in current directory or subdirectories.\n";
51    exit(1);
52}
53define('_CLI', true);
54require_once $_config_file;
55die;///
56
57/********************************************************************
58* MAIN
59********************************************************************/
60
61if (isset($CFG) && is_object($CFG)) {
62    echo "user.cli.php is not compatible with codebase v1.\n";
63    exit(1);
64}
65
66if (!isset($db) || !($db instanceof \DB)) {
67    echo "This project doesn't have a \$db object.\n";
68    exit(1);
69}
70
71if (!isset($auth) || !($auth instanceof \Auth_SQL)) {
72    echo "This project doesn't have an \$auth object.\n";
73    exit(1);
74}
75
76if (!$auth->getParam('db_table') ||
77    !$auth->getParam('db_primary_key') ||
78    !$auth->getParam('db_username_column')) {
79    echo "This project's \$auth object does not have the required db_* parameters.\n";
80    exit(1);
81}
82
83// COMMAND
84$command = User_CLI::getArg(1, 'command');
85switch ($command) {
86case 'help':
87    User_CLI::usage();
88    exit(1);
89
90case 'list':
91    $users = User_CLI::getList();
92    $positions = "%-3s  %-15s  %-11s  %-15s\n";
93    printf($positions,
94        'ID',
95        'USERNAME',
96        'LAST_ACCESS',
97        'LAST_IP'
98    );
99    foreach ($users as $u) {
100        printf($positions,
101            $u[$auth->getParam('db_primary_key')],
102            $u['username'],
103            date($app->getParam('date_format'), strtotime($u['last_access_datetime'])),
104            $u['last_login_ip']
105        );
106    }
107    break;
108
109case 'create':
110    $username = User_CLI::getArg(2, 'username');
111    $password = User_CLI::getArg(3, 'password');
112    $user_id = $auth->getUserID($username);
113    if (false !== $auth->getUserID($username)) {
114        printf("User '%s' already exists. Use 'update' instead.\n", $username);
115        exit(1);
116    }
117    $user_id = User_CLI::create($username, $password);
118    printf("Created user '%s' (user_id %s).\n", $username, $user_id);
119    break;
120
121case 'update':
122    $username = User_CLI::getArg(2, 'username');
123    $password = User_CLI::getArg(3, 'password');
124    if (!$user_id = $auth->getUserID($username)) {
125        printf("User '%s' not found. Use 'create' first.\n", $username);
126        exit(1);
127    }
128    $auth->setPassword($user_id, $password);
129    printf("Updated user '%s' password (user_id %s).\n", $username, $user_id);
130    break;
131
132case 'remove':
133    $username = User_CLI::getArg(2, 'username');
134    if (!$user_id = $auth->getUserID($username)) {
135        printf("User '%s' not found.\n", $username);
136        exit(1);
137    }
138    User_CLI::remove($username);
139    printf("Removed user '%s' (user_id %s).\n", $username, $user_id);
140    break;
141
142default:
143    printf("Unknown command: %s\n", $command);
144    break;
145}
146
147// End of script.
148exit(0);
149
150
151/********************************************************************
152* FUNCTIONS
153********************************************************************/
154
155/*
156* Static methods for this script only.
157*/
158class User_CLI
159{
160    static public function getArg($pos, $name)
161    {
162        if (!isset($_SERVER['argv'][$pos]) || $_SERVER['argv'][$pos] == '') {
163            // Required arguments missing.
164            printf("Required argument %s is missing. Lost? Try `%s help`.\n", strtoupper($name), basename($_SERVER['argv'][0]));
165            exit(1);
166        }
167
168        return $_SERVER['argv'][$pos];
169    }
170
171    static public function getList()
172    {
173        global $auth, $db;
174
175        $qid = $db->query("
176            SELECT *
177            FROM `" . $auth->getParam('db_table') . "`
178            LIMIT 1000
179        ");
180        $results = array();
181        while ($row = mysql_fetch_assoc($qid)) {
182            $results[] = $row;
183        }
184
185        return $results;
186    }
187
188    static public function create($username, $password)
189    {
190        global $auth, $db;
191
192        $qid = $db->query("DESCRIBE " . $auth->getParam('db_table'));
193        $cols = array();
194        while ($row = mysql_fetch_row($qid)) {
195            $cols[] = $row[0];
196        }
197        $addtl_cols = array();
198        $addtl_vals = array();
199        if (in_array('account_id', $cols)) {
200            $addtl_cols[] = ", account_id";
201            $addtl_vals[] = ", '1'";
202        }
203        $db->query("
204            INSERT INTO `" . $auth->getParam('db_table') . "` (
205                `" . $auth->getParam('db_primary_key') . "`,
206                " . $auth->getParam('db_username_column') . join("\n", $addtl_cols) . "
207            ) VALUES (
208                NULL,
209                '" . $db->escapeString($username) . "'" . join("\n", $addtl_vals) . "
210            )
211        ");
212        $user_id = mysql_insert_id($db->getDBH());
213        $auth->setPassword($user_id, $password);
214
215        return $user_id;
216    }
217
218    static public function remove($username)
219    {
220        global $auth, $db;
221
222        $qid = $db->query("
223            DELETE FROM `" . $auth->getParam('db_table') . "`
224            WHERE `" . $auth->getParam('db_username_column') . "` = '" . $db->escapeString($username) . "'
225        ");
226    }
227
228    static public function usage()
229    {
230        ?>
231Manage codebase (Auth_SQL) user accounts.
232
233Usage: <?php echo basename($_SERVER['argv'][0]); ?> COMMAND [
]
234
235COMMANDS
236
237    help                        Display this help
238    list                        List all users.
239    create USERNAME PASSWORD    Create a user USERNAME authenticated by PASSWORD.
240    update USERNAME PASSWORD    Update the password for user USERNAME to PASSWORD.
241
242This script must be run in a common site directory configured with a DB auth file,
243e.g., `lib/db_auth.json`, readable by the user executing this script.
244<?php
245    }
246}
Note: See TracBrowser for help on using the repository browser.