[ Root ] [ Search ] [ Index ]

PHP Cross Reference of WordPress MU 2.9.2

Provided by Yoast

title

Body

[close]

/wp-includes/ -> wpmu-functions.php (source)

   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 = WPMU_PLUGIN_DIR;
  12  
  13      $mofile = WPMU_PLUGIN_DIR . "/$domain-$locale.mo";
  14      load_textdomain($domain, $mofile);
  15  }
  16  
  17  function wpmu_update_blogs_date() {
  18      global $wpdb;
  19  
  20      $wpdb->update( $wpdb->blogs, array('last_updated' => current_time('mysql', true)), array('blog_id' => $wpdb->blogid) );
  21      refresh_blog_details( $wpdb->blogid );
  22  
  23      do_action( 'wpmu_blog_updated', $wpdb->blogid );
  24  }
  25  
  26  function get_blogaddress_by_id( $blog_id ) {
  27      $bloginfo = get_blog_details( (int) $blog_id, false ); // only get bare details!
  28      return clean_url("http://" . $bloginfo->domain . $bloginfo->path);
  29  }
  30  
  31  function get_blogaddress_by_name( $blogname ) {
  32      global $current_site;
  33  
  34      if( defined( "VHOST" ) && constant( "VHOST" ) == 'yes' ) {
  35          if( $blogname == 'main' )
  36              $blogname = 'www';
  37          return clean_url( "http://" . $blogname . "." . $current_site->domain . $current_site->path );
  38      } else {
  39          return clean_url( "http://" . $current_site->domain . $current_site->path . $blogname . '/' );
  40      }
  41  }
  42  
  43  function get_blogaddress_by_domain( $domain, $path ){
  44      if( defined( "VHOST" ) && constant( "VHOST" ) == 'yes' ) {
  45          $url = "http://".$domain.$path;
  46      } else {
  47          if( $domain != $_SERVER['HTTP_HOST'] ) {
  48              $blogname = substr( $domain, 0, strpos( $domain, '.' ) );
  49              if( $blogname != 'www.' ) {
  50                  $url = 'http://' . substr( $domain, strpos( $domain, '.' ) + 1 ) . $path . $blogname . '/';
  51              } else { // we're installing the main blog
  52                  $url = 'http://' . substr( $domain, strpos( $domain, '.' ) + 1 ) . $path;
  53              }
  54          } else { // main blog
  55              $url = 'http://' . $domain . $path;
  56          }
  57      }
  58      return clean_url($url);
  59  }
  60  
  61  function get_sitestats() {
  62      global $wpdb;
  63  
  64      $stats['blogs'] = get_blog_count();
  65  
  66      $count_ts = get_site_option( "get_user_count_ts" );
  67      if( time() - $count_ts > 3600 ) {
  68          $count = $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->users}" );
  69          update_site_option( "user_count", $count );
  70          update_site_option( "user_count_ts", time() );
  71      } else {
  72          $count = get_site_option( "user_count" );
  73      }
  74      $stats['users'] = $count;
  75      return $stats;
  76  }
  77  
  78  function get_admin_users_for_domain( $sitedomain = '', $path = '' ) {
  79      global $wpdb;
  80      
  81      if( $sitedomain == '' ) {
  82          $site_id = $wpdb->siteid;
  83      } else {
  84          $site_id = $wpdb->get_var( $wpdb->prepare("SELECT id FROM $wpdb->site WHERE domain = %s AND path = %s", $sitedomain, $path) );
  85      }
  86  
  87      if( $site_id != false ) {
  88          return $wpdb->get_results( $wpdb->prepare("SELECT u.ID, u.user_login, u.user_pass FROM $wpdb->users AS u, $wpdb->sitemeta AS sm WHERE sm.meta_key = 'admin_user_id' AND u.ID = sm.meta_value AND sm.site_id = %d", $site_id), ARRAY_A );
  89      }
  90      return false;
  91  }
  92  
  93  function get_user_details( $username ) {
  94      global $wpdb;
  95      return $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->users WHERE user_login = %s", $username) );
  96  }
  97  
  98  function is_main_blog() {
  99      global $current_blog, $current_site;
 100      if( $current_blog->domain == $current_site->domain && $current_blog->path == $current_site->path )
 101          return true;
 102      return false;
 103  }
 104  
 105  function get_id_from_blogname( $name ) {
 106      global $wpdb, $current_site;
 107      $blog_id = wp_cache_get( "get_id_from_blogname_" . $name, 'blog-details' );
 108      if( $blog_id )
 109          return $blog_id;
 110  
 111      if( constant( 'VHOST' ) == 'yes' ) {
 112          $domain = $name . '.' . $current_site->domain;
 113          $path = $current_site->path;
 114      } else {
 115          $domain = $current_site->domain;
 116          $path = $current_site->path . $name . '/';
 117      }
 118      $blog_id = $wpdb->get_var( $wpdb->prepare("SELECT blog_id FROM {$wpdb->blogs} WHERE domain = %s AND path = %s", $domain, $path) );
 119      wp_cache_set( 'get_id_from_blogname_' . $name, $blog_id, 'blog-details' );
 120      return $blog_id;
 121  }
 122  
 123  function get_blog_details( $id, $getall = true ) {
 124      global $wpdb;
 125  
 126      if( !is_numeric( $id ) ) {
 127          $id = get_id_from_blogname( $id );
 128      }
 129      $all = $getall == true ? '' : 'short';
 130      $details = wp_cache_get( $id . $all, 'blog-details' );
 131  
 132      if ( $details ) {
 133          if ( $details == -1 )
 134              return false;
 135          elseif ( !is_object($details) ) // Clear old pre-serialized objects. Cache clients do better with that.
 136              wp_cache_delete( $id . $all, 'blog-details' );
 137          else
 138              return $details;
 139      }
 140  
 141      $details = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->blogs WHERE blog_id = %d /* get_blog_details */", $id) );
 142      if ( !$details ) {
 143          wp_cache_set( $id . $all, -1, 'blog-details' );
 144          return false;
 145      }
 146  
 147      if ( !$getall ) {
 148          wp_cache_set( $id . $all, $details, 'blog-details' );
 149          return $details;
 150      }
 151  
 152      $wpdb->suppress_errors();
 153      switch_to_blog( $id );
 154      $details->blogname   = get_option( 'blogname' );
 155      $details->siteurl    = get_option( 'siteurl' );
 156      $details->post_count = get_option( 'post_count' );
 157      restore_current_blog();
 158      $wpdb->suppress_errors( false );
 159  
 160      $details = apply_filters('blog_details', $details);
 161  
 162      wp_cache_set( $id . $all, $details, 'blog-details' );
 163  
 164      $key = md5( $details->domain . $details->path );
 165      wp_cache_set( $key, $details, 'blog-lookup' );
 166  
 167      return $details;
 168  }
 169  
 170  function refresh_blog_details( $id ) {
 171      $id = (int) $id;
 172      $details = get_blog_details( $id, false );
 173  
 174      wp_cache_delete( $id , 'blog-details' );
 175      wp_cache_delete( $id . 'short' , 'blog-details' );
 176      wp_cache_delete( md5( $details->domain . $details->path )  , 'blog-lookup' );
 177      wp_cache_delete( 'current_blog_' . $details->domain, 'site-options' );
 178      wp_cache_delete( 'current_blog_' . $details->domain . $details->path, 'site-options' );
 179  }
 180  
 181  function get_current_user_id() {
 182      global $current_user;
 183      return $current_user->ID;
 184  }
 185  
 186  function is_site_admin( $user_login = false ) {
 187      global $current_user;
 188  
 189      if ( !$current_user && !$user_login )
 190          return false;
 191  
 192      if ( $user_login ) {
 193          $user_login = sanitize_user( $user_login );
 194      } elseif( isset( $current_user->user_login ) ) {
 195          $user_login = $current_user->user_login;
 196      } else {
 197          return false;
 198      }
 199  
 200      $site_admins = get_site_option( 'site_admins', array('admin') );
 201      if( is_array( $site_admins ) && in_array( $user_login, $site_admins ) )
 202          return true;
 203  
 204      return false;
 205  }
 206  
 207  /**
 208   * Retrieve option value based on setting name and blog_id.
 209   *
 210   * If the option does not exist or does not have a value, then the return value
 211   * will be false. This is useful to check whether you need to install an option
 212   * and is commonly used during installation of plugin options and to test
 213   * whether upgrading is required.
 214   *
 215   * There is a filter called 'blog_option_$option' with the $option being
 216   * replaced with the option name. The filter takes two parameters. $value and
 217   * $blog_id. It returns $value.
 218   * The 'option_$option' filter in get_option() is not called.
 219   *
 220   * @since NA
 221   * @package WordPress MU
 222   * @subpackage Option
 223   * @uses apply_filters() Calls 'blog_option_$optionname' with the option name value.
 224   *
 225   * @param int $blog_id is the id of the blog.
 226   * @param string $setting Name of option to retrieve. Should already be SQL-escaped
 227   * @param string $default (optional) Default value returned if option not found.
 228   * @return mixed Value set for the option.
 229   */
 230  function get_blog_option( $blog_id, $setting, $default = false ) {
 231      global $wpdb;
 232  
 233      $key = $blog_id."-".$setting."-blog_option";
 234      $value = wp_cache_get( $key, "site-options" );
 235      if ( $value == null ) {
 236          $blog_prefix = $wpdb->get_blog_prefix( $blog_id );
 237          $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$blog_prefix}options WHERE option_name = %s", $setting ) );
 238          if ( is_object( $row ) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
 239              $value = $row->option_value;
 240              if ( $value == false ) {
 241                  wp_cache_set( $key, 'falsevalue', 'site-options' );
 242              } else {
 243                  wp_cache_set( $key, $value, 'site-options' );
 244              }
 245          } else { // option does not exist, so we must cache its non-existence
 246              wp_cache_set( $key, 'noop', 'site-options' );
 247              $value = $default;
 248          }
 249      } elseif( $value == 'noop' ) {
 250          $value = $default;
 251      } elseif( $value == 'falsevalue' ) {
 252          $value = false;
 253      }
 254      // If home is not set use siteurl.
 255      if ( 'home' == $setting && '' == $value )
 256          return get_blog_option( $blog_id, 'siteurl' );
 257  
 258      if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
 259          $value = preg_replace( '|/+$|', '', $value );
 260  
 261      if (! @unserialize( $value ) )
 262          $value = stripslashes( $value );
 263  
 264      return apply_filters( 'blog_option_' . $setting, maybe_unserialize( $value ), $blog_id );
 265  }
 266  
 267  function add_blog_option( $id, $key, $value ) {
 268      $id = (int) $id;
 269      
 270      switch_to_blog($id);
 271      add_option( $key, $value );
 272      restore_current_blog();
 273      wp_cache_set( $id."-".$key."-blog_option", $value, 'site-options' );
 274  }
 275  
 276  function delete_blog_option( $id, $key ) {
 277      $id = (int) $id;
 278      
 279      switch_to_blog($id);
 280      delete_option( $key );
 281      restore_current_blog();
 282      wp_cache_set( $id."-".$key."-blog_option", '', 'site-options' );
 283  }
 284  
 285  function update_blog_option( $id, $key, $value, $refresh = true ) {
 286      $id = (int) $id;
 287      
 288      switch_to_blog($id);
 289      update_option( $key, $value );
 290      restore_current_blog();
 291  
 292      if( $refresh == true )
 293          refresh_blog_details( $id );
 294      wp_cache_set( $id."-".$key."-blog_option", $value, 'site-options');
 295  }
 296  
 297  function switch_to_blog( $new_blog ) {
 298      global $wpdb, $table_prefix, $blog_id, $switched, $switched_stack, $wp_roles, $current_user, $wp_object_cache;
 299  
 300      if ( empty($new_blog) )
 301          $new_blog = $blog_id;
 302  
 303      if ( empty($switched_stack) )
 304          $switched_stack = array();
 305  
 306      $switched_stack[] = $blog_id;
 307  
 308      /* If we're switching to the same blog id that we're on, 
 309      * set the right vars, do the associated actions, but skip 
 310      * the extra unnecessary work */
 311      if ( $blog_id == $new_blog ) {
 312          do_action( 'switch_blog', $blog_id, $blog_id );
 313          $switched = true;
 314          return true;
 315      }
 316  
 317      $wpdb->set_blog_id($new_blog);
 318      $table_prefix = $wpdb->prefix;
 319      $prev_blog_id = $blog_id;
 320      $blog_id = $new_blog;
 321  
 322      if( is_object( $wp_roles ) ) {
 323          $wpdb->suppress_errors();
 324          if ( method_exists( $wp_roles ,'_init' ) ) {
 325              $wp_roles->_init();
 326          } elseif( method_exists( $wp_roles, '__construct' ) ) {
 327              $wp_roles->__construct();
 328          }
 329          $wpdb->suppress_errors( false );
 330      }
 331  
 332      if ( is_object( $current_user ) )
 333          $current_user->_init_caps();
 334  
 335      if ( is_object( $wp_object_cache ) ) {
 336          $global_groups = $wp_object_cache->global_groups;
 337      } else {
 338          $global_groups = false;
 339      }
 340      wp_cache_init();
 341      if ( function_exists('wp_cache_add_global_groups') ) {
 342          if ( is_array( $global_groups ) ) {
 343              wp_cache_add_global_groups( $global_groups );
 344          } else {
 345              wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'site-transient', 'global-posts' ) );
 346          }
 347          wp_cache_add_non_persistent_groups(array( 'comment', 'counts', 'plugins' ));
 348      }
 349  
 350      do_action('switch_blog', $blog_id, $prev_blog_id);
 351      $switched = true;
 352      return true;
 353  }
 354  
 355  function restore_current_blog() {
 356      global $table_prefix, $wpdb, $blog_id, $switched, $switched_stack, $wp_roles, $current_user, $wp_object_cache;
 357  
 358      if ( !$switched )
 359          return false;
 360  
 361      if ( !is_array( $switched_stack ) )
 362          return false;
 363  
 364      $blog = array_pop( $switched_stack );
 365      if ( $blog_id == $blog ) {
 366          do_action( 'switch_blog', $blog, $blog );
 367          /* If we still have items in the switched stack, consider ourselves still 'switched' */
 368          $switched = ( is_array( $switched_stack ) && count( $switched_stack ) > 0 );
 369          return true;
 370      }
 371  
 372      $wpdb->set_blog_id($blog);
 373      $prev_blog_id = $blog_id;
 374      $blog_id = $blog;
 375      $table_prefix = $wpdb->prefix;
 376  
 377      if( is_object( $wp_roles ) ) {
 378          $wpdb->suppress_errors();
 379          if ( method_exists( $wp_roles ,'_init' ) ) {
 380              $wp_roles->_init();
 381          } elseif( method_exists( $wp_roles, '__construct' ) ) {
 382              $wp_roles->__construct();
 383          }
 384          $wpdb->suppress_errors( false );
 385      }
 386  
 387      if ( is_object( $current_user ) )
 388          $current_user->_init_caps();
 389  
 390      if ( is_object( $wp_object_cache ) ) {
 391          $global_groups = $wp_object_cache->global_groups;
 392      } else {
 393          $global_groups = false;
 394      }
 395      wp_cache_init();
 396      if ( function_exists('wp_cache_add_global_groups') ) {
 397          if ( is_array( $global_groups ) ) {
 398              wp_cache_add_global_groups( $global_groups );
 399          } else {
 400              wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'site-transient' ) );
 401          }
 402          wp_cache_add_non_persistent_groups(array( 'comment', 'counts', 'plugins' ));
 403      }
 404  
 405      do_action('switch_blog', $blog_id, $prev_blog_id);
 406  
 407      /* If we still have items in the switched stack, consider ourselves still 'switched' */ 
 408      $switched = ( is_array( $switched_stack ) && count( $switched_stack ) > 0 );
 409      return true;
 410  }
 411  
 412  function get_blogs_of_user( $id, $all = false ) {
 413      global $wpdb;
 414  
 415      $cache_suffix = $all ? '_all' : '_short';
 416      $return = wp_cache_get( 'blogs_of_user_' . $id . $cache_suffix, 'users' );
 417      if ( $return ) {
 418          return apply_filters( 'get_blogs_of_user', $return, $id, $all );
 419      }
 420  
 421      $user = get_userdata( (int) $id );
 422      if ( !$user )
 423          return false;
 424  
 425      $blogs = $match = array();
 426      foreach ( (array) $user as $key => $value ) {
 427          if ( false !== strpos( $key, '_capabilities') && 0 === strpos( $key, $wpdb->base_prefix ) && preg_match( '/' . $wpdb->base_prefix . '(\d+)_capabilities/', $key, $match ) ) {
 428              $blog = get_blog_details( $match[1] );
 429              if ( $blog && isset( $blog->domain ) && ( $all == true || $all == false && ( $blog->archived == 0 && $blog->spam == 0 && $blog->deleted == 0 ) ) ) {
 430                  $blogs[$match[1]]->userblog_id = $match[1];
 431                  $blogs[$match[1]]->blogname    = $blog->blogname;
 432                  $blogs[$match[1]]->domain      = $blog->domain;
 433                  $blogs[$match[1]]->path        = $blog->path;
 434                  $blogs[$match[1]]->site_id     = $blog->site_id;
 435                  $blogs[$match[1]]->siteurl     = $blog->siteurl;
 436              }
 437          }
 438      }
 439  
 440      wp_cache_add( 'blogs_of_user_' . $id . $cache_suffix, $blogs, 'users', 5 );
 441      return apply_filters( 'get_blogs_of_user', $blogs, $id, $all );
 442  }
 443  
 444  function get_active_blog_for_user( $user_id ) { // get an active blog for user - either primary blog or from blogs list
 445      global $wpdb;
 446      $blogs = get_blogs_of_user( $user_id );
 447      if ( empty( $blogs ) ) {
 448          $details = get_dashboard_blog();
 449          add_user_to_blog( $details->blog_id, $user_id, 'subscriber' );
 450          update_usermeta( $user_id, 'primary_blog', $details->blog_id );
 451          wp_cache_delete( $user_id, 'users' );
 452          return $details;
 453      }
 454  
 455      $primary_blog = get_usermeta( $user_id, "primary_blog" );
 456      $details = get_dashboard_blog();
 457      if ( $primary_blog ) {
 458          $blogs = get_blogs_of_user( $user_id );
 459          if ( isset( $blogs[ $primary_blog ] ) == false ) {
 460              add_user_to_blog( $details->blog_id, $user_id, 'subscriber' );
 461              update_usermeta( $user_id, 'primary_blog', $details->blog_id );
 462              wp_cache_delete( $user_id, 'users' );
 463          } else {
 464              $details = get_blog_details( $primary_blog );
 465          }
 466      } else {
 467          add_user_to_blog( $details->blog_id, $user_id, 'subscriber' ); // Add subscriber permission for dashboard blog
 468          update_usermeta( $user_id, 'primary_blog', $details->blog_id );
 469      }
 470  
 471      if ( ( is_object( $details ) == false ) || ( is_object( $details ) && $details->archived == 1 || $details->spam == 1 || $details->deleted == 1 ) ) {
 472          $blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs.
 473          $ret = false;
 474          if ( is_array( $blogs ) && count( $blogs ) > 0 ) {
 475              foreach( (array) $blogs as $blog_id => $blog ) {
 476                  if ( $blog->site_id != $wpdb->siteid )
 477                      continue;
 478                  $details = get_blog_details( $blog_id );
 479                  if ( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) {
 480                      $ret = $blog;
 481                      $changed = false;
 482                      if ( get_usermeta( $user_id , 'primary_blog' ) != $blog_id ) {
 483                          update_usermeta( $user_id, 'primary_blog', $blog_id );
 484                          $changed = true;
 485                      }
 486                      if ( !get_usermeta($user_id , 'source_domain') ) {
 487                          update_usermeta( $user_id, 'source_domain', $blog->domain );
 488                          $changed = true;
 489                      }
 490                      if ( $changed )
 491                          wp_cache_delete( $user_id, 'users' );
 492                      break;
 493                  }
 494              }
 495          } else {
 496              // Should never get here
 497              $dashboard_blog = get_dashboard_blog();
 498              add_user_to_blog( $dashboard_blog->blog_id, $user_id, 'subscriber' ); // Add subscriber permission for dashboard blog
 499              update_usermeta( $user_id, 'primary_blog', $dashboard_blog->blog_id );
 500              return $dashboard_blog;
 501          }
 502          return $ret;
 503      } else {
 504          return $details;
 505      }
 506  }
 507  
 508  function is_user_member_of_blog( $user_id, $blog_id = 0 ) {
 509      $user_id = (int) $user_id;
 510      $blog_id = (int) $blog_id;
 511      
 512      if( $blog_id == 0 ) {
 513          global $wpdb;
 514          $blog_id = $wpdb->blogid;
 515      }
 516      
 517      $blogs = get_blogs_of_user( $user_id );
 518      if( is_array( $blogs ) ) {
 519          return array_key_exists( $blog_id, $blogs );
 520      } else {
 521          return false;
 522      }
 523  }
 524  
 525  function is_archived( $id ) {
 526      return get_blog_status($id, 'archived');
 527  }
 528  
 529  function update_archived( $id, $archived ) {
 530      update_blog_status($id, 'archived', $archived);
 531      return $archived;
 532  }
 533  
 534  function update_blog_status( $id, $pref, $value, $refresh = 1 ) {
 535      global $wpdb;
 536  
 537      if ( !in_array( $pref, array( 'site_id', 'domain', 'path', 'registered', 'last_updated', 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id') ) )
 538          return $value;
 539  
 540      $wpdb->update( $wpdb->blogs, array($pref => $value, 'last_updated' => current_time('mysql', true)), array('blog_id' => $id) );
 541      if( $refresh == 1 )
 542          refresh_blog_details($id);
 543  
 544      if( $pref == 'spam' ) {
 545          if( $value == 1 ) {
 546              do_action( "make_spam_blog", $id );
 547          } else {
 548              do_action( "make_ham_blog", $id );
 549          }
 550      }
 551  
 552      return $value;
 553  }
 554  
 555  function get_blog_status( $id, $pref ) {
 556      global $wpdb;
 557  
 558      $details = get_blog_details( $id, false );
 559      if( $details ) {
 560          return $details->$pref;
 561      }
 562      return $wpdb->get_var( $wpdb->prepare("SELECT $pref FROM {$wpdb->blogs} WHERE blog_id = %d", $id) );
 563  }
 564  
 565  function get_last_updated( $deprecated = '', $start = 0, $quantity = 40 ) {
 566      global $wpdb;
 567      return $wpdb->get_results( $wpdb->prepare("SELECT blog_id, domain, path FROM $wpdb->blogs WHERE site_id = %d 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 %d, %d", $wpdb->siteid, $start, $quantity ) , ARRAY_A );
 568  }
 569  
 570  function get_most_active_blogs( $num = 10, $display = true ) {
 571      $most_active = get_site_option( "most_active" );
 572      $update = false;
 573      if( is_array( $most_active ) ) {
 574          if( ( $most_active['time'] + 60 ) < time() ) { // cache for 60 seconds.
 575              $update = true;
 576          }
 577      } else {
 578          $update = true;
 579      }
 580  
 581      if( $update == true ) {
 582          unset( $most_active );
 583          $blogs = get_blog_list( 0, 'all', false ); // $blog_id -> $details
 584          if( is_array( $blogs ) ) {
 585              reset( $blogs );
 586              foreach ( (array) $blogs as $key => $details ) {
 587                  $most_active[ $details['blog_id'] ] = $details['postcount'];
 588                  $blog_list[ $details['blog_id'] ] = $details; // array_slice() removes keys!!
 589              }
 590              arsort( $most_active );
 591              reset( $most_active );
 592              foreach ( (array) $most_active as $key => $details ) {
 593                  $t[ $key ] = $blog_list[ $key ];
 594              }
 595              unset( $most_active );
 596              $most_active = $t;
 597          }
 598          update_site_option( "most_active", $most_active );
 599      }
 600  
 601      if( $display == true ) {
 602          if( is_array( $most_active ) ) {
 603              reset( $most_active );
 604              foreach ( (array) $most_active as $key => $details ) {
 605                  $url = clean_url("http://" . $details['domain'] . $details['path']);
 606                  echo "<li>" . $details['postcount'] . " <a href='$url'>$url</a></li>";
 607              }
 608          }
 609      }
 610      return array_slice( $most_active, 0, $num );
 611  }
 612  
 613  function get_blog_list( $start = 0, $num = 10, $deprecated = '' ) {
 614      global $wpdb;
 615  
 616      $blogs = get_site_option( "blog_list" );
 617      $update = false;
 618      if( is_array( $blogs ) ) {
 619          if( ( $blogs['time'] + 60 ) < time() ) { // cache for 60 seconds.
 620              $update = true;
 621          }
 622      } else {
 623          $update = true;
 624      }
 625  
 626      if( $update == true ) {
 627          unset( $blogs );
 628          $blogs = $wpdb->get_results( $wpdb->prepare("SELECT blog_id, domain, path FROM $wpdb->blogs WHERE site_id = %d AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0' ORDER BY registered DESC", $wpdb->siteid), ARRAY_A );
 629  
 630          foreach ( (array) $blogs as $details ) {
 631              $blog_list[ $details['blog_id'] ] = $details;
 632              $blog_list[ $details['blog_id'] ]['postcount'] = $wpdb->get_var( "SELECT COUNT(ID) FROM " . $wpdb->base_prefix . $details['blog_id'] . "_posts WHERE post_status='publish' AND post_type='post'" );
 633          }
 634          unset( $blogs );
 635          $blogs = $blog_list;
 636          update_site_option( "blog_list", $blogs );
 637      }
 638  
 639      if( false == is_array( $blogs ) )
 640          return array();
 641  
 642      if( $num == 'all' ) {
 643          return array_slice( $blogs, $start, count( $blogs ) );
 644      } else {
 645          return array_slice( $blogs, $start, $num );
 646      }
 647  }
 648  
 649  function get_user_count() {
 650      global $wpdb;
 651  
 652      $count_ts = get_site_option( "user_count_ts" );
 653      if( time() - $count_ts > 3600 ) {
 654          $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(ID) as c FROM $wpdb->users WHERE spam = '0' AND deleted = '0'") );
 655          update_site_option( "user_count", $count );
 656          update_site_option( "user_count_ts", time() );
 657      }
 658  
 659      $count = get_site_option( "user_count" );
 660  
 661      return $count;
 662  }
 663  
 664  function get_blog_count( $id = 0 ) {
 665      global $wpdb;
 666  
 667      if( $id == 0 )
 668          $id = $wpdb->siteid;
 669  
 670      $count_ts = get_site_option( "blog_count_ts" );
 671      if( time() - $count_ts > 3600 ) {
 672          $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(blog_id) as c FROM $wpdb->blogs WHERE site_id = %d AND spam = '0' AND deleted = '0' and archived = '0'", $id) );
 673          update_site_option( "blog_count", $count );
 674          update_site_option( "blog_count_ts", time() );
 675      }
 676  
 677      $count = get_site_option( "blog_count" );
 678  
 679      return $count;
 680  }
 681  
 682  function get_blog_post( $blog_id, $post_id ) {
 683      global $wpdb;
 684  
 685      $key = $blog_id . "-" . $post_id;
 686      $post = wp_cache_get( $key, "global-posts" );
 687      if( $post == false ) {
 688          $post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM " . $wpdb->get_blog_prefix( $blog_id ) . "posts WHERE ID = %d", $post_id ) );
 689          wp_cache_add( $key, $post, "global-posts" );
 690      }
 691  
 692      return $post;
 693  }
 694  
 695  function clear_global_post_cache( $post_id ) {
 696      global $wpdb;
 697  
 698      wp_cache_delete( $wpdb->blogid . '-' . $post_id, 'global-posts' );
 699  }
 700  add_action( 'publish_post', 'clear_global_post_cache' );
 701  add_action( 'delete_post', 'clear_global_post_cache' );
 702  
 703  function add_user_to_blog( $blog_id, $user_id, $role ) {
 704      switch_to_blog($blog_id);
 705  
 706      $user = new WP_User($user_id);
 707  
 708      if ( empty($user) )
 709          return new WP_Error('user_does_not_exist', __('That user does not exist.'));
 710  
 711      if ( !get_usermeta($user_id, 'primary_blog') ) {
 712          update_usermeta($user_id, 'primary_blog', $blog_id);
 713          $details = get_blog_details($blog_id);
 714          update_usermeta($user_id, 'source_domain', $details->domain);
 715      }
 716  
 717      $user->set_role($role);
 718  
 719      do_action('add_user_to_blog', $user_id, $role, $blog_id);
 720      wp_cache_delete( $user_id, 'users' );
 721      restore_current_blog();
 722      return true;
 723  }
 724  
 725  function remove_user_from_blog($user_id, $blog_id = '', $reassign = '') {
 726      global $wpdb;
 727      switch_to_blog($blog_id);
 728      $user_id = (int) $user_id;
 729      do_action('remove_user_from_blog', $user_id, $blog_id);
 730  
 731      // If being removed from the primary blog, set a new primary if the user is assigned
 732      // to multiple blogs.
 733      $primary_blog = get_usermeta($user_id, 'primary_blog');
 734      if ( $primary_blog == $blog_id ) {
 735          $new_id = '';
 736          $new_domain = '';
 737          $blogs = get_blogs_of_user($user_id);
 738          foreach ( (array) $blogs as $blog ) {
 739              if ( $blog->userblog_id == $blog_id )
 740                  continue;
 741              $new_id = $blog->userblog_id;
 742              $new_domain = $blog->domain;
 743              break;
 744          }
 745  
 746          update_usermeta($user_id, 'primary_blog', $new_id);
 747          update_usermeta($user_id, 'source_domain', $new_domain);
 748      }
 749  
 750      // wp_revoke_user($user_id);
 751      $user = new WP_User($user_id);
 752      $user->remove_all_caps();
 753  
 754      $blogs = get_blogs_of_user($user_id);
 755      if ( count($blogs) == 0 ) {
 756          update_usermeta($user_id, 'primary_blog', '');
 757          update_usermeta($user_id, 'source_domain', '');
 758      }
 759  
 760      if( $reassign != '' ) {
 761          $reassign = (int) $reassign;
 762          $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_author = %d WHERE post_author = %d", $reassign, $user_id) );
 763          $wpdb->query( $wpdb->prepare("UPDATE $wpdb->links SET link_owner = %d WHERE link_owner = %d", $reassign, $user_id) );
 764      }
 765  
 766      restore_current_blog();
 767  }
 768  
 769  function create_empty_blog( $domain, $path, $weblog_title, $site_id = 1 ) {
 770      $domain       = addslashes( $domain );
 771      $weblog_title = addslashes( $weblog_title );
 772  
 773      if( empty($path) )
 774          $path = '/';
 775  
 776      // Check if the domain has been used already. We should return an error message.
 777      if ( domain_exists($domain, $path, $site_id) )
 778          return __('error: Blog URL already taken.');
 779  
 780      // Need to backup wpdb table names, and create a new wp_blogs entry for new blog.
 781      // Need to get blog_id from wp_blogs, and create new table names.
 782      // Must restore table names at the end of function.
 783  
 784      if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
 785          return __('error: problem creating blog entry');
 786  
 787      switch_to_blog($blog_id);
 788      install_blog($blog_id);
 789      restore_current_blog();
 790  
 791      return $blog_id;
 792  }
 793  
 794  function get_blog_permalink( $_blog_id, $post_id ) {
 795      $key = "{$_blog_id}-{$post_id}-blog_permalink";
 796      $link = wp_cache_get( $key, 'site-options' );
 797      if( $link == false ) {
 798          switch_to_blog( $_blog_id );
 799          $link = get_permalink( $post_id );
 800          restore_current_blog();
 801          wp_cache_add( $key, $link, 'site-options', 360 );
 802      }
 803      return $link;
 804  }
 805  
 806  function get_blog_id_from_url( $domain, $path = '/' ) {
 807      global $wpdb;
 808  
 809      $domain = strtolower( $wpdb->escape( $domain ) );
 810      $path = strtolower( $wpdb->escape( $path ) );
 811      $id = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' );
 812  
 813      if( $id == -1 ) { // blog does not exist
 814          return 0;
 815      } elseif( $id ) {
 816          return (int)$id;
 817      }
 818  
 819      $id = $wpdb->get_var( "SELECT blog_id FROM $wpdb->blogs WHERE domain = '$domain' and path = '$path' /* get_blog_id_from_url */" );
 820  
 821      if ( !$id ) {
 822          wp_cache_set( md5( $domain . $path ), -1, 'blog-id-cache' );
 823          return false;
 824      }
 825      wp_cache_set( md5( $domain . $path ), $id, 'blog-id-cache' );
 826  
 827      return $id;
 828  }
 829  
 830  // wpmu admin functions
 831  
 832  function wpmu_admin_do_redirect( $url = '' ) {
 833      $ref = '';
 834      if ( isset( $_GET['ref'] ) )
 835          $ref = $_GET['ref'];
 836      if ( isset( $_POST['ref'] ) )
 837          $ref = $_POST['ref'];
 838  
 839      if( $ref ) {
 840          $ref = wpmu_admin_redirect_add_updated_param( $ref );
 841          wp_redirect( $ref );
 842          exit();
 843      }
 844      if( empty( $_SERVER['HTTP_REFERER'] ) == false ) {
 845          wp_redirect( $_SERVER['HTTP_REFERER'] );
 846          exit();
 847      }
 848  
 849      $url = wpmu_admin_redirect_add_updated_param( $url );
 850      if( isset( $_GET['redirect'] ) ) {
 851          if( substr( $_GET['redirect'], 0, 2 ) == 's_' ) {
 852              $url .= "&action=blogs&s=". wp_specialchars( substr( $_GET['redirect'], 2 ) );
 853          }
 854      } elseif( isset( $_POST['redirect'] ) ) {
 855          $url = wpmu_admin_redirect_add_updated_param( $_POST['redirect'] );
 856      }
 857      wp_redirect( $url );
 858      exit();
 859  }
 860  
 861  function wpmu_admin_redirect_add_updated_param( $url = '' ) {
 862      if( strpos( $url, 'updated=true' ) === false ) {
 863          if( strpos( $url, '?' ) === false ) {
 864              return $url . '?updated=true';
 865          } else {
 866              return $url . '&updated=true';
 867          }
 868      }
 869      return $url;
 870  }
 871  
 872  function is_blog_user( $blog_id = 0 ) {
 873      global $current_user, $wpdb;
 874  
 875      if ( !$blog_id )
 876          $blog_id = $wpdb->blogid;
 877  
 878      $cap_key = $wpdb->base_prefix . $blog_id . '_capabilities';
 879  
 880      if ( is_array($current_user->$cap_key) && in_array(1, $current_user->$cap_key) )
 881          return true;
 882  
 883      return false;
 884  }
 885  
 886  function validate_email( $email, $check_domain = true) {
 887      if (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.'@'.
 888          '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
 889          '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $email))
 890      {
 891          if ($check_domain && function_exists('checkdnsrr')) {
 892              list (, $domain)  = explode('@', $email);
 893  
 894              if (checkdnsrr($domain.'.', 'MX') || checkdnsrr($domain.'.', 'A')) {
 895                  return true;
 896              }
 897              return false;
 898          }
 899          return true;
 900      }
 901      return false;
 902  }
 903  
 904  function is_email_address_unsafe( $user_email ) {
 905      $banned_names = get_site_option( "banned_email_domains" );
 906      if ($banned_names && !is_array( $banned_names )) { 
 907          $banned_names = explode( "\n", $banned_names); 
 908      } 
 909      if ( is_array( $banned_names ) && empty( $banned_names ) == false ) {
 910          $email_domain = strtolower( substr( $user_email, 1 + strpos( $user_email, '@' ) ) );
 911          foreach( (array) $banned_names as $banned_domain ) {
 912              if( $banned_domain == '' )
 913                  continue;
 914              if (
 915                  strstr( $email_domain, $banned_domain ) ||
 916                  (
 917                      strstr( $banned_domain, '/' ) &&
 918                      preg_match( $banned_domain, $email_domain )
 919                  )
 920              )
 921              return true;
 922          }
 923      }
 924      return false;
 925  }
 926  
 927  function wpmu_validate_user_signup($user_name, $user_email) {
 928      global $wpdb;
 929  
 930      $errors = new WP_Error();
 931  
 932      $user_name = preg_replace( "/\s+/", '', sanitize_user( $user_name, true ) );
 933      $user_email = sanitize_email( $user_email );
 934  
 935      if ( empty( $user_name ) )
 936             $errors->add('user_name', __("Please enter a username"));
 937  
 938      $maybe = array();
 939      preg_match( "/[a-z0-9]+/", $user_name, $maybe );
 940  
 941      if( $user_name != $maybe[0] ) {
 942          $errors->add('user_name', __("Only lowercase letters and numbers allowed"));
 943      }
 944  
 945      $illegal_names = get_site_option( "illegal_names" );
 946      if( is_array( $illegal_names ) == false ) {
 947          $illegal_names = array(  "www", "web", "root", "admin", "main", "invite", "administrator" );
 948          add_site_option( "illegal_names", $illegal_names );
 949      }
 950      if( in_array( $user_name, $illegal_names ) == true ) {
 951          $errors->add('user_name',  __("That username is not allowed"));
 952      }
 953  
 954      if( is_email_address_unsafe( $user_email ) )
 955          $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."));
 956  
 957      if( strlen( $user_name ) < 4 ) {
 958          $errors->add('user_name',  __("Username must be at least 4 characters"));
 959      }
 960  
 961      if ( strpos( " " . $user_name, "_" ) != false )
 962          $errors->add('user_name', __("Sorry, usernames may not contain the character '_'!"));
 963  
 964      // all numeric?
 965      $match = array();
 966      preg_match( '/[0-9]*/', $user_name, $match );
 967      if ( $match[0] == $user_name )
 968          $errors->add('user_name', __("Sorry, usernames must have letters too!"));
 969  
 970      if ( !is_email( $user_email ) )
 971          $errors->add('user_email', __("Please enter a correct email address"));
 972  
 973      if ( !validate_email( $user_email ) )
 974          $errors->add('user_email', __("Please check your email address."));
 975  
 976      $limited_email_domains = get_site_option( 'limited_email_domains' );
 977      if ( is_array( $limited_email_domains ) && empty( $limited_email_domains ) == false ) {
 978          $emaildomain = substr( $user_email, 1 + strpos( $user_email, '@' ) );
 979          if( in_array( $emaildomain, $limited_email_domains ) == false ) {
 980              $errors->add('user_email', __("Sorry, that email address is not allowed!"));
 981          }
 982      }
 983  
 984      // Check if the username has been used already.
 985      if ( username_exists($user_name) )
 986          $errors->add('user_name', __("Sorry, that username already exists!"));
 987  
 988      // Check if the email address has been used already.
 989      if ( email_exists($user_email) )
 990          $errors->add('user_email', __("Sorry, that email address is already used!"));
 991  
 992      // Has someone already signed up for this username?
 993      $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_login = %s", $user_name) );
 994      if ( $signup != null ) {
 995          $registered_at =  mysql2date('U', $signup->registered);
 996          $now = current_time( 'timestamp', true );
 997          $diff = $now - $registered_at;
 998          // If registered more than two days ago, cancel registration and let this signup go through.
 999          if ( $diff > 172800 ) {
1000              $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->signups WHERE user_login = %s", $user_name) );
1001          } else {
1002              $errors->add('user_name', __("That username is currently reserved but may be available in a couple of days."));
1003          }
1004          if( $signup->active == 0 && $signup->user_email == $user_email )
1005              $errors->add('user_email_used', __("username and email used"));
1006      }
1007  
1008      $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_email = %s", $user_email) );
1009      if ( $signup != null ) {
1010          $diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered);
1011          // If registered more than two days ago, cancel registration and let this signup go through.
1012          if ( $diff > 172800 ) {
1013              $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->signups WHERE user_email = %s", $user_email) );
1014          } else {
1015              $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."));
1016          }
1017      }
1018  
1019      $result = array('user_name' => $user_name, 'user_email' => $user_email,    'errors' => $errors);
1020  
1021      return apply_filters('wpmu_validate_user_signup', $result);
1022  }
1023  
1024  function wpmu_validate_blog_signup($blogname, $blog_title, $user = '') {
1025      global $wpdb, $domain, $base, $current_site;
1026  
1027      $blogname = preg_replace( "/\s+/", '', sanitize_user( $blogname, true ) );
1028      $blog_title = strip_tags( $blog_title );
1029      $blog_title = substr( $blog_title, 0, 50 );
1030  
1031      $errors = new WP_Error();
1032      $illegal_names = get_site_option( "illegal_names" );
1033      if( $illegal_names == false ) {
1034          $illegal_names = array( "www", "web", "root", "admin", "main", "invite", "administrator" );
1035          add_site_option( "illegal_names", $illegal_names );
1036      }
1037  
1038      if ( empty( $blogname ) )
1039          $errors->add('blogname', __("Please enter a blog name"));
1040  
1041      $maybe = array();
1042      preg_match( "/[a-z0-9]+/", $blogname, $maybe );
1043      if( $blogname != $maybe[0] ) {
1044          $errors->add('blogname', __("Only lowercase letters and numbers allowed"));
1045      }
1046      if( in_array( $blogname, $illegal_names ) == true ) {
1047          $errors->add('blogname',  __("That name is not allowed"));
1048      }
1049      if( strlen( $blogname ) < 4 && !is_site_admin() ) {
1050          $errors->add('blogname',  __("Blog name must be at least 4 characters"));
1051      }
1052  
1053      if ( strpos( " " . $blogname, "_" ) != false )
1054          $errors->add('blogname', __("Sorry, blog names may not contain the character '_'!"));
1055  
1056      // do not allow users to create a blog that conflicts with a page on the main blog.
1057      if ( constant( "VHOST" ) == 'no' && $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM " . $wpdb->get_blog_prefix( $current_site->blog_id ) . "posts WHERE post_type = 'page' AND post_name = %s", $blogname ) ) ) {
1058          $errors->add( 'blogname', __( "Sorry, you may not use that blog name" ) );
1059      }
1060  
1061      // all numeric?
1062      $match = array();
1063      preg_match( '/[0-9]*/', $blogname, $match );
1064      if ( $match[0] == $blogname )
1065          $errors->add('blogname', __("Sorry, blog names must have letters too!"));
1066  
1067      $blogname = apply_filters( "newblogname", $blogname );
1068  
1069      $blog_title = stripslashes(  $blog_title );
1070  
1071      if ( empty( $blog_title ) )
1072          $errors->add('blog_title', __("Please enter a blog title"));
1073  
1074      // Check if the domain/path has been used already.
1075      if( constant( "VHOST" ) == 'yes' ) {
1076          $mydomain = "$blogname.$domain";
1077          $path = $base;
1078      } else {
1079          $mydomain = "$domain";
1080          $path = $base.$blogname.'/';
1081      }
1082      if ( domain_exists($mydomain, $path) )
1083          $errors->add('blogname', __("Sorry, that blog already exists!"));
1084  
1085      if ( username_exists( $blogname ) ) {
1086          if ( is_object( $user ) == false || ( is_object($user) && ( $user->user_login != $blogname ) ) )
1087              $errors->add( 'blogname', __( "Sorry, that blog is reserved!" ) );
1088      }
1089  
1090      // Has someone already signed up for this domain?
1091      $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path) ); // TODO: Check email too?
1092      if ( ! empty($signup) ) {
1093          $diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered);
1094          // If registered more than two days ago, cancel registration and let this signup go through.
1095          if ( $diff > 172800 ) {
1096              $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path) );
1097          } else {
1098              $errors->add('blogname', __("That blog is currently reserved but may be available in a couple days."));
1099          }
1100      }
1101  
1102      $result = array('domain' => $mydomain, 'path' => $path, 'blogname' => $blogname, 'blog_title' => $blog_title, 'errors' => $errors);
1103      return apply_filters('wpmu_validate_blog_signup', $result);
1104  }
1105  
1106  // Record signup information for future activation. wpmu_validate_signup() should be run
1107  // on the inputs before calling wpmu_signup().
1108  function wpmu_signup_blog($domain, $path, $title, $user, $user_email, $meta = '') {
1109      global $wpdb;
1110  
1111      $key = substr( md5( time() . rand() . $domain ), 0, 16 );
1112      $meta = serialize($meta);
1113      $domain = $wpdb->escape($domain);
1114      $path = $wpdb->escape($path);
1115      $title = $wpdb->escape($title);
1116                      
1117      $wpdb->insert( $wpdb->signups, array(
1118          'domain' => $domain, 
1119          'path' => $path, 
1120          'title' => $title,
1121          'user_login' => $user, 
1122          'user_email' => $user_email, 
1123          'registered' => current_time('mysql', true),
1124          'activation_key' => $key, 
1125          'meta' => $meta
1126      ) );
1127  
1128      wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta);
1129  }
1130  
1131  function wpmu_signup_user($user, $user_email, $meta = '') {
1132      global $wpdb;
1133  
1134      // Format data
1135      $user = preg_replace( "/\s+/", '', sanitize_user( $user, true ) );
1136      $user_email = sanitize_email( $user_email );
1137      $key = substr( md5( time() . rand() . $user_email ), 0, 16 );
1138      $meta = serialize($meta);
1139                      
1140      $wpdb->insert( $wpdb->signups, array(
1141          'domain' => '', 
1142          'path' => '', 
1143          'title' => '',
1144          'user_login' => $user, 
1145          'user_email' => $user_email, 
1146          'registered' => current_time('mysql', true),
1147          'activation_key' => $key, 
1148          'meta' => $meta
1149      ) );
1150  
1151      wpmu_signup_user_notification($user, $user_email, $key, $meta);
1152  }
1153  
1154  // Notify user of signup success.
1155  function wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta = '') {
1156      global $current_site;
1157  
1158      if( !apply_filters('wpmu_signup_blog_notification', $domain, $path, $title, $user, $user_email, $key, $meta) )
1159          return false;
1160  
1161      // Send email with activation link.
1162      if( constant( "VHOST" ) == 'no' || $current_site->id != 1 ) {
1163          $activate_url = "http://" . $current_site->domain . $current_site->path . "wp-activate.php?key=$key";
1164      } else {
1165          $activate_url = "http://{$domain}{$path}wp-activate.php?key=$key";
1166      }
1167      $activate_url = clean_url($activate_url);
1168      $admin_email = get_site_option( "admin_email" );
1169      if( $admin_email == '' )
1170          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1171      $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1172      $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1173      $message = sprintf( apply_filters( 'wpmu_signup_blog_notification_email', __( "To activate your blog, please click the following link:\n\n%s\n\nAfter you activate, you will receive *another email* with your login.\n\nAfter you activate, you can visit your blog here:\n\n%s" ) ), $activate_url, clean_url( "http://{$domain}{$path}" ), $key );
1174      // TODO: Don't hard code activation link.
1175      $subject = sprintf( apply_filters( 'wpmu_signup_blog_notification_subject', __( '[%1s] Activate %2s' ) ), $from_name, clean_url( 'http://' . $domain . $path ) );
1176      wp_mail($user_email, $subject, $message, $message_headers);
1177      return true;
1178  }
1179  
1180  function wpmu_signup_user_notification($user, $user_email, $key, $meta = '') {
1181      global $current_site;
1182  
1183      if( !apply_filters('wpmu_signup_user_notification', $user, $user_email, $key, $meta) )
1184          return false;
1185  
1186      // Send email with activation link.
1187      $admin_email = get_site_option( "admin_email" );
1188      if( $admin_email == '' )
1189          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1190      $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1191      $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1192      $message = sprintf( apply_filters( 'wpmu_signup_user_notification_email', __( "To activate your user, please click the following link:\n\n%s\n\nAfter you activate, you will receive *another email* with your login.\n\n" ) ), site_url( "wp-activate.php?key=$key" ), $key );
1193      // TODO: Don't hard code activation link.
1194      $subject = sprintf( __( apply_filters( 'wpmu_signup_user_notification_subject', '[%1s] Activate %2s' ) ), $from_name, $user);
1195      wp_mail($user_email, $subject, $message, $message_headers);
1196      return true;
1197  }
1198  
1199  function wpmu_activate_signup($key) {
1200      global $wpdb, $current_site;
1201  
1202      $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key) );
1203  
1204      if ( empty($signup) )
1205          return new WP_Error('invalid_key', __('Invalid activation key.'));
1206  
1207      if ( $signup->active )
1208          return new WP_Error('already_active', __('The blog is already active.'), $signup);
1209  
1210      $meta = unserialize($signup->meta);
1211      $user_login = $wpdb->escape($signup->user_login);
1212      $user_email = $wpdb->escape($signup->user_email);
1213      wpmu_validate_user_signup($user_login, $user_email);
1214      $password = generate_random_password();
1215  
1216      $user_id = username_exists($user_login);
1217  
1218      if ( ! $user_id )
1219          $user_id = wpmu_create_user($user_login, $password, $user_email);
1220      else
1221          $user_already_exists = true;
1222  
1223      if ( ! $user_id )
1224          return new WP_Error('create_user', __('Could not create user'), $signup);
1225  
1226      $now = current_time('mysql', true);
1227  
1228      if ( empty($signup->domain) ) {
1229          $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) );
1230          if ( isset( $user_already_exists ) )
1231              return new WP_Error( 'user_already_exists', __( 'That username is already activated.' ), $signup);
1232          wpmu_welcome_user_notification($user_id, $password, $meta);
1233          $user_site = get_site_option( 'dashboard_blog', $current_site->blog_id );
1234          if ( $user_site == false ) {
1235              add_user_to_blog( '1', $user_id, get_site_option( 'default_user_role', 'subscriber' ) );
1236          } else {
1237              add_user_to_blog( $user_site, $user_id, get_site_option( 'default_user_role', 'subscriber' ) );
1238          }
1239          add_new_user_to_blog( $user_id, $user_email, $meta );
1240          do_action('wpmu_activate_user', $user_id, $password, $meta);
1241          return array('user_id' => $user_id, 'password' => $password, 'meta' => $meta);
1242      }
1243  
1244      wpmu_validate_blog_signup($signup->domain, $signup->title);
1245      $blog_id = wpmu_create_blog( $signup->domain, $signup->path, $signup->title, $user_id, $meta, $wpdb->siteid );
1246  
1247      // TODO: What to do if we create a user but cannot create a blog?
1248      if ( is_wp_error($blog_id) ) {
1249          // If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and
1250          // setting the activation flag.  Let's just set the active flag and instruct the user to reset their password.
1251          if ( 'blog_taken' == $blog_id->get_error_code() ) {
1252              $blog_id->add_data( $signup );
1253              $wpdb->update( $wpdb->signups, array( 'active' => 1, 'activated' => $now ), array( 'activation_key' => $key ) );
1254          }
1255  
1256          return $blog_id;
1257      }
1258  
1259      $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) );
1260  
1261      wpmu_welcome_notification($blog_id, $user_id, $password, $signup->title, $meta);
1262  
1263      do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta);
1264  
1265      return array('blog_id' => $blog_id, 'user_id' => $user_id, 'password' => $password, 'title' => $signup->title, 'meta' => $meta);
1266  }
1267  
1268  function generate_random_password( $len = 8 ) {
1269      $random_password = substr(md5(uniqid(microtime())), 0, intval( $len ) );
1270      $random_password = apply_filters('random_password', $random_password);
1271      return $random_password;
1272  }
1273  
1274  function wpmu_create_user( $user_name, $password, $email) {
1275      $user_name = preg_replace( "/\s+/", '', sanitize_user( $user_name, true ) );
1276      if ( username_exists($user_name) )
1277          return false;
1278  
1279      // Check if the email address has been used already.
1280      if ( email_exists($email) )
1281          return false;
1282  
1283      $user_id = wp_create_user( $user_name, $password, $email );
1284      $user = new WP_User($user_id);
1285  
1286      // Newly created users have no roles or caps until they are added to a blog.
1287      update_user_option($user_id, 'capabilities', '');
1288      update_user_option($user_id, 'user_level', '');
1289  
1290      do_action( 'wpmu_new_user', $user_id );
1291  
1292      return $user_id;
1293  }
1294  
1295  function wpmu_create_blog($domain, $path, $title, $user_id, $meta = '', $site_id = 1) {
1296      $domain = preg_replace( "/\s+/", '', sanitize_user( $domain, true ) );
1297      if( constant( 'VHOST' ) == 'yes' )
1298          $domain = str_replace( '@', '', $domain );
1299      $title = strip_tags( $title );
1300      $user_id = (int) $user_id;
1301  
1302      if( empty($path) )
1303          $path = '/';
1304  
1305      // Check if the domain has been used already. We should return an error message.
1306      if ( domain_exists($domain, $path, $site_id) )
1307          return new WP_Error('blog_taken', __('Blog already exists.'));
1308  
1309      if ( !defined("WP_INSTALLING") )
1310          define( "WP_INSTALLING", true );
1311  
1312      if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
1313          return new WP_Error('insert_blog', __('Could not create blog.'));
1314  
1315      switch_to_blog($blog_id);
1316  
1317      install_blog($blog_id, $title);
1318  
1319      install_blog_defaults($blog_id, $user_id);
1320  
1321      add_user_to_blog($blog_id, $user_id, 'administrator');
1322  
1323      if ( is_array($meta) ) foreach ($meta as $key => $value) {
1324          if( $key == 'public' || $key == 'archived' || $key == 'mature' || $key == 'spam' || $key == 'deleted' || $key == 'lang_id' ) {
1325              update_blog_status( $blog_id, $key, $value );
1326          } else {
1327              update_option( $key, $value );
1328          }
1329      }
1330  
1331      add_option( 'WPLANG', get_site_option( 'WPLANG' ) );
1332  
1333      update_option( 'blog_public', $meta['public'] );
1334  
1335      if ( !is_site_admin() && get_usermeta( $user_id, 'primary_blog' ) == get_site_option( 'dashboard_blog', 1 ) )
1336          update_usermeta( $user_id, 'primary_blog', $blog_id );
1337  
1338      restore_current_blog();
1339  
1340      do_action( 'wpmu_new_blog', $blog_id, $user_id );
1341  
1342      return $blog_id;
1343  }
1344  
1345  function newblog_notify_siteadmin( $blog_id, $deprecated = '' ) {
1346      global $current_site;
1347      if( get_site_option( 'registrationnotification' ) != 'yes' )
1348          return false;
1349          
1350      $email = get_site_option( 'admin_email' );
1351      if( is_email($email) == false )
1352          return false;
1353      
1354      $options_site_url = clean_url("http://{$current_site->domain}{$current_site->path}wp-admin/wpmu-options.php");
1355  
1356      switch_to_blog( $blog_id );
1357      $blogname = get_option( 'blogname' );
1358      $siteurl = get_option( 'siteurl' );
1359      restore_current_blog();
1360      
1361      $msg = sprintf( __( "New Blog: %1s
1362  URL: %2s
1363  Remote IP: %3s
1364  
1365  Disable these notifications: %4s"), $blogname, $siteurl, $_SERVER['REMOTE_ADDR'], $options_site_url);
1366      $msg = apply_filters( 'newblog_notify_siteadmin', $msg );
1367      
1368      wp_mail( $email, sprintf( __( "New Blog Registration: %s" ), $siteurl ), $msg );
1369      return true;
1370  }
1371  
1372  function newuser_notify_siteadmin( $user_id ) {
1373      global $current_site;
1374      if( get_site_option( 'registrationnotification' ) != 'yes' )
1375          return false;
1376          
1377      $email = get_site_option( 'admin_email' );
1378      if( is_email($email) == false )
1379          return false;
1380      $user = new WP_User($user_id);
1381  
1382      $options_site_url = clean_url("http://{$current_site->domain}{$current_site->path}wp-admin/wpmu-options.php");
1383      $msg = sprintf(__("New User: %1s
1384  Remote IP: %2s
1385  
1386  Disable these notifications: %3s"), $user->user_login, $_SERVER['REMOTE_ADDR'], $options_site_url);
1387      
1388      $msg = apply_filters( 'newuser_notify_siteadmin', $msg );
1389      wp_mail( $email, sprintf(__("New User Registration: %s"), $user->user_login), $msg );
1390      return true;
1391  }
1392  
1393  function domain_exists($domain, $path, $site_id = 1) {
1394      global $wpdb;
1395      return $wpdb->get_var( $wpdb->prepare("SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s AND site_id = %d", $domain, $path, $site_id) );
1396  }
1397  
1398  function insert_blog($domain, $path, $site_id) {
1399      global $wpdb;
1400  
1401      $path = trailingslashit($path);
1402      $site_id = (int) $site_id;
1403  
1404      $result = $wpdb->insert( $wpdb->blogs, array('site_id' => $site_id, 'domain' => $domain, 'path' => $path, 'registered' => current_time('mysql')) );
1405      if ( ! $result )
1406          return false;
1407  
1408      refresh_blog_details($wpdb->insert_id);
1409      return $wpdb->insert_id;
1410  }
1411  
1412  // Install an empty blog.  wpdb should already be switched.
1413  function install_blog($blog_id, $blog_title = '') {
1414      global $wpdb, $table_prefix, $wp_roles;
1415      $wpdb->suppress_errors();
1416  
1417      // Cast for security
1418      $blog_id = (int) $blog_id;
1419  
1420      require_once ( ABSPATH . 'wp-admin/includes/upgrade.php');
1421  
1422      if ( $wpdb->get_results("SELECT ID FROM $wpdb->posts") ) 
1423          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>');
1424      $wpdb->suppress_errors( false);
1425  
1426      $url = get_blogaddress_by_id($blog_id);
1427  
1428      // Set everything up
1429      make_db_current_silent();
1430      populate_options();
1431      populate_roles();
1432      $wp_roles->_init();
1433  
1434      // fix url.
1435      update_option('siteurl', $url);
1436      update_option('home', $url);
1437      update_option('fileupload_url', $url . "files" );
1438      update_option('upload_path', "wp-content/blogs.dir/" . $blog_id . "/files");
1439      update_option('blogname', stripslashes( $blog_title ) );
1440      update_option('admin_email', '');
1441      $wpdb->update( $wpdb->options, array('option_value' => ''), array('option_name' => 'admin_email') );
1442  
1443      // Default category
1444      $wpdb->insert( $wpdb->terms, array('term_id' => 1, 'name' => __('Uncategorized'), 'slug' => sanitize_title(__('Uncategorized')), 'term_group' => 0) );
1445      $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => 1, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1) );
1446  
1447      // Default link category
1448      $cat_name = __('Blogroll');
1449      $cat_slug = sanitize_title($cat_name);
1450      
1451      $blogroll_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
1452      if( $blogroll_id == null ) {
1453          $wpdb->insert( $wpdb->sitecategories, array('cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time('mysql', true)) );
1454          $blogroll_id = $wpdb->insert_id;
1455      }
1456      $wpdb->insert( $wpdb->terms, array('term_id' => $blogroll_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
1457      $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $blogroll_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 2) );
1458      update_option('default_link_category', $blogroll_id);
1459  
1460      // remove all perms
1461      $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE meta_key = %s", $table_prefix.'user_level') );
1462      $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE meta_key = %s", $table_prefix.'capabilities') );
1463  
1464      $wpdb->suppress_errors( false );
1465  }
1466  
1467  // should be switched already as $blog_id is ignored.
1468  function install_blog_defaults($blog_id, $user_id) {
1469      global $wpdb, $wp_rewrite, $current_site, $table_prefix;
1470  
1471      $wpdb->suppress_errors();
1472  
1473      // Cast for security
1474      $user_id = (int) $user_id;
1475      $blog_id = (int) $blog_id;
1476  
1477      // Default links
1478      $wpdb->insert( $wpdb->links, array( 'link_url' => 'http://wordpress.com/', 'link_name' => 'WordPress.com', 'link_owner' => $user_id, 'link_rss' => 'http://en.blog.wordpress.com/feed/', 'link_notes' => '' ) );
1479      $wpdb->insert( $wpdb->links, array( 'link_url' => 'http://wordpress.org/', 'link_name' => 'WordPress.org', 'link_owner' => $user_id, 'link_rss' => 'http://wordpress.org/development/feed/', 'link_notes' => '' ) );
1480      $wpdb->insert( $wpdb->term_relationships, array('object_id' => 1, 'term_taxonomy_id' => 2));
1481      $wpdb->insert( $wpdb->term_relationships, array('object_id' => 2, 'term_taxonomy_id' => 2));
1482  
1483      // First post
1484      $now = date('Y-m-d H:i:s');
1485      $now_gmt = gmdate('Y-m-d H:i:s');
1486      $first_post = get_site_option( 'first_post' );
1487      if( $first_post == false ) {
1488          $first_post = stripslashes( __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' ) );
1489      }
1490      $first_post = str_replace( "SITE_URL", clean_url("http://" . $current_site->domain . $current_site->path), $first_post );
1491      $first_post = str_replace( "SITE_NAME", $current_site->site_name, $first_post );
1492      $wpdb->insert( $wpdb->posts, array(
1493          'post_author' => $user_id, 
1494          'post_date' => $now, 
1495          'post_date_gmt' => $now_gmt,
1496          'post_content' => stripslashes( $first_post ), 
1497          'post_excerpt' => '', 
1498          'post_title' => __('Hello world!'),
1499          'post_name' => __('hello-world'),
1500          'post_modified' => $now,
1501          'post_modified_gmt' => $now_gmt,
1502          'comment_count' => 1,
1503          'to_ping' => '',
1504          'pinged' => '',
1505          'post_content_filtered' => ''
1506      ) );
1507      $wpdb->insert( $wpdb->term_relationships, array('object_id' => 1, 'term_taxonomy_id' => 1));
1508      update_option( "post_count", 1 );
1509  
1510      // First page
1511      $wpdb->insert( $wpdb->posts, array(
1512          'post_author' => $user_id, 
1513          'post_date' => $now, 
1514          'post_date_gmt' => $now_gmt,
1515          'post_content' => get_site_option( 'first_page' ),
1516          'post_excerpt' => '', 
1517          'post_title' => __('About'),
1518          'post_name' => __('about'),
1519          'post_modified' => $now,
1520          'post_modified_gmt' => $now_gmt,
1521          'post_status' => 'publish',
1522          'post_type' => 'page',
1523          'to_ping' => '',
1524          'pinged' => '',
1525          'post_content_filtered' => ''
1526      ) );
1527      
1528      // Flush rules to pick up the new page.
1529      $wp_rewrite->init();
1530      $wp_rewrite->flush_rules();
1531  
1532      // Default comment
1533      $wpdb->insert( $wpdb->comments, array(
1534          'comment_post_ID' => '1', 
1535          'comment_author' => __( get_site_option( 'first_comment_author' ) ),
1536          'comment_author_email' => '',
1537          'comment_author_url' => get_site_option( 'first_comment_url' ),
1538          'comment_author_IP' => '127.0.0.1', 
1539          'comment_date' => $now,
1540          'comment_date_gmt' => $now_gmt, 
1541          'comment_content' => __( get_site_option( 'first_comment' ) )
1542      ) );
1543      
1544      $user = new WP_User($user_id);
1545      $wpdb->update( $wpdb->options, array('option_value' => $user->user_email), array('option_name' => 'admin_email') );
1546  
1547      // Remove all perms except for the login user.
1548      $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'user_level') );
1549      $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'capabilities') );
1550      
1551      // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
1552      if ( !is_site_admin( $user->user_login ) && $user_id != 1 )
1553          $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $wpdb->base_prefix.'1_capabilities') );
1554  
1555      $wpdb->suppress_errors( false );
1556  }
1557  
1558  function wpmu_welcome_notification($blog_id, $user_id, $password, $title, $meta = '') {
1559      global $current_site;
1560  
1561      if( !apply_filters('wpmu_welcome_notification', $blog_id, $user_id, $password, $title, $meta) )
1562          return false;
1563  
1564      $welcome_email = stripslashes( get_site_option( 'welcome_email' ) );
1565      if( $welcome_email == false )
1566          $welcome_email = stripslashes( __( "Dear User,
1567  
1568  Your new SITE_NAME blog has been successfully set up at:
1569  BLOG_URL
1570  
1571  You can log in to the administrator account with the following information:
1572  Username: USERNAME
1573  Password: PASSWORD
1574  Login Here: BLOG_URLwp-login.php
1575  
1576  We hope you enjoy your new weblog.
1577  Thanks!
1578  
1579  --The WordPress Team
1580  SITE_NAME" ) );
1581  
1582      $url = get_blogaddress_by_id($blog_id);
1583      $user = new WP_User($user_id);
1584  
1585      $welcome_email = str_replace( "SITE_NAME", $current_site->site_name, $welcome_email );
1586      $welcome_email = str_replace( "BLOG_TITLE", $title, $welcome_email );
1587      $welcome_email = str_replace( "BLOG_URL", $url, $welcome_email );
1588      $welcome_email = str_replace( "USERNAME", $user->user_login, $welcome_email );
1589      $welcome_email = str_replace( "PASSWORD", $password, $welcome_email );
1590  
1591      $welcome_email = apply_filters( "update_welcome_email", $welcome_email, $blog_id, $user_id, $password, $title, $meta);
1592      $admin_email = get_site_option( "admin_email" );
1593      if( $admin_email == '' )
1594          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1595      $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1596      $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1597      $message = $welcome_email;
1598      if( empty( $current_site->site_name ) )
1599          $current_site->site_name = "WordPress MU";
1600      $subject = apply_filters( 'update_welcome_subject', sprintf(__('New %1$s Blog: %2$s'), $current_site->site_name, stripslashes( $title ) ) );
1601      wp_mail($user->user_email, $subject, $message, $message_headers);
1602      return true;
1603  }
1604  
1605  function wpmu_welcome_user_notification($user_id, $password, $meta = '') {
1606      global $current_site;
1607  
1608      if( !apply_filters('wpmu_welcome_user_notification', $user_id, $password, $meta) )
1609          return false;
1610  
1611      $welcome_email = get_site_option( 'welcome_user_email' ); 
1612  
1613      $user = new WP_User($user_id);
1614  
1615      $welcome_email = apply_filters( "update_welcome_user_email", $welcome_email, $user_id, $password, $meta);
1616      $welcome_email = str_replace( "SITE_NAME", $current_site->site_name, $welcome_email );
1617      $welcome_email = str_replace( "USERNAME", $user->user_login, $welcome_email );
1618      $welcome_email = str_replace( "PASSWORD", $password, $welcome_email );
1619      $welcome_email = str_replace( "LOGINLINK", wp_login_url(), $welcome_email );
1620  
1621      $admin_email = get_site_option( "admin_email" );
1622      if( $admin_email == '' )
1623          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1624      $from_name = get_site_option( "site_name" ) == '' ? 'WordPress' : wp_specialchars( get_site_option( "site_name" ) );
1625      $message_headers = "MIME-Version: 1.0\n" . "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1626      $message = $welcome_email;
1627      if( empty( $current_site->site_name ) )
1628          $current_site->site_name = "WordPress MU";
1629      $subject = apply_filters( 'update_welcome_user_subject', sprintf(__('New %1$s User: %2$s'), $current_site->site_name, $user->user_login) );
1630      wp_mail($user->user_email, $subject, $message, $message_headers);
1631      return true;
1632  }
1633  
1634  function get_current_site() {
1635      global $current_site;
1636      return $current_site;
1637  }
1638  
1639  function get_user_id_from_string( $string ) {
1640      global $wpdb;
1641  
1642      $user_id = 0;
1643      if ( is_email( $string ) ) {
1644          $user = get_user_by_email($string);
1645          if ( $user )
1646              $user_id = $user->ID;
1647      } elseif ( is_numeric( $string ) ) {
1648          $user_id = $string;
1649      } else {
1650          $user = get_userdatabylogin($string);
1651          if ( $user )
1652              $user_id = $user->ID;
1653      }
1654  
1655      return $user_id;
1656  }
1657  
1658  function get_most_recent_post_of_user( $user_id ) {
1659      global $wpdb;
1660  
1661      $user_blogs = get_blogs_of_user( (int) $user_id );
1662      $most_recent_post = array();
1663  
1664      // Walk through each blog and get the most recent post
1665      // published by $user_id
1666      foreach ( (array) $user_blogs as $blog ) {
1667          $recent_post = $wpdb->get_row( $wpdb->prepare("SELECT ID, post_date_gmt FROM {$wpdb->base_prefix}{$blog->userblog_id}_posts WHERE post_author = %d AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1", $user_id ), ARRAY_A);
1668  
1669          // Make sure we found a post
1670          if ( isset($recent_post['ID']) ) {
1671              $post_gmt_ts = strtotime($recent_post['post_date_gmt']);
1672  
1673              // If this is the first post checked or if this post is
1674              // newer than the current recent post, make it the new
1675              // most recent post.
1676              if (
1677                  !isset($most_recent_post['post_gmt_ts'])
1678                  || ($post_gmt_ts > $most_recent_post['post_gmt_ts'])
1679              ) {
1680                  $most_recent_post = array(
1681                      'blog_id'        => $blog->userblog_id,
1682                      'post_id'        => $recent_post['ID'],
1683                      'post_date_gmt'    => $recent_post['post_date_gmt'],
1684                      'post_gmt_ts'    => $post_gmt_ts
1685                  );
1686              }
1687          }
1688      }
1689  
1690      return $most_recent_post;
1691  }
1692  
1693  /* Misc functions */
1694  function get_dirsize( $directory ) {
1695      $dirsize = get_transient( 'dirsize_cache' );
1696      if ( is_array( $dirsize ) && isset( $dirsize[ $directory ][ 'size' ] ) ) {
1697          return $dirsize[ $directory ][ 'size' ];
1698      }
1699      if ( false == is_array( $dirsize ) ) {
1700          $dirsize = array();
1701      }
1702      $dirsize[ $directory ][ 'size' ] = recurse_dirsize( $directory );
1703  
1704      set_transient( 'dirsize_cache', $dirsize, 3600 );
1705      return $dirsize[ $directory ][ 'size' ];
1706  }
1707  
1708  function clear_dirsize_cache( $file = true ) {
1709      delete_transient( 'dirsize_cache' );
1710      return $file;
1711  }
1712  add_filter( 'wp_handle_upload', 'clear_dirsize_cache' );
1713  add_action( 'delete_attachment', 'clear_dirsize_cache' );
1714  
1715  function recurse_dirsize( $directory ) {
1716      $size = 0;
1717      if(substr($directory,-1) == '/') $directory = substr($directory,0,-1);
1718      if(!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) return false;
1719      if($handle = opendir($directory)) {
1720          while(($file = readdir($handle)) !== false) {
1721              $path = $directory.'/'.$file;
1722              if($file != '.' && $file != '..') {
1723                  if(is_file($path)) {
1724                      $size += filesize($path);
1725                  } elseif(is_dir($path)) {
1726                      $handlesize = recurse_dirsize($path);
1727                      if($handlesize >= 0) {
1728                          $size += $handlesize;
1729                      } else {
1730                          return false;
1731                      }
1732                  }
1733              }
1734          }
1735          closedir($handle);
1736      }
1737      return $size;
1738  }
1739  
1740  function upload_is_user_over_quota( $echo = true ) {
1741      if ( get_site_option( 'upload_space_check_disabled' ) ) {
1742          return true;
1743      }
1744      $spaceAllowed = get_space_allowed();
1745      if(empty($spaceAllowed) || !is_numeric($spaceAllowed))
1746          $spaceAllowed = 10;    // Default space allowed is 10 MB 
1747      
1748      $dirName = BLOGUPLOADDIR;
1749      $size = get_dirsize($dirName) / 1024 / 1024;
1750      
1751      if( ($spaceAllowed-$size) < 0 ) { 
1752          if( $echo )
1753              _e( "Sorry, you have used your space allocation. Please delete some files to upload more files." ); //No space left
1754          return true;
1755      } else {
1756          return false;
1757      }
1758  }
1759  
1760  function check_upload_mimes($mimes) {
1761      $site_exts = explode( " ", get_site_option( "upload_filetypes" ) );
1762      foreach ( $site_exts as $ext ) {
1763          foreach ( $mimes as $ext_pattern => $mime ) {
1764              if( $ext != '' && strpos( $ext_pattern, $ext ) !== false ) {
1765                  $site_mimes[$ext_pattern] = $mime;
1766              }
1767          }
1768      }
1769      return $site_mimes;
1770  }
1771  
1772  function update_posts_count( $deprecated = '' ) {
1773      global $wpdb;
1774      update_option( "post_count", (int) $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_status = 'publish' and post_type = 'post'" ) );
1775  }
1776  
1777  function wpmu_log_new_registrations( $blog_id, $user_id ) {
1778      global $wpdb;
1779      $user = new WP_User( (int) $user_id );
1780      $wpdb->insert( $wpdb->registration_log, array('email' => $user->user_email, 'IP' => preg_replace( '/[^0-9., ]/', '',$_SERVER['REMOTE_ADDR'] ), 'blog_id' => $blog_id, 'date_registered' => current_time('mysql')) );
1781  }
1782  
1783  function fix_import_form_size( $size ) {
1784      if( upload_is_user_over_quota( false ) == true ) {
1785          return 0;
1786      }
1787      
1788      $spaceAllowed = 1024 * 1024 * get_space_allowed();
1789      $dirName = BLOGUPLOADDIR;
1790      $dirsize = get_dirsize($dirName) ;
1791      if( $size > $spaceAllowed - $dirsize ) {
1792          return $spaceAllowed - $dirsize; // remaining space
1793      } else {
1794          return $size; // default
1795      }
1796  }
1797  
1798  if ( !function_exists('graceful_fail') ) :
1799  function graceful_fail( $message ) {
1800      $message = apply_filters('graceful_fail', $message);
1801      $message_template = apply_filters( 'graceful_fail_template', 
1802  '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1803  <html xmlns="http://www.w3.org/1999/xhtml"><head profile="http://gmpg.org/xfn/11">
1804  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1805  <title>Error!</title>
1806  <style type="text/css">
1807  img {
1808      border: 0;
1809  }
1810  body {
1811  line-height: 1.6em; font-family: Georgia, serif; width: 390px; margin: auto;
1812  text-align: center;
1813  }
1814  .message {
1815      font-size: 22px;
1816      width: 350px;
1817      margin: auto;
1818  }
1819  </style>
1820  </head>
1821  <body>
1822  <p class="message">%s</p>
1823  </body>
1824  </html>' );
1825      die( sprintf( $message_template, $message ) );
1826  }
1827  endif;
1828  
1829  /* Delete blog */
1830  class delete_blog {
1831  	function delete_blog() {
1832          $this->reallydeleteblog = false;
1833          add_action('admin_menu', array(&$this, 'admin_menu'));
1834          add_action('admin_footer', array(&$this, 'admin_footer'));
1835      }
1836  
1837  	function admin_footer() {
1838          global $wpdb, $current_blog, $current_site;
1839          if( $current_blog->domain . $current_blog->path == $current_site->domain . $current_site->path )
1840              return false;
1841  
1842          if( $this->reallydeleteblog == true ) {
1843              wpmu_delete_blog( $wpdb->blogid ); 
1844          }
1845      }
1846  
1847  	function admin_menu() {
1848          global $current_blog, $current_site;
1849          if( $current_blog->domain . $current_blog->path != $current_site->domain . $current_site->path )
1850              add_submenu_page('options-general.php', __('Delete Blog'), __('Delete Blog'), 'manage_options', 'delete-blog', array(&$this, 'plugin_content'));
1851      }
1852  
1853  	function plugin_content() {
1854          global $current_blog, $current_site;
1855          $this->delete_blog_hash = get_settings('delete_blog_hash');
1856          echo '<div class="wrap"><h2>' . __('Delete Blog') . '</h2>';
1857          if( $_POST['action'] == "deleteblog" && $_POST['confirmdelete'] == '1' ) {
1858              $hash = substr( md5( $_SERVER['REQUEST_URI'] . time() ), 0, 6 );
1859              update_option( "delete_blog_hash", $hash );
1860              $url_delete = get_option( "siteurl" ) . "/wp-admin/options-general.php?page=delete-blog&h=" . $hash;
1861              $msg = __("Dear User,
1862  You recently clicked the 'Delete Blog' link on your blog and filled in a 
1863  form on that page.
1864  If you really want to delete your blog, click the link below. You will not
1865  be asked to confirm again so only click this link if you are 100% certain:
1866  URL_DELETE
1867  
1868  If you delete your blog, please consider opening a new blog here
1869  some time in the future! (But remember your current blog and username 
1870  are gone forever.)
1871  
1872  Thanks for using the site,
1873  Webmaster
1874  SITE_NAME
1875  ");
1876              $msg = str_replace( "URL_DELETE", $url_delete, $msg );
1877              $msg = str_replace( "SITE_NAME", $current_site->site_name, $msg );
1878              wp_mail( get_option( "admin_email" ), "[ " . get_option( "blogname" ) . " ] ".__("Delete My Blog"), $msg );
1879              ?>
1880              <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>
1881              <?php
1882          } elseif( isset( $_GET['h'] ) && $_GET['h'] != '' && get_option('delete_blog_hash') != false ) {
1883              if( get_option('delete_blog_hash') == $_GET['h'] ) {
1884                  $this->reallydeleteblog = true;
1885                  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>";
1886              } else {
1887                  $this->reallydeleteblog = false;
1888                  echo "<p>" . __("I'm sorry, the link you clicked is stale. Please select another option.") . "</p>";
1889              }
1890          } else {
1891  ?>
1892              <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>
1893              <p><?php _e('Remember, once deleted your blog cannot be restored.') ?></p>
1894              <form method='post' name='deletedirect'>
1895              <input type="hidden" name="page" value="<?php echo $_GET['page'] ?>" />
1896              <input type='hidden' name='action' value='deleteblog' />
1897              <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>
1898              <p class="submit"><input type='submit' value='<?php _e('Delete My Blog Permanently &raquo;') ?>' /></p>
1899              </form>
1900  <?php
1901          }
1902          echo "</div>";
1903      }
1904  }
1905  $delete_blog_obj = new delete_blog();
1906  
1907  /* Global Categories */
1908  function global_terms( $term_id, $deprecated = '' ) {
1909      global $wpdb;
1910  
1911      $term_id = intval( $term_id );
1912      $c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->terms WHERE term_id = %d", $term_id ) );
1913  
1914      if ( null == $c ) {
1915          return $term_d;
1916      }
1917  
1918      if ( sanitize_title( $c->name ) != $c->slug ) {
1919          $c->name = str_replace( '_', ' ', ucfirst( $c->slug ) );
1920      }
1921  
1922      $global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE category_nicename = %s", $c->slug ) );
1923      if ( $global_id == null ) {
1924          $wpdb->insert( $wpdb->sitecategories, array('cat_name' => $c->name, 'category_nicename' => $c->slug) );
1925          $global_id = $wpdb->insert_id;
1926      }
1927  
1928      if ( $global_id == $term_id )
1929          return $global_id;
1930  
1931      if( get_option( 'default_category' ) == $term_id )
1932          update_option( 'default_category', $global_id );
1933  
1934      $wpdb->update( $wpdb->terms, array('term_id' => $global_id), array('term_id' => $term_id) );
1935      $wpdb->update( $wpdb->term_taxonomy, array('term_id' => $global_id), array('term_id' => $term_id) );
1936      $wpdb->update( $wpdb->term_taxonomy, array('parent' => $global_id), array('parent' => $term_id) );
1937  
1938      clean_term_cache($term_id);
1939  
1940      return $global_id; 
1941  }   
1942  
1943  function redirect_this_site( $deprecated = '' ) {
1944      global $current_site;
1945      return array( $current_site->domain );
1946  }
1947  
1948  function upload_is_file_too_big( $upload ) {
1949      if( is_array( $upload ) == false || defined( 'WP_IMPORTING' ) )
1950          return $upload;
1951      if( strlen( $upload[ 'bits' ] )  > ( 1024 * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
1952          return sprintf(__( "This file is too big. Files must be less than %dKb in size.<br />" ), get_site_option( 'fileupload_maxk', 1500 )); 
1953      }
1954  
1955      return $upload;
1956  }
1957  
1958  function wordpressmu_authenticate_siteadmin( $user, $password = '' ) {
1959      if( is_site_admin( $user->user_login ) == false && ( $primary_blog = get_usermeta( $user->user_id, "primary_blog" ) ) ) {
1960          $details = get_blog_details( $primary_blog );
1961          if( is_object( $details ) && $details->spam == 1 ) {
1962              return new WP_Error('blog_suspended', __('Blog Suspended.'));
1963          }
1964      }
1965      return $user;
1966  }
1967  
1968  function wordpressmu_wp_mail_from( $email ) {
1969      if( strpos( $email, 'wordpress@' ) !== false )
1970          $email = get_option( 'admin_email' );
1971      return $email;
1972  }
1973  
1974  /*
1975  XMLRPC getUsersBlogs() for a multiblog environment
1976  http://trac.mu.wordpress.org/attachment/ticket/551/xmlrpc-mu.php
1977  */
1978  function wpmu_blogger_getUsersBlogs($args) {
1979      global $current_blog;
1980      $domain = $current_blog->domain;
1981      $path = $current_blog->path . 'xmlrpc.php';
1982  
1983      $rpc = new IXR_Client("http://{$domain}{$path}");
1984      $rpc->query('wp.getUsersBlogs', $args[1], $args[2]);
1985      $blogs = $rpc->getResponse();
1986  
1987      if ( isset($blogs['faultCode']) ) {
1988          return new IXR_Error($blogs['faultCode'], $blogs['faultString']);
1989      }
1990  
1991      if ( $_SERVER['HTTP_HOST'] == $domain && $_SERVER['REQUEST_URI'] == $path ) {
1992          return $blogs;
1993      } else {
1994          foreach ( (array) $blogs as $blog ) {
1995              if ( strpos($blog['url'], $_SERVER['HTTP_HOST']) )
1996                  return array($blog);
1997          }
1998          return array();
1999      }
2000  }
2001  
2002  function attach_wpmu_xmlrpc($methods) {
2003      $methods['blogger.getUsersBlogs'] = 'wpmu_blogger_getUsersBlogs';
2004      return $methods;
2005  }
2006  
2007  function mu_locale( $locale ) {
2008      if( defined('WP_INSTALLING') == false ) {
2009          $mu_locale = get_option('WPLANG');
2010          if( $mu_locale === false )
2011              $mu_locale = get_site_option('WPLANG');
2012  
2013          if( $mu_locale !== false )
2014              return $mu_locale;
2015      }
2016      return $locale;
2017  }
2018  
2019  function signup_nonce_fields() {
2020      $id = mt_rand();
2021      echo "<input type='hidden' name='signup_form_id' value='{$id}' />";
2022      wp_nonce_field('signup_form_' . $id, '_signup_form', false);
2023  }
2024  
2025  function signup_nonce_check( $result ) {
2026      if( !strpos( $_SERVER[ 'PHP_SELF' ], 'wp-signup.php' ) )
2027          return $result;
2028  
2029      if ( wp_create_nonce('signup_form_' . $_POST[ 'signup_form_id' ]) != $_POST['_signup_form'] )
2030          wp_die( __('Please try again!') );
2031  
2032      return $result;
2033  }
2034  
2035  function maybe_redirect_404() {
2036      global $current_site;
2037      if( is_main_blog() && is_404() && defined( 'NOBLOGREDIRECT' ) && constant( 'NOBLOGREDIRECT' ) != '' ) {
2038          $destination = constant( 'NOBLOGREDIRECT' );
2039          if ( $destination == '%siteurl%' )
2040              $destination = $current_site->domain . $current_site->path;
2041          wp_redirect( $destination );
2042          exit();
2043      }
2044  }
2045  
2046  function remove_tinymce_media_button( $buttons ) {
2047      unset( $buttons[ array_search( 'media', $buttons ) ] );
2048      return $buttons;
2049  }
2050  
2051  function maybe_add_existing_user_to_blog() {
2052      if ( false === strpos( $_SERVER[ 'REQUEST_URI' ], '/newbloguser/' ) ) {
2053          return false;
2054      }
2055  
2056      $parts = explode( '/', $_SERVER[ 'REQUEST_URI' ] );
2057      $key = array_pop( $parts );
2058      if ( $key == '' )
2059          $key = array_pop( $parts );
2060      $details = get_option( "new_user_" . $key );
2061      add_existing_user_to_blog( $details );
2062      delete_option( 'new_user_' . $key );
2063      wp_die( sprintf(__('You have been added to this blog. Please visit the <a href="%s">homepage</a> or <a href="%s">login</a> using your username and password.'), site_url(), admin_url() ) );
2064  }
2065  
2066  function add_existing_user_to_blog( $details = false ) {
2067      if ( is_array( $details ) ) {
2068          add_user_to_blog( '', $details[ 'user_id' ], $details[ 'role' ] );
2069          do_action( "added_existing_user", $details[ 'user_id' ] );
2070      }
2071  }
2072  
2073  function add_new_user_to_blog( $user_id, $email, $meta ) {
2074      global $current_site;
2075      if( $meta[ 'add_to_blog' ] ) {
2076          $blog_id = $meta[ 'add_to_blog' ];
2077          $role = $meta[ 'new_role' ];
2078          remove_user_from_blog($user_id, $current_site->blogid); // remove user from main blog.
2079          add_user_to_blog( $blog_id, $user_id, $role );
2080          update_usermeta( $user_id, 'primary_blog', $blog_id );
2081      }
2082  }
2083  
2084  function fix_phpmailer_messageid( $phpmailer ) {
2085      global $current_site;
2086      $phpmailer->Hostname = $current_site->domain;
2087  }
2088  
2089  function is_user_spammy( $username = 0 ) {
2090      if( $username == 0 ) {
2091          global $current_user;
2092          $user_id = $current_user->ID;
2093      } else {
2094          $user_id = get_user_id_from_string( $username );
2095      }
2096      $u = new WP_User( $user_id );
2097      if( $u->spam == 1 )
2098          return true;
2099      return false;
2100  }
2101  
2102  function login_spam_check( $user, $password ) {
2103      if( is_user_spammy( $user->ID ) )
2104          return new WP_Error('invalid_username', __('<strong>ERROR</strong>: your account has been marked as a spammer.'));
2105      return $user;
2106  }
2107  add_action( 'wp_authenticate_user', 'login_spam_check', 10, 2 );
2108  
2109  function update_blog_public( $old_value, $value ) {
2110      global $wpdb;
2111      do_action('update_blog_public');
2112      update_blog_status( $wpdb->blogid, 'public', (int) $value );
2113  }
2114  add_action('update_option_blog_public', 'update_blog_public', 10, 2);
2115  
2116  function strtolower_usernames( $username, $raw, $strict ) {
2117      return strtolower( $username );
2118  }
2119  
2120  /* Short circuit the update checks. Make sure update informtion is 
2121     stored in wp_sitemeta rather than the options table of individual blogs */
2122  
2123  // update_plugins (transient)
2124  function site_delete_update_plugins() {
2125      return update_site_option( 'update_plugins', false );
2126  }
2127  add_action( 'delete_transient_update_plugins', 'site_delete_update_plugins' );
2128  
2129  function site_pre_update_plugins() {
2130      return get_site_option( 'update_plugins' );
2131  }
2132  add_filter( 'pre_transient_update_plugins', 'site_pre_update_plugins' );
2133  
2134  function site_pre_set_transient_update_plugins( $value ) {
2135      update_site_option( 'update_plugins', $value );
2136      return $value;
2137  }
2138  add_filter( 'pre_set_transient_update_plugins', 'site_pre_set_transient_update_plugins' );
2139  
2140  add_action( 'add_option__transient_update_plugins', 'site_add_option__transient_update');
2141  
2142  // update_themes (transient)
2143  function site_delete_update_themes() {
2144      return update_site_option( 'update_themes', false );
2145  }
2146  add_action( 'delete_transient_update_themes', 'site_delete_update_themes' );
2147  
2148  function site_pre_update_themes() {
2149      return get_site_option( 'update_themes' );
2150  }
2151  add_filter( 'pre_transient_update_themes', 'site_pre_update_themes' );
2152  
2153  function site_pre_set_transient_update_themes( $value ) {
2154      update_site_option( 'update_themes', $value );
2155      return $value;
2156  }
2157  add_filter( 'pre_set_transient_update_themes', 'site_pre_set_transient_update_themes' );
2158  
2159  add_action( 'add_option__transient_update_themes', 'site_add_option__transient_update');
2160  
2161  // update_core (transient)
2162  function site_delete_update_core() {
2163      return update_site_option( 'update_core', false );
2164  }
2165  add_action( 'delete_transient_update_core', 'site_delete_update_core' );
2166  
2167  function site_pre_update_core() {
2168      return get_site_option( 'update_core' );
2169  }
2170  add_filter( 'pre_transient_update_core', 'site_pre_update_core' );
2171  
2172  function site_pre_set_transient_update_core( $value ) {
2173      update_site_option( 'update_core', $value );
2174      return $value;
2175  }
2176  add_filter( 'pre_set_transient_update_core', 'site_pre_set_transient_update_core' );
2177  
2178  add_action( 'add_option__transient_update_core', 'site_add_option__transient_update');
2179  
2180  // dismissed_update_core (option, not a transient)
2181  function site_pre_dismissed_update_core() {
2182      return get_site_option( 'dismissed_update_core' );
2183  }
2184  add_filter( 'pre_option_dismissed_update_core', 'site_pre_dismissed_update_core' );
2185  
2186  function site_pre_update_option_dismissed_update_core( $newvalue, $oldvalue ) {
2187      update_site_option( 'dismissed_update_core', $newvalue );
2188      delete_option('dismissed_update_core');
2189      // Return the old value so the update_option() call is aborted after this filter is run. It's in sitemeta now.
2190      return $oldvalue;
2191  }
2192  add_filter( 'pre_update_option_dismissed_update_core', 'site_pre_update_option_dismissed_update_core', 10, 2 );
2193  
2194  
2195  
2196  function site_add_option__transient_update($name) {
2197      delete_option($name);
2198  }
2199  
2200  /* Redirect all hits to "dashboard" blog to wp-admin/ Dashboard. */
2201  function redirect_mu_dashboard() {
2202      global $current_site, $current_blog;
2203  
2204      $dashboard_blog = get_dashboard_blog();
2205      if ( $current_blog->blog_id == $dashboard_blog->blog_id && $dashboard_blog->blog_id != $current_site->blog_id ) { 
2206          $protocol = ( is_ssl() ? 'https://' : 'http://' ); 
2207          wp_redirect( $protocol . $dashboard_blog->domain . trailingslashit( $dashboard_blog->path ) . 'wp-admin/' );
2208          die();
2209      }
2210  }
2211  add_action( 'template_redirect', 'redirect_mu_dashboard' );
2212  
2213  function get_dashboard_blog() {
2214      global $current_site;
2215  
2216      if ( get_site_option( 'dashboard_blog' ) == false ) {
2217          return get_blog_details( $current_site->blog_id );
2218      } else {
2219          return get_blog_details( get_site_option( 'dashboard_blog' ) );
2220      }
2221  }
2222  
2223  function is_user_option_local( $key, $user_id = 0, $blog_id = 0 ) {
2224      global $current_user, $wpdb;
2225  
2226      if( $user_id == 0 )
2227          $user_id = $current_user->ID;
2228      if( $blog_id == 0 )
2229          $blog_id = $wpdb->blogid;
2230      
2231      $local_key = $wpdb->base_prefix . $blog_id . "_" . $key;
2232      if( isset( $current_user->$local_key ) )
2233          return true;
2234      return false;
2235  }
2236  
2237  function fix_active_plugins( $value ) {
2238      if( false == is_array( $value ) )
2239          $value = array();
2240      return $value;
2241  }
2242  add_filter( "option_active_plugins", "fix_active_plugins" );
2243  
2244  if ( !function_exists('rss_gc') ) :
2245  function rss_gc() {
2246      global $wpdb;
2247      // Garbage Collection
2248      $rows = $wpdb->get_results( "SELECT meta_key FROM {$wpdb->sitemeta} WHERE meta_key LIKE 'rss\_%\_ts' AND meta_value < unix_timestamp( date_sub( NOW(), interval 7200 second ) )" );
2249      if( is_array( $rows ) ) {
2250          foreach( $rows as $row ) {
2251              $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->sitemeta} WHERE meta_key = %s", $row->meta_key ) );
2252              $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->sitemeta} WHERE meta_key = %s", str_replace( '_ts', '', $row->meta_key ) ) );
2253          }
2254      }
2255  }
2256  endif;
2257  add_action( 'wp_rss_gc', 'rss_gc' );
2258  
2259  function retrieve_password_sitename( $title ) {
2260      global $current_site;
2261      return sprintf( __( '[%s] Password Reset' ), $current_site->site_name );
2262  }
2263  add_filter( 'retrieve_password_title', 'retrieve_password_sitename' );
2264  
2265  function reset_password_sitename( $title ) {
2266      global $current_site;
2267      return sprintf( __( '[%s] Your new password' ), $current_site->site_name );
2268  }
2269  add_filter( 'password_reset_title', 'reset_password_sitename' );
2270  
2271  function lowercase_username( $username, $raw_username, $strict ) {
2272      return strtolower( $username );
2273  }
2274  add_filter( 'sanitize_user', 'lowercase_username', 10, 3 );
2275  
2276  function users_can_register_signup_filter() {
2277      $registration = get_site_option('registration');
2278      if ( $registration == 'all' || $registration == 'user' ) {
2279          return true;
2280      } else {
2281          return false;
2282      }
2283  }
2284  add_filter('option_users_can_register', 'users_can_register_signup_filter');
2285  
2286  function welcome_user_msg_filter( $text ) {
2287      if ( !$text ) {
2288          return __( "Dear User,
2289  
2290  Your new account is set up.
2291  
2292  You can log in with the following information:
2293  Username: USERNAME
2294  Password: PASSWORD
2295  LOGINLINK
2296  
2297  Thanks!
2298  
2299  --The Team @ SITE_NAME" );
2300      }
2301      return $text;
2302  }
2303  add_filter( 'site_option_welcome_user_email', 'welcome_user_msg_filter' );
2304  
2305  function first_page_filter( $text ) {
2306      if ( !$text ) {
2307          return __( "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." );
2308      }
2309      return $text;
2310  }
2311  add_filter( 'site_option_first_page', 'first_page_filter' );
2312  
2313  function first_comment_filter( $text ) {
2314      if ( !$text ) {
2315          return __( "This is an example of a WordPress comment, 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 comments like this one or sub-comments as you like and manage all of your content inside of WordPress." );
2316      }
2317      return $text;
2318  }
2319  add_filter( 'site_option_first_comment', 'first_comment_filter' );
2320  
2321  function first_comment_author_filter( $text ) {
2322      if ( !$text ) {
2323          return __( "Mr WordPress" );
2324      }
2325      return $text;
2326  }
2327  add_filter( 'site_option_first_comment_author', 'first_comment_author_filter' );
2328  
2329  function first_comment_url_filter( $text ) {
2330      global $current_site;
2331      if ( !$text ) {
2332          return 'http://' . $current_site->domain . $current_site->path;
2333      }
2334      return $text;
2335  }
2336  add_filter( 'site_option_first_comment_url', 'first_comment_url_filter' );
2337  
2338  function mu_filter_plugins_list( $active_plugins ) {
2339      $active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
2340  
2341      if ( !$active_sitewide_plugins )
2342          return $active_plugins;
2343      
2344      $plugins = array_merge( (array) $active_plugins, array_keys( (array) $active_sitewide_plugins ) );
2345      sort( $plugins );
2346      return $plugins;
2347  }
2348  add_filter( 'active_plugins', 'mu_filter_plugins_list' );
2349  
2350   /**
2351   * Whether to force SSL on content.
2352   *
2353   * @since 2.8.5
2354   *
2355   * @param string|bool $force
2356   * @return bool True if forced, false if not forced.
2357   */
2358  function force_ssl_content( $force = '' ) {
2359          static $forced_content;
2360  
2361          if ( '' != $force ) {
2362                  $old_forced = $forced_content;
2363                  $forced_content = $force;
2364                  return $old_forced;
2365          }
2366          return $forced_content;
2367  }
2368  
2369  /**
2370   * Formats an String URL to use HTTPS if HTTP is found.
2371   * Useful as a filter.
2372   *
2373   * @since 2.8.5
2374   **/
2375  function filter_SSL( $url) {
2376      if ( !is_string( $url ) ) {
2377          return get_bloginfo( 'url' ); //return home blog url with proper scheme
2378      }
2379  
2380      $arrURL = parse_url( $url );
2381  
2382      if ( force_ssl_content() && is_ssl() ) {
2383          if ( 'http' === $arrURL['scheme'] && 'https' !== $arrURL['scheme'] ) {
2384              $url = str_replace( $arrURL['scheme'], 'https', $url );
2385          }
2386      }
2387  
2388      return $url;
2389  }
2390  
2391  function maybe_cancel_post_by_email() {
2392      if ( false == defined( 'POST_BY_EMAIL' ) ) {
2393          die( __( 'This action has been disabled by the administrator' ) );
2394      }
2395  }
2396  add_action( 'wp-mail.php', 'maybe_cancel_post_by_email' );
2397  
2398  ?>


Generated: Mon May 3 12:25:32 2010 Cross-referenced by PHPXref 0.7