[ Index ]

PHP Cross Reference of WordPress 3.0 beta 1

[ Index ]     [ Variables ]     [ Functions ]     [ Classes ]     [ Constants ]     [ Statistics ]

title

Body

[close]

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

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


Generated: Mon Apr 5 14:26:09 2010 Cross-referenced by PHPXref 0.7