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