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