*/
function useMessageCache() {
global $wgLang;
+
foreach ( $this->getTrace() as $frame ) {
if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
return false;
}
}
+
return is_object( $wgLang );
}
*/
function runHooks( $name, $args = array() ) {
global $wgExceptionHooks;
- if( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) )
+
+ if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
return; // Just silently ignore
- if( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) )
+ }
+
+ if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) ) {
return;
+ }
+
$hooks = $wgExceptionHooks[ $name ];
$callargs = array_merge( array( $this ), $args );
- foreach( $hooks as $hook ) {
- if( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { //'function' or array( 'class', hook' )
+ foreach ( $hooks as $hook ) {
+ if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
$result = call_user_func_array( $hook, $callargs );
} else {
$result = null;
}
- if( is_string( $result ) )
+
+ if ( is_string( $result ) )
return $result;
}
}
*/
function msg( $key, $fallback /*[, params...] */ ) {
$args = array_slice( func_get_args(), 2 );
+
if ( $this->useMessageCache() ) {
return wfMsgReal( $key, $args );
} else {
*/
function getHTML() {
global $wgShowExceptionDetails;
- if( $wgShowExceptionDetails ) {
+
+ if ( $wgShowExceptionDetails ) {
return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
'</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
"</p>\n";
*/
function getText() {
global $wgShowExceptionDetails;
- if( $wgShowExceptionDetails ) {
+
+ if ( $wgShowExceptionDetails ) {
return $this->getMessage() .
"\nBacktrace:\n" . $this->getTraceAsString() . "\n";
} else {
return wfMsg( 'internalerror' );
} else {
global $wgSitename;
+
return "$wgSitename error";
}
}
*/
function getLogMessage() {
global $wgRequest;
+
$file = $this->getFile();
$line = $this->getLine();
$message = $this->getMessage();
+
if ( isset( $wgRequest ) ) {
$url = $wgRequest->getRequestURL();
if ( !$url ) {
/** Output the exception report using HTML */
function reportHTML() {
global $wgOut;
+
if ( $this->useOutputPage() ) {
$wgOut->setPageTitle( $this->getPageTitle() );
$wgOut->setRobotPolicy( "noindex,nofollow" );
$wgOut->enableClientCache( false );
$wgOut->redirect( '' );
$wgOut->clearHTML();
- if( $hookResult = $this->runHooks( get_class( $this ) ) ) {
+
+ if ( $hookResult = $this->runHooks( get_class( $this ) ) ) {
$wgOut->addHTML( $hookResult );
} else {
$wgOut->addHTML( $this->getHTML() );
}
+
$wgOut->output();
} else {
- if( $hookResult = $this->runHooks( get_class( $this ) . "Raw" ) ) {
+ if ( $hookResult = $this->runHooks( get_class( $this ) . "Raw" ) ) {
die( $hookResult );
}
+
if ( defined( 'MEDIAWIKI_INSTALL' ) || $this->htmlBodyOnly() ) {
echo $this->getHTML();
} else {
*/
function report() {
$log = $this->getLogMessage();
+
if ( $log ) {
wfDebugLog( 'exception', $log );
}
+
if ( self::isCommandLine() ) {
wfPrintError( $this->getText() );
} else {
if ( !headers_sent() ) {
header( 'HTTP/1.0 500 Internal Server Error' );
- header( 'Content-type: text/html; charset='.$wgOutputEncoding );
+ header( 'Content-type: text/html; charset=' . $wgOutputEncoding );
/* Don't cache error pages! They cause no end of trouble... */
header( 'Cache-control: none' );
header( 'Pragma: nocache' );
}
+
$title = $this->getPageTitle();
return "<html>
<head>
function report() {
global $wgOut;
+
$wgOut->showErrorPage( $this->title, $this->msg );
$wgOut->output();
}
global $wgShowExceptionDetails;
$cmdLine = MWException::isCommandLine();
+
if ( $e instanceof MWException ) {
try {
$e->report();
// Show a simpler error message for the original exception,
// don't try to invoke report()
$message = "MediaWiki internal error.\n\n";
+
if ( $wgShowExceptionDetails ) {
$message .= 'Original exception: ' . $e->__toString() . "\n\n" .
'Exception caught inside exception handler: ' . $e2->__toString();
"Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
"to show detailed debugging information.";
}
+
$message .= "\n";
+
if ( $cmdLine ) {
wfPrintError( $message );
} else {
- echo nl2br( htmlspecialchars( $message ) ). "\n";
+ echo nl2br( htmlspecialchars( $message ) ) . "\n";
}
}
} else {
$message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
$e->__toString() . "\n";
+
if ( $wgShowExceptionDetails ) {
- $message .= "\n" . $e->getTraceAsString() ."\n";
+ $message .= "\n" . $e->getTraceAsString() . "\n";
}
+
if ( $cmdLine ) {
wfPrintError( $message );
} else {
- echo nl2br( htmlspecialchars( $message ) ). "\n";
+ echo nl2br( htmlspecialchars( $message ) ) . "\n";
}
}
}
* Use this in command line mode only (see isCommandLine)
*/
function wfPrintError( $message ) {
- #NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
+ # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
# Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
if ( defined( 'STDERR' ) ) {
fwrite( STDERR, $message );
*/
function wfExceptionHandler( $e ) {
global $wgFullyInitialised;
+
wfReportException( $e );
// Final cleanup, similar to wfErrorExit()
$url = wfExpandUrl( $url );
wfDebug( "HTTP: $method: $url\n" );
$options['method'] = strtoupper( $method );
+
if ( !isset( $options['timeout'] ) ) {
$options['timeout'] = 'default';
}
+
$req = HttpRequest::factory( $url, $options );
$status = $req->execute();
+
if ( $status->isOK() ) {
return $req->getContent();
} else {
*/
public static function isLocalURL( $url ) {
global $wgCommandLineMode, $wgConf;
+
if ( $wgCommandLineMode ) {
return false;
}
$domainParts = explode( '.', $host );
// Check if this domain or any superdomain is listed in $wgConf as a local virtual host
$domainParts = array_reverse( $domainParts );
+
for ( $i = 0; $i < count( $domainParts ); $i++ ) {
$domainPart = $domainParts[$i];
if ( $i == 0 ) {
} else {
$domain = $domainPart . '.' . $domain;
}
+
if ( $wgConf->isLocalVHost( $domain ) ) {
return true;
}
}
}
+
return false;
}
$this->parsedUrl = parse_url( $url );
if ( !Http::isValidURI( $this->url ) ) {
- $this->status = Status::newFatal('http-invalid-url');
+ $this->status = Status::newFatal( 'http-invalid-url' );
} else {
$this->status = Status::newGood( 100 ); // continue
}
- if ( isset($options['timeout']) && $options['timeout'] != 'default' ) {
+ if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
$this->timeout = $options['timeout'];
} else {
$this->timeout = $wgHTTPTimeout;
$members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
"method", "followRedirects", "maxRedirects", "sslVerifyCert" );
+
foreach ( $members as $o ) {
- if ( isset($options[$o]) ) {
+ if ( isset( $options[$o] ) ) {
$this->$o = $options[$o];
}
}
if ( !Http::$httpEngine ) {
Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
} elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
- throw new MWException( __METHOD__.': curl (http://php.net/curl) is not installed, but'.
+ throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
' Http::$httpEngine is set to "curl"' );
}
switch( Http::$httpEngine ) {
- case 'curl':
- return new CurlHttpRequest( $url, $options );
- case 'php':
- if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
- throw new MWException( __METHOD__.': allow_url_fopen needs to be enabled for pure PHP'.
- ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
- }
- return new PhpHttpRequest( $url, $options );
- default:
- throw new MWException( __METHOD__.': The setting of Http::$httpEngine is not valid.' );
+ case 'curl':
+ return new CurlHttpRequest( $url, $options );
+ case 'php':
+ if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
+ throw new MWException( __METHOD__ . ': allow_url_fopen needs to be enabled for pure PHP' .
+ ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
+ }
+ return new PhpHttpRequest( $url, $options );
+ default:
+ throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
}
}
* @param $args Array
* @todo overload the args param
*/
- public function setData($args) {
+ public function setData( $args ) {
$this->postData = $args;
}
if ( $this->proxy ) {
return;
}
+
if ( Http::isLocalURL( $this->url ) ) {
$this->proxy = 'http://localhost:80/';
} elseif ( $wgHTTPProxy ) {
* Set the refererer header
*/
public function setReferer( $url ) {
- $this->setHeader('Referer', $url);
+ $this->setHeader( 'Referer', $url );
}
/**
* Set the user agent
*/
public function setUserAgent( $UA ) {
- $this->setHeader('User-Agent', $UA);
+ $this->setHeader( 'User-Agent', $UA );
}
/**
* Set an arbitrary header
*/
- public function setHeader($name, $value) {
+ public function setHeader( $name, $value ) {
// I feel like I should normalize the case here...
$this->reqHeaders[$name] = $value;
}
public function getHeaderList() {
$list = array();
- if( $this->cookieJar ) {
+ if ( $this->cookieJar ) {
$this->reqHeaders['Cookie'] =
- $this->cookieJar->serializeToHttpRequest($this->parsedUrl['path'],
- $this->parsedUrl['host']);
+ $this->cookieJar->serializeToHttpRequest(
+ $this->parsedUrl['path'],
+ $this->parsedUrl['host']
+ );
}
- foreach($this->reqHeaders as $name => $value) {
+
+ foreach ( $this->reqHeaders as $name => $value ) {
$list[] = "$name: $value";
}
+
return $list;
}
$this->content = "";
- if( strtoupper($this->method) == "HEAD" ) {
+ if ( strtoupper( $this->method ) == "HEAD" ) {
$this->headersOnly = true;
}
$this->postData = wfArrayToCGI( $this->postData );
}
- if ( is_object( $wgTitle ) && !isset($this->reqHeaders['Referer']) ) {
+ if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
$this->setReferer( $wgTitle->getFullURL() );
}
$this->setCallback( array( $this, 'read' ) );
}
- if ( !isset($this->reqHeaders['User-Agent']) ) {
- $this->setUserAgent(Http::userAgent());
+ if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
+ $this->setUserAgent( Http::userAgent() );
}
}
*/
protected function parseHeader() {
$lastname = "";
- foreach( $this->headerList as $header ) {
- if( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
+
+ foreach ( $this->headerList as $header ) {
+ if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
$this->respVersion = $match[1];
$this->respStatus = $match[2];
- } elseif( preg_match( "#^[ \t]#", $header ) ) {
- $last = count($this->respHeaders[$lastname]) - 1;
+ } elseif ( preg_match( "#^[ \t]#", $header ) ) {
+ $last = count( $this->respHeaders[$lastname] ) - 1;
$this->respHeaders[$lastname][$last] .= "\r\n$header";
- } elseif( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
+ } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
$this->respHeaders[strtolower( $match[1] )][] = $match[2];
$lastname = strtolower( $match[1] );
}
* @return nothing
*/
protected function setStatus() {
- if( !$this->respHeaders ) {
+ if ( !$this->respHeaders ) {
$this->parseHeader();
}
- if((int)$this->respStatus !== 200) {
- list( $code, $message ) = explode(" ", $this->respStatus, 2);
- $this->status->fatal("http-bad-status", $code, $message );
+ if ( (int)$this->respStatus !== 200 ) {
+ list( $code, $message ) = explode( " ", $this->respStatus, 2 );
+ $this->status->fatal( "http-bad-status", $code, $message );
}
}
* @return Boolean
*/
public function isRedirect() {
- if( !$this->respHeaders ) {
+ if ( !$this->respHeaders ) {
$this->parseHeader();
}
$status = (int)$this->respStatus;
+
if ( $status >= 300 && $status <= 303 ) {
return true;
}
+
return false;
}
* @return Array
*/
public function getResponseHeaders() {
- if( !$this->respHeaders ) {
+ if ( !$this->respHeaders ) {
$this->parseHeader();
}
+
return $this->respHeaders;
}
* @param $header String
* @return String
*/
- public function getResponseHeader($header) {
- if( !$this->respHeaders ) {
+ public function getResponseHeader( $header ) {
+ if ( !$this->respHeaders ) {
$this->parseHeader();
}
+
if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
$v = $this->respHeaders[strtolower ( $header ) ];
return $v[count( $v ) - 1];
}
+
return null;
}
* @returns CookieJar
*/
public function getCookieJar() {
- if( !$this->respHeaders ) {
+ if ( !$this->respHeaders ) {
$this->parseHeader();
}
+
return $this->cookieJar;
}
* Set-Cookie headers.
* @see Cookie::set
*/
- public function setCookie( $name, $value = null, $attr = null) {
- if( !$this->cookieJar ) {
+ public function setCookie( $name, $value = null, $attr = null ) {
+ if ( !$this->cookieJar ) {
$this->cookieJar = new CookieJar;
}
- $this->cookieJar->setCookie($name, $value, $attr);
+
+ $this->cookieJar->setCookie( $name, $value, $attr );
}
/**
* Parse the cookies in the response headers and store them in the cookie jar.
*/
protected function parseCookies() {
- if( !$this->cookieJar ) {
+ if ( !$this->cookieJar ) {
$this->cookieJar = new CookieJar;
}
- if( isset( $this->respHeaders['set-cookie'] ) ) {
+
+ if ( isset( $this->respHeaders['set-cookie'] ) ) {
$url = parse_url( $this->getFinalUrl() );
- foreach( $this->respHeaders['set-cookie'] as $cookie ) {
+ foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
$this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
}
}
* @return String
*/
public function getFinalUrl() {
- $location = $this->getResponseHeader("Location");
+ $location = $this->getResponseHeader( "Location" );
+
if ( $location ) {
return $location;
}
*/
public function set( $value, $attr ) {
$this->value = $value;
- if( isset( $attr['expires'] ) ) {
+
+ if ( isset( $attr['expires'] ) ) {
$this->isSessionKey = false;
$this->expires = strtotime( $attr['expires'] );
}
- if( isset( $attr['path'] ) ) {
+
+ if ( isset( $attr['path'] ) ) {
$this->path = $attr['path'];
} else {
$this->path = "/";
}
- if( isset( $attr['domain'] ) ) {
- if( self::validateCookieDomain( $attr['domain'] ) ) {
+
+ if ( isset( $attr['domain'] ) ) {
+ if ( self::validateCookieDomain( $attr['domain'] ) ) {
$this->domain = $attr['domain'];
}
} else {
- throw new MWException("You must specify a domain.");
+ throw new MWException( "You must specify a domain." );
}
}
* @param $originDomain String: (optional) the domain the cookie originates from
* @return Boolean
*/
- public static function validateCookieDomain( $domain, $originDomain = null) {
+ public static function validateCookieDomain( $domain, $originDomain = null ) {
// Don't allow a trailing dot
- if( substr( $domain, -1 ) == "." ) return false;
+ if ( substr( $domain, -1 ) == "." ) {
+ return false;
+ }
- $dc = explode(".", $domain);
+ $dc = explode( ".", $domain );
// Only allow full, valid IP addresses
- if( preg_match( '/^[0-9.]+$/', $domain ) ) {
- if( count( $dc ) != 4 ) return false;
+ if ( preg_match( '/^[0-9.]+$/', $domain ) ) {
+ if ( count( $dc ) != 4 ) {
+ return false;
+ }
- if( ip2long( $domain ) === false ) return false;
+ if ( ip2long( $domain ) === false ) {
+ return false;
+ }
- if( $originDomain == null || $originDomain == $domain ) return true;
+ if ( $originDomain == null || $originDomain == $domain ) {
+ return true;
+ }
}
// Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
- if( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
- if( (count($dc) == 2 && strlen( $dc[0] ) <= 2 )
- || (count($dc) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
+ if ( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
+ if ( ( count( $dc ) == 2 && strlen( $dc[0] ) <= 2 )
+ || ( count( $dc ) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
return false;
}
- if( (count($dc) == 2 || (count($dc) == 3 && $dc[0] == "") )
- && preg_match( '/(com|net|org|gov|edu)\...$/', $domain) ) {
+ if ( ( count( $dc ) == 2 || ( count( $dc ) == 3 && $dc[0] == "" ) )
+ && preg_match( '/(com|net|org|gov|edu)\...$/', $domain ) ) {
return false;
}
}
- if( $originDomain != null ) {
- if( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
+ if ( $originDomain != null ) {
+ if ( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
return false;
}
- if( substr( $domain, 0, 1 ) == "."
+
+ if ( substr( $domain, 0, 1 ) == "."
&& substr_compare( $originDomain, $domain, -strlen( $domain ),
strlen( $domain ), TRUE ) != 0 ) {
return false;
public function serializeToHttpRequest( $path, $domain ) {
$ret = "";
- if( $this->canServeDomain( $domain )
+ if ( $this->canServeDomain( $domain )
&& $this->canServePath( $path )
&& $this->isUnExpired() ) {
- $ret = $this->name ."=". $this->value;
+ $ret = $this->name . "=" . $this->value;
}
return $ret;
}
protected function canServeDomain( $domain ) {
- if( $domain == $this->domain
- || ( strlen( $domain) > strlen( $this->domain )
- && substr( $this->domain, 0, 1) == "."
+ if ( $domain == $this->domain
+ || ( strlen( $domain ) > strlen( $this->domain )
+ && substr( $this->domain, 0, 1 ) == "."
&& substr_compare( $domain, $this->domain, -strlen( $this->domain ),
strlen( $this->domain ), TRUE ) == 0 ) ) {
return true;
}
+
return false;
}
protected function canServePath( $path ) {
- if( $this->path && substr_compare( $this->path, $path, 0, strlen( $this->path ) ) == 0 ) {
+ if ( $this->path && substr_compare( $this->path, $path, 0, strlen( $this->path ) ) == 0 ) {
return true;
}
+
return false;
}
protected function isUnExpired() {
- if( $this->isSessionKey || $this->expires > time() ) {
+ if ( $this->isSessionKey || $this->expires > time() ) {
return true;
}
+
return false;
}
-
}
class CookieJar {
* Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
* @see Cookie::set()
*/
- public function setCookie ($name, $value, $attr) {
+ public function setCookie ( $name, $value, $attr ) {
/* cookies: case insensitive, so this should work.
* We'll still send the cookies back in the same case we got them, though.
*/
- $index = strtoupper($name);
- if( isset( $this->cookie[$index] ) ) {
+ $index = strtoupper( $name );
+
+ if ( isset( $this->cookie[$index] ) ) {
$this->cookie[$index]->set( $value, $attr );
} else {
$this->cookie[$index] = new Cookie( $name, $value, $attr );
public function serializeToHttpRequest( $path, $domain ) {
$cookies = array();
- foreach( $this->cookie as $c ) {
+ foreach ( $this->cookie as $c ) {
$serialized = $c->serializeToHttpRequest( $path, $domain );
- if ( $serialized ) $cookies[] = $serialized;
+
+ if ( $serialized ) {
+ $cookies[] = $serialized;
+ }
}
- return implode("; ", $cookies);
+ return implode( "; ", $cookies );
}
/**
*/
public function parseCookieResponseHeader ( $cookie, $domain ) {
$len = strlen( "Set-Cookie:" );
+
if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
$cookie = substr( $cookie, $len );
}
$bit = array_map( 'trim', explode( ";", $cookie ) );
- if ( count($bit) >= 1 ) {
- list($name, $value) = explode( "=", array_shift( $bit ), 2 );
+
+ if ( count( $bit ) >= 1 ) {
+ list( $name, $value ) = explode( "=", array_shift( $bit ), 2 );
$attr = array();
- foreach( $bit as $piece ) {
+
+ foreach ( $bit as $piece ) {
$parts = explode( "=", $piece );
- if( count( $parts ) > 1 ) {
+ if ( count( $parts ) > 1 ) {
$attr[strtolower( $parts[0] )] = $parts[1];
} else {
$attr[strtolower( $parts[0] )] = true;
}
}
- if( !isset( $attr['domain'] ) ) {
+ if ( !isset( $attr['domain'] ) ) {
$attr['domain'] = $domain;
} elseif ( !Cookie::validateCookieDomain( $attr['domain'], $domain ) ) {
return null;
}
+
$this->setCookie( $name, $value, $attr );
}
}
}
-
/**
* HttpRequest implemented using internal curl compiled into PHP
*/
public function execute() {
parent::execute();
+
if ( !$this->status->isOK() ) {
return $this->status;
}
+
$this->curlOptions[CURLOPT_PROXY] = $this->proxy;
$this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
$this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
$this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
- $this->curlOptions[CURLOPT_HEADERFUNCTION] = array($this, "readHeader");
+ $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
$this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
$this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
/* not sure these two are actually necessary */
- if(isset($this->reqHeaders['Referer'])) {
+ if ( isset( $this->reqHeaders['Referer'] ) ) {
$this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
}
$this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
$this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
$curlHandle = curl_init( $this->url );
+
if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
- throw new MWException("Error setting curl options.");
+ throw new MWException( "Error setting curl options." );
}
+
if ( $this->followRedirects && $this->canFollowRedirects() ) {
if ( ! @curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
- wfDebug( __METHOD__.": Couldn't set CURLOPT_FOLLOWLOCATION. " .
- "Probably safe_mode or open_basedir is set.\n");
+ wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
+ "Probably safe_mode or open_basedir is set.\n" );
// Continue the processing. If it were in curl_setopt_array,
// processing would have halted on its entry
}
$this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
}
} else {
- $this->headerList = explode("\r\n", $this->headerText);
+ $this->headerList = explode( "\r\n", $this->headerText );
}
curl_close( $curlHandle );
$this->parseHeader();
$this->setStatus();
+
return $this->status;
}
wfDebug( "Cannot follow redirects in safe mode\n" );
return false;
}
+
if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
return false;
}
+
return true;
}
}
}
$options['method'] = $this->method;
- $options['header'] = implode("\r\n", $this->getHeaderList());
+ $options['header'] = implode( "\r\n", $this->getHeaderList() );
// Note that at some future point we may want to support
// HTTP/1.1, but we'd have to write support for chunking
// in version of PHP < 5.3.1
$oldTimeout = false;
if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
- $oldTimeout = ini_set('default_socket_timeout', $this->timeout);
+ $oldTimeout = ini_set( 'default_socket_timeout', $this->timeout );
} else {
$options['timeout'] = $this->timeout;
}
$this->headerList = array();
$reqCount = 0;
$url = $this->url;
+
do {
$reqCount++;
wfSuppressWarnings();
$fh = fopen( $url, "r", false, $context );
wfRestoreWarnings();
+
if ( !$fh ) {
break;
}
+
$result = stream_get_meta_data( $fh );
$this->headerList = $result['wrapper_data'];
$this->parseHeader();
+
if ( !$manuallyRedirect || !$this->followRedirects ) {
break;
}
break;
}
# Check security of URL
- $url = $this->getResponseHeader("Location");
+ $url = $this->getResponseHeader( "Location" );
+
if ( substr( $url, 0, 7 ) !== 'http://' ) {
- wfDebug( __METHOD__.": insecure redirection\n" );
+ wfDebug( __METHOD__ . ": insecure redirection\n" );
break;
}
} while ( true );
if ( $oldTimeout !== false ) {
- ini_set('default_socket_timeout', $oldTimeout);
+ ini_set( 'default_socket_timeout', $oldTimeout );
}
+
$this->setStatus();
if ( $fh === false ) {
return $this->status;
}
- if($this->status->isOK()) {
+ if ( $this->status->isOK() ) {
while ( !feof( $fh ) ) {
$buf = fread( $fh, 8192 );
+
if ( $buf === false ) {
$this->status->fatal( 'http-read-error' );
break;
}
+
if ( strlen( $buf ) ) {
call_user_func( $this->callback, $fh, $buf );
}
static function getSkinNames() {
global $wgValidSkinNames;
static $skinsInitialised = false;
+
if ( !$skinsInitialised ) {
# Get a list of available skins
# Build using the regular expression '^(.*).php$'
# Array keys are all lower case, array value keep the case used by filename
#
wfProfileIn( __METHOD__ . '-init' );
+
global $wgStyleDirectory;
+
$skinDir = dir( $wgStyleDirectory );
# while code from www.php.net
- while( false !== ( $file = $skinDir->read() ) ) {
+ while ( false !== ( $file = $skinDir->read() ) ) {
// Skip non-PHP files, hidden files, and '.dep' includes
$matches = array();
- if( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
+
+ if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
$aSkin = $matches[1];
$wgValidSkinNames[strtolower( $aSkin )] = $aSkin;
}
*/
public static function getUsableSkins() {
global $wgSkipSkins;
+
$usableSkins = self::getSkinNames();
+
foreach ( $wgSkipSkins as $skip ) {
unset( $usableSkins[$skip] );
}
+
return $usableSkins;
}
*/
static function normalizeKey( $key ) {
global $wgDefaultSkin;
+
$skinNames = Skin::getSkinNames();
- if( $key == '' ) {
+ if ( $key == '' ) {
// Don't return the default immediately;
// in a misconfiguration we need to fall back.
$key = $wgDefaultSkin;
}
- if( isset( $skinNames[$key] ) ) {
+ if ( isset( $skinNames[$key] ) ) {
return $key;
}
2 => 'cologneblue'
);
- if( isset( $fallback[$key] ) ) {
+ if ( isset( $fallback[$key] ) ) {
$key = $fallback[$key];
}
- if( isset( $skinNames[$key] ) ) {
+ if ( isset( $skinNames[$key] ) ) {
return $key;
- } else if( isset( $skinNames[$wgDefaultSkin] ) ) {
+ } else if ( isset( $skinNames[$wgDefaultSkin] ) ) {
return $wgDefaultSkin;
} else {
return 'vector';
if ( !class_exists( $className ) ) {
// Preload base classes to work around APC/PHP5 bug
$deps = "{$wgStyleDirectory}/{$skinName}.deps.php";
- if( file_exists( $deps ) ) {
+
+ if ( file_exists( $deps ) ) {
include_once( $deps );
}
require_once( "{$wgStyleDirectory}/{$skinName}.php" );
# Check if we got if not failback to default skin
- if( !class_exists( $className ) ) {
+ if ( !class_exists( $className ) ) {
# DO NOT die if the class isn't found. This breaks maintenance
# scripts and can cause a user account to be unrecoverable
# except by SQL manipulation if a previously valid skin name
if ( $wgOut->isQuickbarSuppressed() ) {
return 0;
}
+
$q = $wgUser->getOption( 'quickbar', 0 );
+
return $q;
}
# should not matter, but Konqueror (3.5.9 at least) incorrectly
# uses whichever one appears later in the HTML source. Make sure
# apple-touch-icon is specified first to avoid this.
- if( false !== $wgAppleTouchIcon ) {
+ if ( false !== $wgAppleTouchIcon ) {
$out->addLink( array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
}
- if( false !== $wgFavicon ) {
+ if ( false !== $wgFavicon ) {
$out->addLink( array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
}
'type' => 'application/opensearchdescription+xml',
'href' => wfScript( 'opensearch_desc' ),
'title' => wfMsgForContent( 'opensearch-desc' ),
- ));
+ ) );
$this->addMetadataLinks( $out );
global $wgEnableDublinCoreRdf, $wgEnableCreativeCommonsRdf;
global $wgRightsPage, $wgRightsUrl;
- if( $out->isArticleRelated() ) {
+ if ( $out->isArticleRelated() ) {
# note: buggy CC software only reads first "meta" link
- if( $wgEnableCreativeCommonsRdf ) {
+ if ( $wgEnableCreativeCommonsRdf ) {
$out->addMetadataLink( array(
'title' => 'Creative Commons',
'type' => 'application/rdf+xml',
'href' => $this->mTitle->getLocalURL( 'action=creativecommons' ) )
);
}
- if( $wgEnableDublinCoreRdf ) {
+
+ if ( $wgEnableDublinCoreRdf ) {
$out->addMetadataLink( array(
'title' => 'Dublin Core',
'type' => 'application/rdf+xml',
}
}
$copyright = '';
- if( $wgRightsPage ) {
+ if ( $wgRightsPage ) {
$copy = Title::newFromText( $wgRightsPage );
- if( $copy ) {
+
+ if ( $copy ) {
$copyright = $copy->getLocalURL();
}
}
- if( !$copyright && $wgRightsUrl ) {
+
+ if ( !$copyright && $wgRightsUrl ) {
$copyright = $wgRightsUrl;
}
- if( $copyright ) {
+
+ if ( $copyright ) {
$out->addLink( array(
'rel' => 'copyright',
'href' => $copyright )
$out->out( "\n</body></html>" );
wfProfileOut( __METHOD__ );
}
-
+
static function makeVariablesScript( $data ) {
- if( $data ) {
+ if ( $data ) {
return Html::inlineScript( 'mediaWiki.config.set(' . json_encode( $data ) . ');' );
} else {
return '';
# Weird back-compat stuff.
$skinName = $skinName['skinname'];
}
+
global $wgScript, $wgTitle, $wgStylePath, $wgUser, $wgScriptExtension;
global $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang, $wgLang;
global $wgOut, $wgArticle;
'wgSiteName' => $wgSitename,
'wgCategories' => $wgOut->getCategories(),
);
+
if ( $wgContLang->hasVariants() ) {
$vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
}
// if on upload page output the extension list & js_upload
- if( SpecialPage::resolveAlias( $wgTitle->getDBkey() ) == 'Upload' ) {
+ if ( SpecialPage::resolveAlias( $wgTitle->getDBkey() ) == 'Upload' ) {
global $wgFileExtensions;
$vars['wgFileExtensions'] = $wgFileExtensions;
}
- if( $wgUseAjax && $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
+ if ( $wgUseAjax && $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
$vars['wgMWSuggestTemplate'] = SearchEngine::getMWSuggestTemplate();
$vars['wgDBname'] = $wgDBname;
$vars['wgSearchNamespaces'] = SearchEngine::userNamespaces( $wgUser );
$vars['wgMWSuggestMessages'] = array( wfMsg( 'search-mwsuggest-enabled' ), wfMsg( 'search-mwsuggest-disabled' ) );
}
- foreach( $wgRestrictionTypes as $type ) {
+ foreach ( $wgRestrictionTypes as $type ) {
$vars['wgRestriction' . ucfirst( $type )] = $wgTitle->getRestrictions( $type );
}
if ( $wgOut->isArticleRelated() && $wgUseAjax && $wgAjaxWatch && $wgUser->isLoggedIn() ) {
$msgs = (object)array();
+
foreach ( array( 'watch', 'unwatch', 'watching', 'unwatching',
'tooltip-ca-watch', 'tooltip-ca-unwatch' ) as $msgName ) {
- $msgs->{$msgName . 'Msg'} = wfMsg( $msgName );
+ $msgs-> { $msgName . 'Msg' } = wfMsg( $msgName );
}
$vars['wgAjaxWatch'] = $msgs;
}
public function userCanPreview( $action ) {
global $wgRequest, $wgUser;
- if( $action != 'submit' ) {
+ if ( $action != 'submit' ) {
return false;
}
- if( !$wgRequest->wasPosted() ) {
+ if ( !$wgRequest->wasPosted() ) {
return false;
}
- if( !$this->mTitle->userCanEditCssSubpage() ) {
+ if ( !$this->mTitle->userCanEditCssSubpage() ) {
return false;
}
- if( !$this->mTitle->userCanEditJsSubpage() ) {
+ if ( !$this->mTitle->userCanEditJsSubpage() ) {
return false;
}
+
return $wgUser->matchEditToken(
$wgRequest->getVal( 'wpEditToken' ) );
}
global $wgStylePath;
wfProfileIn( __METHOD__ );
- if( !$skinName ) {
+
+ if ( !$skinName ) {
$skinName = $this->getSkinName();
}
$s .= "var skin = '" . Xml::escapeJsString( $skinName ) . "';\n";
$s .= "var stylepath = '" . Xml::escapeJsString( $wgStylePath ) . "';";
$s .= "\n\n/* MediaWiki:Common.js */\n";
+
$commonJs = wfMsgExt( 'common.js', 'content' );
+
if ( !wfEmptyMsg( 'common.js', $commonJs ) ) {
$s .= $commonJs;
}
$s .= "\n\n/* MediaWiki:" . ucfirst( $skinName ) . ".js */\n";
+
// avoid inclusion of non defined user JavaScript (with custom skins only)
// by checking for default message content
$msgKey = ucfirst( $skinName ) . '.js';
$userJS = wfMsgExt( $msgKey, 'content' );
+
if ( !wfEmptyMsg( $msgKey, $userJS ) ) {
$s .= $userJS;
}
*/
public function generateUserStylesheet() {
wfProfileIn( __METHOD__ );
+
$s = "/* generated user stylesheet */\n" .
$this->reallyGenerateUserStylesheet();
+
wfProfileOut( __METHOD__ );
return $s;
}
*/
protected function reallyGenerateUserStylesheet() {
global $wgUser;
+
$s = '';
- if( ( $undopt = $wgUser->getOption( 'underline' ) ) < 2 ) {
+
+ if ( ( $undopt = $wgUser->getOption( 'underline' ) ) < 2 ) {
$underline = $undopt ? 'underline' : 'none';
$s .= "a { text-decoration: $underline; }\n";
}
- if( $wgUser->getOption( 'highlightbroken' ) ) {
+
+ if ( $wgUser->getOption( 'highlightbroken' ) ) {
$s .= "a.new, #quickbar a.new { color: #CC2200; }\n";
} else {
$s .= <<<CSS
}
CSS;
}
- if( $wgUser->getOption( 'justify' ) ) {
+
+ if ( $wgUser->getOption( 'justify' ) ) {
$s .= "#article, #bodyContent, #mw_content { text-align: justify; }\n";
}
- if( !$wgUser->getOption( 'showtoc' ) ) {
+
+ if ( !$wgUser->getOption( 'showtoc' ) ) {
$s .= "#toc { display: none; }\n";
}
- if( !$wgUser->getOption( 'editsection' ) ) {
+
+ if ( !$wgUser->getOption( 'editsection' ) ) {
$s .= ".editsection { display: none; }\n";
}
+
$fontstyle = $wgUser->getOption( 'editfont' );
+
if ( $fontstyle !== 'default' ) {
$s .= "textarea { font-family: $fontstyle; }\n";
}
+
return $s;
}
// If we use the site's dynamic CSS, throw that in, too
// Per-site custom styles
- if( $wgUseSiteCss ) {
+ if ( $wgUseSiteCss ) {
global $wgHandheldStyle;
+
$query = wfArrayToCGI( self::getDynamicStylesheetQuery() );
# Site settings must override extension css! (bug 15025)
$out->addStyle( self::makeNSUrl( 'Common.css', $query, NS_MEDIAWIKI ) );
$out->addStyle( self::makeNSUrl( 'Print.css', $query, NS_MEDIAWIKI ), 'print' );
- if( $wgHandheldStyle ) {
+
+ if ( $wgHandheldStyle ) {
$out->addStyle( self::makeNSUrl( 'Handheld.css', $query, NS_MEDIAWIKI ), 'handheld' );
}
$out->addStyle( self::makeNSUrl( $this->getSkinName() . '.css', $query, NS_MEDIAWIKI ) );
}
global $wgAllowUserCssPrefs;
- if( $wgAllowUserCssPrefs ){
- if( $wgUser->isLoggedIn() ) {
+
+ if ( $wgAllowUserCssPrefs ) {
+ if ( $wgUser->isLoggedIn() ) {
// Ensure that logged-in users' generated CSS isn't clobbered
// by anons' publicly cacheable generated CSS.
$siteargs['smaxage'] = '0';
$siteargs['ts'] = $wgUser->mTouched;
}
+
// Per-user styles based on preferences
$siteargs['gen'] = 'css';
- if( ( $us = $wgRequest->getVal( 'useskin', '' ) ) !== '' ) {
+
+ if ( ( $us = $wgRequest->getVal( 'useskin', '' ) ) !== '' ) {
$siteargs['useskin'] = $us;
}
+
$out->addStyle( self::makeUrl( '-', wfArrayToCGI( $siteargs ) ) );
}
// Per-user custom style pages
- if( $wgAllowUserCss && $wgUser->isLoggedIn() ) {
+ if ( $wgAllowUserCss && $wgUser->isLoggedIn() ) {
$action = $wgRequest->getVal( 'action' );
+
# If we're previewing the CSS page, use it
- if( $this->mTitle->isCssSubpage() && $this->userCanPreview( $action ) ) {
+ if ( $this->mTitle->isCssSubpage() && $this->userCanPreview( $action ) ) {
// @FIXME: properly escape the cdata!
$out->addInlineStyle( $wgRequest->getText( 'wpTextbox1' ) );
} else {
$names = array( 'common', $this->getSkinName() );
- foreach( $names as $name ) {
+ foreach ( $names as $name ) {
$out->addStyle( self::makeUrl(
$this->userpage . '/' . $name . '.css',
'action=raw&ctype=text/css' )
*/
public static function getDynamicStylesheetQuery() {
global $wgSquidMaxage;
+
return array(
'action' => 'raw',
'maxage' => $wgSquidMaxage,
function getPageClasses( $title ) {
$numeric = 'ns-' . $title->getNamespace();
- if( $title->getNamespace() == NS_SPECIAL ) {
+
+ if ( $title->getNamespace() == NS_SPECIAL ) {
$type = 'ns-special';
- } elseif( $title->isTalkPage() ) {
+ } elseif ( $title->isTalkPage() ) {
$type = 'ns-talk';
} else {
$type = 'ns-subject';
}
+
$name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() );
+
return "$numeric $type $name";
}
$qb = $this->qbSetting();
$langlinks = $this->otherLanguages();
- if( $langlinks ) {
+ if ( $langlinks ) {
$rows = 2;
$borderhack = '';
} else {
$shove = ( $qb != 0 );
$left = ( $qb == 1 || $qb == 3 );
- if( $wgContLang->isRTL() ) {
+
+ if ( $wgContLang->isRTL() ) {
$left = !$left;
}
- if( !$shove ) {
+ if ( !$shove ) {
$s .= "<td class='top' align='left' valign='top' rowspan='{$rows}'>\n" .
$this->logoText() . '</td>';
- } elseif( $left ) {
+ } elseif ( $left ) {
$s .= $this->getQuickbarCompensator( $rows );
}
+
$l = $wgContLang->alignStart();
$s .= "<td {$borderhack} align='$l' valign='top'>\n";
if ( $shove && !$left ) { # Right
$s .= $this->getQuickbarCompensator( $rows );
}
+
$s .= "</tr>\n</table>\n</div>\n";
$s .= "\n<div id='article'>\n";
$notice = wfGetSiteNotice();
- if( $notice ) {
+
+ if ( $notice ) {
$s .= "\n<div id='siteNotice'>$notice</div>\n";
}
$s .= $this->pageTitle();
$s .= $this->pageSubtitle();
$s .= $this->getCategories();
+
wfProfileOut( __METHOD__ );
return $s;
}
global $wgOut, $wgUseCategoryBrowser;
global $wgContLang, $wgUser;
- if( count( $wgOut->mCategoryLinks ) == 0 ) {
+ if ( count( $wgOut->mCategoryLinks ) == 0 ) {
return '';
}
$allCats = $wgOut->getCategoryLinks();
$s = '';
$colon = wfMsgExt( 'colon-separator', 'escapenoentities' );
+
if ( !empty( $allCats['normal'] ) ) {
$t = $embed . implode( "{$pop} {$sep} {$embed}" , $allCats['normal'] ) . $pop;
# Hidden categories
if ( isset( $allCats['hidden'] ) ) {
if ( $wgUser->getBoolOption( 'showhiddencats' ) ) {
- $class ='mw-hidden-cats-user-shown';
+ $class = 'mw-hidden-cats-user-shown';
} elseif ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
$class = 'mw-hidden-cats-ns-shown';
} else {
$class = 'mw-hidden-cats-hidden';
}
+
$s .= "<div id=\"mw-hidden-catlinks\" class=\"$class\">" .
wfMsgExt( 'hidden-categories', array( 'parsemag', 'escapenoentities' ), count( $allCats['hidden'] ) ) .
$colon . $embed . implode( "$pop $sep $embed", $allCats['hidden'] ) . $pop .
# optional 'dmoz-like' category browser. Will be shown under the list
# of categories an article belong to
- if( $wgUseCategoryBrowser ) {
+ if ( $wgUseCategoryBrowser ) {
$s .= '<br /><hr />';
# get a big array of the parents tree
*/
function drawCategoryBrowser( $tree, &$skin ) {
$return = '';
- foreach( $tree as $element => $parent ) {
- if( empty( $parent ) ) {
+
+ foreach ( $tree as $element => $parent ) {
+ if ( empty( $parent ) ) {
# element start a new list
$return .= "\n";
} else {
# grab the others elements
$return .= $this->drawCategoryBrowser( $parent, $skin ) . ' > ';
}
+
# add our current element to the list
$eltitle = Title::newFromText( $element );
$return .= $skin->link( $eltitle, $eltitle->getText() );
}
+
return $return;
}
$classes = 'catlinks';
- // Check what we're showing
global $wgOut, $wgUser;
+
+ // Check what we're showing
$allCats = $wgOut->getCategoryLinks();
$showHidden = $wgUser->getBoolOption( 'showhiddencats' ) ||
$this->mTitle->getNamespace() == NS_CATEGORY;
- if( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
+ if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
$classes .= ' catlinks-allhidden';
}
protected function afterContentHook() {
$data = '';
- if( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
+ if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
// adding just some spaces shouldn't toggle the output
// of the whole <div/>, so we use trim() here
- if( trim( $data ) != '' ) {
+ if ( trim( $data ) != '' ) {
// Doing this here instead of in the skins to
// ensure that the div has the same ID in all
// skins
*/
protected function generateDebugHTML() {
global $wgShowDebug, $wgOut;
+
if ( $wgShowDebug ) {
$listInternals = $this->formatDebugHTML( $wgOut->mDebugtext );
return "\n<hr />\n<strong>Debug data:</strong><ul style=\"font-family:monospace;\" id=\"mw-debug-html\">" .
$listInternals . "</ul>\n";
}
+
return '';
}
$lines = explode( "\n", $debugText );
$curIdent = 0;
$ret = '<li>';
- foreach( $lines as $line ) {
+
+ foreach ( $lines as $line ) {
$m = array();
$display = ltrim( $line );
$ident = strlen( $line ) - strlen( $display );
$curIdent = $ident;
}
+
$ret .= str_repeat( '</li></ul>', $curIdent ) . '</li>';
+
return $ret;
}
function bottomScripts( $out ) {
$bottomScriptText = "\n" . $out->getHeadScripts( $this );
wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
+
return $bottomScriptText;
}
$s[] = $this->printableLink();
$disclaimer = $this->disclaimerLink(); # may be empty
- if( $disclaimer ) {
+
+ if ( $disclaimer ) {
$s[] = $disclaimer;
}
+
$privacy = $this->privacyLink(); # may be empty too
- if( $privacy ) {
+
+ if ( $privacy ) {
$s[] = $privacy;
}
if ( $this->mTitle->getNamespace() == NS_FILE ) {
$name = $this->mTitle->getDBkey();
$image = wfFindFile( $this->mTitle );
- if( $image ) {
+
+ if ( $image ) {
$link = htmlspecialchars( $image->getURL() );
$style = $this->getInternalLinkAttributes( $link, $name );
$s[] = "<a href=\"{$link}\"{$style}>{$name}</a>";
}
}
}
+
if ( 'history' == $action || isset( $diff ) || isset( $oldid ) ) {
$s[] .= $this->link(
$this->mTitle,
if ( $wgUser->getNewtalk() ) {
# do not show "You have new messages" text when we are viewing our
# own talk page
- if( !$this->mTitle->equals( $wgUser->getTalkPage() ) ) {
+ if ( !$this->mTitle->equals( $wgUser->getTalkPage() ) ) {
$tl = $this->link(
$wgUser->getTalkPage(),
wfMsgHtml( 'newmessageslink' ),
array( 'diff' => 'cur' ),
array( 'known', 'noclasses' )
);
- $s[] = '<strong>'. wfMsg( 'youhavenewmessages', $tl, $dl ) . '</strong>';
+ $s[] = '<strong>' . wfMsg( 'youhavenewmessages', $tl, $dl ) . '</strong>';
# disable caching
$wgOut->setSquidMaxage( 0 );
$wgOut->enableClientCache( false );
}
$undelete = $this->getUndeleteLink();
- if( !empty( $undelete ) ) {
+
+ if ( !empty( $undelete ) ) {
$s[] = $undelete;
}
+
return $wgLang->pipeList( $s );
}
if ( $wgUser->isAllowed( 'deletedhistory' ) &&
( $this->mTitle->getArticleId() == 0 || $action == 'history' ) ) {
$n = $this->mTitle->isDeleted();
+
if ( $n ) {
if ( $wgUser->isAllowed( 'undelete' ) ) {
$msg = 'thisisdeleted';
} else {
$msg = 'viewdeleted';
}
+
return wfMsg(
$msg,
$this->link(
);
}
}
+
return '';
}
$s[] = "<a href=\"$printurl\" rel=\"alternate\">" . wfMsg( 'printableversion' ) . '</a>';
}
- if( $wgOut->isSyndicated() ) {
- foreach( $wgFeedClasses as $format => $class ) {
+ if ( $wgOut->isSyndicated() ) {
+ foreach ( $wgFeedClasses as $format => $class ) {
$feedurl = $wgRequest->escapeAppendQuery( "feed=$format" );
$s[] = "<a href=\"$feedurl\" rel=\"alternate\" type=\"application/{$format}+xml\""
. " class=\"feedlink\">" . wfMsgHtml( "feed-$format" ) . "</a>";
global $wgOut;
$sub = $wgOut->getSubtitle();
+
if ( $sub == '' ) {
global $wgExtraSubtitle;
$sub = wfMsgExt( 'tagline', 'parsemag' ) . $wgExtraSubtitle;
}
+
$subpages = $this->subPageSubtitle();
$sub .= !empty( $subpages ) ? "</p><p class='subpages'>$subpages" : '';
$s = "<p class='subtitle'>{$sub}</p>\n";
+
return $s;
}
function subPageSubtitle() {
$subpages = '';
- if( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages ) ) ) {
+
+ if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages ) ) ) {
return $subpages;
}
global $wgOut;
- if( $wgOut->isArticle() && MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
+
+ if ( $wgOut->isArticle() && MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
$ptext = $this->mTitle->getPrefixedText();
- if( preg_match( '/\//', $ptext ) ) {
+ if ( preg_match( '/\//', $ptext ) ) {
$links = explode( '/', $ptext );
array_pop( $links );
$c = 0;
$growinglink = '';
$display = '';
- foreach( $links as $link ) {
+
+ foreach ( $links as $link ) {
$growinglink .= $link;
$display .= $link;
$linkObj = Title::newFromText( $growinglink );
- if( is_object( $linkObj ) && $linkObj->exists() ) {
+
+ if ( is_object( $linkObj ) && $linkObj->exists() ) {
$getlink = $this->link(
$linkObj,
htmlspecialchars( $display ),
array(),
array( 'known', 'noclasses' )
);
+
$c++;
- if( $c > 1 ) {
+
+ if ( $c > 1 ) {
$subpages .= wfMsgExt( 'pipe-separator', 'escapenoentities' );
} else {
$subpages .= '< ';
}
+
$subpages .= $getlink;
$display = '';
} else {
}
}
}
+
return $subpages;
}
$logoutPage = $wgContLang->specialPage( 'Userlogout' );
$ret = '';
+
if ( $wgUser->isAnon() ) {
- if( $this->showIPinHeader() ) {
+ if ( $this->showIPinHeader() ) {
$name = wfGetIP();
$talkLink = $this->link( $wgUser->getTalkPage(),
$returnTo = $this->mTitle->getPrefixedDBkey();
$query = array();
+
if ( $logoutPage != $returnTo ) {
$query['returnto'] = $returnTo;
}
$this->specialLink( 'preferences' ),
) );
}
+
$ret = $wgLang->pipeList( array(
$ret,
$this->link(
function searchForm() {
global $wgRequest, $wgUseTwoButtonsSearchForm;
+
$search = $wgRequest->getText( 'search' );
$s = '<form id="searchform' . $this->searchboxes . '" name="search" class="inline" method="post" action="'
. htmlspecialchars( substr( $search, 0, 256 ) ) . "\" />\n"
. '<input type="submit" name="go" value="' . wfMsg( 'searcharticle' ) . '" />';
- if( $wgUseTwoButtonsSearchForm ) {
+ if ( $wgUseTwoButtonsSearchForm ) {
$s .= ' <input type="submit" name="fulltext" value="' . wfMsg( 'searchbutton' ) . "\" />\n";
} else {
$s .= ' <a href="' . $this->escapeSearchLink() . '" rel="search">' . wfMsg( 'powersearch-legend' ) . "</a>\n";
$s[] = $this->editThisPage();
$s[] = $this->historyLink();
}
+
# Many people don't like this dropdown box
- #$s[] = $this->specialPagesList();
+ # $s[] = $this->specialPagesList();
- if( $this->variantLinks() ) {
+ if ( $this->variantLinks() ) {
$s[] = $this->variantLinks();
}
- if( $this->extensionTabLinks() ) {
+ if ( $this->extensionTabLinks() ) {
$s[] = $this->extensionTabLinks();
}
- // FIXME: Is using Language::pipeList impossible here? Do not quite understand the use of the newline
+ // @todo FIXME: Is using Language::pipeList impossible here? Do not quite understand the use of the newline
return implode( $s, wfMsgExt( 'pipe-separator', 'escapenoentities' ) . "\n" );
}
$out = '';
$s = array();
wfRunHooks( 'SkinTemplateTabs', array( $this, &$tabs ) );
- foreach( $tabs as $tab ) {
+ foreach ( $tabs as $tab ) {
$s[] = Xml::element( 'a',
array( 'href' => $tab['href'] ),
$tab['text'] );
}
- if( count( $s ) ) {
+ if ( count( $s ) ) {
global $wgLang;
$out = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
*/
function variantLinks() {
$s = '';
+
/* show links to different language variants */
global $wgDisableLangConversion, $wgLang, $wgContLang;
+
$variants = $wgContLang->getVariants();
- if( !$wgDisableLangConversion && sizeof( $variants ) > 1 ) {
- foreach( $variants as $code ) {
+
+ if ( !$wgDisableLangConversion && sizeof( $variants ) > 1 ) {
+ foreach ( $variants as $code ) {
$varname = $wgContLang->getVariantname( $code );
- if( $varname == 'disable' ) {
+
+ if ( $varname == 'disable' ) {
continue;
}
$s = $wgLang->pipeList( array(
) );
}
}
+
return $s;
}
$s = '';
if ( $wgOut->isArticleRelated() ) {
$element[] = '<strong>' . $this->editThisPage() . '</strong>';
+
if ( $wgUser->isLoggedIn() ) {
$element[] = $this->watchThisPage();
}
+
$element[] = $this->talkLink();
$element[] = $this->historyLink();
$element[] = $this->whatLinksHere();
$element[] = $this->watchPageLinksLink();
- if( $wgUseTrackbacks ) {
+ if ( $wgUseTrackbacks ) {
$element[] = $this->trackbackLink();
}
if (
$this->mTitle->getNamespace() == NS_USER ||
$this->mTitle->getNamespace() == NS_USER_TALK
- )
- {
+ ) {
$id = User::idFromName( $this->mTitle->getText() );
$ip = User::isIP( $this->mTitle->getText() );
# Both anons and non-anons have contributions list
- if( $id || $ip ) {
+ if ( $id || $ip ) {
$element[] = $this->userContribsLink();
}
- if( $this->showEmailUser( $id ) ) {
+
+ if ( $this->showEmailUser( $id ) ) {
$element[] = $this->emailUserLink();
}
}
if ( $this->mTitle->getArticleId() ) {
$s .= "\n<br />";
+
// Delete/protect/move links for privileged users
- if( $wgUser->isAllowed( 'delete' ) ) {
+ if ( $wgUser->isAllowed( 'delete' ) ) {
$s .= $this->deleteThisPage();
}
- if( $wgUser->isAllowed( 'protect' ) ) {
+
+ if ( $wgUser->isAllowed( 'protect' ) ) {
$s .= $sep . $this->protectThisPage();
}
- if( $wgUser->isAllowed( 'move' ) ) {
+
+ if ( $wgUser->isAllowed( 'move' ) ) {
$s .= $sep . $this->moveThisPage();
}
}
+
$s .= "<br />\n" . $this->otherLanguages();
}
$oldid = $wgRequest->getVal( 'oldid' );
$diff = $wgRequest->getVal( 'diff' );
+
if ( !$wgOut->isArticle() ) {
return '';
}
- if( !$wgArticle instanceof Article ) {
+
+ if ( !$wgArticle instanceof Article ) {
return '';
}
+
if ( isset( $oldid ) || isset( $diff ) ) {
return '';
}
+
if ( 0 == $wgArticle->getID() ) {
return '';
}
$s = '';
+
if ( !$wgDisableCounters ) {
$count = $wgLang->formatNum( $wgArticle->getCount() );
+
if ( $count ) {
$s = wfMsgExt( 'viewcount', array( 'parseinline' ), $count );
}
}
- if( $wgMaxCredits != 0 ) {
+ if ( $wgMaxCredits != 0 ) {
$s .= ' ' . Credits::getCredits( $wgArticle, $wgMaxCredits, $wgShowCreditsIfMax );
} else {
$s .= $this->lastModified();
}
- if( $wgPageShowWatchingUsers && $wgUser->getOption( 'shownumberswatching' ) ) {
+ if ( $wgPageShowWatchingUsers && $wgUser->getOption( 'shownumberswatching' ) ) {
$dbr = wfGetDB( DB_SLAVE );
$res = $dbr->select(
'watchlist',
if ( $type == 'detect' ) {
$diff = $wgRequest->getVal( 'diff' );
$isCur = $wgArticle && $wgArticle->isCurrent();
+
if ( is_null( $diff ) && !$isCur && wfMsgForContent( 'history_copyright' ) !== '-' ) {
$type = 'history';
} else {
}
$out = '';
- if( $wgRightsPage ) {
+
+ if ( $wgRightsPage ) {
$title = Title::newFromText( $wgRightsPage );
$link = $this->linkKnown( $title, $wgRightsText );
- } elseif( $wgRightsUrl ) {
+ } elseif ( $wgRightsUrl ) {
$link = $this->makeExternalLink( $wgRightsUrl, $wgRightsText );
- } elseif( $wgRightsText ) {
+ } elseif ( $wgRightsText ) {
$link = $wgRightsText;
} else {
# Give up now
return $out;
}
+
// Allow for site and per-namespace customization of copyright notice.
$forContent = true;
- if( isset( $wgArticle ) ) {
+
+ if ( isset( $wgArticle ) ) {
wfRunHooks( 'SkinCopyrightFooter', array( $wgArticle->getTitle(), $type, &$msg, &$link, &$forContent ) );
}
} else {
$out .= wfMsg( $msg, $link );
}
+
return $out;
}
function getCopyrightIcon() {
global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
+
$out = '';
+
if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
$out = $wgCopyrightIcon;
} elseif ( $wgRightsIcon ) {
$icon = htmlspecialchars( $wgRightsIcon );
+
if ( $wgRightsUrl ) {
$url = htmlspecialchars( $wgRightsUrl );
- $out .= '<a href="'.$url.'">';
+ $out .= '<a href="' . $url . '">';
}
+
$text = htmlspecialchars( $wgRightsText );
$out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
+
if ( $wgRightsUrl ) {
$out .= '</a>';
}
}
+
return $out;
}
*/
function getPoweredBy() {
global $wgStylePath;
+
$url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
$img = '<a href="http://www.mediawiki.org/"><img src="' . $url . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
+
return $img;
}
function lastModified() {
global $wgLang, $wgArticle;
- if( $this->mRevisionId && $this->mRevisionId != $wgArticle->getLatest() ) {
+
+ if ( $this->mRevisionId && $this->mRevisionId != $wgArticle->getLatest() ) {
$timestamp = Revision::getTimestampFromId( $wgArticle->getTitle(), $this->mRevisionId );
} else {
$timestamp = $wgArticle->getTimestamp();
}
+
if ( $timestamp ) {
$d = $wgLang->date( $timestamp, true );
$t = $wgLang->time( $timestamp, true );
} else {
$s = '';
}
+
if ( wfGetLB()->getLaggedSlaveMode() ) {
$s .= ' <strong>' . wfMsg( 'laggedslavemode' ) . '</strong>';
}
+
return $s;
}
$logourl = $this->getLogo();
$s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
+
return $s;
}
*/
function specialPagesList() {
global $wgContLang, $wgServer, $wgRedirectScript;
+
$pages = array_merge( SpecialPage::getRegularPages(), SpecialPage::getRestrictedPages() );
+
foreach ( $pages as $name => $page ) {
$pages[$name] = $page->getDescription();
}
$p = $wgContLang->specialPage( $name );
$s .= "<option value=\"{$p}\">{$desc}</option>\n";
}
+
$s .= "</select>\n";
$s .= "<input type='submit' value=\"{$go}\" name='redirect' />\n";
$s .= "</form>\n";
+
return $s;
}
array(),
array( 'known', 'noclasses' )
);
+
return $s;
}
private function footerLink( $desc, $page ) {
// if the link description has been set to "-" in the default language,
- if ( wfMsgForContent( $desc ) == '-') {
+ if ( wfMsgForContent( $desc ) == '-' ) {
// then it is disabled, for all languages.
return '';
} else {
// language (which may or may not be the same as the default language),
// but we make the link target be the one site-wide page.
$title = Title::newFromText( wfMsgForContent( $page ) );
+
return $this->linkKnown(
$title,
wfMsgExt( $desc, array( 'parsemag', 'escapenoentities' ) )
if ( !$wgOut->isArticleRelated() ) {
$s = wfMsg( 'protectedpage' );
} else {
- if( $this->mTitle->quickUserCan( 'edit' ) && $this->mTitle->exists() ) {
+ if ( $this->mTitle->quickUserCan( 'edit' ) && $this->mTitle->exists() ) {
$t = wfMsg( 'editthispage' );
- } elseif( $this->mTitle->quickUserCan( 'create' ) && !$this->mTitle->exists() ) {
+ } elseif ( $this->mTitle->quickUserCan( 'create' ) && !$this->mTitle->exists() ) {
$t = wfMsg( 'create-this-page' );
} else {
$t = wfMsg( 'viewsource' );
array( 'known', 'noclasses' )
);
}
+
return $s;
}
$options = array( 'action' => 'edit' );
- if( $this->mRevisionId && ! $wgArticle->isCurrent() ) {
+ if ( $this->mRevisionId && ! $wgArticle->isCurrent() ) {
$options['oldid'] = intval( $this->mRevisionId );
}
global $wgUser, $wgRequest;
$diff = $wgRequest->getVal( 'diff' );
+
if ( $this->mTitle->getArticleId() && ( !$diff ) && $wgUser->isAllowed( 'delete' ) ) {
$t = wfMsg( 'deletethispage' );
} else {
$s = '';
}
+
return $s;
}
global $wgUser, $wgRequest;
$diff = $wgRequest->getVal( 'diff' );
- if ( $this->mTitle->getArticleId() && ( ! $diff ) && $wgUser->isAllowed('protect') ) {
+
+ if ( $this->mTitle->getArticleId() && ( ! $diff ) && $wgUser->isAllowed( 'protect' ) ) {
if ( $this->mTitle->isProtected() ) {
$text = wfMsg( 'unprotectthispage' );
$query = array( 'action' => 'unprotect' );
} else {
$s = '';
}
+
return $s;
}
} else {
$s = wfMsg( 'notanarticle' );
}
+
return $s;
}
function watchPageLinksLink() {
global $wgOut;
+
if ( !$wgOut->isArticleRelated() ) {
return '(' . wfMsg( 'notanarticle' ) . ')';
} else {
}
$a = $wgOut->getLanguageLinks();
+
if ( 0 == count( $a ) ) {
return '';
}
$s = wfMsg( 'otherlanguages' ) . wfMsg( 'colon-separator' );
$first = true;
- if( $wgContLang->isRTL() ) {
+
+ if ( $wgContLang->isRTL() ) {
$s .= '<span dir="LTR">';
}
- foreach( $a as $l ) {
+
+ foreach ( $a as $l ) {
if ( !$first ) {
$s .= wfMsgExt( 'pipe-separator', 'escapenoentities' );
}
+
$first = false;
$nt = Title::newFromText( $l );
if ( $text == '' ) {
$text = $l;
}
+
$style = $this->getExternalLinkAttributes();
$s .= "<a href=\"{$url}\" title=\"{$title}\"{$style}>{$text}</a>";
}
- if( $wgContLang->isRTL() ) {
+
+ if ( $wgContLang->isRTL() ) {
$s .= '</span>';
}
+
return $s;
}
$linkOptions = array();
- if( $this->mTitle->isTalkPage() ) {
+ if ( $this->mTitle->isTalkPage() ) {
$link = $this->mTitle->getSubjectPage();
switch( $link->getNamespace() ) {
case NS_MAIN:
case NS_FILE:
$text = wfMsg( 'imagepage' );
# Make link known if image exists, even if the desc. page doesn't.
- if( wfFindFile( $link ) )
+ if ( wfFindFile( $link ) )
$linkOptions[] = 'known';
break;
case NS_MEDIAWIKI:
# __NEWSECTIONLINK___ changes behaviour here
# If it is present, the link points to this page, otherwise
# it points to the talk page
- if( $this->mTitle->isTalkPage() ) {
+ if ( $this->mTitle->isTalkPage() ) {
$title = $this->mTitle;
- } elseif( $wgOut->showNewSectionLink() ) {
+ } elseif ( $wgOut->showNewSectionLink() ) {
$title = $this->mTitle;
} else {
$title = $this->mTitle->getTalkPage();
function getUploadLink() {
global $wgUploadNavigationUrl;
- if( $wgUploadNavigationUrl ) {
+ if ( $wgUploadNavigationUrl ) {
# Using an empty class attribute to avoid automatic setting of "external" class
- return $this->makeExternalLink( $wgUploadNavigationUrl, wfMsgHtml( 'upload' ), false, null, array( 'class' => '') );
+ return $this->makeExternalLink( $wgUploadNavigationUrl, wfMsgHtml( 'upload' ), false, null, array( 'class' => '' ) );
} else {
return $this->link(
- SpecialPage::getTitleFor('Upload'),
+ SpecialPage::getTitleFor( 'Upload' ),
wfMsgHtml( 'upload' ),
array(),
array(),
static function makeMainPageUrl( $urlaction = '' ) {
$title = Title::newMainPage();
self::checkTitle( $title, '' );
+
return $title->getLocalURL( $urlaction );
}
static function makeUrl( $name, $urlaction = '' ) {
$title = Title::newFromText( $name );
self::checkTitle( $title, $name );
+
return $title->getLocalURL( $urlaction );
}
static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
$title = Title::makeTitleSafe( $namespace, $name );
self::checkTitle( $title, $name );
+
return $title->getLocalURL( $urlaction );
}
static function makeUrlDetails( $name, $urlaction = '' ) {
$title = Title::newFromText( $name );
self::checkTitle( $title, $name );
+
return array(
'href' => $title->getLocalURL( $urlaction ),
'exists' => $title->getArticleID() != 0 ? true : false
static function makeKnownUrlDetails( $name, $urlaction = '' ) {
$title = Title::newFromText( $name );
self::checkTitle( $title, $name );
+
return array(
'href' => $title->getLocalURL( $urlaction ),
'exists' => true
# make sure we have some title to operate on
static function checkTitle( &$title, $name ) {
- if( !is_object( $title ) ) {
+ if ( !is_object( $title ) ) {
$title = Title::newFromText( $name );
- if( !is_object( $title ) ) {
+ if ( !is_object( $title ) ) {
$title = Title::newFromText( '--error: link target missing--' );
}
}
if ( $wgEnableSidebarCache ) {
$parserMemc->set( $key, $bar, $wgSidebarCacheExpiry );
}
+
wfProfileOut( __METHOD__ );
return $bar;
}
$wikiBar = array(); # We need to handle the wikitext on a different variable, to avoid trying to do an array operation on text, which would be a fatal error.
$heading = '';
- foreach( $lines as $line ) {
- if( strpos( $line, '*' ) !== 0 ) {
+
+ foreach ( $lines as $line ) {
+ if ( strpos( $line, '*' ) !== 0 ) {
continue;
}
- if( strpos( $line, '**') !== 0 ) {
+
+ if ( strpos( $line, '**' ) !== 0 ) {
$heading = trim( $line, '* ' );
- if( !array_key_exists( $heading, $bar ) ) {
+ if ( !array_key_exists( $heading, $bar ) ) {
$bar[$heading] = array();
}
} else {
$line = trim( $line, '* ' );
- if( strpos( $line, '|' ) !== false ) { // sanity check
+
+ if ( strpos( $line, '|' ) !== false ) { // sanity check
$line = array_map( 'trim', explode( '|', $line, 2 ) );
$link = wfMsgForContent( $line[0] );
- if( $link == '-' ) {
+
+ if ( $link == '-' ) {
continue;
}
$text = wfMsgExt( $line[1], 'parsemag' );
- if( wfEmptyMsg( $line[1], $text ) ) {
+
+ if ( wfEmptyMsg( $line[1], $text ) ) {
$text = $line[1];
}
- if( wfEmptyMsg( $line[0], $link ) ) {
+
+ if ( wfEmptyMsg( $line[0], $link ) ) {
$link = $line[0];
}
$href = $link;
} else {
$title = Title::newFromText( $link );
+
if ( $title ) {
$title = $title->fixSpecialName();
$href = $title->getLocalURL();
'id' => 'n-' . strtr( $line[1], ' ', '-' ),
'active' => false
);
- } else if ( (substr($line, 0, 2) == '{{') && (substr($line, -2) == '}}') ) {
+ } else if ( ( substr( $line, 0, 2 ) == '{{' ) && ( substr( $line, -2 ) == '}}' ) ) {
global $wgParser, $wgTitle;
- $line = substr($line, 2, strlen($line) - 4 );
+ $line = substr( $line, 2, strlen( $line ) - 4 );
- if (is_null($wgParser->mOptions))
+ if ( is_null( $wgParser->mOptions ) ) {
$wgParser->mOptions = new ParserOptions();
+ }
- $wgParser->mOptions->setEditSection(false);
+ $wgParser->mOptions->setEditSection( false );
$wikiBar[$heading] = $wgParser->parse( wfMsgForContentNoTrans( $line ) , $wgTitle, $wgParser->mOptions )->getText();
} else {
continue;
}
}
- if ( count($wikiBar) > 0 )
- $bar = array_merge($bar, $wikiBar);
+ if ( count( $wikiBar ) > 0 ) {
+ $bar = array_merge( $bar, $wikiBar );
+ }
return $bar;
}
*/
function getNewtalks() {
global $wgUser, $wgOut;
+
$newtalks = $wgUser->getNewMessageLinks();
$ntl = '';
- if( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
+ if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
$userTitle = $this->mUser->getUserPage();
$userTalkTitle = $userTitle->getTalkPage();
- if( !$userTalkTitle->equals( $this->mTitle ) ) {
+ if ( !$userTalkTitle->equals( $this->mTitle ) ) {
$newMessagesLink = $this->link(
$userTalkTitle,
wfMsgHtml( 'newmessageslink' ),
# Disable Squid cache
$wgOut->setSquidMaxage( 0 );
}
- } elseif( count( $newtalks ) ) {
+ } elseif ( count( $newtalks ) ) {
// _>" " for BC <= 1.16
$sep = str_replace( '_', ' ', wfMsgHtml( 'newtalkseparator' ) );
$msgs = array();
- foreach( $newtalks as $newtalk ) {
+
+ foreach ( $newtalks as $newtalk ) {
$msgs[] = Xml::element(
'a',
array( 'href' => $newtalk['link'] ), $newtalk['wiki']
$ntl = wfMsgHtml( 'youhavenewmessagesmulti', $parts );
$wgOut->setSquidMaxage( 0 );
}
+
return $ntl;
}
-
}
*/
abstract class DatabaseBase implements DatabaseType {
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
# Variables
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
protected $mLastQuery = '';
protected $mDoneWrites = false;
protected $mFakeSlaveLag = null, $mFakeMaster = false;
protected $mDefaultBigSelects = null;
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
# Accessors
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
# These optionally set a variable and return the previous state
/**
* @return Boolean
*/
function getFlag( $flag ) {
- return !!($this->mFlags & $flag);
+ return !!( $this->mFlags & $flag );
}
/**
}
function getWikiID() {
- if( $this->mTablePrefix ) {
+ if ( $this->mTablePrefix ) {
return "{$this->mDBname}-{$this->mTablePrefix}";
} else {
return $this->mDBname;
}
}
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
# Other functions
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
/**
* Constructor.
* @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
*/
function __construct( $server = false, $user = false, $password = false, $dbName = false,
- $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
-
+ $failFunction = false, $flags = 0, $tablePrefix = 'get from global'
+ ) {
global $wgOut, $wgDBprefix, $wgCommandLineMode;
+
# Can't get a reference if it hasn't been set yet
if ( !isset( $wgOut ) ) {
$wgOut = null;
* @param failFunction
* @param $flags
*/
- static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
- {
+ static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
wfDeprecated( __METHOD__ );
return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
}
# logging size most of the time. The substr is really just a sanity check.
# Who's been wasting my precious column space? -- TS
- #$profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
+ # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
if ( $isMaster ) {
$queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
$queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
$totalProf = 'DatabaseBase::query';
}
+
wfProfileIn( $totalProf );
wfProfileIn( $queryProf );
}
$this->mLastQuery = $sql;
if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
// Set a flag indicating that writes have been done
- wfDebug( __METHOD__.": Writes done: $sql\n" );
+ wfDebug( __METHOD__ . ": Writes done: $sql\n" );
$this->mDoneWrites = true;
}
# Add a comment for easy SHOW PROCESSLIST interpretation
- #if ( $fname ) {
+ # if ( $fname ) {
global $wgUser;
- if ( is_object( $wgUser ) && !($wgUser instanceof StubObject) ) {
+ if ( is_object( $wgUser ) && !( $wgUser instanceof StubObject ) ) {
$userName = $wgUser->getName();
if ( mb_strlen( $userName ) > 15 ) {
$userName = mb_substr( $userName, 0, 15 ) . '...';
} else {
$userName = '';
}
- $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
- #} else {
+ $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
+ # } else {
# $commentedSql = $sql;
- #}
+ # }
# If DBO_TRX is set, start a transaction
if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
- $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
+ $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
// avoid establishing transactions for SHOW and SET statements too -
// that would delay transaction initializations to once connection
// is really used by application
- $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
- if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
+ $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
+ if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
$this->begin();
}
if ( $this->debug() ) {
static $cnt = 0;
+
$cnt++;
$sqlx = substr( $commentedSql, 0, 500 );
$sqlx = strtr( $sqlx, "\t\n", ' ' );
+
if ( $isMaster ) {
wfDebug( "Query $cnt (master): $sqlx\n" );
} else {
# Transaction is gone, like it or not
$this->mTrxLevel = 0;
wfDebug( "Connection lost, reconnecting...\n" );
+
if ( $this->ping() ) {
wfDebug( "Reconnected\n" );
$sqlx = substr( $commentedSql, 0, 500 );
$sqlx = strtr( $sqlx, "\t\n", ' ' );
global $wgRequestTime;
- $elapsed = round( microtime(true) - $wgRequestTime, 3 );
+ $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
$ret = $this->doQuery( $commentedSql );
} else {
wfProfileOut( $queryProf );
wfProfileOut( $totalProf );
}
+
return $this->resultObject( $ret );
}
$ignore = $this->ignoreErrors( true );
++$this->mErrorCount;
- if( $ignore || $tempIgnore ) {
- wfDebug("SQL ERROR (ignored): $error\n");
+ if ( $ignore || $tempIgnore ) {
+ wfDebug( "SQL ERROR (ignored): $error\n" );
$this->ignoreErrors( $ignore );
} else {
$sql1line = str_replace( "\n", "\\n", $sql );
- wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
- wfDebug("SQL ERROR: " . $error . "\n");
+ wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
+ wfDebug( "SQL ERROR: " . $error . "\n" );
throw new DBQueryError( $this, $error, $errno, $sql, $fname );
}
}
* @param $args Mixed: Either an array here, or put scalars as varargs
*/
function execute( $prepared, $args = null ) {
- if( !is_array( $args ) ) {
+ if ( !is_array( $args ) ) {
# Pull the var args
$args = func_get_args();
array_shift( $args );
}
+
$sql = $this->fillPrepared( $prepared['query'], $args );
+
return $this->query( $sql, $prepared['func'] );
}
*/
function safeQuery( $query, $args = null ) {
$prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
- if( !is_array( $args ) ) {
+
+ if ( !is_array( $args ) ) {
# Pull the var args
$args = func_get_args();
array_shift( $args );
}
+
$retval = $this->execute( $prepared, $args );
$this->freePrepared( $prepared );
+
return $retval;
}
function fillPrepared( $preparedQuery, $args ) {
reset( $args );
$this->preparedArgs =& $args;
+
return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
array( &$this, 'fillPreparedArg' ), $preparedQuery );
}
case '\\!': return '!';
case '\\&': return '&';
}
+
list( /* $n */ , $arg ) = each( $this->preparedArgs );
+
switch( $matches[1] ) {
case '?': return $this->addQuotes( $arg );
case '!': return $arg;
$table = $this->tableName( $table );
$sql = "UPDATE $table SET $var = '" .
$this->strencode( $value ) . "' WHERE ($cond)";
+
return (bool)$this->query( $sql, $fname );
}
* Usually aborts on failure
* If errors are explicitly ignored, returns FALSE on failure
*/
- function selectField( $table, $var, $cond='', $fname = 'DatabaseBase::selectField', $options = array() ) {
+ function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
if ( !is_array( $options ) ) {
$options = array( $options );
}
+
$options['LIMIT'] = 1;
$res = $this->select( $table, $var, $cond, $fname, $options );
+
if ( $res === false || !$this->numRows( $res ) ) {
return false;
}
+
$row = $this->fetchRow( $res );
+
if ( $row !== false ) {
return reset( $row );
} else {
$startOpts = '';
$noKeyOptions = array();
+
foreach ( $options as $key => $option ) {
if ( is_numeric( $key ) ) {
$noKeyOptions[$option] = true;
if ( isset( $options['GROUP BY'] ) ) {
$preLimitTail .= " GROUP BY {$options['GROUP BY']}";
}
+
if ( isset( $options['HAVING'] ) ) {
$preLimitTail .= " HAVING {$options['HAVING']}";
}
+
if ( isset( $options['ORDER BY'] ) ) {
$preLimitTail .= " ORDER BY {$options['ORDER BY']}";
}
- //if (isset($options['LIMIT'])) {
+ // if (isset($options['LIMIT'])) {
// $tailOpts .= $this->limitResult('', $options['LIMIT'],
// isset($options['OFFSET']) ? $options['OFFSET']
// : false);
- //}
+ // }
if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
$postLimitTail .= ' FOR UPDATE';
}
+
if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
$postLimitTail .= ' LOCK IN SHARE MODE';
}
+
if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
$startOpts .= 'DISTINCT';
}
if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
$startOpts .= ' /*! STRAIGHT_JOIN */';
}
+
if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
$startOpts .= ' HIGH_PRIORITY';
}
+
if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
$startOpts .= ' SQL_BIG_RESULT';
}
+
if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
$startOpts .= ' SQL_BUFFER_RESULT';
}
+
if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
$startOpts .= ' SQL_SMALL_RESULT';
}
+
if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
$startOpts .= ' SQL_CALC_FOUND_ROWS';
}
+
if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
$startOpts .= ' SQL_CACHE';
}
+
if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
$startOpts .= ' SQL_NO_CACHE';
}
* (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
* @return mixed Database result resource (feed to DatabaseBase::fetchObject or whatever), or false on failure
*/
- function select( $table, $vars, $conds='', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
+ function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
$sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
+
return $this->query( $sql, $fname );
}
* (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
* @return string, the SQL text
*/
- function selectSQLText( $table, $vars, $conds='', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
- if( is_array( $vars ) ) {
+ function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
+ if ( is_array( $vars ) ) {
$vars = implode( ',', $vars );
}
- if( !is_array( $options ) ) {
+
+ if ( !is_array( $options ) ) {
$options = array( $options );
}
- if( is_array( $table ) ) {
- if ( !empty($join_conds) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
+
+ if ( is_array( $table ) ) {
+ if ( !empty( $join_conds ) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
$from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
} else {
$from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
}
- } elseif ($table!='') {
- if ($table{0}==' ') {
+ } elseif ( $table != '' ) {
+ if ( $table { 0 } == ' ' ) {
$from = ' FROM ' . $table;
} else {
$from = ' FROM ' . $this->tableName( $table );
list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
- if( !empty( $conds ) ) {
+ if ( !empty( $conds ) ) {
if ( is_array( $conds ) ) {
$conds = $this->makeList( $conds, LIST_AND );
}
$sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
}
- if (isset($options['LIMIT']))
- $sql = $this->limitResult($sql, $options['LIMIT'],
- isset($options['OFFSET']) ? $options['OFFSET'] : false);
+ if ( isset( $options['LIMIT'] ) )
+ $sql = $this->limitResult( $sql, $options['LIMIT'],
+ isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
$sql = "$sql $postLimitTail";
- if (isset($options['EXPLAIN'])) {
+ if ( isset( $options['EXPLAIN'] ) ) {
$sql = 'EXPLAIN ' . $sql;
}
+
return $sql;
}
function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
$options['LIMIT'] = 1;
$res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
+
if ( $res === false ) {
return false;
}
- if ( !$this->numRows($res) ) {
+
+ if ( !$this->numRows( $res ) ) {
return false;
}
+
$obj = $this->fetchObject( $res );
+
return $obj;
}
* @param $options Array: options for select
* @return Integer: row count
*/
- public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
+ public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
$rows = 0;
$res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
+
if ( $res ) {
$row = $this->fetchRow( $res );
$rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
}
+
return $rows;
}
# as to avoid crashing php on some large strings.
# $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
- $sql = str_replace ( "\\\\", '', $sql);
- $sql = str_replace ( "\\'", '', $sql);
- $sql = str_replace ( "\\\"", '', $sql);
- $sql = preg_replace ("/'.*'/s", "'X'", $sql);
- $sql = preg_replace ('/".*"/s', "'X'", $sql);
+ $sql = str_replace ( "\\\\", '', $sql );
+ $sql = str_replace ( "\\'", '', $sql );
+ $sql = str_replace ( "\\\"", '', $sql );
+ $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
+ $sql = preg_replace ( '/".*"/s', "'X'", $sql );
# All newlines, tabs, etc replaced by single space
- $sql = preg_replace ( '/\s+/', ' ', $sql);
+ $sql = preg_replace ( '/\s+/', ' ', $sql );
# All numbers => N
- $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
+ $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
return $sql;
}
*/
function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
$info = $this->fieldInfo( $table, $field );
+
return (bool)$info;
}
# http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
$table = $this->tableName( $table );
$index = $this->indexName( $index );
- $sql = 'SHOW INDEX FROM '.$table;
+ $sql = 'SHOW INDEX FROM ' . $table;
$res = $this->query( $sql, $fname );
+
if ( !$res ) {
return null;
}
$result = array();
+
while ( $row = $this->fetchObject( $res ) ) {
if ( $row->Key_name == $index ) {
$result[] = $row;
}
}
- return empty($result) ? false : $result;
+ return empty( $result ) ? false : $result;
}
/**
$old = $this->ignoreErrors( true );
$res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
$this->ignoreErrors( $old );
+
return (bool)$res;
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return mysql_field_type( $res, $index );
}
*/
function indexUnique( $table, $index ) {
$indexInfo = $this->indexInfo( $table, $index );
+
if ( !$indexInfo ) {
return null;
}
+
return !$indexInfo[0]->Non_unique;
}
-
+
/**
* INSERT wrapper, inserts an array into a table
*
}
$table = $this->tableName( $table );
+
if ( !is_array( $options ) ) {
$options = array( $options );
}
+
if ( isset( $a[0] ) && is_array( $a[0] ) ) {
$multi = true;
$keys = array_keys( $a[0] );
* @return string
*/
function makeUpdateOptions( $options ) {
- if( !is_array( $options ) ) {
+ if ( !is_array( $options ) ) {
$options = array( $options );
}
+
$opts = array();
+
if ( in_array( 'LOW_PRIORITY', $options ) ) {
$opts[] = $this->lowPriorityOption();
}
+
if ( in_array( 'IGNORE', $options ) ) {
$opts[] = 'IGNORE';
}
- return implode(' ', $opts);
+
+ return implode( ' ', $opts );
}
/**
$table = $this->tableName( $table );
$opts = $this->makeUpdateOptions( $options );
$sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
+
if ( $conds != '*' ) {
$sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
}
+
return $this->query( $sql, $fname );
}
$first = true;
$list = '';
+
foreach ( $a as $field => $value ) {
if ( !$first ) {
if ( $mode == LIST_AND ) {
$list .= ' AND ';
- } elseif($mode == LIST_OR) {
+ } elseif ( $mode == LIST_OR ) {
$list .= ' OR ';
} else {
$list .= ',';
} else {
$first = false;
}
- if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
+
+ if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
$list .= "($value)";
- } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
+ } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
$list .= "$value";
- } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
+ } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
if ( count( $value ) == 0 ) {
- throw new MWException( __METHOD__.': empty input' );
- } elseif( count( $value ) == 1 ) {
+ throw new MWException( __METHOD__ . ': empty input' );
+ } elseif ( count( $value ) == 1 ) {
// Special-case single values, as IN isn't terribly efficient
// Don't necessarily assume the single key is 0; we don't
// enforce linear numeric ordering on other arrays here.
$value = array_values( $value );
- $list .= $field." = ".$this->addQuotes( $value[0] );
+ $list .= $field . " = " . $this->addQuotes( $value[0] );
} else {
- $list .= $field." IN (".$this->makeList($value).") ";
+ $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
}
} elseif ( $value === null ) {
if ( $mode == LIST_AND || $mode == LIST_OR ) {
$list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
}
}
+
return $list;
}
*/
function makeWhereFrom2d( $data, $baseKey, $subKey ) {
$conds = array();
+
foreach ( $data as $base => $sub ) {
if ( count( $sub ) ) {
$conds[] = $this->makeList(
array( $baseKey => $base, $subKey => array_keys( $sub ) ),
- LIST_AND);
+ LIST_AND );
}
}
* Bitwise operations
*/
- function bitNot($field) {
+ function bitNot( $field ) {
return "(~$field)";
}
- function bitAnd($fieldLeft, $fieldRight) {
+ function bitAnd( $fieldLeft, $fieldRight ) {
return "($fieldLeft & $fieldRight)";
}
- function bitOr($fieldLeft, $fieldRight) {
+ function bitOr( $fieldLeft, $fieldRight ) {
return "($fieldLeft | $fieldRight)";
}
/**
* Change the current database
*
+ * @todo Explain what exactly will fail if this is not overridden.
* @return bool Success or failure
*/
function selectDB( $db ) {
# Stub. Shouldn't cause serious problems if it's not overridden, but
# if your database engine supports a concept similar to MySQL's
- # databases you may as well. TODO: explain what exactly will fail if
- # this is not overridden.
+ # databases you may as well.
return true;
}
# Note that we use a whitespace test rather than a \b test to avoid
# any remote case where a word like on may be inside of a table name
# surrounded by symbols which may be considered word breaks.
- if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
+ if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
return $name;
}
# We reverse the explode so that database.table and table both output
# the correct table.
$dbDetails = array_reverse( explode( '.', $name, 2 ) );
- if( isset( $dbDetails[1] ) ) {
+ if ( isset( $dbDetails[1] ) ) {
@list( $table, $database ) = $dbDetails;
} else {
@list( $table ) = $dbDetails;
# A database name has been specified in input. Quote the table name
# because we don't want any prefixes added.
- if( isset($database) ) {
+ if ( isset( $database ) ) {
$table = ( $table[0] == '`' ? $table : "`{$table}`" );
}
# Note that we use the long format because php will complain in in_array if
# the input is not an array, and will complain in is_array if it is not set.
- if( !isset( $database ) # Don't use shared database if pre selected.
+ if ( !isset( $database ) # Don't use shared database if pre selected.
&& isset( $wgSharedDB ) # We have a shared database
&& $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
&& isset( $wgSharedTables )
}
# Quote the $database and $table and apply the prefix if not quoted.
- if( isset($database) ) {
+ if ( isset( $database ) ) {
$database = ( $database[0] == '`' ? $database : "`{$database}`" );
}
$table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
# Merge our database and table into our final table name.
- $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
+ $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
- # We're finished, return.
return $tableName;
}
public function tableNames() {
$inArray = func_get_args();
$retVal = array();
+
foreach ( $inArray as $name ) {
$retVal[$name] = $this->tableName( $name );
}
+
return $retVal;
}
public function tableNamesN() {
$inArray = func_get_args();
$retVal = array();
+
foreach ( $inArray as $name ) {
$retVal[] = $this->tableName( $name );
}
+
return $retVal;
}
function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
$ret = array();
$retJOIN = array();
- $use_index_safe = is_array($use_index) ? $use_index : array();
- $join_conds_safe = is_array($join_conds) ? $join_conds : array();
+ $use_index_safe = is_array( $use_index ) ? $use_index : array();
+ $join_conds_safe = is_array( $join_conds ) ? $join_conds : array();
+
foreach ( $tables as $table ) {
// Is there a JOIN and INDEX clause for this table?
- if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
+ if ( isset( $join_conds_safe[$table] ) && isset( $use_index_safe[$table] ) ) {
$tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
$tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
- $on = $this->makeList((array)$join_conds_safe[$table][1], LIST_AND);
+ $on = $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND );
+
if ( $on != '' ) {
$tableClause .= ' ON (' . $on . ')';
}
+
$retJOIN[] = $tableClause;
// Is there an INDEX clause?
- } else if ( isset($use_index_safe[$table]) ) {
+ } else if ( isset( $use_index_safe[$table] ) ) {
$tableClause = $this->tableName( $table );
$tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
$ret[] = $tableClause;
// Is there a JOIN clause?
- } else if ( isset($join_conds_safe[$table]) ) {
+ } else if ( isset( $join_conds_safe[$table] ) ) {
$tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
- $on = $this->makeList((array)$join_conds_safe[$table][1], LIST_AND);
+ $on = $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND );
+
if ( $on != '' ) {
$tableClause .= ' ON (' . $on . ')';
}
+
$retJOIN[] = $tableClause;
} else {
$tableClause = $this->tableName( $table );
$ret[] = $tableClause;
}
}
+
// We can't separate explicit JOIN clauses with ',', use ' ' for those
- $straightJoins = !empty($ret) ? implode( ',', $ret ) : "";
- $otherJoins = !empty($retJOIN) ? implode( ' ', $retJOIN ) : "";
+ $straightJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
+ $otherJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
+
// Compile our final table clause
- return implode(' ',array($straightJoins,$otherJoins) );
+ return implode( ' ', array( $straightJoins, $otherJoins ) );
}
/**
'un_user_id' => 'user_id',
'un_user_ip' => 'user_ip',
);
+
if ( isset( $renamed[$index] ) ) {
return $renamed[$index];
} else {
$s = str_replace( '\\', '\\\\', $s );
$s = $this->strencode( $s );
$s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
+
return $s;
}
*/
function buildLike() {
$params = func_get_args();
- if (count($params) > 0 && is_array($params[0])) {
+
+ if ( count( $params ) > 0 && is_array( $params[0] ) ) {
$params = $params[0];
}
$s = '';
- foreach( $params as $value) {
- if( $value instanceof LikeMatch ) {
+
+ foreach ( $params as $value ) {
+ if ( $value instanceof LikeMatch ) {
$s .= $value->toString();
} else {
$s .= $this->escapeLikeInternal( $value );
}
}
+
return " LIKE '" . $s . "' ";
}
$rows = array( $rows );
}
- $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
+ $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
$first = true;
+
foreach ( $rows as $row ) {
if ( $first ) {
$first = false;
} else {
$sql .= ',';
}
+
$sql .= '(' . $this->makeList( $row ) . ')';
}
+
return $this->query( $sql, $fname );
}
$delTable = $this->tableName( $delTable );
$joinTable = $this->tableName( $joinTable );
$sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
+
if ( $conds != '*' ) {
$sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
}
$row = $this->fetchObject( $res );
$m = array();
+
if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
$size = $m[1];
} else {
$size = -1;
}
+
return $size;
}
if ( !$conds ) {
throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
}
+
$table = $this->tableName( $table );
$sql = "DELETE FROM $table";
+
if ( $conds != '*' ) {
$sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
}
+
return $this->query( $sql, $fname );
}
$insertOptions = array(), $selectOptions = array() )
{
$destTable = $this->tableName( $destTable );
+
if ( is_array( $insertOptions ) ) {
$insertOptions = implode( ' ', $insertOptions );
}
- if( !is_array( $selectOptions ) ) {
+
+ if ( !is_array( $selectOptions ) ) {
$selectOptions = array( $selectOptions );
}
+
list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
+
if ( is_array( $srcTable ) ) {
$srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
} else {
$srcTable = $this->tableName( $srcTable );
}
+
$sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
" SELECT $startOpts " . implode( ',', $varMap ) .
" FROM $srcTable $useIndex ";
+
if ( $conds != '*' ) {
$sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
}
+
$sql .= " $tailOpts";
+
return $this->query( $sql, $fname );
}
* @param $limit Integer: the SQL limit
* @param $offset Integer the SQL offset (default false)
*/
- function limitResult( $sql, $limit, $offset=false ) {
- if( !is_numeric( $limit ) ) {
+ function limitResult( $sql, $limit, $offset = false ) {
+ if ( !is_numeric( $limit ) ) {
throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
}
+
return "$sql LIMIT "
- . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
+ . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
. "{$limit} ";
}
+
function limitResultForUpdate( $sql, $num ) {
return $this->limitResult( $sql, $num, 0 );
}
* @param $all Boolean: use UNION ALL
* @return String: SQL fragment
*/
- function unionQueries($sqls, $all) {
+ function unionQueries( $sqls, $all ) {
$glue = $all ? ') UNION ALL (' : ') UNION (';
- return '('.implode( $glue, $sqls ) . ')';
+ return '(' . implode( $glue, $sqls ) . ')';
}
/**
$function = array_shift( $args );
$oldIgnore = $this->ignoreErrors( true );
$tries = DEADLOCK_TRIES;
+
if ( is_array( $function ) ) {
$fname = $function[0];
} else {
$fname = $function;
}
+
do {
$retVal = call_user_func_array( $function, $args );
$error = $this->lastError();
}
}
} while ( $this->wasDeadlock() && --$tries > 0 );
+
$this->ignoreErrors( $oldIgnore );
+
if ( $tries <= 0 ) {
$this->rollback( $myFname );
$this->reportQueryError( $error, $errno, $sql, $fname );
}
if ( !is_null( $this->mFakeSlaveLag ) ) {
- $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
+ $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
+
if ( $wait > $timeout * 1e6 ) {
wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
wfProfileOut( $fname );
$encPos = intval( $pos->pos );
$sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
$res = $this->doQuery( $sql );
+
if ( $res && $row = $this->fetchRow( $res ) ) {
wfProfileOut( $fname );
return $row[0];
*/
function getSlavePos() {
if ( !is_null( $this->mFakeSlaveLag ) ) {
- $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
- wfDebug( __METHOD__.": fake slave pos = $pos\n" );
+ $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
+ wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
return $pos;
}
+
$res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
$row = $this->fetchObject( $res );
+
if ( $row ) {
- $pos = isset($row->Exec_master_log_pos) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
+ $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
} else {
return false;
if ( $this->mFakeMaster ) {
return new MySQLMasterPos( 'fake', microtime( true ) );
}
+
$res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
$row = $this->fetchObject( $res );
+
if ( $row ) {
return new MySQLMasterPos( $row->File, $row->Position );
} else {
* End a transaction
*/
function commit( $fname = 'DatabaseBase::commit' ) {
- if( $this->mTrxLevel ) {
+ if ( $this->mTrxLevel ) {
$this->query( 'COMMIT', $fname );
$this->mTrxLevel = 0;
}
* No-op on non-transactional databases.
*/
function rollback( $fname = 'DatabaseBase::rollback' ) {
- if( $this->mTrxLevel ) {
+ if ( $this->mTrxLevel ) {
$this->query( 'ROLLBACK', $fname, true );
$this->mTrxLevel = 0;
}
/**
* Return MW-style timestamp used for MySQL schema
*/
- function timestamp( $ts=0 ) {
- return wfTimestamp(TS_MW,$ts);
+ function timestamp( $ts = 0 ) {
+ return wfTimestamp( TS_MW, $ts );
}
/**
/**
* Return aggregated value alias
*/
- function aggregateValue ($valuedata,$valuename='value') {
+ function aggregateValue ( $valuedata, $valuename = 'value' ) {
return $valuename;
}
/**
* Get status information from SHOW STATUS in an associative array
*/
- function getStatus($which="%") {
+ function getStatus( $which = "%" ) {
$res = $this->query( "SHOW STATUS LIKE '{$which}'" );
$status = array();
+
while ( $row = $this->fetchObject( $res ) ) {
$status[$row->Variable_name] = $row->Value;
}
+
return $status;
}
return 0;
}
- function encodeBlob($b) {
+ function encodeBlob( $b ) {
return $b;
}
- function decodeBlob($b) {
+ function decodeBlob( $b ) {
return $b;
}
*/
function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
$fp = fopen( $filename, 'r' );
+
if ( false === $fp ) {
- if (!defined("MEDIAWIKI_INSTALL"))
+ if ( !defined( "MEDIAWIKI_INSTALL" ) )
throw new MWException( "Could not open \"{$filename}\".\n" );
else
return "Could not open \"{$filename}\".\n";
}
+
try {
$error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
}
- catch( MWException $e ) {
- if ( defined("MEDIAWIKI_INSTALL") ) {
+ catch ( MWException $e ) {
+ if ( defined( "MEDIAWIKI_INSTALL" ) ) {
$error = $e->getMessage();
} else {
fclose( $fp );
}
fclose( $fp );
+
return $error;
}
*/
public static function patchPath( $patch ) {
global $wgDBtype, $IP;
+
if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$patch" ) ) {
return "$IP/maintenance/$wgDBtype/archives/$patch";
} else {
if ( $lineCallback ) {
call_user_func( $lineCallback );
}
+
$line = trim( fgets( $fp, 1024 ) );
$sl = strlen( $line ) - 1;
if ( $sl < 0 ) {
continue;
}
- if ( '-' == $line{0} && '-' == $line{1} ) {
+
+ if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
continue;
}
- ## Allow dollar quoting for function declarations
- if (substr($line,0,4) == '$mw$') {
- if ($dollarquote) {
+ # # Allow dollar quoting for function declarations
+ if ( substr( $line, 0, 4 ) == '$mw$' ) {
+ if ( $dollarquote ) {
$dollarquote = false;
$done = true;
}
$dollarquote = true;
}
}
- else if (!$dollarquote) {
- if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
+ else if ( !$dollarquote ) {
+ if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
$done = true;
$line = substr( $line, 0, $sl );
}
if ( $cmd != '' ) {
$cmd .= ' ';
}
+
$cmd .= "$line\n";
if ( $done ) {
- $cmd = str_replace(';;', ";", $cmd);
+ $cmd = str_replace( ';;', ";", $cmd );
$cmd = $this->replaceVars( $cmd );
$res = $this->query( $cmd, __METHOD__ );
+
if ( $resultCallback ) {
call_user_func( $resultCallback, $res, $this );
}
$done = false;
}
}
+
return true;
}
-
/**
* Replace variables in sourced SQL
*/
// Index names
$ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
array( $this, 'indexNameCallback' ), $ins );
+
return $ins;
}
}
}
-
/******************************************************************************
* Utility classes
*****************************************************************************/
class DBObject {
public $mData;
- function __construct($data) {
+ function __construct( $data ) {
$this->mData = $data;
}
*/
class Blob {
private $mData;
- function __construct($data) {
+
+ function __construct( $data ) {
$this->mData = $data;
}
+
function fetch() {
return $this->mData;
}
class MySQLField {
private $name, $tablename, $default, $max_length, $nullable,
$is_pk, $is_unique, $is_multiple, $is_key, $type;
- function __construct ($info) {
+
+ function __construct ( $info ) {
$this->name = $info->name;
$this->tablename = $info->table;
$this->default = $info->def;
$this->is_pk = $info->primary_key;
$this->is_unique = $info->unique_key;
$this->is_multiple = $info->multiple_key;
- $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
+ $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
$this->type = $info->type;
}
function getText() {
global $wgShowDBErrorBacktrace;
+
$s = $this->getMessage() . "\n";
+
if ( $wgShowDBErrorBacktrace ) {
$s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
}
+
return $s;
}
}
function __construct( DatabaseBase &$db, $error = 'unknown error' ) {
$msg = 'DB connection error';
+
if ( trim( $error ) != '' ) {
$msg .= ": $error";
}
+
$this->error = $error;
+
parent::__construct( $db, $msg );
}
function getPageTitle() {
global $wgSitename, $wgLang;
+
$header = "$wgSitename has a problem";
+
if ( $wgLang instanceof Language ) {
$header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
}
}
if ( trim( $this->error ) == '' ) {
- $this->error = $this->db->getProperty('mServer');
+ $this->error = $this->db->getProperty( 'mServer' );
}
$noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
$extra = $this->searchForm();
- if( $wgUseFileCache ) {
+ if ( $wgUseFileCache ) {
try {
$cache = $this->fileCachedPage();
# Cached version on file system?
- if( $cache !== null ) {
+ if ( $cache !== null ) {
# Hack: extend the body for error messages
- $cache = str_replace( array('</html>','</body>'), '', $cache );
+ $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
# Add cache notice...
$cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
+
# Localize it if possible...
- if( $wgLang instanceof Language ) {
+ if ( $wgLang instanceof Language ) {
$cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
}
+
$warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
+
# Output cached page with notices on bottom and re-close body
return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
}
- } catch( MWException $e ) {
+ } catch ( MWException $e ) {
// Do nothing, just use the default page
}
}
+
# Headers needed here - output is just the error message
- return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
+ return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
}
function searchForm() {
global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
+
$usegoogle = "You can try searching via Google in the meantime.";
$outofdate = "Note that their indexes of our content may be out of date.";
$googlesearch = "Search";
$googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
}
- $search = htmlspecialchars(@$_REQUEST['search']);
+ $search = htmlspecialchars( @$_REQUEST['search'] );
$trygoogle = <<<EOT
<div style="margin: 1.5em">$usegoogle<br />
function fileCachedPage() {
global $wgTitle, $title, $wgLang, $wgOut;
- if( $wgOut->isDisabled() ) return; // Done already?
+
+ if ( $wgOut->isDisabled() ) {
+ return; // Done already?
+ }
+
$mainpage = 'Main Page';
+
if ( $wgLang instanceof Language ) {
$mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
}
- if( $wgTitle ) {
+ if ( $wgTitle ) {
$t =& $wgTitle;
- } elseif( $title ) {
+ } elseif ( $title ) {
$t = Title::newFromURL( $title );
} else {
$t = Title::newFromText( $mainpage );
}
$cache = new HTMLFileCache( $t );
- if( $cache->isFileCached() ) {
+ if ( $cache->isFileCached() ) {
return $cache->fetchPageText();
} else {
return '';
function htmlBodyOnly() {
return true;
}
-
}
/**
"Error: $errno $error\n";
parent::__construct( $db, $message );
+
$this->error = $error;
$this->errno = $errno;
$this->sql = $sql;
function getText() {
global $wgShowDBErrorBacktrace;
+
if ( $this->useMessageCache() ) {
$s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
+
if ( $wgShowDBErrorBacktrace ) {
$s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
}
+
return $s;
} else {
return parent::getText();
function getSQL() {
global $wgShowSQLErrors;
- if( !$wgShowSQLErrors ) {
+
+ if ( !$wgShowSQLErrors ) {
return $this->msg( 'sqlhidden', 'SQL hidden' );
} else {
return $this->sql;
function getHTML() {
global $wgShowDBErrorBacktrace;
+
if ( $this->useMessageCache() ) {
$s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
} else {
$s = nl2br( htmlspecialchars( $this->getMessage() ) );
}
+
if ( $wgShowDBErrorBacktrace ) {
$s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
}
+
return $s;
}
}
*/
function __construct( $database, $result ) {
$this->db = $database;
+
if ( $result instanceof ResultWrapper ) {
$this->result = $result->result;
} else {
*/
function rewind() {
- if ($this->numRows()) {
- $this->db->dataSeek($this, 0);
+ if ( $this->numRows() ) {
+ $this->db->dataSeek( $this, 0 );
}
$this->pos = 0;
$this->currentRow = null;
}
}
-/* Overloads the relevant methods of the real ResultsWrapper so it
+/**
+ * Overloads the relevant methods of the real ResultsWrapper so it
* doesn't go anywhere near an actual database.
*/
class FakeResultWrapper extends ResultWrapper {
-
var $result = array();
var $db = null; // And it's going to stay that way :D
var $pos = 0;
var $currentRow = null;
- function __construct( $array ){
+ function __construct( $array ) {
$this->result = $array;
}
function free() {}
// Callers want to be able to access fields with $this->fieldName
- function fetchObject(){
+ function fetchObject() {
$this->currentRow = $this->result[$this->pos++];
return (object)$this->currentRow;
}
$title = Title::makeTitle( NS_FILE, $row->img_name );
$file = new self( $title, $repo );
$file->loadFromRow( $row );
+
return $file;
}
*/
static function newFromKey( $sha1, $repo, $timestamp = false ) {
$conds = array( 'img_sha1' => $sha1 );
- if( $timestamp ) {
+
+ if ( $timestamp ) {
$conds['img_timestamp'] = $timestamp;
}
+
$dbr = $repo->getSlaveDB();
$row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
- if( $row ) {
+
+ if ( $row ) {
return self::newFromRow( $row, $repo );
} else {
return false;
* Do not call this except from inside a repo class.
*/
function __construct( $title, $repo ) {
- if( !is_object( $title ) ) {
+ if ( !is_object( $title ) ) {
throw new MWException( __CLASS__ . ' constructor given bogus title.' );
}
+
parent::__construct( $title, $repo );
+
$this->metadata = '';
$this->historyLine = 0;
$this->historyRes = null;
*/
function getCacheKey() {
$hashedName = md5( $this->getName() );
+
return $this->repo->getSharedCacheKey( 'file', $hashedName );
}
*/
function loadFromCache() {
global $wgMemc;
+
wfProfileIn( __METHOD__ );
$this->dataLoaded = false;
$key = $this->getCacheKey();
+
if ( !$key ) {
wfProfileOut( __METHOD__ );
return false;
}
+
$cachedValues = $wgMemc->get( $key );
// Check if the key existed and belongs to this version of MediaWiki
}
$this->dataLoaded = true;
}
+
if ( $this->dataLoaded ) {
wfIncrStats( 'image_cache_hit' );
} else {
*/
function saveToCache() {
global $wgMemc;
+
$this->load();
$key = $this->getCacheKey();
+
if ( !$key ) {
return;
}
+
$fields = $this->getCacheFields( '' );
$cache = array( 'version' => MW_FILE_VERSION );
$cache['fileExists'] = $this->fileExists;
+
if ( $this->fileExists ) {
foreach ( $fields as $field ) {
$cache[$field] = $this->$field;
static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
static $results = array();
+
if ( $prefix == '' ) {
return $fields;
}
+
if ( !isset( $results[$prefix] ) ) {
$prefixedFields = array();
foreach ( $fields as $field ) {
}
$results[$prefix] = $prefixedFields;
}
+
return $results[$prefix];
}
$row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
array( 'img_name' => $this->getName() ), $fname );
+
if ( $row ) {
$this->loadFromRow( $row );
} else {
function decodeRow( $row, $prefix = 'img_' ) {
$array = (array)$row;
$prefixLength = strlen( $prefix );
+
// Sanity check prefix once
if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
}
+
$decoded = array();
+
foreach ( $array as $name => $value ) {
$decoded[substr( $name, $prefixLength )] = $value;
}
+
$decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
+
if ( empty( $decoded['major_mime'] ) ) {
$decoded['mime'] = 'unknown/unknown';
} else {
}
$decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
}
+
# Trim zero padding from char/binary field
$decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
+
return $decoded;
}
function loadFromRow( $row, $prefix = 'img_' ) {
$this->dataLoaded = true;
$array = $this->decodeRow( $row, $prefix );
+
foreach ( $array as $name => $value ) {
$this->$name = $value;
}
+
$this->fileExists = true;
$this->maybeUpgradeRow();
}
if ( wfReadOnly() ) {
return;
}
+
if ( is_null( $this->media_type ) ||
$this->mime == 'image/svg'
) {
wfProfileOut( __METHOD__ );
return;
}
+
$dbw = $this->repo->getMasterDB();
list( $major, $minor ) = self::splitMime( $this->mime );
), array( 'img_name' => $this->getName() ),
__METHOD__
);
+
$this->saveToCache();
wfProfileOut( __METHOD__ );
}
$this->dataLoaded = true;
$fields = $this->getCacheFields( '' );
$fields[] = 'fileExists';
+
foreach ( $fields as $field ) {
if ( isset( $info[$field] ) ) {
$this->$field = $info[$field];
/** isVisible inhereted */
function isMissing() {
- if( $this->missing === null ) {
+ if ( $this->missing === null ) {
list( $fileExists ) = $this->repo->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo::FILES_ONLY );
$this->missing = !$fileExists;
}
*/
public function getWidth( $page = 1 ) {
$this->load();
+
if ( $this->isMultipage() ) {
$dim = $this->getHandler()->getPageDimensions( $this, $page );
if ( $dim ) {
*/
public function getHeight( $page = 1 ) {
$this->load();
+
if ( $this->isMultipage() ) {
$dim = $this->getHandler()->getPageDimensions( $this, $page );
if ( $dim ) {
*/
function getUser( $type = 'text' ) {
$this->load();
- if( $type == 'text' ) {
+
+ if ( $type == 'text' ) {
return $this->user_text;
- } elseif( $type == 'id' ) {
+ } elseif ( $type == 'id' ) {
return $this->user;
}
}
function migrateThumbFile( $thumbName ) {
$thumbDir = $this->getThumbPath();
$thumbPath = "$thumbDir/$thumbName";
+
if ( is_dir( $thumbPath ) ) {
// Directory where file should be
// This happened occasionally due to broken migration code in 1.5
// Doesn't exist anymore
clearstatcache();
}
+
if ( is_file( $thumbDir ) ) {
// File where directory should be
unlink( $thumbDir );
*/
function getThumbnails() {
$this->load();
+
$files = array();
$dir = $this->getThumbPath();
if ( $handle ) {
while ( false !== ( $file = readdir( $handle ) ) ) {
- if ( $file{0} != '.' ) {
+ if ( $file { 0 } != '.' ) {
$files[] = $file;
}
}
+
closedir( $handle );
}
}
*/
function purgeHistory() {
global $wgMemc;
+
$hashedName = md5( $this->getName() );
$oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
+
if ( $oldKey ) {
$wgMemc->delete( $oldKey );
}
*/
function purgeThumbnails() {
global $wgUseSquid;
+
// Delete thumbnails
$files = $this->getThumbnails();
$dir = $this->getThumbPath();
$urls = array();
+
foreach ( $files as $file ) {
# Check that the base file name is part of the thumb name
# This is a basic sanity check to avoid erasing unrelated directories
$conds = $opts = $join_conds = array();
$eq = $inc ? '=' : '';
$conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
- if( $start ) {
+
+ if ( $start ) {
$conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
}
- if( $end ) {
+
+ if ( $end ) {
$conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
}
- if( $limit ) {
+
+ if ( $limit ) {
$opts['LIMIT'] = $limit;
}
+
// Search backwards for time > x queries
$order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
$opts['ORDER BY'] = "oi_timestamp $order";
$res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
$r = array();
- while( $row = $dbr->fetchObject( $res ) ) {
+
+ while ( $row = $dbr->fetchObject( $res ) ) {
if ( $this->repo->oldFileFromRowFactory ) {
$r[] = call_user_func( $this->repo->oldFileFromRowFactory, $row, $this->repo );
} else {
$r[] = OldLocalFile::newFromRow( $row, $this->repo );
}
}
- if( $order == 'ASC' ) {
+
+ if ( $order == 'ASC' ) {
$r = array_reverse( $r ); // make sure it ends up descending
}
+
return $r;
}
array( 'img_name' => $this->title->getDBkey() ),
$fname
);
+
if ( 0 == $dbr->numRows( $this->historyRes ) ) {
$this->historyRes = null;
return false;
*/
public function resetHistory() {
$this->historyLine = 0;
+
if ( !is_null( $this->historyRes ) ) {
$this->historyRes = null;
}
function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
$this->lock();
$status = $this->publish( $srcPath, $flags );
+
if ( $status->ok ) {
if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
$status->fatal( 'filenotfound', $srcPath );
}
}
+
$this->unlock();
+
return $status;
}
$watch = false, $timestamp = false )
{
$pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
+
if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
return false;
}
+
if ( $watch ) {
global $wgUser;
$wgUser->addWatch( $this->getTitle() );
*/
function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
{
- if( is_null( $user ) ) {
+ if ( is_null( $user ) ) {
global $wgUser;
$user = $wgUser;
}
if ( !$props ) {
$props = $this->repo->getFileProps( $this->getVirtualUrl() );
}
+
$props['description'] = $comment;
$props['user'] = $user->getId();
$props['user_text'] = $user->getName();
# Delete thumbnails
$this->purgeThumbnails();
+
# The file is already on its final location, remove it from the squid cache
SquidUpdate::purge( array( $this->getURL() ) );
}
$reupload = false;
+
if ( $timestamp === false ) {
$timestamp = $dbw->timestamp();
}
$dbw->insert( 'image',
array(
'img_name' => $this->getName(),
- 'img_size'=> $this->size,
+ 'img_size' => $this->size,
'img_width' => intval( $this->width ),
'img_height' => intval( $this->height ),
'img_bits' => $this->bits,
'IGNORE'
);
- if( $dbw->affectedRows() == 0 ) {
+ if ( $dbw->affectedRows() == 0 ) {
$reupload = true;
# Collision, this is an update of a file
$action = $reupload ? 'overwrite' : 'upload';
$log->addEntry( $action, $descTitle, $comment, array(), $user );
- if( $descTitle->exists() ) {
+ if ( $descTitle->exists() ) {
# Create a null revision
$latest = $descTitle->getLatestRevID();
- $nullRevision = Revision::newNullRevision( $dbw, $descTitle->getArticleId(),
- $log->getRcComment(), false );
+ $nullRevision = Revision::newNullRevision(
+ $dbw,
+ $descTitle->getArticleId(),
+ $log->getRcComment(),
+ false
+ );
$nullRevision->insertOn( $dbw );
wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
# in case of a rollback there is an usable file from memcached
# which in fact doesn't really exist (bug 24978)
$this->saveToCache();
-
+
# Hooks, hooks, the magic of hooks...
wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
# Invalidate cache for all pages using this file
$update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
$update->doUpdate();
+
# Invalidate cache for all pages that redirects on this page
$redirs = $this->getTitle()->getRedirectsHere();
- foreach( $redirs as $redir ) {
+
+ foreach ( $redirs as $redir ) {
$update = new HTMLCacheUpdate( $redir, 'imagelinks' );
$update->doUpdate();
}
*/
function publish( $srcPath, $flags = 0 ) {
$this->lock();
+
$dstRel = $this->getRel();
- $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
+ $archiveName = gmdate( 'YmdHis' ) . '!' . $this->getName();
$archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
$flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
$status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
+
if ( $status->value == 'new' ) {
$status->value = '';
} else {
$status->value = $archiveName;
}
+
$this->unlock();
+
return $status;
}
function move( $target ) {
wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
$this->lock();
+
$batch = new LocalFileMoveBatch( $this, $target );
$batch->addCurrent();
$batch->addOlds();
$status = $batch->execute();
wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
+
$this->purgeEverything();
$this->unlock();
*/
function delete( $reason, $suppress = false ) {
$this->lock();
+
$batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
$batch->addCurrent();
}
$this->unlock();
+
return $status;
}
* @throws MWException or FSException on database or file store failure
* @return FileRepoStatus object.
*/
- function deleteOld( $archiveName, $reason, $suppress=false ) {
+ function deleteOld( $archiveName, $reason, $suppress = false ) {
$this->lock();
+
$batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
$batch->addOld( $archiveName );
$status = $batch->execute();
+
$this->unlock();
+
if ( $status->ok ) {
$this->purgeDescription();
$this->purgeHistory();
}
+
return $status;
}
*/
function restore( $versions = array(), $unsuppress = false ) {
$batch = new LocalFileRestoreBatch( $this, $unsuppress );
+
if ( !$versions ) {
$batch->addAll();
} else {
$batch->addIds( $versions );
}
+
$status = $batch->execute();
+
if ( !$status->ok ) {
return $status;
}
$cleanupStatus->successCount = 0;
$cleanupStatus->failCount = 0;
$status->merge( $cleanupStatus );
+
return $status;
}
*/
function lock() {
$dbw = $this->repo->getMasterDB();
+
if ( !$this->locked ) {
$dbw->begin();
$this->locked++;
}
+
return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
}
}
} // LocalFile class
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
/**
* Helper class for file deletion
unset( $oldRels['.'] );
$deleteCurrent = true;
}
+
return array( $oldRels, $deleteCurrent );
}
/*protected*/ function getHashes() {
$hashes = array();
list( $oldRels, $deleteCurrent ) = $this->getOldRels();
+
if ( $deleteCurrent ) {
$hashes['.'] = $this->file->getSha1();
}
+
if ( count( $oldRels ) ) {
$dbw = $this->file->repo->getMasterDB();
- $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
- 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
- __METHOD__ );
+ $res = $dbw->select(
+ 'oldimage',
+ array( 'oi_archive_name', 'oi_sha1' ),
+ 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
+ __METHOD__
+ );
+
while ( $row = $dbw->fetchObject( $res ) ) {
if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
// Get the hash from the file
$oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
$props = $this->file->repo->getFileProps( $oldUrl );
+
if ( $props['fileExists'] ) {
// Upgrade the oldimage row
$dbw->update( 'oldimage',
}
}
}
+
$missing = array_diff_key( $this->srcRels, $hashes );
+
foreach ( $missing as $name => $rel ) {
$this->status->error( 'filedelete-old-unregistered', $name );
}
+
foreach ( $hashes as $name => $hash ) {
if ( !$hash ) {
$this->status->error( 'filedelete-missing', $this->srcRels[$name] );
function doDBInserts() {
global $wgUser;
+
$dbw = $this->file->repo->getMasterDB();
$encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
$encUserId = $dbw->addQuotes( $wgUser->getId() );
function doDBDeletes() {
$dbw = $this->file->repo->getMasterDB();
list( $oldRels, $deleteCurrent ) = $this->getOldRels();
+
if ( count( $oldRels ) ) {
$dbw->delete( 'oldimage',
array(
'oi_archive_name' => array_keys( $oldRels )
), __METHOD__ );
}
+
if ( $deleteCurrent ) {
$dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
}
$privateFiles = array();
list( $oldRels, $deleteCurrent ) = $this->getOldRels();
$dbw = $this->file->repo->getMasterDB();
- if( !empty( $oldRels ) ) {
+
+ if ( !empty( $oldRels ) ) {
$res = $dbw->select( 'oldimage',
array( 'oi_archive_name' ),
array( 'oi_name' => $this->file->getName(),
- 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
- $dbw->bitAnd('oi_deleted', File::DELETED_FILE) => File::DELETED_FILE ),
+ 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
+ $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
__METHOD__ );
- while( $row = $dbw->fetchObject( $res ) ) {
+
+ while ( $row = $dbw->fetchObject( $res ) ) {
$privateFiles[$row->oi_archive_name] = 1;
}
}
$this->deletionBatch = array();
$ext = $this->file->getExtension();
$dotExt = $ext === '' ? '' : ".$ext";
+
foreach ( $this->srcRels as $name => $srcRel ) {
// Skip files that have no hash (missing source).
// Keep private files where they are.
// Execute the file deletion batch
$status = $this->file->repo->deleteBatch( $this->deletionBatch );
+
if ( !$status->isGood() ) {
$this->status->merge( $status );
}
// Purge squid
if ( $wgUseSquid ) {
$urls = array();
+
foreach ( $this->srcRels as $srcRel ) {
$urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
$urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
// Commit and return
$this->file->unlock();
wfProfileOut( __METHOD__ );
+
return $this->status;
}
*/
function removeNonexistentFiles( $batch ) {
$files = $newBatch = array();
- foreach( $batch as $batchItem ) {
+
+ foreach ( $batch as $batchItem ) {
list( $src, $dest ) = $batchItem;
$files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
}
+
$result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
- foreach( $batch as $batchItem )
- if( $result[$batchItem[0]] )
+
+ foreach ( $batch as $batchItem ) {
+ if ( $result[$batchItem[0]] ) {
$newBatch[] = $batchItem;
+ }
+ }
+
return $newBatch;
}
}
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
/**
* Helper class for file undeletion
*/
function execute() {
global $wgLang;
+
if ( !$this->all && !$this->ids ) {
// Do nothing
return $this->file->repo->newGood();
// Fetch all or selected archived revisions for the file,
// sorted from the most recent to the oldest.
$conditions = array( 'fa_name' => $this->file->getName() );
- if( !$this->all ) {
+
+ if ( !$this->all ) {
$conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
}
$deleteIds = array();
$first = true;
$archiveNames = array();
- while( $row = $dbw->fetchObject( $result ) ) {
+
+ while ( $row = $dbw->fetchObject( $result ) ) {
$idsPresent[] = $row->fa_id;
if ( $row->fa_name != $this->file->getName() ) {
$status->failCount++;
continue;
}
+
if ( $row->fa_storage_key == '' ) {
// Revision was missing pre-deletion
$status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
$deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
$sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
+
# Fix leading zero
if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
$sha1 = substr( $sha1, 1 );
}
- if( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
+ if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
|| is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
|| is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
|| is_null( $row->fa_metadata ) ) {
'img_timestamp' => $row->fa_timestamp,
'img_sha1' => $sha1
);
+
// The live (current) version cannot be hidden!
- if( !$this->unsuppress && $row->fa_deleted ) {
+ if ( !$this->unsuppress && $row->fa_deleted ) {
$storeBatch[] = array( $deletedUrl, 'public', $destRel );
$this->cleanupBatch[] = $row->fa_storage_key;
}
} else {
$archiveName = $row->fa_archive_name;
- if( $archiveName == '' ) {
+
+ if ( $archiveName == '' ) {
// This was originally a current version; we
// have to devise a new archive name for it.
// Format is <timestamp of archiving>!<name>
$timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
+
do {
$archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
$timestamp++;
} while ( isset( $archiveNames[$archiveName] ) );
}
+
$archiveNames[$archiveName] = true;
$destRel = $this->file->getArchiveRel( $archiveName );
$insertBatch[] = array(
}
$deleteIds[] = $row->fa_id;
- if( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
+
+ if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
// private files can stay where they are
$status->successCount++;
} else {
$storeBatch[] = array( $deletedUrl, 'public', $destRel );
$this->cleanupBatch[] = $row->fa_storage_key;
}
+
$first = false;
}
+
unset( $result );
// Add a warning to the status object for missing IDs
$missingIds = array_diff( $this->ids, $idsPresent );
+
foreach ( $missingIds as $id ) {
$status->error( 'undelete-missing-filearchive', $id );
}
// Store batch returned a critical error -- this usually means nothing was stored
// Stop now and return an error
$this->file->unlock();
+
return $status;
}
if ( $insertCurrent ) {
$dbw->insert( 'image', $insertCurrent, __METHOD__ );
}
+
if ( $insertBatch ) {
$dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
}
+
if ( $deleteIds ) {
$dbw->delete( 'filearchive',
array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
}
// If store batch is empty (all files are missing), deletion is to be considered successful
- if( $status->successCount > 0 || !$storeBatch ) {
- if( !$exists ) {
+ if ( $status->successCount > 0 || !$storeBatch ) {
+ if ( !$exists ) {
wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
// Update site_stats
$this->file->purgeHistory();
}
}
+
$this->file->unlock();
+
return $status;
}
*/
function removeNonexistentFiles( $triplets ) {
$files = $filteredTriplets = array();
- foreach( $triplets as $file )
+ foreach ( $triplets as $file )
$files[$file[0]] = $file[0];
+
$result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
- foreach( $triplets as $file )
- if( $result[$file[0]] )
+
+ foreach ( $triplets as $file ) {
+ if ( $result[$file[0]] ) {
$filteredTriplets[] = $file;
+ }
+ }
+
return $filteredTriplets;
}
function removeNonexistentFromCleanup( $batch ) {
$files = $newBatch = array();
$repo = $this->file->repo;
- foreach( $batch as $file ) {
+
+ foreach ( $batch as $file ) {
$files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
}
$result = $repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
- foreach( $batch as $file )
- if( $result[$file] )
+
+ foreach ( $batch as $file ) {
+ if ( $result[$file] ) {
$newBatch[] = $file;
+ }
+ }
+
return $newBatch;
}
if ( !$this->cleanupBatch ) {
return $this->file->repo->newGood();
}
+
$this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
+
$status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
+
return $status;
}
}
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
/**
* Helper class for file movement
array( 'oi_name' => $this->oldName ),
__METHOD__
);
- while( $row = $this->db->fetchObject( $result ) ) {
+
+ while ( $row = $this->db->fetchObject( $result ) ) {
$oldName = $row->oi_archive_name;
$bits = explode( '!', $oldName, 2 );
- if( count( $bits ) != 2 ) {
+
+ if ( count( $bits ) != 2 ) {
wfDebug( "Invalid old file name: $oldName \n" );
continue;
}
+
list( $timestamp, $filename ) = $bits;
- if( $this->oldName != $filename ) {
+
+ if ( $this->oldName != $filename ) {
wfDebug( "Invalid old file name: $oldName \n" );
continue;
}
+
$this->oldCount++;
+
// Do we want to add those to oldCount?
- if( $row->oi_deleted & File::DELETED_FILE ) {
+ if ( $row->oi_deleted & File::DELETED_FILE ) {
continue;
}
+
$this->olds[] = array(
"{$archiveBase}/{$this->oldHash}{$oldName}",
"{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
$statusMove = $repo->storeBatch( $triplets, FSRepo::DELETE_SOURCE );
wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
- if( !$statusMove->isOk() ) {
+
+ if ( !$statusMove->isOk() ) {
wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
$this->db->rollback();
}
$status->merge( $statusDb );
$status->merge( $statusMove );
+
return $status;
}
array( 'img_name' => $this->oldName ),
__METHOD__
);
- if( $dbw->affectedRows() ) {
+
+ if ( $dbw->affectedRows() ) {
$status->successCount++;
} else {
$status->failCount++;
'oldimage',
array(
'oi_name' => $this->newName,
- 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName), $dbw->addQuotes($this->newName) ),
+ 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
),
array( 'oi_name' => $this->oldName ),
__METHOD__
);
+
$affected = $dbw->affectedRows();
$total = $this->oldCount;
$status->successCount += $affected;
function getMoveTriplets() {
$moves = array_merge( array( $this->cur ), $this->olds );
$triplets = array(); // The format is: (srcUrl, destZone, destUrl)
- foreach( $moves as $move ) {
+
+ foreach ( $moves as $move ) {
// $move: (oldRelativePath, newRelativePath)
$srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
$triplets[] = array( $srcUrl, 'public', $move[1] );
wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
}
+
return $triplets;
}
*/
function removeNonexistentFiles( $triplets ) {
$files = array();
- foreach( $triplets as $file )
+
+ foreach ( $triplets as $file ) {
$files[$file[0]] = $file[0];
+ }
+
$result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
$filteredTriplets = array();
- foreach( $triplets as $file )
- if( $result[$file[0]] ) {
+
+ foreach ( $triplets as $file ) {
+ if ( $result[$file[0]] ) {
$filteredTriplets[] = $file;
} else {
wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
}
+ }
+
return $filteredTriplets;
}
}
$this->showStatusMessage( $status );
echo "\n";
exit;
- } elseif ( count($warnings) !== 0 ) {
+ } elseif ( count( $warnings ) !== 0 ) {
foreach ( $status->getWikiTextArray( $warnings ) as $w ) {
$this->showMessage( $w . wfMsg( 'ellipsis' ) .
wfMsg( 'word-separator' ) );
}
}
- $this->showMessage( wfMsg( 'config-install-step-done' ) ."\n");
+ $this->showMessage( wfMsg( 'config-install-step-done' ) . "\n" );
}
public function showMessage( $msg /*, ... */ ) {
public function showStatusMessage( Status $status ) {
$this->showMessage( $status->getWikiText() );
}
-
-}
\ No newline at end of file
+}
break;
}
}
+
$this->term = $this->color
? new AnsiTermColorer()
: new DummyTermColorer();
mt_srand( ++$this->fuzzSeed );
$totalLength = mt_rand( 1, $this->maxFuzzTestLength );
$input = '';
+
while ( strlen( $input ) < $totalLength ) {
$logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
$hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
$this->setupGlobals();
$parser = $this->getParser();
+
// Run the test
try {
$parser->parse( $input, $title, $opts );
} else {
$numSuccess++;
}
+
$numTotal++;
$this->teardownGlobals();
$parser->__destruct();
if ( $usage > 90 ) {
echo "Out of memory:\n";
$memStats = $this->getMemoryBreakdown();
+
foreach ( $memStats as $name => $usage ) {
echo "$name: $usage\n";
}
*/
function getFuzzInput( $filenames ) {
$dict = '';
+
foreach ( $filenames as $filename ) {
$contents = file_get_contents( $filename );
preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
+
foreach ( $matches[1] as $match ) {
$dict .= $match . "\n";
}
}
+
return $dict;
}
*/
function getMemoryBreakdown() {
$memStats = array();
+
foreach ( $GLOBALS as $name => $value ) {
$memStats['$' . $name] = strlen( serialize( $value ) );
}
+
$classes = get_declared_classes();
+
foreach ( $classes as $class ) {
$rc = new ReflectionClass( $class );
$props = $rc->getStaticProperties();
$memStats[$class] = strlen( serialize( $props ) );
$methods = $rc->getMethods();
+
foreach ( $methods as $method ) {
$memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
}
}
+
$functions = get_defined_functions();
+
foreach ( $functions['user'] as $function ) {
$rf = new ReflectionFunction( $function );
$memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
}
+
asort( $memStats );
+
return $memStats;
}
$this->recorder->start();
$this->setupDatabase();
$ok = true;
+
foreach ( $filenames as $filename ) {
$tests = new TestFileIterator( $filename, $this );
$ok = $this->runTests( $tests ) && $ok;
}
+
$this->teardownDatabase();
$this->recorder->report();
$this->recorder->end();
+
return $ok;
}
function runTests( $tests ) {
$ok = true;
+
foreach ( $tests as $i => $t ) {
$result =
$this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
$ok = $ok && $result;
$this->recorder->record( $t['test'], $result );
}
+
if ( $this->showProgress ) {
print "\n";
}
+
return $ok;
}
*/
function getParser( $preprocessor = null ) {
global $wgParserConf;
+
$class = $wgParserConf['class'];
$parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
+
foreach ( $this->hooks as $tag => $callback ) {
$parser->setHook( $tag, $callback );
}
+
foreach ( $this->functionHooks as $tag => $bits ) {
list( $callback, $flags ) = $bits;
$parser->setFunctionHook( $tag, $callback, $flags );
}
+
wfRunHooks( 'ParserTestParser', array( &$parser ) );
+
return $parser;
}
$out = $output->getText();
if ( isset( $opts['showtitle'] ) ) {
- if ( $output->getTitleText() ) $title = $output->getTitleText();
+ if ( $output->getTitleText() ) {
+ $title = $output->getTitleText();
+ }
+
$out = "$title\n$out";
}
+
if ( isset( $opts['ill'] ) ) {
$out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
} elseif ( isset( $opts['cat'] ) ) {
global $wgOut;
+
$wgOut->addCategoryLinks( $output->getCategories() );
$cats = $wgOut->getCategoryLinks();
+
if ( isset( $cats['normal'] ) ) {
$out = $this->tidy( implode( ' ', $cats['normal'] ) );
} else {
}
}
-
/**
* Use a regex to find out the value of an option
* @param $key String: name of option val to retrieve
*/
private static function getOptionValue( $key, $opts, $default ) {
$key = strtolower( $key );
+
if ( isset( $opts[$key] ) ) {
return $opts[$key];
} else {
if ( substr( $opt, 0, 1 ) == '"' ) {
return substr( $opt, 1, -1 );
}
+
if ( substr( $opt, 0, 2 ) == '[[' ) {
return substr( $opt, 2, -2 );
}
}
$this->savedGlobals = array();
+
foreach ( $settings as $var => $val ) {
if ( array_key_exists( $var, $GLOBALS ) ) {
$this->savedGlobals[$var] = $GLOBALS[$var];
}
+
$GLOBALS[$var] = $val;
}
+
$langObj = Language::factory( $lang );
$GLOBALS['wgLang'] = $langObj;
$GLOBALS['wgContLang'] = $langObj;
$GLOBALS['wgOut'] = new OutputPage;
global $wgHooks;
+
$wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
$wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
$wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
*/
private function listTables() {
global $wgDBtype;
+
$tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
*/
public function setupDatabase() {
global $wgDBprefix, $wgDBtype;
+
if ( $this->databaseSetupDone ) {
return;
}
+
if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
throw new MWException( 'setupDatabase should be called before setupGlobals' );
}
+
$this->databaseSetupDone = true;
$this->oldTablePrefix = $wgDBprefix;
} elseif ( $db->tableExists( $tbl ) ) {
$db->query( "DROP TABLE $newTableName" );
}
+
# Create new table
$db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
}
+
if ( $wgDBtype == 'oracle' )
$db->query( 'BEGIN FILL_WIKI_INFO; END;' );
'media_type' => MEDIATYPE_BITMAP,
'mime' => 'image/jpeg',
'metadata' => serialize( array() ),
- 'sha1' => sha1(''),
+ 'sha1' => sha1( '' ),
'fileExists' => true
), $db->timestamp( '20010115123500' ), $user );
'media_type' => MEDIATYPE_BITMAP,
'mime' => 'image/jpeg',
'metadata' => serialize( array() ),
- 'sha1' => sha1(''),
+ 'sha1' => sha1( '' ),
'fileExists' => true
), $db->timestamp( '20010115123500' ), $user );
}
public function teardownDatabase() {
global $wgDBtype;
+
if ( !$this->databaseSetupDone ) {
return;
}
$this->changePrefix( $this->oldTablePrefix );
$this->databaseSetupDone = false;
+
if ( $this->useTemporaryTables ) {
# Don't need to do anything
return;
$tables = $this->listTables();
$db = wfGetDB( DB_MASTER );
+
foreach ( $tables as $table ) {
$sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
$db->query( $sql );
}
- if ($wgDBtype == 'oracle')
- $db->query('BEGIN FILL_WIKI_INFO; END;');
+
+ if ( $wgDBtype == 'oracle' )
+ $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
}
/**
*/
private function setupUploadDir() {
global $IP;
+
if ( $this->keepUploads ) {
$dir = wfTempDir() . '/mwParser-images';
+
if ( is_dir( $dir ) ) {
return $dir;
}
$dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
}
- //wfDebug( "Creating upload directory $dir\n" );
+ // wfDebug( "Creating upload directory $dir\n" );
if ( file_exists( $dir ) ) {
wfDebug( "Already exists!\n" );
return $dir;
}
+
wfMkdirParents( $dir . '/3/3a' );
copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
wfMkdirParents( $dir . '/0/09' );
copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
+
return $dir;
}
private function teardownGlobals() {
RepoGroup::destroySingleton();
LinkCache::singleton()->clear();
+
foreach ( $this->savedGlobals as $var => $val ) {
$GLOBALS[$var] = $val;
}
if ( $this->showProgress ) {
print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
}
+
return true;
}
# test, in case it succeeded. Show it now:
$this->showTesting( $desc );
}
+
print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
+
if ( $this->showOutput ) {
print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
}
+
if ( $this->showDiffs ) {
print $this->quickDiff( $result, $html );
if ( !$this->wellFormed( $html ) ) {
}
}
}
+
return false;
}
$wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
$title = Title::newFromText( $name );
+
if ( is_null( $title ) ) {
wfDie( "invalid title at line $line\n" );
}
$aid = $title->getArticleID( GAID_FOR_UPDATE );
+
if ( $aid != 0 ) {
wfDie( "duplicate article '$name' at line $line\n" );
}
*/
public function requireHook( $name ) {
global $wgParser;
+
$wgParser->firstCallInit( ); // make sure hooks are loaded.
+
if ( isset( $wgParser->mTagHooks[$name] ) ) {
$this->hooks[$name] = $wgParser->mTagHooks[$name];
} else {
echo " This test suite requires the '$name' hook extension, skipping.\n";
return false;
}
+
return true;
}
*/
public function requireFunctionHook( $name ) {
global $wgParser;
+
$wgParser->firstCallInit( ); // make sure hooks are loaded.
+
if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
$this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
} else {
echo " This test suite requires the '$name' function hook extension, skipping.\n";
return false;
}
+
return true;
}
*/
private function tidy( $text ) {
global $wgUseTidy;
+
if ( $wgUseTidy ) {
$text = MWTidy::tidy( $text );
}
+
return $text;
}
$fragment = $this->extractFragment( $html, $position );
$this->mXmlError = "$err at byte $position:\n$fragment";
xml_parser_free( $parser );
+
return false;
}
+
xml_parser_free( $parser );
+
return true;
}
$this->term->color( 31 ) .
'^' .
$this->term->color( 0 );
+
return "$display\n$caret";
}
*/
public function color( $color ) {
global $wgCommandLineDarkBg;
+
$light = $wgCommandLineDarkBg ? "1;" : "0;";
+
return "\x1b[{$light}{$color}m";
}
function reportPercentage( $success, $total ) {
$ratio = wfPercent( 100 * $success / $total );
print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
+
if ( $success == $total ) {
print $this->term->color( 32 ) . "ALL TESTS PASSED!";
} else {
$failed = $total - $success ;
print $this->term->color( 31 ) . "$failed tests failed!";
}
+
print $this->term->reset() . "\n";
+
return ( $success == $total );
}
}
*/
function __construct( $parent ) {
parent::__construct( $parent );
+
$this->lb = wfGetLBFactory()->newMainLB();
// This connection will have the wiki's table prefix, not parsertest_
$this->db = $this->lb->getConnection( DB_MASTER );
// We'll make comparisons against the previous run later...
$this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
}
+
$this->results = array();
}
$res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
array( 'ti_run' => $this->prevRun ), __METHOD__ );
+
foreach ( $res as $row ) {
if ( !$this->parent->regex
|| preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
} else /* if ( $prevResults[$test] == 0 )*/ {
$before = 'f';
}
+
if ( !isset( $this->results[$test] ) ) {
$after = 'n';
} elseif ( $this->results[$test] == 1 ) {
} else /*if ( $this->results[$test] == 0 ) */ {
$after = 'f';
}
+
$code = $before . $after;
+
if ( isset( $table[$code] ) ) {
$breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
}
if ( !empty( $breakdown[$code] ) ) {
$count = count( $breakdown[$code] );
printf( "\n%4d %s\n", $count, $label );
+
foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
print " * $differing_test_name [$statusInfo]\n";
}
} else {
print "No previous test runs to compare against.\n";
}
+
print "\n";
parent::report();
}
* which have never passed (which are more change requests than regressions).
*/
private function getTestStatusInfo( $testname, $after ) {
-
// If we're looking at a test that has just been removed, then say when it first appeared.
if ( $after == 'n' ) {
$changedRun = $this->db->selectField ( 'testitem',
array( 'tr_date', 'tr_mw_version' ),
array( 'tr_id' => $changedRun ),
__METHOD__ );
+
return "First recorded appearance: "
. date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
. ", " . $appear->tr_mw_version;
$conds = array(
'ti_name' => $testname,
'ti_success' => ( $after == 'f' ? "1" : "0" ) );
+
if ( $this->curRun ) {
$conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
}
} else {
$postDate = 'now';
}
+
return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
. date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
. " and $postDate";
or ! $this->db->tableExists( 'testitem' ) )
{
print "WARNING> `testrun` table not found in database. Trying to create table.\n";
- if ( $wgDBtype === 'postgres' )
+ if ( $wgDBtype === 'postgres' ) {
$this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
- elseif ( $wgDBtype === 'oracle' )
+ } elseif ( $wgDBtype === 'oracle' ) {
$this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
- else
+ } else {
$this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
+ }
+
echo "OK, resuming.\n";
}
'tr_uname' => php_uname()
),
__METHOD__ );
- if ( $wgDBtype === 'postgres' )
+ if ( $wgDBtype === 'postgres' ) {
$this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
- else
+ } else {
$this->curRun = $this->db->insertId();
+ }
}
/**
*/
function record( $test, $result ) {
parent::record( $test, $result );
+
$this->db->insert( 'testitem',
array(
'ti_run' => $this->curRun,
class RemoteTestRecorder extends TestRecorder {
function start() {
parent::start();
+
$this->results = array();
$this->ping( 'running' );
}
$revId,
$status,
);
+
if ( $status == "complete" ) {
$message[] = $jsonResults;
}
'status' => $status,
'hmac' => $hmac,
);
+
if ( $status == "complete" ) {
$postData['results'] = $jsonResults;
}
+
$response = $this->post( $remote['api-url'], $postData );
if ( $response === false ) {
print "CodeReview info upload failed to reach server.\n";
exit( 1 );
}
+
$responseData = FormatJson::decode( $response, true );
+
if ( !is_array( $responseData ) ) {
print "CodeReview API response not recognized...\n";
wfDebug( "Unrecognized CodeReview API response: $response\n" );
exit( 1 );
}
+
if ( isset( $responseData['error'] ) ) {
$code = $responseData['error']['code'];
$info = $responseData['error']['info'];
$this->file = $file;
$this->fh = fopen( $this->file, "rt" );
+
if ( !$this->fh ) {
wfDie( "Couldn't open file '$file'\n" );
}
$this->parser = $parser;
- if ( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
+ if ( $this->parser ) {
+ $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
+ }
+
$this->lineNum = $this->index = 0;
}
if ( fseek( $this->fh, 0 ) ) {
wfDie( "Couldn't fseek to the start of '$this->file'\n" );
}
+
$this->index = -1;
$this->lineNum = 0;
$this->eof = false;
while ( false !== ( $line = fgets( $this->fh ) ) ) {
$this->lineNum++;
$matches = array();
+
if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
$section = strtolower( $matches[1] );
+
if ( $section == 'endarticle' ) {
if ( !isset( $data['text'] ) ) {
wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
}
+
if ( !isset( $data['article'] ) ) {
wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
}
+
if ( $this->parser ) {
$this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
$this->lineNum );
}
+
$data = array();
$section = null;
+
continue;
}
+
if ( $section == 'endhooks' ) {
if ( !isset( $data['hooks'] ) ) {
wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
}
+
foreach ( explode( "\n", $data['hooks'] ) as $line ) {
$line = trim( $line );
+
if ( $line ) {
if ( $this->parser && !$this->parser->requireHook( $line ) ) {
return false;
}
}
}
+
$data = array();
$section = null;
+
continue;
}
+
if ( $section == 'endfunctionhooks' ) {
if ( !isset( $data['functionhooks'] ) ) {
wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
}
+
foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
$line = trim( $line );
+
if ( $line ) {
if ( $this->parser && !$this->parser->requireFunctionHook( $line ) ) {
return false;
}
}
}
+
$data = array();
$section = null;
+
continue;
}
+
if ( $section == 'end' ) {
if ( !isset( $data['test'] ) ) {
wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
}
+
if ( !isset( $data['input'] ) ) {
wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
}
+
if ( !isset( $data['result'] ) ) {
wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
}
+
if ( !isset( $data['options'] ) ) {
$data['options'] = '';
}
+
if ( !isset( $data['config'] ) )
$data['config'] = '';
# disabled test
$data = array();
$section = null;
+
continue;
}
+
global $wgUseTeX;
+
if ( $this->parser &&
preg_match( '/\\bmath\\b/i', $data['options'] ) && !$wgUseTeX ) {
# don't run math tests if $wgUseTeX is set to false in LocalSettings
$data = array();
$section = null;
+
continue;
}
} else {
$this->test['test'] = $data['test'];
}
+
return true;
}
+
if ( isset ( $data[$section] ) ) {
wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
}
+
$data[$section] = '';
+
continue;
}
+
if ( $section ) {
$data[$section] .= $line;
}
}
+
return false;
}
}
-
<?php
-class UploadFromUrlTestSuite extends PHPUnit_Framework_TestSuite
-{
+class UploadFromUrlTestSuite extends PHPUnit_Framework_TestSuite {
public static function addTables( &$tables ) {
$tables[] = 'user_properties';
$tables[] = 'filearchive';
$tables[] = 'logging';
$tables[] = 'updatelog';
$tables[] = 'iwlinks';
+
return true;
}
$wgLocalFileRepo = array(
'class' => 'LocalRepo',
'name' => 'local',
- 'directory' => wfTempDir().'/test-repo',
+ 'directory' => wfTempDir() . '/test-repo',
'url' => 'http://example.com/images',
- 'deletedDir' => wfTempDir().'/test-repo/delete',
+ 'deletedDir' => wfTempDir() . '/test-repo/delete',
'hashLevels' => 2,
'transformVia404' => false,
);
$messageMemc =& wfGetMessageCacheStorage();
$parserMemc =& wfGetParserCacheStorage();
- //$wgContLang = new StubContLang;
+ // $wgContLang = new StubContLang;
$wgUser = new User;
$wgLang = new StubUserLang;
$wgOut = new StubObject( 'wgOut', 'OutputPage' );
$wgMessageCache = new StubObject( 'wgMessageCache', 'MessageCache',
array( $messageMemc, $wgUseDatabaseMessages,
$wgMsgCacheExpiry ) );
- if ( $wgStyleDirectory === false ) $wgStyleDirectory = "$IP/skins";
+ if ( $wgStyleDirectory === false ) {
+ $wgStyleDirectory = "$IP/skins";
+ }
}
);
}
-
/**
* Delete the specified files, if they exist.
*
*/
private function setupUploadDir() {
global $IP;
+
if ( $this->keepUploads ) {
$dir = wfTempDir() . '/mwParser-images';
+
if ( is_dir( $dir ) ) {
return $dir;
}
}
wfDebug( "Creating upload directory $dir\n" );
+
if ( file_exists( $dir ) ) {
wfDebug( "Already exists!\n" );
return $dir;
}
+
wfMkdirParents( $dir . '/3/3a' );
copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
wfMkdirParents( $dir . '/0/09' );
copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
+
return $dir;
}
- public static function suite()
- {
+ public static function suite() {
return new UploadFromUrlTestSuite( 'UploadFromUrlTest' );
}
-
}
-
*/
require( 'Testing/Selenium.php' );
+
class Selenium {
protected static $_instance = null;
public $isStarted = false;
if ( null === self::$_instance ) {
self::$_instance = $this;
} else {
- throw new MWException("Already have one Selenium instance.");
+ throw new MWException( "Already have one Selenium instance." );
}
}
$this->type( 'wpName1', $this->user );
$this->type( 'wpPassword1', $this->pass );
$this->click( "//input[@id='wpLoginAttempt']" );
- $this->waitForPageToLoad(5000);
- //after login we redirect to the main page. So check whether the "Prefernces" top menu item exists
+ $this->waitForPageToLoad( 5000 );
+
+ // after login we redirect to the main page. So check whether the "Prefernces" top menu item exists
$value = $this->isElementPresent( "//li[@id='pt-preferences']" );
+
if ( $value != true ) {
throw new Testing_Selenium_Exception( "Login Failed" );
}
public function loadPage( $title, $action ) {
$this->open( self::$url . '/index.php?title=' . $title . '&action=' . $action );
}
-
+
public function setLogger( $logger ) {
$this->logger = $logger;
}
public function setBrowser( $b ) {
$browsers = $this->setupBrowsers();
+
+
if ( !isset( $browsers[$b] ) ) {
throw new MWException( "Invalid Browser: $b.\n" );
}
+
$this->browser = $browsers[$b];
}
public function __call( $name, $args ) {
- $t = call_user_func_array( array( $this->tester, $name), $args );
+ $t = call_user_func_array( array( $this->tester, $name ), $args );
return $t;
}
public function setBrowser( $b ) {
$browsers = $this->setupBrowsers();
+
if ( !isset( $browsers[$b] ) ) {
throw new MWException( "Invalid Browser: $b.\n" );
}
+
$this->browser = $browsers[$b];
}
public function __call( $name, $args ) {
- $t = call_user_func_array( array( $this->tester, $name), $args );
+ $t = call_user_func_array( array( $this->tester, $name ), $args );
return $t;
}
public function setUp() {
// Hack because because PHPUnit version 3.0.6 which is on prototype does not
- //run setUp as part of TestSuite::run
+ // run setUp as part of TestSuite::run
if ( $this->isSetUp ) {
return;
}
$this->selenium->loadPage( $title, $action );
}
}
-