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