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