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