public static function onSetupAfterCache()
 {
     global $wgUploadDirectory, $wgUploadBaseUrl, $wgUploadPath, $wgHashedUploadDirectory, $wgThumbnailScriptPath, $wgGenerateThumbnailOnParse, $wgLocalFileRepo, $wgDeletedDirectory;
     $wgLocalFileRepo = array('class' => 'WikiaLocalRepo', 'name' => 'local', 'directory' => $wgUploadDirectory, 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath, 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0, 'thumbScriptUrl' => $wgThumbnailScriptPath, 'transformVia404' => !$wgGenerateThumbnailOnParse, 'deletedDir' => $wgDeletedDirectory, 'deletedHashLevels' => $wgLocalFileRepo['deletedHashLevels'], 'backend' => 'local-backend');
     wfRunHooks('AfterSetupLocalFileRepo', [&$wgLocalFileRepo]);
     return true;
 }
 function execute($par)
 {
     global $wgRequest, $wgUser, $wgOut, $wgSessionStarted;
     if (!$wgSessionStarted) {
         $wgUser->SetupSession();
     }
     $this->setHeaders();
     if ($wgUser->getID() != 0) {
         $this->templateAlreadyLoggedIn();
         return;
     }
     $facebook = new Facebook(MEDIAWIKI_AUTHFACEBOOK_APIKEY, MEDIAWIKI_AUTHFACEBOOK_SECRET);
     if (!$facebook) {
         $wgOut->errorpage('authfacebookrror', 'authfacebookerrortext');
         return;
     }
     $auth_token = $wgRequest->getText('auth_token');
     if (!$auth_token) {
         $this->templateDefaultPage();
         return;
     }
     try {
         $session_response = $facebook->api_client->auth_getSession($auth_token);
     } catch (Exception $e) {
         $this->templateDefaultPage('There was an error, please refresh the page and try again.');
         error_log($e);
         return;
     }
     $session_key = $session_response['session_key'];
     $session_expires = $session_response['expires'];
     $fb_userid = $session_response['uid'];
     try {
         $userinfo_response = $facebook->api_client->users_getInfo(array($fb_userid), array('name'));
     } catch (Exception $e) {
         $this->templateDefaultPage('There was an error, please refresh the page and try again.');
         error_log($e);
         return;
     }
     $fb_username = $userinfo_response[0]['name'];
     $user = $this->getUserFromFB($fb_userid);
     if (isset($user)) {
         $this->updateUser($fb_userid, $session_key, $session_expires, $fb_username);
     } else {
         # For easy names
         $name = $this->createName($fb_username);
         if ($name) {
             $user = $this->createUser($fb_userid, $fb_username, $session_key, $session_expires);
         }
     }
     if (!isset($user)) {
         $wgOut->errorpage('authfacebookrror', 'authfacebookerrortext');
     } else {
         $wgUser = $user;
         $wgUser->SetupSession();
         $wgUser->SetCookies();
         wfRunHooks('UserLoginComplete', array(&$wgUser));
         $this->setLoginCookie($fb_userid, $session_expires);
         $this->templateLoggedInPage();
     }
 }
 public function buildData()
 {
     global $wgUser, $wgTitle;
     $page = SpecialPageFactory::getPage($this->name);
     if (!is_object($page)) {
         $this->buildExternalData();
         // BugId:22989 - we don't want the PageLayoutBuilder to be shown if disabled.
         if ('LayoutBuilder' == $this->name) {
             // do not show PLB if it's not available on the wiki
             $this->available = $this->enabled;
         }
         return;
     }
     $this->available = true;
     $this->enabled = $page->userCanExecute($wgUser);
     $this->caption = $page->getDescription();
     $this->description = $page->getDescription();
     $this->href = $page->getTitle()->getLocalUrl();
     switch ($this->name) {
         case 'RecentChangesLinked':
             $this->href .= '/' . $wgTitle->getPartialUrl();
             break;
         case 'Contributions':
             $this->href .= '/' . $wgUser->getTitleKey();
             break;
     }
     $specialPageName = $page->getName();
     $options = array();
     wfRunHooks("UserCommand::SpecialPage::{$specialPageName}", array($this, &$options));
     foreach ($options as $k => $v) {
         $this->{$k} = $v;
     }
 }
 public static function ArticleCommentCheck($title = null)
 {
     global $wgRequest, $wgUser;
     wfProfileIn(__METHOD__);
     if ($title === null) {
         global $wgTitle;
         $title = $wgTitle;
     }
     if (is_null(self::$enable) && !empty($title)) {
         self::$enable = self::ArticleCommentCheckTitle($title);
         if (self::$enable && !is_null($wgRequest->getVal('diff'))) {
             self::$enable = false;
         }
         $action = $wgRequest->getVal('action', 'view');
         if (self::$enable && $action == 'purge' && $wgUser->isAnon() && !$wgRequest->wasPosted()) {
             self::$enable = false;
         }
         if (self::$enable && $action != 'view' && $action != 'purge') {
             self::$enable = false;
         }
         if (self::$enable && !wfRunHooks('ArticleCommentCheck', array($title))) {
             self::$enable = false;
         }
     }
     wfProfileOut(__METHOD__);
     return self::$enable;
 }
 public static function format_position($aConfig, $sNewId)
 {
     $aReturn = "";
     if ($aConfig->navigation == 'right') {
         $aReturn[] = "#bs-application{position: relative;}";
         $aReturn[] = "#bs-content-column{margin: 0 302px 0 0;}";
         $aReturn[] = "#bs-nav-sections{right: 0; top: 30px;}";
         $aReturn[] = "#footer{margin: 0px 302px 5px 0px}";
     }
     if ($aConfig->content != 'center') {
         $aReturn[] = "#bs-wrapper{margin-" . $aConfig->content . ":0;}";
     }
     if ($aConfig->fullWidth == 0) {
         $aReturn[] = "#bs-menu-top{width:" . (int) $aConfig->width . "px;}";
         $aReturn[] = "#bs-application{width:" . (int) $aConfig->width . "px;}";
         $aReturn[] = "#bs-wrapper{width:" . (int) $aConfig->width . "px;min-width:" . (int) $aConfig->width . "px;}";
         //$aReturn[] = "#bs-tools-container{width:" . ((int) $aConfig->width - 200 + 28) . "px;margin-left:-" . ((int) $aConfig->width - 246) . "px}";
     } else {
         $aReturn[] = "#bs-menu-top{width:100%;}";
         $aReturn[] = "#bs-application{width:100%;}";
         $aReturn[] = "#bs-wrapper{width:100%;min-width:100%;}";
     }
     wfRunHooks("BSFlexiskinFormatterPosition", array(&$aConfig, &$aReturn));
     return implode(" \n", $aReturn);
 }
 protected function getConfig($context)
 {
     global $wgLoadScript;
     $vars = array('wgLoadScript' => $wgLoadScript, 'debug' => $context->getDebug(), 'skin' => $context->getSkin(), 'wgUserLanguage' => $context->getLanguage());
     wfRunHooks('ResourceLoaderGetConfigVars', array(&$vars));
     return $vars;
 }
Example #7
0
 /**
  * @see Content::replaceSection()
  */
 public function replaceSection($section, Content $with, $sectionTitle = '')
 {
     wfProfileIn(__METHOD__);
     $myModelId = $this->getModel();
     $sectionModelId = $with->getModel();
     if ($sectionModelId != $myModelId) {
         wfProfileOut(__METHOD__);
         throw new MWException("Incompatible content model for section: " . "document uses {$myModelId} but " . "section uses {$sectionModelId}.");
     }
     $oldtext = $this->getNativeData();
     $text = $with->getNativeData();
     if ($section === '') {
         wfProfileOut(__METHOD__);
         return $with;
         # XXX: copy first?
     }
     if ($section == 'new') {
         # Inserting a new section
         $subject = $sectionTitle ? wfMessage('newsectionheaderdefaultlevel')->rawParams($sectionTitle)->inContentLanguage()->text() . "\n\n" : '';
         if (wfRunHooks('PlaceNewSection', array($this, $oldtext, $subject, &$text))) {
             $text = strlen(trim($oldtext)) > 0 ? "{$oldtext}\n\n{$subject}{$text}" : "{$subject}{$text}";
         }
     } else {
         # Replacing an existing section; roll out the big guns
         global $wgParser;
         $text = $wgParser->replaceSection($oldtext, $section, $text);
     }
     $newContent = new WikitextContent($text);
     wfProfileOut(__METHOD__);
     return $newContent;
 }
function AssetsManagerEntryPoint()
{
    global $wgRequest;
    AssetsManagerServer::serve($wgRequest);
    wfRunHooks('RestInPeace');
    exit;
}
 protected function parseFormData()
 {
     global $wgRequest;
     wfRunHooks('BlogsAlternateEdit', array(false));
     $this->mFormData['postBody'] = $wgRequest->getVal('wpTextbox1');
     $this->mFormData['postTitle'] = $wgRequest->getVal('postTitle');
     $this->mFormData['postEditSummary'] = $wgRequest->getVal('wpSummary');
     $this->mFormData['postCategories'] = $wgRequest->getVal('wpCategoryTextarea1');
     $postBody = trim($this->mFormData['postBody']);
     if (empty($postBody)) {
         $this->mFormErrors[] = wfMsg('createpage_empty_article_body_error');
     }
     if (empty($this->mFormData['postTitle'])) {
         $this->mFormErrors[] = wfMsg('createpage_empty_title_error');
     } else {
         $oPostTitle = Title::newFromText($this->mFormData['postTitle'], NS_MAIN);
         if (!$oPostTitle instanceof Title) {
             $this->mFormErrors[] = wfMsg('createpage_invalid_title_error');
         } else {
             $sFragment = $oPostTitle->getFragment();
             if (strlen($sFragment) > 0) {
                 $this->mFormErrors[] = wfMsg('createpage_invalid_title_error');
             } else {
                 $this->mPostArticle = new Article($oPostTitle, 0);
                 if ($this->mPostArticle->exists()) {
                     $this->mFormErrors[] = wfMsg('createpage_article_already_exists');
                 }
             }
         }
     }
     parent::parseFormData();
 }
Example #10
0
 /**
  * Loads skin and user CSS files.
  * @param OutputPage $out
  */
 function setupSkinUserCss(OutputPage $out)
 {
     parent::setupSkinUserCss($out);
     $styles = array('skins.libre.styles');
     wfRunHooks('SkinLibreStyleModules', array($this, &$styles));
     $out->addModuleStyles($styles);
 }
Example #11
0
 /**
  * Does update. First deletes, then inserts.
  * @param $data
  */
 function updateData(SMWSemanticData $data)
 {
     $export = SMWExporter::makeExportData($data);
     $sparqlDeleteText = "";
     $sparqlUpdateText = "INSERT DATA {\n";
     // let other extensions add additional RDF data for this page (i.e. Semantic Internal Objects)
     //this code is based on the modifications made on SemanticMediaWiki/includes/export/SMW_OWLExport.php
     $additionalDataArray = array();
     $fullexport = true;
     $backlinks = false;
     wfRunHooks('smwAddToRDFExport', array($data->getSubject()->getTitle(), &$additionalDataArray, $fullexport, $backlinks));
     // this writes update text for each of the Semantic Internal Objects
     foreach ($additionalDataArray as $additionalData) {
         $subject_uri = SMWExporter::expandURI($additionalData->getSubject()->getName());
         // remove subject from triple store
         $sparqlDeleteText .= $this->writeDeleteText($subject_uri);
         //add new data associated with internal objects
         $sparqlUpdateText .= $this->writeUpdateText($additionalData->getTripleList());
     }
     $subject_uri = SMWExporter::expandURI($export->getSubject()->getName());
     // remove subject from triple store
     $sparqlDeleteText .= $this->writeDeleteText($subject_uri);
     $triple_list = $export->getTripleList();
     $sparqlUpdateText .= $this->writeUpdateText($triple_list);
     $sparqlUpdateText .= "}";
     //delete the old triples
     wfDebugLog('SPARQL_LOG', "#===DELETE===\n" . $sparqlDeleteText);
     $response = $this->do_joseki_post($sparqlDeleteText);
     //insert the new triples
     wfDebugLog('SPARQL_LOG', "#===INSERT===\n" . $sparqlUpdateText);
     $response = $this->do_joseki_post($sparqlUpdateText);
     //can the delete and insert statements be combined, or will this lead to concurrency issues?
     return parent::updateData($data);
 }
 public function execute()
 {
     global $wgUser;
     $params = $this->extractRequestParams();
     $page = Title::newFromText($params['page']);
     if (!$page) {
         throw new MWApiGetMarkAsHelpfulItemInvalidPageException('Invalid page!');
     }
     // check if current user has permission to mark the item,
     $isAbleToMark = false;
     // check if the page has permission to request the item
     $isAbleToShow = false;
     wfRunHooks('onMarkItemAsHelpful', array($params['type'], $params['item'], $wgUser, &$isAbleToMark, $page, &$isAbleToShow));
     if ($isAbleToShow) {
         $HelpfulUserList = MarkAsHelpfulItem::getMarkAsHelpfulList($params['type'], $params['item']);
         if ($params['prop'] == 'metadata') {
             $data = $HelpfulUserList;
             $format = 'metadata';
         } else {
             $data = MarkAsHelpfulUtil::getMarkAsHelpfulTemplate($wgUser, $isAbleToMark, $HelpfulUserList, $params['type'], $params['item']);
             $format = 'formatted';
         }
     } else {
         $data = '';
         if ($params['prop'] == 'metadata') {
             $format = 'metadata';
         } else {
             $format = 'formatted';
         }
     }
     $result = array('result' => 'success', $format => $data);
     $this->getResult()->addValue(null, $this->getModuleName(), $result);
 }
 /**
  * AjaxAddScript hook
  * Adds scripts
  */
 public static function addResources($out)
 {
     global $wgExtensionAssetsPath, $wgJsMimeType;
     global $wgUsabilityInitiativeResourceMode;
     global $wgEnableJS2system, $wgEditToolbarRunTests;
     global $wgStyleVersion;
     wfRunHooks('UsabilityInitiativeLoadModules');
     if (!self::$doOutput) {
         return true;
     }
     // Default to raw
     $mode = $wgUsabilityInitiativeResourceMode;
     // Just an alias
     if (!isset(self::$scriptFiles['base_sets'][$mode])) {
         $mode = 'raw';
     }
     // Include base-set of scripts
     self::$scripts = array_merge(self::$scriptFiles['base_sets'][$mode], self::$scriptFiles['modules'][$mode], self::$scripts);
     // Provide enough support to make things work, even when js2 is not
     // in use (eventually it will be standard, but right now it's not)
     if (!$wgEnableJS2system) {
         $out->includeJQuery();
     }
     // Include base-set of styles
     self::$styles = array_merge(self::$styleFiles['base_sets'][$mode], self::$styles);
     if ($wgEditToolbarRunTests) {
         // Include client side tests
         self::$scripts = array_merge(self::$scripts, self::$scriptFiles['tests']);
     }
     // Loops over each script
     foreach (self::$scripts as $script) {
         // Add javascript to document
         if ($script['src'][0] == '/') {
             // Path is relative to $wgScriptPath
             global $wgScriptPath;
             $src = "{$wgScriptPath}{$script['src']}";
         } else {
             // Path is relative to $wgExtensionAssetsPath
             $src = "{$wgExtensionAssetsPath}/UsabilityInitiative/{$script['src']}";
         }
         $version = isset($script['version']) ? $script['version'] : $wgStyleVersion;
         $out->addScriptFile($src, $version);
     }
     // Transforms messages into javascript object members
     foreach (self::$messages as $i => $message) {
         $escapedMessageValue = Xml::escapeJsString(wfMsg($message));
         $escapedMessageKey = Xml::escapeJsString($message);
         self::$messages[$i] = "'{$escapedMessageKey}':'{$escapedMessageValue}'";
     }
     // Add javascript to document
     if (count(self::$messages) > 0) {
         $out->addScript(Xml::tags('script', array('type' => $wgJsMimeType), 'mw.usability.addMessages({' . implode(',', self::$messages) . '});'));
     }
     // Loops over each style
     foreach (self::$styles as $style) {
         // Add css for various styles
         $out->addLink(array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => $wgExtensionAssetsPath . "/UsabilityInitiative/" . "{$style['src']}?{$style['version']}"));
     }
     return true;
 }
 /**
  * @param ResourceLoaderContext $context
  * @return array
  */
 protected function getConfigSettings($context)
 {
     $hash = $context->getHash();
     if (isset($this->configVars[$hash])) {
         return $this->configVars[$hash];
     }
     global $wgContLang;
     $mainPage = Title::newMainPage();
     /**
      * Namespace related preparation
      * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
      * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
      */
     $namespaceIds = $wgContLang->getNamespaceIds();
     $caseSensitiveNamespaces = array();
     foreach (MWNamespace::getCanonicalNamespaces() as $index => $name) {
         $namespaceIds[$wgContLang->lc($name)] = $index;
         if (!MWNamespace::isCapitalized($index)) {
             $caseSensitiveNamespaces[] = $index;
         }
     }
     $conf = $this->getConfig();
     // Build list of variables
     $vars = array('wgLoadScript' => wfScript('load'), 'debug' => $context->getDebug(), 'skin' => $context->getSkin(), 'stylepath' => $conf->get('StylePath'), 'wgUrlProtocols' => wfUrlProtocols(), 'wgArticlePath' => $conf->get('ArticlePath'), 'wgScriptPath' => $conf->get('ScriptPath'), 'wgScriptExtension' => $conf->get('ScriptExtension'), 'wgScript' => wfScript(), 'wgSearchType' => $conf->get('SearchType'), 'wgVariantArticlePath' => $conf->get('VariantArticlePath'), 'wgActionPaths' => (object) $conf->get('ActionPaths'), 'wgServer' => $conf->get('Server'), 'wgServerName' => $conf->get('ServerName'), 'wgUserLanguage' => $context->getLanguage(), 'wgContentLanguage' => $wgContLang->getCode(), 'wgVersion' => $conf->get('Version'), 'wgEnableAPI' => $conf->get('EnableAPI'), 'wgEnableWriteAPI' => $conf->get('EnableWriteAPI'), 'wgMainPageTitle' => $mainPage->getPrefixedText(), 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(), 'wgNamespaceIds' => $namespaceIds, 'wgContentNamespaces' => MWNamespace::getContentNamespaces(), 'wgSiteName' => $conf->get('Sitename'), 'wgFileExtensions' => array_values(array_unique($conf->get('FileExtensions'))), 'wgDBname' => $conf->get('DBname'), 'wgFileCanRotate' => SpecialUpload::rotationEnabled(), 'wgAvailableSkins' => Skin::getSkinNames(), 'wgExtensionAssetsPath' => $conf->get('ExtensionAssetsPath'), 'wgCookiePrefix' => $conf->get('CookiePrefix'), 'wgCookieDomain' => $conf->get('CookieDomain'), 'wgCookiePath' => $conf->get('CookiePath'), 'wgCookieExpiration' => $conf->get('CookieExpiration'), 'wgResourceLoaderMaxQueryLength' => $conf->get('ResourceLoaderMaxQueryLength'), 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces, 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass(Title::legalChars()), 'wgResourceLoaderStorageVersion' => $conf->get('ResourceLoaderStorageVersion'), 'wgResourceLoaderStorageEnabled' => $conf->get('ResourceLoaderStorageEnabled'));
     wfRunHooks('ResourceLoaderGetConfigVars', array(&$vars));
     $this->configVars[$hash] = $vars;
     return $this->configVars[$hash];
 }
Example #15
0
 /**
  * @throws MWException
  * @param string $collationName
  * @return Collation
  */
 static function factory($collationName)
 {
     switch ($collationName) {
         case 'uppercase':
             return new UppercaseCollation();
         case 'identity':
             return new IdentityCollation();
         case 'uca-default':
             return new IcuCollation('root');
         case 'xx-uca-ckb':
             return new CollationCkb();
         case 'xx-uca-et':
             return new CollationEt();
         default:
             $match = array();
             if (preg_match('/^uca-([a-z@=-]+)$/', $collationName, $match)) {
                 return new IcuCollation($match[1]);
             }
             # Provide a mechanism for extensions to hook in.
             $collationObject = null;
             wfRunHooks('Collation::factory', array($collationName, &$collationObject));
             if ($collationObject instanceof Collation) {
                 return $collationObject;
             }
             // If all else fails...
             throw new MWException(__METHOD__ . ": unknown collation type \"{$collationName}\"");
     }
 }
 protected function getMessageInfo()
 {
     $msgKeys = array();
     // Messages that just require simple parsing
     $msgArgs = array('minoredit' => array('minoredit'), 'missingsummary' => array('missingsummary'), 'summary' => array('summary'), 'watchthis' => array('watchthis'), 'visualeditor-browserwarning' => array('visualeditor-browserwarning'), 'visualeditor-wikitext-warning' => array('visualeditor-wikitext-warning'));
     // Override message value
     $msgVals = array('visualeditor-feedback-link' => wfMessage('visualeditor-feedback-link')->inContentLanguage()->text());
     // Copyright warning (based on EditPage::getCopyrightWarning)
     $rightsText = $this->config->get('RightsText');
     if ($rightsText) {
         $copywarnMsg = array('copyrightwarning', '[[' . wfMessage('copyrightpage')->inContentLanguage()->text() . ']]', $rightsText);
     } else {
         $copywarnMsg = array('copyrightwarning2', '[[' . wfMessage('copyrightpage')->inContentLanguage()->text() . ']]');
     }
     // EditPage supports customisation based on title, we can't support that here
     // since these messages are cached on a site-level. $wgTitle is likely set to null.
     $title = Title::newFromText('Dwimmerlaik');
     wfRunHooks('EditPageCopyrightWarning', array($title, &$copywarnMsg));
     // Keys used in copyright warning
     $msgKeys[] = 'copyrightpage';
     $msgKeys[] = $copywarnMsg[0];
     // Normalise to 'copyrightwarning' so we have a consistent key in the front-end.
     $msgArgs['copyrightwarning'] = $copywarnMsg;
     // Citation tools
     $msgVals['visualeditor-cite-tool-definition.json'] = json_encode(self::getCitationTools());
     $msgKeys = array_values(array_unique(array_merge($msgKeys, array_keys($msgArgs), array_keys($msgVals))));
     return array('keys' => $msgKeys, 'args' => $msgArgs, 'vals' => $msgVals);
 }
Example #17
0
 function execute($par)
 {
     /**
      * Some satellite ISPs use broken precaching schemes that log people out straight after
      * they're logged in (bug 17790). Luckily, there's a way to detect such requests.
      */
     if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '&') !== false) {
         wfDebug("Special:Userlogout request {$_SERVER['REQUEST_URI']} looks suspicious, denying.\n");
         throw new HttpError(400, wfMessage('suspicious-userlogout'), wfMessage('loginerror'));
     }
     $this->setHeaders();
     $this->outputHeader();
     $user = $this->getUser();
     $oldName = $user->getName();
     $user->logout();
     $out = $this->getOutput();
     $out->addWikiMsg('logouttext');
     // Hook.
     $injected_html = '';
     wfRunHooks('UserLogoutComplete', array(&$user, &$injected_html, $oldName));
     $out->addHTML($injected_html);
     $mReturnTo = $this->getRequest()->getVal('returnto');
     $mReturnToQuery = $this->getRequest()->getVal('returntoquery');
     $title = Title::newFromText($mReturnTo);
     if (!empty($title)) {
         $mResolvedReturnTo = strtolower(array_shift(SpecialPageFactory::resolveAlias($title->getDBKey())));
         if (in_array($mResolvedReturnTo, array('userlogout', 'signup', 'connect'))) {
             $titleObj = Title::newMainPage();
             $mReturnTo = $titleObj->getText();
             $mReturnToQuery = '';
         }
     }
     $out->returnToMain(false, $mReturnTo, $mReturnToQuery);
 }
Example #18
0
 /**
 		Returns index in pattern array of *first* pattern match.
 		
 		@param: patternArrayName:	variable name (found in PageFunctions extension) 
 		@param: input:				input string to regex match
 */
 public function mg_regx_vars(&$parser, &$patternArrayName, &$input)
 {
     // the worst that can happen is that no valid return values are received.
     wfRunHooks('PageVarGet', array(&$patternArrayName, &$parray));
     $mIndex = self::regexMatchArray($parray, $input);
     return $mIndex;
 }
 /**
  * Show a global usage section on the image page
  *
  * @param object $imagePage The ImagePage
  * @param string $html HTML to add to the image page as global usage section
  * @return bool
  */
 public static function onImagePageAfterImageLinks($imagePage, &$html)
 {
     if (!self::hasResults($imagePage)) {
         return true;
     }
     $title = $imagePage->getFile()->getTitle();
     $targetName = $title->getText();
     $query = self::getImagePageQuery($title);
     $guHtml = '';
     foreach ($query->getSingleImageResult() as $wiki => $result) {
         $wikiName = WikiMap::getWikiName($wiki);
         $escWikiName = Sanitizer::escapeClass($wikiName);
         /* Wikia change begin */
         wfRunHooks('GlobalUsageImagePageWikiLink', array(&$wikiName));
         /* Wikia change end */
         $guHtml .= "<li class='mw-gu-onwiki-{$escWikiName}'>" . wfMsgExt('globalusage-on-wiki', 'parseinline', $targetName, $wikiName) . "\n<ul>";
         foreach ($result as $item) {
             $guHtml .= "\t<li>" . SpecialGlobalUsage::formatItem($item) . "</li>\n";
         }
         $guHtml .= "</ul></li>\n";
     }
     if ($guHtml) {
         $html .= '<h2 id="globalusage">' . wfMsgHtml('globalusage') . "</h2>\n" . '<div id="mw-imagepage-section-globalusage">' . wfMsgExt('globalusage-of-file', 'parse') . "<ul>\n" . $guHtml . "</ul>\n";
         if ($query->hasMore()) {
             $html .= wfMsgExt('globalusage-more', 'parse', $targetName);
         }
         $html .= '</div>';
     }
     return true;
 }
Example #20
0
 /**
  * Does update. First deletes, then inserts.
  * @param $data
  */
 function updateData(SMWSemanticData $data)
 {
     $export = SMWExporter::makeExportData($data);
     // let other extensions add additional RDF data for this page (i.e. Semantic Internal Objects)
     //this code is based on the modifications made on SemanticMediaWiki/includes/export/SMW_OWLExport.php
     $additionalDataArray = array();
     $fullexport = true;
     $backlinks = false;
     wfRunHooks('smwAddToRDFExport', array($data->getSubject()->getTitle(), &$additionalDataArray, $fullexport, $backlinks));
     $addStatements = array();
     foreach ($additionalDataArray as $additionalData) {
         //add new data associated with internal objects
         $addStatements = $this->createStatements($additionalData->getTripleList());
     }
     $subject_uri = SMWExporter::expandURI($export->getSubject()->getName());
     $this->removeDataForURI($subject_uri);
     $triple_list = $export->getTripleList();
     $addStatements = array_merge($addStatements, $this->createStatements($export->getTripleList()));
     // create a transaction to execute the updates
     $statements = array('add' => $addStatements);
     $transaction = $this->createTransaction($statements);
     $response = $this->sendTransaction($transaction);
     //can the delete and insert statements be combined, or will this lead to concurrency issues?
     return parent::updateData($data);
 }
 /**
  * Get variables values
  *
  * @return object key / value list variables
  */
 private function getVariablesValues()
 {
     global $wgInstantGlobalsOverride;
     if (!empty($wgInstantGlobalsOverride) && is_array($wgInstantGlobalsOverride)) {
         $override = $wgInstantGlobalsOverride;
     } else {
         $override = [];
     }
     $ret = [];
     $variables = [];
     wfRunHooks('InstantGlobalsGetVariables', [&$variables]);
     foreach ($variables as $name) {
         // Use the value on community but override with the $wgInstantGlobalsOverride
         if (array_key_exists($name, $override)) {
             $value = $override[$name];
         } else {
             $value = WikiFactory::getVarValueByName($name, Wikia::COMMUNITY_WIKI_ID);
         }
         // don't emit "falsy" values
         if (!empty($value)) {
             $ret[$name] = $value;
         }
     }
     return (object) $ret;
 }
Example #22
0
 public function doPostCommitUpdates()
 {
     $this->title->purgeSquid();
     // Extensions that require referencing previous revisions may need this
     wfRunHooks('ArticleRevisionVisibilitySet', array(&$this->title));
     return Status::newGood();
 }
 /**
  * @param $langCode string
  * @return array
  * @throws MWException
  */
 private static function getFeedsInternal($langCode)
 {
     global $wgFeaturedFeeds, $wgFeaturedFeedsDefaults, $wgContLang;
     wfProfileIn(__METHOD__);
     $feedDefs = $wgFeaturedFeeds;
     wfRunHooks('FeaturedFeeds::getFeeds', array(&$feedDefs));
     // fill defaults
     foreach ($feedDefs as $name => $opts) {
         foreach ($wgFeaturedFeedsDefaults as $setting => $value) {
             if (!isset($opts[$setting])) {
                 $feedDefs[$name][$setting] = $value;
             }
         }
     }
     $feeds = array();
     $requestedLang = Language::factory($langCode);
     $parser = new Parser();
     foreach ($feedDefs as $name => $opts) {
         $feed = new FeaturedFeedChannel($name, $opts, $requestedLang);
         if (!$feed->isOK()) {
             continue;
         }
         $feed->getFeedItems();
         $feeds[$name] = $feed;
     }
     wfProfileOut(__METHOD__);
     return $feeds;
 }
 public function buildData()
 {
     global $wgUser, $wgTitle;
     $page = SpecialPageFactory::getPage($this->name);
     if (!is_object($page)) {
         $this->buildExternalData();
         return;
     }
     $this->available = true;
     $this->enabled = $page->userCanExecute($wgUser);
     $this->caption = $page->getDescription();
     $this->description = $page->getDescription();
     $this->href = $page->getTitle()->getLocalUrl();
     switch ($this->name) {
         case 'RecentChangesLinked':
             $this->href .= '/' . $wgTitle->getPartialUrl();
             break;
         case 'Contributions':
             $this->href .= '/' . $wgUser->getTitleKey();
             break;
     }
     $specialPageName = $page->getName();
     $options = array();
     wfRunHooks("UserCommand::SpecialPage::{$specialPageName}", array($this, &$options));
     foreach ($options as $k => $v) {
         $this->{$k} = $v;
     }
 }
function efStompTest($input, $args, &$parser)
{
    $parser->disableCache();
    $output = "STOMP Test page";
    wfRunHooks('gwStomp', array(&$transaction));
    return $output;
}
 /**
  *
  * @param string $name
  * @param int $amount
  * @return boolean false if failed
  */
 private function credit($name = null, $amount = 0)
 {
     $output = $this->getOutput();
     $output->addWikiText("=== Credit (name, amount) ===");
     $output->addWikiText("name = {$name}");
     $output->addWikiText("amount = {$amount}");
     $user = User::newFromName($name);
     if (!$user || $user->getId() == 0) {
         $output->addWikiText("=== ERROR: Invalid UserName ===");
         return false;
     }
     $output->addWikiText("=== User ===");
     $output->addWikiText("user_id = " . $user->getId());
     $output->addWikiText("user_name = " . $user->getName());
     $output->addWikiText("user_realname = " . $user->getRealName());
     $output->addWikiText("user_email = " . $user->getEmail());
     $output->addWikiText("=== Transaction ===");
     $output->addWikiText("True balance before = " . TMRecord::getTrueBalanceFromDB($user->getId()));
     if (!is_int($amount) || $amount <= 0 || $amount > 1000) {
         $output->addWikiText("=== ERROR: Invalid Amount ===");
         return false;
     }
     $tmr = array('tmr_type' => TM_REFUND_TYPE, 'tmr_user_id' => $user->getId(), 'tmr_mail' => $user->getEmail(), 'tmr_ip' => IP::sanitizeIP(wfGetIP()), 'tmr_amount' => $amount, 'tmr_currency' => 'EUR', 'tmr_desc' => 'tm-refund', 'tmr_status' => 'OK');
     wfRunHooks('CreateTransaction', array(&$tmr));
     $output->addWikiText("==== DONE ====");
     $output->addWikiText("True balance after = " . TMRecord::getTrueBalanceFromDB($user->getId()));
     $output->addWikiText("== SUCCESS ==");
 }
Example #27
0
 /**
  * Set the browser cookie
  * @param string $name name of cookie
  * @param string $value value to give cookie
  * @param int|null $expire Unix timestamp (in seconds) when the cookie should expire.
  *        0 (the default) causes it to expire $wgCookieExpiration seconds from now.
  *        null causes it to be a session cookie.
  * @param array $options Assoc of additional cookie options:
  *     prefix: string, name prefix ($wgCookiePrefix)
  *     domain: string, cookie domain ($wgCookieDomain)
  *     path: string, cookie path ($wgCookiePath)
  *     secure: bool, secure attribute ($wgCookieSecure)
  *     httpOnly: bool, httpOnly attribute ($wgCookieHttpOnly)
  *     raw: bool, if true uses PHP's setrawcookie() instead of setcookie()
  *   For backwards compatability, if $options is not an array then it and
  *   the following two parameters will be interpreted as values for
  *   'prefix', 'domain', and 'secure'
  * @since 1.22 Replaced $prefix, $domain, and $forceSecure with $options
  */
 public function setcookie($name, $value, $expire = 0, $options = null)
 {
     global $wgCookiePath, $wgCookiePrefix, $wgCookieDomain;
     global $wgCookieSecure, $wgCookieExpiration, $wgCookieHttpOnly;
     if (!is_array($options)) {
         // Backwards compatability
         $options = array('prefix' => $options);
         if (func_num_args() >= 5) {
             $options['domain'] = func_get_arg(4);
         }
         if (func_num_args() >= 6) {
             $options['secure'] = func_get_arg(5);
         }
     }
     $options = array_filter($options, function ($a) {
         return $a !== null;
     }) + array('prefix' => $wgCookiePrefix, 'domain' => $wgCookieDomain, 'path' => $wgCookiePath, 'secure' => $wgCookieSecure, 'httpOnly' => $wgCookieHttpOnly, 'raw' => false);
     if ($expire === null) {
         $expire = 0;
         // Session cookie
     } elseif ($expire == 0 && $wgCookieExpiration != 0) {
         $expire = time() + $wgCookieExpiration;
     }
     $func = $options['raw'] ? 'setrawcookie' : 'setcookie';
     if (wfRunHooks('WebResponseSetCookie', array(&$name, &$value, &$expire, $options))) {
         wfDebugLog('cookie', $func . ': "' . implode('", "', array($options['prefix'] . $name, $value, $expire, $options['path'], $options['domain'], $options['secure'], $options['httpOnly'])) . '"');
         call_user_func($func, $options['prefix'] . $name, $value, $expire, $options['path'], $options['domain'], $options['secure'], $options['httpOnly']);
     }
 }
 /**
  * Loads skin and user CSS files.
  * @param OutputPage $out
  */
 function setupSkinUserCss(OutputPage $out)
 {
     parent::setupSkinUserCss($out);
     $styles = array('mediawiki.skinning.interface', 'skins.mediawikibootstrap');
     wfRunHooks('SkinMediawikibootstrapStyleModules', array($this, &$styles));
     $out->addModuleStyles($styles);
 }
Example #29
0
 /**
  * Initialise the special page list
  * This must be called before accessing SpecialPage::$mList
  *
  * @return array
  */
 static function getList()
 {
     global $wgSpecialPages;
     global $wgDisableCounters, $wgDisableInternalSearch, $wgEmailAuthentication;
     global $wgEnableEmail;
     if (!is_object(self::$mList)) {
         wfProfileIn(__METHOD__);
         if (!$wgDisableCounters) {
             self::$mList['Popularpages'] = 'PopularpagesPage';
         }
         if (!$wgDisableInternalSearch) {
             self::$mList['Search'] = 'SpecialSearch';
         }
         if ($wgEmailAuthentication) {
             self::$mList['Confirmemail'] = 'EmailConfirmation';
             self::$mList['Invalidateemail'] = 'EmailInvalidation';
         }
         if ($wgEnableEmail) {
             self::$mList['ChangeEmail'] = 'SpecialChangeEmail';
         }
         // Add extension special pages
         self::$mList = array_merge(self::$mList, $wgSpecialPages);
         // Run hooks
         // This hook can be used to remove undesired built-in special pages
         wfRunHooks('SpecialPage_initList', array(&self::$mList));
         // Cast to object: func()[$key] doesn't work, but func()->$key does
         settype(self::$mList, 'object');
         wfProfileOut(__METHOD__);
     }
     return self::$mList;
 }
Example #30
0
 /**
  * {{#embed: mime-type|local-or-interwiki-link[|param1=value1 ...]}}
  */
 public function mg_embed(&$parser, $type, $iwl_link)
 {
     // sanitize the input
     $sanitized_type = htmlspecialchars($type);
     $sanitized_link = htmlspecialchars($iwl_link);
     // deal with the variable parameters list.
     $params = func_get_args();
     array_shift($params);
     // get rid of $parser
     array_shift($params);
     // get rid of $type
     array_shift($params);
     // get rid of $iwl_link
     // sanitizes & formats the params list as a string.
     $liste = $this->formatParamsList($params);
     // check the validation of the interwiki prefix
     $msg_id = 'importbadinterwiki';
     $link = $this->getLink($sanitized_link);
     if ($link === false) {
         return wfMsg($msg_id);
     }
     // use an already translated message.
     $completeElement = '<embed type="' . $type . '" src="' . $link . '" ' . $liste . ' />';
     // prepare for the call to [[Extension:ParserFunctionsHelper]]
     // public function hParserFunctionsHelperSet( $key, &$value, &$index, &$anchor )
     $anchor = null;
     $index = null;
     wfRunHooks('ParserFunctionsHelperSet', array('embed', &$completeElement, &$index, &$anchor));
     if ($anchor === null) {
         return '[http://www.mediawiki.org/wiki/Extension:ParserFunctionsHelper Extension:ParserFunctionHelper] missing.';
     }
     return $anchor;
 }