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