OSDN Git Service

9e02172f8c7b291f950b286fbcd1dd9496037d39
[wvm/wvm.git] / php / commands / user.php
1 <?php
2
3 /**
4  * Manage users.
5  *
6  * @package wp-cli
7  */
8 class User_Command extends \WP_CLI\CommandWithDBObject {
9
10         protected $obj_type = 'user';
11         protected $obj_fields = array(
12                 'ID',
13                 'user_login',
14                 'display_name',
15                 'user_email',
16                 'user_registered',
17                 'roles'
18         );
19
20         public function __construct() {
21                 $this->fetcher = new \WP_CLI\Fetchers\User;
22         }
23
24         /**
25          * List users.
26          *
27          * ## OPTIONS
28          *
29          * [--role=<role>]
30          * : Only display users with a certain role.
31          *
32          * [--<field>=<value>]
33          * : Filter by one or more fields. For accepted fields, see get_users().
34          *
35          * [--field=<field>]
36          * : Prints the value of a single field for each user.
37          *
38          * [--fields=<fields>]
39          * : Limit the output to specific object fields. Defaults to ID,user_login,display_name,user_email,user_registered,roles
40          *
41          * [--format=<format>]
42          * : Accepted values: table, csv, json, count. Default: table
43          *
44          * ## EXAMPLES
45          *
46          *     wp user list --field=ID
47          *
48          *     wp user list --role=administrator --format=csv
49          *
50          *     wp user list --fields=display_name,user_email --format=json
51          *
52          * @subcommand list
53          */
54         public function _list( $args, $assoc_args ) {
55                 $formatter = $this->get_formatter( $assoc_args );
56
57                 if ( 'ids' == $formatter->format ) {
58                         $assoc_args['fields'] = 'ids';
59                 } else {
60                         $assoc_args['fields'] = 'all_with_meta';
61                 }
62
63                 $users = get_users( $assoc_args );
64
65                 $it = WP_CLI\Utils\iterator_map( $users, function ( $user ) {
66                         if ( !is_object( $user ) )
67                                 return $user;
68
69                         $user->roles = implode( ',', $user->roles );
70
71                         return $user;
72                 } );
73
74                 $formatter->display_items( $it );
75         }
76
77         /**
78          * Get a single user.
79          *
80          * ## OPTIONS
81          *
82          * <user>
83          * : User ID or user login.
84          *
85          * [--field=<field>]
86          * : Instead of returning the whole user, returns the value of a single field.
87          *
88          * [--format=<format>]
89          * : Accepted values: table, json. Default: table
90          *
91          * ## EXAMPLES
92          *
93          *     wp user get 12 --field=login
94          *
95          *     wp user get bob --format=json > bob.json
96          */
97         public function get( $args, $assoc_args ) {
98                 $user = $this->fetcher->get_check( $args[0] );
99
100                 if ( method_exists( $user, 'to_array' ) ) {
101                         $user_data = $user->to_array();
102                 } else {
103                         // WP 3.4 compat
104                         $user_data = (array) $user->data;
105                 }
106                 $user_data['roles'] = implode( ', ', $user->roles );
107
108                 $formatter = $this->get_formatter( $assoc_args );
109                 $formatter->display_item( $user_data );
110         }
111
112         /**
113          * Delete one or more users.
114          *
115          * ## OPTIONS
116          *
117          * <user>...
118          * : The user login or ID of the user(s) to update.
119          *
120          * [--reassign=<user-id>]
121          * : User ID to reassign the posts to.
122          *
123          * ## EXAMPLES
124          *
125          *     wp user delete 123 --reassign=567
126          */
127         public function delete( $args, $assoc_args ) {
128                 $assoc_args = wp_parse_args( $assoc_args, array(
129                         'reassign' => null
130                 ) );
131
132                 $users = $this->fetcher->get_many( $args );
133
134                 parent::_delete( $users, $assoc_args, function ( $user, $assoc_args ) {
135                         $user_id = $user->ID;
136
137                         if ( is_multisite() ) {
138                                 $r = wpmu_delete_user( $user_id );
139                         } else {
140                                 $r = wp_delete_user( $user_id, $assoc_args['reassign'] );
141                         }
142
143                         if ( $r ) {
144                                 return array( 'success', "Deleted user $user_id." );
145                         } else {
146                                 return array( 'error', "Failed deleting user $user_id." );
147                         }
148                 } );
149         }
150
151         /**
152          * Create a user.
153          *
154          * ## OPTIONS
155          *
156          * <user-login>
157          * : The login of the user to create.
158          *
159          * <user-email>
160          * : The email address of the user to create.
161          *
162          * [--role=<role>]
163          * : The role of the user to create. Default: default role
164          *
165          * [--user_pass=<password>]
166          * : The user password. Default: randomly generated
167          *
168          * [--user_registered=<yyyy-mm-dd>]
169          * : The date the user registered. Default: current date
170          *
171          * [--display_name=<name>]
172          * : The display name.
173          *
174          * [--porcelain]
175          * : Output just the new user id.
176          *
177          * ## EXAMPLES
178          *
179          *     wp user create bob bob@example.com --role=author
180          */
181         public function create( $args, $assoc_args ) {
182                 list( $user_login, $user_email ) = $args;
183
184                 $defaults = array(
185                         'role' => get_option('default_role'),
186                         'user_pass' => false,
187                         'user_registered' => strftime( "%F %T", time() ),
188                         'display_name' => false,
189                 );
190                 extract( array_merge( $defaults, $assoc_args ), EXTR_SKIP );
191
192                 if ( !self::validate_role( $role ) ) {
193                         WP_CLI::error( "Invalid role: $role" );
194                 }
195
196                 // @codingStandardsIgnoreStart
197                 if ( !$user_pass ) {
198                         $user_pass = wp_generate_password();
199                         $generated_pass = true;
200                 }
201
202                 $user_id = wp_insert_user( array(
203                         'user_email' => $user_email,
204                         'user_login' => $user_login,
205                         'user_pass' => $user_pass,
206                         'user_registered' => $user_registered,
207                         'display_name' => $display_name,
208                         'role' => $role,
209                 ) );
210
211                 if ( is_wp_error( $user_id ) ) {
212                         WP_CLI::error( $user_id );
213                 } else {
214                         if ( false === $role ) {
215                                 delete_user_option( $user_id, 'capabilities' );
216                                 delete_user_option( $user_id, 'user_level' );
217                         }
218                 }
219
220                 if ( isset( $assoc_args['porcelain'] ) ) {
221                         WP_CLI::line( $user_id );
222                 } else {
223                         WP_CLI::success( "Created user $user_id." );
224                         if ( isset( $generated_pass ) )
225                                 WP_CLI::line( "Password: $user_pass" );
226                 }
227                 // @codingStandardsIgnoreEnd
228         }
229
230         /**
231          * Update a user.
232          *
233          * ## OPTIONS
234          *
235          * <user>...
236          * : The user login or ID of the user(s) to update.
237          *
238          * --<field>=<value>
239          * : One or more fields to update. For accepted fields, see wp_update_user().
240          *
241          * ## EXAMPLES
242          *
243          *     wp user update 123 --user_login=mary --display_name=Mary
244          *
245          *     wp user update mary --user_pass=marypass
246          */
247         public function update( $args, $assoc_args ) {
248                 $user_ids = array();
249
250                 foreach ( $this->fetcher->get_many( $args ) as $user ) {
251                         $user_ids[] = $user->ID;
252                 }
253
254                 parent::_update( $user_ids, $assoc_args, 'wp_update_user' );
255         }
256
257         /**
258          * Generate users.
259          *
260          * ## OPTIONS
261          *
262          * [--count=<number>]
263          * : How many users to generate. Default: 100
264          *
265          * [--role=<role>]
266          * : The role of the generated users. Default: default role from WP
267          */
268         public function generate( $args, $assoc_args ) {
269                 global $blog_id;
270
271                 $defaults = array(
272                         'count' => 100,
273                         'role' => get_option('default_role'),
274                 );
275                 $assoc_args = array_merge( $defaults, $assoc_args );
276
277                 if ( !self::validate_role( $assoc_args['role'] ) ) {
278                         WP_CLI::error( "Invalid role: $role" );
279                 }
280
281                 $user_count = count_users();
282                 $total = $user_count['total_users'];
283                 $limit = $assoc_args['count'] + $total;
284
285                 $notify = \WP_CLI\Utils\make_progress_bar( 'Generating users', $assoc_args['count'] );
286
287                 for ( $i = $total; $i < $limit; $i++ ) {
288                         $login = sprintf( 'user_%d_%d', $blog_id, $i );
289                         $name = "User $i";
290
291                         $user_id = wp_insert_user( array(
292                                 'user_login' => $login,
293                                 'user_pass' => $login,
294                                 'nickname' => $name,
295                                 'display_name' => $name,
296                                 'role' => $role
297                         ) );
298
299                         if ( false === $role ) {
300                                 delete_user_option( $user_id, 'capabilities' );
301                                 delete_user_option( $user_id, 'user_level' );
302                         }
303
304                         $notify->tick();
305                 }
306
307                 $notify->finish();
308         }
309
310         /**
311          * Set the user role (for a particular blog).
312          *
313          * ## OPTIONS
314          *
315          * <user>
316          * : User ID or user login.
317          *
318          * [<role>]
319          * : Make the user have the specified role. If not passed, the default role is
320          * used.
321          *
322          * ## EXAMPLES
323          *
324          *     wp user set-role bob author
325          *     wp user set-role 12 author
326          *
327          * @subcommand set-role
328          */
329         public function set_role( $args, $assoc_args ) {
330                 $user = $this->fetcher->get_check( $args[0] );
331
332                 $role = isset( $args[1] ) ? $args[1] : get_option( 'default_role' );
333
334                 // Multisite
335                 if ( function_exists( 'add_user_to_blog' ) )
336                         add_user_to_blog( get_current_blog_id(), $user->ID, $role );
337                 else
338                         $user->set_role( $role );
339
340                 WP_CLI::success( "Added {$user->user_login} ({$user->ID}) to " . site_url() . " as {$role}" );
341         }
342
343         /**
344          * Add a role for a user.
345          *
346          * ## OPTIONS
347          *
348          * <user>
349          * : User ID or user login.
350          *
351          * <role>
352          * : Add the specified role to the user.
353          *
354          * ## EXAMPLES
355          *
356          *     wp user add-role bob author
357          *     wp user add-role 12 author
358          *
359          * @subcommand add-role
360          */
361         public function add_role( $args, $assoc_args ) {
362                 $user = $this->fetcher->get_check( $args[0] );
363
364                 $role = $args[1];
365
366                 $user->add_role( $role );
367
368                 WP_CLI::success( sprintf( "Added '%s' role for %s (%d).", $role, $user->user_login, $user->ID ) );
369         }
370
371         /**
372          * Remove a user's role.
373          *
374          * ## OPTIONS
375          *
376          * <user>
377          * : User ID or user login.
378          *
379          * [<role>]
380          * : A specific role to remove.
381          *
382          * ## EXAMPLES
383          *
384          *     wp user remove-role bob
385          *     wp user remove-role 12 editor
386          *
387          * @subcommand remove-role
388          */
389         public function remove_role( $args, $assoc_args ) {
390                 $user = $this->fetcher->get_check( $args[0] );
391
392                 if ( isset( $args[1] ) ) {
393                         $role = $args[1];
394
395                         $user->remove_role( $role );
396
397                         WP_CLI::success( sprintf( "Removed '%s' role for %s (%d).", $role, $user->user_login, $user->ID ) );
398                 } else {
399                         // Multisite
400                         if ( function_exists( 'remove_user_from_blog' ) )
401                                 remove_user_from_blog( $user->ID, get_current_blog_id() );
402                         else
403                                 $user->remove_all_caps();
404
405                         WP_CLI::success( "Removed {$user->user_login} ({$user->ID}) from " . site_url() );
406                 }
407         }
408
409         /**
410          * Add a capability for a user.
411          *
412          * ## OPTIONS
413          *
414          * <user>
415          * : User ID or user login.
416          *
417          * <cap>
418          * : The capability to add.
419          *
420          * ## EXAMPLES
421          *
422          *     wp user add-cap john create_premium_item
423          *     wp user add-cap 15 edit_product
424          *
425          * @subcommand add-cap
426          */
427         public function add_cap( $args, $assoc_args ) {
428                 $user = $this->fetcher->get_check( $args[0] );
429                 if ( $user ) {
430                         $cap  = $args[1];
431                         $user->add_cap( $cap );
432
433                         WP_CLI::success( sprintf( "Added '%s' capability for %s (%d).", $cap, $user->user_login, $user->ID ) );
434                 }
435         }
436
437         /**
438          * Remove a user's capability.
439          *
440          * ## OPTIONS
441          *
442          * <user>
443          * : User ID or user login.
444          *
445          * <cap>
446          * : The capability to be removed.
447          *
448          * ## EXAMPLES
449          *
450          *     wp user remove-cap bob edit_themes
451          *     wp user remove-cap 11 publish_newsletters
452          *
453          * @subcommand remove-cap
454          */
455         public function remove_cap( $args, $assoc_args ) {
456                 $user = $this->fetcher->get_check( $args[0] );
457                 if ( $user ) {
458                         $cap = $args[1];
459                         $user->remove_cap( $cap );
460
461                         WP_CLI::success( sprintf( "Removed '%s' cap for %s (%d).", $cap, $user->user_login, $user->ID ) );
462                 }
463         }
464
465         /**
466          * List all user's capabilities.
467          *
468          * ## OPTIONS
469          *
470          * <user>
471          * : User ID or login.
472          *
473          * ## EXAMPLES
474          *
475          *     wp user list-caps admin
476          *     wp user list-caps 21
477          *
478          * @subcommand list-caps
479          */
480         public function list_caps( $args, $assoc_args ) {
481                 $user = $this->fetcher->get_check( $args[0] );
482
483                 if ( $user ) {
484                         $user->get_role_caps();
485
486                         $user_caps_list = $user->allcaps;
487                         $cap_table_titles = array( 'capability', 'status' );
488
489                         foreach ( $user_caps_list as $cap => $active ) {
490                                 if ( $active ) {
491                                         \cli\line( $cap );
492                                 }
493                         }
494                 }
495         }
496
497         /**
498          * Import users from a CSV file.
499          *
500          * ## OPTIONS
501          *
502          * <file>
503          * : The CSV file of users to import.
504          *
505          * ## EXAMPLES
506          *
507          *     wp user import-csv /path/to/users.csv
508          *
509          *     Sample users.csv file:
510          *
511          *     user_login,user_email,display_name,role
512          *     bobjones,bobjones@domain.com,Bob Jones,contributor
513          *     newuser1,newuser1@domain.com,New User,author
514          *     existinguser,existinguser@domain.com,Existing User,administrator
515          *
516          * @subcommand import-csv
517          */
518         public function import_csv( $args, $assoc_args ) {
519
520                 $blog_users = get_users();
521
522                 $filename = $args[0];
523
524                 if ( ! file_exists( $filename ) ) {
525                         WP_CLI::warning( sprintf( "Missing file: %s", $filename ) );
526                 }
527
528                 foreach ( new \WP_CLI\Iterators\CSV( $filename ) as $i => $new_user ) {
529                         $defaults = array(
530                                 'role' => get_option('default_role'),
531                                 'user_pass' => wp_generate_password(),
532                                 'user_registered' => strftime( "%F %T", time() ),
533                                 'display_name' => false,
534                         );
535                         $new_user = array_merge( $defaults, $new_user );
536
537                         if ( 'none' === $new_user['role'] ) {
538                                 $new_user['role'] = false;
539                         } elseif ( is_null( get_role( $new_user['role'] ) ) ) {
540                                 WP_CLI::warning( "{$new_user['user_login']} has an invalid role" );
541                                 continue;
542                         }
543
544                         // User already exists and we just need to add them to the site if they aren't already there
545                         $existing_user = get_user_by( 'email', $new_user['user_email'] );
546
547                         if ( !$existing_user ) {
548                                 $existing_user = get_user_by( 'login', $new_user['user_login'] );
549                         }
550
551                         if ( $existing_user ) {
552                                 $new_user['ID'] = $existing_user->ID;
553                                 $user_id = wp_update_user( $new_user );
554
555                                 if ( !in_array( $existing_user->user_login, wp_list_pluck( $blog_users, 'user_login' ) ) &&  $new_user['role'] ) {
556                                         add_user_to_blog( get_current_blog_id(), $existing_user->ID, $new_user['role'] );
557                                         WP_CLI::log( "{$existing_user->user_login} added as {$new_user['role']}." );
558                                 }
559
560                         // Create the user
561                         } else {
562                                 $user_id = wp_insert_user( $new_user );
563                         }
564
565                         if ( is_wp_error( $user_id ) ) {
566                                 WP_CLI::warning( $user_id );
567                                 continue;
568
569                         } else if ( $new_user['role'] === false ) {
570                                 delete_user_option( $user_id, 'capabilities' );
571                                 delete_user_option( $user_id, 'user_level' );
572                         }
573
574                         if ( !empty( $existing_user ) ) {
575                                 WP_CLI::success( $new_user['user_login'] . " updated" );
576                         } else {
577                                 WP_CLI::success( $new_user['user_login'] . " created" );
578                         }
579                 }
580         }
581
582         private static function validate_role( $role ) {
583                 if ( empty( $role ) || ! is_null( get_role( $role ) ) ) {
584                         return true;
585                 }
586                 return false;
587         }
588 }
589
590 WP_CLI::add_command( 'user', 'User_Command' );
591