예제 #1
0
 /**
  * Perform actual update for the entry
  */
 public function doUpdate()
 {
     global $wgDisableSearchUpdate;
     if ($wgDisableSearchUpdate || !$this->id) {
         return;
     }
     $page = WikiPage::newFromID($this->id, WikiPage::READ_LATEST);
     foreach (SearchEngine::getSearchTypes() as $type) {
         $search = SearchEngine::create($type);
         $indexTitle = $this->indexTitle($search);
         if (!$search->supports('search-update')) {
             continue;
         }
         $normalTitle = $search->normalizeText($indexTitle);
         if ($page === null) {
             $search->delete($this->id, $normalTitle);
             continue;
         } elseif ($this->content === false) {
             $search->updateTitle($this->id, $normalTitle);
             continue;
         }
         $text = $search->getTextFromContent($this->title, $this->content);
         if (!$search->textAlreadyUpdatedForIndex()) {
             $text = self::updateText($text);
         }
         # Perform the actual update
         $search->update($this->id, $normalTitle, $search->normalizeText($text));
     }
 }
 public function extractTemplatesFromPage($pageId, array $flagTypesToExtract)
 {
     $app = \F::app();
     $wikiId = $this->getWikiId();
     $wikiPage = \WikiPage::newFromID($pageId);
     $app->wg->User = \User::newFromId($wikiPage->getUser());
     $content = $wikiPage->getText();
     $flagsExtractor = new FlagsExtractor();
     /**
      * Get the existing flags first
      */
     $existingFlags = $app->sendRequest('FlagsApiController', 'getFlagsForPage', ['page_id' => $pageId])->getData()[\FlagsApiController::FLAGS_API_RESPONSE_DATA];
     /**
      * Prepare actions for the extraction and check which flags should be updated
      */
     $actions = [FlagsExtractor::ACTION_REMOVE_ALL_FLAGS];
     /**
      * Check which flags should be added and which should be updated
      */
     $flagsToAdd = $flagsToUpdate = [];
     foreach ($flagTypesToExtract as $flagType) {
         $actionParams = ['wiki_id' => $wikiId, 'page_id' => $pageId, 'flag_type_id' => $flagType['flag_type_id']];
         $flagsExtractor->init($content, $flagType['flag_view'], $actions, $actionParams);
         $template = $flagsExtractor->getTemplate()[0];
         if (isset($existingFlags[$flagType['flag_type_id']])) {
             $flagsToUpdate[] = ['flag_id' => $existingFlags[$flagType['flag_type_id']]['flag_id'], 'params' => $template['params']];
         } else {
             $flagsToAdd[] = ['flag_type_id' => $flagType['flag_type_id'], 'params' => $template['params']];
         }
         /**
          * Modify the content for the next template
          */
         $content = $flagsExtractor->getText();
     }
     /**
      * Send requests
      */
     if (!empty($flagsToAdd)) {
         $responseData = $app->sendRequest('FlagsApiController', 'addFlagsToPage', ['wiki_id' => $wikiId, 'page_id' => $pageId, 'flags' => $flagsToAdd])->getData();
         $this->actionsStatus = $responseData[\FlagsApiController::FLAGS_API_RESPONSE_STATUS];
         if ($this->actionsStatus !== true) {
             $this->error('The adding operation failed.');
         }
     }
     if (!empty($flagsToUpdate)) {
         $responseData = $app->sendRequest('FlagsApiController', 'updateFlagsForPage', ['wiki_id' => $wikiId, 'page_id' => $pageId, 'flags' => $flagsToUpdate])->getData();
         $this->actionsStatus = $responseData[\FlagsApiController::FLAGS_API_RESPONSE_STATUS];
         if ($this->actionsStatus !== true) {
             $this->error('The updating operation failed.');
         }
     }
     /**
      * If the actions succeeded - make the actual edit as WikiaBot
      */
     if ($this->actionsStatus) {
         $user = \User::newFromName('WikiaBot');
         $wikiPage->doEdit($content, 'Templates converted to the new Flags feature.', EDIT_FORCE_BOT | EDIT_MINOR, false, $user);
     }
 }
 public function run()
 {
     $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
     $lb = $lbFactory->getMainLB();
     $dbw = $lb->getConnection(DB_MASTER);
     $this->ticket = $lbFactory->getEmptyTransactionTicket(__METHOD__);
     $page = WikiPage::newFromID($this->params['pageId'], WikiPage::READ_LATEST);
     if (!$page) {
         $this->setLastError("Could not find page #{$this->params['pageId']}");
         return false;
         // deleted?
     }
     // Use a named lock so that jobs for this page see each others' changes
     $lockKey = "CategoryMembershipUpdates:{$page->getId()}";
     $scopedLock = $dbw->getScopedLockAndFlush($lockKey, __METHOD__, 3);
     if (!$scopedLock) {
         $this->setLastError("Could not acquire lock '{$lockKey}'");
         return false;
     }
     $dbr = $lb->getConnection(DB_REPLICA, ['recentchanges']);
     // Wait till the replica DB is caught up so that jobs for this page see each others' changes
     if (!$lb->safeWaitForMasterPos($dbr)) {
         $this->setLastError("Timed out while waiting for replica DB to catch up");
         return false;
     }
     // Clear any stale REPEATABLE-READ snapshot
     $dbr->flushSnapshot(__METHOD__);
     $cutoffUnix = wfTimestamp(TS_UNIX, $this->params['revTimestamp']);
     // Using ENQUEUE_FUDGE_SEC handles jobs inserted out of revision order due to the delay
     // between COMMIT and actual enqueueing of the CategoryMembershipChangeJob job.
     $cutoffUnix -= self::ENQUEUE_FUDGE_SEC;
     // Get the newest revision that has a SRC_CATEGORIZE row...
     $row = $dbr->selectRow(['revision', 'recentchanges'], ['rev_timestamp', 'rev_id'], ['rev_page' => $page->getId(), 'rev_timestamp >= ' . $dbr->addQuotes($dbr->timestamp($cutoffUnix))], __METHOD__, ['ORDER BY' => 'rev_timestamp DESC, rev_id DESC'], ['recentchanges' => ['INNER JOIN', ['rc_this_oldid = rev_id', 'rc_source' => RecentChange::SRC_CATEGORIZE, 'rc_cur_id = rev_page', 'rc_timestamp >= rev_timestamp']]]);
     // Only consider revisions newer than any such revision
     if ($row) {
         $cutoffUnix = wfTimestamp(TS_UNIX, $row->rev_timestamp);
         $lastRevId = (int) $row->rev_id;
     } else {
         $lastRevId = 0;
     }
     // Find revisions to this page made around and after this revision which lack category
     // notifications in recent changes. This lets jobs pick up were the last one left off.
     $encCutoff = $dbr->addQuotes($dbr->timestamp($cutoffUnix));
     $res = $dbr->select('revision', Revision::selectFields(), ['rev_page' => $page->getId(), "rev_timestamp > {$encCutoff}" . " OR (rev_timestamp = {$encCutoff} AND rev_id > {$lastRevId})"], __METHOD__, ['ORDER BY' => 'rev_timestamp ASC, rev_id ASC']);
     // Apply all category updates in revision timestamp order
     foreach ($res as $row) {
         $this->notifyUpdatesForRevision($lbFactory, $page, Revision::newFromRow($row));
     }
     return true;
 }
 /**
  * Purge the cache for articles related to a given thread
  * @param int $threadId
  */
 public static function purgeCache($threadId)
 {
     $relatedPages = new WallRelatedPages();
     $ids = $relatedPages->getMessagesRelatedArticleIds($threadId, 'order_index', DB_MASTER);
     foreach ($ids as $id) {
         $key = wfMemcKey(__CLASS__, 'getData', $id);
         WikiaDataAccess::cachePurge($key);
         // VOLDEV-46: Update module by purging page, not via AJAX
         $wikiaPage = WikiPage::newFromID($id);
         if ($wikiaPage) {
             $wikiaPage->doPurge();
         } else {
             self::logError("Found a null related wikipage on thread purge", ["articleID" => $id, "threadID" => $threadId]);
         }
     }
 }
 public function run()
 {
     $page = WikiPage::newFromID($this->params['pageId'], WikiPage::READ_LATEST);
     if (!$page) {
         $this->setLastError("Could not find page #{$this->params['pageId']}");
         return false;
         // deleted?
     }
     $dbw = wfGetDB(DB_MASTER);
     // Use a named lock so that jobs for this page see each others' changes
     $fname = __METHOD__;
     $lockKey = "CategoryMembershipUpdates:{$page->getId()}";
     if (!$dbw->lock($lockKey, $fname, 10)) {
         $this->setLastError("Could not acquire lock '{$lockKey}'");
         return false;
     }
     $unlocker = new ScopedCallback(function () use($dbw, $lockKey, $fname) {
         $dbw->unlock($lockKey, $fname);
     });
     // Sanity: clear any DB transaction snapshot
     $dbw->commit(__METHOD__, 'flush');
     $cutoffUnix = wfTimestamp(TS_UNIX, $this->params['revTimestamp']);
     // Using ENQUEUE_FUDGE_SEC handles jobs inserted out of revision order due to the delay
     // between COMMIT and actual enqueueing of the CategoryMembershipChangeJob job.
     $cutoffUnix -= self::ENQUEUE_FUDGE_SEC;
     // Get the newest revision that has a SRC_CATEGORIZE row...
     $row = $dbw->selectRow(array('revision', 'recentchanges'), array('rev_timestamp', 'rev_id'), array('rev_page' => $page->getId(), 'rev_timestamp >= ' . $dbw->addQuotes($dbw->timestamp($cutoffUnix))), __METHOD__, array('ORDER BY' => 'rev_timestamp DESC, rev_id DESC'), array('recentchanges' => array('INNER JOIN', array('rc_this_oldid = rev_id', 'rc_source' => RecentChange::SRC_CATEGORIZE, 'rc_cur_id = rev_page', 'rc_timestamp >= rev_timestamp'))));
     // Only consider revisions newer than any such revision
     if ($row) {
         $cutoffUnix = wfTimestamp(TS_UNIX, $row->rev_timestamp);
         $lastRevId = (int) $row->rev_id;
     } else {
         $lastRevId = 0;
     }
     // Find revisions to this page made around and after this revision which lack category
     // notifications in recent changes. This lets jobs pick up were the last one left off.
     $encCutoff = $dbw->addQuotes($dbw->timestamp($cutoffUnix));
     $res = $dbw->select('revision', Revision::selectFields(), array('rev_page' => $page->getId(), "rev_timestamp > {$encCutoff}" . " OR (rev_timestamp = {$encCutoff} AND rev_id > {$lastRevId})"), __METHOD__, array('ORDER BY' => 'rev_timestamp ASC, rev_id ASC'));
     // Apply all category updates in revision timestamp order
     foreach ($res as $row) {
         $this->notifyUpdatesForRevision($page, Revision::newFromRow($row));
     }
     ScopedCallback::consume($unlocker);
     return true;
 }
예제 #6
0
 function run()
 {
     if (is_null($this->title)) {
         $this->setLastError("deleteLinks: Invalid title");
         return false;
     }
     $pageId = $this->params['pageId'];
     if (WikiPage::newFromID($pageId, WikiPage::READ_LATEST)) {
         // The page was restored somehow or something went wrong
         $this->setLastError("deleteLinks: Page #{$pageId} exists");
         return false;
     }
     $page = WikiPage::factory($this->title);
     // title when deleted
     $update = new LinksDeletionUpdate($page, $pageId);
     DataUpdate::runUpdates([$update]);
     return true;
 }
 /**
  * Triggered if a user edits a Draft subpage of a template.
  * It pre-fills the content of the Draft with a converted markup.
  * @param $text
  * @param Title $title
  * @return bool
  */
 public static function onEditFormPreloadText(&$text, Title $title)
 {
     $helper = new TemplateDraftHelper();
     if ($helper->isTitleNewDraft($title) && TemplateConverter::isConversion()) {
         $parentTitleId = $helper->getParentTitle($title)->getArticleID();
         if ($parentTitleId > 0) {
             $parentContent = WikiPage::newFromID($parentTitleId)->getText();
             /**
              * TODO: Introduce a parameter to modify conversion flags
              * If you want to perform different conversions, not only the infobox one,
              * you can introduce a URL parameter to control the binary sum of flags.
              */
             $controller = new TemplateDraftController();
             $text = $controller->createDraftContent($title, $parentContent, TemplateClassificationController::TEMPLATE_INFOBOX);
         }
     }
     return true;
 }
예제 #8
0
 /**
  * Overrides content of parent page with contents of draft page
  * @param Title $draftTitle Title object of sub page (draft)
  * @throws PermissionsException
  */
 private function approveDraft(Title $draftTitle)
 {
     // Get Title object of parent page
     $helper = new TemplateDraftHelper();
     $parentTitle = $helper->getParentTitle($draftTitle);
     // Check edit rights
     if (!$parentTitle->userCan('templatedraft')) {
         throw new PermissionsException('edit');
     }
     // Get contents of draft page
     $article = Article::newFromId($draftTitle->getArticleID());
     $draftContent = $article->getContent();
     // Get WikiPage object of parent page
     $page = WikiPage::newFromID($parentTitle->getArticleID());
     // Save to parent page
     $page->doEdit($draftContent, wfMessage('templatedraft-approval-summary')->inContentLanguage()->plain());
     // Remove Draft page
     $draftPage = WikiPage::newFromID($draftTitle->getArticleID());
     $draftPage->doDeleteArticle(wfMessage('templatedraft-draft-removal-summary')->inContentLanguage()->plain());
     // Show a confirmation message to a user after redirect
     BannerNotificationsController::addConfirmation(wfMessage('templatedraft-approval-success-confirmation')->escaped(), BannerNotificationsController::CONFIRMATION_CONFIRM, true);
 }
예제 #9
0
 function run()
 {
     if (is_null($this->title)) {
         $this->setLastError("deleteLinks: Invalid title");
         return false;
     }
     $pageId = $this->params['pageId'];
     // Serialize links updates by page ID so they see each others' changes
     $scopedLock = LinksUpdate::acquirePageLock(wfGetDB(DB_MASTER), $pageId, 'job');
     if (WikiPage::newFromID($pageId, WikiPage::READ_LATEST)) {
         // The page was restored somehow or something went wrong
         $this->setLastError("deleteLinks: Page #{$pageId} exists");
         return false;
     }
     $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
     $timestamp = isset($this->params['timestamp']) ? $this->params['timestamp'] : null;
     $page = WikiPage::factory($this->title);
     // title when deleted
     $update = new LinksDeletionUpdate($page, $pageId, $timestamp);
     $update->setTransactionTicket($factory->getEmptyTransactionTicket(__METHOD__));
     $update->doUpdate();
     return true;
 }
예제 #10
0
 /**
  * Run LinksUpdate for all links on a given page_id
  * @param int $id The page_id
  */
 public static function fixLinksFromArticle($id)
 {
     $page = WikiPage::newFromID($id);
     LinkCache::singleton()->clear();
     if ($page === null) {
         return;
     }
     $content = $page->getContent(Revision::RAW);
     if ($content === null) {
         return;
     }
     $dbw = wfGetDB(DB_MASTER);
     $dbw->begin(__METHOD__);
     $updates = $content->getSecondaryDataUpdates($page->getTitle());
     DataUpdate::runUpdates($updates);
     $dbw->commit(__METHOD__);
 }
예제 #11
0
 /**
  * Run LinksUpdate for all links on a given page_id
  * @param $id int The page_id
  */
 public static function fixLinksFromArticle($id)
 {
     global $wgParser, $wgContLang;
     $page = WikiPage::newFromID($id);
     LinkCache::singleton()->clear();
     if ($page === null) {
         return;
     }
     $text = $page->getRawText();
     if ($text === false) {
         return;
     }
     $dbw = wfGetDB(DB_MASTER);
     $dbw->begin(__METHOD__);
     $options = ParserOptions::newFromUserAndLang(new User(), $wgContLang);
     $parserOutput = $wgParser->parse($text, $page->getTitle(), $options, true, true, $page->getLatest());
     $update = new LinksUpdate($page->getTitle(), $parserOutput, false);
     $update->doUpdate();
     $dbw->commit(__METHOD__);
 }
예제 #12
0
 /**
  * @param $params array
  * @param $load bool|string Whether load the object's state from the database:
  *        - false: don't load (if the pageid is given, it will still be loaded)
  *        - 'fromdb': load from a slave database
  *        - 'fromdbmaster': load from the master database
  * @return WikiPage
  */
 public function getTitleOrPageId($params, $load = false)
 {
     $this->requireOnlyOneParameter($params, 'title', 'pageid');
     $pageObj = null;
     if (isset($params['title'])) {
         $titleObj = Title::newFromText($params['title']);
         if (!$titleObj) {
             $this->dieUsageMsg(array('invalidtitle', $params['title']));
         }
         $pageObj = WikiPage::factory($titleObj);
         if ($load !== false) {
             $pageObj->loadPageData($load);
         }
     } elseif (isset($params['pageid'])) {
         if ($load === false) {
             $load = 'fromdb';
         }
         $pageObj = WikiPage::newFromID($params['pageid'], $load);
         if (!$pageObj) {
             $this->dieUsageMsg(array('nosuchpageid', $params['pageid']));
         }
     }
     return $pageObj;
 }
예제 #13
0
 /**
  *  Called on BeforeParserFetchFileAndTitle hook
  *  Changes links and thumbnails of files to point to the approved revision in all cases except
  *  the primary file on file pages (e.g. the big image in the top left on File:My File.png). To
  *  modify that image see self::onImagePageFindFile()
  **/
 public static function modifyFileLinks($parser, Title $fileTitle, &$options, &$query)
 {
     if ($fileTitle->getNamespace() == NS_MEDIA) {
         $fileTitle = Title::makeTitle(NS_FILE, $fileTitle->getDBkey());
         $fileTitle->resetArticleId($fileTitle->getArticleID());
         // avoid extra queries
         // Media link redirects don't get caught by the normal redirect check, so this
         // extra check is required
         if ($temp = WikiPage::newFromID($fileTitle->getArticleID())->getRedirectTarget()) {
             $fileTitle = $temp;
             unset($temp);
         }
     }
     if ($fileTitle->isRedirect()) {
         $page = WikiPage::newFromID($fileTitle->getArticleID());
         $fileTitle = $page->getRedirectTarget();
         $fileTitle->resetArticleId($fileTitle->getArticleID());
         // avoid extra queries
     }
     # Tell Parser what file version to use
     list($approvedRevTimestamp, $approvedRevSha1) = ApprovedRevs::getApprovedFileInfo($fileTitle);
     // no valid approved timestamp or sha1, so don't modify image or image link
     if (!$approvedRevTimestamp || !$approvedRevSha1) {
         return true;
     }
     $options['time'] = wfTimestampOrNull(TS_MW, $approvedRevTimestamp);
     $options['sha1'] = $approvedRevSha1;
     // $options['broken'] = true; // breaks the link? was in FlaggedRevs...why would we want to do this?
     # Stabilize the file link
     if ($query != '') {
         $query .= '&';
     }
     $query .= "filetimestamp=" . urlencode(wfTimestamp(TS_MW, $approvedRevTimestamp));
     return true;
 }
예제 #14
0
 /**
  * Run LinksUpdate for all links on a given page_id
  * @param int $id The page_id
  * @param int|bool $ns Only fix links if it is in this namespace
  */
 public static function fixLinksFromArticle($id, $ns = false)
 {
     $page = WikiPage::newFromID($id);
     LinkCache::singleton()->clear();
     if ($page === null) {
         return;
     } elseif ($ns !== false && !$page->getTitle()->inNamespace($ns)) {
         return;
     }
     $content = $page->getContent(Revision::RAW);
     if ($content === null) {
         return;
     }
     foreach ($content->getSecondaryDataUpdates($page->getTitle()) as $update) {
         DeferredUpdates::addUpdate($update);
     }
 }
 /**
  * Generates plain text content of a given wiki page without WikiText or HTML tags
  * @param object $oTitle Title object
  * @return string Plain text content
  */
 public function prepareTextForIndex(Title $oTitle)
 {
     $sText = WikiPage::newFromID($oTitle->getArticleID())->getContent()->getParserOutput($oTitle)->getText();
     $sText = Sanitizer::stripAllTags($sText);
     $sText = str_replace($this->aFragsToBeReplaced, ' ', $sText);
     $sText = html_entity_decode($sText);
     return $sText;
 }
예제 #16
0
 /**
  * Returns feed item
  *
  * @since 1.8
  *
  * @param array $row
  *
  * @return array
  */
 protected function feedItem(array $row)
 {
     $rowItems = array();
     $subject = false;
     /**
      * Loop over all properties within a row
      *
      * @var SMWResultArray $field
      * @var SMWDataValue $object
      */
     foreach ($row as $field) {
         $itemSegments = array();
         $subject = $field->getResultSubject()->getTitle();
         // Loop over all values for the property.
         while (($dataValue = $field->getNextDataValue()) !== false) {
             if ($dataValue->getDataItem() instanceof SMWDIWikipage) {
                 $itemSegments[] = Sanitizer::decodeCharReferences($dataValue->getLongHTMLText());
             } else {
                 $itemSegments[] = Sanitizer::decodeCharReferences($dataValue->getWikiValue());
             }
         }
         // Join all property values into a single string, separated by a comma
         if ($itemSegments !== array()) {
             $rowItems[] = implode(', ', $itemSegments);
         }
     }
     if ($subject instanceof Title) {
         $wikiPage = WikiPage::newFromID($subject->getArticleID());
         if ($wikiPage->exists()) {
             return new FeedItem($subject->getPrefixedText(), $this->feedItemDescription($rowItems, $this->getPageContent($wikiPage)), $subject->getFullURL(), $wikiPage->getTimestamp(), $wikiPage->getUserText(), $this->feedItemComments());
         }
     }
     return array();
 }
예제 #17
0
 /**
  * Get a WikiPage object from a title or pageid param, if possible.
  * Can die, if no param is set or if the title or page id is not valid.
  *
  * @param array $params
  * @param bool|string $load Whether load the object's state from the database:
  *        - false: don't load (if the pageid is given, it will still be loaded)
  *        - 'fromdb': load from a slave database
  *        - 'fromdbmaster': load from the master database
  * @return WikiPage
  */
 public function getTitleOrPageId($params, $load = false)
 {
     $this->requireOnlyOneParameter($params, 'title', 'pageid');
     $pageObj = null;
     if (isset($params['title'])) {
         $titleObj = Title::newFromText($params['title']);
         if (!$titleObj || $titleObj->isExternal()) {
             $this->dieUsageMsg(array('invalidtitle', $params['title']));
         }
         if (!$titleObj->canExist()) {
             $this->dieUsage("Namespace doesn't allow actual pages", 'pagecannotexist');
         }
         $pageObj = WikiPage::factory($titleObj);
         if ($load !== false) {
             $pageObj->loadPageData($load);
         }
     } elseif (isset($params['pageid'])) {
         if ($load === false) {
             $load = 'fromdb';
         }
         $pageObj = WikiPage::newFromID($params['pageid'], $load);
         if (!$pageObj) {
             $this->dieUsageMsg(array('nosuchpageid', $params['pageid']));
         }
     }
     return $pageObj;
 }
 public static function getListOptions($listTitle)
 {
     $aOptions = array();
     $oTitle = Title::newFromText($listTitle, NS_TEMPLATE);
     //echo $args['list']." ".$oTitle->getArticleID();
     if (is_object($oTitle)) {
         $oWikiPage = WikiPage::newFromID($oTitle->getArticleID());
         if (is_object($oWikiPage)) {
             $sContent = $oWikiPage->getContent()->getNativeData();
             $aLines = explode("\n", $sContent);
             foreach ($aLines as $sLine) {
                 if (strpos($sLine, '*') !== 0) {
                     continue;
                 }
                 $sNewLine = trim(substr($sLine, 1));
                 $aOptions[] = $sNewLine;
             }
         }
     }
     return $aOptions;
 }
 public function execute($par)
 {
     $request = $this->getRequest();
     $output = $this->getOutput();
     $this->setHeaders();
     $action = $request->getText('action');
     $page = $request->getText('page');
     $currStage = $request->getText('source');
     $targetStage = $request->getText('target');
     $showArchived = $request->getBool('showArchived');
     $baseUrl = '?title=Special:ContentStaging';
     $baseUrl .= $showArchived ? '&showArchived=1' : '';
     if (!empty($this->pagePrefix)) {
         if ($action === 'copy') {
             $this->copyPage($this->pagePrefix, WikiPage::newFromID($page), $currStage, $targetStage);
         }
         if ($action === 'archive') {
             $this->archivePage($page);
         }
         if ($action === 'restore') {
             $this->restorePage($page);
         }
         $pages = array();
         $allPages = $this->getPagesByPrefix($this->pagePrefix);
         foreach ($allPages as $page) {
             $stage = $this->getStage($page->page_title);
             $title = $this->getTitleWithoutPrefixes($page->page_title);
             $wikiPage = WikiPage::newFromID($page->page_id);
             if ($this->shouldPageShow($wikiPage, $showArchived)) {
                 if (!array_key_exists($title, $pages)) {
                     $pages[$title] = $this->stages;
                 }
                 $pages[$title][$stage] = $wikiPage;
             }
             if ($action === "stageall" && $currStage === $stage) {
                 $pages[$title][$targetStage] = $this->copyPage($this->pagePrefix, $wikiPage, $currStage, $targetStage);
             }
         }
         $resultTable = "{| class=\"wikitable sortable\" border=\"1\"\n";
         $resultTable .= "|-\n";
         $resultTable .= "! Title\n";
         $resultTable .= "! Test <html><br /><a href='" . $baseUrl . "&action=stageall&source=test&target=stage'>Stage all</a></html>\n";
         $resultTable .= "! Stage <html><br /><a href='" . $baseUrl . "&action=stageall&source=stage&target=production'>Stage all</a></html>\n";
         $resultTable .= "! Production\n";
         $resultTable .= "! Options\n";
         foreach ($pages as $title => $stages) {
             $resultTable .= "|-\n";
             $resultTable .= "| [[" . $this->mwNamespace . $this->pagePrefix . "/test/" . $title . " | " . $title . "]]\n";
             foreach (array_keys($this->stages) as $stage) {
                 if ($this->wikiPageExists($stages[$stage])) {
                     $currStage = $stage;
                     $targetStage = '';
                     $keys = array_keys($stages);
                     $element = array_search($currStage, $keys);
                     if ($stage !== "production") {
                         $targetStage = $keys[$element + 1];
                         $targetPage = $stages[$targetStage];
                     }
                     $currPage = $stages[$stage];
                     $stagingStatus = '<span style="color: green">&#10003;</span>';
                     if ($stage !== "production" && (!$this->wikiPageExists($targetPage) || $this->stageContentDiffers($currPage, $targetPage, $currStage, $targetStage))) {
                         $stagingStatus = '<html><a href="' . $baseUrl . '&action=copy&page=' . $currPage->getId() . '&source=' . $currStage . '&target=' . $targetStage . '" style="color: red;">&#10007;</a></html>';
                     }
                     $resultTable .= "| style='text-align: center;' | " . $stagingStatus . "\n";
                 } else {
                     $resultTable .= "| \n";
                 }
             }
             if (!$showArchived) {
                 $archiveOption = '<html><a href="' . $baseUrl . '&action=archive&page=' . $title . '" style="font-weight:bold">&#128448;</a></html>';
             } else {
                 $archiveOption = '<html><a href="' . $baseUrl . '&action=restore&page=' . $title . '" style="font-weight:bold">&#128449;</a></html>';
             }
             $resultTable .= "| style='text-align: center;' | " . $archiveOption . "\n";
         }
         $resultTable .= "|}\n";
         if (!$showArchived) {
             $archiveLink = '<html><a href="?title=Special:ContentStaging&showArchived=1">&#128448; View Archive</a></html>';
         } else {
             $archiveLink = '<html><a href="?title=Special:ContentStaging">&#128449; View List</a></html>';
         }
         $output->addWikiText($archiveLink . "\n" . $resultTable);
     }
 }
예제 #20
0
 public function execute()
 {
     global $wgCityId, $wgParser, $wgUser;
     $this->app = F::app();
     if (empty($wgCityId)) {
         exit("Wiki ID is not set\n");
     }
     $this->wikiId = $wgCityId;
     $section = $this->getOption('section');
     $list = $this->getOption('list');
     $replaceTop = $this->getOption('replaceTop');
     $this->templateName = $this->getOption('template');
     $tag = $this->getOption('tag', null);
     $actions = [];
     if (!$list) {
         $actions = $this->prepareActionOptions();
     }
     $actionsSum = array_sum($actions);
     // get log file
     $this->openLogFile();
     if (!$this->logFile) {
         $this->output("[WARNING] Log file is not set.\n");
         exit;
     }
     if (!$this->templateName) {
         $this->addToLog("[ERROR] Template name is not set.\n");
         $this->writeToLog();
         $this->closeLogFile();
         exit;
     }
     $flags = $this->getFlagsForWiki();
     if (empty($flags)) {
         $this->addToLog("[ERROR] Cannot find flags for this wiki [{$this->wikiId}].\n");
         $this->writeToLog();
         $this->closeLogFile();
         exit;
     }
     $templateNames = array_keys($flags);
     $flagsExtractor = new FlagsExtractor();
     $this->log = '';
     $this->flagTypeId = $this->getFlagTypeId();
     if (!$this->flagTypeId) {
         $this->addToLog("[ERROR] Cannot get flag type id.\n");
         $this->writeToLog();
         $this->closeLogFile();
         exit;
     }
     $this->addToLog("Start processing template: {$this->templateName} \n");
     $title = Title::newFromText('Template:' . $this->templateName);
     $rows = $title->getIndirectLinks();
     if (empty($rows)) {
         $this->addToLog("[WARNING] This template is not used \n");
         $this->addToLog("================================================== \n\n\n");
         fwrite($this->logFile, $this->log);
         $this->output($this->log);
         exit;
     }
     if (is_null($section)) {
         $this->addToLog("Searching in section " . self::SECTION_DEFAULT . " (by default)\n");
         $section = self::SECTION_DEFAULT;
     } elseif ($section == self::SECTION_ALL) {
         $this->addToLog("Searching in all article content\n");
     } else {
         $this->addToLog("Searching in section {$section}\n");
     }
     $this->writeToLog();
     /**
      * Perform all edits as WikiaBot
      */
     $wgUser = User::newFromName(self::EDIT_USER);
     foreach ($rows as $row) {
         $this->log = '';
         $this->pageId = $row->page_id;
         $flagsOnPage = $this->getFlagsOnPage();
         if (isset($flagsOnPage[$this->flagTypeId])) {
             continue;
         }
         $firstTemplate = null;
         $page = Title::makeTitle($row->page_namespace, $row->page_title);
         $this->pageName = $page->getPrefixedText();
         $wiki = WikiPage::newFromID($this->pageId);
         $content = $wiki->getText();
         $textToParse = $content;
         $this->addToLog("Start processing page {$this->pageName} [{$this->pageId}]\n");
         if ($section !== self::SECTION_ALL) {
             $textToParse = $wgParser->getSection($content, $section);
         }
         $textToParse = ltrim($textToParse);
         if ($replaceTop && !$list) {
             $this->addToLog("Looking for top template on {$this->pageName} [{$this->pageId}]\n");
             $firstTemplate = $this->checkFirstTemplate($flagsExtractor, $textToParse, $templateNames);
             if (!is_null($firstTemplate) && $this->templateName == $firstTemplate) {
                 $actions[] = FlagsExtractor::ACTION_REPLACE_FIRST_FLAG;
                 $actionsSum = array_sum($actions);
             }
         }
         $this->addToLog("Looking for template {$this->templateName} on {$this->pageName} [{$this->pageId}]\n");
         $actionParams = $this->prepareActionParams($actionsSum, $tag);
         $flagsExtractor->init($textToParse, $this->templateName, $actions, $actionParams);
         $templates = $flagsExtractor->getAllTemplates();
         $this->logTemplatesInfo($templates, $actionsSum, $actionParams, $list);
         $this->addToLog("Looking for other templates on {$this->pageName} [{$this->pageId}]\n");
         foreach ($templateNames as $templateName) {
             if ($this->templateName == $templateName) {
                 continue;
             }
             $flagTypeId = $flags[$templateName]['flag_type_id'];
             if (isset($flagsOnPage[$flagTypeId])) {
                 continue;
             }
             $position = $flagsExtractor->findTemplatePosition($templateName, 0);
             if ($position !== false) {
                 $this->addToLog("Template {$templateName} found on {$this->pageName} [{$this->pageId}]\n");
                 if ($replaceTop && !$list) {
                     $actions = $this->prepareActionOptions();
                     $actionsSum = array_sum($actions);
                     if (!is_null($firstTemplate) && $templateName == $firstTemplate) {
                         $actions[] = FlagsExtractor::ACTION_REPLACE_FIRST_FLAG;
                         $actionsSum = array_sum($actions);
                     }
                 }
                 $actionParams = $this->prepareActionParams($actionsSum, $tag, $flagTypeId);
                 $text = $flagsExtractor->getText();
                 $flagsExtractor->init($text, $templateName, $actions, $actionParams);
                 $templates = $flagsExtractor->getAllTemplates();
                 $this->logTemplatesInfo($templates, $actionsSum, $actionParams, $list);
             }
         }
         if ($actionsSum & (FlagsExtractor::ACTION_REPLACE_FIRST_FLAG | FlagsExtractor::ACTION_REPLACE_ALL_FLAGS | FlagsExtractor::ACTION_REMOVE_FIRST_FLAG | FlagsExtractor::ACTION_REMOVE_ALL_FLAGS) || $replaceTop) {
             $text = $flagsExtractor->getText();
             if ($section !== self::SECTION_ALL) {
                 $text = str_replace($textToParse, $text, $content);
             }
             $text = ltrim($text);
             if (strcmp($content, $text) !== 0) {
                 $wiki->doEdit($text, self::EDIT_SUMMARY, EDIT_FORCE_BOT);
             }
         }
         if ($replaceTop && !$list) {
             $actions = $this->prepareActionOptions();
             $actionsSum = array_sum($actions);
         }
         $this->log .= "Processing template: {$this->templateName} on page {$this->pageName} [{$this->pageId}] completed \n";
         $this->addToLog("================================================== \n\n\n");
         $this->writeToLog();
     }
     $this->log .= "Processing template: {$this->templateName} completed \n";
     $this->addToLog("================================================== \n\n\n");
     $this->writeToLog();
     $this->closeLogFile();
     $this->output("Processing completed\n");
 }
 public function buildMovePackage($oTitle, $oUser, $page_id = null, $redirect_id = null)
 {
     wfProfileIn(__METHOD__);
     if (!$oTitle instanceof Title) {
         Wikia::log(__METHOD__, "error", "Cannot send log using scribe ({$this->app->wg->CityId}): invalid title object");
         wfProfileOut(__METHOD__);
         return true;
     }
     $oRevision = Revision::newFromTitle($oTitle);
     if (!is_object($oRevision) && !empty($redirect_id)) {
         $db = wfGetDB(DB_MASTER);
         $oRevision = Revision::loadFromPageId($db, $redirect_id);
     }
     if (!$oRevision instanceof Revision) {
         Wikia::log(__METHOD__, "error", "Cannot send log using scribe ({$this->app->wg->CityId}): invalid revision object");
         wfProfileOut(__METHOD__);
         return true;
     }
     if (empty($page_id)) {
         $page_id = $oRevision->getPage();
     }
     if (empty($page_id) || $page_id < 0) {
         $page_id = $oTitle->getArticleId();
     }
     $oPage = WikiPage::newFromID($page_id);
     if (!$oPage instanceof WikiPage) {
         Wikia::log(__METHOD__, "error", "Cannot send log using scribe ({$this->app->wg->CityId}): invalid WikiPage object");
         wfProfileOut(__METHOD__);
         return true;
     }
     wfProfileOut(__METHOD__);
     return $this->buildEditPackage($oPage, $oUser, $oRevision);
 }
예제 #22
0
 /**
  * {@inheritDoc}
  */
 public function getValues()
 {
     if (!$this->title) {
         return array();
     }
     $article = WikiPage::newFromID($this->title->getArticleId());
     if ($article === null || !$article->exists()) {
         return array();
     }
     return array_filter(array_map('trim', explode("\n", $article->getText())));
 }
예제 #23
0
 /**
  * Run LinksUpdate for all links on a given page_id
  * @param int $id The page_id
  */
 public static function fixLinksFromArticle($id)
 {
     $page = WikiPage::newFromID($id);
     LinkCache::singleton()->clear();
     if ($page === null) {
         return;
     }
     $content = $page->getContent(Revision::RAW);
     if ($content === null) {
         return;
     }
     $updates = $content->getSecondaryDataUpdates($page->getTitle());
     DataUpdate::runUpdates($updates);
 }
예제 #24
0
 /**
  * Get WikiPage for the SearchUpdate $id using WikiPage::READ_LATEST
  * and ensure using the same WikiPage object if there are multiple
  * SearchEngine types.
  *
  * Returns null if a page has been deleted or is not found.
  *
  * @return WikiPage|null
  */
 private function getLatestPage()
 {
     if (!isset($this->page)) {
         $this->page = WikiPage::newFromID($this->id, WikiPage::READ_LATEST);
     }
     return $this->page;
 }
 /**
  * Retrieve the text of a WikiPage
  * @param Title $title The title object of the WikiPage
  * @return string The text of the page
  */
 protected function getWikiPageText(Title $title)
 {
     $text = '';
     $wikiPage = WikiPage::newFromID($title->getArticleID());
     if ($wikiPage) {
         $content = $wikiPage->getContent();
         if ($content) {
             $text = ContentHandler::getContentText($content);
         }
     }
     return $text;
 }