root/tags/1.5-rc1/wp-includes/wpmu-functions.php

Revision 1246, 65.7 kB (checked in by donncha, 1 year ago)

Check that user isn't a site_admin before deleting their blog 1 perms, fixes #536

  • Property svn:eol-style set to native
Line 
1 <?php
2 /*
3     Helper functions for WPMU
4 */
5 function load_muplugin_textdomain($domain, $path = false) {
6     $locale = get_locale();
7     if ( empty($locale) )
8         $locale = 'en_US';
9
10     if ( false === $path )
11         $path = MUPLUGINDIR;
12
13     $mofile = ABSPATH . "$path/$domain-$locale.mo";
14     load_textdomain($domain, $mofile);
15 }
16
17 function wpmu_update_blogs_date() {
18     global $wpdb;
19
20     $wpdb->query( "UPDATE {$wpdb->blogs} SET last_updated = NOW() WHERE  blog_id = '{$wpdb->blogid}'" );
21     refresh_blog_details( $wpdb->blogid );
22
23     do_action( 'wpmu_blog_updated', $wpdb->blogid );
24 }
25
26 add_action('delete_post', 'wpmu_update_blogs_date');
27 add_action('private_to_published', 'wpmu_update_blogs_date');
28 add_action('publish_phone', 'wpmu_update_blogs_date');
29 add_action('publish_post', 'wpmu_update_blogs_date');
30
31 function get_blogaddress_by_id( $blog_id ) {
32     $bloginfo = get_blog_details( (int) $blog_id, false ); // only get bare details!
33     return clean_url("http://" . $bloginfo->domain . $bloginfo->path);
34 }
35
36 function get_blogaddress_by_name( $blogname ) {
37     global $hostname, $domain, $base;
38
39     if( defined( "VHOST" ) && constant( "VHOST" ) == 'yes' ) {
40         if( $blogname == 'main' )
41             $blogname = 'www';
42         return clean_url("http://".$blogname.".".$domain.$base);
43     } else {
44         return clean_url("http://".$hostname.$base.$blogname);
45     }
46 }
47
48 function get_blogaddress_by_domain( $domain, $path ){
49     if( defined( "VHOST" ) && constant( "VHOST" ) == 'yes' ) {
50         $url = "http://".$domain.$path;
51     } else {
52         if( $domain != $_SERVER['HTTP_HOST'] ) {
53             $blogname = substr( $domain, 0, strpos( $domain, '.' ) );
54             if( $blogname != 'www.' ) {
55                 $url = 'http://' . substr( $domain, strpos( $domain, '.' ) + 1 ) . $path . $blogname . '/';
56             } else { // we're installing the main blog
57                 $url = 'http://' . substr( $domain, strpos( $domain, '.' ) + 1 ) . $path;
58             }
59         } else { // main blog
60             $url = 'http://' . $domain . $path;
61         }
62     }
63     return clean_url($url);
64 }
65
66 function get_sitestats() {
67     global $wpdb;
68
69     $stats['blogs'] = get_blog_count();
70
71     $count_ts = get_site_option( "get_user_count_ts" );
72     if( time() - $count_ts > 3600 ) {
73         $count = $wpdb->get_var( "SELECT count(*) as c FROM {$wpdb->users}" );
74         update_site_option( "user_count", $count );
75         update_site_option( "user_count_ts", time() );
76     } else {
77         $count = get_site_option( "user_count" );
78     }
79     $stats['users'] = $count;
80     return $stats;
81 }
82
83 function get_admin_users_for_domain( $sitedomain = '', $path = '' ) {
84     global $wpdb;
85     if( $sitedomain == '' ) {
86         $site_id = $wpdb->siteid;
87     } else {
88         $site_id = $wpdb->get_var( "SELECT id FROM ".$wpdb->site." WHERE domain = '".$sitedomain."' AND path = '".$path."'" );
89     }
90     if( $site_id != false ) {
91         $details = $wpdb->get_results( "SELECT ID, user_login, user_pass FROM ".$wpdb->users.", ".$wpdb->sitemeta." WHERE meta_key = 'admin_user_id' AND ".$wpdb->users.".ID = ".$wpdb->sitemeta.".meta_value AND ".$wpdb->sitemeta.".site_id = '".$site_id."'", ARRAY_A );
92     } else {
93         $details = false;
94     }
95     return $details;
96 }
97
98 function get_user_details( $username ) {
99     global $wpdb;
100     return $wpdb->get_row( "SELECT * FROM $wpdb->users WHERE user_login = '$username'" );
101 }
102
103 function get_blog_details( $id, $getall = true ) {
104     global $wpdb;
105
106     $all = $getall == true ? '' : 'short';
107     $details = wp_cache_get( $id . $all, 'blog-details' );
108
109     if ( $details ) {
110         if ( $details == -1 )
111             return false;
112         elseif ( !is_object($details) ) // Clear old pre-serialized objects. Cache clients do better with that.
113             wp_cache_delete( $id . $all, 'blog-details' );
114         else
115             return $details;
116     }
117
118     $details = $wpdb->get_row( "SELECT * FROM $wpdb->blogs WHERE blog_id = '$id' /* get_blog_details */" );
119
120     if ( !$details ) {
121         wp_cache_set( $id . $all, -1, 'blog-details' );
122         return false;
123     }
124
125     if ( !$getall ) {
126         wp_cache_add( $id . $all, $details, 'blog-details' );
127         return $details;
128     }
129
130     $wpdb->hide_errors();
131     $details->blogname   = get_blog_option($id, 'blogname');
132     $details->siteurl    = get_blog_option($id, 'siteurl');
133     $details->post_count = get_blog_option($id, 'post_count');
134     $wpdb->show_errors();
135
136     $details = apply_filters('blog_details', $details);
137
138     wp_cache_set( $id . $all, $details, 'blog-details' );
139
140     $key = md5( $details->domain . $details->path );
141     wp_cache_set( $key, $details, 'blog-lookup' );
142
143     return $details;
144 }
145
146 function refresh_blog_details( $id ) {
147     $id = (int) $id;
148     $details = get_blog_details( $id, false );
149     
150     wp_cache_delete( $id , 'blog-details' );
151     wp_cache_delete( md5( $details->domain . $details->path )  , 'blog-lookup' );
152 }
153
154 function get_current_user_id() {
155     global $current_user;
156     return $current_user->ID;
157 }
158
159 function is_site_admin( $user_login = false ) {
160     global $current_user;
161
162     if ( !$current_user && !$user_login )
163         return false;
164
165     if ( $user_login )
166         $user_login = sanitize_user( $user_login );
167     else
168         $user_login = $current_user->user_login;
169
170     $site_admins = get_site_option( 'site_admins', array('admin') );
171     if( is_array( $site_admins ) && in_array( $user_login, $site_admins ) )
172         return true;
173
174     return false;
175 }
176
177 // expects key not to be SQL escaped
178 function get_site_option( $key, $default = false, $use_cache = true ) {
179     global $wpdb;
180
181     $safe_key = $wpdb->escape( $key );
182
183     if( $use_cache == true ) {
184         $value = wp_cache_get($wpdb->siteid . $key, 'site-options');
185     } else {
186         $value = false;
187     }
188
189     if ( false === $value ) {
190         $value = $wpdb->get_var("SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = '$safe_key' AND site_id = '{$wpdb->siteid}'");
191         if ( ! is_null($value) ) {
192             wp_cache_add($wpdb->siteid . $key, $value, 'site-options');
193         } elseif ( $default ) {
194             wp_cache_add($wpdb->siteid . $key, addslashes( $default ), 'site-options');
195             return $default;
196         } else {
197             wp_cache_add($wpdb->siteid . $key, false, 'site-options');
198             return false;
199         }
200     }
201
202     $value = stripslashes( $value );
203     @ $kellogs = unserialize($value);
204     if ( $kellogs !== FALSE )
205         return $kellogs;
206     else
207         return $value;
208 }
209
210 // expects $key, $value not to be SQL escaped
211 function add_site_option( $key, $value ) {
212     global $wpdb;
213
214     $safe_key = $wpdb->escape( $key );
215
216     $exists = $wpdb->get_row("SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = '$safe_key' AND site_id = '{$wpdb->siteid}'");
217     if ( is_object( $exists ) ) {// If we already have it
218         update_site_option( $key, $value );
219         return false;
220     }
221
222     if ( is_array($value) || is_object($value) )
223         $value = serialize($value);
224     wp_cache_delete($wpdb->siteid . $key, 'site-options');
225     $wpdb->query( "INSERT INTO $wpdb->sitemeta ( site_id , meta_key , meta_value ) VALUES ( '{$wpdb->siteid}', '$safe_key', '" . $wpdb->escape( $value ) . "')" );
226     return $wpdb->insert_id;
227 }
228
229 // expects $key, $value not to be SQL escaped
230 function update_site_option( $key, $value ) {
231     global $wpdb;
232
233     $safe_key = $wpdb->escape( $key );
234
235     if ( $value == get_site_option( $key ) )
236          return;
237
238     $exists = $wpdb->get_row("SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = '$safe_key' AND site_id = '{$wpdb->siteid}'");
239
240     if ( false == is_object( $exists ) ) // It's a new record
241         return add_site_option( $key, $value );
242
243     if ( is_array($value) || is_object($value) )
244         $value = serialize($value);
245
246     $wpdb->query( "UPDATE $wpdb->sitemeta SET meta_value = '" . $wpdb->escape( $value ) . "' WHERE site_id='{$wpdb->siteid}' AND meta_key = '$safe_key'" );
247     wp_cache_delete( $wpdb->siteid . $key, 'site-options' );
248 }
249
250 /*
251 function get_blog_option( $id, $key, $default='na' ) {
252     switch_to_blog($id);
253     $opt = get_option( $key );
254     restore_current_blog();
255
256     return $opt;
257 }
258 */
259
260 function get_blog_option( $blog_id, $setting, $default='na' ) {
261     global $wpdb;
262
263     $key = $blog_id."-".$setting."-blog_option";
264     $value = wp_cache_get( $key, "site-options" );
265     if( $value == null ) {
266         $row = $wpdb->get_row( "SELECT * FROM {$wpdb->base_prefix}{$blog_id}_options WHERE option_name = '{$setting}'" );
267         if( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
268             $value = $row->option_value;
269             if( $value == false ) {
270                 wp_cache_set($key, 'falsevalue', 'site-options');
271                 return false;
272             } else {
273                 wp_cache_set($key, $value, 'site-options');
274             }
275         } else { // option does not exist, so we must cache its non-existence
276             wp_cache_set($key, 'noop', 'site-options');
277         }
278     } elseif( $value == 'noop' ) {
279         return false;
280     } elseif( $value == 'falsevalue' ) {
281         return false;
282     }
283     // If home is not set use siteurl.
284     if ( 'home' == $setting && '' == $value )
285         return get_blog_option($blog_id, 'siteurl');
286
287     if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
288         $value = preg_replace('|/+$|', '', $value);
289
290     if (! unserialize($value) )
291         $value = stripslashes( $value );
292
293     return apply_filters( 'option_' . $setting, maybe_unserialize($value) );
294 }
295
296 function add_blog_option( $id, $key, $value ) {
297     switch_to_blog($id);
298     add_option( $key, $value );
299     restore_current_blog();
300     $opt = $id."-".$key."-blog_option";
301     wp_cache_set($opt, $value, 'site-options');
302 }
303
304 function delete_blog_option( $id, $key ) {
305     switch_to_blog($id);
306     delete_option( $key );
307     restore_current_blog();
308     $opt = $id."-".$key."-blog_option";
309     wp_cache_set($opt, '', 'site-options');
310 }
311
312 function update_blog_option( $id, $key, $value, $refresh = true ) {
313     switch_to_blog($id);
314     $opt = update_option( $key, $value );
315     restore_current_blog();
316     if( $refresh == true )
317         refresh_blog_details( $id );
318     $opt = $id."-".$key."-blog_option";
319     wp_cache_set($opt, $value, 'site-options');
320 }
321
322 function switch_to_blog( $new_blog ) {
323     global $tmpoldblogdetails, $wpdb, $table_prefix, $blog_id, $switched, $switched_stack, $wp_roles, $current_user;
324
325     if ( empty($new_blog) )
326         $new_blog = $blog_id;
327
328     if ( empty($switched_stack) )
329         $switched_stack = array();
330
331     $switched_stack[] = $blog_id;
332
333     // backup
334     $tmpoldblogdetails['blogid']         = $wpdb->blogid;
335     $tmpoldblogdetails['posts']          = $wpdb->posts;
336     $tmpoldblogdetails['categories']     = $wpdb->categories;
337     $tmpoldblogdetails['post2cat']       = $wpdb->post2cat;
338     $tmpoldblogdetails['comments']       = $wpdb->comments;
339     $tmpoldblogdetails['links']          = $wpdb->links;
340     $tmpoldblogdetails['link2cat']       = $wpdb->link2cat;
341     $tmpoldblogdetails['linkcategories'] = $wpdb->linkcategories;
342     $tmpoldblogdetails['options']        = $wpdb->options;
343     $tmpoldblogdetails['postmeta']       = $wpdb->postmeta;
344     $tmpoldblogdetails['terms']          = $wpdb->terms;
345     $tmpoldblogdetails['term_taxonomy']  = $wpdb->term_taxonomy;
346     $tmpoldblogdetails['term_relationships'] = $wpdb->term_relationships;
347     $tmpoldblogdetails['prefix']         = $wpdb->prefix;
348     $tmpoldblogdetails['table_prefix']   = $table_prefix;
349     $tmpoldblogdetails['blog_id']        = $blog_id;
350
351     // fix the new prefix.
352     $table_prefix = $wpdb->base_prefix . $new_blog . "_";
353     $wpdb->prefix            = $table_prefix;
354     $wpdb->blogid           = $new_blog;
355     $wpdb->posts            = $table_prefix . 'posts';
356     $wpdb->categories       = $table_prefix . 'categories';
357     $wpdb->post2cat         = $table_prefix . 'post2cat';
358     $wpdb->comments         = $table_prefix . 'comments';
359     $wpdb->links            = $table_prefix . 'links';
360     $wpdb->link2cat         = $table_prefix . 'link2cat';
361     $wpdb->linkcategories   = $table_prefix . 'linkcategories';
362     $wpdb->options          = $table_prefix . 'options';
363     $wpdb->postmeta         = $table_prefix . 'postmeta';
364     $wpdb->terms            = $table_prefix . 'terms';
365     $wpdb->term_taxonomy    = $table_prefix . 'term_taxonomy';
366     $wpdb->term_relationships = $table_prefix . 'term_relationships';
367     $blog_id = $new_blog;
368
369     if( is_object( $wp_roles ) ) {
370         $wpdb->hide_errors();
371         $wp_roles->_init();
372         $wpdb->show_errors();
373     }
374     if ( is_object( $current_user ) ) {
375         $current_user->_init_caps();
376     }
377
378     do_action('switch_blog', $blog_id, $tmpoldblogdetails['blog_id']);
379     $switched = true;
380 }
381
382 function restore_current_blog() {
383     global $table_prefix, $tmpoldblogdetails, $wpdb, $blog_id, $switched, $switched_stack, $wp_roles, $current_user;
384
385     if ( !$switched )
386         return;
387
388     $blog = array_pop($switched_stack);
389
390     if ( $blog_id == $blog )
391         return;
392
393     // backup
394     $wpdb->blogid = $tmpoldblogdetails['blogid'];
395     $wpdb->posts = $tmpoldblogdetails['posts'];
396     $wpdb->categories = $tmpoldblogdetails['categories'];
397     $wpdb->post2cat = $tmpoldblogdetails['post2cat'];
398     $wpdb->comments = $tmpoldblogdetails['comments'];
399     $wpdb->links = $tmpoldblogdetails['links'];
400     $wpdb->link2cat = $tmpoldblogdetails['link2cat'];
401     $wpdb->linkcategories = $tmpoldblogdetails['linkcategories'];
402     $wpdb->options = $tmpoldblogdetails['options'];
403     $wpdb->postmeta = $tmpoldblogdetails['postmeta'];
404     $wpdb->terms = $tmpoldblogdetails['terms'];
405     $wpdb->term_taxonomy = $tmpoldblogdetails['term_taxonomy'];
406     $wpdb->term_relationships = $tmpoldblogdetails['term_relationships'];
407     $wpdb->prefix = $tmpoldblogdetails['prefix'];
408     $table_prefix = $tmpoldblogdetails['table_prefix'];
409     $prev_blog_id = $blog_id;
410     $blog_id = $tmpoldblogdetails['blog_id'];
411     unset( $tmpoldblogdetails );
412
413     if( is_object( $wp_roles ) ) {
414         $wpdb->hide_errors();
415         $wp_roles->_init();
416         $wpdb->show_errors();
417     }
418     if ( is_object( $current_user ) ) {
419         $current_user->_init_caps();
420     }
421     do_action('switch_blog', $blog_id, $prev_blog_id);
422
423     $switched = false;
424 }
425
426 function get_blogs_of_user( $id, $all = false ) {
427     global $wpdb;
428
429     $user = get_userdata( $id );
430     if ( !$user )
431         return false;
432
433     $blogs = array();
434
435     $i = 0;
436     foreach ( (array) $user as $key => $value ) {
437         if ( strstr( $key, '_capabilities') && strstr( $key, 'wp_') ) {
438             preg_match('/' . $wpdb->base_prefix . '(\d+)_capabilities/', $key, $match);
439             $blog = get_blog_details( $match[1] );
440             if ( $blog && isset( $blog->domain ) && ( $all == true || $all == false && ( $blog->archived == 0 && $blog->spam == 0 && $blog->deleted == 0 ) ) ) {
441                 $blogs[$match[1]]->userblog_id = $match[1];
442                 $blogs[$match[1]]->blogname    = $blog->blogname;
443                 $blogs[$match[1]]->domain      = $blog->domain;
444                 $blogs[$match[1]]->path        = $blog->path;
445                 $blogs[$match[1]]->site_id     = $blog->site_id;
446                 $blogs[$match[1]]->siteurl     = $blog->siteurl;
447             }
448         }
449     }
450
451     return $blogs;
452 }
453
454 function get_active_blog_for_user( $user_id ) { // get an active blog for user - either primary blog or from blogs list
455     $primary_blog = get_usermeta( $user_id, "primary_blog" );
456     if( $primary_blog == false ) {
457         $details = false;
458     } else {
459         $details = get_blog_details( $primary_blog );
460     }
461
462     if( ( is_object( $details ) == false ) || ( is_object( $details ) && $details->archived == 1 || $details->spam == 1 || $details->deleted == 1 ) ) {
463         $blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs.
464         $ret = false;
465         if( is_array( $blogs ) && count( $blogs ) > 0 ) {
466             foreach( (array) $blogs as $blog_id => $blog ) {
467                 $details = get_blog_details( $blog_id );
468                 if( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) {
469                     $ret = $blog;
470                     break;
471                 }
472             }
473         } else {
474             $ret = "username only"; // user has no blogs. We can add details for dashboard.wordpress.com here.
475         }
476         return $ret;
477     } else {
478         return $details;
479     }
480 }
481
482 function is_user_member_of_blog( $user_id, $blog_id = 0 ) {
483     global $wpdb;
484     if( $blog_id == 0 )
485         $blog_id = $wpdb->blogid;
486
487     $blogs = get_blogs_of_user( $user_id );
488     if( is_array( $blogs ) ) {
489         return array_key_exists( $blog_id, $blogs );
490     } else {
491         return false;
492     }
493 }
494
495 function is_archived( $id ) {
496     return get_blog_status($id, 'archived');
497 }
498
499 function update_archived( $id, $archived ) {
500     update_blog_status($id, 'archived', $archived);
501     return $archived;
502 }
503
504 function update_blog_status( $id, $pref, $value, $refresh = 1 ) {
505     global $wpdb;
506
507     $wpdb->query( "UPDATE {$wpdb->blogs} SET {$pref} = '{$value}', last_updated = NOW() WHERE blog_id = '$id'" );
508
509     if( $refresh == 1 )
510         refresh_blog_details($id);
511
512     if( $pref == 'spam' ) {
513         if( $value == 1 ) {
514             do_action( "make_spam_blog", $id );
515         } else {
516             do_action( "make_ham_blog", $id );
517         }
518     }
519
520     return $value;
521 }
522
523 function get_blog_status( $id, $pref ) {
524     global $wpdb;
525
526     $details = get_blog_details( $id, false );
527     if( $details ) {
528         return $details->$pref;
529     }
530     return $wpdb->get_var( "SELECT $pref FROM {$wpdb->blogs} WHERE blog_id = '$id'" );
531 }
532
533 function get_last_updated( $display = false ) {
534     global $wpdb;
535     return $wpdb->get_results( "SELECT blog_id, domain, path FROM $wpdb->blogs WHERE site_id = '$wpdb->siteid' AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0' AND last_updated != '0000-00-00 00:00:00' ORDER BY last_updated DESC limit 0,40", ARRAY_A );
536 }
537
538 function get_most_active_blogs( $num = 10, $display = true ) {
539     global $wpdb;
540     $most_active = get_site_option( "most_active" );
541     $update = false;
542     if( is_array( $most_active ) ) {
543         if( ( $most_active['time'] + 60 ) < time() ) { // cache for 60 seconds.
544             $update = true;
545         }
546     } else {
547         $update = true;
548     }
549
550     if( $update == true ) {
551         unset( $most_active );
552         $blogs = get_blog_list( 0, 'all', false ); // $blog_id -> $details
553         if( is_array( $blogs ) ) {
554             reset( $blogs );
555             foreach ( (array) $blogs as $key => $details ) {
556                 $most_active[ $details['blog_id'] ] = $details['postcount'];
557                 $blog_list[ $details['blog_id'] ] = $details; // array_slice() removes keys!!
558             }
559             arsort( $most_active );
560             reset( $most_active );
561             foreach ( (array) $most_active as $key => $details ) {
562                 $t[ $key ] = $blog_list[ $key ];
563             }
564             unset( $most_active );
565             $most_active = $t;
566         }
567         update_site_option( "most_active", $most_active );
568     }
569
570     if( $display == true ) {
571         if( is_array( $most_active ) ) {
572             reset( $most_active );
573             foreach ( (array) $most_active as $key => $details ) {
574                 $url = clean_url("http://" . $details['domain'] . $details['path']);
575                 echo "<li>" . $details['postcount'] . " <a href='$url'>$url</a></li>";
576             }
577         }
578     }
579     return array_slice( $most_active, 0, $num );
580 }
581
582 function get_blog_list( $start = 0, $num = 10, $display = true ) {
583     global $wpdb;
584
585     $blogs = get_site_option( "blog_list" );
586     $update = false;
587     if( is_array( $blogs ) ) {
588         if( ( $blogs['time'] + 60 ) < time() ) { // cache for 60 seconds.
589             $update = true;
590         }
591     } else {
592         $update = true;
593     }
594
595     if( $update == true ) {
596         unset( $blogs );
597         $blogs = $wpdb->get_results( "SELECT blog_id, domain, path FROM $wpdb->blogs WHERE site_id = '$wpdb->siteid' AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0' ORDER BY registered DESC", ARRAY_A );
598
599         foreach ( (array) $blogs as $key => $details ) {
600             $blog_list[ $details['blog_id'] ] = $details;
601             $blog_list[ $details['blog_id'] ]['postcount'] = $wpdb->get_var( "SELECT count(*) FROM " . $wpdb->base_prefix . $details['blog_id'] . "_posts WHERE post_status='publish' AND post_type='post'" );
602         }
603         unset( $blogs );
604         $blogs = $blog_list;
605         update_site_option( "blog_list", $blogs );
606     }
607
608     if( $num == 'all' ) {
609         return array_slice( $blogs, $start, count( $blogs ) );
610     } else {
611         return array_slice( $blogs, $start, $num );
612     }
613 }
614
615 function get_blog_count( $id = 0 ) {
616     global $wpdb;
617
618     if( $id == 0 )
619         $id = $wpdb->siteid;
620
621     $count_ts = get_site_option( "blog_count_ts" );
622     if( time() - $count_ts > 3600 ) {
623         $count = $wpdb->get_var( "SELECT count(*) as c FROM $wpdb->blogs WHERE site_id = '$id' AND spam='0' AND deleted='0' and archived='0'" );
624         update_site_option( "blog_count", $count );
625         update_site_option( "blog_count_ts", time() );
626     }
627
628     $count = get_site_option( "blog_count" );
629
630     return $count;
631 }
632
633 function get_blog_post( $blog_id, $post_id ) {
634     global $wpdb;
635
636     $key = $blog_id."-".$post_id."-blog_post";
637     $post = wp_cache_get( $key, "site-options" );
638     if( $post == false ) {
639         $post = $wpdb->get_row( "SELECT * FROM {$wpdb->base_prefix}{$blog_id}_posts WHERE ID = '{$post_id}'" );
640         wp_cache_add( $key, $post, "site-options", 120 );
641     }
642
643     return $post;
644
645 }
646
647 function add_user_to_blog( $blog_id, $user_id, $role ) {
648     switch_to_blog($blog_id);
649
650     $user = new WP_User($user_id);
651
652     if ( empty($user) )
653         return new WP_Error('user_does_not_exist', __('That user does not exist.'));
654
655     if ( !get_usermeta($user_id, 'primary_blog') ) {
656         update_usermeta($user_id, 'primary_blog', $blog_id);
657         $details = get_blog_details($blog_id);
658         update_usermeta($user_id, 'source_domain', $details->domain);
659     }
660
661     $user->set_role($role);
662
663     do_action('add_user_to_blog', $user_id, $role, $blog_id);
664     wp_cache_delete( $user_id, 'users' );
665     restore_current_blog();
666 }
667
668 function remove_user_from_blog($user_id, $blog_id = '') {
669     global $wpdb;
670
671     switch_to_blog($blog_id);
672
673     $user_id = (int) $user_id;
674
675     do_action('remove_user_from_blog', $user_id, $blog_id);
676
677     // If being removed from the primary blog, set a new primary if the user is assigned
678     // to multiple blogs.
679     $primary_blog = get_usermeta($user_id, 'primary_blog');
680     if ( $primary_blog == $blog_id ) {
681         $new_id = '';
682         $new_domain = '';
683         $blogs = get_blogs_of_user($user_id);
684         foreach ( (array) $blogs as $blog ) {
685             if ( $blog->userblog_id == $blog_id )
686                 continue;
687             $new_id = $blog->userblog_id;
688             $new_domain = $blog->domain;
689             break;
690         }
691
692         update_usermeta($user_id, 'primary_blog', $new_id);
693         update_usermeta($user_id, 'source_domain', $new_domain);
694     }
695
696     wp_revoke_user($user_id);
697
698     $blogs = get_blogs_of_user($user_id);
699     if ( count($blogs) == 0 ) {
700         update_usermeta($user_id, 'primary_blog', '');
701         update_usermeta($user_id, 'source_domain', '');
702     }
703
704     restore_current_blog();
705 }
706
707 function create_empty_blog( $domain, $path, $weblog_title, $site_id = 1 ) {
708     global $wpdb;
709
710     $domain       = addslashes( $domain );
711     $weblog_title = addslashes( $weblog_title );
712
713     if( empty($path) )
714         $path = '/';
715
716     // Check if the domain has been used already. We should return an error message.
717     if ( domain_exists($domain, $path, $site_id) )
718         return __('error: Blog URL already taken.');
719
720     // Need to backup wpdb table names, and create a new wp_blogs entry for new blog.
721     // Need to get blog_id from wp_blogs, and create new table names.
722     // Must restore table names at the end of function.
723
724     if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
725         return __('error: problem creating blog entry');
726
727     switch_to_blog($blog_id);
728     install_blog($blog_id);
729     restore_current_blog();
730
731     return $blog_id;
732 }
733
734 function get_blog_permalink( $blog_id, $post_id ) {
735     $key = "{$blog_id}-{$post_id}-blog_permalink";
736     $link = wp_cache_get( $key, 'site-options' );
737     if( $link == false ) {
738         switch_to_blog( $blog_id );
739         $link = get_permalink( $post_id );
740         restore_current_blog();
741         wp_cache_add( $key, $link, "site-options", 30 );
742     }
743     return $link;
744 }
745
746 // wpmu admin functions
747
748 function wpmu_admin_do_redirect( $url = '' ) {
749     $ref = '';
750     if ( isset( $_GET['ref'] ) )
751         $ref = $_GET['ref'];
752     if ( isset( $_POST['ref'] ) )
753         $ref = $_POST['ref'];
754     
755     if( $ref ) {
756         $ref = wpmu_admin_redirect_add_updated_param( $ref );
757         wp_redirect( $ref );
758         die();
759     }
760     if( empty( $_SERVER['HTTP_REFERER'] ) == false ) {
761         wp_redirect( $_SERVER['HTTP_REFERER'] );
762         die();
763     }
764
765     $url = wpmu_admin_redirect_add_updated_param( $url );
766     if( isset( $_GET['redirect'] ) ) {
767         if( substr( $_GET['redirect'], 0, 2 ) == 's_' ) {
768             $url .= "&action=blogs&s=". wp_specialchars( substr( $_GET['redirect'], 2 ) );
769         }
770     } elseif( isset( $_POST['redirect'] ) ) {
771         $url = wpmu_admin_redirect_add_updated_param( $_POST['redirect'] );
772     }
773     wp_redirect( $url );
774     die();
775 }
776
777 function wpmu_admin_redirect_add_updated_param( $url = '' ) {
778     if( strpos( $url, 'updated=true' ) === false ) {
779         if( strpos( $url, '?' ) === false ) {
780             return $url . '?updated=true';
781         } else {
782             return $url . '&updated=true';
783         }
784     }
785     return $url;
786 }
787
788 function wpmu_admin_redirect_url() {
789     if( isset( $_GET['s'] ) ) {
790         return "s_".$_GET['s'];
791     }
792 }
793
794 function is_blog_user( $blog_id = 0 ) {
795     global $current_user, $wpdb;
796
797     if ( !$blog_id )
798         $blog_id = $wpdb->blogid;
799
800     $cap_key = $wpdb->base_prefix . $blog_id . '_capabilities';
801
802     if ( is_array($current_user->$cap_key) && in_array(1, $current_user->$cap_key) )
803         return true;
804
805     return false;
806 }
807
808 function validate_email( $email, $check_domain = true) {
809     if (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.'@'.
810         '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
811         '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $email))
812     {
813         if ($check_domain && function_exists('checkdnsrr')) {
814             list (, $domain)  = explode('@', $email);
815
816             if (checkdnsrr($domain.'.', 'MX') || checkdnsrr($domain.'.', 'A')) {
817                 return true;
818             }
819             return false;
820         }
821         return true;
822     }
823     return false;
824 }
825
826 function is_email_address_unsafe( $user_email ) {
827     $banned_names = get_site_option( "banned_email_domains" );
828     if ( is_array( $banned_names ) && empty( $banned_names ) == false ) {
829         $email_domain = strtolower( substr( $user_email, 1 + strpos( $user_email, '@' ) ) );
830         foreach( (array) $banned_names as $banned_domain ) {
831             if( $banned_domain == '' )
832                 continue;
833             if (
834                 strstr( $email_domain, $banned_domain ) ||
835                 (
836                     strstr( $banned_domain, '/' ) &&
837                     preg_match( $banned_domain, $email_domain )
838                 )
839             )
840             return true;
841         }
842     }
843     return false;
844 }
845
846 function wpmu_validate_user_signup($user_name, $user_email) {
847     global $wpdb, $current_site;
848
849     $errors = new WP_Error();
850
851     $user_name = sanitize_user($user_name);
852     $user_email = sanitize_email( $user_email );
853
854     if ( empty( $user_name ) )
855            $errors->add('user_name', __("Please enter a username"));
856
857     preg_match( "/[a-z0-9]+/", $user_name, $maybe );
858
859     if( $user_name != $maybe[0] ) {
860         $errors->add('user_name', __("Only lowercase letters and numbers allowed"));
861     }
862
863     $illegal_names = get_site_option( "illegal_names" );
864     if( is_array( $illegal_names ) == false ) {
865         $illegal_names = array(  "www", "web", "root", "admin", "main", "invite", "administrator" );
866         add_site_option( "illegal_names", $illegal_names );
867     }
868     if( in_array( $user_name, $illegal_names ) == true ) {
869         $errors->add('user_name'__("That username is not allowed"));
870     }
871
872     if( is_email_address_unsafe( $user_email ) )
873         $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."));
874
875     if( strlen( $user_name ) < 4 ) {
876         $errors->add('user_name'__("Username must be at least 4 characters"));
877     }
878
879     if ( strpos( " " . $user_name, "_" ) != false )
880         $errors->add('user_name', __("Sorry, usernames may not contain the character '_'!"));
881
882     // all numeric?
883     preg_match( '/[0-9]*/', $user_name, $match );
884     if ( $match[0] == $user_name )
885         $errors->add('user_name', __("Sorry, usernames must have letters too!"));
886
887     if ( !is_email( $user_email ) )
888         $errors->add('user_email', __("Please enter a correct email address"));
889
890     if ( !validate_email( $user_email ) )
891         $errors->add('user_email', __("Please check your email address."));
892
893     $limited_email_domains = get_site_option( 'limited_email_domains' );
894     if ( is_array( $limited_email_domains ) && empty( $limited_email_domains ) == false ) {
895         $emaildomain = substr( $user_email, 1 + strpos( $user_email, '@' ) );
896         if( in_array( $emaildomain, $limited_email_domains ) == false ) {
897             $errors->add('user_email', __("Sorry, that email address is not allowed!"));
898         }
899     }
900
901     // Check if the username has been used already.
902     if ( username_exists($user_name) )
903         $errors->add('user_name', __("Sorry, that username already exists!"));
904
905     // Check if the email address has been used already.
906     if ( email_exists($user_email) )
907         $errors->add('user_email', __("Sorry, that email address is already used!"));
908
909     // Has someone already signed up for this username?
910     $signup = $wpdb->get_row("SELECT * FROM $wpdb->signups WHERE user_login = '$user_name'");
911     if ( $signup != null ) {
912         $registered_at mysql2date('U', $signup->registered);
913         $now = current_time( 'timestamp', true );
914         $diff = $now - $registered_at;
915         // If registered more than two days ago, cancel registration and let this signup go through.
916         if ( $diff > 172800 ) {
917             $wpdb->query("DELETE FROM $wpdb->signups WHERE user_login = '$user_name'");
918         } else {
919             $errors->add('user_name', __("That username is currently reserved but may be available in a couple of days."));
920         }
921         if( $signup->active == 0 && $signup->user_email == $user_email )
922             $errors->add('user_email_used', __("username and email used"));
923     }
924
925     $signup = $wpdb->get_row("SELECT * FROM $wpdb->signups WHERE user_email = '$user_email'");
926     if ( $signup != null ) {
927         $registered_at mysql2date('U', $signup->registered);
928         $now = current_time( 'timestamp', true );
929         $diff = $now - $registered_at;
930         // If registered more than two days ago, cancel registration and let this signup go through.
931         if ( $diff > 172800 ) {
932             $wpdb->query("DELETE FROM $wpdb->signups WHERE user_email = '$user_email'");
933         } else {
934             $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."));
935         }
936     }
937
938     $result = array('user_name' => $user_name, 'user_email' => $user_email,    'errors' => $errors);
939
940     return apply_filters('wpmu_validate_user_signup', $result);
941 }
942
943 function wpmu_validate_blog_signup($blog_id, $blog_title, $user = '') {
944     global $wpdb, $domain, $base;
945
946     $blog_id = sanitize_user( $blog_id );
947     $blog_title = strip_tags( $blog_title );
948     $blog_title = substr( $blog_title, 0, 50 );
949
950     $errors = new WP_Error();
951     $illegal_names = get_site_option( "illegal_names" );
952     if( $illegal_names == false ) {
953         $illegal_names = array( "www", "web", "root", "admin", "main", "invite", "administrator" );
954         add_site_option( "illegal_names", $illegal_names );
955     }
956
957     if ( empty( $blog_id ) )
958         $errors->add('blog_id', __("Please enter a blog name"));
959
960     preg_match( "/[a-z0-9]+/", $blog_id, $maybe );
961     if( $blog_id != $maybe[0] ) {
962         $errors->add('blog_id', __("Only lowercase letters and numbers allowed"));
963     }
964     if( in_array( $blog_id, $illegal_names ) == true ) {
965         $errors->add('blog_id'__("That name is not allowed"));
966     }
967     if( strlen( $blog_id ) < 4 && !is_site_admin() ) {
968         $errors->add('blog_id'__("Blog name must be at least 4 characters"));
969     }
970
971     if ( strpos( " " . $blog_id, "_" ) != false )
972         $errors->add('blog_id', __("Sorry, blog names may not contain the character '_'!"));
973
974     // all numeric?
975     preg_match( '/[0-9]*/', $blog_id, $match );
976     if ( $match[0] == $blog_id )
977         $errors->add('blog_id', __("Sorry, blog names must have letters too!"));
978
979     $blog_id = apply_filters( "newblog_id", $blog_id );
980
981     $blog_title = stripslashes$blog_title );
982
983     if ( empty( $blog_title ) )
984         $errors->add('blog_title', __("Please enter a blog title"));
985
986     // Check if the domain/path has been used already.
987     if( constant( "VHOST" ) == 'yes' ) {
988         $mydomain = "$blog_id.$domain";
989         $path = $base;
990     } else {
991         $mydomain = "$domain";
992         $path = $base.$blog_id.'/';
993     }
994     if ( domain_exists($mydomain, $path) )
995         $errors->add('blog_id', __("Sorry, that blog already exists!"));
996
997     if ( username_exists($blog_id) ) {
998         if  ( !is_object($user) && ( $user->user_login != $blog_id ) )
999             $errors->add('blog_id', __("Sorry, that blog is reserved!"));
1000     }
1001
1002     // Has someone already signed up for this domain?
1003     // TODO: Check email too?
1004     $signup = $wpdb->get_row("SELECT * FROM $wpdb->signups WHERE domain = '$mydomain' AND path = '$path'");
1005     if ( ! empty($signup) ) {
1006         $registered_at mysql2date('U', $signup->registered);
1007         $now = current_time( 'timestamp', true );
1008         $diff = $now - $registered_at;
1009         // If registered more than two days ago, cancel registration and let this signup go through.
1010         if ( $diff > 172800 ) {
1011             $wpdb->query("DELETE FROM $wpdb->signups WHERE domain = '$mydomain' AND path = '$path'");
1012         } else {
1013             $errors->add('blog_id', __("That blog is currently reserved but may be available in a couple days."));
1014         }
1015     }
1016
1017     $result = array('domain' => $mydomain, 'path' => $path, 'blog_id' => $blog_id, 'blog_title' => $blog_title,
1018                 'errors' => $errors);
1019
1020     return apply_filters('wpmu_validate_blog_signup', $result);
1021 }
1022
1023 // Record signup information for future activation. wpmu_validate_signup() should be run
1024 // on the inputs before calling wpmu_signup().
1025 function wpmu_signup_blog($domain, $path, $title, $user, $user_email, $meta = '') {
1026     global $wpdb;
1027
1028     $key = substr( md5( time() . rand() . $domain ), 0, 16 );
1029     $registered = current_time('mysql', true);
1030     $meta = serialize($meta);
1031     $domain = $wpdb->escape($domain);
1032     $path = $wpdb->escape($path);
1033     $title = $wpdb->escape($title);
1034     $wpdb->query( "INSERT INTO $wpdb->signups ( domain, path, title, user_login, user_email, registered, activation_key, meta )
1035                     VALUES ( '$domain', '$path', '$title', '$user', '$user_email', '$registered', '$key', '$meta' )" );
1036
1037     wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta);
1038 }
1039
1040 function wpmu_signup_user($user, $user_email, $meta = '') {
1041     global $wpdb;
1042
1043     $user = sanitize_user( $user );
1044     $user_email = sanitize_email( $user_email );
1045
1046     $key = substr( md5( time() . rand() . $user_email ), 0, 16 );
1047     $registered = current_time('mysql', true);
1048     $meta = serialize($meta);
1049     $wpdb->query( "INSERT INTO $wpdb->signups ( domain, path, title, user_login, user_email, registered, activation_key, meta )
1050                     VALUES ( '', '', '', '$user', '$user_email', '$registered', '$key', '$meta' )" );
1051
1052     wpmu_signup_user_notification($user, $user_email, $key, $meta);
1053 }
1054
1055 // Notify user of signup success.
1056 function wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta = '') {
1057     global $current_site;
1058
1059     if( !apply_filters('wpmu_signup_blog_notification', $domain, $path, $title, $user, $user_email, $key, $meta) )
1060         return;
1061
1062     // Send email with activation link.
1063     if( constant( "VHOST" ) == 'no' ) {
1064         $activate_url = "http://" . $current_site->domain . $current_site->path . "wp-activate.php?key=$key";
1065     } else {
1066         $activate_url = "http://{$domain}{$path}wp-activate.php?key=$key";
1067     }
1068     $activate_url = clean_url($activate_url);
1069     $admin_email = get_site_option( "admin_email" );
1070     if( $admin_email == '' )
1071         $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1072     $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1073     $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1074     $message = sprintf(__("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 blog here:\n\n%s"), $activate_url, clean_url("http://{$domain}{$path}"));
1075     // TODO: Don't hard code activation link.
1076     $subject = '[' . $from_name . '] ' . sprintf(__('Activate %s'), clean_url('http://' . $domain . $path));
1077     wp_mail($user_email, $subject, $message, $message_headers);
1078 }
1079
1080 function wpmu_signup_user_notification($user, $user_email, $key, $meta = '') {
1081     global $current_site;
1082
1083     if( !apply_filters('wpmu_signup_user_notification', $user, $user_email, $key, $meta) )
1084         return;
1085
1086     // Send email with activation link.
1087     $admin_email = get_site_option( "admin_email" );
1088     if( $admin_email == '' )
1089         $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1090     $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1091     $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1092     $message = sprintf(__("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"), clean_url("http://{$current_site->domain}{$current_site->path}wp-activate.php?key=$key") );
1093     // TODO: Don't hard code activation link.
1094     $subject = sprintf(__('Activate %s'), $user);
1095     wp_mail($user_email, $subject, $message, $message_headers);
1096 }
1097
1098 function wpmu_activate_signup($key) {
1099     global $wpdb;
1100
1101     $result = array();
1102     $signup = $wpdb->get_row("SELECT * FROM $wpdb->signups WHERE activation_key = '$key'");
1103
1104     if ( empty($signup) )
1105         return new WP_Error('invalid_key', __('Invalid activation key.'));
1106
1107     if ( $signup->active )
1108         return new WP_Error('already_active', __('The blog is already active.'), $signup);
1109
1110     $meta = unserialize($signup->meta);
1111     $user_login = $wpdb->escape($signup->user_login);
1112     $user_email = $wpdb->escape($signup->user_email);
1113     wpmu_validate_user_signup($user_login, $user_email);
1114     $password = generate_random_password();
1115
1116     $user_id = username_exists($user_login);
1117
1118     if ( ! $user_id )
1119         $user_id = wpmu_create_user($user_login, $password, $user_email);
1120     else
1121         $user_already_exists = true;
1122
1123     if ( ! $user_id )
1124         return new WP_Error('create_user', __('Could not create user'), $signup);
1125
1126     $now = current_time('mysql', true);
1127
1128     if ( empty($signup->domain) ) {
1129         $wpdb->query("UPDATE $wpdb->signups SET active = '1', activated = '$now' WHERE activation_key = '$key'");
1130         if ( isset($user_already_exists) )
1131             return new WP_Error('user_already_exists', __('That username is already activated.'), $signup);
1132         wpmu_welcome_user_notification($user_id, $password, $meta);
1133         add_user_to_blog('1', $user_id, 'subscriber');
1134         do_action('wpmu_activate_user', $user_id, $password, $meta);
1135         return array('user_id' => $user_id, 'password' => $password, 'meta' => $meta);
1136     }
1137
1138     wpmu_validate_blog_signup($signup->domain, $signup->title);
1139     $blog_id = wpmu_create_blog($signup->domain, $signup->path, $signup->title, $user_id, $meta);
1140
1141     // TODO: What to do if we create a user but cannot create a blog?
1142     if ( is_wp_error($blog_id) ) {
1143         // If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and
1144         // setting the activation flag.  Let's just set the active flag and instruct the user to reset their password.
1145         if ( 'blog_taken' == $blog_id->get_error_code() ) {
1146             $blog_id->add_data($signup);
1147             $wpdb->query("UPDATE $wpdb->signups SET active = '1', activated = '$now' WHERE activation_key = '$key'");
1148         }
1149
1150         return $blog_id;
1151     }
1152
1153     $wpdb->query("UPDATE $wpdb->signups SET active = '1', activated = '$now' WHERE activation_key = '$key'");
1154
1155     wpmu_welcome_notification($blog_id, $user_id, $password, $signup->title, $meta);
1156
1157     do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta);
1158
1159     return array('blog_id' => $blog_id, 'user_id' => $user_id, 'password' => $password, 'title' => $signup->title, 'meta' => $meta);
1160 }
1161
1162 function generate_random_password( $len = 8 ) {
1163     $random_password = substr(md5(uniqid(microtime())), 0, intval( $len ) );
1164     $random_password = apply_filters('random_password', $random_password);
1165     return $random_password;
1166 }
1167
1168 function wpmu_create_user( $user_name, $password, $email) {
1169     if ( username_exists($user_name) )
1170         return false;
1171
1172     // Check if the email address has been used already.
1173     if ( email_exists($email) )
1174         return false;
1175
1176     $user_id = wp_create_user( $user_name, $password, $email );
1177     $user = new WP_User($user_id);
1178     // Newly created users have no roles or caps until they are added to a blog.
1179     update_usermeta($user_id, 'capabilities', '');
1180     update_usermeta($user_id, 'user_level', '');
1181
1182     do_action( 'wpmu_new_user', $user_id );
1183
1184     return $user_id;
1185 }
1186
1187 function wpmu_create_blog($domain, $path, $title, $user_id, $meta = '', $site_id = 1) {
1188     $domain = sanitize_user( $domain );
1189     $title = strip_tags( $title );
1190     $user_id = (int) $user_id;
1191
1192     if( empty($path) )
1193         $path = '/';
1194
1195     // Check if the domain has been used already. We should return an error message.
1196     if ( domain_exists($domain, $path, $site_id) )
1197         return new WP_Error('blog_taken', __('Blog already exists.'));
1198
1199     if ( !defined("WP_INSTALLING") )
1200         define( "WP_INSTALLING", true );
1201
1202     if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
1203         return new WP_Error('insert_blog', __('Could not create blog.'));
1204
1205     switch_to_blog($blog_id);
1206
1207     install_blog($blog_id, $title);
1208
1209     install_blog_defaults($blog_id, $user_id);
1210
1211     add_user_to_blog($blog_id, $user_id, 'administrator');
1212
1213     restore_current_blog();
1214
1215     if ( is_array($meta) ) foreach ($meta as $key => $value) {
1216         update_blog_status( $blog_id, $key, $value );
1217         update_blog_option( $blog_id, $key, $value );
1218     }
1219
1220     add_blog_option( $blog_id, 'WPLANG', get_site_option( 'WPLANG' ) );
1221
1222     update_blog_option( $blog_id, 'blog_public', $meta['public'] );
1223     delete_blog_option( $blog_id, 'public' );
1224
1225     if(get_usermeta( $user_id, 'primary_blog' ) == 1 )
1226         update_usermeta( $user_id, 'primary_blog', $blog_id );
1227
1228
1229     do_action( 'wpmu_new_blog', $blog_id, $user_id );
1230
1231     return $blog_id;
1232 }
1233
1234 function newblog_notify_siteadmin( $blog_id, $user_id ) {
1235     global $current_site;
1236     if( get_site_option( 'registrationnotification' ) != 'yes' )
1237         return;
1238         
1239     $email = get_site_option( 'admin_email' );
1240     if( is_email($email) == false )
1241         return false;
1242     
1243     $options_site_url = clean_url("http://{$current_site->domain}{$current_site->path}wp-admin/wpmu-options.php");
1244     
1245     $msg = sprintf(__("New Blog: %1s
1246 URL: %2s
1247 Remote IP: %3s
1248
1249 Disable these notifications: %4s"), get_blog_option( $blog_id, "blogname" ), get_blog_option( $blog_id, "siteurl" ), $_SERVER['REMOTE_ADDR'], $options_site_url);
1250     $msg = apply_filters( 'newblog_notify_siteadmin', $msg );
1251     
1252     wp_mail( $email, sprintf(__("New Blog Registration: %s"), get_blog_option( $blog_id, "siteurl" )), $msg );
1253 }
1254 add_action( "wpmu_new_blog", "newblog_notify_siteadmin", 10, 2 );
1255
1256 function newuser_notify_siteadmin( $user_id ) {
1257     global $current_site;
1258     if( get_site_option( 'registrationnotification' ) != 'yes' )
1259         return;
1260         
1261     $email = get_site_option( 'admin_email' );
1262     if( is_email($email) == false )
1263         return false;
1264     $user = new WP_User($user_id);
1265
1266     $options_site_url = clean_url("http://{$current_site->domain}{$current_site->path}wp-admin/wpmu-options.php");
1267     $msg = sprintf(__("New User: %1s
1268 Remote IP: %2s
1269
1270 Disable these notifications: %3s"), $user->user_login, $_SERVER['REMOTE_ADDR'], $options_site_url);
1271     
1272     $msg = apply_filters( 'newuser_notify_siteadmin', $msg );
1273     wp_mail( $email, sprintf(__("New User Registration: %s"), $user->user_login), $msg );
1274 }
1275 add_action( "wpmu_new_user", "newuser_notify_siteadmin" );
1276
1277 function domain_exists($domain, $path, $site_id = 1) {
1278     global $wpdb;
1279     return $wpdb->get_var("SELECT blog_id FROM $wpdb->blogs WHERE domain = '$domain' AND path = '$path' AND site_id = '$site_id'" );
1280 }
1281
1282 function insert_blog($domain, $path, $site_id) {
1283     global $wpdb;
1284     $path = trailingslashit($path);
1285     $site_id = (int) $site_id;
1286     
1287     $result = $wpdb->query( "INSERT INTO $wpdb->blogs ( blog_id, site_id, domain, path, registered ) VALUES ( NULL, '$site_id', '$domain', '$path', NOW( ))" );
1288     if ( !$result )
1289         return false;
1290
1291     refresh_blog_details($wpdb->insert_id);
1292     return $wpdb->insert_id;
1293 }
1294
1295 // Install an empty blog.  wpdb should already be switched.
1296 function install_blog($blog_id, $blog_title = '') {
1297     global $wpdb, $table_prefix, $wp_roles;
1298
1299     require_once( ABSPATH . 'wp-admin/includes/upgrade.php');
1300     $wpdb->suppress_errors();
1301     $installed = $wpdb->get_results("SELECT * FROM $wpdb->posts");
1302     $wpdb->suppress_errors( false);
1303     if ($installed) 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>');
1304
1305     $url = get_blogaddress_by_id($blog_id);
1306
1307     // Set everything up
1308     make_db_current_silent();
1309     populate_options();
1310     populate_roles();
1311     $wp_roles->_init();
1312     // fix url.
1313     wp_cache_delete('notoptions', 'options');
1314     wp_cache_delete('alloptions', 'options');
1315     update_option('siteurl', $url);
1316     update_option('home', $url);
1317     update_option('fileupload_url', $url . "files" );
1318     update_option('upload_path', "wp-content/blogs.dir/" . $blog_id . "/files");
1319     update_option('blogname', $blog_title);
1320
1321     $wpdb->query("UPDATE $wpdb->options SET option_value = '' WHERE option_name = 'admin_email'");
1322
1323     // Default category
1324     $cat_name = $wpdb->escape(__('Uncategorized'));
1325     $cat_slug = sanitize_title(__('Uncategorized'));
1326     $wpdb->query("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES ('1', '$cat_name', '$cat_slug', '0')");
1327
1328     $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('1', 'category', '', '0', '1')");
1329
1330     // Default link category
1331     $cat_name = $wpdb->escape(__('Blogroll'));
1332     $cat_slug = sanitize_title(__('Blogroll'));
1333     $blogroll_id = $wpdb->get_var( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = '$cat_slug'" );
1334     if( $blogroll_id == null ) {
1335         $wpdb->query( "INSERT INTO " . $wpdb->sitecategories . " (cat_ID, cat_name, category_nicename, last_updated) VALUES (0, '$cat_name', '$cat_slug', NOW())" );
1336         $blogroll_id = $wpdb->insert_id;
1337     }
1338     $wpdb->query("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES ('$blogroll_id', '$cat_name', '$cat_slug', '0')");
1339     $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('$blogroll_id', 'link_category', '', '0', '2')");
1340
1341     update_option('default_link_category', $blogroll_id);
1342
1343     // remove all perms
1344     $wpdb->query( "DELETE FROM ".$wpdb->usermeta." WHERE meta_key = '".$table_prefix."user_level'" );
1345     $wpdb->query( "DELETE FROM ".$wpdb->usermeta." WHERE meta_key = '".$table_prefix."capabilities'" );
1346
1347     $wpdb->show_errors();
1348 }
1349
1350 function install_blog_defaults($blog_id, $user_id) {
1351     global $wpdb, $wp_rewrite, $current_site, $table_prefix;
1352
1353     $wpdb->hide_errors();
1354
1355     // Default links
1356     $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_owner, link_rss) VALUES ('http://wordpress.com/', 'WordPress.com', 1356, '$user_id', 'http://wordpress.com/feed/');");
1357     $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_owner, link_rss) VALUES ('http://wordpress.org/', 'WordPress.org', 1356, '$user_id', 'http://wordpress.org/development/feed/');");
1358     $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (1, 2)" );
1359     $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (2, 2)" );
1360
1361     // First post
1362     $now = date('Y-m-d H:i:s');
1363     $now_gmt = gmdate('Y-m-d H:i:s');
1364     $first_post = get_site_option( 'first_post' );
1365     if( $first_post == false )
1366         $first_post = stripslashes( __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' ) );
1367
1368     $first_post = str_replace( "SITE_URL", clean_url("http://" . $current_site->domain . $current_site->path), $first_post );
1369     $first_post = str_replace( "SITE_NAME", $current_site->site_name, $first_post );
1370     $first_post = stripslashes( $first_post );
1371
1372     $wpdb->query("INSERT INTO $wpdb->posts (post_author, post_date, post_date_gmt, post_content, post_title, post_category, post_name, post_modified, post_modified_gmt, comment_count) VALUES ('".$user_id."', '$now', '$now_gmt', '".addslashes($first_post)."', '".addslashes(__('Hello world!'))."', '0', '".addslashes(__('hello-world'))."', '$now', '$now_gmt', '1')");
1373     $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (1, 1)" );
1374     update_option( "post_count", 1 );
1375
1376     // First page
1377     $wpdb->query("INSERT INTO $wpdb->posts (post_author, post_date, post_date_gmt, post_content, post_excerpt, post_title, post_category, post_name, post_modified, post_modified_gmt, post_status, post_type, to_ping, pinged, post_content_filtered) VALUES ('$user_id', '$now', '$now_gmt', '".$wpdb->escape(__('This is an example of a WordPress page, you could edit this to put information about yourself or your site so readers know where you are coming from. You can create as many pages like this one or sub-pages as you like and manage all of your content inside of WordPress.'))."', '', '".$wpdb->escape(__('About'))."', '0', '".$wpdb->escape(__('about'))."', '$now', '$now_gmt', 'publish', 'page', '', '', '')");
1378     // Flush rules to pick up the new page.
1379     $wp_rewrite->init();
1380     $wp_rewrite->flush_rules();
1381
1382     // Default comment
1383     $wpdb->query("INSERT INTO $wpdb->comments (comment_post_ID, comment_author, comment_author_email, comment_author_url, comment_author_IP, comment_date, comment_date_gmt, comment_content) VALUES ('1', '".addslashes(__('Mr WordPress'))."', '', 'http://" . $current_site->domain . $current_site->path . "', '127.0.0.1', '$now', '$now_gmt', '".addslashes(__('Hi, this is a comment.<br />To delete a comment, just log in, and view the posts\' comments, there you will have the option to edit or delete them.'))."')");
1384
1385     $user = new WP_User($user_id);
1386     $wpdb->query("UPDATE $wpdb->options SET option_value = '$user->user_email' WHERE option_name = 'admin_email'");
1387
1388     // Remove all perms except for the login user.
1389     $wpdb->query( "DELETE FROM ".$wpdb->usermeta." WHERE  user_id != '".$user_id."' AND meta_key = '".$table_prefix."user_level'" );
1390     $wpdb->query( "DELETE FROM ".$wpdb->usermeta." WHERE  user_id != '".$user_id."' AND meta_key = '".$table_prefix."capabilities'" );
1391     // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
1392     if ( !is_site_admin( $user->user_login ) && $user_id != 1 )
1393         $wpdb->query( "DELETE FROM ".$wpdb->usermeta." WHERE  user_id = '".$user_id."' AND meta_key = '" . $wpdb->base_prefix . "1_capabilities'" );
1394
1395     $wpdb->show_errors();
1396 }
1397
1398 function wpmu_welcome_notification($blog_id, $user_id, $password, $title, $meta = '') {
1399     global $current_site;
1400
1401     if( !apply_filters('wpmu_welcome_notification', $blog_id, $user_id, $password, $title, $meta) )
1402         return;
1403
1404     $welcome_email = stripslashes( get_site_option( 'welcome_email' ) );
1405     if( $welcome_email == false )
1406         $welcome_email = stripslashes( __( "Dear User,
1407
1408 Your new SITE_NAME blog has been successfully set up at:
1409 BLOG_URL
1410
1411 You can log in to the administrator account with the following information:
1412 Username: USERNAME
1413 Password: PASSWORD
1414 Login Here: BLOG_URLwp-login.php
1415
1416 We hope you enjoy your new weblog.
1417 Thanks!
1418
1419 --The WordPress Team
1420 SITE_NAME" ) );
1421
1422     $url = get_blogaddress_by_id($blog_id);
1423     $user = new WP_User($user_id);
1424
1425     $welcome_email = str_replace( "SITE_NAME", $current_site->site_name, $welcome_email );
1426     $welcome_email = str_replace( "BLOG_URL", $url, $welcome_email );
1427     $welcome_email = str_replace( "USERNAME", $user->user_login, $welcome_email );
1428     $welcome_email = str_replace( "PASSWORD", $password, $welcome_email );
1429
1430     $welcome_email = apply_filters( "update_welcome_email", $welcome_email, $blog_id, $user_id, $password, $title, $meta);
1431     $admin_email = get_site_option( "admin_email" );
1432     if( $admin_email == '' )
1433         $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1434     $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1435     $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1436     $message = $welcome_email;
1437     if( empty( $current_site->site_name ) )
1438         $current_site->site_name = "WordPress MU";
1439     $subject = sprintf(__('New %1$s Blog: %2$s'), $current_site->site_name, $title);
1440     wp_mail($user->user_email, $subject, $message, $message_headers);
1441 }
1442
1443 function wpmu_welcome_user_notification($user_id, $password, $meta = '') {
1444     global $current_site;
1445
1446     if( !apply_filters('wpmu_welcome_user_notification', $user_id, $password, $meta) )
1447         return;
1448
1449     $welcome_email = __( "Dear User,
1450
1451 Your new account is setup.
1452
1453 You can log in with the following information:
1454 Username: USERNAME
1455 Password: PASSWORD
1456
1457 Thanks!
1458
1459 --The WordPress Team
1460 SITE_NAME" );
1461
1462     $user = new WP_User($user_id);
1463
1464     $welcome_email = apply_filters( "update_welcome_user_email", $welcome_email, $user_id, $password, $meta);
1465     $welcome_email = str_replace( "SITE_NAME", $current_site->site_name, $welcome_email );
1466     $welcome_email = str_replace( "USERNAME", $user->user_login, $welcome_email );
1467     $welcome_email = str_replace( "PASSWORD", $password, $welcome_email );
1468
1469     $admin_email = get_site_option( "admin_email" );
1470     if( $admin_email == '' )
1471         $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1472     $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1473     $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1474     $message = $welcome_email;
1475     if( empty( $current_site->site_name ) )
1476         $current_site->site_name = "WordPress MU";
1477     $subject = sprintf(__('New %1$s User: %2$s'), $current_site->site_name, $user->user_login);
1478     wp_mail($user->user_email, $subject, $message, $message_headers);
1479 }
1480
1481 function get_current_site() {
1482     global $current_site;
1483     return $current_site;
1484 }
1485
1486 function get_user_id_from_string( $string ) {
1487     global $wpdb;
1488     if( is_email( $string ) ) {
1489         $user_id = $wpdb->get_var( "SELECT ID FROM {$wpdb->users} WHERE user_email = '$string'" );
1490     } elseif ( is_numeric( $string ) ) {
1491         $user_id = $string;
1492     } else {
1493         $user_id = $wpdb->get_var( "SELECT ID FROM {$wpdb->users} WHERE user_login = '$string'" );
1494     }
1495
1496     return $user_id;
1497 }
1498
1499 function get_most_recent_post_of_user( $user_id ) {
1500     global $wpdb;
1501
1502     $user_id = (int) $user_id;
1503
1504     $user_blogs = get_blogs_of_user($user_id);
1505     $most_recent_post = array();
1506
1507     // Walk through each blog and get the most recent post
1508     // published by $user_id
1509     foreach ( $user_blogs as $blog ) {
1510         $recent_post = $wpdb->get_row("SELECT ID, post_date_gmt FROM {$wpdb->base_prefix}{$blog->userblog_id}_posts WHERE post_author = '{$user_id}' AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1", ARRAY_A);
1511
1512         // Make sure we found a post
1513         if ( isset($recent_post['ID']) ) {
1514             $post_gmt_ts = strtotime($recent_post['post_date_gmt']);
1515
1516             // If this is the first post checked or if this post is
1517             // newer than the current recent post, make it the new
1518             // most recent post.
1519             if (
1520                 !isset($most_recent_post['post_gmt_ts'])
1521                 || ($post_gmt_ts > $most_recent_post['post_gmt_ts'])
1522             ) {
1523                 $most_recent_post = array(
1524                     'blog_id'        => $blog->userblog_id,
1525                     'post_id'        => $recent_post['ID'],
1526                     'post_date_gmt'    => $recent_post['post_date_gmt'],
1527                     'post_gmt_ts'    => $post_gmt_ts
1528                 );
1529             }
1530         }
1531     }
1532
1533     return $most_recent_post;
1534 }
1535
1536 /* Misc functions */
1537
1538 function fix_upload_details( $uploads ) {
1539     $uploads['url'] = str_replace( UPLOADS, "files", $uploads['url'] );
1540     return $uploads;
1541 }
1542 add_filter( "upload_dir", "fix_upload_details" );
1543
1544
1545 function get_dirsize($directory) {
1546     $size = 0;
1547     if(substr($directory,-1) == '/') $directory = substr($directory,0,-1);
1548     if(!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) return false;
1549     if($handle = opendir($directory)) {
1550         while(($file = readdir($handle)) !== false) {
1551             $path = $directory.'/'.$file;
1552             if($file != '.' && $file != '..') {
1553                 if(is_file($path)) {
1554                     $size += filesize($path);
1555                 } elseif(is_dir($path)) {
1556                     $handlesize = get_dirsize($path);
1557                     if($handlesize >= 0) {
1558                         $size += $handlesize;
1559                     } else {
1560                         return false;
1561                     }
1562                 }
1563             }
1564         }
1565         closedir($handle);
1566     }
1567     return $size;
1568 }
1569
1570 function upload_is_user_over_quota( $echo = true ) {
1571     global $wpdb;
1572     
1573     // Default space allowed is 10 MB
1574     $spaceAllowed = get_space_allowed();
1575     if(empty($spaceAllowed) || !is_numeric($spaceAllowed)) $spaceAllowed = 10;
1576     
1577     $dirName = constant( "ABSPATH" ) . constant( "UPLOADS" );
1578     $size = get_dirsize($dirName) / 1024 / 1024;
1579     
1580     if( ($spaceAllowed-$size) < 0 ) {
1581         if( $echo )
1582             _e( "Sorry, you have used your space allocation. Please delete some files to upload more files." ); //No space left
1583         return true;
1584     } else {
1585         return false;
1586     }
1587 }
1588 add_action( 'upload_files_upload', 'upload_is_user_over_quota' );
1589 add_action( 'upload_files_browse', 'upload_is_user_over_quota' );
1590 add_action( 'upload_files_browse-all', 'upload_is_user_over_quota' );
1591
1592 function check_upload_mimes($mimes) {
1593     $site_exts = explode( " ", get_site_option( "upload_filetypes" ) );
1594     foreach ( $site_exts as $ext )
1595         foreach ( $mimes as $ext_pattern => $mime )
1596             if( strpos( $ext_pattern, $ext ) !== false )
1597                 $site_mimes[$ext_pattern] = $mime;
1598     return $site_mimes;
1599 }
1600 add_filter('upload_mimes', 'check_upload_mimes');
1601
1602 function update_posts_count( $post_id ) {
1603     global $wpdb;
1604     $post_id = intval( $post_id );
1605     $c = $wpdb->get_var( "SELECT count(*) FROM {$wpdb->posts} WHERE post_status = 'publish' and post_type='post'" );
1606     update_option( "post_count", $c );
1607 }
1608 add_action( "publish_post", "update_posts_count" );
1609
1610 function wpmu_log_new_registrations( $blog_id, $user_id ) {
1611     global $wpdb;
1612     $user = new WP_User($user_id);
1613     $email = $wpdb->escape($user->user_email);
1614     $IP = preg_replace( '/[^0-9., ]/', '',$_SERVER['REMOTE_ADDR'] );
1615     $wpdb->query( "INSERT INTO {$wpdb->registration_log} ( email , IP , blog_id, date_registered ) VALUES ( '{$email}', '{$IP}', '{$blog_id}', NOW( ))" );
1616 }
1617
1618 add_action( "wpmu_new_blog" ,"wpmu_log_new_registrations", 10, 2 );
1619
1620 function scriptaculous_admin_loader() {
1621             wp_enqueue_script('scriptaculous');
1622 }
1623 add_action( 'admin_print_scripts', 'scriptaculous_admin_loader' );
1624
1625 function fix_import_form_size( $size ) {
1626     if( upload_is_user_over_quota( false ) == true )
1627         return 0;
1628     $spaceAllowed = 1024 * 1024 * get_space_allowed();
1629     $dirName = constant( "ABSPATH" ) . constant( "UPLOADS" );
1630     $dirsize = get_dirsize($dirName) ;
1631     if( $size > $spaceAllowed - $dirsize ) {
1632         return $spaceAllowed - $dirsize; // remaining space
1633     } else {
1634         return $size; // default
1635     }
1636 }
1637 add_filter( 'import_upload_size_limit', 'fix_import_form_size' );
1638
1639 if ( !function_exists('graceful_fail') ) :
1640 function graceful_fail( $message ) {
1641     die('
1642 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1643 <html xmlns="http://www.w3.org/1999/xhtml"><head profile="http://gmpg.org/xfn/11">
1644 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1645 <title>Error!</title>
1646 <style type="text/css">
1647 img {
1648     border: 0;
1649 }
1650 body {
1651 line-height: 1.6em; font-family: Georgia, serif; width: 390px; margin: auto;
1652 text-align: center;
1653 }
1654 .message {
1655     font-size: 22px;
1656     width: 350px;
1657     margin: auto;
1658 }
1659 </style>
1660 </head>
1661 <body>
1662 <p class="message">' . $message . '</p>
1663 </body>
1664 </html>
1665     ');
1666 }
1667 endif;
1668
1669 /* Delete blog */
1670
1671 class delete_blog {
1672     function delete_blog() {
1673         $this->reallydeleteblog = false;
1674         add_action('admin_menu', array(&$this, 'admin_menu'));
1675         add_action('admin_footer', array(&$this, 'admin_footer'));
1676     }
1677
1678     function admin_footer() {
1679         global $wpdb;
1680
1681         if( $this->reallydeleteblog == true ) {
1682             wpmu_delete_blog( $wpdb->blogid );
1683         }
1684     }
1685
1686     function admin_menu() {
1687         add_submenu_page('options-general.php', __('Delete Blog'), __('Delete Blog'), 'manage_options', 'delete-blog', array(&$this, 'plugin_content'));
1688     }
1689
1690     function plugin_content() {
1691         global $wpdb, $current_blog, $current_site;
1692         $this->delete_blog_hash = get_settings('delete_blog_hash');
1693         echo '<div class="wrap"><h2>' . __('Delete Blog') . '</h2>';
1694         if( $_POST['action'] == "deleteblog" && $_POST['confirmdelete'] == '1' ) {
1695             $hash = substr( md5( $_SERVER['REQUEST_URI'] . time() ), 0, 6 );
1696             update_option( "delete_blog_hash", $hash );
1697             $url_delete = get_option( "siteurl" ) . "/wp-admin/options-general.php?page=delete-blog&h=" . $hash;
1698             $msg = __("Dear User,
1699 You recently clicked the 'Delete Blog' link on your blog and filled in a
1700 form on that page.
1701 If you really want to delete your blog, click the link below. You will not
1702 be asked to confirm again so only click this link if you are 100% certain:
1703 URL_DELETE
1704
1705 If you delete your blog, please consider opening a new blog here
1706 some time in the future! (But remember your current blog and username
1707 are gone forever.)
1708
1709 Thanks for using the site,
1710 Webmaster
1711 SITE_NAME
1712 ");
1713             $msg = str_replace( "URL_DELETE", $url_delete, $msg );
1714             $msg = str_replace( "SITE_NAME", $current_site->site_name, $msg );
1715             wp_mail( get_option( "admin_email" ), "[ " . get_option( "blogname" ) . " ] ".__("Delete My Blog"), $msg );
1716             ?>
1717             <p><?php _e('Thank you. Please check your email for a link to confirm your action. Your blog will not be deleted until this link is clicked.') ?></p>
1718             <?php
1719         } elseif( isset( $_GET['h'] ) && $_GET['h'] != '' && get_option('delete_blog_hash') != false ) {
1720             if( get_option('delete_blog_hash') == $_GET['h'] ) {
1721                 $this->reallydeleteblog = true;
1722                 echo "<p>" . sprintf(__('Thank you for using %s, your blog has been deleted. Happy trails to you until we meet again.'), $current_site->site_name) . "</p>";
1723             } else {
1724                 $this->reallydeleteblog = false;
1725                 echo "<p>" . __("I'm sorry, the link you clicked is stale. Please select another option.") . "</p>";
1726             }
1727         } else {
1728 ?>
1729             <p><?php printf(__('If you do not want to use your %s blog any more, you can delete it using the form below. When you click <strong>Delete My Blog</strong> you will be sent an email with a link in it. Click on this link to delete your blog.'), $current_site->site_name); ?></p>
1730             <p><?php _e('Remember, once deleted your blog cannot be restored.') ?></p>
1731             <form method='post' name='deletedirect'>
1732             <input type="hidden" name="page" value="<?php echo $_GET['page'] ?>" />
1733             <input type='hidden' name='action' value='deleteblog' />
1734             <p><input id='confirmdelete' type='checkbox' name='confirmdelete' value='1' /> <label for='confirmdelete'><strong><?php printf( __("I'm sure I want to permanently disable my blog, and I am aware I can never get it back or use %s again."), $current_blog->domain); ?></strong></label></p>
1735             <p class="submit"><input type='submit' value='<?php _e('Delete My Blog Permanently &raquo;') ?>' /></p>
1736             </form>
1737 <?php
1738         }
1739         echo "</div>";
1740     }
1741 }
1742
1743 $delete_blog_obj = new delete_blog();
1744
1745 /* Global Categories */
1746
1747 function global_terms( $term_id, $tt_id ) {
1748     global $wpdb;
1749
1750     $term_id = intval( $term_id );
1751     $c = $wpdb->get_row( "SELECT * FROM $wpdb->terms WHERE term_id = '$term_id'" );
1752
1753     $global_id = $wpdb->get_var( "SELECT cat_ID FROM $wpdb->sitecategories WHERE category_nicename = '" . $wpdb->escape( $c->slug ) . "'" );
1754
1755     if ( $global_id == null ) {
1756         $wpdb->query( "INSERT INTO $wpdb->sitecategories ( cat_name, category_nicename ) VALUES ( '" . $wpdb->escape( $c->name ) . "', '" . $wpdb->escape( $c->slug ) . "' )" );
1757         $global_id = $wpdb->insert_id;
1758     }
1759
1760     if ( $global_id == $term_id )
1761         return $global_id;
1762
1763     if( get_option( 'default_category' ) == $term_id )
1764         update_option( 'default_category', $global_id );
1765     $wpdb->query( "UPDATE $wpdb->terms SET term_id = '$global_id' WHERE term_id = '$term_id'" );
1766     $wpdb->query( "UPDATE $wpdb->term_taxonomy SET term_id = '$global_id' WHERE term_id = '$term_id'" );
1767     $wpdb->query( "UPDATE $wpdb->term_taxonomy SET parent = '$global_id' WHERE parent = '$term_id'" );
1768
1769     clean_term_cache($term_id);
1770
1771     return $global_id;
1772 }   
1773 add_filter( 'term_id_filter', 'global_terms', 10, 2 ); // taxonomy specific filter
1774
1775 function choose_primary_blog() {
1776     global $current_user;
1777     ?>
1778     <table class="form-table">
1779     <tr>
1780         <th scope="row"><?php _e('Primary Blog:'); ?></th>
1781         <td>
1782         <?php
1783         $all_blogs = get_blogs_of_user( $current_user->ID );
1784         if( count( $all_blogs ) > 1 ) {
1785             $primary_blog = get_usermeta($current_user->ID, 'primary_blog');
1786             ?>
1787             <select name="primary_blog">
1788                 <?php foreach( (array) $all_blogs as $blog ) { ?>
1789                     <option value='<?php echo $blog->userblog_id ?>'<?php if( $primary_blog == $blog->userblog_id ) echo ' selected="selected"' ?>>http://<?php echo $blog->domain.$blog->path ?></option>
1790                 <?php } ?>
1791             </select>
1792             <?php
1793         } else {
1794             echo $_SERVER['HTTP_HOST'];
1795         }
1796         ?>
1797         </td>
1798     </tr>
1799     </table>
1800     <?php   
1801 }
1802 add_action( 'profile_personal_options', 'choose_primary_blog' );
1803
1804 function redirect_this_site( $hosts ) {
1805     global $current_site;
1806     return array( $current_site->domain );
1807 }
1808 add_filter( 'allowed_redirect_hosts', 'redirect_this_site' );
1809
1810 function upload_is_file_too_big( $upload ) {
1811     if( is_array( $upload ) == false || defined( 'WP_IMPORTING' ) )
1812         return $upload;
1813     if( strlen( $upload[ 'bits' ] )  > ( 1024 * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
1814         return sprintf(__( "This file is too big. Files must be less than %dKb in size.<br />" ), get_site_option( 'fileupload_maxk', 1500 ));
1815     }
1816
1817     return $upload;
1818 }
1819 add_filter( "wp_upload_bits", "upload_is_file_too_big" );
1820
1821 function safecss_filter_attr( $css, $element ) {
1822     $css = wp_kses_no_null($css);
1823     $css = str_replace(array("\n","\r","\t"), '', $css);
1824     $css_array = split( ';', trim( $css ) );
1825     $allowed_attr = apply_filters( 'safe_style_css', array( 'text-align', 'margin', 'color', 'float',
1826     'text-direction', 'font', 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight', 'height',
1827     'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'padding', 'padding-bottom',
1828     'padding-left', 'padding-right', 'padding-top', 'width', 'border', 'vertical-align', 'text-decoration' ) );
1829     $css = '';
1830     foreach( $css_array as $css_item ) {
1831         if( $css_item == '' )
1832             con