globalfunctions.php

来自「php 开发的内容管理系统」· PHP 代码 · 共 2,006 行 · 第 1/4 页

PHP
2,006
字号
	$wgMimeMagic= new MimeMagic();	return $wgMimeMagic;}/** * Tries to get the system directory for temporary files. * The TMPDIR, TMP, and TEMP environment variables are checked in sequence, * and if none are set /tmp is returned as the generic Unix default. * * NOTE: When possible, use the tempfile() function to create temporary * files to avoid race conditions on file creation, etc. * * @return string */function wfTempDir() {	foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {		$tmp = getenv( $var );		if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {			return $tmp;		}	}	# Hope this is Unix of some kind!	return '/tmp';}/** * Make directory, and make all parent directories if they don't exist */function wfMkdirParents( $fullDir, $mode = 0777 ) {	if ( strval( $fullDir ) === '' ) {		return true;	}		# Go back through the paths to find the first directory that exists	$currentDir = $fullDir;	$createList = array();	while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {			# Strip trailing slashes		$currentDir = rtrim( $currentDir, '/\\' );		# Add to create list		$createList[] = $currentDir;		# Find next delimiter searching from the end		$p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );		if ( $p === false ) {			$currentDir = false;		} else {			$currentDir = substr( $currentDir, 0, $p );		}	}		if ( count( $createList ) == 0 ) {		# Directory specified already exists		return true;	} elseif ( $currentDir === false ) {		# Went all the way back to root and it apparently doesn't exist		return false;	}		# Now go forward creating directories	$createList = array_reverse( $createList );	foreach ( $createList as $dir ) {		# use chmod to override the umask, as suggested by the PHP manual		if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {			return false;		} 	}	return true;}/** * Increment a statistics counter */ function wfIncrStats( $key ) {	 global $wgDBname, $wgMemc;	 $key = "$wgDBname:stats:$key";	 if ( is_null( $wgMemc->incr( $key ) ) ) {		 $wgMemc->add( $key, 1 );	 } }/** * @param mixed $nr The number to format * @param int $acc The number of digits after the decimal point, default 2 * @param bool $round Whether or not to round the value, default true * @return float */function wfPercent( $nr, $acc = 2, $round = true ) {	$ret = sprintf( "%.${acc}f", $nr );	return $round ? round( $ret, $acc ) . '%' : "$ret%";}/** * Encrypt a username/password. * * @param string $userid ID of the user * @param string $password Password of the user * @return string Hashed password */function wfEncryptPassword( $userid, $password ) {	global $wgPasswordSalt;	$p = md5( $password);	if($wgPasswordSalt)		return md5( "{$userid}-{$p}" );	else		return $p;}/** * Appends to second array if $value differs from that in $default */function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {	if ( is_null( $changed ) ) {		throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');	}	if ( $default[$key] !== $value ) {		$changed[$key] = $value;	}}/** * Since wfMsg() and co suck, they don't return false if the message key they * looked up didn't exist but a XHTML string, this function checks for the * nonexistance of messages by looking at wfMsg() output * * @param $msg      The message key looked up * @param $wfMsgOut The output of wfMsg*() * @return bool */function wfEmptyMsg( $msg, $wfMsgOut ) {	return $wfMsgOut === "&lt;$msg&gt;";}/** * Find out whether or not a mixed variable exists in a string * * @param mixed  needle * @param string haystack * @return bool */function in_string( $needle, $str ) {	return strpos( $str, $needle ) !== false;}function wfSpecialList( $page, $details ) {	global $wgContLang;	$details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";	return $page . $details;}/** * Returns a regular expression of url protocols * * @return string */function wfUrlProtocols() {	global $wgUrlProtocols;	// Support old-style $wgUrlProtocols strings, for backwards compatibility	// with LocalSettings files from 1.5	if ( is_array( $wgUrlProtocols ) ) {		$protocols = array();		foreach ($wgUrlProtocols as $protocol)			$protocols[] = preg_quote( $protocol, '/' );		return implode( '|', $protocols );	} else {		return $wgUrlProtocols;	}}/** * Execute a shell command, with time and memory limits mirrored from the PHP * configuration if supported. * @param $cmd Command line, properly escaped for shell. * @param &$retval optional, will receive the program's exit code. *                 (non-zero is usually failure) * @return collected stdout as a string (trailing newlines stripped) */function wfShellExec( $cmd, &$retval=null ) {	global $IP, $wgMaxShellMemory;		if( ini_get( 'safe_mode' ) ) {		wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );		$retval = 1;		return "Unable to run external programs in safe mode.";	}	if ( php_uname( 's' ) == 'Linux' ) {		$time = ini_get( 'max_execution_time' );		$mem = intval( $wgMaxShellMemory );		if ( $time > 0 && $mem > 0 ) {			$script = "$IP/bin/ulimit.sh";			if ( is_executable( $script ) ) {				$cmd = escapeshellarg( $script ) . " $time $mem $cmd";			}		}	} elseif ( php_uname( 's' ) == 'Windows NT' ) {		# This is a hack to work around PHP's flawed invocation of cmd.exe		# http://news.php.net/php.internals/21796		$cmd = '"' . $cmd . '"';	}	wfDebug( "wfShellExec: $cmd\n" );		$output = array();	$retval = 1; // error by default?	$lastline = exec( $cmd, $output, $retval );	return implode( "\n", $output );	}/** * This function works like "use VERSION" in Perl, the program will die with a * backtrace if the current version of PHP is less than the version provided * * This is useful for extensions which due to their nature are not kept in sync * with releases, and might depend on other versions of PHP than the main code * * Note: PHP might die due to parsing errors in some cases before it ever *       manages to call this function, such is life * * @see perldoc -f use * * @param mixed $version The version to check, can be a string, an integer, or *                       a float */function wfUsePHP( $req_ver ) {	$php_ver = PHP_VERSION;	if ( version_compare( $php_ver, (string)$req_ver, '<' ) )		 throw new MWException( "PHP $req_ver required--this is only $php_ver" );}/** * This function works like "use VERSION" in Perl except it checks the version * of MediaWiki, the program will die with a backtrace if the current version * of MediaWiki is less than the version provided. * * This is useful for extensions which due to their nature are not kept in sync * with releases * * @see perldoc -f use * * @param mixed $version The version to check, can be a string, an integer, or *                       a float */function wfUseMW( $req_ver ) {	global $wgVersion;	if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )		throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );}/** * Escape a string to make it suitable for inclusion in a preg_replace() * replacement parameter. * * @param string $string * @return string */function wfRegexReplacement( $string ) {	$string = str_replace( '\\', '\\\\', $string );	$string = str_replace( '$', '\\$', $string );	return $string;}/** * Return the final portion of a pathname. * Reimplemented because PHP5's basename() is buggy with multibyte text. * http://bugs.php.net/bug.php?id=33898 * * PHP's basename() only considers '\' a pathchar on Windows and Netware. * We'll consider it so always, as we don't want \s in our Unix paths either. *  * @param string $path * @return string */function wfBaseName( $path ) {	if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {		return $matches[1];	} else {		return '';	}}/** * Make a URL index, appropriate for the el_index field of externallinks. */function wfMakeUrlIndex( $url ) {	wfSuppressWarnings();	$bits = parse_url( $url );	wfRestoreWarnings();	if ( !$bits || $bits['scheme'] !== 'http' ) {		return false;	}	// Reverse the labels in the hostname, convert to lower case	$reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );	// Add an extra dot to the end	if ( substr( $reversedHost, -1, 1 ) !== '.' ) {		$reversedHost .= '.';	}	// Reconstruct the pseudo-URL	$index = "http://$reversedHost";	// Leave out user and password. Add the port, path, query and fragment	if ( isset( $bits['port'] ) )      $index .= ':' . $bits['port'];	if ( isset( $bits['path'] ) ) {		$index .= $bits['path'];	} else {		$index .= '/';	}	if ( isset( $bits['query'] ) )     $index .= '?' . $bits['query'];	if ( isset( $bits['fragment'] ) )  $index .= '#' . $bits['fragment'];	return $index;}/** * Do any deferred updates and clear the list * TODO: This could be in Wiki.php if that class made any sense at all */function wfDoUpdates(){	global $wgPostCommitUpdateList, $wgDeferredUpdateList;	foreach ( $wgDeferredUpdateList as $update ) {		$update->doUpdate();	}	foreach ( $wgPostCommitUpdateList as $update ) {		$update->doUpdate();	}	$wgDeferredUpdateList = array();	$wgPostCommitUpdateList = array();}/** * More or less "markup-safe" explode() * Ignores any instances of the separator inside <...> * @param string $separator * @param string $text * @return array */function wfExplodeMarkup( $separator, $text ) {	$placeholder = "\x00";		// Just in case...	$text = str_replace( $placeholder, '', $text );		// Trim stuff	$replacer = new ReplacerCallback( $separator, $placeholder );	$cleaned = preg_replace_callback( '/(<.*?>)/', array( $replacer, 'go' ), $text );		$items = explode( $separator, $cleaned );	foreach( $items as $i => $str ) {		$items[$i] = str_replace( $placeholder, $separator, $str );	}		return $items;}class ReplacerCallback {	function ReplacerCallback( $from, $to ) {		$this->from = $from;		$this->to = $to;	}		function go( $matches ) {		return str_replace( $this->from, $this->to, $matches[1] );	}}/** * Convert an arbitrarily-long digit string from one numeric base * to another, optionally zero-padding to a minimum column width. * * Supports base 2 through 36; digit values 10-36 are represented * as lowercase letters a-z. Input is case-insensitive. * * @param $input string of digits * @param $sourceBase int 2-36 * @param $destBase int 2-36 * @param $pad int 1 or greater * @return string or false on invalid input */function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {	if( $sourceBase < 2 ||		$sourceBase > 36 ||		$destBase < 2 ||		$destBase > 36 ||		$pad < 1 ||		$sourceBase != intval( $sourceBase ) ||		$destBase != intval( $destBase ) ||		$pad != intval( $pad ) ||		!is_string( $input ) ||		$input == '' ) {		return false;	}		$digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';	$inDigits = array();	$outChars = '';		// Decode and validate input string	$input = strtolower( $input );	for( $i = 0; $i < strlen( $input ); $i++ ) {		$n = strpos( $digitChars, $input{$i} );		if( $n === false || $n > $sourceBase ) {			return false;		}		$inDigits[] = $n;	}		// Iterate over the input, modulo-ing out an output digit	// at a time until input is gone.	while( count( $inDigits ) ) {		$work = 0;		$workDigits = array();				// Long division...		foreach( $inDigits as $digit ) {			$work *= $sourceBase;			$work += $digit;						if( $work < $destBase ) {				// Gonna need to pull another digit.				if( count( $workDigits ) ) {					// Avoid zero-padding; this lets us find					// the end of the input very easily when					// length drops to zero.					$workDigits[] = 0;				}			} else {				// Finally! Actual division!				$workDigits[] = intval( $work / $destBase );								// Isn't it annoying that most programming languages				// don't have a single divide-and-remainder operator,				// even though the CPU implements it that way?				$work = $work % $destBase;			}		}				// All that division leaves us with a remainder,		// which is conveniently our next output digit.		$outChars .= $digitChars[$work];				// And we continue!		$inDigits = $workDigits;	}		while( strlen( $outChars ) < $pad ) {		$outChars .= '0';	}		return strrev( $outChars );}/** * Create an object with a given name and an array of construct parameters * @param string $name * @param array $p parameters */function wfCreateObject( $name, $p ){	$p = array_values( $p );	switch ( count( $p ) ) {		case 0:			return new $name;		case 1:			return new $name( $p[0] );		case 2:			return new $name( $p[0], $p[1] );		case 3:			return new $name( $p[0], $p[1], $p[2] );		case 4:			return new $name( $p[0], $p[1], $p[2], $p[3] );		case 5:			return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );		case 6:			return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );		default:			throw new MWException( "Too many arguments to construtor in wfCreateObject" );	}}/** * Aliases for modularized functions */function wfGetHTTP( $url, $timeout = 'default' ) { 	return Http::get( $url, $timeout ); }function wfIsLocalURL( $url ) { 	return Http::isLocalURL( $url ); }?>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?