]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/ms-functions.php
Wordpress 3.0
[autoinstalls/wordpress.git] / wp-includes / ms-functions.php
1 <?php
2 /**
3  * Multi-site WordPress API
4  *
5  * @package WordPress
6  * @subpackage Multisite
7  * @since 3.0.0
8  */
9
10 function get_sitestats() {
11         global $wpdb;
12
13         $stats['blogs'] = get_blog_count();
14
15         $count_ts = get_site_option( 'user_count_ts' );
16         if ( time() - $count_ts > 3600 ) {
17                 $count = $wpdb->get_var( "SELECT COUNT(ID) FROM $wpdb->users" );
18                 update_site_option( 'user_count', $count );
19                 update_site_option( 'user_count_ts', time() );
20         } else {
21                 $count = get_site_option( 'user_count' );
22         }
23         $stats['users'] = $count;
24         return $stats;
25 }
26
27 function get_admin_users_for_domain( $sitedomain = '', $path = '' ) {
28         global $wpdb;
29
30         if ( ! $sitedomain )
31                 $site_id = $wpdb->siteid;
32         else
33                 $site_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM $wpdb->site WHERE domain = %s AND path = %s", $sitedomain, $path ) );
34
35         if ( $site_id )
36                 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 );
37
38         return false;
39 }
40
41 function get_blogs_of_user( $id, $all = false ) {
42         global $wpdb;
43
44         $cache_suffix = $all ? '_all' : '_short';
45         $return = wp_cache_get( 'blogs_of_user_' . $id . $cache_suffix, 'users' );
46         if ( $return )
47                 return apply_filters( 'get_blogs_of_user', $return, $id, $all );
48
49         $user = get_userdata( (int) $id );
50         if ( !$user )
51                 return false;
52
53         $blogs = $match = array();
54         $prefix_length = strlen($wpdb->base_prefix);
55         foreach ( (array) $user as $key => $value ) {
56                 if ( $prefix_length && substr($key, 0, $prefix_length) != $wpdb->base_prefix )
57                         continue;
58                 if ( substr($key, -12, 12) != 'capabilities' )
59                         continue;
60                 if ( preg_match( '/^' . $wpdb->base_prefix . '((\d+)_)?capabilities$/', $key, $match ) ) {
61                         if ( count( $match ) > 2 )
62                                 $blog_id = $match[ 2 ];
63                         else
64                                 $blog_id = 1;
65                         $blog = get_blog_details( $blog_id );
66                         if ( $blog && isset( $blog->domain ) && ( $all == true || $all == false && ( $blog->archived == 0 && $blog->spam == 0 && $blog->deleted == 0 ) ) ) {
67                                 $blogs[ $blog_id ]->userblog_id = $blog_id;
68                                 $blogs[ $blog_id ]->blogname            = $blog->blogname;
69                                 $blogs[ $blog_id ]->domain              = $blog->domain;
70                                 $blogs[ $blog_id ]->path                        = $blog->path;
71                                 $blogs[ $blog_id ]->site_id             = $blog->site_id;
72                                 $blogs[ $blog_id ]->siteurl             = $blog->siteurl;
73                         }
74                 }
75         }
76
77         wp_cache_add( 'blogs_of_user_' . $id . $cache_suffix, $blogs, 'users', 5 );
78         return apply_filters( 'get_blogs_of_user', $blogs, $id, $all );
79 }
80
81 function get_active_blog_for_user( $user_id ) { // get an active blog for user - either primary blog or from blogs list
82         global $wpdb;
83         $blogs = get_blogs_of_user( $user_id );
84         if ( empty( $blogs ) ) {
85                 $details = get_dashboard_blog();
86                 add_user_to_blog( $details->blog_id, $user_id, 'subscriber' );
87                 update_user_meta( $user_id, 'primary_blog', $details->blog_id );
88                 wp_cache_delete( $user_id, 'users' );
89                 return $details;
90         }
91
92         $primary_blog = get_user_meta( $user_id, 'primary_blog', true );
93         $details = get_dashboard_blog();
94         if ( $primary_blog ) {
95                 $blogs = get_blogs_of_user( $user_id );
96                 if ( isset( $blogs[ $primary_blog ] ) == false ) {
97                         add_user_to_blog( $details->blog_id, $user_id, 'subscriber' );
98                         update_user_meta( $user_id, 'primary_blog', $details->blog_id );
99                         wp_cache_delete( $user_id, 'users' );
100                 } else {
101                         $details = get_blog_details( $primary_blog );
102                 }
103         } else {
104                 add_user_to_blog( $details->blog_id, $user_id, 'subscriber' ); // Add subscriber permission for dashboard blog
105                 update_user_meta( $user_id, 'primary_blog', $details->blog_id );
106         }
107
108         if ( ( is_object( $details ) == false ) || ( is_object( $details ) && $details->archived == 1 || $details->spam == 1 || $details->deleted == 1 ) ) {
109                 $blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs.
110                 $ret = false;
111                 if ( is_array( $blogs ) && count( $blogs ) > 0 ) {
112                         foreach ( (array) $blogs as $blog_id => $blog ) {
113                                 if ( $blog->site_id != $wpdb->siteid )
114                                         continue;
115                                 $details = get_blog_details( $blog_id );
116                                 if ( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) {
117                                         $ret = $blog;
118                                         $changed = false;
119                                         if ( get_user_meta( $user_id , 'primary_blog', true ) != $blog_id ) {
120                                                 update_user_meta( $user_id, 'primary_blog', $blog_id );
121                                                 $changed = true;
122                                         }
123                                         if ( !get_user_meta($user_id , 'source_domain', true) ) {
124                                                 update_user_meta( $user_id, 'source_domain', $blog->domain );
125                                                 $changed = true;
126                                         }
127                                         if ( $changed )
128                                                 wp_cache_delete( $user_id, 'users' );
129                                         break;
130                                 }
131                         }
132                 } else {
133                         // Should never get here
134                         $dashboard_blog = get_dashboard_blog();
135                         add_user_to_blog( $dashboard_blog->blog_id, $user_id, 'subscriber' ); // Add subscriber permission for dashboard blog
136                         update_user_meta( $user_id, 'primary_blog', $dashboard_blog->blog_id );
137                         return $dashboard_blog;
138                 }
139                 return $ret;
140         } else {
141                 return $details;
142         }
143 }
144
145 function is_user_member_of_blog( $user_id, $blog_id = 0 ) {
146         $user_id = (int) $user_id;
147         $blog_id = (int) $blog_id;
148
149         if ( $blog_id == 0 ) {
150                 global $wpdb;
151                 $blog_id = $wpdb->blogid;
152         }
153
154         $blogs = get_blogs_of_user( $user_id );
155         if ( is_array( $blogs ) )
156                 return array_key_exists( $blog_id, $blogs );
157         else
158                 return false;
159 }
160
161 function get_user_count() {
162         global $wpdb;
163
164         $count_ts = get_site_option( 'user_count_ts' );
165         if ( time() - $count_ts > 3600 ) {
166                 $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(ID) as c FROM $wpdb->users WHERE spam = '0' AND deleted = '0'") );
167                 update_site_option( 'user_count', $count );
168                 update_site_option( 'user_count_ts', time() );
169         }
170
171         $count = get_site_option( 'user_count' );
172
173         return $count;
174 }
175
176 function get_blog_count( $id = 0 ) {
177         global $wpdb;
178
179         if ( $id == 0 )
180                 $id = $wpdb->siteid;
181
182         $count_ts = get_site_option( 'blog_count_ts' );
183         if ( time() - $count_ts > 3600 ) {
184                 $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'", $id) );
185                 update_site_option( 'blog_count', $count );
186                 update_site_option( 'blog_count_ts', time() );
187         }
188
189         $count = get_site_option( 'blog_count' );
190
191         return $count;
192 }
193
194 function get_blog_post( $blog_id, $post_id ) {
195         global $wpdb;
196
197         $key = $blog_id . '-' . $post_id;
198         $post = wp_cache_get( $key, 'global-posts' );
199         if ( $post == false ) {
200                 $post = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . $wpdb->get_blog_prefix( $blog_id ) . 'posts WHERE ID = %d', $post_id ) );
201                 wp_cache_add( $key, $post, 'global-posts' );
202         }
203
204         return $post;
205 }
206
207 function add_user_to_blog( $blog_id, $user_id, $role ) {
208         switch_to_blog($blog_id);
209
210         $user = new WP_User($user_id);
211
212         if ( empty($user) || !$user->ID )
213                 return new WP_Error('user_does_not_exist', __('That user does not exist.'));
214
215         if ( !get_user_meta($user_id, 'primary_blog', true) ) {
216                 update_user_meta($user_id, 'primary_blog', $blog_id);
217                 $details = get_blog_details($blog_id);
218                 update_user_meta($user_id, 'source_domain', $details->domain);
219         }
220
221         $user->set_role($role);
222
223         do_action('add_user_to_blog', $user_id, $role, $blog_id);
224         wp_cache_delete( $user_id, 'users' );
225         restore_current_blog();
226         return true;
227 }
228
229 function remove_user_from_blog($user_id, $blog_id = '', $reassign = '') {
230         global $wpdb;
231         switch_to_blog($blog_id);
232         $user_id = (int) $user_id;
233         do_action('remove_user_from_blog', $user_id, $blog_id);
234
235         // If being removed from the primary blog, set a new primary if the user is assigned
236         // to multiple blogs.
237         $primary_blog = get_user_meta($user_id, 'primary_blog', true);
238         if ( $primary_blog == $blog_id ) {
239                 $new_id = '';
240                 $new_domain = '';
241                 $blogs = get_blogs_of_user($user_id);
242                 foreach ( (array) $blogs as $blog ) {
243                         if ( $blog->userblog_id == $blog_id )
244                                 continue;
245                         $new_id = $blog->userblog_id;
246                         $new_domain = $blog->domain;
247                         break;
248                 }
249
250                 update_user_meta($user_id, 'primary_blog', $new_id);
251                 update_user_meta($user_id, 'source_domain', $new_domain);
252         }
253
254         // wp_revoke_user($user_id);
255         $user = new WP_User($user_id);
256         $user->remove_all_caps();
257
258         $blogs = get_blogs_of_user($user_id);
259         if ( count($blogs) == 0 ) {
260                 update_user_meta($user_id, 'primary_blog', '');
261                 update_user_meta($user_id, 'source_domain', '');
262         }
263
264         if ( $reassign != '' ) {
265                 $reassign = (int) $reassign;
266                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_author = %d WHERE post_author = %d", $reassign, $user_id) );
267                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->links SET link_owner = %d WHERE link_owner = %d", $reassign, $user_id) );
268         }
269
270         restore_current_blog();
271 }
272
273 function create_empty_blog( $domain, $path, $weblog_title, $site_id = 1 ) {
274         $domain                 = addslashes( $domain );
275         $weblog_title   = addslashes( $weblog_title );
276
277         if ( empty($path) )
278                 $path = '/';
279
280         // Check if the domain has been used already. We should return an error message.
281         if ( domain_exists($domain, $path, $site_id) )
282                 return __( 'Error: Site URL already taken.' );
283
284         // Need to backup wpdb table names, and create a new wp_blogs entry for new blog.
285         // Need to get blog_id from wp_blogs, and create new table names.
286         // Must restore table names at the end of function.
287
288         if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
289                 return __( 'Error: problem creating site entry.' );
290
291         switch_to_blog($blog_id);
292         install_blog($blog_id);
293         restore_current_blog();
294
295         return $blog_id;
296 }
297
298 function get_blog_permalink( $_blog_id, $post_id ) {
299         $key = "{$_blog_id}-{$post_id}-blog_permalink";
300         $link = wp_cache_get( $key, 'site-options' );
301         if ( $link == false ) {
302                 switch_to_blog( $_blog_id );
303                 $link = get_permalink( $post_id );
304                 restore_current_blog();
305                 wp_cache_add( $key, $link, 'site-options', 360 );
306         }
307         return $link;
308 }
309
310 function get_blog_id_from_url( $domain, $path = '/' ) {
311         global $wpdb;
312
313         $domain = strtolower( $wpdb->escape( $domain ) );
314         $path = strtolower( $wpdb->escape( $path ) );
315         $id = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' );
316
317         if ( $id == -1 ) { // blog does not exist
318                 return 0;
319         } elseif ( $id ) {
320                 return (int)$id;
321         }
322
323         $id = $wpdb->get_var( "SELECT blog_id FROM $wpdb->blogs WHERE domain = '$domain' and path = '$path' /* get_blog_id_from_url */" );
324
325         if ( !$id ) {
326                 wp_cache_set( md5( $domain . $path ), -1, 'blog-id-cache' );
327                 return false;
328         }
329         wp_cache_set( md5( $domain . $path ), $id, 'blog-id-cache' );
330
331         return $id;
332 }
333
334 // wpmu admin functions
335
336 function wpmu_admin_do_redirect( $url = '' ) {
337         $ref = '';
338         if ( isset( $_GET['ref'] ) )
339                 $ref = $_GET['ref'];
340         if ( isset( $_POST['ref'] ) )
341                 $ref = $_POST['ref'];
342
343         if ( $ref ) {
344                 $ref = wpmu_admin_redirect_add_updated_param( $ref );
345                 wp_redirect( $ref );
346                 exit();
347         }
348         if ( empty( $_SERVER['HTTP_REFERER'] ) == false ) {
349                 wp_redirect( $_SERVER['HTTP_REFERER'] );
350                 exit();
351         }
352
353         $url = wpmu_admin_redirect_add_updated_param( $url );
354         if ( isset( $_GET['redirect'] ) ) {
355                 if ( substr( $_GET['redirect'], 0, 2 ) == 's_' )
356                         $url .= '&action=blogs&s='. esc_html( substr( $_GET['redirect'], 2 ) );
357         } elseif ( isset( $_POST['redirect'] ) ) {
358                 $url = wpmu_admin_redirect_add_updated_param( $_POST['redirect'] );
359         }
360         wp_redirect( $url );
361         exit();
362 }
363
364 function wpmu_admin_redirect_add_updated_param( $url = '' ) {
365         if ( strpos( $url, 'updated=true' ) === false ) {
366                 if ( strpos( $url, '?' ) === false )
367                         return $url . '?updated=true';
368                 else
369                         return $url . '&updated=true';
370         }
371         return $url;
372 }
373
374 function is_blog_user( $blog_id = 0 ) {
375         global $current_user, $wpdb;
376
377         if ( !$blog_id )
378                 $blog_id = $wpdb->blogid;
379
380         $cap_key = $wpdb->base_prefix . $blog_id . '_capabilities';
381
382         if ( is_array($current_user->$cap_key) && in_array(1, $current_user->$cap_key) )
383                 return true;
384
385         return false;
386 }
387
388 function is_email_address_unsafe( $user_email ) {
389         $banned_names = get_site_option( 'banned_email_domains' );
390         if ($banned_names && !is_array( $banned_names ))
391                 $banned_names = explode( "\n", $banned_names);
392
393         if ( is_array( $banned_names ) && empty( $banned_names ) == false ) {
394                 $email_domain = strtolower( substr( $user_email, 1 + strpos( $user_email, '@' ) ) );
395                 foreach ( (array) $banned_names as $banned_domain ) {
396                         if ( $banned_domain == '' )
397                                 continue;
398                         if (
399                                 strstr( $email_domain, $banned_domain ) ||
400                                 (
401                                         strstr( $banned_domain, '/' ) &&
402                                         preg_match( $banned_domain, $email_domain )
403                                 )
404                         )
405                         return true;
406                 }
407         }
408         return false;
409 }
410
411 function wpmu_validate_user_signup($user_name, $user_email) {
412         global $wpdb;
413
414         $errors = new WP_Error();
415
416         $orig_username = $user_name;
417         $user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
418         $maybe = array();
419         preg_match( '/[a-z0-9]+/', $user_name, $maybe );
420
421         if ( $user_name != $orig_username || $user_name != $maybe[0] ) {
422                 $errors->add( 'user_name', __( "Only the lowercase letters a-z and numbers allowed" ) );
423                 $user_name = $orig_username;
424         }
425
426         $user_email = sanitize_email( $user_email );
427
428         if ( empty( $user_name ) )
429                 $errors->add('user_name', __('Please enter a username'));
430
431         $illegal_names = get_site_option( 'illegal_names' );
432         if ( is_array( $illegal_names ) == false ) {
433                 $illegal_names = array(  'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
434                 add_site_option( 'illegal_names', $illegal_names );
435         }
436         if ( in_array( $user_name, $illegal_names ) == true )
437                 $errors->add('user_name',  __('That username is not allowed'));
438
439         if ( is_email_address_unsafe( $user_email ) )
440                 $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.'));
441
442         if ( strlen( $user_name ) < 4 )
443                 $errors->add('user_name',  __('Username must be at least 4 characters'));
444
445         if ( strpos( ' ' . $user_name, '_' ) != false )
446                 $errors->add( 'user_name', __( 'Sorry, usernames may not contain the character &#8220;_&#8221;!' ) );
447
448         // all numeric?
449         $match = array();
450         preg_match( '/[0-9]*/', $user_name, $match );
451         if ( $match[0] == $user_name )
452                 $errors->add('user_name', __('Sorry, usernames must have letters too!'));
453
454         if ( !is_email( $user_email ) )
455                 $errors->add('user_email', __('Please enter a correct email address'));
456
457         $limited_email_domains = get_site_option( 'limited_email_domains' );
458         if ( is_array( $limited_email_domains ) && empty( $limited_email_domains ) == false ) {
459                 $emaildomain = substr( $user_email, 1 + strpos( $user_email, '@' ) );
460                 if ( in_array( $emaildomain, $limited_email_domains ) == false )
461                         $errors->add('user_email', __('Sorry, that email address is not allowed!'));
462         }
463
464         // Check if the username has been used already.
465         if ( username_exists($user_name) )
466                 $errors->add('user_name', __('Sorry, that username already exists!'));
467
468         // Check if the email address has been used already.
469         if ( email_exists($user_email) )
470                 $errors->add('user_email', __('Sorry, that email address is already used!'));
471
472         // Has someone already signed up for this username?
473         $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_login = %s", $user_name) );
474         if ( $signup != null ) {
475                 $registered_at =  mysql2date('U', $signup->registered);
476                 $now = current_time( 'timestamp', true );
477                 $diff = $now - $registered_at;
478                 // If registered more than two days ago, cancel registration and let this signup go through.
479                 if ( $diff > 172800 )
480                         $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->signups WHERE user_login = %s", $user_name) );
481                 else
482                         $errors->add('user_name', __('That username is currently reserved but may be available in a couple of days.'));
483
484                 if ( $signup->active == 0 && $signup->user_email == $user_email )
485                         $errors->add('user_email_used', __('username and email used'));
486         }
487
488         $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_email = %s", $user_email) );
489         if ( $signup != null ) {
490                 $diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered);
491                 // If registered more than two days ago, cancel registration and let this signup go through.
492                 if ( $diff > 172800 )
493                         $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->signups WHERE user_email = %s", $user_email) );
494                 else
495                         $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.'));
496         }
497
498         $result = array('user_name' => $user_name, 'orig_username' => $orig_username, 'user_email' => $user_email, 'errors' => $errors);
499
500         return apply_filters('wpmu_validate_user_signup', $result);
501 }
502
503 function wpmu_validate_blog_signup($blogname, $blog_title, $user = '') {
504         global $wpdb, $domain, $base, $current_site;
505
506         $blog_title = strip_tags( $blog_title );
507         $blog_title = substr( $blog_title, 0, 50 );
508
509         $errors = new WP_Error();
510         $illegal_names = get_site_option( 'illegal_names' );
511         if ( $illegal_names == false ) {
512                 $illegal_names = array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
513                 add_site_option( 'illegal_names', $illegal_names );
514         }
515
516         // On sub dir installs, Some names are so illegal, only a filter can spring them from jail
517         if (! is_subdomain_install() )
518                 $illegal_names = array_merge($illegal_names, apply_filters( 'subdirectory_reserved_names', array( 'page', 'comments', 'blog', 'files', 'feed' ) ) );
519
520
521         if ( empty( $blogname ) )
522                 $errors->add('blogname', __('Please enter a site name'));
523
524         $maybe = array();
525         preg_match( '/[a-z0-9]+/', $blogname, $maybe );
526         if ( $blogname != $maybe[0] )
527                 $errors->add('blogname', __('Only lowercase letters and numbers allowed'));
528
529         if ( in_array( $blogname, $illegal_names ) == true )
530                 $errors->add('blogname',  __('That name is not allowed'));
531
532         if ( strlen( $blogname ) < 4 && !is_super_admin() )
533                 $errors->add('blogname',  __('Site name must be at least 4 characters'));
534
535         if ( strpos( ' ' . $blogname, '_' ) != false )
536                 $errors->add( 'blogname', __( 'Sorry, site names may not contain the character &#8220;_&#8221;!' ) );
537
538         // do not allow users to create a blog that conflicts with a page on the main blog.
539         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 ) ) )
540                 $errors->add( 'blogname', __( 'Sorry, you may not use that site name.' ) );
541
542         // all numeric?
543         $match = array();
544         preg_match( '/[0-9]*/', $blogname, $match );
545         if ( $match[0] == $blogname )
546                 $errors->add('blogname', __('Sorry, site names must have letters too!'));
547
548         $blogname = apply_filters( 'newblogname', $blogname );
549
550         $blog_title = stripslashes(  $blog_title );
551
552         if ( empty( $blog_title ) )
553                 $errors->add('blog_title', __('Please enter a site title'));
554
555         // Check if the domain/path has been used already.
556         if ( is_subdomain_install() ) {
557                 $mydomain = $blogname . '.' . preg_replace( '|^www\.|', '', $domain );
558                 $path = $base;
559         } else {
560                 $mydomain = "$domain";
561                 $path = $base.$blogname.'/';
562         }
563         if ( domain_exists($mydomain, $path) )
564                 $errors->add('blogname', __('Sorry, that site already exists!'));
565
566         if ( username_exists( $blogname ) ) {
567                 if ( is_object( $user ) == false || ( is_object($user) && ( $user->user_login != $blogname ) ) )
568                         $errors->add( 'blogname', __( 'Sorry, that site is reserved!' ) );
569         }
570
571         // Has someone already signed up for this domain?
572         $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path) ); // TODO: Check email too?
573         if ( ! empty($signup) ) {
574                 $diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered);
575                 // If registered more than two days ago, cancel registration and let this signup go through.
576                 if ( $diff > 172800 )
577                         $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path) );
578                 else
579                         $errors->add('blogname', __('That site is currently reserved but may be available in a couple days.'));
580         }
581
582         $result = array('domain' => $mydomain, 'path' => $path, 'blogname' => $blogname, 'blog_title' => $blog_title, 'errors' => $errors);
583         return apply_filters('wpmu_validate_blog_signup', $result);
584 }
585
586 // Record signup information for future activation. wpmu_validate_signup() should be run
587 // on the inputs before calling wpmu_signup().
588 function wpmu_signup_blog($domain, $path, $title, $user, $user_email, $meta = '') {
589         global $wpdb;
590
591         $key = substr( md5( time() . rand() . $domain ), 0, 16 );
592         $meta = serialize($meta);
593         $domain = $wpdb->escape($domain);
594         $path = $wpdb->escape($path);
595         $title = $wpdb->escape($title);
596
597         $wpdb->insert( $wpdb->signups, array(
598                 'domain' => $domain,
599                 'path' => $path,
600                 'title' => $title,
601                 'user_login' => $user,
602                 'user_email' => $user_email,
603                 'registered' => current_time('mysql', true),
604                 'activation_key' => $key,
605                 'meta' => $meta
606         ) );
607
608         wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta);
609 }
610
611 function wpmu_signup_user($user, $user_email, $meta = '') {
612         global $wpdb;
613
614         // Format data
615         $user = preg_replace( '/\s+/', '', sanitize_user( $user, true ) );
616         $user_email = sanitize_email( $user_email );
617         $key = substr( md5( time() . rand() . $user_email ), 0, 16 );
618         $meta = serialize($meta);
619
620         $wpdb->insert( $wpdb->signups, array(
621                 'domain' => '',
622                 'path' => '',
623                 'title' => '',
624                 'user_login' => $user,
625                 'user_email' => $user_email,
626                 'registered' => current_time('mysql', true),
627                 'activation_key' => $key,
628                 'meta' => $meta
629         ) );
630
631         wpmu_signup_user_notification($user, $user_email, $key, $meta);
632 }
633
634 // Notify user of signup success.
635 function wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta = '') {
636         global $current_site;
637
638         if ( !apply_filters('wpmu_signup_blog_notification', $domain, $path, $title, $user, $user_email, $key, $meta) )
639                 return false;
640
641         // Send email with activation link.
642         if ( !is_subdomain_install() || $current_site->id != 1 )
643                 $activate_url = network_site_url("wp-activate.php?key=$key");
644         else
645                 $activate_url = "http://{$domain}{$path}wp-activate.php?key=$key"; // @todo use *_url() API
646
647         $activate_url = esc_url($activate_url);
648         $admin_email = get_site_option( 'admin_email' );
649         if ( $admin_email == '' )
650                 $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
651         $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
652         $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
653         $message = sprintf( apply_filters( 'wpmu_signup_blog_notification_email', __( "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" ) ), $activate_url, esc_url( "http://{$domain}{$path}" ), $key );
654         // TODO: Don't hard code activation link.
655         $subject = sprintf( apply_filters( 'wpmu_signup_blog_notification_subject', __( '[%1s] Activate %2s' ) ), $from_name, esc_url( 'http://' . $domain . $path ) );
656         wp_mail($user_email, $subject, $message, $message_headers);
657         return true;
658 }
659
660 function wpmu_signup_user_notification($user, $user_email, $key, $meta = '') {
661         if ( !apply_filters('wpmu_signup_user_notification', $user, $user_email, $key, $meta) )
662                 return false;
663
664         // Send email with activation link.
665         $admin_email = get_site_option( 'admin_email' );
666         if ( $admin_email == '' )
667                 $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
668         $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
669         $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
670         $message = sprintf( apply_filters( 'wpmu_signup_user_notification_email', __( "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" ) ), site_url( "wp-activate.php?key=$key" ), $key );
671         // TODO: Don't hard code activation link.
672         $subject = sprintf( __( apply_filters( 'wpmu_signup_user_notification_subject', '[%1s] Activate %2s' ) ), $from_name, $user);
673         wp_mail($user_email, $subject, $message, $message_headers);
674         return true;
675 }
676
677 function wpmu_activate_signup($key) {
678         global $wpdb, $current_site;
679
680         $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key) );
681
682         if ( empty($signup) )
683                 return new WP_Error('invalid_key', __('Invalid activation key.'));
684
685         if ( $signup->active )
686                 return new WP_Error('already_active', __('The site is already active.'), $signup);
687
688         $meta = unserialize($signup->meta);
689         $user_login = $wpdb->escape($signup->user_login);
690         $user_email = $wpdb->escape($signup->user_email);
691         $password = wp_generate_password();
692
693         $user_id = username_exists($user_login);
694
695         if ( ! $user_id )
696                 $user_id = wpmu_create_user($user_login, $password, $user_email);
697         else
698                 $user_already_exists = true;
699
700         if ( ! $user_id )
701                 return new WP_Error('create_user', __('Could not create user'), $signup);
702
703         $now = current_time('mysql', true);
704
705         if ( empty($signup->domain) ) {
706                 $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) );
707
708                 if ( isset( $user_already_exists ) )
709                         return new WP_Error( 'user_already_exists', __( 'That username is already activated.' ), $signup);
710
711                 wpmu_welcome_user_notification($user_id, $password, $meta);
712                 $user_site = get_site_option( 'dashboard_blog', $current_site->blog_id );
713
714                 if ( $user_site == false )
715                         add_user_to_blog( '1', $user_id, get_site_option( 'default_user_role', 'subscriber' ) );
716                 else
717                         add_user_to_blog( $user_site, $user_id, get_site_option( 'default_user_role', 'subscriber' ) );
718
719                 add_new_user_to_blog( $user_id, $user_email, $meta );
720                 do_action('wpmu_activate_user', $user_id, $password, $meta);
721                 return array('user_id' => $user_id, 'password' => $password, 'meta' => $meta);
722         }
723
724         $blog_id = wpmu_create_blog( $signup->domain, $signup->path, $signup->title, $user_id, $meta, $wpdb->siteid );
725
726         // TODO: What to do if we create a user but cannot create a blog?
727         if ( is_wp_error($blog_id) ) {
728                 // If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and
729                 // setting the activation flag.  Let's just set the active flag and instruct the user to reset their password.
730                 if ( 'blog_taken' == $blog_id->get_error_code() ) {
731                         $blog_id->add_data( $signup );
732                         $wpdb->update( $wpdb->signups, array( 'active' => 1, 'activated' => $now ), array( 'activation_key' => $key ) );
733                 }
734                 return $blog_id;
735         }
736
737         $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) );
738         wpmu_welcome_notification($blog_id, $user_id, $password, $signup->title, $meta);
739         do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta);
740
741         return array('blog_id' => $blog_id, 'user_id' => $user_id, 'password' => $password, 'title' => $signup->title, 'meta' => $meta);
742 }
743
744 function wpmu_create_user( $user_name, $password, $email) {
745         $user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
746
747         $user_id = wp_create_user( $user_name, $password, $email );
748         if ( is_wp_error($user_id) )
749                 return false;
750
751         // Newly created users have no roles or caps until they are added to a blog.
752         delete_user_option( $user_id, 'capabilities' );
753         delete_user_option( $user_id, 'user_level' );
754
755         do_action( 'wpmu_new_user', $user_id );
756
757         return $user_id;
758 }
759
760 function wpmu_create_blog($domain, $path, $title, $user_id, $meta = '', $site_id = 1) {
761         $domain = preg_replace( '/\s+/', '', sanitize_user( $domain, true ) );
762
763         if ( is_subdomain_install() )
764                 $domain = str_replace( '@', '', $domain );
765
766         $title = strip_tags( $title );
767         $user_id = (int) $user_id;
768
769         if ( empty($path) )
770                 $path = '/';
771
772         // Check if the domain has been used already. We should return an error message.
773         if ( domain_exists($domain, $path, $site_id) )
774                 return new WP_Error('blog_taken', __('Site already exists.'));
775
776         if ( !defined('WP_INSTALLING') )
777                 define( 'WP_INSTALLING', true );
778
779         if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
780                 return new WP_Error('insert_blog', __('Could not create site.'));
781
782         switch_to_blog($blog_id);
783         install_blog($blog_id, $title);
784         wp_install_defaults($user_id);
785
786         add_user_to_blog($blog_id, $user_id, 'administrator');
787
788         if ( is_array($meta) ) foreach ($meta as $key => $value) {
789                 if ( $key == 'public' || $key == 'archived' || $key == 'mature' || $key == 'spam' || $key == 'deleted' || $key == 'lang_id' )
790                         update_blog_status( $blog_id, $key, $value );
791                 else
792                         update_option( $key, $value );
793         }
794
795         add_option( 'WPLANG', get_site_option( 'WPLANG' ) );
796         update_option( 'blog_public', (int)$meta['public'] );
797
798         if ( !is_super_admin() && get_user_meta( $user_id, 'primary_blog', true ) == get_site_option( 'dashboard_blog', 1 ) )
799                 update_user_meta( $user_id, 'primary_blog', $blog_id );
800
801         restore_current_blog();
802         do_action( 'wpmu_new_blog', $blog_id, $user_id, $domain, $path, $site_id, $meta );
803
804         return $blog_id;
805 }
806
807 function newblog_notify_siteadmin( $blog_id, $deprecated = '' ) {
808         if ( get_site_option( 'registrationnotification' ) != 'yes' )
809                 return false;
810
811         $email = get_site_option( 'admin_email' );
812         if ( is_email($email) == false )
813                 return false;
814
815         $options_site_url = esc_url(network_admin_url('ms-options.php'));
816
817         switch_to_blog( $blog_id );
818         $blogname = get_option( 'blogname' );
819         $siteurl = site_url();
820         restore_current_blog();
821
822         $msg = sprintf( __( 'New Site: %1s
823 URL: %2s
824 Remote IP: %3s
825
826 Disable these notifications: %4s' ), $blogname, $siteurl, $_SERVER['REMOTE_ADDR'], $options_site_url);
827         $msg = apply_filters( 'newblog_notify_siteadmin', $msg );
828
829         wp_mail( $email, sprintf( __( 'New Site Registration: %s' ), $siteurl ), $msg );
830         return true;
831 }
832
833 function newuser_notify_siteadmin( $user_id ) {
834         if ( get_site_option( 'registrationnotification' ) != 'yes' )
835                 return false;
836
837         $email = get_site_option( 'admin_email' );
838
839         if ( is_email($email) == false )
840                 return false;
841
842         $user = new WP_User($user_id);
843
844         $options_site_url = esc_url(network_admin_url('ms-options.php'));
845         $msg = sprintf(__('New User: %1s
846 Remote IP: %2s
847
848 Disable these notifications: %3s'), $user->user_login, $_SERVER['REMOTE_ADDR'], $options_site_url);
849
850         $msg = apply_filters( 'newuser_notify_siteadmin', $msg );
851         wp_mail( $email, sprintf(__('New User Registration: %s'), $user->user_login), $msg );
852         return true;
853 }
854
855 function domain_exists($domain, $path, $site_id = 1) {
856         global $wpdb;
857         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) );
858 }
859
860 function insert_blog($domain, $path, $site_id) {
861         global $wpdb;
862
863         $path = trailingslashit($path);
864         $site_id = (int) $site_id;
865
866         $result = $wpdb->insert( $wpdb->blogs, array('site_id' => $site_id, 'domain' => $domain, 'path' => $path, 'registered' => current_time('mysql')) );
867         if ( ! $result )
868                 return false;
869
870         refresh_blog_details($wpdb->insert_id);
871         return $wpdb->insert_id;
872 }
873
874 // Install an empty blog.  wpdb should already be switched.
875 function install_blog($blog_id, $blog_title = '') {
876         global $wpdb, $table_prefix, $wp_roles;
877         $wpdb->suppress_errors();
878
879         // Cast for security
880         $blog_id = (int) $blog_id;
881
882         require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
883
884         if ( $wpdb->get_results("SELECT ID FROM $wpdb->posts") )
885                 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>');
886
887         $wpdb->suppress_errors(false);
888
889         $url = get_blogaddress_by_id($blog_id);
890
891         // Set everything up
892         make_db_current_silent();
893         populate_options();
894         populate_roles();
895         $wp_roles->_init();
896
897         // fix url.
898         update_option('siteurl', $url);
899         update_option('home', $url);
900         update_option('fileupload_url', $url . "files" );
901         update_option('upload_path', "wp-content/blogs.dir/" . $blog_id . "/files");
902         update_option('blogname', stripslashes( $blog_title ) );
903         update_option('admin_email', '');
904         $wpdb->update( $wpdb->options, array('option_value' => ''), array('option_name' => 'admin_email') );
905
906         // remove all perms
907         $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE meta_key = %s", $table_prefix.'user_level') );
908         $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE meta_key = %s", $table_prefix.'capabilities') );
909
910         $wpdb->suppress_errors( false );
911 }
912
913 // Deprecated, use wp_install_defaults()
914 // should be switched already as $blog_id is ignored.
915 function install_blog_defaults($blog_id, $user_id) {
916         global $wpdb;
917
918         require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
919
920         $wpdb->suppress_errors();
921
922         wp_install_defaults($user_id);
923
924         $wpdb->suppress_errors( false );
925 }
926
927 function wpmu_welcome_notification($blog_id, $user_id, $password, $title, $meta = '') {
928         global $current_site;
929
930         if ( !apply_filters('wpmu_welcome_notification', $blog_id, $user_id, $password, $title, $meta) )
931                 return false;
932
933         $welcome_email = stripslashes( get_site_option( 'welcome_email' ) );
934         if ( $welcome_email == false )
935                 $welcome_email = stripslashes( __( 'Dear User,
936
937 Your new SITE_NAME site has been successfully set up at:
938 BLOG_URL
939
940 You can log in to the administrator account with the following information:
941 Username: USERNAME
942 Password: PASSWORD
943 Login Here: BLOG_URLwp-login.php
944
945 We hope you enjoy your new site.
946 Thanks!
947
948 --The Team @ SITE_NAME' ) );
949
950         $url = get_blogaddress_by_id($blog_id);
951         $user = new WP_User($user_id);
952
953         $welcome_email = str_replace( 'SITE_NAME', $current_site->site_name, $welcome_email );
954         $welcome_email = str_replace( 'BLOG_TITLE', $title, $welcome_email );
955         $welcome_email = str_replace( 'BLOG_URL', $url, $welcome_email );
956         $welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email );
957         $welcome_email = str_replace( 'PASSWORD', $password, $welcome_email );
958
959         $welcome_email = apply_filters( 'update_welcome_email', $welcome_email, $blog_id, $user_id, $password, $title, $meta);
960         $admin_email = get_site_option( 'admin_email' );
961
962         if ( $admin_email == '' )
963                 $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
964
965         $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
966         $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
967         $message = $welcome_email;
968
969         if ( empty( $current_site->site_name ) )
970                 $current_site->site_name = 'WordPress MU';
971
972         $subject = apply_filters( 'update_welcome_subject', sprintf(__('New %1$s Site: %2$s'), $current_site->site_name, stripslashes( $title ) ) );
973         wp_mail($user->user_email, $subject, $message, $message_headers);
974         return true;
975 }
976
977 function wpmu_welcome_user_notification($user_id, $password, $meta = '') {
978         global $current_site;
979
980         if ( !apply_filters('wpmu_welcome_user_notification', $user_id, $password, $meta) )
981                 return false;
982
983         $welcome_email = get_site_option( 'welcome_user_email' );
984
985         $user = new WP_User($user_id);
986
987         $welcome_email = apply_filters( 'update_welcome_user_email', $welcome_email, $user_id, $password, $meta);
988         $welcome_email = str_replace( 'SITE_NAME', $current_site->site_name, $welcome_email );
989         $welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email );
990         $welcome_email = str_replace( 'PASSWORD', $password, $welcome_email );
991         $welcome_email = str_replace( 'LOGINLINK', wp_login_url(), $welcome_email );
992
993         $admin_email = get_site_option( 'admin_email' );
994
995         if ( $admin_email == '' )
996                 $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
997
998         $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
999         $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1000         $message = $welcome_email;
1001
1002         if ( empty( $current_site->site_name ) )
1003                 $current_site->site_name = 'WordPress MU';
1004
1005         $subject = apply_filters( 'update_welcome_user_subject', sprintf(__('New %1$s User: %2$s'), $current_site->site_name, $user->user_login) );
1006         wp_mail($user->user_email, $subject, $message, $message_headers);
1007         return true;
1008 }
1009
1010 function get_current_site() {
1011         global $current_site;
1012         return $current_site;
1013 }
1014
1015 function get_user_id_from_string( $string ) {
1016         $user_id = 0;
1017         if ( is_email( $string ) ) {
1018                 $user = get_user_by('email', $string);
1019                 if ( $user )
1020                         $user_id = $user->ID;
1021         } elseif ( is_numeric( $string ) ) {
1022                 $user_id = $string;
1023         } else {
1024                 $user = get_user_by('login', $string);
1025                 if ( $user )
1026                         $user_id = $user->ID;
1027         }
1028
1029         return $user_id;
1030 }
1031
1032 function get_most_recent_post_of_user( $user_id ) {
1033         global $wpdb;
1034
1035         $user_blogs = get_blogs_of_user( (int) $user_id );
1036         $most_recent_post = array();
1037
1038         // Walk through each blog and get the most recent post
1039         // published by $user_id
1040         foreach ( (array) $user_blogs as $blog ) {
1041                 $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);
1042
1043                 // Make sure we found a post
1044                 if ( isset($recent_post['ID']) ) {
1045                         $post_gmt_ts = strtotime($recent_post['post_date_gmt']);
1046
1047                         // If this is the first post checked or if this post is
1048                         // newer than the current recent post, make it the new
1049                         // most recent post.
1050                         if ( !isset($most_recent_post['post_gmt_ts']) || ( $post_gmt_ts > $most_recent_post['post_gmt_ts'] ) ) {
1051                                 $most_recent_post = array(
1052                                         'blog_id'               => $blog->userblog_id,
1053                                         'post_id'               => $recent_post['ID'],
1054                                         'post_date_gmt' => $recent_post['post_date_gmt'],
1055                                         'post_gmt_ts'   => $post_gmt_ts
1056                                 );
1057                         }
1058                 }
1059         }
1060
1061         return $most_recent_post;
1062 }
1063
1064 /* Misc functions */
1065 function get_dirsize( $directory ) {
1066         $dirsize = get_transient( 'dirsize_cache' );
1067         if ( is_array( $dirsize ) && isset( $dirsize[ $directory ][ 'size' ] ) )
1068                 return $dirsize[ $directory ][ 'size' ];
1069
1070         if ( false == is_array( $dirsize ) )
1071                 $dirsize = array();
1072
1073         $dirsize[ $directory ][ 'size' ] = recurse_dirsize( $directory );
1074
1075         set_transient( 'dirsize_cache', $dirsize, 3600 );
1076         return $dirsize[ $directory ][ 'size' ];
1077 }
1078
1079 function recurse_dirsize( $directory ) {
1080         $size = 0;
1081
1082         if ( substr( $directory, -1 ) == '/' )
1083                 $directory = substr($directory,0,-1);
1084
1085         if ( !file_exists($directory) || !is_dir( $directory ) || !is_readable( $directory ) )
1086                 return false;
1087
1088         if ($handle = opendir($directory)) {
1089                 while(($file = readdir($handle)) !== false) {
1090                         $path = $directory.'/'.$file;
1091                         if ($file != '.' && $file != '..') {
1092                                 if (is_file($path)) {
1093                                         $size += filesize($path);
1094                                 } elseif (is_dir($path)) {
1095                                         $handlesize = recurse_dirsize($path);
1096                                         if ($handlesize > 0)
1097                                                 $size += $handlesize;
1098                                 }
1099                         }
1100                 }
1101                 closedir($handle);
1102         }
1103         return $size;
1104 }
1105
1106 function upload_is_user_over_quota( $echo = true ) {
1107         if ( get_site_option( 'upload_space_check_disabled' ) )
1108                 return true;
1109
1110         $spaceAllowed = get_space_allowed();
1111         if ( empty( $spaceAllowed ) || !is_numeric( $spaceAllowed ) )
1112                 $spaceAllowed = 10;     // Default space allowed is 10 MB
1113
1114         $dirName = BLOGUPLOADDIR;
1115         $size = get_dirsize($dirName) / 1024 / 1024;
1116
1117         if ( ($spaceAllowed-$size) < 0 ) {
1118                 if ( $echo )
1119                         _e( 'Sorry, you have used your space allocation. Please delete some files to upload more files.' ); // No space left
1120                 return true;
1121         } else {
1122                 return false;
1123         }
1124 }
1125
1126 function check_upload_mimes( $mimes ) {
1127         $site_exts = explode( ' ', get_site_option( 'upload_filetypes' ) );
1128         foreach ( $site_exts as $ext ) {
1129                 foreach ( $mimes as $ext_pattern => $mime ) {
1130                         if ( $ext != '' && strpos( $ext_pattern, $ext ) !== false )
1131                                 $site_mimes[$ext_pattern] = $mime;
1132                 }
1133         }
1134         return $site_mimes;
1135 }
1136
1137 function update_posts_count( $deprecated = '' ) {
1138         global $wpdb;
1139         update_option( 'post_count', (int) $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_status = 'publish' and post_type = 'post'" ) );
1140 }
1141
1142 function wpmu_log_new_registrations( $blog_id, $user_id ) {
1143         global $wpdb;
1144         $user = new WP_User( (int) $user_id );
1145         $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')) );
1146 }
1147
1148 function fix_import_form_size( $size ) {
1149         if ( upload_is_user_over_quota( false ) == true )
1150                 return 0;
1151
1152         $spaceAllowed = 1024 * 1024 * get_space_allowed();
1153         $dirName = BLOGUPLOADDIR;
1154         $dirsize = get_dirsize($dirName) ;
1155         if ( $size > $spaceAllowed - $dirsize )
1156                 return $spaceAllowed - $dirsize; // remaining space
1157         else
1158                 return $size; // default
1159 }
1160
1161 /**
1162  * Maintains a canonical list of terms by syncing terms created for each blog with the global terms table.
1163  *
1164  * @since 3.0.0
1165  *
1166  * @see term_id_filter
1167  *
1168  * @param int $term_id An ID for a term on the current blog.
1169  * @return int An ID from the global terms table mapped from $term_id.
1170  */
1171 function global_terms( $term_id, $deprecated = '' ) {
1172         global $wpdb;
1173         static $global_terms_recurse = null;
1174
1175         if ( !global_terms_enabled() )
1176                 return $term_id;
1177
1178         // prevent a race condition
1179         $recurse_start = false;
1180         if ( $global_terms_recurse === null ) {
1181                 $recurse_start = true;
1182                 $global_terms_recurse = 1;
1183         } elseif ( 10 < $global_terms_recurse++ ) {
1184                 return $term_id;
1185         }
1186
1187         $term_id = intval( $term_id );
1188         $c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->terms WHERE term_id = %d", $term_id ) );
1189
1190         $global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE category_nicename = %s", $c->slug ) );
1191         if ( $global_id == null ) {
1192                 $used_global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE cat_ID = %d", $c->term_id ) );
1193                 if ( null == $used_global_id ) {
1194                         $wpdb->insert( $wpdb->sitecategories, array( 'cat_ID' => $term_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug ) );
1195                         $global_id = $wpdb->insert_id;
1196                         if ( empty( $global_id ) )
1197                                 return $term_id;
1198                 } else {
1199                         $max_global_id = $wpdb->get_var( "SELECT MAX(cat_ID) FROM $wpdb->sitecategories" );
1200                         $max_local_id = $wpdb->get_var( "SELECT MAX(term_id) FROM $wpdb->terms" );
1201                         $new_global_id = max( $max_global_id, $max_local_id ) + mt_rand( 100, 400 );
1202                         $wpdb->insert( $wpdb->sitecategories, array( 'cat_ID' => $new_global_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug ) );
1203                         $global_id = $wpdb->insert_id;
1204                 }
1205         } elseif ( $global_id != $term_id ) {
1206                 $local_id = $wpdb->get_row( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE term_id = %d", $global_id ) );
1207                 if ( null != $local_id )
1208                         $local_id = global_terms( $local_id );
1209                         if ( 10 < $global_terms_recurse )
1210                                 $global_id = $term_id;
1211         }
1212
1213         if ( $global_id != $term_id ) {
1214                 if ( get_option( 'default_category' ) == $term_id )
1215                         update_option( 'default_category', $global_id );
1216
1217                 $wpdb->update( $wpdb->terms, array('term_id' => $global_id), array('term_id' => $term_id) );
1218                 $wpdb->update( $wpdb->term_taxonomy, array('term_id' => $global_id), array('term_id' => $term_id) );
1219                 $wpdb->update( $wpdb->term_taxonomy, array('parent' => $global_id), array('parent' => $term_id) );
1220
1221                 clean_term_cache($term_id);
1222         }
1223         if( $recurse_start )
1224                 $global_terms_recurse = null;
1225
1226         return $global_id;
1227 }
1228
1229 function redirect_this_site( $deprecated = '' ) {
1230         global $current_site;
1231         return array( $current_site->domain );
1232 }
1233
1234 function upload_is_file_too_big( $upload ) {
1235         if ( is_array( $upload ) == false || defined( 'WP_IMPORTING' ) )
1236                 return $upload;
1237
1238         if ( strlen( $upload['bits'] )  > ( 1024 * get_site_option( 'fileupload_maxk', 1500 ) ) )
1239                 return sprintf( __( 'This file is too big. Files must be less than %d KB in size.' ) . '<br />', get_site_option( 'fileupload_maxk', 1500 ));
1240
1241         return $upload;
1242 }
1243
1244 function wordpressmu_wp_mail_from( $email ) {
1245         if ( strpos( $email, 'wordpress@' ) !== false )
1246                 $email = get_option( 'admin_email' );
1247         return $email;
1248 }
1249
1250 function signup_nonce_fields() {
1251         $id = mt_rand();
1252         echo "<input type='hidden' name='signup_form_id' value='{$id}' />";
1253         wp_nonce_field('signup_form_' . $id, '_signup_form', false);
1254 }
1255
1256 function signup_nonce_check( $result ) {
1257         if ( !strpos( $_SERVER[ 'PHP_SELF' ], 'wp-signup.php' ) )
1258                 return $result;
1259
1260         if ( wp_create_nonce('signup_form_' . $_POST[ 'signup_form_id' ]) != $_POST['_signup_form'] )
1261                 wp_die( __('Please try again!') );
1262
1263         return $result;
1264 }
1265
1266 function maybe_redirect_404() {
1267         global $current_site;
1268         if ( is_main_site() && is_404() && defined( 'NOBLOGREDIRECT' ) && ( $destination = apply_filters( 'blog_redirect_404', NOBLOGREDIRECT ) ) ) {
1269                 if ( $destination == '%siteurl%' )
1270                         $destination = network_home_url();
1271                 wp_redirect( $destination );
1272                 exit();
1273         }
1274 }
1275
1276 function maybe_add_existing_user_to_blog() {
1277         if ( false === strpos( $_SERVER[ 'REQUEST_URI' ], '/newbloguser/' ) )
1278                 return false;
1279
1280         $parts = explode( '/', $_SERVER[ 'REQUEST_URI' ] );
1281         $key = array_pop( $parts );
1282
1283         if ( $key == '' )
1284                 $key = array_pop( $parts );
1285
1286         $details = get_option( 'new_user_' . $key );
1287         if ( !empty( $details ) )
1288                 delete_option( 'new_user_' . $key );
1289
1290         if ( empty( $details ) || is_wp_error( add_existing_user_to_blog( $details ) ) )
1291                 wp_die( sprintf(__('An error occurred adding you to this site. Back to the <a href="%s">homepage</a>.'), site_url() ) );
1292
1293         wp_die( sprintf(__('You have been added to this site. Please visit the <a href="%s">homepage</a> or <a href="%s">login</a> using your username and password.'), site_url(), admin_url() ), __('Success') );
1294 }
1295
1296 function add_existing_user_to_blog( $details = false ) {
1297         if ( is_array( $details ) ) {
1298                 $result = add_user_to_blog( '', $details[ 'user_id' ], $details[ 'role' ] );
1299                 do_action( 'added_existing_user', $details[ 'user_id' ], $result );
1300         }
1301         return $result;
1302 }
1303
1304 function add_new_user_to_blog( $user_id, $email, $meta ) {
1305         global $current_site;
1306         if ( $meta[ 'add_to_blog' ] ) {
1307                 $blog_id = $meta[ 'add_to_blog' ];
1308                 $role = $meta[ 'new_role' ];
1309                 remove_user_from_blog($user_id, $current_site->blogid); // remove user from main blog.
1310                 add_user_to_blog( $blog_id, $user_id, $role );
1311                 update_user_meta( $user_id, 'primary_blog', $blog_id );
1312         }
1313 }
1314
1315 function fix_phpmailer_messageid( $phpmailer ) {
1316         global $current_site;
1317         $phpmailer->Hostname = $current_site->domain;
1318 }
1319
1320 function is_user_spammy( $username = 0 ) {
1321         if ( $username == 0 ) {
1322                 global $current_user;
1323                 $user_id = $current_user->ID;
1324         } else {
1325                 $user_id = get_user_id_from_string( $username );
1326         }
1327         $u = new WP_User( $user_id );
1328
1329         if ( $u->spam == 1 )
1330                 return true;
1331
1332         return false;
1333 }
1334
1335 function update_blog_public( $old_value, $value ) {
1336         global $wpdb;
1337         do_action('update_blog_public');
1338         update_blog_status( $wpdb->blogid, 'public', (int) $value );
1339 }
1340 add_action('update_option_blog_public', 'update_blog_public', 10, 2);
1341
1342 /* Redirect all hits to "dashboard" blog to wp-admin/ Dashboard. */
1343 function redirect_mu_dashboard() {
1344         global $current_site, $current_blog;
1345
1346         $dashboard_blog = get_dashboard_blog();
1347         if ( $current_blog->blog_id == $dashboard_blog->blog_id && $dashboard_blog->blog_id != $current_site->blog_id ) {
1348                 $protocol = ( is_ssl() ? 'https://' : 'http://' );
1349                 wp_redirect( $protocol . $dashboard_blog->domain . trailingslashit( $dashboard_blog->path ) . 'wp-admin/' );
1350                 die();
1351         }
1352 }
1353 add_action( 'template_redirect', 'redirect_mu_dashboard' );
1354
1355 function get_dashboard_blog() {
1356         if ( $blog = get_site_option( 'dashboard_blog' ) )
1357                 return get_blog_details( $blog );
1358
1359         return get_blog_details( $GLOBALS['current_site']->blog_id );
1360 }
1361
1362 function is_user_option_local( $key, $user_id = 0, $blog_id = 0 ) {
1363         global $current_user, $wpdb;
1364
1365         if ( $user_id == 0 )
1366                 $user_id = $current_user->ID;
1367         if ( $blog_id == 0 )
1368                 $blog_id = $wpdb->blogid;
1369
1370         $local_key = $wpdb->base_prefix . $blog_id . '_' . $key;
1371
1372         if ( isset( $current_user->$local_key ) )
1373                 return true;
1374
1375         return false;
1376 }
1377
1378 function users_can_register_signup_filter() {
1379         $registration = get_site_option('registration');
1380         if ( $registration == 'all' || $registration == 'user' )
1381                 return true;
1382
1383         return false;
1384 }
1385 add_filter('option_users_can_register', 'users_can_register_signup_filter');
1386
1387 function welcome_user_msg_filter( $text ) {
1388         if ( !$text ) {
1389                 return __( 'Dear User,
1390
1391 Your new account is set up.
1392
1393 You can log in with the following information:
1394 Username: USERNAME
1395 Password: PASSWORD
1396 LOGINLINK
1397
1398 Thanks!
1399
1400 --The Team @ SITE_NAME' );
1401         }
1402         return $text;
1403 }
1404 add_filter( 'site_option_welcome_user_email', 'welcome_user_msg_filter' );
1405
1406 /**
1407  * Whether to force SSL on content.
1408  *
1409  * @since 2.8.5
1410  *
1411  * @param string|bool $force
1412  * @return bool True if forced, false if not forced.
1413  */
1414 function force_ssl_content( $force = '' ) {
1415         static $forced_content;
1416
1417         if ( '' != $force ) {
1418                 $old_forced = $forced_content;
1419                 $forced_content = $force;
1420                 return $old_forced;
1421         }
1422
1423         return $forced_content;
1424 }
1425
1426 /**
1427  * Formats an String URL to use HTTPS if HTTP is found.
1428  * Useful as a filter.
1429  *
1430  * @since 2.8.5
1431  **/
1432 function filter_SSL( $url ) {
1433         if ( !is_string( $url ) )
1434                 return get_bloginfo( 'url' ); //return home blog url with proper scheme
1435
1436         $arrURL = parse_url( $url );
1437
1438         if ( force_ssl_content() && is_ssl() ) {
1439                 if ( 'http' === $arrURL['scheme'] && 'https' !== $arrURL['scheme'] )
1440                         $url = str_replace( $arrURL['scheme'], 'https', $url );
1441         }
1442
1443         return $url;
1444 }
1445
1446 ?>