root/tags/1.2.4/wp-includes/wpmu-functions.php

Revision 1036, 52.0 kB (checked in by donncha, 2 years ago)

No more linkcategories
Make sure all fields are accounted for. props Vimm, fixes #389

  • 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
24 add_action('delete_post', 'wpmu_update_blogs_date');
25 add_action('private_to_published', 'wpmu_update_blogs_date');
26 add_action('publish_phone', 'wpmu_update_blogs_date');
27 add_action('publish_post', 'wpmu_update_blogs_date');
28
29 /*
30   Determines if the available space defined by the admin has been exceeded by the user
31 */
32 /**
33  * Returns how much space is available (also shows a picture) for the current client blog, retrieving the value from the master blog 'main' option table
34  *
35  * @param string $action
36  * @return string
37  */
38 function wpmu_checkAvailableSpace($action) {
39     // Using the action.
40     // Set the action to 'not-writable' to block the upload
41
42     // Default space allowed is 10 MB
43     $spaceAllowed = get_site_option( "blog_upload_space" );
44     if( $spaceAllowed == false )
45         $spaceAllowed = 10;
46
47     $dirName = constant( "ABSPATH" ) . constant( "UPLOADS" );
48
49       $dir  = dir($dirName);
50        $size = 0;
51
52     while($file = $dir->read()) {
53         if ($file != '.' && $file != '..') {
54             if (is_dir($file)) {
55                $size += dirsize($dirName . '/' . $file);
56            } else {
57                $size += filesize($dirName . '/' . $file);
58            }
59        }
60     }
61     $dir->close();
62     $size = $size / 1024 / 1024;
63     $spaceAvailable = sprintf( "%2.2f", ( ($spaceAllowed-$size) ) );
64     echo sprintf(__('Space Available (<i>%2.2fMB</i>)'), $spaceAvailable);
65
66
67     if (($spaceAllowed-$size)>0) {
68         return $action;
69     } else {
70         // No space left
71         return 'not-writable';
72     }
73 }
74 add_filter('fileupload_init','wpmu_checkAvailableSpace');
75
76 if( defined( "WP_INSTALLING" ) == false ) {
77     header( "X-totalblogs: " . get_blog_count() );
78     header( "X-rootblog: http://" . $current_site->domain . $current_site->path );
79     header( "X-created-on: " . $current_blog->registered );
80
81     if( empty( $WPMU_date ) == false )
82         header( "X-wpmu-date: $WPMU_date" );
83 }
84
85
86 function get_blogaddress_by_id( $blog_id ) {
87     global $hostname, $domain, $base, $wpdb;
88
89     $bloginfo = get_blog_details( $blog_id, false ); // only get bare details!
90     return "http://" . $bloginfo->domain . $bloginfo->path;
91 }
92
93 function get_blogaddress_by_name( $blogname ) {
94     global $hostname, $domain, $base, $wpdb;
95
96     if( defined( "VHOST" ) && constant( "VHOST" ) == 'yes' ) {
97         if( $blogname == 'main' )
98             $blogname = 'www';
99         return "http://".$blogname.".".$domain.$base;
100     } else {
101         return "http://".$hostname.$base.$blogname;
102     }
103 }
104
105 function get_blogaddress_by_domain( $domain, $path ){
106     if( defined( "VHOST" ) && constant( "VHOST" ) == 'yes' ) {
107         $url = "http://".$domain.$path;
108     } else {
109         if( $domain != $_SERVER[ 'HTTP_HOST' ] ) {
110             $blogname = substr( $domain, 0, strpos( $domain, '.' ) );
111             if( $blogname != 'www.' ) {
112                 $url = 'http://' . substr( $domain, strpos( $domain, '.' ) + 1 ) . $path . $blogname . '/';
113             } else { // we're installing the main blog
114                 $url = 'http://' . substr( $domain, strpos( $domain, '.' ) + 1 ) . $path;
115             }
116         } else { // main blog
117             $url = 'http://' . $domain . $path;
118         }
119     }
120
121     return $url;
122 }
123
124 function get_sitestats() {
125     global $wpdb, $basedomain, $base;
126
127     $stats[ 'blogs' ] = get_blog_count();
128
129     $count_ts = get_site_option( "get_user_count_ts" );
130     if( time() - $count_ts > 3600 ) {
131         $count = $wpdb->get_var( "SELECT count(*) as c FROM {$wpdb->users}" );
132         update_site_option( "user_count", $count );
133         update_site_option( "user_count_ts", time() );
134     } else {
135         $count = get_site_option( "user_count" );
136     }
137     $stats[ 'users' ] = $count;
138
139     return $stats;
140 }
141
142 function get_admin_users_for_domain( $sitedomain = '', $path = '' ) {
143     global $domain, $base, $basedomain, $wpdb, $wpmuBaseTablePrefix;
144     if( $sitedomain == '' ) {
145         $sitedomain = $basedomain;
146         $path = $base;
147         $site_id = $wpdb->siteid;
148     } else {
149         $query = "SELECT id FROM ".$wpdb->site." WHERE domain = '".$sitedomain."' AND path = '".$path."'";
150         $site_id = $wpdb->get_var( $query );
151     }
152     if( $site_id != false ) {
153         $query = "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."'";
154         $details = $wpdb->get_results( $query, ARRAY_A );
155     } else {
156         $details = false;
157     }
158
159     return $details;
160 }
161
162 function get_user_details( $username ) {
163     global $wpdb;
164
165     return $wpdb->get_row( "SELECT * FROM $wpdb->users WHERE user_login = '$username'" );
166 }
167
168 function get_blog_details( $id, $all = true ) {
169     global $wpdb;
170
171     $details = wp_cache_get( $id, 'blog-details' );
172
173     if ( $details ) {
174         if ( $details == -1 )
175             return false;
176         elseif ( !is_object($details) ) // Clear old pre-serialized objects. Cache clients do better with that.
177             wp_cache_delete( $id, 'blog-details' );
178         else
179             return $details;
180     }
181
182     $details = $wpdb->get_row( "SELECT * FROM $wpdb->blogs WHERE blog_id = '$id' /* get_blog_details */" );
183
184     if ( !$details ) {
185         wp_cache_set( $id, -1, 'blog-details' );
186         return false;
187     }
188
189     if( $all == true ) {
190         $wpdb->hide_errors();
191         $details->blogname   = get_blog_option($id, 'blogname');
192         $details->siteurl    = get_blog_option($id, 'siteurl');
193         $details->post_count = get_blog_option($id, 'post_count');
194         $wpdb->show_errors();
195
196         wp_cache_add( $id, serialize( $details ), 'blog-details' );
197
198         $key = md5( $details->domain . $details->path );
199         wp_cache_add( $key, serialize( $details ), 'blog-lookup' );
200     }
201
202     return $details;
203 }
204
205 function refresh_blog_details( $id ) {
206     global $wpdb, $wpmuBaseTablePrefix;
207
208     $details = get_blog_details( $id );
209     wp_cache_delete( $id , 'blog-details' );
210
211     $key = md5( $details->domain . $details->path );
212     wp_cache_delete( $key , 'blog-lookup' );
213
214     //return $details;
215 }
216
217 function get_current_user_id() {
218     global $current_user;
219     return $current_user->ID;
220 }
221
222 function is_site_admin( $user_login = false ) {
223     global $wpdb, $current_user;
224
225     if ( !$current_user && !$user_login )
226         return false;
227
228     if ( $user_login )
229         $user_login = sanitize_user( $user_login );
230     else
231         $user_login = $current_user->user_login;
232
233     $site_admins = get_site_option( 'site_admins', array('admin') );
234     if( is_array( $site_admins ) && in_array( $user_login, $site_admins ) )
235         return true;
236
237     return false;
238 }
239
240 // expects key not to be SQL escaped
241 function get_site_option( $key, $default = false, $use_cache = true ) {
242     global $wpdb;
243
244     $safe_key = $wpdb->escape( $key );
245
246     if( $use_cache == true ) {
247         $value = wp_cache_get($wpdb->siteid . $key, 'site-options');
248     } else {
249         $value = false;
250     }
251
252     if ( false === $value ) {
253         $value = $wpdb->get_var("SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = '$safe_key' AND site_id = '{$wpdb->siteid}'");
254         if ( ! is_null($value) ) {
255             wp_cache_add($wpdb->siteid . $key, $value, 'site-options');
256         } elseif ( $default ) {
257             wp_cache_add($wpdb->siteid . $key, addslashes( $default ), 'site-options');
258             return $default;
259         } else {
260             wp_cache_add($wpdb->siteid . $key, false, 'site-options');
261             return false;
262         }
263     }
264
265     $value = stripslashes( $value );
266     @ $kellogs = unserialize($value);
267     if ( $kellogs !== FALSE )
268         return $kellogs;
269     else
270         return $value;
271 }
272
273 // expects $key, $value not to be SQL escaped
274 function add_site_option( $key, $value ) {
275     global $wpdb;
276
277     $safe_key = $wpdb->escape( $key );
278
279     $exists = $wpdb->get_row("SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = '$safe_key' AND site_id = '{$wpdb->siteid}'");
280
281     if ( null !== $exists ) {// If we already have it
282         update_site_option( $key, $value );
283         return false;
284     }
285
286     if ( is_array($value) || is_object($value) )
287         $value = serialize($value);
288     wp_cache_delete($wpdb->siteid . $key, 'site-options');
289     $wpdb->query( "INSERT INTO $wpdb->sitemeta ( site_id , meta_key , meta_value ) VALUES ( '{$wpdb->siteid}', '$safe_key', '" . $wpdb->escape( $value ) . "')" );
290     return $wpdb->insert_id;
291 }
292
293 // expects $key, $value not to be SQL escaped
294 function update_site_option( $key, $value ) {
295     global $wpdb;
296
297     if ( $value == get_site_option( $key ) )
298          return;
299
300     if ( get_site_option( $key, false, false ) === false )
301         add_site_option( $key, $value );
302
303     if ( is_array($value) || is_object($value) )
304         $value = serialize($value);
305
306     $safe_key = $wpdb->escape( $key );
307
308     $wpdb->query( "UPDATE $wpdb->sitemeta SET meta_value = '" . $wpdb->escape( $value ) . "' WHERE site_id='{$wpdb->siteid}' AND meta_key = '$safe_key'" );
309     wp_cache_delete( $wpdb->siteid . $key, 'site-options' );
310 }
311
312 /*
313 function get_blog_option( $id, $key, $default='na' ) {
314     switch_to_blog($id);
315     $opt = get_option( $key );
316     restore_current_blog();
317
318     return $opt;
319 }
320 */
321
322 function get_blog_option( $blog_id, $setting, $default='na' ) {
323     global $wpdb, $wpmuBaseTablePrefix;
324
325     $key = $blog_id."-".$setting."-blog_option";
326     $value = wp_cache_get( $key, "site-options" );
327     if( $value == null ) {
328         $row = $wpdb->get_row( "SELECT * FROM {$wpmuBaseTablePrefix}{$blog_id}_options WHERE option_name = '{$setting}'" );
329         if( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
330             $value = $row->option_value;
331             if( $value == false )
332                 $value = 'falsevalue';
333             wp_cache_set($key, $value, 'site-options');
334         } else { // option does not exist, so we must cache its non-existence
335             wp_cache_set($key, 'noop', 'site-options');
336         }
337     } elseif( $value == 'noop' ) {
338         return false;
339     } elseif( $value == 'falsevalue' ) {
340         return false;
341     }
342     // If home is not set use siteurl.
343     if ( 'home' == $setting && '' == $value )
344         return get_blog_option($blog_id, 'siteurl');
345
346     if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
347         $value = preg_replace('|/+$|', '', $value);
348
349     if (! unserialize($value) )
350         $value = stripslashes( $value );
351
352     return apply_filters( 'option_' . $setting, maybe_unserialize($value) );
353 }
354
355 function add_blog_option( $id, $key, $value ) {
356     switch_to_blog($id);
357     add_option( $key, $value );
358     restore_current_blog();
359     $opt = $id."-".$key."-blog_option";
360     wp_cache_set($opt, $value, 'site-options');
361 }
362
363 function delete_blog_option( $id, $key ) {
364     switch_to_blog($id);
365     delete_option( $key );
366     restore_current_blog();
367     $opt = $id."-".$key."-blog_option";
368     wp_cache_set($opt, '', 'site-options');
369 }
370
371 function update_blog_option( $id, $key, $value, $refresh = true ) {
372     switch_to_blog($id);
373     $opt = update_option( $key, $value );
374     restore_current_blog();
375     if( $refresh == true )
376         refresh_blog_details( $id );
377     $opt = $id."-".$key."-blog_option";
378     wp_cache_set($opt, $value, 'site-options');
379 }
380
381 function switch_to_blog( $new_blog ) {
382     global $tmpoldblogdetails, $wpdb, $wpmuBaseTablePrefix, $table_prefix, $blog_id, $switched, $switched_stack, $wp_roles, $current_user;
383
384     if ( empty($new_blog) )
385         $new_blog = $blog_id;
386
387     if ( empty($switched_stack) )
388         $switched_stack = array();
389
390     $switched_stack[] = $blog_id;
391
392     // backup
393     $tmpoldblogdetails[ 'blogid' ]         = $wpdb->blogid;
394     $tmpoldblogdetails[ 'posts' ]          = $wpdb->posts;
395     $tmpoldblogdetails[ 'categories' ]     = $wpdb->categories;
396     $tmpoldblogdetails[ 'post2cat' ]       = $wpdb->post2cat;
397     $tmpoldblogdetails[ 'comments' ]       = $wpdb->comments;
398     $tmpoldblogdetails[ 'links' ]          = $wpdb->links;
399     $tmpoldblogdetails[ 'link2cat' ]       = $wpdb->link2cat;
400     $tmpoldblogdetails[ 'linkcategories' ] = $wpdb->linkcategories;
401     $tmpoldblogdetails[ 'options' ]         = $wpdb->options;
402     $tmpoldblogdetails[ 'postmeta' ]       = $wpdb->postmeta;
403     $tmpoldblogdetails[ 'prefix' ]         = $wpdb->prefix;
404     $tmpoldblogdetails[ 'table_prefix' ] = $table_prefix;
405     $tmpoldblogdetails[ 'blog_id' ] = $blog_id;
406
407     // fix the new prefix.
408     $table_prefix = $wpmuBaseTablePrefix . $new_blog . "_";
409     $wpdb->prefix            = $table_prefix;
410     $wpdb->blogid           = $new_blog;
411     $wpdb->posts            = $table_prefix . 'posts';
412     $wpdb->categories       = $table_prefix . 'categories';
413     $wpdb->post2cat         = $table_prefix . 'post2cat';
414     $wpdb->comments         = $table_prefix . 'comments';
415     $wpdb->links            = $table_prefix . 'links';
416     $wpdb->link2cat         = $table_prefix . 'link2cat';
417     $wpdb->linkcategories   = $table_prefix . 'linkcategories';
418     $wpdb->options          = $table_prefix . 'options';
419     $wpdb->postmeta         = $table_prefix . 'postmeta';
420     $blog_id = $new_blog;
421
422     if( is_object( $wp_roles ) ) {
423         $wpdb->hide_errors();
424         $wp_roles->_init();
425         $wpdb->show_errors();
426     }
427     if ( is_object( $current_user ) ) {
428         $current_user->_init_caps();
429     }
430
431     do_action('switch_blog', $blog_id, $tmpoldblogdetails[ 'blog_id' ]);
432
433     $switched = true;
434 }
435
436 function restore_current_blog() {
437     global $table_prefix, $tmpoldblogdetails, $wpdb, $wpmuBaseTablePrefix, $blog_id, $switched, $switched_stack, $wp_roles, $current_user;
438
439     if ( !$switched )
440         return;
441
442     $blog = array_pop($switched_stack);
443
444     if ( $blog_id == $blog )
445         return;
446
447     // backup
448     $wpdb->blogid = $tmpoldblogdetails[ 'blogid' ];
449     $wpdb->posts = $tmpoldblogdetails[ 'posts' ];
450     $wpdb->categories = $tmpoldblogdetails[ 'categories' ];
451     $wpdb->post2cat = $tmpoldblogdetails[ 'post2cat' ];
452     $wpdb->comments = $tmpoldblogdetails[ 'comments' ];
453     $wpdb->links = $tmpoldblogdetails[ 'links' ];
454     $wpdb->link2cat = $tmpoldblogdetails[ 'link2cat' ];
455     $wpdb->linkcategories = $tmpoldblogdetails[ 'linkcategories' ];
456     $wpdb->options = $tmpoldblogdetails[ 'options' ];
457     $wpdb->postmeta = $tmpoldblogdetails[ 'postmeta' ];
458     $wpdb->prefix = $tmpoldblogdetails[ 'prefix' ];
459     $table_prefix = $tmpoldblogdetails[ 'table_prefix' ];
460     $prev_blog_id = $blog_id;
461     $blog_id = $tmpoldblogdetails[ 'blog_id' ];
462     unset( $tmpoldblogdetails );
463
464     if( is_object( $wp_roles ) ) {
465         $wpdb->hide_errors();
466         $wp_roles->_init();
467         $wpdb->show_errors();
468     }
469     if ( is_object( $current_user ) ) {
470         $current_user->_init_caps();
471     }
472     do_action('switch_blog', $blog_id, $prev_blog_id);
473
474     $switched = false;
475 }
476
477 function get_blogs_of_user( $id, $all = false ) {
478     global $wpdb, $wpmuBaseTablePrefix;
479
480     $user = get_userdata( $id );
481
482     if ( !$user )
483         return false;
484
485     $blogs = array();
486
487     $i = 0;
488     foreach ( $user as $key => $value ) {
489         if ( strstr( $key, '_capabilities') && strstr( $key, 'wp_') ) {
490             preg_match('/' . $wpmuBaseTablePrefix . '(\d+)_capabilities/', $key, $match);
491             $blog = get_blog_details( $match[1] );
492             if ( $blog && isset( $blog->domain ) && ( $all == true || $all == false && ( $blog->archived == 0 && $blog->spam == 0 && $blog->deleted == 0 ) ) ) {
493                 $blogs[$match[1]]->userblog_id = $match[1];
494                 $blogs[$match[1]]->blogname    = $blog->blogname;
495                 $blogs[$match[1]]->domain      = $blog->domain;
496                 $blogs[$match[1]]->path        = $blog->path;
497                 $blogs[$match[1]]->site_id     = $blog->site_id;
498                 $blogs[$match[1]]->siteurl     = $blog->siteurl;
499             }
500         }
501     }
502
503     return $blogs;
504 }
505
506 function get_active_blog_for_user( $user_id ) { // get an active blog for user - either primary blog or from blogs list
507     $primary_blog = get_usermeta( $user_id, "primary_blog" );
508     if( $primary_blog == false ) {
509         $details = false;
510     } else {
511         $details = get_blog_details( $primary_blog );
512     }
513
514     if( ( is_object( $details ) == false ) || ( is_object( $details ) && $details->archived == 1 || $details->spam == 1 || $details->deleted == 1 ) ) {
515         $blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs.
516         $ret = false;
517         if( is_array( $blogs ) && count( $blogs ) > 0 ) {
518             foreach( $blogs as $blog_id => $blog ) {
519                 $details = get_blog_details( $blog_id );
520                 if( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) {
521                     $ret = $blog;
522                     break;
523                 }
524             }
525         } else {
526             $ret = "username only"; // user has no blogs. We can add details for dashboard.wordpress.com here.
527         }
528         return $ret;
529     } else {
530         return $details;
531     }
532 }
533
534 function is_user_member_of_blog( $user_id, $blog_id = 0 ) {
535     global $wpdb;
536     if( $blog_id == 0 )
537         $blog_id = $wpdb->blogid;
538
539     $blogs = get_blogs_of_user( $user_id );
540     if( is_array( $blogs ) ) {
541         return array_key_exists( $blog_id, $blogs );
542     } else {
543         return false;
544     }
545 }
546
547 function is_archived( $id ) {
548     return get_blog_status($id, 'archived');
549 }
550
551 function update_archived( $id, $archived ) {
552     update_blog_status($id, 'archived', $archived);
553
554     return $archived;
555 }
556
557 function update_blog_status( $id, $pref, $value, $refresh = 1 ) {
558     global $wpdb;
559
560     $wpdb->query( "UPDATE {$wpdb->blogs} SET {$pref} = '{$value}', last_updated = NOW() WHERE blog_id = '$id'" );
561
562     if( $refresh == 1 )
563         refresh_blog_details($id);
564
565     if( $pref == 'spam' ) {
566         if( $value == 1 ) {
567             do_action( "make_spam_blog", $id );
568         } else {
569             do_action( "make_ham_blog", $id );
570         }
571     }
572
573     return $value;
574 }
575
576 function get_blog_status( $id, $pref ) {
577     global $wpdb;
578
579     $details = get_blog_details( $id, false );
580     if( $details ) {
581         return $details->$pref;
582     }
583
584     return $wpdb->get_var( "SELECT $pref FROM {$wpdb->blogs} WHERE blog_id = '$id'" );
585 }
586
587 function get_last_updated( $display = false ) {
588     global $wpdb;
589     $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' AND last_updated != '0000-00-00 00:00:00' ORDER BY last_updated DESC limit 0,40", ARRAY_A );
590
591     return $blogs;
592 }
593
594 function get_most_active_blogs( $num = 10, $display = true ) {
595     global $wpdb;
596     $most_active = get_site_option( "most_active" );
597     $update = false;
598     if( is_array( $most_active ) ) {
599         if( ( $most_active[ 'time' ] + 60 ) < time() ) { // cache for 60 seconds.
600             $update = true;
601         }
602     } else {
603         $update = true;
604     }
605
606     if( $update == true ) {
607         unset( $most_active );
608         $blogs = get_blog_list( 0, 'all', false ); // $blog_id -> $details
609         if( is_array( $blogs ) ) {
610             reset( $blogs );
611             while( list( $key, $details ) = each( $blogs ) ) {
612                 $most_active[ $details[ 'blog_id' ] ] = $details[ 'postcount' ];
613                 $blog_list[ $details[ 'blog_id' ] ] = $details; // array_slice() removes keys!!
614             }
615             arsort( $most_active );
616             reset( $most_active );
617             while( list( $key, $details ) = each( $most_active ) ) {
618                 $t[ $key ] = $blog_list[ $key ];
619             }
620             unset( $most_active );
621             $most_active = $t;
622         }
623         update_site_option( "most_active", $most_active );
624     }
625
626     if( $display == true ) {
627         if( is_array( $most_active ) ) {
628             reset( $most_active );
629             while( list( $key, $details ) = each( $most_active ) ) {
630                 $url = "http://" . $details[ 'domain' ] . $details[ 'path' ];
631                 print "<li>" . $details[ 'postcount' ] . " <a href='$url'>$url</a></li>";
632             }
633         }
634     }
635
636     return array_slice( $most_active, 0, $num );
637 }
638
639 function get_blog_list( $start = 0, $num = 10, $display = true ) {
640     global $wpdb, $wpmuBaseTablePrefix;
641
642     $blogs = get_site_option( "blog_list" );
643     $update = false;
644     if( is_array( $blogs ) ) {
645         if( ( $blogs[ 'time' ] + 60 ) < time() ) { // cache for 60 seconds.
646             $update = true;
647         }
648     } else {
649         $update = true;
650     }
651
652     if( $update == true ) {
653         unset( $blogs );
654         $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 );
655         if( is_array( $blogs ) ) {
656             while( list( $key, $details ) = each( $blogs ) ) {
657                 $blog_list[ $details[ 'blog_id' ] ] = $details;
658                 $blog_list[ $details[ 'blog_id' ] ][ 'postcount' ] = $wpdb->get_var( "SELECT count(*) FROM " . $wpmuBaseTablePrefix . $details[ 'blog_id' ] . "_posts WHERE post_status='publish' AND post_type='post'" );
659             }
660             unset( $blogs );
661             $blogs = $blog_list;
662         }
663         update_site_option( "blog_list", $blogs );
664     }
665
666     if( $num == 'all' ) {
667         return array_slice( $blogs, $start, count( $blogs ) );
668     } else {
669         return array_slice( $blogs, $start, $num );
670     }
671 }
672
673 function get_blog_count( $id = 0 ) {
674     global $wpdb;
675
676     if( $id == 0 )
677         $id = $wpdb->siteid;
678
679     $count_ts = get_site_option( "blog_count_ts" );
680     if( time() - $count_ts > 3600 ) {
681         $count = $wpdb->get_var( "SELECT count(*) as c FROM $wpdb->blogs WHERE site_id = '$id' AND spam='0' AND deleted='0' and archived='0'" );
682         update_site_option( "blog_count", $count );
683         update_site_option( "blog_count_ts", time() );
684     }
685
686     $count = get_site_option( "blog_count" );
687
688     return $count;
689 }
690
691 function get_blog_post( $blog_id, $post_id ) {
692     global $wpdb, $wpmuBaseTablePrefix;
693
694     $key = $blog_id."-".$post_id."-blog_post";
695     $post = wp_cache_get( $key, "site-options" );
696     if( $post == false ) {
697         $post = $wpdb->get_row( "SELECT * FROM {$wpmuBaseTablePrefix}{$blog_id}_posts WHERE ID = '{$post_id}'" );
698         wp_cache_add( $key, $post, "site-options", 120 );
699     }
700
701     return $post;
702
703 }
704
705 function add_user_to_blog( $blog_id, $user_id, $role ) {
706     switch_to_blog($blog_id);
707
708     $user = new WP_User($user_id);
709
710     if ( empty($user) )
711         return new WP_Error('user_does_not_exist', __('That user does not exist.'));
712
713     if ( !get_usermeta($user_id, 'primary_blog') ) {
714         update_usermeta($user_id, 'primary_blog', $blog_id);
715         $details = get_blog_details($blog_id);
716         update_usermeta($user_id, 'source_domain', $details->domain);
717     }
718
719     $user->set_role($role);
720
721     do_action('add_user_to_blog', $user_id, $role, $blog_id);
722
723     wp_cache_delete( $user_id, 'users' );
724
725     restore_current_blog();
726 }
727
728 function remove_user_from_blog($user_id, $blog_id = '') {
729     global $wpdb;
730
731     switch_to_blog($blog_id);
732
733     $user_id = (int) $user_id;
734
735     do_action('remove_user_from_blog', $user_id, $blog_id);
736
737     // If being removed from the primary blog, set a new primary if the user is assigned
738     // to multiple blogs.
739     $primary_blog = get_usermeta($user_id, 'primary_blog');
740     if ( $primary_blog == $blog_id ) {
741         $new_id = '';
742         $new_domain = '';
743         $blogs = get_blogs_of_user($user_id);
744         if ( count($blogs) > 1 ) {
745             foreach ( $blogs as $blog ) {
746                 if ( $blog->userblog_id == $blog_id )
747                     continue;
748                  $new_id = $blog->userblog_id;
749                  $new_domain = $blog->domain;
750                  break;
751             }
752         }
753         update_usermeta($user_id, 'primary_blog', $new_id);
754         update_usermeta($user_id, 'source_domain', $new_domain);
755     }
756
757     wp_revoke_user($user_id);
758
759     $blogs = get_blogs_of_user($user_id);
760     if ( count($blogs) == 0 ) {
761         update_usermeta($user_id, 'primary_blog', '');
762         update_usermeta($user_id, 'source_domain', '');
763     }
764
765     restore_current_blog();
766 }
767
768 function create_empty_blog( $domain, $path, $weblog_title, $site_id = 1 ) {
769     global $wpdb, $table_prefix, $wp_queries, $wpmuBaseTablePrefix, $current_site;
770
771     $domain       = addslashes( $domain );
772     $weblog_title = addslashes( $weblog_title );
773
774     if( empty($path) )
775         $path = '/';
776
777     // Check if the domain has been used already. We should return an error message.
778     if ( domain_exists($domain, $path, $site_id) )
779         return 'error: Blog URL already taken.';
780
781     // Need to backup wpdb table names, and create a new wp_blogs entry for new blog.
782     // Need to get blog_id from wp_blogs, and create new table names.
783     // Must restore table names at the end of function.
784
785     if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
786         return "error: problem creating blog entry";
787
788     switch_to_blog($blog_id);
789
790     install_blog($blog_id);
791
792     restore_current_blog();
793
794     return true;
795 }
796
797 function get_blog_permalink( $blog_id, $post_id ) {
798     global $wpdb, $cache_settings;
799
800     $key = "{$blog_id}-{$post_id}-blog_permalink";
801     $link = wp_cache_get( $key, 'site-options' );
802     if( $link == false ) {
803         switch_to_blog( $blog_id );
804         $link = get_permalink( $post_id );
805         restore_current_blog();
806         wp_cache_add( $key, $link, "site-options", 30 );
807     }
808     return $link;
809 }
810
811 // wpmu admin functions
812
813 function wpmu_admin_do_redirect( $url = '' ) {
814     if( $_REQUEST[ 'ref' ] ) {
815         $ref = $_REQUEST[ 'ref' ];
816         $ref = wpmu_admin_redirect_add_updated_param( $_REQUEST[ 'ref' ] );
817         header( "Location: {$ref}" );
818         die();
819     }
820     if( empty( $_SERVER[ 'HTTP_REFERER' ] ) == false ) {
821         wp_redirect( $_SERVER[ 'HTTP_REFERER' ] );
822         die();
823     }
824
825     $url = wpmu_admin_redirect_add_updated_param( $url );
826     if( isset( $_GET[ 'redirect' ] ) ) {
827         if( substr( $_GET[ 'redirect' ], 0, 2 ) == 's_' ) {
828             $url .= "&action=blogs&s=". wp_specialchars( substr( $_GET[ 'redirect' ], 2 ) );
829         }
830     } elseif( isset( $_POST[ 'redirect' ] ) ) {
831         $url = wpmu_admin_redirect_add_updated_param( $_POST[ 'redirect' ] );
832     }
833     header( "Location: {$url}" );
834     die();
835 }
836 function wpmu_admin_redirect_add_updated_param( $url = '' ) {
837     if( strpos( $url, 'updated=true' ) === false ) {
838         if( strpos( $url, '?' ) === false ) {
839             return $url . '?updated=true';
840         } else {
841             return $url . '&updated=true';
842         }
843     }
844     return $url;
845 }
846
847 function wpmu_admin_redirect_url() {
848     if( isset( $_GET[ 's' ] ) ) {
849         return "s_".$_GET[ 's' ];
850     }
851 }
852
853 function is_blog_user( $blog_id = 0 ) {
854     global $current_user, $wpdb, $wpmuBaseTablePrefix;
855
856     if ( !$blog_id )
857         $blog_id = $wpdb->blogid;
858
859     $cap_key = $wpmuBaseTablePrefix . $blog_id . '_capabilities';
860
861     if ( is_array($current_user->$cap_key) && in_array(1, $current_user->$cap_key) )
862         return true;
863
864     return false;
865 }
866
867 function validate_email( $email, $check_domain = true) {
868     if (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.'@'.
869         '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
870         '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $email))
871     {
872         if ($check_domain && function_exists('checkdnsrr')) {
873             list (, $domain)  = explode('@', $email);
874
875             if (checkdnsrr($domain.'.', 'MX') || checkdnsrr($domain.'.', 'A')) {
876                 return true;
877             }
878             return false;
879         }
880         return true;
881     }
882     return false;
883 }
884
885 function is_email_address_unsafe( $user_email ) {
886     $banned_names = get_site_option( "banned_email_domains" );
887     if ( is_array( $banned_names ) && empty( $banned_names ) == false ) {
888         $email_domain = strtolower( substr( $user_email, 1 + strpos( $user_email, '@' ) ) );
889         foreach( $banned_names as $banned_domain ) {
890             if( $banned_domain == '' )
891                 continue;
892             if (
893                 strstr( $email_domain, $banned_domain ) ||
894                 (
895                     strstr( $banned_domain, '/' ) &&
896                     preg_match( $banned_domain, $email_domain )
897                 )
898             )
899             return true;
900         }
901     }
902     return false;
903 }
904
905 function wpmu_validate_user_signup($user_name, $user_email) {
906     global $wpdb, $current_site;
907
908     $errors = new WP_Error();
909
910     $user_name = sanitize_title($user_name);
911
912     if ( empty( $user_name ) )
913            $errors->add('user_name', __("Please enter a username"));
914
915     preg_match( "/[a-zA-Z0-9]+/", $user_name, $maybe );
916
917     if( $user_name != $maybe[0] ) {
918         $errors->add('user_name', __("Only letters and numbers allowed"));
919     }
920
921     $illegal_names = get_site_option( "illegal_names" );
922     if( is_array( $illegal_names ) == false ) {
923         $illegal_names = array(  "www", "web", "root", "admin", "main", "invite", "administrator" );
924         add_site_option( "illegal_names", $illegal_names );
925     }
926     if( in_array( $user_name, $illegal_names ) == true ) {
927         $errors->add('user_name'__("That username is not allowed"));
928     }
929
930     if( is_email_address_unsafe( $user_email ) )
931         $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."));
932
933     if( strlen( $user_name ) < 4 ) {
934         $errors->add('user_name'__("Username must be at least 4 characters"));
935     }
936
937     if ( strpos( " " . $user_name, "_" ) != false )
938         $errors->add('user_name', __("Sorry, usernames may not contain the character '_'!"));
939
940     // all numeric?
941     preg_match( '/[0-9]*/', $user_name, $match );
942     if ( $match[0] == $user_name )
943         $errors->add('user_name', __("Sorry, usernames must have letters too!"));
944
945     if ( !is_email( $user_email ) )
946         $errors->add('user_email', __("Please enter a correct email address"));
947
948     if ( !validate_email( $user_email ) )
949         $errors->add('user_email', __("Please check your email address."));
950
951     $limited_email_domains = get_site_option( 'limited_email_domains' );
952     if ( is_array( $limited_email_domains ) && empty( $limited_email_domains ) == false ) {
953         $emaildomain = substr( $user_email, 1 + strpos( $user_email, '@' ) );
954         if( in_array( $emaildomain, $limited_email_domains ) == false ) {
955             $errors->add('user_email', __("Sorry, that email address is not allowed!"));
956         }
957     }
958
959     // Check if the username has been used already.
960     if ( username_exists($user_name) )
961         $errors->add('user_name', __("Sorry, that username already exists!"));
962
963     // Check if the email address has been used already.
964     if ( email_exists($user_email) )
965         $errors->add('user_email', __("Sorry, that email address is already used!"));
966
967     // Has someone already signed up for this username?
968     $signup = $wpdb->get_row("SELECT * FROM $wpdb->signups WHERE user_login = '$user_name'");
969     if ( $signup != null ) {
970         $registered_at mysql2date('U', $signup->registered);
971         $now = current_time( 'timestamp', true );
972         $diff = $now - $registered_at;
973         // If registered more than two days ago, cancel registration and let this signup go through.
974         if ( $diff > 172800 ) {
975             $wpdb->query("DELETE FROM $wpdb->signups WHERE user_login = '$user_name'");
976         } else {
977             $errors->add('user_name', __("That username is currently reserved but may be available in a couple of days."));
978         }
979         if( $signup->active == 0 && $signup->user_email == $user_email )
980             $errors->add('user_email_used', __("username and email used"));
981     }
982
983     $signup = $wpdb->get_row("SELECT * FROM $wpdb->signups WHERE user_email = '$user_email'");
984     if ( $signup != null ) {
985         $registered_at mysql2date('U', $signup->registered);
986         $now = current_time( 'timestamp', true );
987         $diff = $now - $registered_at;
988         // If registered more than two days ago, cancel registration and let this signup go through.
989         if ( $diff > 172800 ) {
990             $wpdb->query("DELETE FROM $wpdb->signups WHERE user_email = '$user_email'");
991         } else {
992             $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."));
993         }
994     }
995
996     $result = array('user_name' => $user_name, 'user_email' => $user_email,    'errors' => $errors);
997
998     return apply_filters('wpmu_validate_user_signup', $result);
999 }
1000
1001 function wpmu_validate_blog_signup($blog_id, $blog_title, $user = '') {
1002     global $wpdb, $domain, $base;
1003
1004     $errors = new WP_Error();
1005     $illegal_names = get_site_option( "illegal_names" );
1006     if( $illegal_names == false ) {
1007         $illegal_names = array( "www", "web", "root", "admin", "main", "invite", "administrator" );
1008         add_site_option( "illegal_names", $illegal_names );
1009     }
1010
1011     $blog_id = sanitize_title($blog_id);
1012
1013     if ( empty( $blog_id ) )
1014         $errors->add('blog_id', __("Please enter a blog name"));
1015
1016     preg_match( "/[a-zA-Z0-9]+/", $blog_id, $maybe );
1017     if( $blog_id != $maybe[0] ) {
1018         $errors->add('blog_id', __("Only letters and numbers allowed"));
1019     }
1020     if( in_array( $blog_id, $illegal_names ) == true ) {
1021         $errors->add('blog_id'__("That name is not allowed"));
1022     }
1023     if( strlen( $blog_id ) < 4 ) {
1024         $errors->add('blog_id'__("Blog name must be at least 4 characters"));
1025     }
1026
1027     if ( strpos( " " . $blog_id, "_" ) != false )
1028         $errors->add('blog_id', __("Sorry, blog names may not contain the character '_'!"));
1029
1030     // all numeric?
1031     preg_match( '/[0-9]*/', $blog_id, $match );
1032     if ( $match[0] == $blog_id )
1033         $errors->add('blog_id', __("Sorry, blog names must have letters too!"));
1034
1035     $blog_id = apply_filters( "newblog_id", $blog_id );
1036
1037     $blog_title = stripslashes$blog_title );
1038
1039     if ( empty( $blog_title ) )
1040         $errors->add('blog_title', __("Please enter a blog title"));
1041
1042     // Check if the domain/path has been used already.
1043     if( constant( "VHOST" ) == 'yes' ) {
1044         $mydomain = "$blog_id.$domain";
1045         $path = $base;
1046     } else {
1047         $mydomain = "$domain";
1048         $path = $base.$blog_id.'/';
1049     }
1050     if ( domain_exists($mydomain, $path) )
1051         $errors->add('blog_id', __("Sorry, that blog already exists!"));
1052
1053     if ( username_exists($blog_id) ) {
1054         if  ( !is_object($user) && ( $user->user_login != $blog_id ) )
1055             $errors->add('blog_id', __("Sorry, that blog is reserved!"));
1056     }
1057
1058     // Has someone already signed up for this domain?
1059     // TODO: Check email too?
1060     $signup = $wpdb->get_row("SELECT * FROM $wpdb->signups WHERE domain = '$mydomain' AND path = '$path'");
1061     if ( ! empty($signup) ) {
1062         $registered_at mysql2date('U', $signup->registered);
1063         $now = current_time( 'timestamp', true );
1064         $diff = $now - $registered_at;
1065         // If registered more than two days ago, cancel registration and let this signup go through.
1066         if ( $diff > 172800 ) {
1067             $wpdb->query("DELETE FROM $wpdb->signups WHERE domain = '$mydomain' AND path = '$path'");
1068         } else {
1069             $errors->add('blog_id', __("That blog is currently reserved but may be available in a couple days."));
1070         }
1071     }
1072
1073     $result = array('domain' => $mydomain, 'path' => $path, 'blog_id' => $blog_id, 'blog_title' => $blog_title,
1074                 'errors' => $errors);
1075
1076     return apply_filters('wpmu_validate_blog_signup', $result);
1077 }
1078
1079 // Record signup information for future activation. wpmu_validate_signup() should be run
1080 // on the inputs before calling wpmu_signup().
1081 function wpmu_signup_blog($domain, $path, $title, $user, $user_email, $meta = '') {
1082     global $wpdb;
1083
1084     $key = substr( md5( time() . rand() . $domain ), 0, 16 );
1085     $registered = current_time('mysql', true);
1086     $meta = serialize($meta);
1087     $domain = $wpdb->escape($domain);
1088     $path = $wpdb->escape($path);
1089     $title = $wpdb->escape($title);
1090     $wpdb->query( "INSERT INTO $wpdb->signups ( domain, path, title, user_login, user_email, registered, activation_key, meta )
1091                     VALUES ( '$domain', '$path', '$title', '$user', '$user_email', '$registered', '$key', '$meta' )" );
1092
1093     wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta);
1094 }
1095
1096 function wpmu_signup_user($user, $user_email, $meta = '') {
1097     global $wpdb;
1098
1099     $key = substr( md5( time() . rand() . $user_email ), 0, 16 );
1100     $registered = current_time('mysql', true);
1101     $meta = serialize($meta);
1102     $wpdb->query( "INSERT INTO $wpdb->signups ( domain, path, title, user_login, user_email, registered, activation_key, meta )
1103                     VALUES ( '', '', '', '$user', '$user_email', '$registered', '$key', '$meta' )" );
1104
1105     wpmu_signup_user_notification($user, $user_email, $key, $meta);
1106 }
1107
1108 // Notify user of signup success.
1109 function wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta = '') {
1110     global $current_site;
1111     // Send email with activation link.
1112     if( constant( "VHOST" ) == 'no' ) {
1113         $activate_url = "http://" . $current_site->domain . $current_site->path . "wp-activate.php?key=$key";
1114     } else {
1115         $activate_url = "http://{$domain}{$path}wp-activate.php?key=$key";
1116     }
1117     $admin_email = get_site_option( "admin_email" );
1118     if( $admin_email == '' )
1119         $admin_email = 'support@' . $_SERVER[ 'SERVER_NAME' ];
1120     $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1121     $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1122     $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, "http://{$domain}{$path}");
1123     // TODO: Don't hard code activation link.
1124     $subject = sprintf(__('Activate %s'), $domain.$path);
1125     wp_mail($user_email, $subject, $message, $message_headers);
1126 }
1127
1128 function wpmu_signup_user_notification($user, $user_email, $key, $meta = '') {
1129     global $current_site;
1130     // Send email with activation link.
1131     $admin_email = get_site_option( "admin_email" );
1132     if( $admin_email == '' )
1133         $admin_email = 'support@' . $_SERVER[ 'SERVER_NAME' ];
1134     $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1135     $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1136     $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"), "http://{$current_site->domain}{$current_site->path}wp-activate.php?key=$key" );
1137     // TODO: Don't hard code activation link.
1138     $subject = sprintf(__('Activate %s'), $user);
1139     wp_mail($user_email, $subject, $message, $message_headers);
1140 }
1141
1142 function wpmu_activate_signup($key) {
1143     global $wpdb;
1144
1145     $result = array();
1146     $signup = $wpdb->get_row("SELECT * FROM $wpdb->signups WHERE activation_key = '$key'");
1147
1148     if ( empty($signup) )
1149         return new WP_Error('invalid_key', __('Invalid activation key.'));
1150
1151     if ( $signup->active )
1152         return new WP_Error('already_active', __('The blog is already active.'), $signup);
1153
1154     $meta = unserialize($signup->meta);
1155     $user_login = $wpdb->escape($signup->user_login);
1156     $user_email = $wpdb->escape($signup->user_email);
1157     wpmu_validate_user_signup($user_login, $user_email);
1158     $password = generate_random_password();
1159
1160     $user_id = username_exists($user_login);
1161
1162     if ( ! $user_id )
1163         $user_id = wpmu_create_user($user_login, $password, $user_email);
1164     else
1165         $user_already_exists = true;
1166
1167     if ( ! $user_id )
1168         return new WP_Error('create_user', __('Could not create user'), $signup);
1169
1170     $now = current_time('mysql', true);
1171
1172     if ( empty($signup->domain) ) {
1173         $wpdb->query("UPDATE $wpdb->signups SET active = '1', activated = '$now' WHERE activation_key = '$key'");
1174         if ( isset($user_already_exists) )
1175             return new WP_Error('user_already_exists', __('That username is already activated.'), $signup);
1176         wpmu_welcome_user_notification($user_id, $password, $meta);
1177         add_user_to_blog('1', $user_id, 'subscriber');
1178         do_action('wpmu_activate_user', $user_id, $password, $meta);
1179         return array('user_id' => $user_id, 'password' => $password, 'meta' => $meta);
1180     }
1181
1182     wpmu_validate_blog_signup($signup->domain, $signup->title);
1183     $blog_id = wpmu_create_blog($signup->domain, $signup->path, $signup->title, $user_id, $meta);
1184
1185     // TODO: What to do if we create a user but cannot create a blog?
1186     if ( is_wp_error($blog_id) ) {
1187         // If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and
1188         // setting the activation flag.  Let's just set the active flag and instruct the user to reset their password.
1189         if ( 'blog_taken' == $blog_id->get_error_code() ) {
1190             $blog_id->add_data($signup);
1191             $wpdb->query("UPDATE $wpdb->signups SET active = '1', activated = '$now' WHERE activation_key = '$key'");
1192             error_log("Blog $blog_id failed to complete activation.", 0);   
1193         }
1194
1195         return $blog_id;
1196     }
1197
1198     $wpdb->query("UPDATE $wpdb->signups SET active = '1', activated = '$now' WHERE activation_key = '$key'");
1199
1200     wpmu_welcome_notification($blog_id, $user_id, $password, $signup->title, $meta);
1201
1202     do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta);
1203
1204     return array('blog_id' => $blog_id, 'user_id' => $user_id, 'password' => $password, 'title' => $signup->title, 'meta' => $meta);
1205 }
1206
1207 function generate_random_password() {
1208     $random_password = substr(md5(uniqid(microtime())), 0, 6);
1209     $random_password = apply_filters('random_password', $random_password);
1210     return $random_password;
1211 }
1212
1213 function wpmu_create_user( $user_name, $password, $email) {
1214     if ( username_exists($user_name) )
1215         return false;
1216
1217     // Check if the email address has been used already.
1218     if ( email_exists($email) )
1219         return false;
1220
1221     $user_id = wp_create_user( $user_name, $password, $email );
1222     $user = new WP_User($user_id);
1223     // Newly created users have no roles or caps until they are added to a blog.
1224     update_user_option($user_id, 'capabilities', '');
1225     update_user_option($user_id, 'user_level', '');
1226
1227     do_action( 'wpmu_new_user', $user_id );
1228
1229     return $user_id;
1230 }
1231
1232 function wpmu_create_blog($domain, $path, $title, $user_id, $meta = '', $site_id = 1) {
1233     $domain = addslashes( $domain );
1234     $user_id = (int) $user_id;
1235
1236     if( empty($path) )
1237         $path = '/';
1238
1239     // Check if the domain has been used already. We should return an error message.
1240     if ( domain_exists($domain, $path, $site_id) )
1241         return new WP_Error('blog_taken', __('Blog already exists.'));
1242
1243     // Need to backup wpdb table names, and create a new wp_blogs entry for new blog.
1244     // Need to get blog_id from wp_blogs, and create new table names.
1245     // Must restore table names at the end of function.
1246
1247     if ( !defined("WP_INSTALLING") )
1248         define( "WP_INSTALLING", true );
1249
1250     if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
1251         return new WP_Error('insert_blog', __('Could not create blog.'));
1252
1253     switch_to_blog($blog_id);
1254
1255     install_blog($blog_id, $title);
1256
1257     install_blog_defaults($blog_id, $user_id);
1258
1259     add_user_to_blog($blog_id, $user_id, 'administrator');
1260
1261     restore_current_blog();
1262
1263     if ( is_array($meta) ) foreach ($meta as $key => $value) {
1264         update_blog_status( $blog_id, $key, $value );
1265         update_blog_option( $blog_id, $key, $value );
1266     }
1267
1268     do_action( 'wpmu_new_blog', $blog_id, $user_id );
1269
1270     return $blog_id;
1271 }
1272
1273 function domain_exists($domain, $path, $site_id = 1) {
1274     global $wpdb;
1275     return $wpdb->get_var("SELECT blog_id FROM $wpdb->blogs WHERE domain = '$domain' AND path = '$path' AND site_id = '$site_id'" );
1276 }
1277
1278 function insert_blog($domain, $path, $site_id) {
1279     global $wpdb;
1280     $path = trailingslashit( $path );
1281     $query = "INSERT INTO $wpdb->blogs ( blog_id, site_id, domain, path, registered ) VALUES ( NULL, '$site_id', '$domain', '$path', NOW( ))";
1282     $result = $wpdb->query( $query );
1283     if ( ! $result )
1284         return false;
1285
1286     $id = $wpdb->insert_id;
1287     refresh_blog_details($id);
1288     return $id;
1289 }
1290
1291 // Install an empty blog.  wpdb should already be switched.
1292 function install_blog($blog_id, $blog_title = '') {
1293     global $wpdb, $table_prefix, $wp_roles;
1294     $wpdb->hide_errors();
1295
1296     require_once( ABSPATH . 'wp-admin/upgrade-functions.php');
1297     $installed = $wpdb->get_results("SELECT * FROM $wpdb->posts");
1298     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>');
1299
1300     $url = get_blogaddress_by_id($blog_id);
1301     error_log("install_blog - ID: $blog_id  URL: $url Title: $blog_title ", 0);
1302
1303     // Set everything up
1304     make_db_current_silent();
1305     populate_options();
1306     populate_roles();
1307     $wp_roles->_init();
1308     // fix url.
1309     wp_cache_delete('notoptions', 'options');
1310     wp_cache_delete('alloptions', 'options');
1311     update_option('siteurl', $url);
1312     update_option('home', $url);
1313     update_option('fileupload_url', $url . "files" );
1314     update_option('upload_path', "wp-content/blogs.dir/" . $blog_id . "/files");
1315     update_option('blogname', $blog_title);
1316
1317     $wpdb->query("UPDATE $wpdb->options SET option_value = '' WHERE option_name = 'admin_email'");
1318
1319     // Default category
1320     $wpdb->query("INSERT INTO $wpdb->categories (cat_ID, cat_name, category_nicename, category_count, category_description) VALUES ('0', '".addslashes(__('Uncategorized'))."', '".sanitize_title(__('Uncategorized'))."', 1, '')");
1321     $blogroll_id = $wpdb->get_var( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = 'blogroll'" );
1322     if( $blogroll_id == null ) {
1323         $wpdb->query( "INSERT INTO " . $wpdb->sitecategories . " (cat_ID, cat_name, category_nicename, last_updated) VALUES (0, 'Blogroll', 'blogroll', NOW())" );
1324         $blogroll_id = $wpdb->insert_id;
1325     }
1326     $wpdb->query("INSERT INTO $wpdb->categories (cat_ID, cat_name, category_nicename, link_count, category_description) VALUES ('{$blogroll_id}', '".addslashes(__('Blogroll'))."', '".sanitize_title(__('Blogroll'))."', 2, '')");
1327     $wpdb->query("INSERT INTO $wpdb->link2cat (link_id, category_id) VALUES (1, $blogroll_id)");
1328     $wpdb->query("INSERT INTO $wpdb->link2cat (link_id, category_id) VALUES (2, $blogroll_id)");
1329
1330     // remove all perms
1331     $wpdb->query( "DELETE FROM ".$wpdb->usermeta." WHERE meta_key = '".$table_prefix."user_level'" );
1332     $wpdb->query( "DELETE FROM ".$wpdb->usermeta." WHERE meta_key = '".$table_prefix."capabilities'" );
1333
1334     $wpdb->show_errors();
1335 }
1336
1337 function install_blog_defaults($blog_id, $user_id) {
1338     global $wpdb, $wp_rewrite, $current_site, $table_prefix, $wpmuBaseTablePrefix;
1339
1340     $wpdb->hide_errors();
1341
1342     // Default links
1343     $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_image, link_target, link_category, link_description, link_visible, link_owner, link_rating, link_updated, link_rel, link_notes, link_rss) VALUES ('http://wordpress.com/', 'WordPress.com', '', '', 1, '', 'Y', '$user_id', 0, 0, '', '', 'http://wordpress.com/feed/')");
1344     $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_image, link_target, link_category, link_description, link_visible, link_owner, link_rating, link_updated, link_rel, link_notes, link_rss) VALUES ('http://wordpress.org/', 'WordPress.org', '', '', 1, '', 'Y', '$user_id', 0, 0, '', '', 'http://wordpress.org/development/feed/')");
1345
1346     // First post
1347     $now = date('Y-m-d H:i:s');
1348     $now_gmt = gmdate('Y-m-d H:i:s');
1349     $first_post = get_site_option( 'first_post' );
1350     if( $first_post == false )
1351         $first_post = stripslashes( __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' ) );
1352
1353     $first_post = str_replace( "SITE_URL", "http://" . $current_site->domain . $current_site->path, $first_post );
1354     $first_post = str_replace( "SITE_NAME", $current_site->site_name, $first_post );
1355     $first_post = stripslashes( $first_post );
1356
1357     $wpdb->query("INSERT INTO $wpdb->posts (post_author, post_date, post_date_gmt, post_content, post_title, post_category, post_excerpt, post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_content_filtered, post_parent, guid, menu_order, post_type, post_mime_type, comment_count) VALUES ('".$user_id."', '$now', '$now_gmt', '".addslashes($first_post)."', '".addslashes(__('Hello world!'))."', '0', '', 'publish', 'open', 'open', '', '".addslashes(__('hello-world'))."', to_ping, pinged, '$now', '$now_gmt', '', 0, '', 0, 'post', '', 1)");
1358     $wpdb->query( "INSERT INTO $wpdb->post2cat (`rel_id`, `post_id`, `category_id`) VALUES (1, 1, 1)" );
1359     update_option( "post_count", 1 );
1360
1361     // First page
1362     $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', '', '', '')");
1363     $wpdb->query( "INSERT INTO $wpdb->post2cat (`rel_id`, `post_id`, `category_id`) VALUES (2, 2, 1)" );
1364     // Flush rules to pick up the new page.
1365     $wp_rewrite->init();
1366     $wp_rewrite->flush_rules();
1367
1368     // Default comment
1369     $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.'))."')");
1370
1371     $user = new WP_User($user_id);
1372     $wpdb->query("UPDATE $wpdb->options SET option_value = '$user->user_email' WHERE option_name = 'admin_email'");
1373
1374     // Remove all perms except for the login user.
1375     $wpdb->query( "DELETE FROM ".$wpdb->usermeta." WHERE  user_id != '".$user_id."' AND meta_key = '".$table_prefix."user_level'" );
1376     $wpdb->query( "DELETE FROM ".$wpdb->usermeta." WHERE  user_id != '".$user_id."' AND meta_key = '".$table_prefix."capabilities'" );
1377     // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
1378     if ( $user_id != 1 )
1379         $wpdb->query( "DELETE FROM ".$wpdb->usermeta." WHERE  user_id = '".$user_id."' AND meta_key = '" . $wpmuBaseTablePrefix . "1_capabilities'" );
1380
1381     $wpdb->show_errors();
1382 }
1383
1384 function wpmu_welcome_notification($blog_id, $user_id, $password, $title, $meta = '') {
1385     global $current_site;
1386
1387     $welcome_email = stripslashes( get_site_option( 'welcome_email' ) );
1388     if( $welcome_email == false )
1389         $welcome_email = stripslashes( __( "Dear User,
1390
1391 Your new SITE_NAME blog has been successfully set up at:
1392 BLOG_URL
1393
1394 You can log in to the administrator account with the following information:
1395 Username: USERNAME
1396 Password: PASSWORD
1397 Login Here: BLOG_URLwp-login.php
1398
1399 We hope you enjoy your new weblog.
1400 Thanks!
1401
1402 --The WordPress Team
1403 SITE_NAME" ) );
1404
1405     $url = get_blogaddress_by_id($blog_id);
1406     $user = new WP_User($user_id);
1407
1408     $welcome_email = str_replace( "SITE_NAME", $current_site->site_name, $welcome_email );
1409     $welcome_email = str_replace( "BLOG_URL", $url, $welcome_email );
1410     $welcome_email = str_replace( "USERNAME", $user->user_login, $welcome_email );
1411     $welcome_email = str_replace( "PASSWORD", $password, $welcome_email );
1412
1413     $welcome_email = apply_filters( "update_welcome_email", $welcome_email, $blog_id, $user_id, $password, $title, $meta);
1414     $admin_email = get_site_option( "admin_email" );
1415     if( $admin_email == '' )
1416         $admin_email = 'support@' . $_SERVER[ 'SERVER_NAME' ];
1417     $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1418     $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1419     $message = $welcome_email;
1420     if( empty( $current_site->site_name ) )
1421         $current_site->site_name = "WordPress MU";
1422     $subject = sprintf(__('New %1$s Blog: %2$s'), $current_site->site_name, $title);
1423     wp_mail($user->user_email, $subject, $message, $message_headers);
1424 }
1425
1426 function wpmu_welcome_user_notification($user_id, $password, $meta = '') {
1427     global $current_site;
1428
1429     $welcome_email = __( "Dear User,
1430
1431 Your new account is setup.
1432
1433 You can log in with the following information:
1434 Username: USERNAME
1435 Password: PASSWORD
1436
1437 Thanks!
1438
1439 --The WordPress Team
1440 SITE_NAME" );
1441
1442     $user = new WP_User($user_id);
1443
1444     $welcome_email = apply_filters( "update_welcome_user_email", $welcome_email, $user_id, $password, $meta);
1445     $welcome_email = str_replace( "SITE_NAME", $current_site->site_name, $welcome_email );
1446     $welcome_email = str_replace( "USERNAME", $user->user_login, $welcome_email );
1447     $welcome_email = str_replace( "PASSWORD", $password, $welcome_email );
1448
1449     $admin_email = get_site_option( "admin_email" );
1450     if( $admin_email == '' )
1451         $admin_email = 'support@' . $_SERVER[ 'SERVER_NAME' ];
1452     $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1453     $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1454     $message = $welcome_email;
1455     if( empty( $current_site->site_name ) )
1456         $current_site->site_name = "WordPress MU";
1457     $subject = sprintf(__('New %1$s User: %2$s'), $current_site->site_name, $user->user_login);
1458     wp_mail($user->user_email, $subject, $message, $message_headers);
1459 }
1460
1461 function get_current_site() {
1462     global $current_site;
1463     return $current_site;
1464 }
1465
1466 function get_user_id_from_string( $string ) {
1467     global $wpdb;
1468     if( is_email( $string ) ) {
1469         $user_id = $wpdb->get_var( "SELECT ID FROM {$wpdb->users} WHERE user_email = '$string'" );
1470     } elseif ( is_numeric( $string ) ) {
1471         $user_id = $string;
1472     } else {
1473         $user_id = $wpdb->get_var( "SELECT ID FROM {$wpdb->users} WHERE user_login = '$string'" );
1474     }
1475
1476     return $user_id;
1477 }
1478
1479 function get_most_recent_post_of_user( $user_id ) {
1480     global $wpdb, $wpmuBaseTablePrefix;
1481
1482     $user_id = (int) $user_id;
1483
1484     $user_blogs = get_blogs_of_user($user_id);
1485     $most_recent_post = array();
1486
1487     // Walk through each blog and get the most recent post
1488     // published by $user_id
1489     foreach ( $user_blogs as $blog ) {
1490         $recent_post = $wpdb->get_row("SELECT ID, post_date_gmt FROM {$wpmuBaseTablePrefix}{$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);
1491
1492         // Make sure we found a post
1493         if ( isset($recent_post['ID']) ) {
1494             $post_gmt_ts = strtotime($recent_post['post_date_gmt']);
1495
1496             // If this is the first post checked or if this post is
1497             // newer than the current recent post, make it the new
1498             // most recent post.
1499             if (
1500                 !isset($most_recent_post['post_gmt_ts'])
1501                 || ($post_gmt_ts > $most_recent_post['post_gmt_ts'])
1502             ) {
1503                 $most_recent_post = array(
1504                     'blog_id'        => $blog->userblog_id,
1505                     'post_id'        => $recent_post['ID'],
1506                     'post_date_gmt'    => $recent_post['post_date_gmt'],
1507                     'post_gmt_ts'    => $post_gmt_ts
1508                 );
1509             }
1510         }
1511     }
1512
1513     return $most_recent_post;
1514 }
1515
1516 ?>
1517
Note: See TracBrowser for help on using the browser.