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

Last change on this file since 771 was 771, 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;
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  %-11s  %-15s\n";
92    printf($positions,
93        'ID',
94        'USERNAME',
95        'LAST_ACCESS',
96        'LAST_IP'
97    );
98    foreach ($users as $u) {
99        printf($positions,
100            $u[$auth->getParam('db_primary_key')],
101            $u['username'],
102            date($app->getParam('date_format'), strtotime($u['last_access_datetime'])),
103            $u['last_login_ip']
104        );
105    }
106    break;
107
108case 'create':
109    $username = User_CLI::getArg(2, 'username');
110    $password = User_CLI::getArg(3, 'password');
111    $user_id = $auth->getUserID($username);
112    if (false !== $auth->getUserID($username)) {
113        printf("User '%s' already exists. Use 'update' instead.\n", $username);
114        exit(1);
115    }
116    $user_id = User_CLI::create($username, $password);
117    printf("Created user '%s' (user_id %s).\n", $username, $user_id);
118    break;
119
120case 'update':
121    $username = User_CLI::getArg(2, 'username');
122    $password = User_CLI::getArg(3, 'password');
123    if (!$user_id = $auth->getUserID($username)) {
124        printf("User '%s' not found. Use 'create' first.\n", $username);
125        exit(1);
126    }
127    $auth->setPassword($user_id, $password);
128    printf("Updated user '%s' password (user_id %s).\n", $username, $user_id);
129    break;
130
131case 'remove':
132    $username = User_CLI::getArg(2, 'username');
133    if (!$user_id = $auth->getUserID($username)) {
134        printf("User '%s' not found.\n", $username);
135        exit(1);
136    }
137    User_CLI::remove($username);
138    printf("Removed user '%s' (user_id %s).\n", $username, $user_id);
139    break;
140
141default:
142    printf("Unknown command: %s\n", $command);
143    break;
144}
145
146// End of script.
147exit(0);
148
149
150/********************************************************************
151* FUNCTIONS
152********************************************************************/
153
154/*
155* Static methods for this script only.
156*/
157class User_CLI
158{
159    static public function getArg($pos, $name)
160    {
161        if (!isset($_SERVER['argv'][$pos]) || $_SERVER['argv'][$pos] == '') {
162            // Required arguments missing.
163            printf("Required argument %s is missing. Lost? Try `%s help`.\n", strtoupper($name), basename($_SERVER['argv'][0]));
164            exit(1);
165        }
166
167        return $_SERVER['argv'][$pos];
168    }
169
170    static public function getList()
171    {
172        global $auth, $db;
173
174        $qid = $db->query("
175            SELECT *
176            FROM `" . $auth->getParam('db_table') . "`
177            LIMIT 1000
178        ");
179        $results = array();
180        while ($row = mysql_fetch_assoc($qid)) {
181            $results[] = $row;
182        }
183
184        return $results;
185    }
186
187    static public function create($username, $password)
188    {
189        global $auth, $db;
190
191        $qid = $db->query("DESCRIBE " . $auth->getParam('db_table'));
192        $cols = array();
193        while ($row = mysql_fetch_row($qid)) {
194            $cols[] = $row[0];
195        }
196        $addtl_cols = array();
197        $addtl_vals = array();
198        if (in_array('account_id', $cols)) {
199            $addtl_cols[] = ", account_id";
200            $addtl_vals[] = ", '1'";
201        }
202        $db->query("
203            INSERT INTO `" . $auth->getParam('db_table') . "` (
204                `" . $auth->getParam('db_primary_key') . "`,
205                " . $auth->getParam('db_username_column') . join("\n", $addtl_cols) . "
206            ) VALUES (
207                NULL,
208                '" . $db->escapeString($username) . "'" . join("\n", $addtl_vals) . "
209            )
210        ");
211        $user_id = mysql_insert_id($db->getDBH());
212        $auth->setPassword($user_id, $password);
213
214        return $user_id;
215    }
216
217    static public function remove($username)
218    {
219        global $auth, $db;
220
221        $qid = $db->query("
222            DELETE FROM `" . $auth->getParam('db_table') . "`
223            WHERE `" . $auth->getParam('db_username_column') . "` = '" . $db->escapeString($username) . "'
224        ");
225    }
226
227    static public function usage()
228    {
229        ?>
230Manage codebase (Auth_SQL) user accounts.
231
232Usage: <?php echo basename($_SERVER['argv'][0]); ?> COMMAND [
]
233
234COMMANDS
235
236    help                        Display this help
237    list                        List all users.
238    create USERNAME PASSWORD    Create a user USERNAME authenticated by PASSWORD.
239    update USERNAME PASSWORD    Update the password for user USERNAME to PASSWORD.
240
241This script must be run in a common site directory configured with a DB auth file,
242e.g., `lib/db_auth.json`, readable by the user executing this script.
243<?php
244    }
245}
Note: See TracBrowser for help on using the repository browser.