[ XREF Home ] [ Index ]

PHP Cross Reference of WordPress Trunk

Provided by Yoast

title

Body

[close]

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

   1  <?php
   2  /**
   3   * Multi-site WordPress API
   4   *
   5   * @package WordPress
   6   * @subpackage Multisite
   7   * @since 3.0.0
   8   */
   9  
  10  /**
  11   * Gets the network's site and user counts.
  12   *
  13   * @since MU 1.0
  14   * @uses get_blog_count()
  15   * @uses get_user_count()
  16   *
  17   * @return array Site and user count for the network.
  18   */
  19  function get_sitestats() {
  20      global $wpdb;
  21  
  22      $stats['blogs'] = get_blog_count();
  23      $stats['users'] = get_user_count();
  24  
  25      return $stats;
  26  }
  27  
  28  /**
  29   * Get the admin for a domain/path combination.
  30   *
  31   * @since MU 1.0
  32   *
  33   * @param string $sitedomain Optional. Site domain.
  34   * @param string $path Optional. Site path.
  35   * @return array The network admins
  36   */
  37  function get_admin_users_for_domain( $sitedomain = '', $path = '' ) {
  38      global $wpdb;
  39  
  40      if ( ! $sitedomain )
  41          $site_id = $wpdb->siteid;
  42      else
  43          $site_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM $wpdb->site WHERE domain = %s AND path = %s", $sitedomain, $path ) );
  44  
  45      if ( $site_id )
  46          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 );
  47  
  48      return false;
  49  }
  50  
  51  /**
  52   * Get one of a user's active blogs
  53   *
  54   * Returns the user's primary blog, if she has one and
  55   * it is active. If it's inactive, function returns another
  56   * active blog of the user. If none are found, the user
  57   * is added as a Subscriber to the Dashboard Blog and that blog
  58   * is returned.
  59   *
  60   * @since MU 1.0
  61   * @uses get_blogs_of_user()
  62   * @uses add_user_to_blog()
  63   * @uses get_blog_details()
  64   *
  65   * @param int $user_id The unique ID of the user
  66   * @return object The blog object
  67   */
  68  function get_active_blog_for_user( $user_id ) {
  69      global $wpdb;
  70      $blogs = get_blogs_of_user( $user_id );
  71      if ( empty( $blogs ) )
  72          return null;
  73  
  74      if ( !is_multisite() )
  75          return $blogs[$wpdb->blogid];
  76  
  77      $primary_blog = get_user_meta( $user_id, 'primary_blog', true );
  78      $first_blog = current($blogs);
  79      if ( false !== $primary_blog ) {
  80          if ( ! isset( $blogs[ $primary_blog ] ) ) {
  81              update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id );
  82              $primary = $first_blog;
  83          } else {
  84              $primary = get_blog_details( $primary_blog );
  85          }
  86      } else {
  87          //TODO Review this call to add_user_to_blog too - to get here the user must have a role on this blog?
  88          add_user_to_blog( $first_blog->userblog_id, $user_id, 'subscriber' );
  89          update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id );
  90          $primary = $first_blog;
  91      }
  92  
  93      if ( ( ! is_object( $primary ) ) || ( is_object( $primary ) && $primary->archived == 1 || $primary->spam == 1 || $primary->deleted == 1 ) ) {
  94          $blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs.
  95          $ret = false;
  96          if ( is_array( $blogs ) && count( $blogs ) > 0 ) {
  97              foreach ( (array) $blogs as $blog_id => $blog ) {
  98                  if ( $blog->site_id != $wpdb->siteid )
  99                      continue;
 100                  $details = get_blog_details( $blog_id );
 101                  if ( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) {
 102                      $ret = $blog;
 103                      if ( get_user_meta( $user_id , 'primary_blog', true ) != $blog_id )
 104                          update_user_meta( $user_id, 'primary_blog', $blog_id );
 105                      if ( !get_user_meta($user_id , 'source_domain', true) )
 106                          update_user_meta( $user_id, 'source_domain', $blog->domain );
 107                      break;
 108                  }
 109              }
 110          } else {
 111              return null;
 112          }
 113          return $ret;
 114      } else {
 115          return $primary;
 116      }
 117  }
 118  
 119  /**
 120   * Find out whether a user is a member of a given blog.
 121   *
 122   * @since MU 1.1
 123   * @uses get_blogs_of_user()
 124   *
 125   * @param int $user_id The unique ID of the user
 126   * @param int $blog Optional. If no blog_id is provided, current site is used
 127   * @return bool
 128   */
 129  function is_user_member_of_blog( $user_id, $blog_id = 0 ) {
 130      $user_id = (int) $user_id;
 131      $blog_id = (int) $blog_id;
 132  
 133      if ( $blog_id == 0 ) {
 134          global $wpdb;
 135          $blog_id = $wpdb->blogid;
 136      }
 137  
 138      $blogs = get_blogs_of_user( $user_id );
 139      if ( is_array( $blogs ) )
 140          return array_key_exists( $blog_id, $blogs );
 141      else
 142          return false;
 143  }
 144  
 145  /**
 146   * The number of active users in your installation.
 147   *
 148   * The count is cached and updated twice daily. This is not a live count.
 149   *
 150   * @since MU 2.7
 151   *
 152   * @return int
 153   */
 154  function get_user_count() {
 155      return get_site_option( 'user_count' );
 156  }
 157  
 158  /**
 159   * The number of active sites on your installation.
 160   *
 161   * The count is cached and updated twice daily. This is not a live count.
 162   *
 163   * @since MU 1.0
 164   *
 165   * @param int $id Optional. A site_id.
 166   * @return int
 167   */
 168  function get_blog_count( $id = 0 ) {
 169      return get_site_option( 'blog_count' );
 170  }
 171  
 172  /**
 173   * Get a blog post from any site on the network.
 174   *
 175   * @since MU 1.0
 176   *
 177   * @param int $blog_id ID of the blog.
 178   * @param int $post_id ID of the post you're looking for.
 179   * @return object The post.
 180   */
 181  function get_blog_post( $blog_id, $post_id ) {
 182      global $wpdb;
 183  
 184      $key = $blog_id . '-' . $post_id;
 185      $post = wp_cache_get( $key, 'global-posts' );
 186      if ( $post == false ) {
 187          $post = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . $wpdb->get_blog_prefix( $blog_id ) . 'posts WHERE ID = %d', $post_id ) );
 188          wp_cache_add( $key, $post, 'global-posts' );
 189      }
 190  
 191      return $post;
 192  }
 193  
 194  /**
 195   * Add a user to a blog.
 196   *
 197   * Use the 'add_user_to_blog' action to fire an event when
 198   * users are added to a blog.
 199   *
 200   * @since MU 1.0
 201   *
 202   * @param int $blog_id ID of the blog you're adding the user to.
 203   * @param int $user_id ID of the user you're adding.
 204   * @param string $role The role you want the user to have
 205   * @return bool
 206   */
 207  function add_user_to_blog( $blog_id, $user_id, $role ) {
 208      switch_to_blog($blog_id);
 209  
 210      $user = new WP_User($user_id);
 211  
 212      if ( empty( $user->ID ) ) {
 213          restore_current_blog();
 214          return new WP_Error('user_does_not_exist', __('That user does not exist.'));
 215      }
 216  
 217      if ( !get_user_meta($user_id, 'primary_blog', true) ) {
 218          update_user_meta($user_id, 'primary_blog', $blog_id);
 219          $details = get_blog_details($blog_id);
 220          update_user_meta($user_id, 'source_domain', $details->domain);
 221      }
 222  
 223      $user->set_role($role);
 224  
 225      do_action('add_user_to_blog', $user_id, $role, $blog_id);
 226      wp_cache_delete( $user_id, 'users' );
 227      restore_current_blog();
 228      return true;
 229  }
 230  
 231  /**
 232   * Remove a user from a blog.
 233   *
 234   * Use the 'remove_user_from_blog' action to fire an event when
 235   * users are removed from a blog.
 236   *
 237   * Accepts an optional $reassign parameter, if you want to
 238   * reassign the user's blog posts to another user upon removal.
 239   *
 240   * @since MU 1.0
 241   *
 242   * @param int $user_id ID of the user you're removing.
 243   * @param int $blog_id ID of the blog you're removing the user from.
 244   * @param string $reassign Optional. A user to whom to reassign posts.
 245   * @return bool
 246   */
 247  function remove_user_from_blog($user_id, $blog_id = '', $reassign = '') {
 248      global $wpdb;
 249      switch_to_blog($blog_id);
 250      $user_id = (int) $user_id;
 251      do_action('remove_user_from_blog', $user_id, $blog_id);
 252  
 253      // If being removed from the primary blog, set a new primary if the user is assigned
 254      // to multiple blogs.
 255      $primary_blog = get_user_meta($user_id, 'primary_blog', true);
 256      if ( $primary_blog == $blog_id ) {
 257          $new_id = '';
 258          $new_domain = '';
 259          $blogs = get_blogs_of_user($user_id);
 260          foreach ( (array) $blogs as $blog ) {
 261              if ( $blog->userblog_id == $blog_id )
 262                  continue;
 263              $new_id = $blog->userblog_id;
 264              $new_domain = $blog->domain;
 265              break;
 266          }
 267  
 268          update_user_meta($user_id, 'primary_blog', $new_id);
 269          update_user_meta($user_id, 'source_domain', $new_domain);
 270      }
 271  
 272      // wp_revoke_user($user_id);
 273      $user = new WP_User($user_id);
 274      if ( empty( $user->ID ) ) {
 275          restore_current_blog();
 276          return new WP_Error('user_does_not_exist', __('That user does not exist.'));
 277      }
 278  
 279      $user->remove_all_caps();
 280  
 281      $blogs = get_blogs_of_user($user_id);
 282      if ( count($blogs) == 0 ) {
 283          update_user_meta($user_id, 'primary_blog', '');
 284          update_user_meta($user_id, 'source_domain', '');
 285      }
 286  
 287      if ( $reassign != '' ) {
 288          $reassign = (int) $reassign;
 289          $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_author = %d WHERE post_author = %d", $reassign, $user_id) );
 290          $wpdb->query( $wpdb->prepare("UPDATE $wpdb->links SET link_owner = %d WHERE link_owner = %d", $reassign, $user_id) );
 291      }
 292  
 293      restore_current_blog();
 294  }
 295  
 296  /**
 297   * Create an empty blog.
 298   *
 299   * @since MU 1.0
 300   * @uses install_blog()
 301   *
 302   * @param string $domain The new blog's domain.
 303   * @param string $path The new blog's path.
 304   * @param string $string The new blog's title.
 305   * @param int $site Optional. Defaults to 1.
 306   * @return int The ID of the newly created blog
 307   */
 308  function create_empty_blog( $domain, $path, $weblog_title, $site_id = 1 ) {
 309      $domain            = addslashes( $domain );
 310      $weblog_title    = addslashes( $weblog_title );
 311  
 312      if ( empty($path) )
 313          $path = '/';
 314  
 315      // Check if the domain has been used already. We should return an error message.
 316      if ( domain_exists($domain, $path, $site_id) )
 317          return __( 'Error: Site URL already taken.' );
 318  
 319      // Need to back up wpdb table names, and create a new wp_blogs entry for new blog.
 320      // Need to get blog_id from wp_blogs, and create new table names.
 321      // Must restore table names at the end of function.
 322  
 323      if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
 324          return __( 'Error: problem creating site entry.' );
 325  
 326      switch_to_blog($blog_id);
 327      install_blog($blog_id);
 328      restore_current_blog();
 329  
 330      return $blog_id;
 331  }
 332  
 333  /**
 334   * Get the permalink for a post on another blog.
 335   *
 336   * @since MU 1.0
 337   *
 338   * @param int $_blog_id ID of the source blog.
 339   * @param int $post_id ID of the desired post.
 340   * @return string The post's permalink
 341   */
 342  function get_blog_permalink( $_blog_id, $post_id ) {
 343      $key = "{$_blog_id}-{$post_id}-blog_permalink";
 344      $link = wp_cache_get( $key, 'site-options' );
 345      if ( $link == false ) {
 346          switch_to_blog( $_blog_id );
 347          $link = get_permalink( $post_id );
 348          restore_current_blog();
 349          wp_cache_add( $key, $link, 'site-options', 360 );
 350      }
 351      return $link;
 352  }
 353  
 354  /**
 355   * Get a blog's numeric ID from its URL.
 356   *
 357   * On a subdirectory installation like example.com/blog1/,
 358   * $domain will be the root 'example.com' and $path the
 359   * subdirectory '/blog1/'. With subdomains like blog1.example.com,
 360   * $domain is 'blog1.example.com' and $path is '/'.
 361   *
 362   * @since MU 2.6.5
 363   *
 364   * @param string $domain
 365   * @param string $path Optional. Not required for subdomain installations.
 366   * @return int
 367   */
 368  function get_blog_id_from_url( $domain, $path = '/' ) {
 369      global $wpdb;
 370  
 371      $domain = strtolower( $wpdb->escape( $domain ) );
 372      $path = strtolower( $wpdb->escape( $path ) );
 373      $id = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' );
 374  
 375      if ( $id == -1 ) { // blog does not exist
 376          return 0;
 377      } elseif ( $id ) {
 378          return (int)$id;
 379      }
 380  
 381      $id = $wpdb->get_var( "SELECT blog_id FROM $wpdb->blogs WHERE domain = '$domain' and path = '$path' /* get_blog_id_from_url */" );
 382  
 383      if ( !$id ) {
 384          wp_cache_set( md5( $domain . $path ), -1, 'blog-id-cache' );
 385          return false;
 386      }
 387      wp_cache_set( md5( $domain . $path ), $id, 'blog-id-cache' );
 388  
 389      return $id;
 390  }
 391  
 392  // Admin functions
 393  
 394  /**
 395   * Redirect a user based on $_GET or $_POST arguments.
 396   *
 397   * The function looks for redirect arguments in the following order:
 398   * 1) $_GET['ref']
 399   * 2) $_POST['ref']
 400   * 3) $_SERVER['HTTP_REFERER']
 401   * 4) $_GET['redirect']
 402   * 5) $_POST['redirect']
 403   * 6) $url
 404   *
 405   * @since MU
 406   * @uses wpmu_admin_redirect_add_updated_param()
 407   *
 408   * @param string $url
 409   */
 410  function wpmu_admin_do_redirect( $url = '' ) {
 411      $ref = '';
 412      if ( isset( $_GET['ref'] ) )
 413          $ref = $_GET['ref'];
 414      if ( isset( $_POST['ref'] ) )
 415          $ref = $_POST['ref'];
 416  
 417      if ( $ref ) {
 418          $ref = wpmu_admin_redirect_add_updated_param( $ref );
 419          wp_redirect( $ref );
 420          exit();
 421      }
 422      if ( empty( $_SERVER['HTTP_REFERER'] ) == false ) {
 423          wp_redirect( $_SERVER['HTTP_REFERER'] );
 424          exit();
 425      }
 426  
 427      $url = wpmu_admin_redirect_add_updated_param( $url );
 428      if ( isset( $_GET['redirect'] ) ) {
 429          if ( substr( $_GET['redirect'], 0, 2 ) == 's_' )
 430              $url .= '&action=blogs&s='. esc_html( substr( $_GET['redirect'], 2 ) );
 431      } elseif ( isset( $_POST['redirect'] ) ) {
 432          $url = wpmu_admin_redirect_add_updated_param( $_POST['redirect'] );
 433      }
 434      wp_redirect( $url );
 435      exit();
 436  }
 437  
 438  /**
 439   * Adds an 'updated=true' argument to a URL.
 440   *
 441   * @since MU
 442   *
 443   * @param string $url
 444   * @return string
 445   */
 446  function wpmu_admin_redirect_add_updated_param( $url = '' ) {
 447      if ( strpos( $url, 'updated=true' ) === false ) {
 448          if ( strpos( $url, '?' ) === false )
 449              return $url . '?updated=true';
 450          else
 451              return $url . '&updated=true';
 452      }
 453      return $url;
 454  }
 455  
 456  /**
 457   * Checks an email address against a list of banned domains.
 458   *
 459   * This function checks against the Banned Email Domains list
 460   * at wp-admin/network/settings.php. The check is only run on
 461   * self-registrations; user creation at wp-admin/network/users.php
 462   * bypasses this check.
 463   *
 464   * @since MU
 465   *
 466   * @param string $user_email The email provided by the user at registration.
 467   * @return bool Returns true when the email address is banned.
 468   */
 469  function is_email_address_unsafe( $user_email ) {
 470      $banned_names = get_site_option( 'banned_email_domains' );
 471      if ($banned_names && !is_array( $banned_names ))
 472          $banned_names = explode( "\n", $banned_names);
 473  
 474      if ( is_array( $banned_names ) && empty( $banned_names ) == false ) {
 475          $email_domain = strtolower( substr( $user_email, 1 + strpos( $user_email, '@' ) ) );
 476          foreach ( (array) $banned_names as $banned_domain ) {
 477              if ( $banned_domain == '' )
 478                  continue;
 479              if (
 480                  strstr( $email_domain, $banned_domain ) ||
 481                  (
 482                      strstr( $banned_domain, '/' ) &&
 483                      preg_match( $banned_domain, $email_domain )
 484                  )
 485              )
 486              return true;
 487          }
 488      }
 489      return false;
 490  }
 491  
 492  /**
 493   * Processes new user registrations.
 494   *
 495   * Checks the data provided by the user during signup. Verifies
 496   * the validity and uniqueness of user names and user email addresses,
 497   * and checks email addresses against admin-provided domain
 498   * whitelists and blacklists.
 499   *
 500   * The hook 'wpmu_validate_user_signup' provides an easy way
 501   * to modify the signup process. The value $result, which is passed
 502   * to the hook, contains both the user-provided info and the error
 503   * messages created by the function. 'wpmu_validate_user_signup' allows
 504   * you to process the data in any way you'd like, and unset the
 505   * relevant errors if necessary.
 506   *
 507   * @since MU
 508   * @uses is_email_address_unsafe()
 509   * @uses username_exists()
 510   * @uses email_exists()
 511   *
 512   * @param string $user_name The login name provided by the user.
 513   * @param string $user_email The email provided by the user.
 514   * @return array Contains username, email, and error messages.
 515   */
 516  function wpmu_validate_user_signup($user_name, $user_email) {
 517      global $wpdb;
 518  
 519      $errors = new WP_Error();
 520  
 521      $orig_username = $user_name;
 522      $user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
 523      $maybe = array();
 524      preg_match( '/[a-z0-9]+/', $user_name, $maybe );
 525  
 526      if ( $user_name != $orig_username || $user_name != $maybe[0] ) {
 527          $errors->add( 'user_name', __( 'Only lowercase letters (a-z) and numbers are allowed.' ) );
 528          $user_name = $orig_username;
 529      }
 530  
 531      $user_email = sanitize_email( $user_email );
 532  
 533      if ( empty( $user_name ) )
 534             $errors->add('user_name', __('Please enter a username'));
 535  
 536      $illegal_names = get_site_option( 'illegal_names' );
 537      if ( is_array( $illegal_names ) == false ) {
 538          $illegal_names = array(  'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
 539          add_site_option( 'illegal_names', $illegal_names );
 540      }
 541      if ( in_array( $user_name, $illegal_names ) == true )
 542          $errors->add('user_name',  __('That username is not allowed'));
 543  
 544      if ( is_email_address_unsafe( $user_email ) )
 545          $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.'));
 546  
 547      if ( strlen( $user_name ) < 4 )
 548          $errors->add('user_name',  __('Username must be at least 4 characters'));
 549  
 550      if ( strpos( ' ' . $user_name, '_' ) != false )
 551          $errors->add( 'user_name', __( 'Sorry, usernames may not contain the character &#8220;_&#8221;!' ) );
 552  
 553      // all numeric?
 554      $match = array();
 555      preg_match( '/[0-9]*/', $user_name, $match );
 556      if ( $match[0] == $user_name )
 557          $errors->add('user_name', __('Sorry, usernames must have letters too!'));
 558  
 559      if ( !is_email( $user_email ) )
 560          $errors->add('user_email', __('Please enter a correct email address'));
 561  
 562      $limited_email_domains = get_site_option( 'limited_email_domains' );
 563      if ( is_array( $limited_email_domains ) && empty( $limited_email_domains ) == false ) {
 564          $emaildomain = substr( $user_email, 1 + strpos( $user_email, '@' ) );
 565          if ( in_array( $emaildomain, $limited_email_domains ) == false )
 566              $errors->add('user_email', __('Sorry, that email address is not allowed!'));
 567      }
 568  
 569      // Check if the username has been used already.
 570      if ( username_exists($user_name) )
 571          $errors->add('user_name', __('Sorry, that username already exists!'));
 572  
 573      // Check if the email address has been used already.
 574      if ( email_exists($user_email) )
 575          $errors->add('user_email', __('Sorry, that email address is already used!'));
 576  
 577      // Has someone already signed up for this username?
 578      $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_login = %s", $user_name) );
 579      if ( $signup != null ) {
 580          $registered_at =  mysql2date('U', $signup->registered);
 581          $now = current_time( 'timestamp', true );
 582          $diff = $now - $registered_at;
 583          // If registered more than two days ago, cancel registration and let this signup go through.
 584          if ( $diff > 172800 )
 585              $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->signups WHERE user_login = %s", $user_name) );
 586          else
 587              $errors->add('user_name', __('That username is currently reserved but may be available in a couple of days.'));
 588  
 589          if ( $signup->active == 0 && $signup->user_email == $user_email )
 590              $errors->add('user_email_used', __('username and email used'));
 591      }
 592  
 593      $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_email = %s", $user_email) );
 594      if ( $signup != null ) {
 595          $diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered);
 596          // If registered more than two days ago, cancel registration and let this signup go through.
 597          if ( $diff > 172800 )
 598              $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->signups WHERE user_email = %s", $user_email) );
 599          else
 600              $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.'));
 601      }
 602  
 603      $result = array('user_name' => $user_name, 'orig_username' => $orig_username, 'user_email' => $user_email, 'errors' => $errors);
 604  
 605      return apply_filters('wpmu_validate_user_signup', $result);
 606  }
 607  
 608  /**
 609   * Processes new site registrations.
 610   *
 611   * Checks the data provided by the user during blog signup. Verifies
 612   * the validity and uniqueness of blog paths and domains.
 613   *
 614   * This function prevents the current user from registering a new site
 615   * with a blogname equivalent to another user's login name. Passing the
 616   * $user parameter to the function, where $user is the other user, is
 617   * effectively an override of this limitation.
 618   *
 619   * Filter 'wpmu_validate_blog_signup' if you want to modify
 620   * the way that WordPress validates new site signups.
 621   *
 622   * @since MU
 623   * @uses domain_exists()
 624   * @uses username_exists()
 625   *
 626   * @param string $blogname The blog name provided by the user. Must be unique.
 627   * @param string $blog_title The blog title provided by the user.
 628   * @return array Contains the new site data and error messages.
 629   */
 630  function wpmu_validate_blog_signup($blogname, $blog_title, $user = '') {
 631      global $wpdb, $domain, $base, $current_site;
 632  
 633      $blog_title = strip_tags( $blog_title );
 634      $blog_title = substr( $blog_title, 0, 50 );
 635  
 636      $errors = new WP_Error();
 637      $illegal_names = get_site_option( 'illegal_names' );
 638      if ( $illegal_names == false ) {
 639          $illegal_names = array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
 640          add_site_option( 'illegal_names', $illegal_names );
 641      }
 642  
 643      // On sub dir installs, Some names are so illegal, only a filter can spring them from jail
 644      if (! is_subdomain_install() )
 645          $illegal_names = array_merge($illegal_names, apply_filters( 'subdirectory_reserved_names', array( 'page', 'comments', 'blog', 'files', 'feed' ) ) );
 646  
 647  
 648      if ( empty( $blogname ) )
 649          $errors->add('blogname', __('Please enter a site name'));
 650  
 651      $maybe = array();
 652      preg_match( '/[a-z0-9]+/', $blogname, $maybe );
 653      if ( $blogname != $maybe[0] )
 654          $errors->add('blogname', __('Only lowercase letters and numbers allowed'));
 655  
 656      if ( in_array( $blogname, $illegal_names ) == true )
 657          $errors->add('blogname',  __('That name is not allowed'));
 658  
 659      if ( strlen( $blogname ) < 4 && !is_super_admin() )
 660          $errors->add('blogname',  __('Site name must be at least 4 characters'));
 661  
 662      if ( strpos( ' ' . $blogname, '_' ) != false )
 663          $errors->add( 'blogname', __( 'Sorry, site names may not contain the character &#8220;_&#8221;!' ) );
 664  
 665      // do not allow users to create a blog that conflicts with a page on the main blog.
 666      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 ) ) )
 667          $errors->add( 'blogname', __( 'Sorry, you may not use that site name.' ) );
 668  
 669      // all numeric?
 670      $match = array();
 671      preg_match( '/[0-9]*/', $blogname, $match );
 672      if ( $match[0] == $blogname )
 673          $errors->add('blogname', __('Sorry, site names must have letters too!'));
 674  
 675      $blogname = apply_filters( 'newblogname', $blogname );
 676  
 677      $blog_title = stripslashes(  $blog_title );
 678  
 679      if ( empty( $blog_title ) )
 680          $errors->add('blog_title', __('Please enter a site title'));
 681  
 682      // Check if the domain/path has been used already.
 683      if ( is_subdomain_install() ) {
 684          $mydomain = $blogname . '.' . preg_replace( '|^www\.|', '', $domain );
 685          $path = $base;
 686      } else {
 687          $mydomain = "$domain";
 688          $path = $base.$blogname.'/';
 689      }
 690      if ( domain_exists($mydomain, $path) )
 691          $errors->add('blogname', __('Sorry, that site already exists!'));
 692  
 693      if ( username_exists( $blogname ) ) {
 694          if ( is_object( $user ) == false || ( is_object($user) && ( $user->user_login != $blogname ) ) )
 695              $errors->add( 'blogname', __( 'Sorry, that site is reserved!' ) );
 696      }
 697  
 698      // Has someone already signed up for this domain?
 699      $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path) ); // TODO: Check email too?
 700      if ( ! empty($signup) ) {
 701          $diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered);
 702          // If registered more than two days ago, cancel registration and let this signup go through.
 703          if ( $diff > 172800 )
 704              $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path) );
 705          else
 706              $errors->add('blogname', __('That site is currently reserved but may be available in a couple days.'));
 707      }
 708  
 709      $result = array('domain' => $mydomain, 'path' => $path, 'blogname' => $blogname, 'blog_title' => $blog_title, 'errors' => $errors);
 710      return apply_filters('wpmu_validate_blog_signup', $result);
 711  }
 712  
 713  /**
 714   * Record site signup information for future activation.
 715   *
 716   * @since MU
 717   * @uses wpmu_signup_blog_notification()
 718   *
 719   * @param string $domain The requested domain.
 720   * @param string $path The requested path.
 721   * @param string $title The requested site title.
 722   * @param string $user The user's requested login name.
 723   * @param string $user_email The user's email address.
 724   * @param array $meta By default, contains the requested privacy setting and lang_id.
 725   */
 726  function wpmu_signup_blog($domain, $path, $title, $user, $user_email, $meta = '') {
 727      global $wpdb;
 728  
 729      $key = substr( md5( time() . rand() . $domain ), 0, 16 );
 730      $meta = serialize($meta);
 731      $domain = $wpdb->escape($domain);
 732      $path = $wpdb->escape($path);
 733      $title = $wpdb->escape($title);
 734  
 735      $wpdb->insert( $wpdb->signups, array(
 736          'domain' => $domain,
 737          'path' => $path,
 738          'title' => $title,
 739          'user_login' => $user,
 740          'user_email' => $user_email,
 741          'registered' => current_time('mysql', true),
 742          'activation_key' => $key,
 743          'meta' => $meta
 744      ) );
 745  
 746      wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta);
 747  }
 748  
 749  /**
 750   * Record user signup information for future activation.
 751   *
 752   * This function is used when user registration is open but
 753   * new site registration is not.
 754   *
 755   * @since MU
 756   * @uses wpmu_signup_user_notification()
 757   *
 758   * @param string $user The user's requested login name.
 759   * @param string $user_email The user's email address.
 760   * @param array $meta By default, this is an empty array.
 761   */
 762  function wpmu_signup_user($user, $user_email, $meta = '') {
 763      global $wpdb;
 764  
 765      // Format data
 766      $user = preg_replace( '/\s+/', '', sanitize_user( $user, true ) );
 767      $user_email = sanitize_email( $user_email );
 768      $key = substr( md5( time() . rand() . $user_email ), 0, 16 );
 769      $meta = serialize($meta);
 770  
 771      $wpdb->insert( $wpdb->signups, array(
 772          'domain' => '',
 773          'path' => '',
 774          'title' => '',
 775          'user_login' => $user,
 776          'user_email' => $user_email,
 777          'registered' => current_time('mysql', true),
 778          'activation_key' => $key,
 779          'meta' => $meta
 780      ) );
 781  
 782      wpmu_signup_user_notification($user, $user_email, $key, $meta);
 783  }
 784  
 785  /**
 786   * Notify user of signup success.
 787   *
 788   * This is the notification function used when site registration
 789   * is enabled.
 790   *
 791   * Filter 'wpmu_signup_blog_notification' to bypass this function or
 792   * replace it with your own notification behavior.
 793   *
 794   * Filter 'wpmu_signup_blog_notification_email' and
 795   * 'wpmu_signup_blog_notification_email' to change the content
 796   * and subject line of the email sent to newly registered users.
 797   *
 798   * @since MU
 799   *
 800   * @param string $domain The new blog domain.
 801   * @param string $path The new blog path.
 802   * @param string $title The site title.
 803   * @param string $user The user's login name.
 804   * @param string $user_email The user's email address.
 805   * @param array $meta By default, contains the requested privacy setting and lang_id.
 806   * @param string $key The activation key created in wpmu_signup_blog()
 807   * @return bool
 808   */
 809  function wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta = '') {
 810      global $current_site;
 811  
 812      if ( !apply_filters('wpmu_signup_blog_notification', $domain, $path, $title, $user, $user_email, $key, $meta) )
 813          return false;
 814  
 815      // Send email with activation link.
 816      if ( !is_subdomain_install() || $current_site->id != 1 )
 817          $activate_url = network_site_url("wp-activate.php?key=$key");
 818      else
 819          $activate_url = "http://{$domain}{$path}wp-activate.php?key=$key"; // @todo use *_url() API
 820  
 821      $activate_url = esc_url($activate_url);
 822      $admin_email = get_site_option( 'admin_email' );
 823      if ( $admin_email == '' )
 824          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
 825      $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
 826      $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
 827      $message = sprintf(
 828          apply_filters( 'wpmu_signup_blog_notification_email',
 829              __( "To activate your blog, please click the following link:\n\n%s\n\nAfter you activate, you will receive *another email* with your login.\n\nAfter you activate, you can visit your site here:\n\n%s" ),
 830              $domain, $path, $title, $user, $user_email, $key, $meta
 831          ),
 832          $activate_url,
 833          esc_url( "http://{$domain}{$path}" ),
 834          $key
 835      );
 836      // TODO: Don't hard code activation link.
 837      $subject = sprintf(
 838          apply_filters( 'wpmu_signup_blog_notification_subject',
 839              __( '[%1$s] Activate %2$s' ),
 840              $domain, $path, $title, $user, $user_email, $key, $meta
 841          ),
 842          $from_name,
 843          esc_url( 'http://' . $domain . $path )
 844      );
 845      wp_mail($user_email, $subject, $message, $message_headers);
 846      return true;
 847  }
 848  
 849  /**
 850   * Notify user of signup success.
 851   *
 852   * This is the notification function used when no new site has
 853   * been requested.
 854   *
 855   * Filter 'wpmu_signup_user_notification' to bypass this function or
 856   * replace it with your own notification behavior.
 857   *
 858   * Filter 'wpmu_signup_user_notification_email' and
 859   * 'wpmu_signup_user_notification_subject' to change the content
 860   * and subject line of the email sent to newly registered users.
 861   *
 862   * @since MU
 863   *
 864   * @param string $user The user's login name.
 865   * @param string $user_email The user's email address.
 866   * @param array $meta By default, an empty array.
 867   * @param string $key The activation key created in wpmu_signup_user()
 868   * @return bool
 869   */
 870  function wpmu_signup_user_notification($user, $user_email, $key, $meta = '') {
 871      if ( !apply_filters('wpmu_signup_user_notification', $user, $user_email, $key, $meta) )
 872          return false;
 873  
 874      // Send email with activation link.
 875      $admin_email = get_site_option( 'admin_email' );
 876      if ( $admin_email == '' )
 877          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
 878      $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
 879      $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
 880      $message = sprintf(
 881          apply_filters( 'wpmu_signup_user_notification_email',
 882              __( "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" ),
 883              $user, $user_email, $key, $meta
 884          ),
 885          site_url( "wp-activate.php?key=$key" )
 886      );
 887      // TODO: Don't hard code activation link.
 888      $subject = sprintf(
 889          apply_filters( 'wpmu_signup_user_notification_subject',
 890              __( '[%1$s] Activate %2$s' ),
 891              $user, $user_email, $key, $meta
 892          ),
 893          $from_name,
 894          $user
 895      );
 896      wp_mail($user_email, $subject, $message, $message_headers);
 897      return true;
 898  }
 899  
 900  /**
 901   * Activate a signup.
 902   *
 903   * Hook to 'wpmu_activate_user' or 'wpmu_activate_blog' for events
 904   * that should happen only when users or sites are self-created (since
 905   * those actions are not called when users and sites are created
 906   * by a Super Admin).
 907   *
 908   * @since MU
 909   * @uses wp_generate_password()
 910   * @uses wpmu_welcome_user_notification()
 911   * @uses add_user_to_blog()
 912   * @uses add_new_user_to_blog()
 913   * @uses wpmu_create_user()
 914   * @uses wpmu_create_blog()
 915   * @uses wpmu_welcome_notification()
 916   *
 917   * @param string $key The activation key provided to the user.
 918   * @return array An array containing information about the activated user and/or blog
 919   */
 920  function wpmu_activate_signup($key) {
 921      global $wpdb, $current_site;
 922  
 923      $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key) );
 924  
 925      if ( empty( $signup ) )
 926          return new WP_Error( 'invalid_key', __( 'Invalid activation key.' ) );
 927  
 928      if ( $signup->active ) {
 929          if ( empty( $signup->domain ) )
 930              return new WP_Error( 'already_active', __( 'The user is already active.' ), $signup );
 931          else
 932              return new WP_Error( 'already_active', __( 'The site is already active.' ), $signup );
 933      }
 934  
 935      $meta = unserialize($signup->meta);
 936      $user_login = $wpdb->escape($signup->user_login);
 937      $user_email = $wpdb->escape($signup->user_email);
 938      $password = wp_generate_password( 12, false );
 939  
 940      $user_id = username_exists($user_login);
 941  
 942      if ( ! $user_id )
 943          $user_id = wpmu_create_user($user_login, $password, $user_email);
 944      else
 945          $user_already_exists = true;
 946  
 947      if ( ! $user_id )
 948          return new WP_Error('create_user', __('Could not create user'), $signup);
 949  
 950      $now = current_time('mysql', true);
 951  
 952      if ( empty($signup->domain) ) {
 953          $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) );
 954  
 955          if ( isset( $user_already_exists ) )
 956              return new WP_Error( 'user_already_exists', __( 'That username is already activated.' ), $signup);
 957  
 958          wpmu_welcome_user_notification($user_id, $password, $meta);
 959  
 960          add_new_user_to_blog( $user_id, $user_email, $meta );
 961          do_action('wpmu_activate_user', $user_id, $password, $meta);
 962          return array('user_id' => $user_id, 'password' => $password, 'meta' => $meta);
 963      }
 964  
 965      $blog_id = wpmu_create_blog( $signup->domain, $signup->path, $signup->title, $user_id, $meta, $wpdb->siteid );
 966  
 967      // TODO: What to do if we create a user but cannot create a blog?
 968      if ( is_wp_error($blog_id) ) {
 969          // If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and
 970          // setting the activation flag.  Let's just set the active flag and instruct the user to reset their password.
 971          if ( 'blog_taken' == $blog_id->get_error_code() ) {
 972              $blog_id->add_data( $signup );
 973              $wpdb->update( $wpdb->signups, array( 'active' => 1, 'activated' => $now ), array( 'activation_key' => $key ) );
 974          }
 975          return $blog_id;
 976      }
 977  
 978      $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) );
 979      wpmu_welcome_notification($blog_id, $user_id, $password, $signup->title, $meta);
 980      do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta);
 981  
 982      return array('blog_id' => $blog_id, 'user_id' => $user_id, 'password' => $password, 'title' => $signup->title, 'meta' => $meta);
 983  }
 984  
 985  /**
 986   * Create a user.
 987   *
 988   * This function runs when a user self-registers as well as when
 989   * a Super Admin creates a new user. Hook to 'wpmu_new_user' for events
 990   * that should affect all new users, but only on Multisite (otherwise
 991   * use 'user_register').
 992   *
 993   * @since MU
 994   * @uses wp_create_user()
 995   *
 996   * @param string $user_name The new user's login name.
 997   * @param string $password The new user's password.
 998   * @param string $email The new user's email address.
 999   * @return mixed Returns false on failure, or int $user_id on success
1000   */
1001  function wpmu_create_user( $user_name, $password, $email) {
1002      $user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
1003  
1004      $user_id = wp_create_user( $user_name, $password, $email );
1005      if ( is_wp_error($user_id) )
1006          return false;
1007  
1008      // Newly created users have no roles or caps until they are added to a blog.
1009      delete_user_option( $user_id, 'capabilities' );
1010      delete_user_option( $user_id, 'user_level' );
1011  
1012      do_action( 'wpmu_new_user', $user_id );
1013  
1014      return $user_id;
1015  }
1016  
1017  /**
1018   * Create a site.
1019   *
1020   * This function runs when a user self-registers a new site as well
1021   * as when a Super Admin creates a new site. Hook to 'wpmu_new_blog'
1022   * for events that should affect all new sites.
1023   *
1024   * On subdirectory installs, $domain is the same as the main site's
1025   * domain, and the path is the subdirectory name (eg 'example.com'
1026   * and '/blog1/'). On subdomain installs, $domain is the new subdomain +
1027   * root domain (eg 'blog1.example.com'), and $path is '/'.
1028   *
1029   * @since MU
1030   * @uses domain_exists()
1031   * @uses insert_blog()
1032   * @uses wp_install_defaults()
1033   * @uses add_user_to_blog()
1034   *
1035   * @param string $domain The new site's domain.
1036   * @param string $path The new site's path.
1037   * @param string $title The new site's title.
1038   * @param int $user_id The user ID of the new site's admin.
1039   * @param array $meta Optional. Used to set initial site options.
1040   * @param int $site_id Optional. Only relevant on multi-network installs.
1041   * @return mixed Returns WP_Error object on failure, int $blog_id on success
1042   */
1043  function wpmu_create_blog($domain, $path, $title, $user_id, $meta = '', $site_id = 1) {
1044      $domain = preg_replace( '/\s+/', '', sanitize_user( $domain, true ) );
1045  
1046      if ( is_subdomain_install() )
1047          $domain = str_replace( '@', '', $domain );
1048  
1049      $title = strip_tags( $title );
1050      $user_id = (int) $user_id;
1051  
1052      if ( empty($path) )
1053          $path = '/';
1054  
1055      // Check if the domain has been used already. We should return an error message.
1056      if ( domain_exists($domain, $path, $site_id) )
1057          return new WP_Error('blog_taken', __('Site already exists.'));
1058  
1059      if ( !defined('WP_INSTALLING') )
1060          define( 'WP_INSTALLING', true );
1061  
1062      if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
1063          return new WP_Error('insert_blog', __('Could not create site.'));
1064  
1065      switch_to_blog($blog_id);
1066      install_blog($blog_id, $title);
1067      wp_install_defaults($user_id);
1068  
1069      add_user_to_blog($blog_id, $user_id, 'administrator');
1070  
1071      if ( is_array($meta) ) foreach ($meta as $key => $value) {
1072          if ( $key == 'public' || $key == 'archived' || $key == 'mature' || $key == 'spam' || $key == 'deleted' || $key == 'lang_id' )
1073              update_blog_status( $blog_id, $key, $value );
1074          else
1075              update_option( $key, $value );
1076      }
1077  
1078      add_option( 'WPLANG', get_site_option( 'WPLANG' ) );
1079      update_option( 'blog_public', (int)$meta['public'] );
1080  
1081      if ( !is_super_admin() && ! get_user_meta( $user_id, 'primary_blog', true ) )
1082          update_user_meta( $user_id, 'primary_blog', $blog_id );
1083  
1084      restore_current_blog();
1085      do_action( 'wpmu_new_blog', $blog_id, $user_id, $domain, $path, $site_id, $meta );
1086  
1087      return $blog_id;
1088  }
1089  
1090  /**
1091   * Notifies the network admin that a new site has been activated.
1092   *
1093   * Filter 'newblog_notify_siteadmin' to change the content of
1094   * the notification email.
1095   *
1096   * @since MU
1097   *
1098   * @param int $blog_id The new site's ID.
1099   * @return bool
1100   */
1101  function newblog_notify_siteadmin( $blog_id, $deprecated = '' ) {
1102      if ( get_site_option( 'registrationnotification' ) != 'yes' )
1103          return false;
1104  
1105      $email = get_site_option( 'admin_email' );
1106      if ( is_email($email) == false )
1107          return false;
1108  
1109      $options_site_url = esc_url(network_admin_url('settings.php'));
1110  
1111      switch_to_blog( $blog_id );
1112      $blogname = get_option( 'blogname' );
1113      $siteurl = site_url();
1114      restore_current_blog();
1115  
1116      $msg = sprintf( __( 'New Site: %1s
1117  URL: %2s
1118  Remote IP: %3s
1119  
1120  Disable these notifications: %4s' ), $blogname, $siteurl, $_SERVER['REMOTE_ADDR'], $options_site_url);
1121      $msg = apply_filters( 'newblog_notify_siteadmin', $msg );
1122  
1123      wp_mail( $email, sprintf( __( 'New Site Registration: %s' ), $siteurl ), $msg );
1124      return true;
1125  }
1126  
1127  /**
1128   * Notifies the network admin that a new user has been activated.
1129   *
1130   * Filter 'newuser_notify_siteadmin' to change the content of
1131   * the notification email.
1132   *
1133   * @since MU
1134   *
1135   * @param int $user_id The new user's ID.
1136   * @return bool
1137   */
1138  function newuser_notify_siteadmin( $user_id ) {
1139      if ( get_site_option( 'registrationnotification' ) != 'yes' )
1140          return false;
1141  
1142      $email = get_site_option( 'admin_email' );
1143  
1144      if ( is_email($email) == false )
1145          return false;
1146  
1147      $user = new WP_User($user_id);
1148  
1149      $options_site_url = esc_url(network_admin_url('settings.php'));
1150      $msg = sprintf(__('New User: %1s
1151  Remote IP: %2s
1152  
1153  Disable these notifications: %3s'), $user->user_login, $_SERVER['REMOTE_ADDR'], $options_site_url);
1154  
1155      $msg = apply_filters( 'newuser_notify_siteadmin', $msg );
1156      wp_mail( $email, sprintf(__('New User Registration: %s'), $user->user_login), $msg );
1157      return true;
1158  }
1159  
1160  /**
1161   * Check whether a blogname is already taken.
1162   *
1163   * Used during the new site registration process to ensure
1164   * that each blogname is unique.
1165   *
1166   * @since MU
1167   *
1168   * @param string $domain The domain to be checked.
1169   * @param string $path The path to be checked.
1170   * @param int $site_id Optional. Relevant only on multi-network installs.
1171   * @return int
1172   */
1173  function domain_exists($domain, $path, $site_id = 1) {
1174      global $wpdb;
1175      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) );
1176  }
1177  
1178  /**
1179   * Store basic site info in the blogs table.
1180   *
1181   * This function creates a row in the wp_blogs table and returns
1182   * the new blog's ID. It is the first step in creating a new blog.
1183   *
1184   * @since MU
1185   *
1186   * @param string $domain The domain of the new site.
1187   * @param string $path The path of the new site.
1188   * @param int $site_id Unless you're running a multi-network install, be sure to set this value to 1.
1189   * @return int The ID of the new row
1190   */
1191  function insert_blog($domain, $path, $site_id) {
1192      global $wpdb;
1193  
1194      $path = trailingslashit($path);
1195      $site_id = (int) $site_id;
1196  
1197      $result = $wpdb->insert( $wpdb->blogs, array('site_id' => $site_id, 'domain' => $domain, 'path' => $path, 'registered' => current_time('mysql')) );
1198      if ( ! $result )
1199          return false;
1200  
1201      refresh_blog_details($wpdb->insert_id);
1202      return $wpdb->insert_id;
1203  }
1204  
1205  /**
1206   * Install an empty blog.
1207   *
1208   * Creates the new blog tables and options. If calling this function
1209   * directly, be sure to use switch_to_blog() first, so that $wpdb
1210   * points to the new blog.
1211   *
1212   * @since MU
1213   * @uses make_db_current_silent()
1214   * @uses populate_roles()
1215   *
1216   * @param int $blog_id The value returned by insert_blog().
1217   * @param string $blog_title The title of the new site.
1218   */
1219  function install_blog($blog_id, $blog_title = '') {
1220      global $wpdb, $table_prefix, $wp_roles;
1221      $wpdb->suppress_errors();
1222  
1223      // Cast for security
1224      $blog_id = (int) $blog_id;
1225  
1226      require_once ( ABSPATH . 'wp-admin/includes/upgrade.php' );
1227  
1228      if ( $wpdb->get_results("SELECT ID FROM $wpdb->posts") )
1229          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>');
1230  
1231      $wpdb->suppress_errors(false);
1232  
1233      $url = get_blogaddress_by_id($blog_id);
1234  
1235      // Set everything up
1236      make_db_current_silent();
1237      populate_options();
1238      populate_roles();
1239      $wp_roles->_init();
1240  
1241      // fix url.
1242      update_option('siteurl', $url);
1243      update_option('home', $url);
1244      update_option('fileupload_url', $url . "files" );
1245      update_option('upload_path', UPLOADBLOGSDIR . "/$blog_id/files");
1246      update_option('blogname', stripslashes( $blog_title ) );
1247      update_option('admin_email', '');
1248      $wpdb->update( $wpdb->options, array('option_value' => ''), array('option_name' => 'admin_email') );
1249  
1250      // remove all perms
1251      $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE meta_key = %s", $table_prefix.'user_level') );
1252      $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE meta_key = %s", $table_prefix.'capabilities') );
1253  
1254      $wpdb->suppress_errors( false );
1255  }
1256  
1257  /**
1258   * Set blog defaults.
1259   *
1260   * This function creates a row in the wp_blogs table.
1261   *
1262   * @since MU
1263   * @deprecated MU
1264   * @deprecated Use wp_install_defaults()
1265   * @uses wp_install_defaults()
1266   *
1267   * @param int $blog_id Ignored in this function.
1268   * @param int $user_id
1269   */
1270  function install_blog_defaults($blog_id, $user_id) {
1271      global $wpdb;
1272  
1273      require_once ( ABSPATH . 'wp-admin/includes/upgrade.php' );
1274  
1275      $wpdb->suppress_errors();
1276  
1277      wp_install_defaults($user_id);
1278  
1279      $wpdb->suppress_errors( false );
1280  }
1281  
1282  /**
1283   * Notify a user that her blog activation has been successful.
1284   *
1285   * Filter 'wpmu_welcome_notification' to disable or bypass.
1286   *
1287   * Filter 'update_welcome_email' and 'update_welcome_subject' to
1288   * modify the content and subject line of the notification email.
1289   *
1290   * @since MU
1291   *
1292   * @param int $blog_id
1293   * @param int $user_id
1294   * @param string $password
1295   * @param string $title The new blog's title
1296   * @param array $meta Optional. Not used in the default function, but is passed along to hooks for customization.
1297   * @return bool
1298   */
1299  function wpmu_welcome_notification($blog_id, $user_id, $password, $title, $meta = '') {
1300      global $current_site;
1301  
1302      if ( !apply_filters('wpmu_welcome_notification', $blog_id, $user_id, $password, $title, $meta) )
1303          return false;
1304  
1305      $welcome_email = stripslashes( get_site_option( 'welcome_email' ) );
1306      if ( $welcome_email == false )
1307          $welcome_email = stripslashes( __( 'Dear User,
1308  
1309  Your new SITE_NAME site has been successfully set up at:
1310  BLOG_URL
1311  
1312  You can log in to the administrator account with the following information:
1313  Username: USERNAME
1314  Password: PASSWORD
1315  Login Here: BLOG_URLwp-login.php
1316  
1317  We hope you enjoy your new site.
1318  Thanks!
1319  
1320  --The Team @ SITE_NAME' ) );
1321  
1322      $url = get_blogaddress_by_id($blog_id);
1323      $user = new WP_User($user_id);
1324  
1325      $welcome_email = str_replace( 'SITE_NAME', $current_site->site_name, $welcome_email );
1326      $welcome_email = str_replace( 'BLOG_TITLE', $title, $welcome_email );
1327      $welcome_email = str_replace( 'BLOG_URL', $url, $welcome_email );
1328      $welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email );
1329      $welcome_email = str_replace( 'PASSWORD', $password, $welcome_email );
1330  
1331      $welcome_email = apply_filters( 'update_welcome_email', $welcome_email, $blog_id, $user_id, $password, $title, $meta);
1332      $admin_email = get_site_option( 'admin_email' );
1333  
1334      if ( $admin_email == '' )
1335          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1336  
1337      $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
1338      $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1339      $message = $welcome_email;
1340  
1341      if ( empty( $current_site->site_name ) )
1342          $current_site->site_name = 'WordPress';
1343  
1344      $subject = apply_filters( 'update_welcome_subject', sprintf(__('New %1$s Site: %2$s'), $current_site->site_name, stripslashes( $title ) ) );
1345      wp_mail($user->user_email, $subject, $message, $message_headers);
1346      return true;
1347  }
1348  
1349  /**
1350   * Notify a user that her account activation has been successful.
1351   *
1352   * Filter 'wpmu_welcome_user_notification' to disable or bypass.
1353   *
1354   * Filter 'update_welcome_user_email' and 'update_welcome_user_subject' to
1355   * modify the content and subject line of the notification email.
1356   *
1357   * @since MU
1358   *
1359   * @param int $user_id
1360   * @param string $password
1361   * @param array $meta Optional. Not used in the default function, but is passed along to hooks for customization.
1362   * @return bool
1363   */
1364  function wpmu_welcome_user_notification($user_id, $password, $meta = '') {
1365      global $current_site;
1366  
1367      if ( !apply_filters('wpmu_welcome_user_notification', $user_id, $password, $meta) )
1368          return false;
1369  
1370      $welcome_email = get_site_option( 'welcome_user_email' );
1371  
1372      $user = new WP_User($user_id);
1373  
1374      $welcome_email = apply_filters( 'update_welcome_user_email', $welcome_email, $user_id, $password, $meta);
1375      $welcome_email = str_replace( 'SITE_NAME', $current_site->site_name, $welcome_email );
1376      $welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email );
1377      $welcome_email = str_replace( 'PASSWORD', $password, $welcome_email );
1378      $welcome_email = str_replace( 'LOGINLINK', wp_login_url(), $welcome_email );
1379  
1380      $admin_email = get_site_option( 'admin_email' );
1381  
1382      if ( $admin_email == '' )
1383          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1384  
1385      $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
1386      $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1387      $message = $welcome_email;
1388  
1389      if ( empty( $current_site->site_name ) )
1390          $current_site->site_name = 'WordPress';
1391  
1392      $subject = apply_filters( 'update_welcome_user_subject', sprintf(__('New %1$s User: %2$s'), $current_site->site_name, $user->user_login) );
1393      wp_mail($user->user_email, $subject, $message, $message_headers);
1394      return true;
1395  }
1396  
1397  /**
1398   * Get the current site info.
1399   *
1400   * Returns an object containing the ID, domain, path, and site_name
1401   * of the site being viewed.
1402   *
1403   * @since MU
1404   *
1405   * @return object
1406   */
1407  function get_current_site() {
1408      global $current_site;
1409      return $current_site;
1410  }
1411  
1412  /**
1413   * Get a numeric user ID from either an email address or a login.
1414   *
1415   * @since MU
1416   * @uses is_email()
1417   *
1418   * @param string $string
1419   * @return int
1420   */
1421  function get_user_id_from_string( $string ) {
1422      $user_id = 0;
1423      if ( is_email( $string ) ) {
1424          $user = get_user_by('email', $string);
1425          if ( $user )
1426              $user_id = $user->ID;
1427      } elseif ( is_numeric( $string ) ) {
1428          $user_id = $string;
1429      } else {
1430          $user = get_user_by('login', $string);
1431          if ( $user )
1432              $user_id = $user->ID;
1433      }
1434  
1435      return $user_id;
1436  }
1437  
1438  /**
1439   * Get a user's most recent post.
1440   *
1441   * Walks through each of a user's blogs to find the post with
1442   * the most recent post_date_gmt.
1443   *
1444   * @since MU
1445   * @uses get_blogs_of_user()
1446   *
1447   * @param int $user_id
1448   * @return array Contains the blog_id, post_id, post_date_gmt, and post_gmt_ts
1449   */
1450  function get_most_recent_post_of_user( $user_id ) {
1451      global $wpdb;
1452  
1453      $user_blogs = get_blogs_of_user( (int) $user_id );
1454      $most_recent_post = array();
1455  
1456      // Walk through each blog and get the most recent post
1457      // published by $user_id
1458      foreach ( (array) $user_blogs as $blog ) {
1459          $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);
1460  
1461          // Make sure we found a post
1462          if ( isset($recent_post['ID']) ) {
1463              $post_gmt_ts = strtotime($recent_post['post_date_gmt']);
1464  
1465              // If this is the first post checked or if this post is
1466              // newer than the current recent post, make it the new
1467              // most recent post.
1468              if ( !isset($most_recent_post['post_gmt_ts']) || ( $post_gmt_ts > $most_recent_post['post_gmt_ts'] ) ) {
1469                  $most_recent_post = array(
1470                      'blog_id'        => $blog->userblog_id,
1471                      'post_id'        => $recent_post['ID'],
1472                      'post_date_gmt'    => $recent_post['post_date_gmt'],
1473                      'post_gmt_ts'    => $post_gmt_ts
1474                  );
1475              }
1476          }
1477      }
1478  
1479      return $most_recent_post;
1480  }
1481  
1482  // Misc functions
1483  
1484  /**
1485   * Get the size of a directory.
1486   *
1487   * A helper function that is used primarily to check whether
1488   * a blog has exceeded its allowed upload space.
1489   *
1490   * @since MU
1491   * @uses recurse_dirsize()
1492   *
1493   * @param string $directory
1494   * @return int
1495   */
1496  function get_dirsize( $directory ) {
1497      $dirsize = get_transient( 'dirsize_cache' );
1498      if ( is_array( $dirsize ) && isset( $dirsize[ $directory ][ 'size' ] ) )
1499          return $dirsize[ $directory ][ 'size' ];
1500  
1501      if ( false == is_array( $dirsize ) )
1502          $dirsize = array();
1503  
1504      $dirsize[ $directory ][ 'size' ] = recurse_dirsize( $directory );
1505  
1506      set_transient( 'dirsize_cache', $dirsize, 3600 );
1507      return $dirsize[ $directory ][ 'size' ];
1508  }
1509  
1510  /**
1511   * Get the size of a directory recursively.
1512   *
1513   * Used by get_dirsize() to get a directory's size when it contains
1514   * other directories.
1515   *
1516   * @since MU
1517   *
1518   * @param string $directory
1519   * @return int
1520   */
1521  function recurse_dirsize( $directory ) {
1522      $size = 0;
1523  
1524      if ( substr( $directory, -1 ) == '/' )
1525          $directory = substr($directory,0,-1);
1526  
1527      if ( !file_exists($directory) || !is_dir( $directory ) || !is_readable( $directory ) )
1528          return false;
1529  
1530      if ($handle = opendir($directory)) {
1531          while(($file = readdir($handle)) !== false) {
1532              $path = $directory.'/'.$file;
1533              if ($file != '.' && $file != '..') {
1534                  if (is_file($path)) {
1535                      $size += filesize($path);
1536                  } elseif (is_dir($path)) {
1537                      $handlesize = recurse_dirsize($path);
1538                      if ($handlesize > 0)
1539                          $size += $handlesize;
1540                  }
1541              }
1542          }
1543          closedir($handle);
1544      }
1545      return $size;
1546  }
1547  
1548  /**
1549   * Check whether a blog has used its allotted upload space.
1550   *
1551   * Used by get_dirsize() to get a directory's size when it contains
1552   * other directories.
1553   *
1554   * @since MU
1555   * @uses get_dirsize()
1556   *
1557   * @param bool $echo Optional. If $echo is set and the quota is exceeded, a warning message is echoed. Default is true.
1558   * @return int
1559   */
1560  function upload_is_user_over_quota( $echo = true ) {
1561      if ( get_site_option( 'upload_space_check_disabled' ) )
1562          return false;
1563  
1564      $spaceAllowed = get_space_allowed();
1565      if ( empty( $spaceAllowed ) || !is_numeric( $spaceAllowed ) )
1566          $spaceAllowed = 10;    // Default space allowed is 10 MB
1567  
1568      $dirName = BLOGUPLOADDIR;
1569      $size = get_dirsize($dirName) / 1024 / 1024;
1570  
1571      if ( ($spaceAllowed-$size) < 0 ) {
1572          if ( $echo )
1573              _e( 'Sorry, you have used your space allocation. Please delete some files to upload more files.' ); // No space left
1574          return true;
1575      } else {
1576          return false;
1577      }
1578  }
1579  
1580  /**
1581   * Check an array of MIME types against a whitelist.
1582   *
1583   * WordPress ships with a set of allowed upload filetypes,
1584   * which is defined in wp-includes/functions.php in
1585   * get_allowed_mime_types(). This function is used to filter
1586   * that list against the filetype whitelist provided by Multisite
1587   * Super Admins at wp-admin/network/settings.php.
1588   *
1589   * @since MU
1590   *
1591   * @param array $mimes
1592   * @return array
1593   */
1594  function check_upload_mimes( $mimes ) {
1595      $site_exts = explode( ' ', get_site_option( 'upload_filetypes' ) );
1596      foreach ( $site_exts as $ext ) {
1597          foreach ( $mimes as $ext_pattern => $mime ) {
1598              if ( $ext != '' && strpos( $ext_pattern, $ext ) !== false )
1599                  $site_mimes[$ext_pattern] = $mime;
1600          }
1601      }
1602      return $site_mimes;
1603  }
1604  
1605  /**
1606   * Update a blog's post count.
1607   *
1608   * WordPress MS stores a blog's post count as an option so as
1609   * to avoid extraneous COUNTs when a blog's details are fetched
1610   * with get_blog_details(). This function is called when posts
1611   * are published to make sure the count stays current.
1612   *
1613   * @since MU
1614   */
1615  function update_posts_count( $deprecated = '' ) {
1616      global $wpdb;
1617      update_option( 'post_count', (int) $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_status = 'publish' and post_type = 'post'" ) );
1618  }
1619  
1620  /**
1621   * Logs user registrations.
1622   *
1623   * @since MU
1624   *
1625   * @param int $blog_id
1626   * @param int $user_id
1627   */
1628  function wpmu_log_new_registrations( $blog_id, $user_id ) {
1629      global $wpdb;
1630      $user = new WP_User( (int) $user_id );
1631      $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')) );
1632  }
1633  
1634  /**
1635   * Get the remaining upload space for this blog.
1636   *
1637   * @since MU
1638   * @uses upload_is_user_over_quota()
1639   * @uses get_space_allowed()
1640   * @uses get_dirsize()
1641   *
1642   * @param int $size
1643   * @return int
1644   */
1645  function fix_import_form_size( $size ) {
1646      if ( upload_is_user_over_quota( false ) == true )
1647          return 0;
1648  
1649      $spaceAllowed = 1024 * 1024 * get_space_allowed();
1650      $dirName = BLOGUPLOADDIR;
1651      $dirsize = get_dirsize($dirName) ;
1652      if ( $size > $spaceAllowed - $dirsize )
1653          return $spaceAllowed - $dirsize; // remaining space
1654      else
1655          return $size; // default
1656  }
1657  
1658  /**
1659   * Maintains a canonical list of terms by syncing terms created for each blog with the global terms table.
1660   *
1661   * @since 3.0.0
1662   *
1663   * @see term_id_filter
1664   *
1665   * @param int $term_id An ID for a term on the current blog.
1666   * @return int An ID from the global terms table mapped from $term_id.
1667   */
1668  function global_terms( $term_id, $deprecated = '' ) {
1669      global $wpdb;
1670      static $global_terms_recurse = null;
1671  
1672      if ( !global_terms_enabled() )
1673          return $term_id;
1674  
1675      // prevent a race condition
1676      $recurse_start = false;
1677      if ( $global_terms_recurse === null ) {
1678          $recurse_start = true;
1679          $global_terms_recurse = 1;
1680      } elseif ( 10 < $global_terms_recurse++ ) {
1681          return $term_id;
1682      }
1683  
1684      $term_id = intval( $term_id );
1685      $c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->terms WHERE term_id = %d", $term_id ) );
1686  
1687      $global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE category_nicename = %s", $c->slug ) );
1688      if ( $global_id == null ) {
1689          $used_global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE cat_ID = %d", $c->term_id ) );
1690          if ( null == $used_global_id ) {
1691              $wpdb->insert( $wpdb->sitecategories, array( 'cat_ID' => $term_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug ) );
1692              $global_id = $wpdb->insert_id;
1693              if ( empty( $global_id ) )
1694                  return $term_id;
1695          } else {
1696              $max_global_id = $wpdb->get_var( "SELECT MAX(cat_ID) FROM $wpdb->sitecategories" );
1697              $max_local_id = $wpdb->get_var( "SELECT MAX(term_id) FROM $wpdb->terms" );
1698              $new_global_id = max( $max_global_id, $max_local_id ) + mt_rand( 100, 400 );
1699              $wpdb->insert( $wpdb->sitecategories, array( 'cat_ID' => $new_global_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug ) );
1700              $global_id = $wpdb->insert_id;
1701          }
1702      } elseif ( $global_id != $term_id ) {
1703          $local_id = $wpdb->get_row( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE term_id = %d", $global_id ) );
1704          if ( null != $local_id )
1705              $local_id = global_terms( $local_id );
1706              if ( 10 < $global_terms_recurse )
1707                  $global_id = $term_id;
1708      }
1709  
1710      if ( $global_id != $term_id ) {
1711          if ( get_option( 'default_category' ) == $term_id )
1712              update_option( 'default_category', $global_id );
1713  
1714          $wpdb->update( $wpdb->terms, array('term_id' => $global_id), array('term_id' => $term_id) );
1715          $wpdb->update( $wpdb->term_taxonomy, array('term_id' => $global_id), array('term_id' => $term_id) );
1716          $wpdb->update( $wpdb->term_taxonomy, array('parent' => $global_id), array('parent' => $term_id) );
1717  
1718          clean_term_cache($term_id);
1719      }
1720      if( $recurse_start )
1721          $global_terms_recurse = null;
1722  
1723      return $global_id;
1724  }
1725  
1726  /**
1727   * Ensure that the current site's domain is listed in the allowed redirect host list.
1728   *
1729   * @see wp_validate_redirect()
1730   * @since MU
1731   *
1732   * @return array The current site's domain
1733   */
1734  function redirect_this_site( $deprecated = '' ) {
1735      global $current_site;
1736      return array( $current_site->domain );
1737  }
1738  
1739  /**
1740   * Check whether an upload is too big.
1741   *
1742   * @since MU
1743   *
1744   * @param array $upload
1745   * @return mixed If the upload is under the size limit, $upload is returned. Otherwise returns an error message.
1746   */
1747  function upload_is_file_too_big( $upload ) {
1748      if ( is_array( $upload ) == false || defined( 'WP_IMPORTING' ) )
1749          return $upload;
1750  
1751      if ( strlen( $upload['bits'] )  > ( 1024 * get_site_option( 'fileupload_maxk', 1500 ) ) )
1752          return sprintf( __( 'This file is too big. Files must be less than %d KB in size.' ) . '<br />', get_site_option( 'fileupload_maxk', 1500 ));
1753  
1754      return $upload;
1755  }
1756  
1757  /**
1758   * Add a nonce field to the signup page.
1759   *
1760   * @since MU
1761   * @uses wp_nonce_field()
1762   */
1763  function signup_nonce_fields() {
1764      $id = mt_rand();
1765      echo "<input type='hidden' name='signup_form_id' value='{$id}' />";
1766      wp_nonce_field('signup_form_' . $id, '_signup_form', false);
1767  }
1768  
1769  /**
1770   * Process the signup nonce created in signup_nonce_fields().
1771   *
1772   * @since MU
1773   * @uses wp_create_nonce()
1774   *
1775   * @param array $result
1776   * @return array
1777   */
1778  function signup_nonce_check( $result ) {
1779      if ( !strpos( $_SERVER[ 'PHP_SELF' ], 'wp-signup.php' ) )
1780          return $result;
1781  
1782      if ( wp_create_nonce('signup_form_' . $_POST[ 'signup_form_id' ]) != $_POST['_signup_form'] )
1783          wp_die( __('Please try again!') );
1784  
1785      return $result;
1786  }
1787  
1788  /**
1789   * Correct 404 redirects when NOBLOGREDIRECT is defined.
1790   *
1791   * @since MU
1792   */
1793  function maybe_redirect_404() {
1794      global $current_site;
1795      if ( is_main_site() && is_404() && defined( 'NOBLOGREDIRECT' ) && ( $destination = apply_filters( 'blog_redirect_404', NOBLOGREDIRECT ) ) ) {
1796          if ( $destination == '%siteurl%' )
1797              $destination = network_home_url();
1798          wp_redirect( $destination );
1799          exit();
1800      }
1801  }
1802  
1803  /**
1804   * Add a new user to a blog by visiting /newbloguser/username/.
1805   *
1806   * This will only work when the user's details are saved as an option
1807   * keyed as 'new_user_x', where 'x' is the username of the user to be
1808   * added, as when a user is invited through the regular WP Add User interface.
1809   *
1810   * @since MU
1811   * @uses add_existing_user_to_blog()
1812   */
1813  function maybe_add_existing_user_to_blog() {
1814      if ( false === strpos( $_SERVER[ 'REQUEST_URI' ], '/newbloguser/' ) )
1815          return false;
1816  
1817      $parts = explode( '/', $_SERVER[ 'REQUEST_URI' ] );
1818      $key = array_pop( $parts );
1819  
1820      if ( $key == '' )
1821          $key = array_pop( $parts );
1822  
1823      $details = get_option( 'new_user_' . $key );
1824      if ( !empty( $details ) )
1825          delete_option( 'new_user_' . $key );
1826  
1827      if ( empty( $details ) || is_wp_error( add_existing_user_to_blog( $details ) ) )
1828          wp_die( sprintf(__('An error occurred adding you to this site. Back to the <a href="%s">homepage</a>.'), site_url() ) );
1829  
1830      wp_die( sprintf(__('You have been added to this site. Please visit the <a href="%s">homepage</a> or <a href="%s">login</a> using your username and password.'), site_url(), admin_url() ), __('Success') );
1831  }
1832  
1833  /**
1834   * Add a user to a blog based on details from maybe_add_existing_user_to_blog().
1835   *
1836   * @since MU
1837   * @uses add_user_to_blog()
1838   *
1839   * @param array $details
1840   */
1841  function add_existing_user_to_blog( $details = false ) {
1842      global $blog_id;
1843  
1844      if ( is_array( $details ) ) {
1845          $result = add_user_to_blog( $blog_id, $details[ 'user_id' ], $details[ 'role' ] );
1846          do_action( 'added_existing_user', $details[ 'user_id' ], $result );
1847      }
1848      return $result;
1849  }
1850  
1851  /**
1852   * Add a newly created user to the appropriate blog
1853   *
1854   * @since MU
1855   *
1856   * @param int $user_id
1857   * @param string $email
1858   * @param array $meta
1859   */
1860  function add_new_user_to_blog( $user_id, $email, $meta ) {
1861      global $current_site;
1862      if ( !empty( $meta[ 'add_to_blog' ] ) ) {
1863          $blog_id = $meta[ 'add_to_blog' ];
1864          $role = $meta[ 'new_role' ];
1865          remove_user_from_blog($user_id, $current_site->blog_id); // remove user from main blog.
1866          add_user_to_blog( $blog_id, $user_id, $role );
1867          update_user_meta( $user_id, 'primary_blog', $blog_id );
1868      }
1869  }
1870  
1871  /**
1872   * Correct From host on outgoing mail to match the site domain
1873   *
1874   * @since MU
1875   */
1876  function fix_phpmailer_messageid( $phpmailer ) {
1877      global $current_site;
1878      $phpmailer->Hostname = $current_site->domain;
1879  }
1880  
1881  /**
1882   * Check to see whether a user is marked as a spammer, based on username
1883   *
1884   * @since MU
1885   * @uses get_current_user_id()
1886   * @uses get_user_id_from_string()
1887   *
1888   * @param string $username
1889   * @return bool
1890   */
1891  function is_user_spammy( $username = 0 ) {
1892      if ( $username == 0 ) {
1893          $user_id = get_current_user_id();
1894      } else {
1895          $user_id = get_user_id_from_string( $username );
1896      }
1897      $u = new WP_User( $user_id );
1898  
1899      return ( isset( $u->spam ) && $u->spam == 1 );
1900  }
1901  
1902  /**
1903   * Update this blog's 'public' setting in the global blogs table.
1904   *
1905   * Public blogs have a setting of 1, private blogs are 0.
1906   *
1907   * @since MU
1908   * @uses update_blog_status()
1909   *
1910   * @param int $old_value
1911   * @param int $value The new public value
1912   * @return bool
1913   */
1914  function update_blog_public( $old_value, $value ) {
1915      global $wpdb;
1916      do_action('update_blog_public');
1917      update_blog_status( $wpdb->blogid, 'public', (int) $value );
1918  }
1919  add_action('update_option_blog_public', 'update_blog_public', 10, 2);
1920  
1921  /**
1922   * Get the "dashboard blog", the blog where users without a blog edit their profile data.
1923   *
1924   * @since MU
1925   * @uses get_blog_details()
1926   *
1927   * @return int
1928   */
1929  function get_dashboard_blog() {
1930      if ( $blog = get_site_option( 'dashboard_blog' ) )
1931          return get_blog_details( $blog );
1932  
1933      return get_blog_details( $GLOBALS['current_site']->blog_id );
1934  }
1935  
1936  /**
1937   * Check whether a usermeta key has to do with the current blog.
1938   *
1939   * @since MU
1940   * @uses wp_get_current_user()
1941   *
1942   * @param string $key
1943   * @param int $user_id Optional. Defaults to current user.
1944   * @param int $blog_id Optional. Defaults to current blog.
1945   * @return bool
1946   */
1947  function is_user_option_local( $key, $user_id = 0, $blog_id = 0 ) {
1948      global $wpdb;
1949  
1950      $current_user = wp_get_current_user();
1951      if ( $user_id == 0 )
1952          $user_id = $current_user->ID;
1953      if ( $blog_id == 0 )
1954          $blog_id = $wpdb->blogid;
1955  
1956      $local_key = $wpdb->base_prefix . $blog_id . '_' . $key;
1957  
1958      if ( isset( $current_user->$local_key ) )
1959          return true;
1960  
1961      return false;
1962  }
1963  
1964  /**
1965   * Check whether users can self-register, based on Network settings.
1966   *
1967   * @since MU
1968   *
1969   * @return bool
1970   */
1971  function users_can_register_signup_filter() {
1972      $registration = get_site_option('registration');
1973      if ( $registration == 'all' || $registration == 'user' )
1974          return true;
1975  
1976      return false;
1977  }
1978  add_filter('option_users_can_register', 'users_can_register_signup_filter');
1979  
1980  /**
1981   * Ensure that the welcome message is not empty. Currently unused.
1982   *
1983   * @since MU
1984   *
1985   * @param string $text
1986   * @return string
1987   */
1988  function welcome_user_msg_filter( $text ) {
1989      if ( !$text ) {
1990          return __( 'Dear User,
1991  
1992  Your new account is set up.
1993  
1994  You can log in with the following information:
1995  Username: USERNAME
1996  Password: PASSWORD
1997  LOGINLINK
1998  
1999  Thanks!
2000  
2001  --The Team @ SITE_NAME' );
2002      }
2003      return $text;
2004  }
2005  add_filter( 'site_option_welcome_user_email', 'welcome_user_msg_filter' );
2006  
2007  /**
2008   * Whether to force SSL on content.
2009   *
2010   * @since 2.8.5
2011   *
2012   * @param string|bool $force
2013   * @return bool True if forced, false if not forced.
2014   */
2015  function force_ssl_content( $force = '' ) {
2016      static $forced_content;
2017  
2018      if ( '' != $force ) {
2019          $old_forced = $forced_content;
2020          $forced_content = $force;
2021          return $old_forced;
2022      }
2023  
2024      return $forced_content;
2025  }
2026  
2027  /**
2028   * Formats an String URL to use HTTPS if HTTP is found.
2029   * Useful as a filter.
2030   *
2031   * @since 2.8.5
2032   **/
2033  function filter_SSL( $url ) {
2034      if ( !is_string( $url ) )
2035          return get_bloginfo( 'url' ); //return home blog url with proper scheme
2036  
2037      $arrURL = parse_url( $url );
2038  
2039      if ( force_ssl_content() && is_ssl() ) {
2040          if ( 'http' === $arrURL['scheme'] && 'https' !== $arrURL['scheme'] )
2041              $url = str_replace( $arrURL['scheme'], 'https', $url );
2042      }
2043  
2044      return $url;
2045  }
2046  
2047  /**
2048   * Schedule update of the network-wide counts for the current network.
2049   *
2050   * @since 3.1.0
2051   */
2052  function wp_schedule_update_network_counts() {
2053      if ( !is_main_site() )
2054          return;
2055  
2056      if ( !wp_next_scheduled('update_network_counts') && !defined('WP_INSTALLING') )
2057          wp_schedule_event(time(), 'twicedaily', 'update_network_counts');
2058  }
2059  
2060  /**
2061   *  Update the network-wide counts for the current network.
2062   *
2063   *  @since 3.1.0
2064   */
2065  function wp_update_network_counts() {
2066      global $wpdb;
2067  
2068      $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'", $wpdb->siteid) );
2069      update_site_option( 'blog_count', $count );
2070  
2071      $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(ID) as c FROM $wpdb->users WHERE spam = '0' AND deleted = '0'") );
2072      update_site_option( 'user_count', $count );
2073  }
2074  
2075  ?>


Generated: Wed Jun 1 08:30:02 2011 Cross-referenced by PHPXref 0.7
Provided by Yoast and awesome WordPress Hosting