public function updatePage($pageId) { /** @var Article|WikiPage $article */ $article = Article::newFromID($pageId); $this->debug("\tChecking article ID: {$pageId}"); if (!$article) { echo "ERR: Could not find article with ID {$pageId}\n"; return; } // Some code expects this to be set global $wgTitle; $wgTitle = $article->getTitle(); $text = $article->getContent(); $newText = preg_replace('/\\[\\[ *Video *:/i', '[[File:', $text); // See if we've actually changed anything if ($text !== $newText) { $this->debug("\t-- Updating links"); if ($this->test) { $success = true; } else { $success = $article->doEdit($newText, 'Updating Video:TITLE links to File:TITLE links', EDIT_MINOR | EDIT_FORCE_BOT | EDIT_AUTOSUMMARY | EDIT_SUPPRESS_RC); } if (!$success) { echo "ERR: Failed to save page (ID={$pageId}) with update gallery tags\n"; } } }
/** * Updates wiki specific properties set from wiki creation wizard. * Context of this method is on the wiki that the values are changing on. * Main wiki creation happens on www, and it will redirect to the newly created wiki. * The values are read from the session and only accessible by the admin. */ public function FinishCreate() { global $wgUser, $wgOut, $wgEnableNjordExt; if (!$wgUser->isAllowed('finishcreate')) { return false; } $this->skipRendering(); $this->LoadState(); $mainPage = wfMsgForContent('mainpage'); // set theme if (!empty($this->params['color-body'])) { $themeSettings = new ThemeSettings(); $themeSettings->saveSettings($this->params); } // set description on main page if (!empty($this->params['wikiDescription'])) { $mainTitle = Title::newFromText($mainPage); $mainId = $mainTitle->getArticleID(); $mainArticle = Article::newFromID($mainId); if (!empty($mainArticle)) { if (!empty($wgEnableNjordExt)) { $newMainPageText = $this->getMoMMainPage($mainArticle); } else { $newMainPageText = $this->getClassicMainPage($mainArticle); } $mainArticle->doEdit($newMainPageText, ''); $this->initHeroModule($mainPage); } } $wgOut->enableClientCache(false); $this->clearState(); $wgOut->redirect($mainPage . '?wiki-welcome=1'); }
/** * Update the contents of an existing poll * @param wgRequest pollId */ public static function update() { wfProfileIn(__METHOD__); $wgRequest = F::app()->getGlobal('wgRequest'); $wgUser = F::app()->getGlobal('wgUser'); $pollId = $wgRequest->getInt('pollId'); $answers = $wgRequest->getArray('answer'); // array $res = array(); $poll = F::build('WikiaPoll', array($pollId), 'newFromId'); if (!empty($poll) && $poll->exists()) { $content = ""; foreach ($answers as $answer) { $content .= "*{$answer}\n"; } $article = Article::newFromID($pollId); if ($article instanceof Article) { $status = $article->doEdit($content, 'Poll Updated', EDIT_UPDATE, false, $wgUser); $title_object = $article->getTitle(); // Fixme: check status object $res = array('success' => true, 'pollId' => $article->getID(), 'url' => $title_object->getLocalUrl(), 'question' => $title_object->getPrefixedText()); } } wfProfileOut(__METHOD__); return $res; }
function formatRow($row) { static $sk = null; if (is_null($sk)) { global $wgUser; $sk = $wgUser->getSkin(); } $a = Article::newFromID($row->dq_page); $t = $a->mTitle; $dqi = DeleteQueueItem::newFromArticle($a); $dqi->loadFromRow($row); $queue = $dqi->getQueue(); global $wgLang; if ($dqi->getQueue() == 'deletediscuss') { $discusspage = $sk->makeKnownLinkObj($dqi->getDiscussionPage()->mTitle); } else { $discusspage = ''; } if ($row->dq_expiry > $row->dq_timestamp) { $expirestr = $wgLang->timeanddate($row->dq_expiry); } else { $expirestr = ''; } $tr = ''; $tr .= Xml::tags('td', null, $sk->makeKnownLinkObj($t, $t->getPrefixedText())); $tr .= Xml::element('td', null, wfMsg("deletequeue-queue-{$queue}")); $tr .= Xml::tags('td', null, $sk->makeKnownLinkObj($t, $dqi->formatVoteCount(), 'action=delviewvotes')); $tr .= Xml::element('td', null, $expirestr); $tr .= Xml::tags('td', null, $discusspage); return Xml::tags('tr', null, $tr) . "\n"; }
public function execute() { $prefix = $this->getOption('prefix'); $namespace = intval($this->getOption('namespace', 0)); $isDryRun = $this->hasOption('dry-run'); $this->output("Looking for pages matching '{$prefix}' prefix in namespace #{$namespace}... "); $res = ApiService::call(array('action' => 'query', 'list' => 'allpages', 'apnamespace' => $namespace, 'apprefix' => $prefix, 'aplimit' => 5000)); $pages = !empty($res['query']['allpages']) ? $res['query']['allpages'] : array(); $this->output(count($pages) . " article(s) found\n\n"); if (count($pages) === 0) { $this->output("No articles found!\n"); die; } foreach ($pages as $page) { if ($isDryRun) { $this->output("* {$page['title']} not deleted (dry run)\n"); continue; } $this->output("* Deleting {$page['title']}..."); $article = Article::newFromID($page['pageid']); if ($article instanceof Article) { $res = $article->doDeleteArticle(self::REASON); if ($res === true) { $this->output(" done\n"); } else { $this->output(" error!\n"); } } else { $this->output(" article not found by its ID!\n"); } } $this->output("\nDone!\n"); }
/** * Load poll data (try to use cache layer) */ private function load($master = false) { global $wgMemc; wfProfileIn(__METHOD__); if (!$master) { $this->mData = $wgMemc->get($this->mMemcacheKey); } if (empty($this->mData)) { $article = Article::newFromID($this->mPollId); // check poll existance if (empty($article)) { wfDebug(__METHOD__ . ": poll doesn't exist\n"); wfProfileOut(__METHOD__); return; } // parse wikitext with possible answers (stored as wikitext list) $content = $article->getContent(); $lines = explode("\n", $content); $answers = array(); foreach ($lines as $line) { $line = trim($line, '* '); if ($line != '') { $answers[] = array('text' => $line, 'votes' => 0); } } // get poll's author and creation timestamp $title = $article->getTitle(); $firstRev = $title->getFirstRevision(); // TODO: handle poll parameters (image / video for poll) $params = array(); // query for votes $votes = 0; $whichDB = $master ? DB_MASTER : DB_SLAVE; $dbr = wfGetDB($whichDB); $res = $dbr->select(array('poll_vote'), array('poll_answer as answer', 'COUNT(*) as cnt'), array('poll_id' => $this->mPollId), __METHOD__, array('GROUP BY' => 'poll_answer')); while ($row = $dbr->fetchObject($res)) { $answers[$row->answer]['votes'] = $row->cnt; $votes += $row->cnt; } /* // use random data $votes = 0; foreach($answers as &$answer) { $answer['votes'] = mt_rand(0, 3000); $votes += $answer['votes']; } */ $this->mData = array('creator' => $firstRev->getUser(Revision::RAW), 'created' => $firstRev->getTimestamp(), 'touched' => $article->getTouched(), 'title' => $title->getText(), 'question' => $title->getText(), 'answers' => $answers, 'params' => $params, 'votes' => $votes); wfDebug(__METHOD__ . ": loaded from scratch\n"); // store it in memcache $wgMemc->set($this->mMemcacheKey, $this->mData, self::CACHE_TTL); } else { wfDebug(__METHOD__ . ": loaded from memcache\n"); } $this->mExists = true; wfProfileOut(__METHOD__); return; }
/** * @param int $articleId * @return JsonFormatNode * @throws JsonFormatException */ public function getJsonFormatForArticleId($articleId) { $articleId = (int) $articleId; $article = \Article::newFromID($articleId); if (!$article) { throw new JsonFormatException("Cannot find article with id:" . $articleId); } return $this->getJsonFormatForArticle($article); }
public function onArticleAfterVote($user_id, &$page, $vote) { global $wgSitename; $article = Article::newFromID($page); wfProfileIn(__METHOD__); $params = array('$ARTICLENAME' => $article->getTitle()->getText(), '$WIKINAME' => $wgSitename, '$ARTICLE_URL' => $article->getTitle()->getFullURL("ref=fbfeed&fbtype=ratearticle"), '$RATING' => $vote, '$EVENTIMG' => self::$eventImage, '$TEXT' => self::shortenText(self::parseArticle($article)), '$ARTICLE_OBJ' => $article); self::pushEvent(self::$messageName, $params, __CLASS__); wfProfileOut(__METHOD__); return true; }
public function execute($par) { $this->checkPermissions(); $request = $this->getRequest(); $output = $this->getOutput(); $this->setHeaders(); if ($request->getVal('update') != 1 || empty($request->getVal('update'))) { $output->addHTML($this->getUpdateForm()); } else { $newCat = $request->getText('watchlist-add'); $deleteCat = $request->getText('watchlist-del'); $dbw = wfGetDB(DB_MASTER); if (!empty($newCat)) { $selectResult = $dbw->select('watched_categories', '*', ['category' => $newCat], __METHOD__); if (empty($selectResult->current()->users)) { $vals = array('users' => $this->getUser()->getId()); if ($selectResult->numRows() == 0) { $vals['category'] = $newCat; $dbw->insert('watched_categories', $vals, __METHOD__); } else { $dbw->update('watched_categories', $vals, ['category' => $newCat], __METHOD__); } } else { $dbw->update('watched_categories', ['users' => $selectResult->current()->users . ',' . $this->getUser()->getId()], ['category' => $newCat], __METHOD__); } $pages = $dbw->select('categorylinks', '*', ['cl_to' => $newCat], __METHOD__, ['ORDER BY' => 'cl_sortkey']); foreach ($pages as $page) { $page = Article::newFromID($page->cl_from); $output->addWikiText("Adding {$page->getTitle()} to watchlist"); $this->getUser()->addWatch($page->getTitle()); } } if (!empty($deleteCat)) { $selectResult = $dbw->select('watched_categories', '*', ['category' => $deleteCat], __METHOD__); if ($selectResult->numRows() > 0) { $users = explode(',', $selectResult->current()->users); $users = array_diff($users, [$this->getUser()->getId()]); $userString = implode(',', $users); $dbw->update('watched_categories', ['users' => $userString], ['category' => $deleteCat], __METHOD__); $pages = $dbw->select('categorylinks', '*', ['cl_to' => $deleteCat], __METHOD__, ['ORDER BY' => 'cl_sortkey']); foreach ($pages as $page) { $page = Article::newFromID($page->cl_from); $output->addWikiText("Removing {$page->getTitle()} from watchlist"); $this->getUser()->removeWatch($page->getTitle()); } } } $output->addWikiText("'''" . wfMessage('categorywatchlist-finish')->text() . "'''"); $output->addHTML($this->getUpdateForm()); } }
/** * Fix broken [[File:...]] wiki tag * * @param $pageID * @return bool - Whether this upgrade was successful */ public function fixTags($pageID) { global $wgUser, $wgTestMode; $page = Article::newFromID($pageID); if (empty($page)) { echo "\tERROR: Couldn't load page ID {$pageID}\n"; return false; } echo "Checking " . $page->getTitle()->getPrefixedDBkey() . "\n"; $text = $page->getText(); $matchFile = 'File|' . wfMessage('nstab-image')->text(); global $wgTagFixes; $wgTagFixes = 0; $text = preg_replace_callback("/\\[\\[((?:{$matchFile}):[^\\|\\]]+)\\|([0-9]+)([^\\|\\]]*)\\]\\]/i", function ($matches) { global $wgTagFixes; // Name the bits we're matching, for sanity $original = $matches[0]; $file = $matches[1]; $width = $matches[2]; $suffix = $matches[3]; echo "\tChecking '{$original}'\n"; echo "\t- file: '{$file}' / width: {$width} / suffix: '{$suffix}'\n"; // See if our width is suffixed by 'px' or not. If so // leave it as is, unchanged. if (preg_match('/^ *$/', $suffix)) { $rewrite = "[[{$file}|{$width}px]]"; echo "\t- FIX AS '{$rewrite}\n"; $wgTagFixes++; return $rewrite; } else { echo "\t- Leaving unchanged\n"; return $original; } }, $text); if ($wgTagFixes == 0) { echo "\tNo changes for this article\n"; return true; } if ($wgTestMode) { return true; } # Do the edit $status = $page->doEdit($text, "Adding missing 'px' suffix to video pixel width", EDIT_MINOR | EDIT_FORCE_BOT | EDIT_SUPPRESS_RC); $retval = true; if (!$status->isGood()) { echo "\t" . $status->getWikiText() . "\n"; $retval = false; } return $retval; }
public function deferredPurge() { $db = wfGetDB(DB_SLAVE); $articles = []; (new \WikiaSQL())->SELECT('pp_page')->FROM('page_props')->WHERE('pp_propname')->EQUAL_TO(BLOGTPL_TAG)->runLoop($db, function ($unused, $row) { $article = \Article::newFromID($row->pp_page); if ($article instanceof \Article) { $articles[] = $row->pp_page; $article->doPurge(); $article->getTitle()->purgeSquid(); } }); return $articles; }
public static function buildIndexOnPageEdit($self) { wfProfileIn(__METHOD__); if (count($self->mImages) == 1) { $images = array_keys($self->mImages); self::bulidIndex($self->mId, $images); wfProfileOut(__METHOD__); return true; } $article = Article::newFromID($self->mId); self::buildAndGetIndex($article); wfProfileOut(__METHOD__); return true; }
/** * checks for poll existing * returns contents of poll * * @param wgRequest pollId * @return array {exists, url, text} */ public static function get() { wfProfileIn(__METHOD__); $wg = F::app()->wg; $res = array('exists' => false); $id = $wg->Request->getInt('pollId', 0); if ($id != 0) { $article_object = Article::newFromID($id); $title_object = $article_object instanceof Article ? $article_object->getTitle() : false; } if (is_object($title_object) && $title_object->exists()) { $res = array('exists' => true, 'url' => $title_object->getLocalUrl(), 'question' => $title_object->getPrefixedText(), 'answer' => $article_object->getContent()); } wfProfileOut(__METHOD__); return $res; }
/** * Get all the pages in this wiki that have YouTube tags on them * @return array */ public function getPages() { global $wgCityId, $wgStatsDB; // Find all pages in this wiki that have YouTube tags $dbr = wfGetDB(DB_SLAVE, array(), $wgStatsDB); $sql = "SELECT ct_page_id FROM city_used_tags WHERE ct_wikia_id = {$wgCityId} and ct_kind = 'youtube'"; $result = $dbr->query($sql); // Get an array of pages that have YT tags on them $pages = array(); foreach ($result as $row) { $page = Article::newFromID($row->ct_page_id); if (!empty($page)) { $pages[] = $page; } } return $pages; }
public function execute() { $file = $this->getOption('file'); $namespace = intval($this->getOption('namespace', 0)); $isDryRun = $this->hasOption('dry-run'); if ($isDryRun) { echo "== DRY RUN ==\n\n"; } global $wgUser; $wgUser = User::newFromName('WikiaBot'); if (!file_exists($file)) { die("File {$file} does not exist\n"); } $content = trim(file_get_contents($file)); $lines = explode("\n", $content); if (count($lines) === 0) { die("No articles found!\n"); } echo "Removing " . count($lines) . " article(s) in namespace " . $namespace . "\n"; foreach ($lines as $titleText) { if (preg_match('/^ *$/', $titleText)) { continue; } echo "* Deleting {$titleText} ... "; $title = Title::newFromText($titleText, $namespace); $pageId = $title->getArticleID(); $article = Article::newFromID($pageId); if ($article instanceof Article) { if ($isDryRun) { echo "not deleted (dry run)\n"; continue; } else { $res = $article->doDeleteArticle(self::REASON); } if ($res === true) { echo "done\n"; } else { echo "error!\n"; } } else { echo "article not found by its ID!\n"; } } echo "\nDone!\n"; }
public function nukeContribs() { wfProfileIn(__METHOD__); global $wgSharedDB; $user_id = intval($_GET['user_id']); $wiki_id = intval($_GET['wiki_id']); $page_id = intval($_GET['page_id']); if (empty($wgSharedDB)) { wfProfileOut(__METHOD__); return $this->returnError('Non-shared Users DB, cannot continue'); } if (!$user_id || !$wiki_id || !$page_id) { wfProfileOut(__METHOD__); return $this->returnError('Wrong parameters'); } if ($wiki_id != $this->wg->CityId) { // can only process local requests wfProfileOut(__METHOD__); return $this->returnError('Wrong wiki id'); } if (!$this->wg->User->isAllowed('rollbacknuke')) { // doesn't have permissions wfProfileOut(__METHOD__); return $this->returnError('No permissions to execute action'); } $user = User::newFromId($user_id); if (!$user instanceof User) { wfProfileOut(__METHOD__); return $this->returnError('Unable to create User obj with ID specified'); } $article = Article::newFromID($page_id); if (!$article instanceof Article) { wfProfileOut(__METHOD__); return $this->returnError('Article does not exist'); } $msg = ''; $act = new AccountCreationTracker(); $ret = $act->rollbackPage($article, $user->getName(), 'mass rollback', $msg); $status = $ret ? 'OK' : 'ERROR'; $output = array('status' => $status, 'msg' => $msg); echo json_encode($output); $this->skipRendering(); wfProfileOut(__METHOD__); return false; }
/** * @param $pageIDs */ public function countTags($pageIDs) { global $wgCityId; foreach ($pageIDs as $id) { $page = Article::newFromID($id); if (empty($page)) { continue; } $text = $page->getText(); if (preg_match_all("/(<youtube[^>]*>|<gvideo[^>]*>|<aovideo[^>]*>|<aoaudio[^>]*>|<wegame[^>]*>|<tangler>|<gtrailer>|<nicovideo>|<ggtube>|<cgamer>|<longtail>)/", $text, $matches)) { $tags = $matches[1]; foreach ($tags as $t) { $t2 = preg_replace('/<([^> ]+).*>/', '$1', $t); echo "-,{$wgCityId},{$id},{$t2}\n"; } } } }
/** * See functions below for expected URL params */ public function execute() { global $wgRequest, $wgCacheBuster; wfProfileIn(__METHOD__); extract($this->extractRequestParams()); // Allow optionally using a prefixed-title instead of the page_id. if (empty($Id)) { $title = Title::newFromText($Title); if (is_object($title)) { $Id = $title->getArticleID(); } } $article = Article::newFromID($Id); if (is_object($article)) { // Automatically follow redirects. if ($article->isRedirect()) { $title = $article->followRedirect(); if (is_object($title)) { // if this is not an object, then we're pretty unlikely to get any good image matches, but more likely to get them for the original ID. $Id = $title->getArticleID(); } } $imageUrl = null; $imageServing = new ImageServing(array($Id)); foreach ($imageServing->getImages(1) as $key => $value) { $imgTitle = Title::newFromText($value[0]['name'], NS_FILE); $imgFile = wfFindFile($imgTitle); if (!empty($imgFile)) { $imageUrl = wfReplaceImageServer($imgFile->getFullUrl(), $wgCacheBuster); } } $result = $this->getResult(); if (empty($imageUrl)) { $result->addValue('image', "error", "No good, representiative image was found for this page."); // TODO: i18n } else { $result->addValue('image', $this->getModuleName(), $imageUrl); } } wfProfileOut(__METHOD__); }
/** * @desc Returns description for the article's meta tag. * * This is mostly copied from the ArticleMetaDescription extension. * * @param int $articleId * @param int $descLength * @return string * @throws WikiaException */ private function getArticleDescription($articleId, $descLength = 100) { $article = Article::newFromID($articleId); if (!$article instanceof Article) { throw new NotFoundApiException(); } $title = $article->getTitle(); $sMessage = null; if ($title->isMainPage()) { // we're on Main Page, check MediaWiki:Description message $sMessage = wfMessage('Description')->text(); } if ($sMessage == null || wfEmptyMsg('Description', $sMessage)) { $articleService = new ArticleService($article); $description = $articleService->getTextSnippet($descLength); } else { // MediaWiki:Description message found, use it $description = $sMessage; } return $description; }
/** * Load RelatedVideos NS article data (try to use cache layer) */ protected function load($master = false) { wfProfileIn(__METHOD__); if (!$master) { $this->mData = F::app()->wg->memc->get($this->mMemcacheKey); } if (empty($this->mData)) { $article = Article::newFromID($this->mId); // check existence if (empty($article)) { wfDebug(__METHOD__ . ": RelatedVideos NS article doesn't exist\n"); wfProfileOut(__METHOD__); return; } $lists = array(); $lists[self::BLACKLIST_MARKER] = array(); $lists[self::WHITELIST_MARKER] = array(); $dbr = wfGetDB(DB_SLAVE); $res = $dbr->select(array('imagelinks'), array('il_to'), ' il_from = ' . $this->mId, __METHOD__); if (empty($res)) { return; } while ($row = $res->fetchObject($res)) { $sTitle = $row->il_to; $oTitle = Title::newFromText($sTitle, NS_VIDEO); if (is_object($oTitle) && WikiaFileHelper::isTitleVideo($oTitle)) { $lists[self::WHITELIST_MARKER][] = $this->createEntry($sTitle); } } $this->mData = array('lists' => $lists); wfDebug(__METHOD__ . ": loaded from scratch\n"); // store it in memcache F::app()->wg->memc->set($this->mMemcacheKey, $this->mData, self::CACHE_TTL); } else { wfDebug(__METHOD__ . ": loaded from memcache\n"); } $this->mExists = true; wfProfileOut(__METHOD__); return; }
/** * Update metadata in the wiki * @param $video * @return bool */ protected function addGenreToPageCategories($video) { $name = $video['img_name']; $this->outputMessage("Title: {$name}"); $title = Title::newFromText($name, NS_FILE); if ($title instanceof Title && $title->exists()) { $article = Article::newFromID($title->getArticleID()); $content = $article->getContent(); // set default value $status = Status::newGood(); // add category $metadata = $this->extractMetadata($video); if (empty($metadata['genres'])) { $this->incSkipped(); $this->outputMessage("File remained indifferent. no category changes."); return false; } $categories = explode(', ', $metadata['genres']); $content = $this->addCategories($content, $categories); $msg = 'Added: ' . implode(', ', $categories); if (!$this->isDryRun()) { $botUser = User::newFromName('WikiaBot'); $status = $article->doEdit($content, 'Changing categories', EDIT_UPDATE | EDIT_SUPPRESS_RC | EDIT_FORCE_BOT, false, $botUser); } if ($status instanceof Status) { if ($status->isOK()) { $this->outputMessage("...DONE (" . $msg . ")"); } else { ++$this->failedWiki; echo "...FAILED (" . $status->getMessage() . ").\n"; return false; } } $this->outputMessage("\tUpdated (Wiki): {$name}"); } else { $this->outputError("(Title '{$name}' not found).", "...FAILED "); return false; } return true; }
/** * Delete category with the same name as title from the file page. * @param $titles */ public function deleteCategoryFromPage($titles) { foreach ($titles as $title) { $titleObj = Title::newFromText($title, NS_FILE); $titleName = $titleObj->getText(); $escapedCategoryTag = preg_quote("[[Category:" . $titleName . "]]"); $article = Article::newFromID($titleObj->getArticleID()); $content = $article->getContent(); $contentMinusCategory = preg_replace("/{$escapedCategoryTag}/", "", $content); // Check if there really was a category to remove from the page if ($contentMinusCategory != $content) { if (!$this->dryRun) { $article->doEdit($contentMinusCategory, self::EDIT_MESSAGE, EDIT_UPDATE | EDIT_SUPPRESS_RC | EDIT_FORCE_BOT); } $this->pagesUpdated++; $this->log("Updated {$titleName}"); } else { $this->pagesSkipped++; $this->log("Inconsistency in database, {$titleName} does not have category of same name in page content"); } } }
/** * Add an action to the user's Timeline when they rate an article. */ public static function ArticleAfterVote($user_id, &$page, $vote) { global $facebook; if (self::getAction('rate')) { $fbUser = new FacebookUser(); if ($fbUser->getMWUser()->getId() == $user_id) { $article = Article::newFromID($page); if ($article instanceof Article) { $object = FacebookOpenGraph::newObjectFromTitle($article->getTitle()); if ($object) { try { // Publish the action $facebook->api('/' . $fbUser->getId() . '/' . self::getAction('rate'), 'POST', array($object->getType() => $object->getUrl())); } catch (FacebookApiException $e) { // echo $e->getType() . ": " . $e->getMessage() . "<br/>\n"; } } } } } return true; }
public function submitFlags(&$params) { global $wgUser, $webplatformSectionCommentsSMW; $aTemp = json_decode($params['flags'], true); $aProperties = array(); foreach ($aTemp as $key => $value) { $aTempKey = array(); if (preg_match('#.*?\\[(.*?)\\]\\[.*?\\]#', $key, $aTempKey) && $value != '1') { $aProperties[$aTempKey[1]][] = $value; } } $sbuiltString = ''; foreach ($aProperties as $key => $value) { $sbuiltString .= "\n|" . $key . '='; $aTemp = array(); foreach ($value as $key => $val) { $aTemp[] = $val; } $sbuiltString .= implode(',', $aTemp); } $oArticle = Article::newFromID($params['pageId']); $sContent = $oArticle->fetchContent(); $sNewContent = preg_replace('#(\\{\\{' . $webplatformSectionCommentsSMW['template'] . ').*?(\\}\\})#s', "\$1{$sbuiltString}\n\$2", $sContent); $aData = array('wpTextbox1' => $sNewContent, 'wpSummary' => 'no summary', 'wpStarttime' => 'nostarttime', 'wpEdittime' => 'noedittime', 'wpEditToken' => $wgUser->isLoggedIn() ? $wgUser->editToken() : EDIT_TOKEN_SUFFIX, 'wpSave' => '', 'action' => 'submit'); $oRequest = new FauxRequest($aData, true); $oEditor = new EditPage($oArticle); $oEditor->importFormData($oRequest); // Try to save the page! $aResultDetails = array(); $oSaveResult = $oEditor->internalAttemptSave($aResultDetails); // Return value was made an object in MW 1.19 if (is_object($oSaveResult)) { $sSaveResultCode = $oSaveResult->value; } else { $sSaveResultCode = $oSaveResult; } $params['html_response'] = $sSaveResultCode; }
public static function oasisnav2($cv_name, $city_id, $value) { wfProfileIn(__METHOD__); Wikia::log(__METHOD__, $city_id, $cv_name . ' = ' . intval($value)); if ($cv_name == 'wgOasisNavV2') { Wikia::log(__METHOD__, '', 'Started purging wgOasisNav2'); /* @var $navService WikiNavigationService */ $navService = F::build('WikiNavigationService'); $memCacheKey = $navService->getMemcKey(WikiNavigationService::WIKI_LOCAL_MESSAGE); F::app()->wg->memc->set($memCacheKey, null); $title = F::build('Title', array(WikiNavigationService::WIKI_LOCAL_MESSAGE, NS_MEDIAWIKI), 'newFromText'); if ($title instanceof Title) { $article = Article::newFromID($title->getArticleID()); if ($article instanceof Article) { $article->doPurge(); } } WikiFactory::clearCache($city_id); Wikia::log(__METHOD__, '', 'Finished purging wgOasisNav2'); } wfProfileOut(__METHOD__); return true; }
/** * Updates wiki specific properties set from wiki creation wizard. * Context of this method is on the wiki that the values are changing on. * Main wiki creation happens on www, and it will redirect to the newly created wiki. * The values are read from the session and only accessible by the admin. */ public function FinishCreate() { global $wgUser, $wgSitename; if (!$wgUser->isAllowed('finishcreate')) { return false; } $this->skipRendering(); global $wgOut; $this->LoadState(); $mainPage = wfMsgForContent('mainpage'); // set theme if (!empty($this->params['color-body'])) { $themeSettings = new ThemeSettings(); $themeSettings->saveSettings($this->params); } // set description on main page if (!empty($this->params['wikiDescription'])) { $mainTitle = Title::newFromText($mainPage); $mainId = $mainTitle->getArticleID(); $mainArticle = Article::newFromID($mainId); if (!empty($mainArticle)) { global $wgParser; $mainPageText = $mainArticle->getRawText(); $matches = array(); $description = $this->params['wikiDescription']; if (preg_match('/={2,3}[^=]+={2,3}/', $mainPageText, $matches)) { $newSectionTitle = str_replace('Wiki', $wgSitename, $matches[0]); $description = "{$newSectionTitle}\n{$description}"; } $newMainPageText = $wgParser->replaceSection($mainPageText, 1, $description); $mainArticle->doEdit($newMainPageText, ''); } } $wgOut->enableClientCache(false); $wgOut->redirect($mainPage . '?wiki-welcome=1'); }
foreach ( $messages['en'] as $key => $text ) { echo "Fetching articles from messaging for key = $key... "; $ucKey = ucfirst( $key ); $query = "SELECT page_id AS id, page_title AS title FROM page WHERE page_namespace = 8 AND page_title LIKE '" . $dbr->escapeLike( $ucKey ) . "/%'"; $res = $dbr->query( $query ); echo "Got " . $dbr->numRows( $res ) . " articles.\n"; while ( $row = $dbr->fetchObject( $res ) ) { list( $cKey, $cLang ) = explode( '/', $row->title ); $cKey = strtolower( $cKey ); $oArticle = Article::newFromID( $row->id ); # echo "Collected $cLang version of $cKey\n"; $collected[$cLang][$cKey] = $oArticle->getContent(); } } $fh = fopen( $file, "a" ); echo "\n*** WRITING TO FILE $file...\n"; foreach ( $collected as $wLang => $wMessages ) { if ( !empty( $messages[$wLang] ) ) { continue; } echo "\tLang: $wLang\n";
/** * Sets the Article instance via an article ID * @param integer $articleId A valid article ID from which * an Article instance will be constructed to be used as a * source of content * @return ArticleService fluent interface */ public function setArticleById($articleId) { $this->article = Article::newFromID($articleId); return $this; }
/** * Start the upload. Note that this method always returns an object, even when it fails. * Make sure to check that the return value with: * * $status->isOK() * * @param $oTitle - A title object that will be set if this call is successful * @return FileRepoStatus|Status - A status object representing the result of this call * @throws Exception */ public function upload(&$oTitle) { $apiWrapper = $this->getApiWrapper(); $thumbnailUrl = null; if (method_exists($apiWrapper, 'getThumbnailUrl')) { // Some providers will sometimes return error codes when attempting // to fetch a thumbnail try { $upload = $this->uploadBestThumbnail($apiWrapper->getThumbnailUrl()); } catch (Exception $e) { WikiaLogger::instance()->error('Video upload failed', ['targetFile' => $this->sTargetTitle, 'externalURL' => $this->sExternalUrl, 'videoID' => $this->sVideoId, 'provider' => $this->sProvider, 'exception' => $e]); return Status::newFatal($e->getMessage()); } } else { WikiaLogger::instance()->error('Api wrapper corrupted', ['targetFile' => $this->sTargetTitle, 'overrideMetadata' => $this->aOverrideMetadata, 'externalURL' => $this->sExternalUrl, 'videoID' => $this->sVideoId, 'provider' => $this->sProvider, 'apiWrapper' => get_class($apiWrapper)]); } $oTitle = Title::newFromText($this->getNormalizedDestinationTitle(), NS_FILE); // Check if the user has the proper permissions // Mimicks Special:Upload's behavior $user = F::app()->wg->User; $permErrors = $oTitle->getUserPermissionsErrors('edit', $user); $permErrorsUpload = $oTitle->getUserPermissionsErrors('upload', $user); if (!$oTitle->exists()) { $permErrorsCreate = $oTitle->getUserPermissionsErrors('create', $user); } else { $permErrorsCreate = []; } if ($permErrors || $permErrorsUpload || $permErrorsCreate) { $permErrors = array_merge($permErrors, wfArrayDiff2($permErrorsUpload, $permErrors)); $permErrors = array_merge($permErrors, wfArrayDiff2($permErrorsCreate, $permErrors)); $msgKey = array_shift($permErrors[0]); throw new Exception(wfMessage($msgKey, $permErrors[0])->parse()); } if ($oTitle->exists()) { // @TODO // if video already exists make sure that we are in fact changing something // before generating upload (for now this only works for edits) $articleId = $oTitle->getArticleID(); $article = Article::newFromID($articleId); // In case Article is null log more info and throw an exception if (is_null($article)) { $exception = new VideoUploadFailedException('Video upload failed'); WikiaLogger::instance()->error('Video upload: title exists but article is null', ['Title object' => $oTitle, 'Video title' => $this->getNormalizedDestinationTitle(), 'Article ID' => $articleId, 'Title from ID' => Title::newFromID($articleId), 'exception' => $exception]); throw $exception; } $content = $article->getContent(); $newcontent = $this->getDescription(); if ($content != $newcontent) { $article->doEdit($newcontent, wfMessage('videos-update-edit-summary')->inContentLanguage()->text()); } } $class = !empty($this->bUndercover) ? 'WikiaNoArticleLocalFile' : 'WikiaLocalFile'; /** @var WikiaLocalFile $file */ $file = new $class($oTitle, RepoGroup::singleton()->getLocalRepo()); /* override thumbnail metadata with video metadata */ $file->forceMime($this->getApiWrapper()->getMimeType()); $file->setVideoId($this->getVideoId()); /* ingestion video won't be able to load anything so we need to spoon feed it the correct data */ if ($this->getApiWrapper()->isIngestion()) { $file->forceMetadata(serialize($this->getNormalizedMetadata())); } $forceMime = $file->forceMime; $file->getMetadata(); //In case of video replacement - Title already exists - preserve forceMime value. //By default it is changed to false in WikiaLocalFileShared::afterSetProps method //which is called by $file->getMetadata(). if ($oTitle->exists()) { $file->forceMime = $forceMime; } /* real upload */ $result = $file->upload($upload->getTempPath(), wfMessage('videos-initial-upload-edit-summary')->inContentLanguage()->text(), \UtfNormal::toNFC($this->getDescription()), File::DELETE_SOURCE); wfRunHooks('AfterVideoFileUploaderUpload', array($file, $result)); return $result; }
public function getAsJson() { $articleId = $this->getRequest()->getInt(self::SIMPLE_JSON_ARTICLE_ID_PARAMETER_NAME, NULL); $articleTitle = $this->getRequest()->getVal(self::SIMPLE_JSON_ARTICLE_TITLE_PARAMETER_NAME, NULL); $redirect = $this->request->getVal('redirect'); if (!empty($articleId) && !empty($articleTitle)) { throw new BadRequestApiException('Can\'t use id and title in the same request'); } if (empty($articleId) && empty($articleTitle)) { throw new BadRequestApiException('You need to pass title or id of an article'); } if (!empty($articleId)) { $article = Article::newFromID($articleId); } else { $title = Title::newFromText($articleTitle, NS_MAIN); if ($title instanceof Title && $title->exists()) { $article = Article::newFromTitle($title, RequestContext::getMain()); } } if (empty($article)) { throw new NotFoundApiException("Unable to find any article"); } if ($redirect !== 'no' && $article->getPage()->isRedirect()) { // false, Title object of local target or string with URL $followRedirect = $article->getPage()->followRedirect(); if ($followRedirect && !is_string($followRedirect)) { $article = Article::newFromTitle($followRedirect, RequestContext::getMain()); } } //Response is based on wikiamobile skin as this already removes inline style //and make response smaller RequestContext::getMain()->setSkin(Skin::newFromKey('wikiamobile')); global $wgArticleAsJson; $wgArticleAsJson = true; $parsedArticle = $article->getParserOutput(); if ($parsedArticle instanceof ParserOutput) { $articleContent = json_decode($parsedArticle->getText()); } else { throw new ArticleAsJsonParserException('Parser is currently not available'); } $wgArticleAsJson = false; $categories = []; foreach (array_keys($parsedArticle->getCategories()) as $category) { $categoryTitle = Title::newFromText($category, NS_CATEGORY); if ($categoryTitle) { $categories[] = ['title' => $categoryTitle->getText(), 'url' => $categoryTitle->getLocalURL()]; } } $result = ['content' => $articleContent->content, 'media' => $articleContent->media, 'users' => $articleContent->users, 'categories' => $categories]; $this->setResponseData($result, '', self::SIMPLE_JSON_VARNISH_CACHE_EXPIRATION); }