/**
	 * Handles autoedit Ajax call from #autoedit parser function and from save
	 * and continue button.
	 *
	 * @param String $optionsString the options/data string
	 * @param String $prefillFromExisting String set to 'true' to retain existing form values (unset by save and continue)
	 * @return String
	 */
	static function handleAutoEdit( $optionsString = null, $prefillFromExisting = 'true' ) {

		global $wgParser;

		$handler = new self( null, 'sfautoedit' );
		$handler->isApiQuery( false );
		$options = $handler->setOptionsString( $optionsString );

		// get oktext (or use default)
		if ( array_key_exists( 'ok text', $options ) ) {
			$oktext = $options['ok text'];
		} else {
			$oktext = wfMsg( 'sf_autoedit_success' );
		}

		// get errortext (or use default)
		if ( array_key_exists( 'error text', $options ) ) {
			$errortext = $options['error text'];
		} else {
			$errortext = '$1';
		}

		// process data
		// result will be true or an error message
		$result = $handler->storeSemanticData( $prefillFromExisting === 'true' );

		// wrap result in ok/error message
		if ( $result === true ) {

			$options = $handler->getOptions();
			$result = wfMsgReplaceArgs( $oktext, array( $options['target'], $options['form'] ) );

		} else {

			$result->setResponseCode( '400 Bad Request' );
			$result = wfMsgReplaceArgs( $errortext, array( $result ) );
		}

		// initialize parser
		$title = Title::newFromText( 'DummyTitle' );

		if ( !StubObject::isRealObject( $wgParser ) ) {
			$wgParser->_unstub();
		}

		$parseroptions = $wgParser->getOptions();

		if ( $parseroptions == null ) {
			$parseroptions = new ParserOptions();
			$wgParser->Options( $parseroptions );
		}

		$parseroptions->enableLimitReport( false );


		$result = new AjaxResponse( $wgParser->parse( $result, $title, $parseroptions )->getText() );
		$result->setContentType( 'text/html' );

		return $result;
	}
Beispiel #2
0
/**
 * Intializes Semantic ExtTab Extension.
 * Called from ET during initialization.
 */
function smwgExtTabSetupExtension()
{
    global $smwgExtTabIP, $wgExtensionCredits;
    global $wgParser, $wgHooks, $wgAutoloadClasses;
    // register hooks
    if (defined('MW_SETPORTS_PARSERFIRSTCALLINIT')) {
        $wgHooks['ParserFirstCallInit'][] = 'ETParserFunctions::registerFunctions';
    } else {
        if (class_exists('StubObject') && !StubObject::isRealObject($wgParser)) {
            $wgParser->_unstub();
        }
        ETParserFunctions::registerFunctions($wgParser);
    }
    global $wgRequest;
    $action = $wgRequest->getVal('action');
    // add some AJAX calls
    if ($action == 'ajax') {
        $method_prefix = smwfExtTabGetAjaxMethodPrefix();
        // decide according to ajax method prefix which script(s) to import
        switch ($method_prefix) {
            case '_et_':
                require_once $smwgExtTabIP . '/includes/ET_AjaxAccess.php';
                break;
        }
    }
    // Register Credits
    $wgExtensionCredits['parserhook'][] = array('name' => 'Semantic ExtTab Extension', 'version' => SMW_EXTTAB_VERSION, 'author' => "Ning Hu, Justin Zhang, [http://smwforum.ontoprise.com/smwforum/index.php/Jesse_Wang Jesse Wang], sponsored by [http://projecthalo.com Project Halo], [http://www.vulcan.com Vulcan Inc.]", 'url' => 'http://wiking.vulcan.com/dev', 'description' => 'Tab control based on ExtJS.');
    return true;
}
Beispiel #3
0
function wfSetupParserFunctions()
{
    global $wgParser, $wgExtParserFunctions, $wgHooks;
    $wgExtParserFunctions = new ExtParserFunctions();
    // Check for SFH_OBJECT_ARGS capability
    if (defined('MW_SUPPORTS_PARSERFIRSTCALLINIT')) {
        $wgHooks['ParserFirstCallInit'][] = array(&$wgExtParserFunctions, 'registerParser');
    } else {
        if (class_exists('StubObject') && !StubObject::isRealObject($wgParser)) {
            $wgParser->_unstub();
        }
        $wgExtParserFunctions->registerParser($wgParser);
    }
    $wgHooks['ParserClearState'][] = array(&$wgExtParserFunctions, 'clearState');
}
Beispiel #4
0
function wfHasCategorySetup()
{
    global $wgParser, $wgHooks;
    $extHasCatObj = new ExtensionHasCategory();
    // Register hooks
    $wgHooks['LanguageGetMagic'][] = array($extHasCatObj, 'onLanguageGetMagic');
    // If we support ParserFirstCallInit, hook our function to register PF hook with it
    if (defined('MW_SUPPORTS_PARSERFIRSTCALLINIT')) {
        $wgHooks['ParserFirstCallInit'][] = array($extHasCatObj, 'RegisterParser');
        // Else manualy unstub Parser and call our function
    } else {
        if (class_exists('StubObject') && !StubObject::isRealObject($wgParser)) {
            $wgParser->_unstub();
        }
        $extHasCatObj->RegisterParser($wgParser);
    }
}
 /**
  * @param $parser Parser
  * @param $frame PPFrame
  * @param $format string
  * @param $date string
  * @param $language string
  * @param $local string|bool
  * @return string
  */
 public static function timeCommon($parser, $frame = null, $format = '', $date = '', $language = '', $local = false)
 {
     global $wgLocaltimezone;
     self::registerClearHook();
     if ($date === '') {
         $cacheKey = $parser->getOptions()->getTimestamp();
         $timestamp = new MWTimestamp($cacheKey);
         $date = $timestamp->getTimestamp(TS_ISO_8601);
         $useTTL = true;
     } else {
         $cacheKey = $date;
         $useTTL = false;
     }
     if (isset(self::$mTimeCache[$format][$cacheKey][$language][$local])) {
         $cachedVal = self::$mTimeCache[$format][$cacheKey][$language][$local];
         if ($useTTL && $cachedVal[1] !== null && $frame && is_callable(array($frame, 'setTTL'))) {
             $frame->setTTL($cachedVal[1]);
         }
         return $cachedVal[0];
     }
     # compute the timestamp string $ts
     # PHP >= 5.2 can handle dates before 1970 or after 2038 using the DateTime object
     $invalidTime = false;
     # the DateTime constructor must be used because it throws exceptions
     # when errors occur, whereas date_create appears to just output a warning
     # that can't really be detected from within the code
     try {
         # Default input timezone is UTC.
         $utc = new DateTimeZone('UTC');
         # Correct for DateTime interpreting 'XXXX' as XX:XX o'clock
         if (preg_match('/^[0-9]{4}$/', $date)) {
             $date = '00:00 ' . $date;
         }
         # Parse date
         # UTC is a default input timezone.
         $dateObject = new DateTime($date, $utc);
         # Set output timezone.
         if ($local) {
             if (isset($wgLocaltimezone)) {
                 $tz = new DateTimeZone($wgLocaltimezone);
             } else {
                 $tz = new DateTimeZone(date_default_timezone_get());
             }
         } else {
             $tz = $utc;
         }
         $dateObject->setTimezone($tz);
         # Generate timestamp
         $ts = $dateObject->format('YmdHis');
     } catch (Exception $ex) {
         $invalidTime = true;
     }
     $ttl = null;
     # format the timestamp and return the result
     if ($invalidTime) {
         $result = '<strong class="error">' . wfMessage('pfunc_time_error')->inContentLanguage()->escaped() . '</strong>';
     } else {
         self::$mTimeChars += strlen($format);
         if (self::$mTimeChars > self::$mMaxTimeChars) {
             return '<strong class="error">' . wfMessage('pfunc_time_too_long')->inContentLanguage()->escaped() . '</strong>';
         } else {
             if ($ts < 0) {
                 // Language can't deal with BC years
                 return '<strong class="error">' . wfMessage('pfunc_time_too_small')->inContentLanguage()->escaped() . '</strong>';
             } elseif ($ts < 100000000000000) {
                 // Language can't deal with years after 9999
                 if ($language !== '' && Language::isValidBuiltInCode($language)) {
                     // use whatever language is passed as a parameter
                     $langObject = Language::factory($language);
                 } else {
                     // use wiki's content language
                     $langObject = $parser->getFunctionLang();
                     StubObject::unstub($langObject);
                     // $ttl is passed by reference, which doesn't work right on stub objects
                 }
                 $result = $langObject->sprintfDate($format, $ts, $tz, $ttl);
             } else {
                 return '<strong class="error">' . wfMessage('pfunc_time_too_big')->inContentLanguage()->escaped() . '</strong>';
             }
         }
     }
     self::$mTimeCache[$format][$cacheKey][$language][$local] = array($result, $ttl);
     if ($useTTL && $ttl !== null && $frame && is_callable(array($frame, 'setTTL'))) {
         $frame->setTTL($ttl);
     }
     return $result;
 }
Beispiel #6
0
 /**
  * Given a language, try and fetch messages from that language and its fallbacks.
  *
  * @see MessageCache::get
  * @param Language|StubObject $lang Preferred language
  * @param string $lckey Lowercase key for the message (as for localisation cache)
  * @param bool $useDB Whether to include messages from the wiki database
  * @param bool[] $alreadyTried Contains true for each language that has been tried already
  * @return string|bool The message, or false if not found
  */
 private function getMessageForLang($lang, $lckey, $useDB, &$alreadyTried)
 {
     global $wgContLang;
     $langcode = $lang->getCode();
     // Try checking the database for the requested language
     if ($useDB) {
         $uckey = $wgContLang->ucfirst($lckey);
         if (!isset($alreadyTried[$langcode])) {
             $message = $this->getMsgFromNamespace($this->getMessagePageName($langcode, $uckey), $langcode);
             if ($message !== false) {
                 return $message;
             }
             $alreadyTried[$langcode] = true;
         }
     } else {
         $uckey = null;
     }
     // Check the CDB cache
     $message = $lang->getMessage($lckey);
     if ($message !== null) {
         return $message;
     }
     // Try checking the database for all of the fallback languages
     if ($useDB) {
         $fallbackChain = Language::getFallbacksFor($langcode);
         foreach ($fallbackChain as $code) {
             if (isset($alreadyTried[$code])) {
                 continue;
             }
             $message = $this->getMsgFromNamespace($this->getMessagePageName($code, $uckey), $code);
             if ($message !== false) {
                 return $message;
             }
             $alreadyTried[$code] = true;
         }
     }
     return false;
 }
Beispiel #7
0
 static function onMediaWikiPerformAction($output, $article, $title, $user, $request, $wiki)
 {
     global $wgCookiePrefix;
     global $qp_enable_showresults;
     // deprecated since v0.6.5
     global $qp_AnonForwardedFor;
     // deprecated since v0.6.5
     global $wgUser;
     self::$output = $output;
     self::$article = $article;
     self::$title = $title;
     # in MW v1.15 / v1.16 user object was stub;
     # in MW v1.19 it seems to be real object.
     # Unstub for the versions where it is stubbed.
     # Borrowed from Title::getUserPermissionsErrors() MW v1.16
     if (!StubObject::isRealObject($user)) {
         // Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
         global $wgUser;
         $wgUser->_unstub('', 5);
         $user = $wgUser;
     }
     self::$user = $user;
     self::$request = $request;
     if (isset($qp_AnonForwardedFor)) {
         self::$anon_forwarded_for = $qp_AnonForwardedFor;
     }
     # setup proper integer global showresults level
     if (isset($qp_enable_showresults)) {
         self::$global_showresults = $qp_enable_showresults;
     }
     if (!is_int(self::$global_showresults)) {
         # convert from older v0.5 boolean value
         self::$global_showresults = (int) (bool) self::$global_showresults;
     }
     if (self::$global_showresults < 0) {
         self::$global_showresults = 0;
     } elseif (self::$global_showresults > 2) {
         self::$global_showresults = 2;
     }
     if (isset($_COOKIE["{$wgCookiePrefix}QPoll"])) {
         $request->response()->setCookie('QPoll', '', time() - 86400);
         // clear cookie
         self::clearCache();
     } elseif ($request->getVal('pollId') !== null) {
         self::clearCache();
     }
     self::$propAttrs = new qp_PropAttrs();
     return true;
 }
	/**
	 * Override for preSaveTransform. Enables quick post publish by signing
	 * the article using the standard --~~~~ marker. This causes the signature
	 * marker to be replaced by a {{wl-publish:...}} parser function call,
	 * that is then saved to the database and causes the post to be published.
	 */
	public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
		global $wgParser, $wgUser;
		$user = is_null( $user ) ? $wgUser : $user;

		if ( $popts === null ) {
			$popts = ParserOptions::newFromUser( $user );
		}

		$t = WikilogUtils::getPublishParameters();
		$date_txt = $t['date'];
		$user_txt = $t['user'];

		$sigs = array(
			'/\n?(--)?~~~~~\n?/m' => "\n{{wl-publish: {$date_txt} }}\n",
			'/\n?(--)?~~~~\n?/m' => "\n{{wl-publish: {$date_txt} | {$user_txt} }}\n",
			'/\n?(--)?~~~\n?/m' => "\n{{wl-author: {$user_txt} }}\n"
		);

		if ( !StubObject::isRealObject( $wgParser ) ) {
			$wgParser->_unstub();
		}
		$wgParser->startExternalParse( $this->mTitle, $popts, Parser::OT_WIKI );

		$text = $wgParser->replaceVariables( $text );
		$text = preg_replace( array_keys( $sigs ), array_values( $sigs ), $text );
		$text = $wgParser->mStripState->unstripBoth( $text );

		return parent::preSaveTransform( $text, $user, $popts );
	}
	/**
	 * Retrieves an article parsed output either from parser cache or by
	 * parsing it again. If parsing again, stores it back into parser cache.
	 *
	 * @param $title Article title object.
	 * @param $feed Whether the result should be part of a feed.
	 * @return Two-element array containing the article and its parser output.
	 *
	 * @note Mw1.16+ provides Article::getParserOptions() and
	 *   Article::getParserOutput(), that could be used here in the future.
	 *   The problem is that getParserOutput() uses ParserCache exclusively,
	 *   which means that only ParserOptions control the key used to store
	 *   the output in the cache and there is no hook yet in
	 *   ParserCache::getKey() to set these extra bits (and the
	 *   'PageRenderingCache' hook is not useful here, it is in the wrong
	 *   place without access to the parser options). This is certainly
	 *   something that should be fixed in the future.  FIXME
	 *
	 * @note This function makes a clone of the parser if
	 *   $wgWikilogCloneParser is set, but cloning the parser is not
	 *   officially supported. The problem here is that we need a different
	 *   parser that we could mess up without interfering with normal page
	 *   rendering, and we can't create a new instance because of too many
	 *   broken extensions around. Check self::parserSanityCheck().
	 */
	public static function parsedArticle( Title $title, $feed = false ) {
		global $wgWikilogCloneParser;
		global $wgUser, $wgEnableParserCache;
		global $wgParser, $wgParserConf;

		static $parser = null;

		$article = new Article( $title );

		# First try the parser cache.
		$useParserCache = $wgEnableParserCache &&
			intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
			$article->exists();
		$parserCache = ParserCache::singleton();

		# Parser options.
		$parserOpt = ParserOptions::newFromUser( $wgUser );
		$parserOpt->setTidy( true );
		if ( $feed ) {
			$parserOpt->setEditSection( false );

			$parserOpt->addExtraKey( "WikilogFeed" );
		} else {
			$parserOpt->enableLimitReport();
		}

		if ( $useParserCache ) {
			# Look for the parsed article output in the parser cache.
			$parserOutput = $parserCache->get( $article, $parserOpt );

			# On success, return the object retrieved from the cache.
			if ( $parserOutput ) {
				return array( $article, $parserOutput );
			}
		}

		# Enable some feed-specific behavior.
		if ( $feed ) {
			$saveFeedParse = WikilogParser::enableFeedParsing();
			$saveExpUrls = WikilogParser::expandLocalUrls();
		}

		# Get a parser instance, if not already cached.
		if ( is_null( $parser ) ) {
			if ( !StubObject::isRealObject( $wgParser ) ) {
				$wgParser->_unstub();
			}
			if ( $wgWikilogCloneParser ) {
				$parser = clone $wgParser;
			} else {
				$class = $wgParserConf['class'];
				$parser = new $class( $wgParserConf );
			}
		}
		$parser->startExternalParse( $title, $parserOpt, Parser::OT_HTML );

		# Parse article.
		$arttext = $article->fetchContent();
		$parserOutput = $parser->parse( $arttext, $title, $parserOpt );

		# Save in parser cache.
		if ( $useParserCache && $parserOutput->getCacheTime() != -1 ) {
			$parserCache->save( $parserOutput, $article, $parserOpt );
		}

		# Restore default behavior.
		if ( $feed ) {
			WikilogParser::enableFeedParsing( $saveFeedParse );
			WikilogParser::expandLocalUrls( $saveExpUrls );
		}

		return array( $article, $parserOutput );
	}
Beispiel #10
0
 /**
  * Can $user perform $action on this page?
  *
  * FIXME: This *does not* check throttles (User::pingLimiter()).
  *
  * @param $action \type{\string}action that permission needs to be checked for
  * @param $user \type{User} user to check
  * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
  * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
  * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
  */
 public function getUserPermissionsErrors($action, $user, $doExpensiveQueries = true, $ignoreErrors = array())
 {
     if (!StubObject::isRealObject($user)) {
         //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
         global $wgUser;
         $wgUser->_unstub('', 5);
         $user = $wgUser;
     }
     $errors = $this->getUserPermissionsErrorsInternal($action, $user, $doExpensiveQueries);
     global $wgContLang;
     global $wgLang;
     global $wgEmailConfirmToEdit;
     if ($wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount') {
         $errors[] = array('confirmedittext');
     }
     // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
     if ($action != 'read' && $action != 'createaccount' && $user->isBlockedFrom($this)) {
         $block = $user->mBlock;
         // This is from OutputPage::blockedPage
         // Copied at r23888 by werdna
         $id = $user->blockedBy();
         $reason = $user->blockedFor();
         if ($reason == '') {
             $reason = wfMsg('blockednoreason');
         }
         $ip = wfGetIP();
         if (is_numeric($id)) {
             $name = User::whoIs($id);
         } else {
             $name = $id;
         }
         $link = '[[' . $wgContLang->getNsText(NS_USER) . ":{$name}|{$name}]]";
         $blockid = $block->mId;
         $blockExpiry = $user->mBlock->mExpiry;
         $blockTimestamp = $wgLang->timeanddate(wfTimestamp(TS_MW, $user->mBlock->mTimestamp), true);
         if ($blockExpiry == 'infinity') {
             // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
             $scBlockExpiryOptions = wfMsg('ipboptions');
             foreach (explode(',', $scBlockExpiryOptions) as $option) {
                 if (strpos($option, ':') == false) {
                     continue;
                 }
                 list($show, $value) = explode(":", $option);
                 if ($value == 'infinite' || $value == 'indefinite') {
                     $blockExpiry = $show;
                     break;
                 }
             }
         } else {
             $blockExpiry = $wgLang->timeanddate(wfTimestamp(TS_MW, $blockExpiry), true);
         }
         $intended = $user->mBlock->mAddress;
         $errors[] = array($block->mAuto ? 'autoblockedtext' : 'blockedtext', $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp);
     }
     // Remove the errors being ignored.
     foreach ($errors as $index => $error) {
         $error_key = is_array($error) ? $error[0] : $error;
         if (in_array($error_key, $ignoreErrors)) {
             unset($errors[$index]);
         }
     }
     return $errors;
 }
 function __construct()
 {
     parent::__construct('wgLang');
 }
Beispiel #12
0
/**
 * @todo document
 */
function wfLogProfilingData()
{
    global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
    global $wgProfiling, $wgUser;
    if ($wgProfiling) {
        $now = wfTime();
        $elapsed = $now - $wgRequestTime;
        $prof = wfGetProfilingOutput($wgRequestTime, $elapsed);
        $forward = '';
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
        }
        if (!empty($_SERVER['HTTP_FROM'])) {
            $forward .= ' from ' . $_SERVER['HTTP_FROM'];
        }
        if ($forward) {
            $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
        }
        // Don't unstub $wgUser at this late stage just for statistics purposes
        if (StubObject::isRealObject($wgUser) && $wgUser->isAnon()) {
            $forward .= ' anon';
        }
        $log = sprintf("%s\t%04.3f\t%s\n", gmdate('YmdHis'), $elapsed, urldecode($_SERVER['REQUEST_URI'] . $forward));
        if ('' != $wgDebugLogFile && ($wgRequest->getVal('action') != 'raw' || $wgDebugRawPage)) {
            error_log($log . $prof, 3, $wgDebugLogFile);
        }
    }
}
<?php
if ( !defined( 'MEDIAWIKI' ) ) die;

global $wgHooks, $wgParser;
if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) {
	$wgHooks['ParserFirstCallInit'][] = 'WOMOutputProcessor::smwgWTregisterParserFunctions';
} else {
	if ( class_exists( 'StubObject' ) && !StubObject::isRealObject( $wgParser ) ) {
		$wgParser->_unstub();
	}
	WOMOutputProcessor::smwgWTregisterParserFunctions( $wgParser );
}

global $wgOMOutputHookedParserFunctions;
$wgOMOutputHookedParserFunctions = array(
	'ask',
	'sparql',
);

global $wgOMIP;
require_once( $wgOMIP . '/includes/apis/WOM_OM_QueryResult.php' );

class WOMOutputProcessor {
	static function smwfProcessSPARQLQueryParserFunctionGTP( &$parser ) {
		global $smwgWebserviceEndpoint;
		if ( !isset( $smwgWebserviceEndpoint ) ) return '';

		global $smwgIQRunningNumber;
		$smwgIQRunningNumber++;
		$params = func_get_args();
		array_shift( $params ); // we already know the $parser ...
 public function getSignature($user, $timestamp)
 {
     global $wgContLang, $wgParser;
     // Force unstub
     StubObject::unstub($wgParser);
     $timestamp = MWTimestamp::getLocalInstance($timestamp);
     $ts = $timestamp->format('YmdHis');
     $tzMsg = $timestamp->format('T');
     # might vary on DST changeover!
     # Allow translation of timezones through wiki. format() can return
     # whatever crap the system uses, localised or not, so we cannot
     # ship premade translations.
     $key = 'timezone-' . strtolower(trim($tzMsg));
     $msg = wfMessage($key)->inContentLanguage();
     if ($msg->exists()) {
         $tzMsg = $msg->text();
     }
     $d = $wgContLang->timeanddate($ts, false, false) . " ({$tzMsg})";
     if ($user) {
         return $wgParser->getUserSig($user, false, false) . ' ' . $d;
     } else {
         return "[Unknown user] {$d}";
     }
 }
Beispiel #15
0
 /**
  * Given a language, try and fetch messages from that language.
  *
  * Will also consider fallbacks of that language, the site language, and fallbacks for
  * the site language.
  *
  * @see MessageCache::get
  * @param Language|StubObject $lang Preferred language
  * @param string $lckey Lowercase key for the message (as for localisation cache)
  * @param bool $useDB Whether to include messages from the wiki database
  * @return string|bool The message, or false if not found
  */
 protected function getMessageFromFallbackChain($lang, $lckey, $useDB)
 {
     global $wgLanguageCode, $wgContLang;
     $uckey = $wgContLang->ucfirst($lckey);
     $langcode = $lang->getCode();
     $message = false;
     // First try the requested language.
     if ($useDB) {
         if ($langcode === $wgLanguageCode) {
             // Messages created in the content language will not have the /lang extension
             $message = $this->getMsgFromNamespace($uckey, $langcode);
         } else {
             $message = $this->getMsgFromNamespace("{$uckey}/{$langcode}", $langcode);
         }
     }
     if ($message !== false) {
         return $message;
     }
     // Check the CDB cache
     $message = $lang->getMessage($lckey);
     if ($message !== null) {
         return $message;
     }
     list($fallbackChain, $siteFallbackChain) = Language::getFallbacksIncludingSiteLanguage($langcode);
     // Next try checking the database for all of the fallback languages of the requested language.
     if ($useDB) {
         foreach ($fallbackChain as $code) {
             if ($code === $wgLanguageCode) {
                 // Messages created in the content language will not have the /lang extension
                 $message = $this->getMsgFromNamespace($uckey, $code);
             } else {
                 $message = $this->getMsgFromNamespace("{$uckey}/{$code}", $code);
             }
             if ($message !== false) {
                 // Found the message.
                 return $message;
             }
         }
     }
     // Now try checking the site language.
     if ($useDB) {
         $message = $this->getMsgFromNamespace($uckey, $wgLanguageCode);
         if ($message !== false) {
             return $message;
         }
     }
     $message = $wgContLang->getMessage($lckey);
     if ($message !== null) {
         return $message;
     }
     // Finally try the DB for the site language's fallbacks.
     if ($useDB) {
         foreach ($siteFallbackChain as $code) {
             $message = $this->getMsgFromNamespace("{$uckey}/{$code}", $code);
             if ($message === false && $code === $wgLanguageCode) {
                 // Messages created in the content language will not have the /lang extension
                 $message = $this->getMsgFromNamespace($uckey, $code);
             }
             if ($message !== false) {
                 // Found the message.
                 return $message;
             }
         }
     }
     return false;
 }
Beispiel #16
0
 /**
  * Check if user account is hidden
  *
  * @return bool True if hidden, false otherwise
  */
 public function isHidden()
 {
     if ($this->mHideName !== null) {
         return $this->mHideName;
     }
     $this->getBlockedStatus();
     if (!$this->mHideName) {
         global $wgAuth;
         StubObject::unstub($wgAuth);
         $authUser = $wgAuth->getUserInstance($this);
         $this->mHideName = (bool) $authUser->isHidden();
     }
     return $this->mHideName;
 }
function wfSetupParserFunctions()
{
    global $wgParser, $wgExtParserFunctions, $wgHooks;
    $wgExtParserFunctions = new ExtParserFunctions();
    // Check for SFH_OBJECT_ARGS capability
    /* DISABLED FOR GREAT S***E (DOESN'T F*****G WERK!!!) --Misza
    	if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) {
    		$wgHooks['ParserFirstCallInit'][] = array( &$wgExtParserFunctions, 'registerParser' );
    	} else {
    	*/
    if (class_exists('StubObject') && !StubObject::isRealObject($wgParser)) {
        $wgParser->_unstub();
    }
    $wgExtParserFunctions->registerParser($wgParser);
    //}
    $wgHooks['ParserClearState'][] = array(&$wgExtParserFunctions, 'clearState');
    $wgHooks['ParserAfterTidy'][] = array(&$wgExtParserFunctions, 'afterTidy');
}
Beispiel #18
0
 function __construct($name, $realValue, $version = false)
 {
     parent::__construct($name);
     $this->mRealValue = $realValue;
     $this->mVersion = $version;
 }
Beispiel #19
0
/**
 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
 * In normal operation this is a NOP.
 *
 * Controlling globals:
 * $wgDebugLogFile - points to the log file
 * $wgProfileOnly - if set, normal debug messages will not be recorded.
 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
 *
 * @param $text String
 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
 */
function wfDebug($text, $logonly = false)
{
    global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
    global $wgDebugLogPrefix, $wgShowDebug;
    static $recursion = 0;
    static $cache = array();
    // Cache of unoutputted messages
    $text = wfDebugTimer() . $text;
    # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
    if (isset($_GET['action']) && $_GET['action'] == 'raw' && !$wgDebugRawPage) {
        return;
    }
    if (($wgDebugComments || $wgShowDebug) && !$logonly) {
        $cache[] = $text;
        if (!isset($wgOut)) {
            return;
        }
        if (!StubObject::isRealObject($wgOut)) {
            if ($recursion) {
                return;
            }
            $recursion++;
            $wgOut->_unstub();
            $recursion--;
        }
        // add the message and possible cached ones to the output
        array_map(array($wgOut, 'debug'), $cache);
        $cache = array();
    }
    if ($wgDebugLogFile != '' && !$wgProfileOnly) {
        # Strip unprintables; they can switch terminal modes when binary data
        # gets dumped, which is pretty annoying.
        $text = preg_replace('![\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f]!', ' ', $text);
        $text = $wgDebugLogPrefix . $text;
        wfErrorLog($text, $wgDebugLogFile);
    }
}
Beispiel #20
0
 function __construct()
 {
     parent::__construct('wgUser');
 }
Beispiel #21
0
 function getRawText()
 {
     global $wgUser, $wgOut, $wgRequest;
     if ($this->mGen) {
         $sk = $wgUser->getSkin();
         if (!StubObject::isRealObject($wgOut)) {
             $wgOut->_unstub(2);
         }
         $sk->initPage($wgOut);
         if ($this->mGen == 'css') {
             return $sk->generateUserStylesheet();
         } else {
             if ($this->mGen == 'js') {
                 return $sk->generateUserJs();
             }
         }
     } else {
         return $this->getArticleText();
     }
 }
Beispiel #22
0
 /**
  * Constructor
  * @param User $user
  * @param Language $lang
  */
 public function __construct($user = null, $lang = null)
 {
     if ($user === null) {
         global $wgUser;
         if ($wgUser === null) {
             $user = new User();
         } else {
             $user = $wgUser;
         }
     }
     if ($lang === null) {
         global $wgLang;
         if (!StubObject::isRealObject($wgLang)) {
             $wgLang->_unstub();
         }
         $lang = $wgLang;
     }
     $this->initialiseFromUser($user, $lang);
 }
/**
 * @todo document
 */
function wfLogProfilingData()
{
    global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
    global $wgProfiler, $wgProfileLimit, $wgUser;
    # Profiling must actually be enabled...
    if (!isset($wgProfiler)) {
        return;
    }
    # Get total page request time
    $now = wfTime();
    $elapsed = $now - $wgRequestTime;
    # Only show pages that longer than $wgProfileLimit time (default is 0)
    if ($elapsed <= $wgProfileLimit) {
        return;
    }
    $prof = wfGetProfilingOutput($wgRequestTime, $elapsed);
    $forward = '';
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
    }
    if (!empty($_SERVER['HTTP_FROM'])) {
        $forward .= ' from ' . $_SERVER['HTTP_FROM'];
    }
    if ($forward) {
        $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
    }
    // Don't unstub $wgUser at this late stage just for statistics purposes
    if (StubObject::isRealObject($wgUser) && $wgUser->isAnon()) {
        $forward .= ' anon';
    }
    $log = sprintf("%s\t%04.3f\t%s\n", gmdate('YmdHis'), $elapsed, urldecode($wgRequest->getRequestURL() . $forward));
    if ('' != $wgDebugLogFile && ($wgRequest->getVal('action') != 'raw' || $wgDebugRawPage)) {
        wfErrorLog($log . $prof, $wgDebugLogFile);
    }
}