wp/wp-includes/pluggable.php
changeset 0 d970ebf37754
child 5 5e2f62d02dcd
equal deleted inserted replaced
-1:000000000000 0:d970ebf37754
       
     1 <?php
       
     2 /**
       
     3  * These functions can be replaced via plugins. If plugins do not redefine these
       
     4  * functions, then these will be used instead.
       
     5  *
       
     6  * @package WordPress
       
     7  */
       
     8 
       
     9 if ( !function_exists('wp_set_current_user') ) :
       
    10 /**
       
    11  * Changes the current user by ID or name.
       
    12  *
       
    13  * Set $id to null and specify a name if you do not know a user's ID.
       
    14  *
       
    15  * Some WordPress functionality is based on the current user and not based on
       
    16  * the signed in user. Therefore, it opens the ability to edit and perform
       
    17  * actions on users who aren't signed in.
       
    18  *
       
    19  * @since 2.0.3
       
    20  * @global object $current_user The current user object which holds the user data.
       
    21  * @uses do_action() Calls 'set_current_user' hook after setting the current user.
       
    22  *
       
    23  * @param int $id User ID
       
    24  * @param string $name User's username
       
    25  * @return WP_User Current user User object
       
    26  */
       
    27 function wp_set_current_user($id, $name = '') {
       
    28 	global $current_user;
       
    29 
       
    30 	if ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->ID ) )
       
    31 		return $current_user;
       
    32 
       
    33 	$current_user = new WP_User( $id, $name );
       
    34 
       
    35 	setup_userdata( $current_user->ID );
       
    36 
       
    37 	do_action('set_current_user');
       
    38 
       
    39 	return $current_user;
       
    40 }
       
    41 endif;
       
    42 
       
    43 if ( !function_exists('wp_get_current_user') ) :
       
    44 /**
       
    45  * Retrieve the current user object.
       
    46  *
       
    47  * @since 2.0.3
       
    48  *
       
    49  * @return WP_User Current user WP_User object
       
    50  */
       
    51 function wp_get_current_user() {
       
    52 	global $current_user;
       
    53 
       
    54 	get_currentuserinfo();
       
    55 
       
    56 	return $current_user;
       
    57 }
       
    58 endif;
       
    59 
       
    60 if ( !function_exists('get_currentuserinfo') ) :
       
    61 /**
       
    62  * Populate global variables with information about the currently logged in user.
       
    63  *
       
    64  * Will set the current user, if the current user is not set. The current user
       
    65  * will be set to the logged in person. If no user is logged in, then it will
       
    66  * set the current user to 0, which is invalid and won't have any permissions.
       
    67  *
       
    68  * @since 0.71
       
    69  * @uses $current_user Checks if the current user is set
       
    70  * @uses wp_validate_auth_cookie() Retrieves current logged in user.
       
    71  *
       
    72  * @return bool|null False on XMLRPC Request and invalid auth cookie. Null when current user set
       
    73  */
       
    74 function get_currentuserinfo() {
       
    75 	global $current_user;
       
    76 
       
    77 	if ( ! empty( $current_user ) ) {
       
    78 		if ( $current_user instanceof WP_User )
       
    79 			return;
       
    80 
       
    81 		// Upgrade stdClass to WP_User
       
    82 		if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
       
    83 			$cur_id = $current_user->ID;
       
    84 			$current_user = null;
       
    85 			wp_set_current_user( $cur_id );
       
    86 			return;
       
    87 		}
       
    88 
       
    89 		// $current_user has a junk value. Force to WP_User with ID 0.
       
    90 		$current_user = null;
       
    91 		wp_set_current_user( 0 );
       
    92 		return false;
       
    93 	}
       
    94 
       
    95 	if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
       
    96 		wp_set_current_user( 0 );
       
    97 		return false;
       
    98 	}
       
    99 
       
   100 	if ( ! $user = wp_validate_auth_cookie() ) {
       
   101 		 if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[LOGGED_IN_COOKIE] ) || !$user = wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' ) ) {
       
   102 		 	wp_set_current_user( 0 );
       
   103 		 	return false;
       
   104 		 }
       
   105 	}
       
   106 
       
   107 	wp_set_current_user( $user );
       
   108 }
       
   109 endif;
       
   110 
       
   111 if ( !function_exists('get_userdata') ) :
       
   112 /**
       
   113  * Retrieve user info by user ID.
       
   114  *
       
   115  * @since 0.71
       
   116  *
       
   117  * @param int $user_id User ID
       
   118  * @return WP_User|bool WP_User object on success, false on failure.
       
   119  */
       
   120 function get_userdata( $user_id ) {
       
   121 	return get_user_by( 'id', $user_id );
       
   122 }
       
   123 endif;
       
   124 
       
   125 if ( !function_exists('get_user_by') ) :
       
   126 /**
       
   127  * Retrieve user info by a given field
       
   128  *
       
   129  * @since 2.8.0
       
   130  *
       
   131  * @param string $field The field to retrieve the user with. id | slug | email | login
       
   132  * @param int|string $value A value for $field. A user ID, slug, email address, or login name.
       
   133  * @return WP_User|bool WP_User object on success, false on failure.
       
   134  */
       
   135 function get_user_by( $field, $value ) {
       
   136 	$userdata = WP_User::get_data_by( $field, $value );
       
   137 
       
   138 	if ( !$userdata )
       
   139 		return false;
       
   140 
       
   141 	$user = new WP_User;
       
   142 	$user->init( $userdata );
       
   143 
       
   144 	return $user;
       
   145 }
       
   146 endif;
       
   147 
       
   148 if ( !function_exists('cache_users') ) :
       
   149 /**
       
   150  * Retrieve info for user lists to prevent multiple queries by get_userdata()
       
   151  *
       
   152  * @since 3.0.0
       
   153  *
       
   154  * @param array $user_ids User ID numbers list
       
   155  */
       
   156 function cache_users( $user_ids ) {
       
   157 	global $wpdb;
       
   158 
       
   159 	$clean = _get_non_cached_ids( $user_ids, 'users' );
       
   160 
       
   161 	if ( empty( $clean ) )
       
   162 		return;
       
   163 
       
   164 	$list = implode( ',', $clean );
       
   165 
       
   166 	$users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" );
       
   167 
       
   168 	$ids = array();
       
   169 	foreach ( $users as $user ) {
       
   170 		update_user_caches( $user );
       
   171 		$ids[] = $user->ID;
       
   172 	}
       
   173 	update_meta_cache( 'user', $ids );
       
   174 }
       
   175 endif;
       
   176 
       
   177 if ( !function_exists( 'wp_mail' ) ) :
       
   178 /**
       
   179  * Send mail, similar to PHP's mail
       
   180  *
       
   181  * A true return value does not automatically mean that the user received the
       
   182  * email successfully. It just only means that the method used was able to
       
   183  * process the request without any errors.
       
   184  *
       
   185  * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
       
   186  * creating a from address like 'Name <email@address.com>' when both are set. If
       
   187  * just 'wp_mail_from' is set, then just the email address will be used with no
       
   188  * name.
       
   189  *
       
   190  * The default content type is 'text/plain' which does not allow using HTML.
       
   191  * However, you can set the content type of the email by using the
       
   192  * 'wp_mail_content_type' filter.
       
   193  *
       
   194  * The default charset is based on the charset used on the blog. The charset can
       
   195  * be set using the 'wp_mail_charset' filter.
       
   196  *
       
   197  * @since 1.2.1
       
   198  * @uses apply_filters() Calls 'wp_mail' hook on an array of all of the parameters.
       
   199  * @uses apply_filters() Calls 'wp_mail_from' hook to get the from email address.
       
   200  * @uses apply_filters() Calls 'wp_mail_from_name' hook to get the from address name.
       
   201  * @uses apply_filters() Calls 'wp_mail_content_type' hook to get the email content type.
       
   202  * @uses apply_filters() Calls 'wp_mail_charset' hook to get the email charset
       
   203  * @uses do_action_ref_array() Calls 'phpmailer_init' hook on the reference to
       
   204  *		phpmailer object.
       
   205  * @uses PHPMailer
       
   206  *
       
   207  * @param string|array $to Array or comma-separated list of email addresses to send message.
       
   208  * @param string $subject Email subject
       
   209  * @param string $message Message contents
       
   210  * @param string|array $headers Optional. Additional headers.
       
   211  * @param string|array $attachments Optional. Files to attach.
       
   212  * @return bool Whether the email contents were sent successfully.
       
   213  */
       
   214 function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
       
   215 	// Compact the input, apply the filters, and extract them back out
       
   216 	extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) );
       
   217 
       
   218 	if ( !is_array($attachments) )
       
   219 		$attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
       
   220 
       
   221 	global $phpmailer;
       
   222 
       
   223 	// (Re)create it, if it's gone missing
       
   224 	if ( !is_object( $phpmailer ) || !is_a( $phpmailer, 'PHPMailer' ) ) {
       
   225 		require_once ABSPATH . WPINC . '/class-phpmailer.php';
       
   226 		require_once ABSPATH . WPINC . '/class-smtp.php';
       
   227 		$phpmailer = new PHPMailer( true );
       
   228 	}
       
   229 
       
   230 	// Headers
       
   231 	if ( empty( $headers ) ) {
       
   232 		$headers = array();
       
   233 	} else {
       
   234 		if ( !is_array( $headers ) ) {
       
   235 			// Explode the headers out, so this function can take both
       
   236 			// string headers and an array of headers.
       
   237 			$tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
       
   238 		} else {
       
   239 			$tempheaders = $headers;
       
   240 		}
       
   241 		$headers = array();
       
   242 		$cc = array();
       
   243 		$bcc = array();
       
   244 
       
   245 		// If it's actually got contents
       
   246 		if ( !empty( $tempheaders ) ) {
       
   247 			// Iterate through the raw headers
       
   248 			foreach ( (array) $tempheaders as $header ) {
       
   249 				if ( strpos($header, ':') === false ) {
       
   250 					if ( false !== stripos( $header, 'boundary=' ) ) {
       
   251 						$parts = preg_split('/boundary=/i', trim( $header ) );
       
   252 						$boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
       
   253 					}
       
   254 					continue;
       
   255 				}
       
   256 				// Explode them out
       
   257 				list( $name, $content ) = explode( ':', trim( $header ), 2 );
       
   258 
       
   259 				// Cleanup crew
       
   260 				$name    = trim( $name    );
       
   261 				$content = trim( $content );
       
   262 
       
   263 				switch ( strtolower( $name ) ) {
       
   264 					// Mainly for legacy -- process a From: header if it's there
       
   265 					case 'from':
       
   266 						if ( strpos($content, '<' ) !== false ) {
       
   267 							// So... making my life hard again?
       
   268 							$from_name = substr( $content, 0, strpos( $content, '<' ) - 1 );
       
   269 							$from_name = str_replace( '"', '', $from_name );
       
   270 							$from_name = trim( $from_name );
       
   271 
       
   272 							$from_email = substr( $content, strpos( $content, '<' ) + 1 );
       
   273 							$from_email = str_replace( '>', '', $from_email );
       
   274 							$from_email = trim( $from_email );
       
   275 						} else {
       
   276 							$from_email = trim( $content );
       
   277 						}
       
   278 						break;
       
   279 					case 'content-type':
       
   280 						if ( strpos( $content, ';' ) !== false ) {
       
   281 							list( $type, $charset ) = explode( ';', $content );
       
   282 							$content_type = trim( $type );
       
   283 							if ( false !== stripos( $charset, 'charset=' ) ) {
       
   284 								$charset = trim( str_replace( array( 'charset=', '"' ), '', $charset ) );
       
   285 							} elseif ( false !== stripos( $charset, 'boundary=' ) ) {
       
   286 								$boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset ) );
       
   287 								$charset = '';
       
   288 							}
       
   289 						} else {
       
   290 							$content_type = trim( $content );
       
   291 						}
       
   292 						break;
       
   293 					case 'cc':
       
   294 						$cc = array_merge( (array) $cc, explode( ',', $content ) );
       
   295 						break;
       
   296 					case 'bcc':
       
   297 						$bcc = array_merge( (array) $bcc, explode( ',', $content ) );
       
   298 						break;
       
   299 					default:
       
   300 						// Add it to our grand headers array
       
   301 						$headers[trim( $name )] = trim( $content );
       
   302 						break;
       
   303 				}
       
   304 			}
       
   305 		}
       
   306 	}
       
   307 
       
   308 	// Empty out the values that may be set
       
   309 	$phpmailer->ClearAddresses();
       
   310 	$phpmailer->ClearAllRecipients();
       
   311 	$phpmailer->ClearAttachments();
       
   312 	$phpmailer->ClearBCCs();
       
   313 	$phpmailer->ClearCCs();
       
   314 	$phpmailer->ClearCustomHeaders();
       
   315 	$phpmailer->ClearReplyTos();
       
   316 
       
   317 	// From email and name
       
   318 	// If we don't have a name from the input headers
       
   319 	if ( !isset( $from_name ) )
       
   320 		$from_name = 'WordPress';
       
   321 
       
   322 	/* If we don't have an email from the input headers default to wordpress@$sitename
       
   323 	 * Some hosts will block outgoing mail from this address if it doesn't exist but
       
   324 	 * there's no easy alternative. Defaulting to admin_email might appear to be another
       
   325 	 * option but some hosts may refuse to relay mail from an unknown domain. See
       
   326 	 * http://trac.wordpress.org/ticket/5007.
       
   327 	 */
       
   328 
       
   329 	if ( !isset( $from_email ) ) {
       
   330 		// Get the site domain and get rid of www.
       
   331 		$sitename = strtolower( $_SERVER['SERVER_NAME'] );
       
   332 		if ( substr( $sitename, 0, 4 ) == 'www.' ) {
       
   333 			$sitename = substr( $sitename, 4 );
       
   334 		}
       
   335 
       
   336 		$from_email = 'wordpress@' . $sitename;
       
   337 	}
       
   338 
       
   339 	// Plugin authors can override the potentially troublesome default
       
   340 	$phpmailer->From     = apply_filters( 'wp_mail_from'     , $from_email );
       
   341 	$phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name  );
       
   342 
       
   343 	// Set destination addresses
       
   344 	if ( !is_array( $to ) )
       
   345 		$to = explode( ',', $to );
       
   346 
       
   347 	foreach ( (array) $to as $recipient ) {
       
   348 		try {
       
   349 			// Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
       
   350 			$recipient_name = '';
       
   351 			if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
       
   352 				if ( count( $matches ) == 3 ) {
       
   353 					$recipient_name = $matches[1];
       
   354 					$recipient = $matches[2];
       
   355 				}
       
   356 			}
       
   357 			$phpmailer->AddAddress( $recipient, $recipient_name);
       
   358 		} catch ( phpmailerException $e ) {
       
   359 			continue;
       
   360 		}
       
   361 	}
       
   362 
       
   363 	// Set mail's subject and body
       
   364 	$phpmailer->Subject = $subject;
       
   365 	$phpmailer->Body    = $message;
       
   366 
       
   367 	// Add any CC and BCC recipients
       
   368 	if ( !empty( $cc ) ) {
       
   369 		foreach ( (array) $cc as $recipient ) {
       
   370 			try {
       
   371 				// Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
       
   372 				$recipient_name = '';
       
   373 				if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
       
   374 					if ( count( $matches ) == 3 ) {
       
   375 						$recipient_name = $matches[1];
       
   376 						$recipient = $matches[2];
       
   377 					}
       
   378 				}
       
   379 				$phpmailer->AddCc( $recipient, $recipient_name );
       
   380 			} catch ( phpmailerException $e ) {
       
   381 				continue;
       
   382 			}
       
   383 		}
       
   384 	}
       
   385 
       
   386 	if ( !empty( $bcc ) ) {
       
   387 		foreach ( (array) $bcc as $recipient) {
       
   388 			try {
       
   389 				// Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
       
   390 				$recipient_name = '';
       
   391 				if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
       
   392 					if ( count( $matches ) == 3 ) {
       
   393 						$recipient_name = $matches[1];
       
   394 						$recipient = $matches[2];
       
   395 					}
       
   396 				}
       
   397 				$phpmailer->AddBcc( $recipient, $recipient_name );
       
   398 			} catch ( phpmailerException $e ) {
       
   399 				continue;
       
   400 			}
       
   401 		}
       
   402 	}
       
   403 
       
   404 	// Set to use PHP's mail()
       
   405 	$phpmailer->IsMail();
       
   406 
       
   407 	// Set Content-Type and charset
       
   408 	// If we don't have a content-type from the input headers
       
   409 	if ( !isset( $content_type ) )
       
   410 		$content_type = 'text/plain';
       
   411 
       
   412 	$content_type = apply_filters( 'wp_mail_content_type', $content_type );
       
   413 
       
   414 	$phpmailer->ContentType = $content_type;
       
   415 
       
   416 	// Set whether it's plaintext, depending on $content_type
       
   417 	if ( 'text/html' == $content_type )
       
   418 		$phpmailer->IsHTML( true );
       
   419 
       
   420 	// If we don't have a charset from the input headers
       
   421 	if ( !isset( $charset ) )
       
   422 		$charset = get_bloginfo( 'charset' );
       
   423 
       
   424 	// Set the content-type and charset
       
   425 	$phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
       
   426 
       
   427 	// Set custom headers
       
   428 	if ( !empty( $headers ) ) {
       
   429 		foreach( (array) $headers as $name => $content ) {
       
   430 			$phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
       
   431 		}
       
   432 
       
   433 		if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
       
   434 			$phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
       
   435 	}
       
   436 
       
   437 	if ( !empty( $attachments ) ) {
       
   438 		foreach ( $attachments as $attachment ) {
       
   439 			try {
       
   440 				$phpmailer->AddAttachment($attachment);
       
   441 			} catch ( phpmailerException $e ) {
       
   442 				continue;
       
   443 			}
       
   444 		}
       
   445 	}
       
   446 
       
   447 	do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
       
   448 
       
   449 	// Send!
       
   450 	try {
       
   451 		return $phpmailer->Send();
       
   452 	} catch ( phpmailerException $e ) {
       
   453 		return false;
       
   454 	}
       
   455 }
       
   456 endif;
       
   457 
       
   458 if ( !function_exists('wp_authenticate') ) :
       
   459 /**
       
   460  * Checks a user's login information and logs them in if it checks out.
       
   461  *
       
   462  * @since 2.5.0
       
   463  *
       
   464  * @param string $username User's username
       
   465  * @param string $password User's password
       
   466  * @return WP_User|WP_Error WP_User object if login successful, otherwise WP_Error object.
       
   467  */
       
   468 function wp_authenticate($username, $password) {
       
   469 	$username = sanitize_user($username);
       
   470 	$password = trim($password);
       
   471 
       
   472 	$user = apply_filters('authenticate', null, $username, $password);
       
   473 
       
   474 	if ( $user == null ) {
       
   475 		// TODO what should the error message be? (Or would these even happen?)
       
   476 		// Only needed if all authentication handlers fail to return anything.
       
   477 		$user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));
       
   478 	}
       
   479 
       
   480 	$ignore_codes = array('empty_username', 'empty_password');
       
   481 
       
   482 	if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
       
   483 		do_action('wp_login_failed', $username);
       
   484 	}
       
   485 
       
   486 	return $user;
       
   487 }
       
   488 endif;
       
   489 
       
   490 if ( !function_exists('wp_logout') ) :
       
   491 /**
       
   492  * Log the current user out.
       
   493  *
       
   494  * @since 2.5.0
       
   495  */
       
   496 function wp_logout() {
       
   497 	wp_clear_auth_cookie();
       
   498 	do_action('wp_logout');
       
   499 }
       
   500 endif;
       
   501 
       
   502 if ( !function_exists('wp_validate_auth_cookie') ) :
       
   503 /**
       
   504  * Validates authentication cookie.
       
   505  *
       
   506  * The checks include making sure that the authentication cookie is set and
       
   507  * pulling in the contents (if $cookie is not used).
       
   508  *
       
   509  * Makes sure the cookie is not expired. Verifies the hash in cookie is what is
       
   510  * should be and compares the two.
       
   511  *
       
   512  * @since 2.5
       
   513  *
       
   514  * @param string $cookie Optional. If used, will validate contents instead of cookie's
       
   515  * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
       
   516  * @return bool|int False if invalid cookie, User ID if valid.
       
   517  */
       
   518 function wp_validate_auth_cookie($cookie = '', $scheme = '') {
       
   519 	if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) {
       
   520 		do_action('auth_cookie_malformed', $cookie, $scheme);
       
   521 		return false;
       
   522 	}
       
   523 
       
   524 	extract($cookie_elements, EXTR_OVERWRITE);
       
   525 
       
   526 	$expired = $expiration;
       
   527 
       
   528 	// Allow a grace period for POST and AJAX requests
       
   529 	if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] )
       
   530 		$expired += HOUR_IN_SECONDS;
       
   531 
       
   532 	// Quick check to see if an honest cookie has expired
       
   533 	if ( $expired < time() ) {
       
   534 		do_action('auth_cookie_expired', $cookie_elements);
       
   535 		return false;
       
   536 	}
       
   537 
       
   538 	$user = get_user_by('login', $username);
       
   539 	if ( ! $user ) {
       
   540 		do_action('auth_cookie_bad_username', $cookie_elements);
       
   541 		return false;
       
   542 	}
       
   543 
       
   544 	$pass_frag = substr($user->user_pass, 8, 4);
       
   545 
       
   546 	$key = wp_hash($username . $pass_frag . '|' . $expiration, $scheme);
       
   547 	$hash = hash_hmac('md5', $username . '|' . $expiration, $key);
       
   548 
       
   549 	if ( $hmac != $hash ) {
       
   550 		do_action('auth_cookie_bad_hash', $cookie_elements);
       
   551 		return false;
       
   552 	}
       
   553 
       
   554 	if ( $expiration < time() ) // AJAX/POST grace period set above
       
   555 		$GLOBALS['login_grace_period'] = 1;
       
   556 
       
   557 	do_action('auth_cookie_valid', $cookie_elements, $user);
       
   558 
       
   559 	return $user->ID;
       
   560 }
       
   561 endif;
       
   562 
       
   563 if ( !function_exists('wp_generate_auth_cookie') ) :
       
   564 /**
       
   565  * Generate authentication cookie contents.
       
   566  *
       
   567  * @since 2.5
       
   568  * @uses apply_filters() Calls 'auth_cookie' hook on $cookie contents, User ID
       
   569  *		and expiration of cookie.
       
   570  *
       
   571  * @param int $user_id User ID
       
   572  * @param int $expiration Cookie expiration in seconds
       
   573  * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
       
   574  * @return string Authentication cookie contents
       
   575  */
       
   576 function wp_generate_auth_cookie($user_id, $expiration, $scheme = 'auth') {
       
   577 	$user = get_userdata($user_id);
       
   578 
       
   579 	$pass_frag = substr($user->user_pass, 8, 4);
       
   580 
       
   581 	$key = wp_hash($user->user_login . $pass_frag . '|' . $expiration, $scheme);
       
   582 	$hash = hash_hmac('md5', $user->user_login . '|' . $expiration, $key);
       
   583 
       
   584 	$cookie = $user->user_login . '|' . $expiration . '|' . $hash;
       
   585 
       
   586 	return apply_filters('auth_cookie', $cookie, $user_id, $expiration, $scheme);
       
   587 }
       
   588 endif;
       
   589 
       
   590 if ( !function_exists('wp_parse_auth_cookie') ) :
       
   591 /**
       
   592  * Parse a cookie into its components
       
   593  *
       
   594  * @since 2.7
       
   595  *
       
   596  * @param string $cookie
       
   597  * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
       
   598  * @return array Authentication cookie components
       
   599  */
       
   600 function wp_parse_auth_cookie($cookie = '', $scheme = '') {
       
   601 	if ( empty($cookie) ) {
       
   602 		switch ($scheme){
       
   603 			case 'auth':
       
   604 				$cookie_name = AUTH_COOKIE;
       
   605 				break;
       
   606 			case 'secure_auth':
       
   607 				$cookie_name = SECURE_AUTH_COOKIE;
       
   608 				break;
       
   609 			case "logged_in":
       
   610 				$cookie_name = LOGGED_IN_COOKIE;
       
   611 				break;
       
   612 			default:
       
   613 				if ( is_ssl() ) {
       
   614 					$cookie_name = SECURE_AUTH_COOKIE;
       
   615 					$scheme = 'secure_auth';
       
   616 				} else {
       
   617 					$cookie_name = AUTH_COOKIE;
       
   618 					$scheme = 'auth';
       
   619 				}
       
   620 	    }
       
   621 
       
   622 		if ( empty($_COOKIE[$cookie_name]) )
       
   623 			return false;
       
   624 		$cookie = $_COOKIE[$cookie_name];
       
   625 	}
       
   626 
       
   627 	$cookie_elements = explode('|', $cookie);
       
   628 	if ( count($cookie_elements) != 3 )
       
   629 		return false;
       
   630 
       
   631 	list($username, $expiration, $hmac) = $cookie_elements;
       
   632 
       
   633 	return compact('username', 'expiration', 'hmac', 'scheme');
       
   634 }
       
   635 endif;
       
   636 
       
   637 if ( !function_exists('wp_set_auth_cookie') ) :
       
   638 /**
       
   639  * Sets the authentication cookies based User ID.
       
   640  *
       
   641  * The $remember parameter increases the time that the cookie will be kept. The
       
   642  * default the cookie is kept without remembering is two days. When $remember is
       
   643  * set, the cookies will be kept for 14 days or two weeks.
       
   644  *
       
   645  * @since 2.5
       
   646  *
       
   647  * @param int $user_id User ID
       
   648  * @param bool $remember Whether to remember the user
       
   649  */
       
   650 function wp_set_auth_cookie($user_id, $remember = false, $secure = '') {
       
   651 	if ( $remember ) {
       
   652 		$expiration = time() + apply_filters('auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember);
       
   653 		// Ensure the browser will continue to send the cookie after the expiration time is reached.
       
   654 		// Needed for the login grace period in wp_validate_auth_cookie().
       
   655 		$expire = $expiration + ( 12 * HOUR_IN_SECONDS );
       
   656 	} else {
       
   657 		$expiration = time() + apply_filters('auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember);
       
   658 		$expire = 0;
       
   659 	}
       
   660 
       
   661 	if ( '' === $secure )
       
   662 		$secure = is_ssl();
       
   663 
       
   664 	$secure = apply_filters('secure_auth_cookie', $secure, $user_id);
       
   665 	$secure_logged_in_cookie = apply_filters('secure_logged_in_cookie', false, $user_id, $secure);
       
   666 
       
   667 	if ( $secure ) {
       
   668 		$auth_cookie_name = SECURE_AUTH_COOKIE;
       
   669 		$scheme = 'secure_auth';
       
   670 	} else {
       
   671 		$auth_cookie_name = AUTH_COOKIE;
       
   672 		$scheme = 'auth';
       
   673 	}
       
   674 
       
   675 	$auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme);
       
   676 	$logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
       
   677 
       
   678 	do_action('set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme);
       
   679 	do_action('set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in');
       
   680 
       
   681 	setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
       
   682 	setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
       
   683 	setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
       
   684 	if ( COOKIEPATH != SITECOOKIEPATH )
       
   685 		setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
       
   686 }
       
   687 endif;
       
   688 
       
   689 if ( !function_exists('wp_clear_auth_cookie') ) :
       
   690 /**
       
   691  * Removes all of the cookies associated with authentication.
       
   692  *
       
   693  * @since 2.5
       
   694  */
       
   695 function wp_clear_auth_cookie() {
       
   696 	do_action('clear_auth_cookie');
       
   697 
       
   698 	setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH,   COOKIE_DOMAIN );
       
   699 	setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH,   COOKIE_DOMAIN );
       
   700 	setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
       
   701 	setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
       
   702 	setcookie( LOGGED_IN_COOKIE,   ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,          COOKIE_DOMAIN );
       
   703 	setcookie( LOGGED_IN_COOKIE,   ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH,      COOKIE_DOMAIN );
       
   704 
       
   705 	// Old cookies
       
   706 	setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
       
   707 	setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
       
   708 	setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
       
   709 	setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
       
   710 
       
   711 	// Even older cookies
       
   712 	setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
       
   713 	setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
       
   714 	setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
       
   715 	setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
       
   716 }
       
   717 endif;
       
   718 
       
   719 if ( !function_exists('is_user_logged_in') ) :
       
   720 /**
       
   721  * Checks if the current visitor is a logged in user.
       
   722  *
       
   723  * @since 2.0.0
       
   724  *
       
   725  * @return bool True if user is logged in, false if not logged in.
       
   726  */
       
   727 function is_user_logged_in() {
       
   728 	$user = wp_get_current_user();
       
   729 
       
   730 	if ( ! $user->exists() )
       
   731 		return false;
       
   732 
       
   733 	return true;
       
   734 }
       
   735 endif;
       
   736 
       
   737 if ( !function_exists('auth_redirect') ) :
       
   738 /**
       
   739  * Checks if a user is logged in, if not it redirects them to the login page.
       
   740  *
       
   741  * @since 1.5
       
   742  */
       
   743 function auth_redirect() {
       
   744 	// Checks if a user is logged in, if not redirects them to the login page
       
   745 
       
   746 	$secure = ( is_ssl() || force_ssl_admin() );
       
   747 
       
   748 	$secure = apply_filters('secure_auth_redirect', $secure);
       
   749 
       
   750 	// If https is required and request is http, redirect
       
   751 	if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
       
   752 		if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
       
   753 			wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
       
   754 			exit();
       
   755 		} else {
       
   756 			wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
       
   757 			exit();
       
   758 		}
       
   759 	}
       
   760 
       
   761 	if ( is_user_admin() )
       
   762 		$scheme = 'logged_in';
       
   763 	else
       
   764 		$scheme = apply_filters( 'auth_redirect_scheme', '' );
       
   765 
       
   766 	if ( $user_id = wp_validate_auth_cookie( '',  $scheme) ) {
       
   767 		do_action('auth_redirect', $user_id);
       
   768 
       
   769 		// If the user wants ssl but the session is not ssl, redirect.
       
   770 		if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
       
   771 			if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
       
   772 				wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
       
   773 				exit();
       
   774 			} else {
       
   775 				wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
       
   776 				exit();
       
   777 			}
       
   778 		}
       
   779 
       
   780 		return;  // The cookie is good so we're done
       
   781 	}
       
   782 
       
   783 	// The cookie is no good so force login
       
   784 	nocache_headers();
       
   785 
       
   786 	$redirect = ( strpos( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_get_referer() ) ? wp_get_referer() : set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
       
   787 
       
   788 	$login_url = wp_login_url($redirect, true);
       
   789 
       
   790 	wp_redirect($login_url);
       
   791 	exit();
       
   792 }
       
   793 endif;
       
   794 
       
   795 if ( !function_exists('check_admin_referer') ) :
       
   796 /**
       
   797  * Makes sure that a user was referred from another admin page.
       
   798  *
       
   799  * To avoid security exploits.
       
   800  *
       
   801  * @since 1.2.0
       
   802  * @uses do_action() Calls 'check_admin_referer' on $action.
       
   803  *
       
   804  * @param string $action Action nonce
       
   805  * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
       
   806  */
       
   807 function check_admin_referer($action = -1, $query_arg = '_wpnonce') {
       
   808 	if ( -1 == $action )
       
   809 		_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
       
   810 
       
   811 	$adminurl = strtolower(admin_url());
       
   812 	$referer = strtolower(wp_get_referer());
       
   813 	$result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
       
   814 	if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) {
       
   815 		wp_nonce_ays($action);
       
   816 		die();
       
   817 	}
       
   818 	do_action('check_admin_referer', $action, $result);
       
   819 	return $result;
       
   820 }
       
   821 endif;
       
   822 
       
   823 if ( !function_exists('check_ajax_referer') ) :
       
   824 /**
       
   825  * Verifies the AJAX request to prevent processing requests external of the blog.
       
   826  *
       
   827  * @since 2.0.3
       
   828  *
       
   829  * @param string $action Action nonce
       
   830  * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
       
   831  */
       
   832 function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
       
   833 	$nonce = '';
       
   834 
       
   835 	if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) )
       
   836 		$nonce = $_REQUEST[ $query_arg ];
       
   837 	elseif ( isset( $_REQUEST['_ajax_nonce'] ) )
       
   838 		$nonce = $_REQUEST['_ajax_nonce'];
       
   839 	elseif ( isset( $_REQUEST['_wpnonce'] ) )
       
   840 		$nonce = $_REQUEST['_wpnonce'];
       
   841 
       
   842 	$result = wp_verify_nonce( $nonce, $action );
       
   843 
       
   844 	if ( $die && false == $result ) {
       
   845 		if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
       
   846 			wp_die( -1 );
       
   847 		else
       
   848 			die( '-1' );
       
   849 	}
       
   850 
       
   851 	do_action('check_ajax_referer', $action, $result);
       
   852 
       
   853 	return $result;
       
   854 }
       
   855 endif;
       
   856 
       
   857 if ( !function_exists('wp_redirect') ) :
       
   858 /**
       
   859  * Redirects to another page.
       
   860  *
       
   861  * @since 1.5.1
       
   862  * @uses apply_filters() Calls 'wp_redirect' hook on $location and $status.
       
   863  *
       
   864  * @param string $location The path to redirect to.
       
   865  * @param int $status Status code to use.
       
   866  * @return bool False if $location is not provided, true otherwise.
       
   867  */
       
   868 function wp_redirect($location, $status = 302) {
       
   869 	global $is_IIS;
       
   870 
       
   871 	/**
       
   872 	 * Filter the redirect location.
       
   873 	 *
       
   874 	 * @since 2.1.0
       
   875 	 *
       
   876 	 * @param string $location The path to redirect to.
       
   877 	 * @param int    $status   Status code to use.
       
   878 	 */
       
   879 	$location = apply_filters( 'wp_redirect', $location, $status );
       
   880 
       
   881 	/**
       
   882 	 * Filter the redirect status code.
       
   883 	 *
       
   884 	 * @since 2.3.0
       
   885 	 *
       
   886 	 * @param int    $status   Status code to use.
       
   887 	 * @param string $location The path to redirect to.
       
   888 	 */
       
   889 	$status = apply_filters( 'wp_redirect_status', $status, $location );
       
   890 
       
   891 	if ( ! $location )
       
   892 		return false;
       
   893 
       
   894 	$location = wp_sanitize_redirect($location);
       
   895 
       
   896 	if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' )
       
   897 		status_header($status); // This causes problems on IIS and some FastCGI setups
       
   898 
       
   899 	header("Location: $location", true, $status);
       
   900 
       
   901 	return true;
       
   902 }
       
   903 endif;
       
   904 
       
   905 if ( !function_exists('wp_sanitize_redirect') ) :
       
   906 /**
       
   907  * Sanitizes a URL for use in a redirect.
       
   908  *
       
   909  * @since 2.3
       
   910  *
       
   911  * @return string redirect-sanitized URL
       
   912  **/
       
   913 function wp_sanitize_redirect($location) {
       
   914 	$location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!]|i', '', $location);
       
   915 	$location = wp_kses_no_null($location);
       
   916 
       
   917 	// remove %0d and %0a from location
       
   918 	$strip = array('%0d', '%0a', '%0D', '%0A');
       
   919 	$location = _deep_replace($strip, $location);
       
   920 	return $location;
       
   921 }
       
   922 endif;
       
   923 
       
   924 if ( !function_exists('wp_safe_redirect') ) :
       
   925 /**
       
   926  * Performs a safe (local) redirect, using wp_redirect().
       
   927  *
       
   928  * Checks whether the $location is using an allowed host, if it has an absolute
       
   929  * path. A plugin can therefore set or remove allowed host(s) to or from the
       
   930  * list.
       
   931  *
       
   932  * If the host is not allowed, then the redirect is to wp-admin on the siteurl
       
   933  * instead. This prevents malicious redirects which redirect to another host,
       
   934  * but only used in a few places.
       
   935  *
       
   936  * @since 2.3
       
   937  * @uses wp_validate_redirect() To validate the redirect is to an allowed host.
       
   938  *
       
   939  * @return void Does not return anything
       
   940  **/
       
   941 function wp_safe_redirect($location, $status = 302) {
       
   942 
       
   943 	// Need to look at the URL the way it will end up in wp_redirect()
       
   944 	$location = wp_sanitize_redirect($location);
       
   945 
       
   946 	$location = wp_validate_redirect($location, admin_url());
       
   947 
       
   948 	wp_redirect($location, $status);
       
   949 }
       
   950 endif;
       
   951 
       
   952 if ( !function_exists('wp_validate_redirect') ) :
       
   953 /**
       
   954  * Validates a URL for use in a redirect.
       
   955  *
       
   956  * Checks whether the $location is using an allowed host, if it has an absolute
       
   957  * path. A plugin can therefore set or remove allowed host(s) to or from the
       
   958  * list.
       
   959  *
       
   960  * If the host is not allowed, then the redirect is to $default supplied
       
   961  *
       
   962  * @since 2.8.1
       
   963  * @uses apply_filters() Calls 'allowed_redirect_hosts' on an array containing
       
   964  *		WordPress host string and $location host string.
       
   965  *
       
   966  * @param string $location The redirect to validate
       
   967  * @param string $default The value to return if $location is not allowed
       
   968  * @return string redirect-sanitized URL
       
   969  **/
       
   970 function wp_validate_redirect($location, $default = '') {
       
   971 	$location = trim( $location );
       
   972 	// browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
       
   973 	if ( substr($location, 0, 2) == '//' )
       
   974 		$location = 'http:' . $location;
       
   975 
       
   976 	// In php 5 parse_url may fail if the URL query part contains http://, bug #38143
       
   977 	$test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
       
   978 
       
   979 	$lp  = parse_url($test);
       
   980 
       
   981 	// Give up if malformed URL
       
   982 	if ( false === $lp )
       
   983 		return $default;
       
   984 
       
   985 	// Allow only http and https schemes. No data:, etc.
       
   986 	if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
       
   987 		return $default;
       
   988 
       
   989 	// Reject if scheme is set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.
       
   990 	if ( isset($lp['scheme'])  && !isset($lp['host']) )
       
   991 		return $default;
       
   992 
       
   993 	$wpp = parse_url(home_url());
       
   994 
       
   995 	$allowed_hosts = (array) apply_filters('allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '');
       
   996 
       
   997 	if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
       
   998 		$location = $default;
       
   999 
       
  1000 	return $location;
       
  1001 }
       
  1002 endif;
       
  1003 
       
  1004 if ( ! function_exists('wp_notify_postauthor') ) :
       
  1005 /**
       
  1006  * Notify an author of a comment/trackback/pingback to one of their posts.
       
  1007  *
       
  1008  * @since 1.0.0
       
  1009  *
       
  1010  * @param int $comment_id Comment ID
       
  1011  * @param string $comment_type Optional. The comment type either 'comment' (default), 'trackback', or 'pingback'
       
  1012  * @return bool False if user email does not exist. True on completion.
       
  1013  */
       
  1014 function wp_notify_postauthor( $comment_id, $comment_type = '' ) {
       
  1015 	$comment = get_comment( $comment_id );
       
  1016 	if ( empty( $comment ) )
       
  1017 		return false;
       
  1018 
       
  1019 	$post    = get_post( $comment->comment_post_ID );
       
  1020 	$author  = get_userdata( $post->post_author );
       
  1021 
       
  1022 	// The comment was left by the author
       
  1023 	if ( $comment->user_id == $post->post_author )
       
  1024 		return false;
       
  1025 
       
  1026 	// The author moderated a comment on his own post
       
  1027 	if ( $post->post_author == get_current_user_id() )
       
  1028 		return false;
       
  1029 
       
  1030 	// The post author is no longer a member of the blog
       
  1031 	if ( ! user_can( $post->post_author, 'read_post', $post->ID ) )
       
  1032 		return false;
       
  1033 
       
  1034 	// If there's no email to send the comment to
       
  1035 	if ( '' == $author->user_email )
       
  1036 		return false;
       
  1037 
       
  1038 	$comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
       
  1039 
       
  1040 	// The blogname option is escaped with esc_html on the way into the database in sanitize_option
       
  1041 	// we want to reverse this for the plain text arena of emails.
       
  1042 	$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
       
  1043 
       
  1044 	if ( empty( $comment_type ) ) $comment_type = 'comment';
       
  1045 
       
  1046 	if ('comment' == $comment_type) {
       
  1047 		$notify_message  = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n";
       
  1048 		/* translators: 1: comment author, 2: author IP, 3: author domain */
       
  1049 		$notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
       
  1050 		$notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
       
  1051 		$notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
       
  1052 		$notify_message .= sprintf( __('Whois  : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n";
       
  1053 		$notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
       
  1054 		$notify_message .= __('You can see all comments on this post here: ') . "\r\n";
       
  1055 		/* translators: 1: blog name, 2: post title */
       
  1056 		$subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title );
       
  1057 	} elseif ('trackback' == $comment_type) {
       
  1058 		$notify_message  = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n";
       
  1059 		/* translators: 1: website name, 2: author IP, 3: author domain */
       
  1060 		$notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
       
  1061 		$notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
       
  1062 		$notify_message .= __('Excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
       
  1063 		$notify_message .= __('You can see all trackbacks on this post here: ') . "\r\n";
       
  1064 		/* translators: 1: blog name, 2: post title */
       
  1065 		$subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title );
       
  1066 	} elseif ('pingback' == $comment_type) {
       
  1067 		$notify_message  = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n";
       
  1068 		/* translators: 1: comment author, 2: author IP, 3: author domain */
       
  1069 		$notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
       
  1070 		$notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
       
  1071 		$notify_message .= __('Excerpt: ') . "\r\n" . sprintf('[...] %s [...]', $comment->comment_content ) . "\r\n\r\n";
       
  1072 		$notify_message .= __('You can see all pingbacks on this post here: ') . "\r\n";
       
  1073 		/* translators: 1: blog name, 2: post title */
       
  1074 		$subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title );
       
  1075 	}
       
  1076 	$notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
       
  1077 	$notify_message .= sprintf( __('Permalink: %s'), get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment_id ) . "\r\n";
       
  1078 
       
  1079 	if ( user_can( $post->post_author, 'edit_comment', $comment_id ) ) {
       
  1080 		if ( EMPTY_TRASH_DAYS )
       
  1081 			$notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
       
  1082 		else
       
  1083 			$notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
       
  1084 		$notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
       
  1085 	}
       
  1086 
       
  1087 	$wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
       
  1088 
       
  1089 	if ( '' == $comment->comment_author ) {
       
  1090 		$from = "From: \"$blogname\" <$wp_email>";
       
  1091 		if ( '' != $comment->comment_author_email )
       
  1092 			$reply_to = "Reply-To: $comment->comment_author_email";
       
  1093 	} else {
       
  1094 		$from = "From: \"$comment->comment_author\" <$wp_email>";
       
  1095 		if ( '' != $comment->comment_author_email )
       
  1096 			$reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>";
       
  1097 	}
       
  1098 
       
  1099 	$message_headers = "$from\n"
       
  1100 		. "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
       
  1101 
       
  1102 	if ( isset($reply_to) )
       
  1103 		$message_headers .= $reply_to . "\n";
       
  1104 
       
  1105 	$emails = array( $author->user_email );
       
  1106 
       
  1107 	$emails          = apply_filters( 'comment_notification_recipients', $emails,          $comment_id );
       
  1108 	$notify_message  = apply_filters( 'comment_notification_text',       $notify_message,  $comment_id );
       
  1109 	$subject         = apply_filters( 'comment_notification_subject',    $subject,         $comment_id );
       
  1110 	$message_headers = apply_filters( 'comment_notification_headers',    $message_headers, $comment_id );
       
  1111 
       
  1112 	foreach ( $emails as $email ) {
       
  1113 		@wp_mail( $email, $subject, $notify_message, $message_headers );
       
  1114 	}
       
  1115 
       
  1116 	return true;
       
  1117 }
       
  1118 endif;
       
  1119 
       
  1120 if ( !function_exists('wp_notify_moderator') ) :
       
  1121 /**
       
  1122  * Notifies the moderator of the blog about a new comment that is awaiting approval.
       
  1123  *
       
  1124  * @since 1.0
       
  1125  * @uses $wpdb
       
  1126  *
       
  1127  * @param int $comment_id Comment ID
       
  1128  * @return bool Always returns true
       
  1129  */
       
  1130 function wp_notify_moderator($comment_id) {
       
  1131 	global $wpdb;
       
  1132 
       
  1133 	if ( 0 == get_option( 'moderation_notify' ) )
       
  1134 		return true;
       
  1135 
       
  1136 	$comment = get_comment($comment_id);
       
  1137 	$post = get_post($comment->comment_post_ID);
       
  1138 	$user = get_userdata( $post->post_author );
       
  1139 	// Send to the administration and to the post author if the author can modify the comment.
       
  1140 	$emails = array( get_option('admin_email') );
       
  1141 	if ( user_can($user->ID, 'edit_comment', $comment_id) && !empty($user->user_email) && ( get_option('admin_email') != $user->user_email) )
       
  1142 		$emails[] = $user->user_email;
       
  1143 
       
  1144 	$comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
       
  1145 	$comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
       
  1146 
       
  1147 	// The blogname option is escaped with esc_html on the way into the database in sanitize_option
       
  1148 	// we want to reverse this for the plain text arena of emails.
       
  1149 	$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
       
  1150 
       
  1151 	switch ($comment->comment_type)
       
  1152 	{
       
  1153 		case 'trackback':
       
  1154 			$notify_message  = sprintf( __('A new trackback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
       
  1155 			$notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
       
  1156 			$notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
       
  1157 			$notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
       
  1158 			$notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
       
  1159 			break;
       
  1160 		case 'pingback':
       
  1161 			$notify_message  = sprintf( __('A new pingback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
       
  1162 			$notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
       
  1163 			$notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
       
  1164 			$notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
       
  1165 			$notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
       
  1166 			break;
       
  1167 		default: //Comments
       
  1168 			$notify_message  = sprintf( __('A new comment on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
       
  1169 			$notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
       
  1170 			$notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
       
  1171 			$notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
       
  1172 			$notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
       
  1173 			$notify_message .= sprintf( __('Whois  : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n";
       
  1174 			$notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
       
  1175 			break;
       
  1176 	}
       
  1177 
       
  1178 	$notify_message .= sprintf( __('Approve it: %s'),  admin_url("comment.php?action=approve&c=$comment_id") ) . "\r\n";
       
  1179 	if ( EMPTY_TRASH_DAYS )
       
  1180 		$notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
       
  1181 	else
       
  1182 		$notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
       
  1183 	$notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
       
  1184 
       
  1185 	$notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:',
       
  1186  		'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n";
       
  1187 	$notify_message .= admin_url("edit-comments.php?comment_status=moderated") . "\r\n";
       
  1188 
       
  1189 	$subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), $blogname, $post->post_title );
       
  1190 	$message_headers = '';
       
  1191 
       
  1192 	$emails          = apply_filters( 'comment_moderation_recipients', $emails,          $comment_id );
       
  1193 	$notify_message  = apply_filters( 'comment_moderation_text',       $notify_message,  $comment_id );
       
  1194 	$subject         = apply_filters( 'comment_moderation_subject',    $subject,         $comment_id );
       
  1195 	$message_headers = apply_filters( 'comment_moderation_headers',    $message_headers, $comment_id );
       
  1196 
       
  1197 	foreach ( $emails as $email ) {
       
  1198 		@wp_mail( $email, $subject, $notify_message, $message_headers );
       
  1199 	}
       
  1200 
       
  1201 	return true;
       
  1202 }
       
  1203 endif;
       
  1204 
       
  1205 if ( !function_exists('wp_password_change_notification') ) :
       
  1206 /**
       
  1207  * Notify the blog admin of a user changing password, normally via email.
       
  1208  *
       
  1209  * @since 2.7
       
  1210  *
       
  1211  * @param object $user User Object
       
  1212  */
       
  1213 function wp_password_change_notification(&$user) {
       
  1214 	// send a copy of password change notification to the admin
       
  1215 	// but check to see if it's the admin whose password we're changing, and skip this
       
  1216 	if ( $user->user_email != get_option('admin_email') ) {
       
  1217 		$message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n";
       
  1218 		// The blogname option is escaped with esc_html on the way into the database in sanitize_option
       
  1219 		// we want to reverse this for the plain text arena of emails.
       
  1220 		$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
       
  1221 		wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), $blogname), $message);
       
  1222 	}
       
  1223 }
       
  1224 endif;
       
  1225 
       
  1226 if ( !function_exists('wp_new_user_notification') ) :
       
  1227 /**
       
  1228  * Notify the blog admin of a new user, normally via email.
       
  1229  *
       
  1230  * @since 2.0
       
  1231  *
       
  1232  * @param int $user_id User ID
       
  1233  * @param string $plaintext_pass Optional. The user's plaintext password
       
  1234  */
       
  1235 function wp_new_user_notification($user_id, $plaintext_pass = '') {
       
  1236 	$user = get_userdata( $user_id );
       
  1237 
       
  1238 	// The blogname option is escaped with esc_html on the way into the database in sanitize_option
       
  1239 	// we want to reverse this for the plain text arena of emails.
       
  1240 	$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
       
  1241 
       
  1242 	$message  = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n";
       
  1243 	$message .= sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n";
       
  1244 	$message .= sprintf(__('E-mail: %s'), $user->user_email) . "\r\n";
       
  1245 
       
  1246 	@wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message);
       
  1247 
       
  1248 	if ( empty($plaintext_pass) )
       
  1249 		return;
       
  1250 
       
  1251 	$message  = sprintf(__('Username: %s'), $user->user_login) . "\r\n";
       
  1252 	$message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n";
       
  1253 	$message .= wp_login_url() . "\r\n";
       
  1254 
       
  1255 	wp_mail($user->user_email, sprintf(__('[%s] Your username and password'), $blogname), $message);
       
  1256 
       
  1257 }
       
  1258 endif;
       
  1259 
       
  1260 if ( !function_exists('wp_nonce_tick') ) :
       
  1261 /**
       
  1262  * Get the time-dependent variable for nonce creation.
       
  1263  *
       
  1264  * A nonce has a lifespan of two ticks. Nonces in their second tick may be
       
  1265  * updated, e.g. by autosave.
       
  1266  *
       
  1267  * @since 2.5
       
  1268  *
       
  1269  * @return int
       
  1270  */
       
  1271 function wp_nonce_tick() {
       
  1272 	$nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS );
       
  1273 
       
  1274 	return ceil(time() / ( $nonce_life / 2 ));
       
  1275 }
       
  1276 endif;
       
  1277 
       
  1278 if ( !function_exists('wp_verify_nonce') ) :
       
  1279 /**
       
  1280  * Verify that correct nonce was used with time limit.
       
  1281  *
       
  1282  * The user is given an amount of time to use the token, so therefore, since the
       
  1283  * UID and $action remain the same, the independent variable is the time.
       
  1284  *
       
  1285  * @since 2.0.3
       
  1286  *
       
  1287  * @param string $nonce Nonce that was used in the form to verify
       
  1288  * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
       
  1289  * @return bool Whether the nonce check passed or failed.
       
  1290  */
       
  1291 function wp_verify_nonce($nonce, $action = -1) {
       
  1292 	$user = wp_get_current_user();
       
  1293 	$uid = (int) $user->ID;
       
  1294 	if ( ! $uid )
       
  1295 		$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
       
  1296 
       
  1297 	$i = wp_nonce_tick();
       
  1298 
       
  1299 	// Nonce generated 0-12 hours ago
       
  1300 	if ( substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10) === $nonce )
       
  1301 		return 1;
       
  1302 	// Nonce generated 12-24 hours ago
       
  1303 	if ( substr(wp_hash(($i - 1) . $action . $uid, 'nonce'), -12, 10) === $nonce )
       
  1304 		return 2;
       
  1305 	// Invalid nonce
       
  1306 	return false;
       
  1307 }
       
  1308 endif;
       
  1309 
       
  1310 if ( !function_exists('wp_create_nonce') ) :
       
  1311 /**
       
  1312  * Creates a random, one time use token.
       
  1313  *
       
  1314  * @since 2.0.3
       
  1315  *
       
  1316  * @param string|int $action Scalar value to add context to the nonce.
       
  1317  * @return string The one use form token
       
  1318  */
       
  1319 function wp_create_nonce($action = -1) {
       
  1320 	$user = wp_get_current_user();
       
  1321 	$uid = (int) $user->ID;
       
  1322 	if ( ! $uid )
       
  1323 		$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
       
  1324 
       
  1325 	$i = wp_nonce_tick();
       
  1326 
       
  1327 	return substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10);
       
  1328 }
       
  1329 endif;
       
  1330 
       
  1331 if ( !function_exists('wp_salt') ) :
       
  1332 /**
       
  1333  * Get salt to add to hashes.
       
  1334  *
       
  1335  * Salts are created using secret keys. Secret keys are located in two places:
       
  1336  * in the database and in the wp-config.php file. The secret key in the database
       
  1337  * is randomly generated and will be appended to the secret keys in wp-config.php.
       
  1338  *
       
  1339  * The secret keys in wp-config.php should be updated to strong, random keys to maximize
       
  1340  * security. Below is an example of how the secret key constants are defined.
       
  1341  * Do not paste this example directly into wp-config.php. Instead, have a
       
  1342  * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just
       
  1343  * for you.
       
  1344  *
       
  1345  * <code>
       
  1346  * define('AUTH_KEY',         ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON');
       
  1347  * define('SECURE_AUTH_KEY',  'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~');
       
  1348  * define('LOGGED_IN_KEY',    '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM');
       
  1349  * define('NONCE_KEY',        '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|');
       
  1350  * define('AUTH_SALT',        'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW');
       
  1351  * define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n');
       
  1352  * define('LOGGED_IN_SALT',   '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm');
       
  1353  * define('NONCE_SALT',       'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT');
       
  1354  * </code>
       
  1355  *
       
  1356  * Salting passwords helps against tools which has stored hashed values of
       
  1357  * common dictionary strings. The added values makes it harder to crack.
       
  1358  *
       
  1359  * @since 2.5
       
  1360  *
       
  1361  * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php
       
  1362  *
       
  1363  * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
       
  1364  * @return string Salt value
       
  1365  */
       
  1366 function wp_salt( $scheme = 'auth' ) {
       
  1367 	static $cached_salts = array();
       
  1368 	if ( isset( $cached_salts[ $scheme ] ) )
       
  1369 		return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
       
  1370 
       
  1371 	static $duplicated_keys;
       
  1372 	if ( null === $duplicated_keys ) {
       
  1373 		$duplicated_keys = array( 'put your unique phrase here' => true );
       
  1374 		foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) {
       
  1375 			foreach ( array( 'KEY', 'SALT' ) as $second ) {
       
  1376 				if ( ! defined( "{$first}_{$second}" ) )
       
  1377 					continue;
       
  1378 				$value = constant( "{$first}_{$second}" );
       
  1379 				$duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] );
       
  1380 			}
       
  1381 		}
       
  1382 	}
       
  1383 
       
  1384 	$key = $salt = '';
       
  1385 	if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) )
       
  1386 		$key = SECRET_KEY;
       
  1387 	if ( 'auth' == $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) )
       
  1388 		$salt = SECRET_SALT;
       
  1389 
       
  1390 	if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ) ) ) {
       
  1391 		foreach ( array( 'key', 'salt' ) as $type ) {
       
  1392 			$const = strtoupper( "{$scheme}_{$type}" );
       
  1393 			if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) {
       
  1394 				$$type = constant( $const );
       
  1395 			} elseif ( ! $$type ) {
       
  1396 				$$type = get_site_option( "{$scheme}_{$type}" );
       
  1397 				if ( ! $$type ) {
       
  1398 					$$type = wp_generate_password( 64, true, true );
       
  1399 					update_site_option( "{$scheme}_{$type}", $$type );
       
  1400 				}
       
  1401 			}
       
  1402 		}
       
  1403 	} else {
       
  1404 		if ( ! $key ) {
       
  1405 			$key = get_site_option( 'secret_key' );
       
  1406 			if ( ! $key ) {
       
  1407 				$key = wp_generate_password( 64, true, true );
       
  1408 				update_site_option( 'secret_key', $key );
       
  1409 			}
       
  1410 		}
       
  1411 		$salt = hash_hmac( 'md5', $scheme, $key );
       
  1412 	}
       
  1413 
       
  1414 	$cached_salts[ $scheme ] = $key . $salt;
       
  1415 	return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
       
  1416 }
       
  1417 endif;
       
  1418 
       
  1419 if ( !function_exists('wp_hash') ) :
       
  1420 /**
       
  1421  * Get hash of given string.
       
  1422  *
       
  1423  * @since 2.0.3
       
  1424  * @uses wp_salt() Get WordPress salt
       
  1425  *
       
  1426  * @param string $data Plain text to hash
       
  1427  * @return string Hash of $data
       
  1428  */
       
  1429 function wp_hash($data, $scheme = 'auth') {
       
  1430 	$salt = wp_salt($scheme);
       
  1431 
       
  1432 	return hash_hmac('md5', $data, $salt);
       
  1433 }
       
  1434 endif;
       
  1435 
       
  1436 if ( !function_exists('wp_hash_password') ) :
       
  1437 /**
       
  1438  * Create a hash (encrypt) of a plain text password.
       
  1439  *
       
  1440  * For integration with other applications, this function can be overwritten to
       
  1441  * instead use the other package password checking algorithm.
       
  1442  *
       
  1443  * @since 2.5
       
  1444  * @global object $wp_hasher PHPass object
       
  1445  * @uses PasswordHash::HashPassword
       
  1446  *
       
  1447  * @param string $password Plain text user password to hash
       
  1448  * @return string The hash string of the password
       
  1449  */
       
  1450 function wp_hash_password($password) {
       
  1451 	global $wp_hasher;
       
  1452 
       
  1453 	if ( empty($wp_hasher) ) {
       
  1454 		require_once( ABSPATH . 'wp-includes/class-phpass.php');
       
  1455 		// By default, use the portable hash from phpass
       
  1456 		$wp_hasher = new PasswordHash(8, true);
       
  1457 	}
       
  1458 
       
  1459 	return $wp_hasher->HashPassword( trim( $password ) );
       
  1460 }
       
  1461 endif;
       
  1462 
       
  1463 if ( !function_exists('wp_check_password') ) :
       
  1464 /**
       
  1465  * Checks the plaintext password against the encrypted Password.
       
  1466  *
       
  1467  * Maintains compatibility between old version and the new cookie authentication
       
  1468  * protocol using PHPass library. The $hash parameter is the encrypted password
       
  1469  * and the function compares the plain text password when encrypted similarly
       
  1470  * against the already encrypted password to see if they match.
       
  1471  *
       
  1472  * For integration with other applications, this function can be overwritten to
       
  1473  * instead use the other package password checking algorithm.
       
  1474  *
       
  1475  * @since 2.5
       
  1476  * @global object $wp_hasher PHPass object used for checking the password
       
  1477  *	against the $hash + $password
       
  1478  * @uses PasswordHash::CheckPassword
       
  1479  *
       
  1480  * @param string $password Plaintext user's password
       
  1481  * @param string $hash Hash of the user's password to check against.
       
  1482  * @return bool False, if the $password does not match the hashed password
       
  1483  */
       
  1484 function wp_check_password($password, $hash, $user_id = '') {
       
  1485 	global $wp_hasher;
       
  1486 
       
  1487 	// If the hash is still md5...
       
  1488 	if ( strlen($hash) <= 32 ) {
       
  1489 		$check = ( $hash == md5($password) );
       
  1490 		if ( $check && $user_id ) {
       
  1491 			// Rehash using new hash.
       
  1492 			wp_set_password($password, $user_id);
       
  1493 			$hash = wp_hash_password($password);
       
  1494 		}
       
  1495 
       
  1496 		return apply_filters('check_password', $check, $password, $hash, $user_id);
       
  1497 	}
       
  1498 
       
  1499 	// If the stored hash is longer than an MD5, presume the
       
  1500 	// new style phpass portable hash.
       
  1501 	if ( empty($wp_hasher) ) {
       
  1502 		require_once( ABSPATH . 'wp-includes/class-phpass.php');
       
  1503 		// By default, use the portable hash from phpass
       
  1504 		$wp_hasher = new PasswordHash(8, true);
       
  1505 	}
       
  1506 
       
  1507 	$check = $wp_hasher->CheckPassword($password, $hash);
       
  1508 
       
  1509 	return apply_filters('check_password', $check, $password, $hash, $user_id);
       
  1510 }
       
  1511 endif;
       
  1512 
       
  1513 if ( !function_exists('wp_generate_password') ) :
       
  1514 /**
       
  1515  * Generates a random password drawn from the defined set of characters.
       
  1516  *
       
  1517  * @since 2.5
       
  1518  *
       
  1519  * @param int $length The length of password to generate
       
  1520  * @param bool $special_chars Whether to include standard special characters. Default true.
       
  1521  * @param bool $extra_special_chars Whether to include other special characters. Used when
       
  1522  *   generating secret keys and salts. Default false.
       
  1523  * @return string The random password
       
  1524  **/
       
  1525 function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
       
  1526 	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
       
  1527 	if ( $special_chars )
       
  1528 		$chars .= '!@#$%^&*()';
       
  1529 	if ( $extra_special_chars )
       
  1530 		$chars .= '-_ []{}<>~`+=,.;:/?|';
       
  1531 
       
  1532 	$password = '';
       
  1533 	for ( $i = 0; $i < $length; $i++ ) {
       
  1534 		$password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
       
  1535 	}
       
  1536 
       
  1537 	// random_password filter was previously in random_password function which was deprecated
       
  1538 	return apply_filters('random_password', $password);
       
  1539 }
       
  1540 endif;
       
  1541 
       
  1542 if ( !function_exists('wp_rand') ) :
       
  1543 /**
       
  1544  * Generates a random number
       
  1545  *
       
  1546  * @since 2.6.2
       
  1547  *
       
  1548  * @param int $min Lower limit for the generated number
       
  1549  * @param int $max Upper limit for the generated number
       
  1550  * @return int A random number between min and max
       
  1551  */
       
  1552 function wp_rand( $min = 0, $max = 0 ) {
       
  1553 	global $rnd_value;
       
  1554 
       
  1555 	// Reset $rnd_value after 14 uses
       
  1556 	// 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
       
  1557 	if ( strlen($rnd_value) < 8 ) {
       
  1558 		if ( defined( 'WP_SETUP_CONFIG' ) )
       
  1559 			static $seed = '';
       
  1560 		else
       
  1561 			$seed = get_transient('random_seed');
       
  1562 		$rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
       
  1563 		$rnd_value .= sha1($rnd_value);
       
  1564 		$rnd_value .= sha1($rnd_value . $seed);
       
  1565 		$seed = md5($seed . $rnd_value);
       
  1566 		if ( ! defined( 'WP_SETUP_CONFIG' ) )
       
  1567 			set_transient('random_seed', $seed);
       
  1568 	}
       
  1569 
       
  1570 	// Take the first 8 digits for our value
       
  1571 	$value = substr($rnd_value, 0, 8);
       
  1572 
       
  1573 	// Strip the first eight, leaving the remainder for the next call to wp_rand().
       
  1574 	$rnd_value = substr($rnd_value, 8);
       
  1575 
       
  1576 	$value = abs(hexdec($value));
       
  1577 
       
  1578 	// Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
       
  1579 	$max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff
       
  1580 
       
  1581 	// Reduce the value to be within the min - max range
       
  1582 	if ( $max != 0 )
       
  1583 		$value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 );
       
  1584 
       
  1585 	return abs(intval($value));
       
  1586 }
       
  1587 endif;
       
  1588 
       
  1589 if ( !function_exists('wp_set_password') ) :
       
  1590 /**
       
  1591  * Updates the user's password with a new encrypted one.
       
  1592  *
       
  1593  * For integration with other applications, this function can be overwritten to
       
  1594  * instead use the other package password checking algorithm.
       
  1595  *
       
  1596  * @since 2.5
       
  1597  * @uses $wpdb WordPress database object for queries
       
  1598  * @uses wp_hash_password() Used to encrypt the user's password before passing to the database
       
  1599  *
       
  1600  * @param string $password The plaintext new user password
       
  1601  * @param int $user_id User ID
       
  1602  */
       
  1603 function wp_set_password( $password, $user_id ) {
       
  1604 	global $wpdb;
       
  1605 
       
  1606 	$hash = wp_hash_password( $password );
       
  1607 	$wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) );
       
  1608 
       
  1609 	wp_cache_delete($user_id, 'users');
       
  1610 }
       
  1611 endif;
       
  1612 
       
  1613 if ( !function_exists( 'get_avatar' ) ) :
       
  1614 /**
       
  1615  * Retrieve the avatar for a user who provided a user ID or email address.
       
  1616  *
       
  1617  * @since 2.5
       
  1618  * @param int|string|object $id_or_email A user ID,  email address, or comment object
       
  1619  * @param int $size Size of the avatar image
       
  1620  * @param string $default URL to a default image to use if no avatar is available
       
  1621  * @param string $alt Alternative text to use in image tag. Defaults to blank
       
  1622  * @return string <img> tag for the user's avatar
       
  1623 */
       
  1624 function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
       
  1625 	if ( ! get_option('show_avatars') )
       
  1626 		return false;
       
  1627 
       
  1628 	if ( false === $alt)
       
  1629 		$safe_alt = '';
       
  1630 	else
       
  1631 		$safe_alt = esc_attr( $alt );
       
  1632 
       
  1633 	if ( !is_numeric($size) )
       
  1634 		$size = '96';
       
  1635 
       
  1636 	$email = '';
       
  1637 	if ( is_numeric($id_or_email) ) {
       
  1638 		$id = (int) $id_or_email;
       
  1639 		$user = get_userdata($id);
       
  1640 		if ( $user )
       
  1641 			$email = $user->user_email;
       
  1642 	} elseif ( is_object($id_or_email) ) {
       
  1643 		// No avatar for pingbacks or trackbacks
       
  1644 		$allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
       
  1645 		if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) )
       
  1646 			return false;
       
  1647 
       
  1648 		if ( !empty($id_or_email->user_id) ) {
       
  1649 			$id = (int) $id_or_email->user_id;
       
  1650 			$user = get_userdata($id);
       
  1651 			if ( $user)
       
  1652 				$email = $user->user_email;
       
  1653 		} elseif ( !empty($id_or_email->comment_author_email) ) {
       
  1654 			$email = $id_or_email->comment_author_email;
       
  1655 		}
       
  1656 	} else {
       
  1657 		$email = $id_or_email;
       
  1658 	}
       
  1659 
       
  1660 	if ( empty($default) ) {
       
  1661 		$avatar_default = get_option('avatar_default');
       
  1662 		if ( empty($avatar_default) )
       
  1663 			$default = 'mystery';
       
  1664 		else
       
  1665 			$default = $avatar_default;
       
  1666 	}
       
  1667 
       
  1668 	if ( !empty($email) )
       
  1669 		$email_hash = md5( strtolower( trim( $email ) ) );
       
  1670 
       
  1671 	if ( is_ssl() ) {
       
  1672 		$host = 'https://secure.gravatar.com';
       
  1673 	} else {
       
  1674 		if ( !empty($email) )
       
  1675 			$host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash[0] ) % 2 ) );
       
  1676 		else
       
  1677 			$host = 'http://0.gravatar.com';
       
  1678 	}
       
  1679 
       
  1680 	if ( 'mystery' == $default )
       
  1681 		$default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com')
       
  1682 	elseif ( 'blank' == $default )
       
  1683 		$default = $email ? 'blank' : includes_url( 'images/blank.gif' );
       
  1684 	elseif ( !empty($email) && 'gravatar_default' == $default )
       
  1685 		$default = '';
       
  1686 	elseif ( 'gravatar_default' == $default )
       
  1687 		$default = "$host/avatar/?s={$size}";
       
  1688 	elseif ( empty($email) )
       
  1689 		$default = "$host/avatar/?d=$default&amp;s={$size}";
       
  1690 	elseif ( strpos($default, 'http://') === 0 )
       
  1691 		$default = add_query_arg( 's', $size, $default );
       
  1692 
       
  1693 	if ( !empty($email) ) {
       
  1694 		$out = "$host/avatar/";
       
  1695 		$out .= $email_hash;
       
  1696 		$out .= '?s='.$size;
       
  1697 		$out .= '&amp;d=' . urlencode( $default );
       
  1698 
       
  1699 		$rating = get_option('avatar_rating');
       
  1700 		if ( !empty( $rating ) )
       
  1701 			$out .= "&amp;r={$rating}";
       
  1702 
       
  1703 		$out = str_replace( '&#038;', '&amp;', esc_url( $out ) );
       
  1704 		$avatar = "<img alt='{$safe_alt}' src='{$out}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
       
  1705 	} else {
       
  1706 		$avatar = "<img alt='{$safe_alt}' src='{$default}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />";
       
  1707 	}
       
  1708 
       
  1709 	return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt);
       
  1710 }
       
  1711 endif;
       
  1712 
       
  1713 if ( !function_exists( 'wp_text_diff' ) ) :
       
  1714 /**
       
  1715  * Displays a human readable HTML representation of the difference between two strings.
       
  1716  *
       
  1717  * The Diff is available for getting the changes between versions. The output is
       
  1718  * HTML, so the primary use is for displaying the changes. If the two strings
       
  1719  * are equivalent, then an empty string will be returned.
       
  1720  *
       
  1721  * The arguments supported and can be changed are listed below.
       
  1722  *
       
  1723  * 'title' : Default is an empty string. Titles the diff in a manner compatible
       
  1724  *		with the output.
       
  1725  * 'title_left' : Default is an empty string. Change the HTML to the left of the
       
  1726  *		title.
       
  1727  * 'title_right' : Default is an empty string. Change the HTML to the right of
       
  1728  *		the title.
       
  1729  *
       
  1730  * @since 2.6
       
  1731  * @see wp_parse_args() Used to change defaults to user defined settings.
       
  1732  * @uses Text_Diff
       
  1733  * @uses WP_Text_Diff_Renderer_Table
       
  1734  *
       
  1735  * @param string $left_string "old" (left) version of string
       
  1736  * @param string $right_string "new" (right) version of string
       
  1737  * @param string|array $args Optional. Change 'title', 'title_left', and 'title_right' defaults.
       
  1738  * @return string Empty string if strings are equivalent or HTML with differences.
       
  1739  */
       
  1740 function wp_text_diff( $left_string, $right_string, $args = null ) {
       
  1741 	$defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' );
       
  1742 	$args = wp_parse_args( $args, $defaults );
       
  1743 
       
  1744 	if ( !class_exists( 'WP_Text_Diff_Renderer_Table' ) )
       
  1745 		require( ABSPATH . WPINC . '/wp-diff.php' );
       
  1746 
       
  1747 	$left_string  = normalize_whitespace($left_string);
       
  1748 	$right_string = normalize_whitespace($right_string);
       
  1749 
       
  1750 	$left_lines  = explode("\n", $left_string);
       
  1751 	$right_lines = explode("\n", $right_string);
       
  1752 	$text_diff = new Text_Diff($left_lines, $right_lines);
       
  1753 	$renderer  = new WP_Text_Diff_Renderer_Table( $args );
       
  1754 	$diff = $renderer->render($text_diff);
       
  1755 
       
  1756 	if ( !$diff )
       
  1757 		return '';
       
  1758 
       
  1759 	$r  = "<table class='diff'>\n";
       
  1760 
       
  1761 	if ( ! empty( $args[ 'show_split_view' ] ) ) {
       
  1762 		$r .= "<col class='content diffsplit left' /><col class='content diffsplit middle' /><col class='content diffsplit right' />";
       
  1763 	} else {
       
  1764 		$r .= "<col class='content' />";
       
  1765 	}
       
  1766 
       
  1767 	if ( $args['title'] || $args['title_left'] || $args['title_right'] )
       
  1768 		$r .= "<thead>";
       
  1769 	if ( $args['title'] )
       
  1770 		$r .= "<tr class='diff-title'><th colspan='4'>$args[title]</th></tr>\n";
       
  1771 	if ( $args['title_left'] || $args['title_right'] ) {
       
  1772 		$r .= "<tr class='diff-sub-title'>\n";
       
  1773 		$r .= "\t<td></td><th>$args[title_left]</th>\n";
       
  1774 		$r .= "\t<td></td><th>$args[title_right]</th>\n";
       
  1775 		$r .= "</tr>\n";
       
  1776 	}
       
  1777 	if ( $args['title'] || $args['title_left'] || $args['title_right'] )
       
  1778 		$r .= "</thead>\n";
       
  1779 
       
  1780 	$r .= "<tbody>\n$diff\n</tbody>\n";
       
  1781 	$r .= "</table>";
       
  1782 
       
  1783 	return $r;
       
  1784 }
       
  1785 endif;
       
  1786