source: trunk/bin/user.cli.php

Last change on this file was 779, checked in by anonymous, 15 months ago

Allow passing an email address to user.cli.php

  • Property svn:executable set to *
File size: 7.8 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;
55
56/********************************************************************
57* MAIN
58********************************************************************/
59
60if (isset($CFG) && is_object($CFG)) {
61    echo "user.cli.php is not compatible with codebase v1.\n";
62    exit(1);
63}
64
65if (!isset($db) || !($db instanceof \DB)) {
66    echo "This project doesn't have a \$db object.\n";
67    exit(1);
68}
69
70if (!isset($auth) || !($auth instanceof \Auth_SQL)) {
71    echo "This project doesn't have an \$auth object.\n";
72    exit(1);
73}
74
75if (!$auth->getParam('db_table') ||
76    !$auth->getParam('db_primary_key') ||
77    !$auth->getParam('db_username_column')) {
78    echo "This project's \$auth object does not have the required db_* parameters.\n";
79    exit(1);
80}
81
82// COMMAND
83$command = User_CLI::getArg(1, 'command');
84switch ($command) {
85case 'help':
86    User_CLI::usage();
87    exit(1);
88
89case 'list':
90    $users = User_CLI::getList();
91    $positions = "%-3s  %-15s  %-30s  %-11s  %-15s\n";
92    printf($positions,
93        'ID',
94        'USERNAME',
95        'EMAIL',
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            $u['email'],
104            date($app->getParam('date_format'), strtotime($u['last_access_datetime'])),
105            $u['last_login_ip']
106        );
107    }
108    break;
109
110case 'create':
111    $username = User_CLI::getArg(2, 'username');
112    $password = User_CLI::getArg(3, 'password', $auth->generatePassword());
113    $email = User_CLI::getArg(4, 'email', '');
114    $user_id = $auth->getUserID($username);
115    if (false !== $auth->getUserID($username)) {
116        printf("User `%s` already exists. Use `update` instead.\n", $username);
117        exit(1);
118    }
119    $user_id = User_CLI::create($username, $password, $email);
120    printf("Created user `%s` with password `%s` (user_id %s).\n", $username, $password, $user_id);
121    break;
122
123case 'update':
124    $username = User_CLI::getArg(2, 'username');
125    $password = User_CLI::getArg(3, 'password', $auth->generatePassword());
126    if (!$user_id = $auth->getUserID($username)) {
127        printf("User `%s` not found. Use `create` first.\n", $username);
128        exit(1);
129    }
130    $auth->setPassword($user_id, $password);
131    printf("Updated user `%s` with password `%s` (user_id %s).\n", $username, $password, $user_id);
132    break;
133
134case 'remove':
135    $username = User_CLI::getArg(2, 'username');
136    if (!$user_id = $auth->getUserID($username)) {
137        printf("User `%s` not found.\n", $username);
138        exit(1);
139    }
140    User_CLI::remove($username);
141    printf("Removed user `%s` (user_id %s).\n", $username, $user_id);
142    break;
143
144default:
145    printf("Unknown command: %s\n", $command);
146    break;
147}
148
149// End of script.
150exit(0);
151
152
153/********************************************************************
154* FUNCTIONS
155********************************************************************/
156
157/*
158* Static methods for this script only.
159*/
160class User_CLI
161{
162    public static function getArg($pos, $name, $default=null)
163    {
164        if (isset($_SERVER['argv'][$pos]) && $_SERVER['argv'][$pos] != '') {
165            return $_SERVER['argv'][$pos];
166        }
167
168        if (null === $default) {
169            printf("Required argument %s is missing. Lost? Try `%s help`.\n", strtoupper($name), basename($_SERVER['argv'][0]));
170            exit(1);
171        }
172
173        return $default;
174    }
175
176    public static function getList()
177    {
178        global $auth, $db;
179
180        $qid = $db->query("
181            SELECT *
182            FROM `" . $auth->getParam('db_table') . "`
183            LIMIT 1000
184        ");
185        $results = array();
186        while ($row = mysql_fetch_assoc($qid)) {
187            $results[] = $row;
188        }
189
190        return $results;
191    }
192
193    public static function create($username, $password, $email)
194    {
195        global $auth, $db;
196
197        $qid = $db->query("DESCRIBE " . $auth->getParam('db_table'));
198        $cols = array();
199        while ($row = mysql_fetch_row($qid)) {
200            $cols[] = $row[0];
201        }
202        $addtl_cols = array();
203        $addtl_vals = array();
204        if (in_array('account_id', $cols)) {
205            $addtl_cols[] = ", account_id";
206            $addtl_vals[] = ", '1'";
207        }
208        if (in_array('email', $cols) && '' != $email) {
209            $addtl_cols[] = ", email";
210            $addtl_vals[] = sprintf(", '%s'", $db->escapeString($email));
211        }
212        $db->query("
213            INSERT INTO `" . $auth->getParam('db_table') . "` (
214                `" . $auth->getParam('db_primary_key') . "`,
215                " . $auth->getParam('db_username_column') . join("\n", $addtl_cols) . "
216            ) VALUES (
217                NULL,
218                '" . $db->escapeString($username) . "'" . join("\n", $addtl_vals) . "
219            )
220        ");
221        $user_id = mysql_insert_id($db->getDBH());
222        $auth->setPassword($user_id, $password);
223
224        return $user_id;
225    }
226
227    public static function remove($username)
228    {
229        global $auth, $db;
230
231        $qid = $db->query("
232            DELETE FROM `" . $auth->getParam('db_table') . "`
233            WHERE `" . $auth->getParam('db_username_column') . "` = '" . $db->escapeString($username) . "'
234        ");
235    }
236
237    public static function usage()
238    {
239        ?>
240Manage codebase (Auth_SQL) user accounts.
241
242Usage: <?php echo basename($_SERVER['argv'][0]); ?> COMMAND [
]
243
244COMMANDS
245
246    help                                Display this help
247    list                                List all users.
248    create USERNAME [PASSWORD] [EMAIL]  Create a user USERNAME authenticated by PASSWORD.
249    update USERNAME [PASSWORD]          Update the password for user USERNAME to PASSWORD.
250
251If PASSWORD is not given, a random password will be generated and printed to the screen.
252
253This script must be run in a common site directory configured with a DB auth file,
254e.g., `lib/db_auth.json`, readable by the user executing this script.
255<?php
256    }
257}
Note: See TracBrowser for help on using the repository browser.