]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/ms-functions.php
WordPress 4.5.1-scripts
[autoinstalls/wordpress.git] / wp-includes / ms-functions.php
1 <?php
2 /**
3  * Multisite WordPress API
4  *
5  * @package WordPress
6  * @subpackage Multisite
7  * @since 3.0.0
8  */
9
10 /**
11  * Gets the network's site and user counts.
12  *
13  * @since MU 1.0
14  *
15  * @return array Site and user count for the network.
16  */
17 function get_sitestats() {
18         $stats = array(
19                 'blogs' => get_blog_count(),
20                 'users' => get_user_count(),
21         );
22
23         return $stats;
24 }
25
26 /**
27  * Get one of a user's active blogs
28  *
29  * Returns the user's primary blog, if they have one and
30  * it is active. If it's inactive, function returns another
31  * active blog of the user. If none are found, the user
32  * is added as a Subscriber to the Dashboard Blog and that blog
33  * is returned.
34  *
35  * @since MU 1.0
36  *
37  * @global wpdb $wpdb WordPress database abstraction object.
38  *
39  * @param int $user_id The unique ID of the user
40  * @return WP_Site|void The blog object
41  */
42 function get_active_blog_for_user( $user_id ) {
43         global $wpdb;
44         $blogs = get_blogs_of_user( $user_id );
45         if ( empty( $blogs ) )
46                 return;
47
48         if ( !is_multisite() )
49                 return $blogs[$wpdb->blogid];
50
51         $primary_blog = get_user_meta( $user_id, 'primary_blog', true );
52         $first_blog = current($blogs);
53         if ( false !== $primary_blog ) {
54                 if ( ! isset( $blogs[ $primary_blog ] ) ) {
55                         update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id );
56                         $primary = get_blog_details( $first_blog->userblog_id );
57                 } else {
58                         $primary = get_blog_details( $primary_blog );
59                 }
60         } else {
61                 //TODO Review this call to add_user_to_blog too - to get here the user must have a role on this blog?
62                 add_user_to_blog( $first_blog->userblog_id, $user_id, 'subscriber' );
63                 update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id );
64                 $primary = $first_blog;
65         }
66
67         if ( ( ! is_object( $primary ) ) || ( $primary->archived == 1 || $primary->spam == 1 || $primary->deleted == 1 ) ) {
68                 $blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs.
69                 $ret = false;
70                 if ( is_array( $blogs ) && count( $blogs ) > 0 ) {
71                         foreach ( (array) $blogs as $blog_id => $blog ) {
72                                 if ( $blog->site_id != $wpdb->siteid )
73                                         continue;
74                                 $details = get_blog_details( $blog_id );
75                                 if ( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) {
76                                         $ret = $blog;
77                                         if ( get_user_meta( $user_id , 'primary_blog', true ) != $blog_id )
78                                                 update_user_meta( $user_id, 'primary_blog', $blog_id );
79                                         if ( !get_user_meta($user_id , 'source_domain', true) )
80                                                 update_user_meta( $user_id, 'source_domain', $blog->domain );
81                                         break;
82                                 }
83                         }
84                 } else {
85                         return;
86                 }
87                 return $ret;
88         } else {
89                 return $primary;
90         }
91 }
92
93 /**
94  * The number of active users in your installation.
95  *
96  * The count is cached and updated twice daily. This is not a live count.
97  *
98  * @since MU 2.7
99  *
100  * @return int
101  */
102 function get_user_count() {
103         return get_site_option( 'user_count' );
104 }
105
106 /**
107  * The number of active sites on your installation.
108  *
109  * The count is cached and updated twice daily. This is not a live count.
110  *
111  * @since MU 1.0
112  *
113  * @param int $network_id Deprecated, not supported.
114  * @return int
115  */
116 function get_blog_count( $network_id = 0 ) {
117         if ( func_num_args() )
118                 _deprecated_argument( __FUNCTION__, '3.1' );
119
120         return get_site_option( 'blog_count' );
121 }
122
123 /**
124  * Get a blog post from any site on the network.
125  *
126  * @since MU 1.0
127  *
128  * @param int $blog_id ID of the blog.
129  * @param int $post_id ID of the post you're looking for.
130  * @return WP_Post|null WP_Post on success or null on failure
131  */
132 function get_blog_post( $blog_id, $post_id ) {
133         switch_to_blog( $blog_id );
134         $post = get_post( $post_id );
135         restore_current_blog();
136
137         return $post;
138 }
139
140 /**
141  * Add a user to a blog.
142  *
143  * Use the 'add_user_to_blog' action to fire an event when
144  * users are added to a blog.
145  *
146  * @since MU 1.0
147  *
148  * @param int    $blog_id ID of the blog you're adding the user to.
149  * @param int    $user_id ID of the user you're adding.
150  * @param string $role    The role you want the user to have
151  * @return true|WP_Error
152  */
153 function add_user_to_blog( $blog_id, $user_id, $role ) {
154         switch_to_blog($blog_id);
155
156         $user = get_userdata( $user_id );
157
158         if ( ! $user ) {
159                 restore_current_blog();
160                 return new WP_Error( 'user_does_not_exist', __( 'The requested user does not exist.' ) );
161         }
162
163         if ( !get_user_meta($user_id, 'primary_blog', true) ) {
164                 update_user_meta($user_id, 'primary_blog', $blog_id);
165                 $details = get_blog_details($blog_id);
166                 update_user_meta($user_id, 'source_domain', $details->domain);
167         }
168
169         $user->set_role($role);
170
171         /**
172          * Fires immediately after a user is added to a site.
173          *
174          * @since MU
175          *
176          * @param int    $user_id User ID.
177          * @param string $role    User role.
178          * @param int    $blog_id Blog ID.
179          */
180         do_action( 'add_user_to_blog', $user_id, $role, $blog_id );
181         wp_cache_delete( $user_id, 'users' );
182         wp_cache_delete( $blog_id . '_user_count', 'blog-details' );
183         restore_current_blog();
184         return true;
185 }
186
187 /**
188  * Remove a user from a blog.
189  *
190  * Use the 'remove_user_from_blog' action to fire an event when
191  * users are removed from a blog.
192  *
193  * Accepts an optional $reassign parameter, if you want to
194  * reassign the user's blog posts to another user upon removal.
195  *
196  * @since MU 1.0
197  *
198  * @global wpdb $wpdb WordPress database abstraction object.
199  *
200  * @param int    $user_id  ID of the user you're removing.
201  * @param int    $blog_id  ID of the blog you're removing the user from.
202  * @param string $reassign Optional. A user to whom to reassign posts.
203  * @return true|WP_Error
204  */
205 function remove_user_from_blog($user_id, $blog_id = '', $reassign = '') {
206         global $wpdb;
207         switch_to_blog($blog_id);
208         $user_id = (int) $user_id;
209         /**
210          * Fires before a user is removed from a site.
211          *
212          * @since MU
213          *
214          * @param int $user_id User ID.
215          * @param int $blog_id Blog ID.
216          */
217         do_action( 'remove_user_from_blog', $user_id, $blog_id );
218
219         // If being removed from the primary blog, set a new primary if the user is assigned
220         // to multiple blogs.
221         $primary_blog = get_user_meta($user_id, 'primary_blog', true);
222         if ( $primary_blog == $blog_id ) {
223                 $new_id = '';
224                 $new_domain = '';
225                 $blogs = get_blogs_of_user($user_id);
226                 foreach ( (array) $blogs as $blog ) {
227                         if ( $blog->userblog_id == $blog_id )
228                                 continue;
229                         $new_id = $blog->userblog_id;
230                         $new_domain = $blog->domain;
231                         break;
232                 }
233
234                 update_user_meta($user_id, 'primary_blog', $new_id);
235                 update_user_meta($user_id, 'source_domain', $new_domain);
236         }
237
238         // wp_revoke_user($user_id);
239         $user = get_userdata( $user_id );
240         if ( ! $user ) {
241                 restore_current_blog();
242                 return new WP_Error('user_does_not_exist', __('That user does not exist.'));
243         }
244
245         $user->remove_all_caps();
246
247         $blogs = get_blogs_of_user($user_id);
248         if ( count($blogs) == 0 ) {
249                 update_user_meta($user_id, 'primary_blog', '');
250                 update_user_meta($user_id, 'source_domain', '');
251         }
252
253         if ( $reassign != '' ) {
254                 $reassign = (int) $reassign;
255                 $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d", $user_id ) );
256                 $link_ids = $wpdb->get_col( $wpdb->prepare( "SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $user_id ) );
257
258                 if ( ! empty( $post_ids ) ) {
259                         $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_author = %d WHERE post_author = %d", $reassign, $user_id ) );
260                         array_walk( $post_ids, 'clean_post_cache' );
261                 }
262
263                 if ( ! empty( $link_ids ) ) {
264                         $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->links SET link_owner = %d WHERE link_owner = %d", $reassign, $user_id ) );
265                         array_walk( $link_ids, 'clean_bookmark_cache' );
266                 }
267         }
268
269         restore_current_blog();
270
271         return true;
272 }
273
274 /**
275  * Get the permalink for a post on another blog.
276  *
277  * @since MU 1.0
278  *
279  * @param int $blog_id ID of the source blog.
280  * @param int $post_id ID of the desired post.
281  * @return string The post's permalink
282  */
283 function get_blog_permalink( $blog_id, $post_id ) {
284         switch_to_blog( $blog_id );
285         $link = get_permalink( $post_id );
286         restore_current_blog();
287
288         return $link;
289 }
290
291 /**
292  * Get a blog's numeric ID from its URL.
293  *
294  * On a subdirectory installation like example.com/blog1/,
295  * $domain will be the root 'example.com' and $path the
296  * subdirectory '/blog1/'. With subdomains like blog1.example.com,
297  * $domain is 'blog1.example.com' and $path is '/'.
298  *
299  * @since MU 2.6.5
300  *
301  * @global wpdb $wpdb WordPress database abstraction object.
302  *
303  * @param string $domain
304  * @param string $path   Optional. Not required for subdomain installations.
305  * @return int 0 if no blog found, otherwise the ID of the matching blog
306  */
307 function get_blog_id_from_url( $domain, $path = '/' ) {
308         global $wpdb;
309
310         $domain = strtolower( $domain );
311         $path = strtolower( $path );
312         $id = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' );
313
314         if ( $id == -1 ) // blog does not exist
315                 return 0;
316         elseif ( $id )
317                 return (int) $id;
318
319         $id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s and path = %s /* get_blog_id_from_url */", $domain, $path ) );
320
321         if ( ! $id ) {
322                 wp_cache_set( md5( $domain . $path ), -1, 'blog-id-cache' );
323                 return 0;
324         }
325
326         wp_cache_set( md5( $domain . $path ), $id, 'blog-id-cache' );
327
328         return $id;
329 }
330
331 // Admin functions
332
333 /**
334  * Checks an email address against a list of banned domains.
335  *
336  * This function checks against the Banned Email Domains list
337  * at wp-admin/network/settings.php. The check is only run on
338  * self-registrations; user creation at wp-admin/network/users.php
339  * bypasses this check.
340  *
341  * @since MU
342  *
343  * @param string $user_email The email provided by the user at registration.
344  * @return bool Returns true when the email address is banned.
345  */
346 function is_email_address_unsafe( $user_email ) {
347         $banned_names = get_site_option( 'banned_email_domains' );
348         if ( $banned_names && ! is_array( $banned_names ) )
349                 $banned_names = explode( "\n", $banned_names );
350
351         $is_email_address_unsafe = false;
352
353         if ( $banned_names && is_array( $banned_names ) ) {
354                 $banned_names = array_map( 'strtolower', $banned_names );
355                 $normalized_email = strtolower( $user_email );
356
357                 list( $email_local_part, $email_domain ) = explode( '@', $normalized_email );
358
359                 foreach ( $banned_names as $banned_domain ) {
360                         if ( ! $banned_domain )
361                                 continue;
362
363                         if ( $email_domain == $banned_domain ) {
364                                 $is_email_address_unsafe = true;
365                                 break;
366                         }
367
368                         $dotted_domain = ".$banned_domain";
369                         if ( $dotted_domain === substr( $normalized_email, -strlen( $dotted_domain ) ) ) {
370                                 $is_email_address_unsafe = true;
371                                 break;
372                         }
373                 }
374         }
375
376         /**
377          * Filter whether an email address is unsafe.
378          *
379          * @since 3.5.0
380          *
381          * @param bool   $is_email_address_unsafe Whether the email address is "unsafe". Default false.
382          * @param string $user_email              User email address.
383          */
384         return apply_filters( 'is_email_address_unsafe', $is_email_address_unsafe, $user_email );
385 }
386
387 /**
388  * Sanitize and validate data required for a user sign-up.
389  *
390  * Verifies the validity and uniqueness of user names and user email addresses,
391  * and checks email addresses against admin-provided domain whitelists and blacklists.
392  *
393  * The {@see 'wpmu_validate_user_signup'} hook provides an easy way to modify the sign-up
394  * process. The value $result, which is passed to the hook, contains both the user-provided
395  * info and the error messages created by the function. {@see 'wpmu_validate_user_signup'}
396  * allows you to process the data in any way you'd like, and unset the relevant errors if
397  * necessary.
398  *
399  * @since MU
400  *
401  * @global wpdb $wpdb WordPress database abstraction object.
402  *
403  * @param string $user_name  The login name provided by the user.
404  * @param string $user_email The email provided by the user.
405  * @return array Contains username, email, and error messages.
406  */
407 function wpmu_validate_user_signup($user_name, $user_email) {
408         global $wpdb;
409
410         $errors = new WP_Error();
411
412         $orig_username = $user_name;
413         $user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
414
415         if ( $user_name != $orig_username || preg_match( '/[^a-z0-9]/', $user_name ) ) {
416                 $errors->add( 'user_name', __( 'Usernames can only contain lowercase letters (a-z) and numbers.' ) );
417                 $user_name = $orig_username;
418         }
419
420         $user_email = sanitize_email( $user_email );
421
422         if ( empty( $user_name ) )
423                 $errors->add('user_name', __( 'Please enter a username.' ) );
424
425         $illegal_names = get_site_option( 'illegal_names' );
426         if ( ! is_array( $illegal_names ) ) {
427                 $illegal_names = array(  'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
428                 add_site_option( 'illegal_names', $illegal_names );
429         }
430         if ( in_array( $user_name, $illegal_names ) ) {
431                 $errors->add( 'user_name',  __( 'Sorry, that username is not allowed.' ) );
432         }
433
434         /** This filter is documented in wp-includes/user.php */
435         $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
436
437         if ( in_array( strtolower( $user_name ), array_map( 'strtolower', $illegal_logins ) ) ) {
438                 $errors->add( 'user_name',  __( 'Sorry, that username is not allowed.' ) );
439         }
440
441         if ( is_email_address_unsafe( $user_email ) )
442                 $errors->add('user_email',  __('You cannot use that email address to signup. We are having problems with them blocking some of our email. Please use another email provider.'));
443
444         if ( strlen( $user_name ) < 4 )
445                 $errors->add('user_name',  __( 'Username must be at least 4 characters.' ) );
446
447         if ( strlen( $user_name ) > 60 ) {
448                 $errors->add( 'user_name', __( 'Username may not be longer than 60 characters.' ) );
449         }
450
451         // all numeric?
452         if ( preg_match( '/^[0-9]*$/', $user_name ) )
453                 $errors->add('user_name', __('Sorry, usernames must have letters too!'));
454
455         if ( !is_email( $user_email ) )
456                 $errors->add('user_email', __( 'Please enter a valid email address.' ) );
457
458         $limited_email_domains = get_site_option( 'limited_email_domains' );
459         if ( is_array( $limited_email_domains ) && ! empty( $limited_email_domains ) ) {
460                 $emaildomain = substr( $user_email, 1 + strpos( $user_email, '@' ) );
461                 if ( ! in_array( $emaildomain, $limited_email_domains ) ) {
462                         $errors->add('user_email', __('Sorry, that email address is not allowed!'));
463                 }
464         }
465
466         // Check if the username has been used already.
467         if ( username_exists($user_name) )
468                 $errors->add( 'user_name', __( 'Sorry, that username already exists!' ) );
469
470         // Check if the email address has been used already.
471         if ( email_exists($user_email) )
472                 $errors->add( 'user_email', __( 'Sorry, that email address is already used!' ) );
473
474         // Has someone already signed up for this username?
475         $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_login = %s", $user_name) );
476         if ( $signup != null ) {
477                 $registered_at =  mysql2date('U', $signup->registered);
478                 $now = current_time( 'timestamp', true );
479                 $diff = $now - $registered_at;
480                 // If registered more than two days ago, cancel registration and let this signup go through.
481                 if ( $diff > 2 * DAY_IN_SECONDS )
482                         $wpdb->delete( $wpdb->signups, array( 'user_login' => $user_name ) );
483                 else
484                         $errors->add('user_name', __('That username is currently reserved but may be available in a couple of days.'));
485         }
486
487         $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_email = %s", $user_email) );
488         if ( $signup != null ) {
489                 $diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered);
490                 // If registered more than two days ago, cancel registration and let this signup go through.
491                 if ( $diff > 2 * DAY_IN_SECONDS )
492                         $wpdb->delete( $wpdb->signups, array( 'user_email' => $user_email ) );
493                 else
494                         $errors->add('user_email', __('That email address has already been used. Please check your inbox for an activation email. It will become available in a couple of days if you do nothing.'));
495         }
496
497         $result = array('user_name' => $user_name, 'orig_username' => $orig_username, 'user_email' => $user_email, 'errors' => $errors);
498
499         /**
500          * Filter the validated user registration details.
501          *
502          * This does not allow you to override the username or email of the user during
503          * registration. The values are solely used for validation and error handling.
504          *
505          * @since MU
506          *
507          * @param array $result {
508          *     The array of user name, email and the error messages.
509          *
510          *     @type string   $user_name     Sanitized and unique username.
511          *     @type string   $orig_username Original username.
512          *     @type string   $user_email    User email address.
513          *     @type WP_Error $errors        WP_Error object containing any errors found.
514          * }
515          */
516         return apply_filters( 'wpmu_validate_user_signup', $result );
517 }
518
519 /**
520  * Processes new site registrations.
521  *
522  * Checks the data provided by the user during blog signup. Verifies
523  * the validity and uniqueness of blog paths and domains.
524  *
525  * This function prevents the current user from registering a new site
526  * with a blogname equivalent to another user's login name. Passing the
527  * $user parameter to the function, where $user is the other user, is
528  * effectively an override of this limitation.
529  *
530  * Filter 'wpmu_validate_blog_signup' if you want to modify
531  * the way that WordPress validates new site signups.
532  *
533  * @since MU
534  *
535  * @global wpdb   $wpdb
536  * @global string $domain
537  *
538  * @param string         $blogname   The blog name provided by the user. Must be unique.
539  * @param string         $blog_title The blog title provided by the user.
540  * @param WP_User|string $user       Optional. The user object to check against the new site name.
541  * @return array Contains the new site data and error messages.
542  */
543 function wpmu_validate_blog_signup( $blogname, $blog_title, $user = '' ) {
544         global $wpdb, $domain;
545
546         $current_site = get_current_site();
547         $base = $current_site->path;
548
549         $blog_title = strip_tags( $blog_title );
550
551         $errors = new WP_Error();
552         $illegal_names = get_site_option( 'illegal_names' );
553         if ( $illegal_names == false ) {
554                 $illegal_names = array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
555                 add_site_option( 'illegal_names', $illegal_names );
556         }
557
558         /*
559          * On sub dir installs, some names are so illegal, only a filter can
560          * spring them from jail.
561          */
562         if ( ! is_subdomain_install() ) {
563                 $illegal_names = array_merge( $illegal_names, get_subdirectory_reserved_names() );
564         }
565
566         if ( empty( $blogname ) )
567                 $errors->add('blogname', __( 'Please enter a site name.' ) );
568
569         if ( preg_match( '/[^a-z0-9]+/', $blogname ) ) {
570                 $errors->add( 'blogname', __( 'Site names can only contain lowercase letters (a-z) and numbers.' ) );
571         }
572
573         if ( in_array( $blogname, $illegal_names ) )
574                 $errors->add('blogname',  __( 'That name is not allowed.' ) );
575
576         if ( strlen( $blogname ) < 4 && !is_super_admin() )
577                 $errors->add('blogname',  __( 'Site name must be at least 4 characters.' ) );
578
579         // do not allow users to create a blog that conflicts with a page on the main blog.
580         if ( !is_subdomain_install() && $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM " . $wpdb->get_blog_prefix( $current_site->blog_id ) . "posts WHERE post_type = 'page' AND post_name = %s", $blogname ) ) )
581                 $errors->add( 'blogname', __( 'Sorry, you may not use that site name.' ) );
582
583         // all numeric?
584         if ( preg_match( '/^[0-9]*$/', $blogname ) )
585                 $errors->add('blogname', __('Sorry, site names must have letters too!'));
586
587         /**
588          * Filter the new site name during registration.
589          *
590          * The name is the site's subdomain or the site's subdirectory
591          * path depending on the network settings.
592          *
593          * @since MU
594          *
595          * @param string $blogname Site name.
596          */
597         $blogname = apply_filters( 'newblogname', $blogname );
598
599         $blog_title = wp_unslash(  $blog_title );
600
601         if ( empty( $blog_title ) )
602                 $errors->add('blog_title', __( 'Please enter a site title.' ) );
603
604         // Check if the domain/path has been used already.
605         if ( is_subdomain_install() ) {
606                 $mydomain = $blogname . '.' . preg_replace( '|^www\.|', '', $domain );
607                 $path = $base;
608         } else {
609                 $mydomain = "$domain";
610                 $path = $base.$blogname.'/';
611         }
612         if ( domain_exists($mydomain, $path, $current_site->id) )
613                 $errors->add( 'blogname', __( 'Sorry, that site already exists!' ) );
614
615         if ( username_exists( $blogname ) ) {
616                 if ( ! is_object( $user ) || ( is_object($user) && ( $user->user_login != $blogname ) ) )
617                         $errors->add( 'blogname', __( 'Sorry, that site is reserved!' ) );
618         }
619
620         // Has someone already signed up for this domain?
621         $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path) ); // TODO: Check email too?
622         if ( ! empty($signup) ) {
623                 $diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered);
624                 // If registered more than two days ago, cancel registration and let this signup go through.
625                 if ( $diff > 2 * DAY_IN_SECONDS )
626                         $wpdb->delete( $wpdb->signups, array( 'domain' => $mydomain , 'path' => $path ) );
627                 else
628                         $errors->add('blogname', __('That site is currently reserved but may be available in a couple days.'));
629         }
630
631         $result = array('domain' => $mydomain, 'path' => $path, 'blogname' => $blogname, 'blog_title' => $blog_title, 'user' => $user, 'errors' => $errors);
632
633         /**
634          * Filter site details and error messages following registration.
635          *
636          * @since MU
637          *
638          * @param array $result {
639          *     Array of domain, path, blog name, blog title, user and error messages.
640          *
641          *     @type string         $domain     Domain for the site.
642          *     @type string         $path       Path for the site. Used in subdirectory installs.
643          *     @type string         $blogname   The unique site name (slug).
644          *     @type string         $blog_title Blog title.
645          *     @type string|WP_User $user       By default, an empty string. A user object if provided.
646          *     @type WP_Error       $errors     WP_Error containing any errors found.
647          * }
648          */
649         return apply_filters( 'wpmu_validate_blog_signup', $result );
650 }
651
652 /**
653  * Record site signup information for future activation.
654  *
655  * @since MU
656  *
657  * @global wpdb $wpdb WordPress database abstraction object.
658  *
659  * @param string $domain     The requested domain.
660  * @param string $path       The requested path.
661  * @param string $title      The requested site title.
662  * @param string $user       The user's requested login name.
663  * @param string $user_email The user's email address.
664  * @param array  $meta       By default, contains the requested privacy setting and lang_id.
665  */
666 function wpmu_signup_blog( $domain, $path, $title, $user, $user_email, $meta = array() )  {
667         global $wpdb;
668
669         $key = substr( md5( time() . rand() . $domain ), 0, 16 );
670         $meta = serialize($meta);
671
672         $wpdb->insert( $wpdb->signups, array(
673                 'domain' => $domain,
674                 'path' => $path,
675                 'title' => $title,
676                 'user_login' => $user,
677                 'user_email' => $user_email,
678                 'registered' => current_time('mysql', true),
679                 'activation_key' => $key,
680                 'meta' => $meta
681         ) );
682
683         /**
684          * Fires after site signup information has been written to the database.
685          *
686          * @since 4.4.0
687          *
688          * @param string $domain     The requested domain.
689          * @param string $path       The requested path.
690          * @param string $title      The requested site title.
691          * @param string $user       The user's requested login name.
692          * @param string $user_email The user's email address.
693          * @param string $key        The user's activation key
694          * @param array  $meta       By default, contains the requested privacy setting and lang_id.
695          */
696         do_action( 'after_signup_site', $domain, $path, $title, $user, $user_email, $key, $meta );
697 }
698
699 /**
700  * Record user signup information for future activation.
701  *
702  * This function is used when user registration is open but
703  * new site registration is not.
704  *
705  * @since MU
706  *
707  * @global wpdb $wpdb WordPress database abstraction object.
708  *
709  * @param string $user       The user's requested login name.
710  * @param string $user_email The user's email address.
711  * @param array  $meta       By default, this is an empty array.
712  */
713 function wpmu_signup_user( $user, $user_email, $meta = array() ) {
714         global $wpdb;
715
716         // Format data
717         $user = preg_replace( '/\s+/', '', sanitize_user( $user, true ) );
718         $user_email = sanitize_email( $user_email );
719         $key = substr( md5( time() . rand() . $user_email ), 0, 16 );
720         $meta = serialize($meta);
721
722         $wpdb->insert( $wpdb->signups, array(
723                 'domain' => '',
724                 'path' => '',
725                 'title' => '',
726                 'user_login' => $user,
727                 'user_email' => $user_email,
728                 'registered' => current_time('mysql', true),
729                 'activation_key' => $key,
730                 'meta' => $meta
731         ) );
732
733         /**
734          * Fires after a user's signup information has been written to the database.
735          *
736          * @since 4.4.0
737          *
738          * @param string $user       The user's requested login name.
739          * @param string $user_email The user's email address.
740          * @param string $key        The user's activation key
741          * @param array  $meta       Additional signup meta. By default, this is an empty array.
742          */
743         do_action( 'after_signup_user', $user, $user_email, $key, $meta );
744 }
745
746 /**
747  * Notify user of signup success.
748  *
749  * This is the notification function used when site registration
750  * is enabled.
751  *
752  * Filter 'wpmu_signup_blog_notification' to bypass this function or
753  * replace it with your own notification behavior.
754  *
755  * Filter 'wpmu_signup_blog_notification_email' and
756  * 'wpmu_signup_blog_notification_subject' to change the content
757  * and subject line of the email sent to newly registered users.
758  *
759  * @since MU
760  *
761  * @param string $domain     The new blog domain.
762  * @param string $path       The new blog path.
763  * @param string $title      The site title.
764  * @param string $user       The user's login name.
765  * @param string $user_email The user's email address.
766  * @param string $key        The activation key created in wpmu_signup_blog()
767  * @param array  $meta       By default, contains the requested privacy setting and lang_id.
768  * @return bool
769  */
770 function wpmu_signup_blog_notification( $domain, $path, $title, $user, $user_email, $key, $meta = array() ) {
771         /**
772          * Filter whether to bypass the new site email notification.
773          *
774          * @since MU
775          *
776          * @param string|bool $domain     Site domain.
777          * @param string      $path       Site path.
778          * @param string      $title      Site title.
779          * @param string      $user       User login name.
780          * @param string      $user_email User email address.
781          * @param string      $key        Activation key created in wpmu_signup_blog().
782          * @param array       $meta       By default, contains the requested privacy setting and lang_id.
783          */
784         if ( ! apply_filters( 'wpmu_signup_blog_notification', $domain, $path, $title, $user, $user_email, $key, $meta ) ) {
785                 return false;
786         }
787
788         // Send email with activation link.
789         if ( !is_subdomain_install() || get_current_site()->id != 1 )
790                 $activate_url = network_site_url("wp-activate.php?key=$key");
791         else
792                 $activate_url = "http://{$domain}{$path}wp-activate.php?key=$key"; // @todo use *_url() API
793
794         $activate_url = esc_url($activate_url);
795         $admin_email = get_site_option( 'admin_email' );
796         if ( $admin_email == '' )
797                 $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
798         $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
799         $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
800         $message = sprintf(
801                 /**
802                  * Filter the message content of the new blog notification email.
803                  *
804                  * Content should be formatted for transmission via wp_mail().
805                  *
806                  * @since MU
807                  *
808                  * @param string $content    Content of the notification email.
809                  * @param string $domain     Site domain.
810                  * @param string $path       Site path.
811                  * @param string $title      Site title.
812                  * @param string $user       User login name.
813                  * @param string $user_email User email address.
814                  * @param string $key        Activation key created in wpmu_signup_blog().
815                  * @param array  $meta       By default, contains the requested privacy setting and lang_id.
816                  */
817                 apply_filters( 'wpmu_signup_blog_notification_email',
818                         __( "To activate your blog, please click the following link:\n\n%s\n\nAfter you activate, you will receive *another email* with your login.\n\nAfter you activate, you can visit your site here:\n\n%s" ),
819                         $domain, $path, $title, $user, $user_email, $key, $meta
820                 ),
821                 $activate_url,
822                 esc_url( "http://{$domain}{$path}" ),
823                 $key
824         );
825         // TODO: Don't hard code activation link.
826         $subject = sprintf(
827                 /**
828                  * Filter the subject of the new blog notification email.
829                  *
830                  * @since MU
831                  *
832                  * @param string $subject    Subject of the notification email.
833                  * @param string $domain     Site domain.
834                  * @param string $path       Site path.
835                  * @param string $title      Site title.
836                  * @param string $user       User login name.
837                  * @param string $user_email User email address.
838                  * @param string $key        Activation key created in wpmu_signup_blog().
839                  * @param array  $meta       By default, contains the requested privacy setting and lang_id.
840                  */
841                 apply_filters( 'wpmu_signup_blog_notification_subject',
842                         __( '[%1$s] Activate %2$s' ),
843                         $domain, $path, $title, $user, $user_email, $key, $meta
844                 ),
845                 $from_name,
846                 esc_url( 'http://' . $domain . $path )
847         );
848         wp_mail( $user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
849         return true;
850 }
851
852 /**
853  * Notify user of signup success.
854  *
855  * This is the notification function used when no new site has
856  * been requested.
857  *
858  * Filter 'wpmu_signup_user_notification' to bypass this function or
859  * replace it with your own notification behavior.
860  *
861  * Filter 'wpmu_signup_user_notification_email' and
862  * 'wpmu_signup_user_notification_subject' to change the content
863  * and subject line of the email sent to newly registered users.
864  *
865  * @since MU
866  *
867  * @param string $user       The user's login name.
868  * @param string $user_email The user's email address.
869  * @param string $key        The activation key created in wpmu_signup_user()
870  * @param array  $meta       By default, an empty array.
871  * @return bool
872  */
873 function wpmu_signup_user_notification( $user, $user_email, $key, $meta = array() ) {
874         /**
875          * Filter whether to bypass the email notification for new user sign-up.
876          *
877          * @since MU
878          *
879          * @param string $user       User login name.
880          * @param string $user_email User email address.
881          * @param string $key        Activation key created in wpmu_signup_user().
882          * @param array  $meta       Signup meta data.
883          */
884         if ( ! apply_filters( 'wpmu_signup_user_notification', $user, $user_email, $key, $meta ) )
885                 return false;
886
887         // Send email with activation link.
888         $admin_email = get_site_option( 'admin_email' );
889         if ( $admin_email == '' )
890                 $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
891         $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
892         $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
893         $message = sprintf(
894                 /**
895                  * Filter the content of the notification email for new user sign-up.
896                  *
897                  * Content should be formatted for transmission via wp_mail().
898                  *
899                  * @since MU
900                  *
901                  * @param string $content    Content of the notification email.
902                  * @param string $user       User login name.
903                  * @param string $user_email User email address.
904                  * @param string $key        Activation key created in wpmu_signup_user().
905                  * @param array  $meta       Signup meta data.
906                  */
907                 apply_filters( 'wpmu_signup_user_notification_email',
908                         __( "To activate your user, please click the following link:\n\n%s\n\nAfter you activate, you will receive *another email* with your login." ),
909                         $user, $user_email, $key, $meta
910                 ),
911                 site_url( "wp-activate.php?key=$key" )
912         );
913         // TODO: Don't hard code activation link.
914         $subject = sprintf(
915                 /**
916                  * Filter the subject of the notification email of new user signup.
917                  *
918                  * @since MU
919                  *
920                  * @param string $subject    Subject of the notification email.
921                  * @param string $user       User login name.
922                  * @param string $user_email User email address.
923                  * @param string $key        Activation key created in wpmu_signup_user().
924                  * @param array  $meta       Signup meta data.
925                  */
926                 apply_filters( 'wpmu_signup_user_notification_subject',
927                         __( '[%1$s] Activate %2$s' ),
928                         $user, $user_email, $key, $meta
929                 ),
930                 $from_name,
931                 $user
932         );
933         wp_mail( $user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
934         return true;
935 }
936
937 /**
938  * Activate a signup.
939  *
940  * Hook to 'wpmu_activate_user' or 'wpmu_activate_blog' for events
941  * that should happen only when users or sites are self-created (since
942  * those actions are not called when users and sites are created
943  * by a Super Admin).
944  *
945  * @since MU
946  *
947  * @global wpdb $wpdb WordPress database abstraction object.
948  *
949  * @param string $key The activation key provided to the user.
950  * @return array|WP_Error An array containing information about the activated user and/or blog
951  */
952 function wpmu_activate_signup($key) {
953         global $wpdb;
954
955         $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key) );
956
957         if ( empty( $signup ) )
958                 return new WP_Error( 'invalid_key', __( 'Invalid activation key.' ) );
959
960         if ( $signup->active ) {
961                 if ( empty( $signup->domain ) )
962                         return new WP_Error( 'already_active', __( 'The user is already active.' ), $signup );
963                 else
964                         return new WP_Error( 'already_active', __( 'The site is already active.' ), $signup );
965         }
966
967         $meta = maybe_unserialize($signup->meta);
968         $password = wp_generate_password( 12, false );
969
970         $user_id = username_exists($signup->user_login);
971
972         if ( ! $user_id )
973                 $user_id = wpmu_create_user($signup->user_login, $password, $signup->user_email);
974         else
975                 $user_already_exists = true;
976
977         if ( ! $user_id )
978                 return new WP_Error('create_user', __('Could not create user'), $signup);
979
980         $now = current_time('mysql', true);
981
982         if ( empty($signup->domain) ) {
983                 $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) );
984
985                 if ( isset( $user_already_exists ) )
986                         return new WP_Error( 'user_already_exists', __( 'That username is already activated.' ), $signup);
987
988                 /**
989                  * Fires immediately after a new user is activated.
990                  *
991                  * @since MU
992                  *
993                  * @param int   $user_id  User ID.
994                  * @param int   $password User password.
995                  * @param array $meta     Signup meta data.
996                  */
997                 do_action( 'wpmu_activate_user', $user_id, $password, $meta );
998                 return array( 'user_id' => $user_id, 'password' => $password, 'meta' => $meta );
999         }
1000
1001         $blog_id = wpmu_create_blog( $signup->domain, $signup->path, $signup->title, $user_id, $meta, $wpdb->siteid );
1002
1003         // TODO: What to do if we create a user but cannot create a blog?
1004         if ( is_wp_error($blog_id) ) {
1005                 // If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and
1006                 // setting the activation flag. Let's just set the active flag and instruct the user to reset their password.
1007                 if ( 'blog_taken' == $blog_id->get_error_code() ) {
1008                         $blog_id->add_data( $signup );
1009                         $wpdb->update( $wpdb->signups, array( 'active' => 1, 'activated' => $now ), array( 'activation_key' => $key ) );
1010                 }
1011                 return $blog_id;
1012         }
1013
1014         $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) );
1015         /**
1016          * Fires immediately after a site is activated.
1017          *
1018          * @since MU
1019          *
1020          * @param int    $blog_id       Blog ID.
1021          * @param int    $user_id       User ID.
1022          * @param int    $password      User password.
1023          * @param string $signup_title  Site title.
1024          * @param array  $meta          Signup meta data.
1025          */
1026         do_action( 'wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta );
1027
1028         return array('blog_id' => $blog_id, 'user_id' => $user_id, 'password' => $password, 'title' => $signup->title, 'meta' => $meta);
1029 }
1030
1031 /**
1032  * Create a user.
1033  *
1034  * This function runs when a user self-registers as well as when
1035  * a Super Admin creates a new user. Hook to 'wpmu_new_user' for events
1036  * that should affect all new users, but only on Multisite (otherwise
1037  * use 'user_register').
1038  *
1039  * @since MU
1040  *
1041  * @param string $user_name The new user's login name.
1042  * @param string $password  The new user's password.
1043  * @param string $email     The new user's email address.
1044  * @return int|false Returns false on failure, or int $user_id on success
1045  */
1046 function wpmu_create_user( $user_name, $password, $email ) {
1047         $user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
1048
1049         $user_id = wp_create_user( $user_name, $password, $email );
1050         if ( is_wp_error( $user_id ) )
1051                 return false;
1052
1053         // Newly created users have no roles or caps until they are added to a blog.
1054         delete_user_option( $user_id, 'capabilities' );
1055         delete_user_option( $user_id, 'user_level' );
1056
1057         /**
1058          * Fires immediately after a new user is created.
1059          *
1060          * @since MU
1061          *
1062          * @param int $user_id User ID.
1063          */
1064         do_action( 'wpmu_new_user', $user_id );
1065
1066         return $user_id;
1067 }
1068
1069 /**
1070  * Create a site.
1071  *
1072  * This function runs when a user self-registers a new site as well
1073  * as when a Super Admin creates a new site. Hook to 'wpmu_new_blog'
1074  * for events that should affect all new sites.
1075  *
1076  * On subdirectory installs, $domain is the same as the main site's
1077  * domain, and the path is the subdirectory name (eg 'example.com'
1078  * and '/blog1/'). On subdomain installs, $domain is the new subdomain +
1079  * root domain (eg 'blog1.example.com'), and $path is '/'.
1080  *
1081  * @since MU
1082  *
1083  * @param string $domain  The new site's domain.
1084  * @param string $path    The new site's path.
1085  * @param string $title   The new site's title.
1086  * @param int    $user_id The user ID of the new site's admin.
1087  * @param array  $meta    Optional. Used to set initial site options.
1088  * @param int    $site_id Optional. Only relevant on multi-network installs.
1089  * @return int|WP_Error Returns WP_Error object on failure, int $blog_id on success
1090  */
1091 function wpmu_create_blog( $domain, $path, $title, $user_id, $meta = array(), $site_id = 1 ) {
1092         $defaults = array( 'public' => 0 );
1093         $meta = wp_parse_args( $meta, $defaults );
1094
1095         $domain = preg_replace( '/\s+/', '', sanitize_user( $domain, true ) );
1096
1097         if ( is_subdomain_install() )
1098                 $domain = str_replace( '@', '', $domain );
1099
1100         $title = strip_tags( $title );
1101         $user_id = (int) $user_id;
1102
1103         if ( empty($path) )
1104                 $path = '/';
1105
1106         // Check if the domain has been used already. We should return an error message.
1107         if ( domain_exists($domain, $path, $site_id) )
1108                 return new WP_Error( 'blog_taken', __( 'Sorry, that site already exists!' ) );
1109
1110         if ( ! wp_installing() ) {
1111                 wp_installing( true );
1112         }
1113
1114         if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
1115                 return new WP_Error('insert_blog', __('Could not create site.'));
1116
1117         switch_to_blog($blog_id);
1118         install_blog($blog_id, $title);
1119         wp_install_defaults($user_id);
1120
1121         add_user_to_blog($blog_id, $user_id, 'administrator');
1122
1123         foreach ( $meta as $key => $value ) {
1124                 if ( in_array( $key, array( 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id' ) ) )
1125                         update_blog_status( $blog_id, $key, $value );
1126                 else
1127                         update_option( $key, $value );
1128         }
1129
1130         add_option( 'WPLANG', get_site_option( 'WPLANG' ) );
1131         update_option( 'blog_public', (int) $meta['public'] );
1132
1133         if ( ! is_super_admin( $user_id ) && ! get_user_meta( $user_id, 'primary_blog', true ) )
1134                 update_user_meta( $user_id, 'primary_blog', $blog_id );
1135
1136         restore_current_blog();
1137         /**
1138          * Fires immediately after a new site is created.
1139          *
1140          * @since MU
1141          *
1142          * @param int    $blog_id Blog ID.
1143          * @param int    $user_id User ID.
1144          * @param string $domain  Site domain.
1145          * @param string $path    Site path.
1146          * @param int    $site_id Site ID. Only relevant on multi-network installs.
1147          * @param array  $meta    Meta data. Used to set initial site options.
1148          */
1149         do_action( 'wpmu_new_blog', $blog_id, $user_id, $domain, $path, $site_id, $meta );
1150
1151         return $blog_id;
1152 }
1153
1154 /**
1155  * Notifies the network admin that a new site has been activated.
1156  *
1157  * Filter 'newblog_notify_siteadmin' to change the content of
1158  * the notification email.
1159  *
1160  * @since MU
1161  *
1162  * @param int    $blog_id    The new site's ID.
1163  * @param string $deprecated Not used.
1164  * @return bool
1165  */
1166 function newblog_notify_siteadmin( $blog_id, $deprecated = '' ) {
1167         if ( get_site_option( 'registrationnotification' ) != 'yes' )
1168                 return false;
1169
1170         $email = get_site_option( 'admin_email' );
1171         if ( is_email($email) == false )
1172                 return false;
1173
1174         $options_site_url = esc_url(network_admin_url('settings.php'));
1175
1176         switch_to_blog( $blog_id );
1177         $blogname = get_option( 'blogname' );
1178         $siteurl = site_url();
1179         restore_current_blog();
1180
1181         $msg = sprintf( __( 'New Site: %1$s
1182 URL: %2$s
1183 Remote IP: %3$s
1184
1185 Disable these notifications: %4$s' ), $blogname, $siteurl, wp_unslash( $_SERVER['REMOTE_ADDR'] ), $options_site_url);
1186         /**
1187          * Filter the message body of the new site activation email sent
1188          * to the network administrator.
1189          *
1190          * @since MU
1191          *
1192          * @param string $msg Email body.
1193          */
1194         $msg = apply_filters( 'newblog_notify_siteadmin', $msg );
1195
1196         wp_mail( $email, sprintf( __( 'New Site Registration: %s' ), $siteurl ), $msg );
1197         return true;
1198 }
1199
1200 /**
1201  * Notifies the network admin that a new user has been activated.
1202  *
1203  * Filter 'newuser_notify_siteadmin' to change the content of
1204  * the notification email.
1205  *
1206  * @since MU
1207  *
1208  * @param int $user_id The new user's ID.
1209  * @return bool
1210  */
1211 function newuser_notify_siteadmin( $user_id ) {
1212         if ( get_site_option( 'registrationnotification' ) != 'yes' )
1213                 return false;
1214
1215         $email = get_site_option( 'admin_email' );
1216
1217         if ( is_email($email) == false )
1218                 return false;
1219
1220         $user = get_userdata( $user_id );
1221
1222         $options_site_url = esc_url(network_admin_url('settings.php'));
1223         $msg = sprintf(__('New User: %1$s
1224 Remote IP: %2$s
1225
1226 Disable these notifications: %3$s'), $user->user_login, wp_unslash( $_SERVER['REMOTE_ADDR'] ), $options_site_url);
1227
1228         /**
1229          * Filter the message body of the new user activation email sent
1230          * to the network administrator.
1231          *
1232          * @since MU
1233          *
1234          * @param string  $msg  Email body.
1235          * @param WP_User $user WP_User instance of the new user.
1236          */
1237         $msg = apply_filters( 'newuser_notify_siteadmin', $msg, $user );
1238         wp_mail( $email, sprintf(__('New User Registration: %s'), $user->user_login), $msg );
1239         return true;
1240 }
1241
1242 /**
1243  * Check whether a blogname is already taken.
1244  *
1245  * Used during the new site registration process to ensure
1246  * that each blogname is unique.
1247  *
1248  * @since MU
1249  *
1250  * @global wpdb $wpdb WordPress database abstraction object.
1251  *
1252  * @param string $domain  The domain to be checked.
1253  * @param string $path    The path to be checked.
1254  * @param int    $site_id Optional. Relevant only on multi-network installs.
1255  * @return int
1256  */
1257 function domain_exists($domain, $path, $site_id = 1) {
1258         global $wpdb;
1259         $path = trailingslashit( $path );
1260         $result = $wpdb->get_var( $wpdb->prepare("SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s AND site_id = %d", $domain, $path, $site_id) );
1261
1262         /**
1263          * Filter whether a blogname is taken.
1264          *
1265          * @since 3.5.0
1266          *
1267          * @param int|null $result  The blog_id if the blogname exists, null otherwise.
1268          * @param string   $domain  Domain to be checked.
1269          * @param string   $path    Path to be checked.
1270          * @param int      $site_id Site ID. Relevant only on multi-network installs.
1271          */
1272         return apply_filters( 'domain_exists', $result, $domain, $path, $site_id );
1273 }
1274
1275 /**
1276  * Store basic site info in the blogs table.
1277  *
1278  * This function creates a row in the wp_blogs table and returns
1279  * the new blog's ID. It is the first step in creating a new blog.
1280  *
1281  * @since MU
1282  *
1283  * @global wpdb $wpdb WordPress database abstraction object.
1284  *
1285  * @param string $domain  The domain of the new site.
1286  * @param string $path    The path of the new site.
1287  * @param int    $site_id Unless you're running a multi-network install, be sure to set this value to 1.
1288  * @return int|false The ID of the new row
1289  */
1290 function insert_blog($domain, $path, $site_id) {
1291         global $wpdb;
1292
1293         $path = trailingslashit($path);
1294         $site_id = (int) $site_id;
1295
1296         $result = $wpdb->insert( $wpdb->blogs, array('site_id' => $site_id, 'domain' => $domain, 'path' => $path, 'registered' => current_time('mysql')) );
1297         if ( ! $result )
1298                 return false;
1299
1300         $blog_id = $wpdb->insert_id;
1301         refresh_blog_details( $blog_id );
1302
1303         wp_maybe_update_network_site_counts();
1304
1305         return $blog_id;
1306 }
1307
1308 /**
1309  * Install an empty blog.
1310  *
1311  * Creates the new blog tables and options. If calling this function
1312  * directly, be sure to use switch_to_blog() first, so that $wpdb
1313  * points to the new blog.
1314  *
1315  * @since MU
1316  *
1317  * @global wpdb     $wpdb
1318  * @global WP_Roles $wp_roles
1319  *
1320  * @param int    $blog_id    The value returned by insert_blog().
1321  * @param string $blog_title The title of the new site.
1322  */
1323 function install_blog( $blog_id, $blog_title = '' ) {
1324         global $wpdb, $wp_roles, $current_site;
1325
1326         // Cast for security
1327         $blog_id = (int) $blog_id;
1328
1329         require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
1330
1331         $suppress = $wpdb->suppress_errors();
1332         if ( $wpdb->get_results( "DESCRIBE {$wpdb->posts}" ) )
1333                 die( '<h1>' . __( 'Already Installed' ) . '</h1><p>' . __( 'You appear to have already installed WordPress. To reinstall please clear your old database tables first.' ) . '</p></body></html>' );
1334         $wpdb->suppress_errors( $suppress );
1335
1336         $url = get_blogaddress_by_id( $blog_id );
1337
1338         // Set everything up
1339         make_db_current_silent( 'blog' );
1340         populate_options();
1341         populate_roles();
1342
1343         // populate_roles() clears previous role definitions so we start over.
1344         $wp_roles = new WP_Roles();
1345
1346         $siteurl = $home = untrailingslashit( $url );
1347
1348         if ( ! is_subdomain_install() ) {
1349
1350                 if ( 'https' === parse_url( get_site_option( 'siteurl' ), PHP_URL_SCHEME ) ) {
1351                         $siteurl = set_url_scheme( $siteurl, 'https' );
1352                 }
1353                 if ( 'https' === parse_url( get_home_url( $current_site->blog_id ), PHP_URL_SCHEME ) ) {
1354                         $home = set_url_scheme( $home, 'https' );
1355                 }
1356
1357         }
1358
1359         update_option( 'siteurl', $siteurl );
1360         update_option( 'home', $home );
1361
1362         if ( get_site_option( 'ms_files_rewriting' ) )
1363                 update_option( 'upload_path', UPLOADBLOGSDIR . "/$blog_id/files" );
1364         else
1365                 update_option( 'upload_path', get_blog_option( get_current_site()->blog_id, 'upload_path' ) );
1366
1367         update_option( 'blogname', wp_unslash( $blog_title ) );
1368         update_option( 'admin_email', '' );
1369
1370         // remove all perms
1371         $table_prefix = $wpdb->get_blog_prefix();
1372         delete_metadata( 'user', 0, $table_prefix . 'user_level',   null, true ); // delete all
1373         delete_metadata( 'user', 0, $table_prefix . 'capabilities', null, true ); // delete all
1374 }
1375
1376 /**
1377  * Set blog defaults.
1378  *
1379  * This function creates a row in the wp_blogs table.
1380  *
1381  * @since MU
1382  * @deprecated MU
1383  * @deprecated Use wp_install_defaults()
1384  *
1385  * @global wpdb $wpdb WordPress database abstraction object.
1386  *
1387  * @param int $blog_id Ignored in this function.
1388  * @param int $user_id
1389  */
1390 function install_blog_defaults($blog_id, $user_id) {
1391         global $wpdb;
1392
1393         require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
1394
1395         $suppress = $wpdb->suppress_errors();
1396
1397         wp_install_defaults($user_id);
1398
1399         $wpdb->suppress_errors( $suppress );
1400 }
1401
1402 /**
1403  * Notify a user that their blog activation has been successful.
1404  *
1405  * Filter 'wpmu_welcome_notification' to disable or bypass.
1406  *
1407  * Filter 'update_welcome_email' and 'update_welcome_subject' to
1408  * modify the content and subject line of the notification email.
1409  *
1410  * @since MU
1411  *
1412  * @param int    $blog_id
1413  * @param int    $user_id
1414  * @param string $password
1415  * @param string $title    The new blog's title
1416  * @param array  $meta     Optional. Not used in the default function, but is passed along to hooks for customization.
1417  * @return bool
1418  */
1419 function wpmu_welcome_notification( $blog_id, $user_id, $password, $title, $meta = array() ) {
1420         $current_site = get_current_site();
1421
1422         /**
1423          * Filter whether to bypass the welcome email after site activation.
1424          *
1425          * Returning false disables the welcome email.
1426          *
1427          * @since MU
1428          *
1429          * @param int|bool $blog_id  Blog ID.
1430          * @param int      $user_id  User ID.
1431          * @param string   $password User password.
1432          * @param string   $title    Site title.
1433          * @param array    $meta     Signup meta data.
1434          */
1435         if ( ! apply_filters( 'wpmu_welcome_notification', $blog_id, $user_id, $password, $title, $meta ) )
1436                 return false;
1437
1438         $welcome_email = get_site_option( 'welcome_email' );
1439         if ( $welcome_email == false ) {
1440                 /* translators: Do not translate USERNAME, SITE_NAME, BLOG_URL, PASSWORD: those are placeholders. */
1441                 $welcome_email = __( 'Howdy USERNAME,
1442
1443 Your new SITE_NAME site has been successfully set up at:
1444 BLOG_URL
1445
1446 You can log in to the administrator account with the following information:
1447
1448 Username: USERNAME
1449 Password: PASSWORD
1450 Log in here: BLOG_URLwp-login.php
1451
1452 We hope you enjoy your new site. Thanks!
1453
1454 --The Team @ SITE_NAME' );
1455         }
1456
1457         $url = get_blogaddress_by_id($blog_id);
1458         $user = get_userdata( $user_id );
1459
1460         $welcome_email = str_replace( 'SITE_NAME', $current_site->site_name, $welcome_email );
1461         $welcome_email = str_replace( 'BLOG_TITLE', $title, $welcome_email );
1462         $welcome_email = str_replace( 'BLOG_URL', $url, $welcome_email );
1463         $welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email );
1464         $welcome_email = str_replace( 'PASSWORD', $password, $welcome_email );
1465
1466         /**
1467          * Filter the content of the welcome email after site activation.
1468          *
1469          * Content should be formatted for transmission via wp_mail().
1470          *
1471          * @since MU
1472          *
1473          * @param string $welcome_email Message body of the email.
1474          * @param int    $blog_id       Blog ID.
1475          * @param int    $user_id       User ID.
1476          * @param string $password      User password.
1477          * @param string $title         Site title.
1478          * @param array  $meta          Signup meta data.
1479          */
1480         $welcome_email = apply_filters( 'update_welcome_email', $welcome_email, $blog_id, $user_id, $password, $title, $meta );
1481         $admin_email = get_site_option( 'admin_email' );
1482
1483         if ( $admin_email == '' )
1484                 $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1485
1486         $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
1487         $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1488         $message = $welcome_email;
1489
1490         if ( empty( $current_site->site_name ) )
1491                 $current_site->site_name = 'WordPress';
1492
1493         /**
1494          * Filter the subject of the welcome email after site activation.
1495          *
1496          * @since MU
1497          *
1498          * @param string $subject Subject of the email.
1499          */
1500         $subject = apply_filters( 'update_welcome_subject', sprintf( __( 'New %1$s Site: %2$s' ), $current_site->site_name, wp_unslash( $title ) ) );
1501         wp_mail( $user->user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
1502         return true;
1503 }
1504
1505 /**
1506  * Notify a user that their account activation has been successful.
1507  *
1508  * Filter 'wpmu_welcome_user_notification' to disable or bypass.
1509  *
1510  * Filter 'update_welcome_user_email' and 'update_welcome_user_subject' to
1511  * modify the content and subject line of the notification email.
1512  *
1513  * @since MU
1514  *
1515  * @param int    $user_id
1516  * @param string $password
1517  * @param array  $meta     Optional. Not used in the default function, but is passed along to hooks for customization.
1518  * @return bool
1519  */
1520 function wpmu_welcome_user_notification( $user_id, $password, $meta = array() ) {
1521         $current_site = get_current_site();
1522
1523         /**
1524          * Filter whether to bypass the welcome email after user activation.
1525          *
1526          * Returning false disables the welcome email.
1527          *
1528          * @since MU
1529          *
1530          * @param int    $user_id  User ID.
1531          * @param string $password User password.
1532          * @param array  $meta     Signup meta data.
1533          */
1534         if ( ! apply_filters( 'wpmu_welcome_user_notification', $user_id, $password, $meta ) )
1535                 return false;
1536
1537         $welcome_email = get_site_option( 'welcome_user_email' );
1538
1539         $user = get_userdata( $user_id );
1540
1541         /**
1542          * Filters the content of the welcome email after user activation.
1543          *
1544          * Content should be formatted for transmission via wp_mail().
1545          *
1546          * @since MU
1547          *
1548          * @param string $welcome_email The message body of the account activation success email.
1549          * @param int    $user_id       User ID.
1550          * @param string $password      User password.
1551          * @param array  $meta          Signup meta data.
1552          */
1553         $welcome_email = apply_filters( 'update_welcome_user_email', $welcome_email, $user_id, $password, $meta );
1554         $welcome_email = str_replace( 'SITE_NAME', $current_site->site_name, $welcome_email );
1555         $welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email );
1556         $welcome_email = str_replace( 'PASSWORD', $password, $welcome_email );
1557         $welcome_email = str_replace( 'LOGINLINK', wp_login_url(), $welcome_email );
1558
1559         $admin_email = get_site_option( 'admin_email' );
1560
1561         if ( $admin_email == '' )
1562                 $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1563
1564         $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
1565         $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1566         $message = $welcome_email;
1567
1568         if ( empty( $current_site->site_name ) )
1569                 $current_site->site_name = 'WordPress';
1570
1571         /**
1572          * Filter the subject of the welcome email after user activation.
1573          *
1574          * @since MU
1575          *
1576          * @param string $subject Subject of the email.
1577          */
1578         $subject = apply_filters( 'update_welcome_user_subject', sprintf( __( 'New %1$s User: %2$s' ), $current_site->site_name, $user->user_login) );
1579         wp_mail( $user->user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
1580         return true;
1581 }
1582
1583 /**
1584  * Get the current network.
1585  *
1586  * Returns an object containing the 'id', 'domain', 'path', and 'site_name'
1587  * properties of the network being viewed.
1588  *
1589  * @see wpmu_current_site()
1590  *
1591  * @since MU
1592  *
1593  * @global WP_Network $current_site
1594  *
1595  * @return WP_Network
1596  */
1597 function get_current_site() {
1598         global $current_site;
1599         return $current_site;
1600 }
1601
1602 /**
1603  * Get a user's most recent post.
1604  *
1605  * Walks through each of a user's blogs to find the post with
1606  * the most recent post_date_gmt.
1607  *
1608  * @since MU
1609  *
1610  * @global wpdb $wpdb WordPress database abstraction object.
1611  *
1612  * @param int $user_id
1613  * @return array Contains the blog_id, post_id, post_date_gmt, and post_gmt_ts
1614  */
1615 function get_most_recent_post_of_user( $user_id ) {
1616         global $wpdb;
1617
1618         $user_blogs = get_blogs_of_user( (int) $user_id );
1619         $most_recent_post = array();
1620
1621         // Walk through each blog and get the most recent post
1622         // published by $user_id
1623         foreach ( (array) $user_blogs as $blog ) {
1624                 $prefix = $wpdb->get_blog_prefix( $blog->userblog_id );
1625                 $recent_post = $wpdb->get_row( $wpdb->prepare("SELECT ID, post_date_gmt FROM {$prefix}posts WHERE post_author = %d AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1", $user_id ), ARRAY_A);
1626
1627                 // Make sure we found a post
1628                 if ( isset($recent_post['ID']) ) {
1629                         $post_gmt_ts = strtotime($recent_post['post_date_gmt']);
1630
1631                         // If this is the first post checked or if this post is
1632                         // newer than the current recent post, make it the new
1633                         // most recent post.
1634                         if ( !isset($most_recent_post['post_gmt_ts']) || ( $post_gmt_ts > $most_recent_post['post_gmt_ts'] ) ) {
1635                                 $most_recent_post = array(
1636                                         'blog_id'               => $blog->userblog_id,
1637                                         'post_id'               => $recent_post['ID'],
1638                                         'post_date_gmt' => $recent_post['post_date_gmt'],
1639                                         'post_gmt_ts'   => $post_gmt_ts
1640                                 );
1641                         }
1642                 }
1643         }
1644
1645         return $most_recent_post;
1646 }
1647
1648 // Misc functions
1649
1650 /**
1651  * Get the size of a directory.
1652  *
1653  * A helper function that is used primarily to check whether
1654  * a blog has exceeded its allowed upload space.
1655  *
1656  * @since MU
1657  *
1658  * @param string $directory Full path of a directory.
1659  * @return int Size of the directory in MB.
1660  */
1661 function get_dirsize( $directory ) {
1662         $dirsize = get_transient( 'dirsize_cache' );
1663         if ( is_array( $dirsize ) && isset( $dirsize[ $directory ][ 'size' ] ) )
1664                 return $dirsize[ $directory ][ 'size' ];
1665
1666         if ( ! is_array( $dirsize ) )
1667                 $dirsize = array();
1668
1669         // Exclude individual site directories from the total when checking the main site,
1670         // as they are subdirectories and should not be counted.
1671         if ( is_main_site() ) {
1672                 $dirsize[ $directory ][ 'size' ] = recurse_dirsize( $directory, $directory . '/sites' );
1673         } else {
1674                 $dirsize[ $directory ][ 'size' ] = recurse_dirsize( $directory );
1675         }
1676
1677         set_transient( 'dirsize_cache', $dirsize, HOUR_IN_SECONDS );
1678         return $dirsize[ $directory ][ 'size' ];
1679 }
1680
1681 /**
1682  * Get the size of a directory recursively.
1683  *
1684  * Used by get_dirsize() to get a directory's size when it contains
1685  * other directories.
1686  *
1687  * @since MU
1688  * @since 4.3.0 $exclude parameter added.
1689  *
1690  * @param string $directory Full path of a directory.
1691  * @param string $exclude   Optional. Full path of a subdirectory to exclude from the total.
1692  * @return int|false Size in MB if a valid directory. False if not.
1693  */
1694 function recurse_dirsize( $directory, $exclude = null ) {
1695         $size = 0;
1696
1697         $directory = untrailingslashit( $directory );
1698
1699         if ( ! file_exists( $directory ) || ! is_dir( $directory ) || ! is_readable( $directory ) || $directory === $exclude ) {
1700                 return false;
1701         }
1702
1703         if ($handle = opendir($directory)) {
1704                 while(($file = readdir($handle)) !== false) {
1705                         $path = $directory.'/'.$file;
1706                         if ($file != '.' && $file != '..') {
1707                                 if (is_file($path)) {
1708                                         $size += filesize($path);
1709                                 } elseif (is_dir($path)) {
1710                                         $handlesize = recurse_dirsize( $path, $exclude );
1711                                         if ($handlesize > 0)
1712                                                 $size += $handlesize;
1713                                 }
1714                         }
1715                 }
1716                 closedir($handle);
1717         }
1718         return $size;
1719 }
1720
1721 /**
1722  * Check an array of MIME types against a whitelist.
1723  *
1724  * WordPress ships with a set of allowed upload filetypes,
1725  * which is defined in wp-includes/functions.php in
1726  * get_allowed_mime_types(). This function is used to filter
1727  * that list against the filetype whitelist provided by Multisite
1728  * Super Admins at wp-admin/network/settings.php.
1729  *
1730  * @since MU
1731  *
1732  * @param array $mimes
1733  * @return array
1734  */
1735 function check_upload_mimes( $mimes ) {
1736         $site_exts = explode( ' ', get_site_option( 'upload_filetypes', 'jpg jpeg png gif' ) );
1737         $site_mimes = array();
1738         foreach ( $site_exts as $ext ) {
1739                 foreach ( $mimes as $ext_pattern => $mime ) {
1740                         if ( $ext != '' && strpos( $ext_pattern, $ext ) !== false )
1741                                 $site_mimes[$ext_pattern] = $mime;
1742                 }
1743         }
1744         return $site_mimes;
1745 }
1746
1747 /**
1748  * Update a blog's post count.
1749  *
1750  * WordPress MS stores a blog's post count as an option so as
1751  * to avoid extraneous COUNTs when a blog's details are fetched
1752  * with get_blog_details(). This function is called when posts
1753  * are published or unpublished to make sure the count stays current.
1754  *
1755  * @since MU
1756  *
1757  * @global wpdb $wpdb WordPress database abstraction object.
1758  *
1759  * @param string $deprecated Not used.
1760  */
1761 function update_posts_count( $deprecated = '' ) {
1762         global $wpdb;
1763         update_option( 'post_count', (int) $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_status = 'publish' and post_type = 'post'" ) );
1764 }
1765
1766 /**
1767  * Logs user registrations.
1768  *
1769  * @since MU
1770  *
1771  * @global wpdb $wpdb WordPress database abstraction object.
1772  *
1773  * @param int $blog_id
1774  * @param int $user_id
1775  */
1776 function wpmu_log_new_registrations( $blog_id, $user_id ) {
1777         global $wpdb;
1778         $user = get_userdata( (int) $user_id );
1779         if ( $user )
1780                 $wpdb->insert( $wpdb->registration_log, array('email' => $user->user_email, 'IP' => preg_replace( '/[^0-9., ]/', '', wp_unslash( $_SERVER['REMOTE_ADDR'] ) ), 'blog_id' => $blog_id, 'date_registered' => current_time('mysql')) );
1781 }
1782
1783 /**
1784  * Maintains a canonical list of terms by syncing terms created for each blog with the global terms table.
1785  *
1786  * @since 3.0.0
1787  *
1788  * @see term_id_filter
1789  *
1790  * @global wpdb $wpdb WordPress database abstraction object.
1791  * @staticvar int $global_terms_recurse
1792  *
1793  * @param int    $term_id    An ID for a term on the current blog.
1794  * @param string $deprecated Not used.
1795  * @return int An ID from the global terms table mapped from $term_id.
1796  */
1797 function global_terms( $term_id, $deprecated = '' ) {
1798         global $wpdb;
1799         static $global_terms_recurse = null;
1800
1801         if ( !global_terms_enabled() )
1802                 return $term_id;
1803
1804         // prevent a race condition
1805         $recurse_start = false;
1806         if ( $global_terms_recurse === null ) {
1807                 $recurse_start = true;
1808                 $global_terms_recurse = 1;
1809         } elseif ( 10 < $global_terms_recurse++ ) {
1810                 return $term_id;
1811         }
1812
1813         $term_id = intval( $term_id );
1814         $c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->terms WHERE term_id = %d", $term_id ) );
1815
1816         $global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE category_nicename = %s", $c->slug ) );
1817         if ( $global_id == null ) {
1818                 $used_global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE cat_ID = %d", $c->term_id ) );
1819                 if ( null == $used_global_id ) {
1820                         $wpdb->insert( $wpdb->sitecategories, array( 'cat_ID' => $term_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug ) );
1821                         $global_id = $wpdb->insert_id;
1822                         if ( empty( $global_id ) )
1823                                 return $term_id;
1824                 } else {
1825                         $max_global_id = $wpdb->get_var( "SELECT MAX(cat_ID) FROM $wpdb->sitecategories" );
1826                         $max_local_id = $wpdb->get_var( "SELECT MAX(term_id) FROM $wpdb->terms" );
1827                         $new_global_id = max( $max_global_id, $max_local_id ) + mt_rand( 100, 400 );
1828                         $wpdb->insert( $wpdb->sitecategories, array( 'cat_ID' => $new_global_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug ) );
1829                         $global_id = $wpdb->insert_id;
1830                 }
1831         } elseif ( $global_id != $term_id ) {
1832                 $local_id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE term_id = %d", $global_id ) );
1833                 if ( null != $local_id ) {
1834                         global_terms( $local_id );
1835                         if ( 10 < $global_terms_recurse ) {
1836                                 $global_id = $term_id;
1837                         }
1838                 }
1839         }
1840
1841         if ( $global_id != $term_id ) {
1842                 if ( get_option( 'default_category' ) == $term_id )
1843                         update_option( 'default_category', $global_id );
1844
1845                 $wpdb->update( $wpdb->terms, array('term_id' => $global_id), array('term_id' => $term_id) );
1846                 $wpdb->update( $wpdb->term_taxonomy, array('term_id' => $global_id), array('term_id' => $term_id) );
1847                 $wpdb->update( $wpdb->term_taxonomy, array('parent' => $global_id), array('parent' => $term_id) );
1848
1849                 clean_term_cache($term_id);
1850         }
1851         if ( $recurse_start )
1852                 $global_terms_recurse = null;
1853
1854         return $global_id;
1855 }
1856
1857 /**
1858  * Ensure that the current site's domain is listed in the allowed redirect host list.
1859  *
1860  * @see wp_validate_redirect()
1861  * @since MU
1862  *
1863  * @param array|string $deprecated Not used.
1864  * @return array The current site's domain
1865  */
1866 function redirect_this_site( $deprecated = '' ) {
1867         return array( get_current_site()->domain );
1868 }
1869
1870 /**
1871  * Check whether an upload is too big.
1872  *
1873  * @since MU
1874  *
1875  * @blessed
1876  *
1877  * @param array $upload
1878  * @return string|array If the upload is under the size limit, $upload is returned. Otherwise returns an error message.
1879  */
1880 function upload_is_file_too_big( $upload ) {
1881         if ( ! is_array( $upload ) || defined( 'WP_IMPORTING' ) || get_site_option( 'upload_space_check_disabled' ) )
1882                 return $upload;
1883
1884         if ( strlen( $upload['bits'] )  > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
1885                 return sprintf( __( 'This file is too big. Files must be less than %d KB in size.' ) . '<br />', get_site_option( 'fileupload_maxk', 1500 ) );
1886         }
1887
1888         return $upload;
1889 }
1890
1891 /**
1892  * Add a nonce field to the signup page.
1893  *
1894  * @since MU
1895  */
1896 function signup_nonce_fields() {
1897         $id = mt_rand();
1898         echo "<input type='hidden' name='signup_form_id' value='{$id}' />";
1899         wp_nonce_field('signup_form_' . $id, '_signup_form', false);
1900 }
1901
1902 /**
1903  * Process the signup nonce created in signup_nonce_fields().
1904  *
1905  * @since MU
1906  *
1907  * @param array $result
1908  * @return array
1909  */
1910 function signup_nonce_check( $result ) {
1911         if ( !strpos( $_SERVER[ 'PHP_SELF' ], 'wp-signup.php' ) )
1912                 return $result;
1913
1914         if ( wp_create_nonce('signup_form_' . $_POST[ 'signup_form_id' ]) != $_POST['_signup_form'] )
1915                 wp_die( __( 'Please try again.' ) );
1916
1917         return $result;
1918 }
1919
1920 /**
1921  * Correct 404 redirects when NOBLOGREDIRECT is defined.
1922  *
1923  * @since MU
1924  */
1925 function maybe_redirect_404() {
1926         /**
1927          * Filter the redirect URL for 404s on the main site.
1928          *
1929          * The filter is only evaluated if the NOBLOGREDIRECT constant is defined.
1930          *
1931          * @since 3.0.0
1932          *
1933          * @param string $no_blog_redirect The redirect URL defined in NOBLOGREDIRECT.
1934          */
1935         if ( is_main_site() && is_404() && defined( 'NOBLOGREDIRECT' ) && ( $destination = apply_filters( 'blog_redirect_404', NOBLOGREDIRECT ) ) ) {
1936                 if ( $destination == '%siteurl%' )
1937                         $destination = network_home_url();
1938                 wp_redirect( $destination );
1939                 exit();
1940         }
1941 }
1942
1943 /**
1944  * Add a new user to a blog by visiting /newbloguser/username/.
1945  *
1946  * This will only work when the user's details are saved as an option
1947  * keyed as 'new_user_x', where 'x' is the username of the user to be
1948  * added, as when a user is invited through the regular WP Add User interface.
1949  *
1950  * @since MU
1951  */
1952 function maybe_add_existing_user_to_blog() {
1953         if ( false === strpos( $_SERVER[ 'REQUEST_URI' ], '/newbloguser/' ) )
1954                 return;
1955
1956         $parts = explode( '/', $_SERVER[ 'REQUEST_URI' ] );
1957         $key = array_pop( $parts );
1958
1959         if ( $key == '' )
1960                 $key = array_pop( $parts );
1961
1962         $details = get_option( 'new_user_' . $key );
1963         if ( !empty( $details ) )
1964                 delete_option( 'new_user_' . $key );
1965
1966         if ( empty( $details ) || is_wp_error( add_existing_user_to_blog( $details ) ) )
1967                 wp_die( sprintf(__('An error occurred adding you to this site. Back to the <a href="%s">homepage</a>.'), home_url() ) );
1968
1969         wp_die( sprintf( __( 'You have been added to this site. Please visit the <a href="%s">homepage</a> or <a href="%s">log in</a> using your username and password.' ), home_url(), admin_url() ), __( 'WordPress &rsaquo; Success' ), array( 'response' => 200 ) );
1970 }
1971
1972 /**
1973  * Add a user to a blog based on details from maybe_add_existing_user_to_blog().
1974  *
1975  * @since MU
1976  *
1977  * @global int $blog_id
1978  *
1979  * @param array $details
1980  * @return true|WP_Error|void
1981  */
1982 function add_existing_user_to_blog( $details = false ) {
1983         global $blog_id;
1984
1985         if ( is_array( $details ) ) {
1986                 $result = add_user_to_blog( $blog_id, $details[ 'user_id' ], $details[ 'role' ] );
1987                 /**
1988                  * Fires immediately after an existing user is added to a site.
1989                  *
1990                  * @since MU
1991                  *
1992                  * @param int   $user_id User ID.
1993                  * @param mixed $result  True on success or a WP_Error object if the user doesn't exist.
1994                  */
1995                 do_action( 'added_existing_user', $details['user_id'], $result );
1996                 return $result;
1997         }
1998 }
1999
2000 /**
2001  * Add a newly created user to the appropriate blog
2002  *
2003  * To add a user in general, use add_user_to_blog(). This function
2004  * is specifically hooked into the wpmu_activate_user action.
2005  *
2006  * @since MU
2007  * @see add_user_to_blog()
2008  *
2009  * @param int   $user_id
2010  * @param mixed $password Ignored.
2011  * @param array $meta
2012  */
2013 function add_new_user_to_blog( $user_id, $password, $meta ) {
2014         if ( !empty( $meta[ 'add_to_blog' ] ) ) {
2015                 $blog_id = $meta[ 'add_to_blog' ];
2016                 $role = $meta[ 'new_role' ];
2017                 remove_user_from_blog($user_id, get_current_site()->blog_id); // remove user from main blog.
2018                 add_user_to_blog( $blog_id, $user_id, $role );
2019                 update_user_meta( $user_id, 'primary_blog', $blog_id );
2020         }
2021 }
2022
2023 /**
2024  * Correct From host on outgoing mail to match the site domain
2025  *
2026  * @since MU
2027  *
2028  * @param PHPMailer $phpmailer The PHPMailer instance, passed by reference.
2029  */
2030 function fix_phpmailer_messageid( $phpmailer ) {
2031         $phpmailer->Hostname = get_current_site()->domain;
2032 }
2033
2034 /**
2035  * Check to see whether a user is marked as a spammer, based on user login.
2036  *
2037  * @since MU
2038  *
2039  * @param string|WP_User $user Optional. Defaults to current user. WP_User object,
2040  *                                 or user login name as a string.
2041  * @return bool
2042  */
2043 function is_user_spammy( $user = null ) {
2044     if ( ! ( $user instanceof WP_User ) ) {
2045                 if ( $user ) {
2046                         $user = get_user_by( 'login', $user );
2047                 } else {
2048                         $user = wp_get_current_user();
2049                 }
2050         }
2051
2052         return $user && isset( $user->spam ) && 1 == $user->spam;
2053 }
2054
2055 /**
2056  * Update this blog's 'public' setting in the global blogs table.
2057  *
2058  * Public blogs have a setting of 1, private blogs are 0.
2059  *
2060  * @since MU
2061  *
2062  * @param int $old_value
2063  * @param int $value     The new public value
2064  */
2065 function update_blog_public( $old_value, $value ) {
2066         update_blog_status( get_current_blog_id(), 'public', (int) $value );
2067 }
2068
2069 /**
2070  * Check whether a usermeta key has to do with the current blog.
2071  *
2072  * @since MU
2073  *
2074  * @global wpdb $wpdb WordPress database abstraction object.
2075  *
2076  * @param string $key
2077  * @param int    $user_id Optional. Defaults to current user.
2078  * @param int    $blog_id Optional. Defaults to current blog.
2079  * @return bool
2080  */
2081 function is_user_option_local( $key, $user_id = 0, $blog_id = 0 ) {
2082         global $wpdb;
2083
2084         $current_user = wp_get_current_user();
2085         if ( $blog_id == 0 ) {
2086                 $blog_id = $wpdb->blogid;
2087         }
2088         $local_key = $wpdb->get_blog_prefix( $blog_id ) . $key;
2089
2090         return isset( $current_user->$local_key );
2091 }
2092
2093 /**
2094  * Check whether users can self-register, based on Network settings.
2095  *
2096  * @since MU
2097  *
2098  * @return bool
2099  */
2100 function users_can_register_signup_filter() {
2101         $registration = get_site_option('registration');
2102         return ( $registration == 'all' || $registration == 'user' );
2103 }
2104
2105 /**
2106  * Ensure that the welcome message is not empty. Currently unused.
2107  *
2108  * @since MU
2109  *
2110  * @param string $text
2111  * @return string
2112  */
2113 function welcome_user_msg_filter( $text ) {
2114         if ( !$text ) {
2115                 remove_filter( 'site_option_welcome_user_email', 'welcome_user_msg_filter' );
2116
2117                 /* translators: Do not translate USERNAME, PASSWORD, LOGINLINK, SITE_NAME: those are placeholders. */
2118                 $text = __( 'Howdy USERNAME,
2119
2120 Your new account is set up.
2121
2122 You can log in with the following information:
2123 Username: USERNAME
2124 Password: PASSWORD
2125 LOGINLINK
2126
2127 Thanks!
2128
2129 --The Team @ SITE_NAME' );
2130                 update_site_option( 'welcome_user_email', $text );
2131         }
2132         return $text;
2133 }
2134
2135 /**
2136  * Whether to force SSL on content.
2137  *
2138  * @since 2.8.5
2139  *
2140  * @staticvar bool $forced_content
2141  *
2142  * @param bool $force
2143  * @return bool True if forced, false if not forced.
2144  */
2145 function force_ssl_content( $force = '' ) {
2146         static $forced_content = false;
2147
2148         if ( '' != $force ) {
2149                 $old_forced = $forced_content;
2150                 $forced_content = $force;
2151                 return $old_forced;
2152         }
2153
2154         return $forced_content;
2155 }
2156
2157 /**
2158  * Formats a URL to use https.
2159  *
2160  * Useful as a filter.
2161  *
2162  * @since 2.8.5
2163  *
2164  * @param string $url URL
2165  * @return string URL with https as the scheme
2166  */
2167 function filter_SSL( $url ) {
2168         if ( ! is_string( $url ) )
2169                 return get_bloginfo( 'url' ); // Return home blog url with proper scheme
2170
2171         if ( force_ssl_content() && is_ssl() )
2172                 $url = set_url_scheme( $url, 'https' );
2173
2174         return $url;
2175 }
2176
2177 /**
2178  * Schedule update of the network-wide counts for the current network.
2179  *
2180  * @since 3.1.0
2181  */
2182 function wp_schedule_update_network_counts() {
2183         if ( !is_main_site() )
2184                 return;
2185
2186         if ( ! wp_next_scheduled('update_network_counts') && ! wp_installing() )
2187                 wp_schedule_event(time(), 'twicedaily', 'update_network_counts');
2188 }
2189
2190 /**
2191  *  Update the network-wide counts for the current network.
2192  *
2193  *  @since 3.1.0
2194  */
2195 function wp_update_network_counts() {
2196         wp_update_network_user_counts();
2197         wp_update_network_site_counts();
2198 }
2199
2200 /**
2201  * Update the count of sites for the current network.
2202  *
2203  * If enabled through the 'enable_live_network_counts' filter, update the sites count
2204  * on a network when a site is created or its status is updated.
2205  *
2206  * @since 3.7.0
2207  */
2208 function wp_maybe_update_network_site_counts() {
2209         $is_small_network = ! wp_is_large_network( 'sites' );
2210
2211         /**
2212          * Filter whether to update network site or user counts when a new site is created.
2213          *
2214          * @since 3.7.0
2215          *
2216          * @see wp_is_large_network()
2217          *
2218          * @param bool   $small_network Whether the network is considered small.
2219          * @param string $context       Context. Either 'users' or 'sites'.
2220          */
2221         if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'sites' ) )
2222                 return;
2223
2224         wp_update_network_site_counts();
2225 }
2226
2227 /**
2228  * Update the network-wide users count.
2229  *
2230  * If enabled through the 'enable_live_network_counts' filter, update the users count
2231  * on a network when a user is created or its status is updated.
2232  *
2233  * @since 3.7.0
2234  */
2235 function wp_maybe_update_network_user_counts() {
2236         $is_small_network = ! wp_is_large_network( 'users' );
2237
2238         /** This filter is documented in wp-includes/ms-functions.php */
2239         if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'users' ) )
2240                 return;
2241
2242         wp_update_network_user_counts();
2243 }
2244
2245 /**
2246  * Update the network-wide site count.
2247  *
2248  * @since 3.7.0
2249  *
2250  * @global wpdb $wpdb WordPress database abstraction object.
2251  */
2252 function wp_update_network_site_counts() {
2253         global $wpdb;
2254
2255         $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(blog_id) as c FROM $wpdb->blogs WHERE site_id = %d AND spam = '0' AND deleted = '0' and archived = '0'", $wpdb->siteid) );
2256         update_site_option( 'blog_count', $count );
2257 }
2258
2259 /**
2260  * Update the network-wide user count.
2261  *
2262  * @since 3.7.0
2263  *
2264  * @global wpdb $wpdb WordPress database abstraction object.
2265  */
2266 function wp_update_network_user_counts() {
2267         global $wpdb;
2268
2269         $count = $wpdb->get_var( "SELECT COUNT(ID) as c FROM $wpdb->users WHERE spam = '0' AND deleted = '0'" );
2270         update_site_option( 'user_count', $count );
2271 }
2272
2273 /**
2274  * Returns the space used by the current blog.
2275  *
2276  * @since 3.5.0
2277  *
2278  * @return int Used space in megabytes
2279  */
2280 function get_space_used() {
2281         /**
2282          * Filter the amount of storage space used by the current site.
2283          *
2284          * @since 3.5.0
2285          *
2286          * @param int|bool $space_used The amount of used space, in megabytes. Default false.
2287          */
2288         $space_used = apply_filters( 'pre_get_space_used', false );
2289         if ( false === $space_used ) {
2290                 $upload_dir = wp_upload_dir();
2291                 $space_used = get_dirsize( $upload_dir['basedir'] ) / MB_IN_BYTES;
2292         }
2293
2294         return $space_used;
2295 }
2296
2297 /**
2298  * Returns the upload quota for the current blog.
2299  *
2300  * @since MU
2301  *
2302  * @return int Quota in megabytes
2303  */
2304 function get_space_allowed() {
2305         $space_allowed = get_option( 'blog_upload_space' );
2306
2307         if ( ! is_numeric( $space_allowed ) )
2308                 $space_allowed = get_site_option( 'blog_upload_space' );
2309
2310         if ( ! is_numeric( $space_allowed ) )
2311                 $space_allowed = 100;
2312
2313         /**
2314          * Filter the upload quota for the current site.
2315          *
2316          * @since 3.7.0
2317          *
2318          * @param int $space_allowed Upload quota in megabytes for the current blog.
2319          */
2320         return apply_filters( 'get_space_allowed', $space_allowed );
2321 }
2322
2323 /**
2324  * Determines if there is any upload space left in the current blog's quota.
2325  *
2326  * @since 3.0.0
2327  *
2328  * @return int of upload space available in bytes
2329  */
2330 function get_upload_space_available() {
2331         $allowed = get_space_allowed();
2332         if ( $allowed < 0 ) {
2333                 $allowed = 0;
2334         }
2335         $space_allowed = $allowed * MB_IN_BYTES;
2336         if ( get_site_option( 'upload_space_check_disabled' ) )
2337                 return $space_allowed;
2338
2339         $space_used = get_space_used() * MB_IN_BYTES;
2340
2341         if ( ( $space_allowed - $space_used ) <= 0 )
2342                 return 0;
2343
2344         return $space_allowed - $space_used;
2345 }
2346
2347 /**
2348  * Determines if there is any upload space left in the current blog's quota.
2349  *
2350  * @since 3.0.0
2351  * @return bool True if space is available, false otherwise.
2352  */
2353 function is_upload_space_available() {
2354         if ( get_site_option( 'upload_space_check_disabled' ) )
2355                 return true;
2356
2357         return (bool) get_upload_space_available();
2358 }
2359
2360 /**
2361  * Filters the maximum upload file size allowed, in bytes.
2362  *
2363  * @since 3.0.0
2364  *
2365  * @param  int $size Upload size limit in bytes.
2366  * @return int       Upload size limit in bytes.
2367  */
2368 function upload_size_limit_filter( $size ) {
2369         $fileupload_maxk = KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 );
2370         if ( get_site_option( 'upload_space_check_disabled' ) )
2371                 return min( $size, $fileupload_maxk );
2372
2373         return min( $size, $fileupload_maxk, get_upload_space_available() );
2374 }
2375
2376 /**
2377  * Whether or not we have a large network.
2378  *
2379  * The default criteria for a large network is either more than 10,000 users or more than 10,000 sites.
2380  * Plugins can alter this criteria using the 'wp_is_large_network' filter.
2381  *
2382  * @since 3.3.0
2383  * @param string $using 'sites or 'users'. Default is 'sites'.
2384  * @return bool True if the network meets the criteria for large. False otherwise.
2385  */
2386 function wp_is_large_network( $using = 'sites' ) {
2387         if ( 'users' == $using ) {
2388                 $count = get_user_count();
2389                 /**
2390                  * Filter whether the network is considered large.
2391                  *
2392                  * @since 3.3.0
2393                  *
2394                  * @param bool   $is_large_network Whether the network has more than 10000 users or sites.
2395                  * @param string $component        The component to count. Accepts 'users', or 'sites'.
2396                  * @param int    $count            The count of items for the component.
2397                  */
2398                 return apply_filters( 'wp_is_large_network', $count > 10000, 'users', $count );
2399         }
2400
2401         $count = get_blog_count();
2402         /** This filter is documented in wp-includes/ms-functions.php */
2403         return apply_filters( 'wp_is_large_network', $count > 10000, 'sites', $count );
2404 }
2405
2406
2407 /**
2408  * Return an array of sites for a network or networks.
2409  *
2410  * @since 3.7.0
2411  *
2412  * @global wpdb $wpdb WordPress database abstraction object.
2413  *
2414  * @param array $args {
2415  *     Array of default arguments. Optional.
2416  *
2417  *     @type int|array $network_id A network ID or array of network IDs. Set to null to retrieve sites
2418  *                                 from all networks. Defaults to current network ID.
2419  *     @type int       $public     Retrieve public or non-public sites. Default null, for any.
2420  *     @type int       $archived   Retrieve archived or non-archived sites. Default null, for any.
2421  *     @type int       $mature     Retrieve mature or non-mature sites. Default null, for any.
2422  *     @type int       $spam       Retrieve spam or non-spam sites. Default null, for any.
2423  *     @type int       $deleted    Retrieve deleted or non-deleted sites. Default null, for any.
2424  *     @type int       $limit      Number of sites to limit the query to. Default 100.
2425  *     @type int       $offset     Exclude the first x sites. Used in combination with the $limit parameter. Default 0.
2426  * }
2427  * @return array An empty array if the install is considered "large" via wp_is_large_network(). Otherwise,
2428  *               an associative array of site data arrays, each containing the site (network) ID, blog ID,
2429  *               site domain and path, dates registered and modified, and the language ID. Also, boolean
2430  *               values for whether the site is public, archived, mature, spam, and/or deleted.
2431  */
2432 function wp_get_sites( $args = array() ) {
2433         global $wpdb;
2434
2435         if ( wp_is_large_network() )
2436                 return array();
2437
2438         $defaults = array(
2439                 'network_id' => $wpdb->siteid,
2440                 'public'     => null,
2441                 'archived'   => null,
2442                 'mature'     => null,
2443                 'spam'       => null,
2444                 'deleted'    => null,
2445                 'limit'      => 100,
2446                 'offset'     => 0,
2447         );
2448
2449         $args = wp_parse_args( $args, $defaults );
2450
2451         $query = "SELECT * FROM $wpdb->blogs WHERE 1=1 ";
2452
2453         if ( isset( $args['network_id'] ) && ( is_array( $args['network_id'] ) || is_numeric( $args['network_id'] ) ) ) {
2454                 $network_ids = implode( ',', wp_parse_id_list( $args['network_id'] ) );
2455                 $query .= "AND site_id IN ($network_ids) ";
2456         }
2457
2458         if ( isset( $args['public'] ) )
2459                 $query .= $wpdb->prepare( "AND public = %d ", $args['public'] );
2460
2461         if ( isset( $args['archived'] ) )
2462                 $query .= $wpdb->prepare( "AND archived = %d ", $args['archived'] );
2463
2464         if ( isset( $args['mature'] ) )
2465                 $query .= $wpdb->prepare( "AND mature = %d ", $args['mature'] );
2466
2467         if ( isset( $args['spam'] ) )
2468                 $query .= $wpdb->prepare( "AND spam = %d ", $args['spam'] );
2469
2470         if ( isset( $args['deleted'] ) )
2471                 $query .= $wpdb->prepare( "AND deleted = %d ", $args['deleted'] );
2472
2473         if ( isset( $args['limit'] ) && $args['limit'] ) {
2474                 if ( isset( $args['offset'] ) && $args['offset'] )
2475                         $query .= $wpdb->prepare( "LIMIT %d , %d ", $args['offset'], $args['limit'] );
2476                 else
2477                         $query .= $wpdb->prepare( "LIMIT %d ", $args['limit'] );
2478         }
2479
2480         $site_results = $wpdb->get_results( $query, ARRAY_A );
2481
2482         return $site_results;
2483 }
2484
2485 /**
2486  * Retrieves a list of reserved site on a sub-directory Multisite install.
2487  *
2488  * @since 4.4.0
2489  *
2490  * @return array $names Array of reserved subdirectory names.
2491  */
2492 function get_subdirectory_reserved_names() {
2493         $names = array(
2494                 'page', 'comments', 'blog', 'files', 'feed', 'wp-admin',
2495                 'wp-content', 'wp-includes', 'wp-json', 'embed'
2496         );
2497
2498         /**
2499          * Filter reserved site names on a sub-directory Multisite install.
2500          *
2501          * @since 3.0.0
2502          * @since 4.4.0 'wp-admin', 'wp-content', 'wp-includes', 'wp-json', and 'embed' were added
2503          *              to the reserved names list.
2504          *
2505          * @param array $subdirectory_reserved_names Array of reserved names.
2506          */
2507         return apply_filters( 'subdirectory_reserved_names', $names );
2508 }