Esempio n. 1
0
function wfSpecialCheckmylinks($par)
{
    global $wgRequest, $wgSitename, $wgLanguageCode;
    global $wgDeferredUpdateList, $wgOut, $wgUser, $wgServer, $wgParser, $wgTitle;
    $fname = "wfCheckmylinks";
    $wgOut->addHTML(wfMsgWikiHtml('checkmylinks_summary'));
    if ($wgUser->getID() > 0) {
        $t = Title::makeTitle(NS_USER, $wgUser->getName() . "/Mylinks");
        if ($t->getArticleID() > 0) {
            $r = Revision::newFromTitle($t);
            $text = $r->getText();
            if ($text != "") {
                $ret = "<h3>" . wfMsg('mylinks') . "</h3>";
                $options = new ParserOptions();
                $output = $wgParser->parse($text, $wgTitle, $options);
                $ret .= $output->getText();
            }
            $size = strlen($ret);
            if ($size > 3000) {
                $wgOut->addHTML(wfMsgWikiHtml('checkmylinks_size_bad', number_format($size, 0, "", ",")));
            } else {
                $wgOut->addHTML(wfMsgWikiHtml('checkmylinks_size_good', number_format($size, 0, "", ",")));
            }
        } else {
            $wgOut->addHTML(wfMsgWikiHtml('checkmylinks_error'));
        }
    } else {
        $wgOut->addHTML(wfMsgWikiHtml('checkmylinks_notloggedin'));
    }
}
Esempio n. 2
0
 function getRepublishText($t)
 {
     global $wgRequest, $wgContLang, $wgOut, $wgServer;
     if (!$t) {
         return "";
     }
     $r = Revision::newFromTitle($t);
     $mp = Title::newMainPage();
     $title = "<h1 style='margin-bottom: 0px;'><a href=\"" . $t->getFullURL() . "\">" . wfMsg('howto', $t->getText()) . "</a></h1>\n" . wfMsg('republish_taglinelink', $mp->getFullURL()) . "<br/>";
     if (!$r) {
         return "";
     }
     $text = $r->getText();
     if ($wgRequest->getVal('striptags', 'true') != 'false') {
         $text = preg_replace("/\\[\\[" . $wgContLang->getNSText(NS_IMAGE) . "[^\\]]*\\]\\]/", "", $text);
     }
     $output = $wgOut->parse($text);
     //$output = str_replace("<div class='SecL'></div><div class='SecR'></div>", "", $output);
     //$output = preg_replace("/<div id=\"[a-z]*\"/", "<div ", $output);
     $output = str_replace('href="/', 'href="' . $wgServer . '/', $output);
     if ($wgRequest->getVal('striptags', 'true') != 'false') {
         $output = strip_tags($output, '<b><i><h1><h2><ol><ul><li><a>');
     } else {
         $output = str_replace('<img src="/', '<img src="http://www.wikihow.com/', $output);
     }
     $output = preg_replace("@href=(['\"])/@", "href=\$1{$wgServer}/", $output);
     $output = $title . "\n" . $output . wfMsg('republish_footer', $t->getText(), $t->getFullURL());
     $output = preg_replace("/\n\n[\n]*/", "\n", $output);
     return $output;
 }
	function parse($grammarName, &$text) {
		wfDebugLog("ParseEngine", "==========Start Parse Engine==========\n");
		$grammar = isset($this->mGrammars[$grammarName]) ? $this->mGrammars[$grammarName] : NULL;
		if ($grammar == NULL) {
			$revision = Revision::newFromTitle(Title::newFromText($grammarName, NS_GRAMMAR));
			$grammar = new DOMDocument();
			if ($revision == NULL || ! $grammar->loadXML($revision->getText(), LIBXML_NOBLANKS)) {
				return TRUE;
			}
			$this->pushTags($grammar->documentElement, NULL);
			$this->mGrammars[$grammarName] = $grammar;
		}
		$doc = new DOMDocument();
		$rootTag = $doc->createElement($grammar->documentElement->getAttribute("rootTag"));
		$startRule = $grammar->documentElement->getAttribute("startRule");
		$xpath = new DOMXPath($grammar);
		$startRule = $xpath->query("/Grammar/*[@name='$startRule']")->item(0);
		$refText = $text;
		if (! $this->parseRec($startRule, "", "", $iter, $refText, $rootTag)) {
			return TRUE;
		}
		$doc->appendChild($rootTag);
		$text = $doc->saveXML();
		wfDebugLog("ParseEngine", "Parsed text - $text\n");
		return TRUE;
	}
Esempio n. 4
0
 function displayQuickNoteButtons($id = '')
 {
     global $wgLanguageCode;
     // INTL: Only give these buttons to english site
     if ($wgLanguageCode != 'en') {
         return "";
     }
     list($tb1, $tb2, $tb3) = QuickNoteEdit::getQNTemplates();
     $start1 = strpos($tb1, "{{subst:") + strlen("{{subst:");
     $end1 = strpos($tb1, "|") - strlen("{{subst:");
     $tp1 = substr($tb1, $start1, $end1);
     $template = Title::makeTitle(NS_TEMPLATE, $tp1);
     $r = Revision::newFromTitle($template);
     $tb1_message = $r->getText();
     $tb1_message = preg_replace('/<noinclude>(.*?)<\\/noinclude>/is', '', $tb1_message);
     $tb1_message = str_replace("\n", "\\n", $tb1_message);
     $tb1_message = str_replace("'", "\\'", $tb1_message);
     $start3 = strpos($tb3, "{{subst:") + strlen("{{subst:");
     $end3 = strpos($tb3, "|") - strlen("{{subst:");
     $tp3 = substr($tb3, $start3, $end3);
     $template = Title::makeTitle(NS_TEMPLATE, $tp3);
     $r = Revision::newFromTitle($template);
     $tb3_message = $r->getText();
     $tb3_message = preg_replace('/<noinclude>(.*?)<\\/noinclude>/is', '', $tb3_message);
     $tb3_message = str_replace("\n", "\\n", $tb3_message);
     $tb3_message = str_replace("'", "\\'", $tb3_message);
     $buttons = "<div><br /><input tabindex='1' class='button secondary' type='button' value='" . wfMsg('Quicknote_Button1') . "' onclick=\"checkThumbsUp();qnButtons('postcommentForm_" . $id . "', '" . $tb1_message . "')\" />\n\t\t <input tabindex='3' class='button secondary' type='button' value='" . wfMsg('Quicknote_Button3') . "' onclick=\"qnButtons('postcommentForm_" . $id . "', '" . $tb3_message . "')\" /></div>";
     return $buttons;
 }
Esempio n. 5
0
 /**
  * Obtain the parse of a wiki article
  */
 public function execute()
 {
     $titles = $this->getPageSet()->getGoodTitles();
     if (count($titles) == 0) {
         return;
     }
     $params = $this->extractRequestParams();
     foreach ($titles as $title) {
         $pageId = $title->getArticleID();
         if (!$title->hasSourceText()) {
             $results = array('errors' => 'Title does not exist');
         } else {
             if (!$title->userCan('read')) {
                 $results = array('errors' => 'Cannot read this title');
             } else {
                 # Get the article text
                 $rev = Revision::newFromTitle($title);
                 if (!is_object($rev)) {
                     $results = array('errors' => 'Could not get revision');
                 } else {
                     $text = $rev->getText();
                     $results['contents'] = $this->getParseTree($text);
                 }
             }
         }
         foreach ($results as $elementName => $item) {
             $fit = $this->addPageSubItem($pageId, $item, $elementName);
             if (!$fit) {
                 /* ?? this should never happen */
             }
         }
     }
 }
Esempio n. 6
0
 public function execute()
 {
     global $wgCityId;
     $db = wfGetDB(DB_MASTER);
     (new WikiaSQL())->SELECT('*')->FROM('page')->WHERE('page_is_redirect')->EQUAL_TO(1)->runLoop($db, function ($a, $row) use($db) {
         $title = Title::newFromID($row->page_id);
         if (!$title->isDeleted()) {
             $rev = Revision::newFromTitle($title);
             $text = $rev->getText();
             $rt = Title::newFromRedirectRecurse($text);
             if (!$rt) {
                 // page is marked as redirect but $text is not valid redirect
                 $this->output('Fixed ID: ' . $title->getArticleID() . ' Title: ' . $title->getText() . "\n");
                 // Fix page table
                 (new WikiaSQL())->UPDATE('page')->SET('page_is_redirect', 0)->WHERE('page_id')->EQUAL_TO($row->page_id)->RUN($db);
                 // remove redirect from redirect table
                 (new WikiaSQL())->DELETE('redirect')->WHERE('rd_from')->EQUAL_TO($row->page_id)->RUN($db);
                 // clear cache
                 LinkCache::singleton()->addGoodLinkObj($row->page_id, $title, strlen($text), 0, $rev->getId());
                 if ($title->getNamespace() == NS_FILE) {
                     RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect($title);
                 }
             }
         }
     });
 }
 public function validateTitle($title)
 {
     if (!$title) {
         // No form input yet
         return true;
     }
     try {
         $titleObj = Title::newFromTextThrow($title);
     } catch (MalformedTitleException $e) {
         $msg = $this->msg($e->getErrorMessage());
         $params = $e->getErrorMessageParameters();
         if ($params) {
             $msg->params($params);
         }
         return $msg->parse();
     }
     if (!$titleObj->canExist()) {
         return $this->msg('changecontentmodel-title-cantexist', $titleObj->getPrefixedText())->escaped();
     }
     $this->oldRevision = Revision::newFromTitle($titleObj) ?: false;
     if ($this->oldRevision) {
         $oldContent = $this->oldRevision->getContent();
         if (!$oldContent->getContentHandler()->supportsDirectEditing()) {
             return $this->msg('changecontentmodel-nodirectediting')->params(ContentHandler::getLocalizedName($oldContent->getModel()))->escaped();
         }
     }
     return true;
 }
Esempio n. 8
0
 function getTopLevelCategories()
 {
     global $wgCategoriesArticle;
     wfLoadExtensionMessages('Sitemap');
     $results = array();
     $revision = Revision::newFromTitle(Title::newFromText(wfMsg('categories_article')));
     if (!$revision) {
         return $results;
     }
     // INTL: If there is a redirect to a localized page name, follow it
     if (strpos($revision->getText(), "#REDIRECT") !== false) {
         $revision = Revision::newFromTitle(Title::newFromRedirect($revision->getText()));
     }
     $lines = split("\n", $revision->getText());
     foreach ($lines as $line) {
         if (preg_match('/^\\*[^\\*]/', $line)) {
             $line = trim(substr($line, 1));
             switch ($line) {
                 case "Other":
                 case "wikiHow":
                     break;
                 default:
                     $results[] = $line;
             }
         }
     }
     return $results;
 }
 protected function handleRow(stdClass $row)
 {
     $title = Title::makeTitle($row->page_namespace, $row->page_title);
     $this->output("Processing {$title} ({$row->page_id})...\n");
     $rev = Revision::newFromTitle($title);
     $content = $rev->getContent(Revision::RAW);
     $dbw = $this->getDB(DB_MASTER);
     if ($content instanceof JsonContent) {
         if ($content->isValid()) {
             // Yay, actually JSON. We need to just change the
             // page_content_model because revision will automatically
             // use the default, which is *now* JSON.
             $this->output("Setting page_content_model to json...");
             $dbw->update('page', ['page_content_model' => CONTENT_MODEL_JSON], ['page_id' => $row->page_id], __METHOD__);
             $this->output("done.\n");
             wfWaitForSlaves();
         } else {
             // Not JSON...force it to wikitext. We need to update the
             // revision table so that these revisions are always processed
             // as wikitext in the future. page_content_model is already
             // set to "wikitext".
             $this->output("Setting rev_content_model to wikitext...");
             // Grab all the ids for batching
             $ids = $dbw->selectFieldValues('revision', 'rev_id', ['rev_page' => $row->page_id], __METHOD__);
             foreach (array_chunk($ids, 50) as $chunk) {
                 $dbw->update('revision', ['rev_content_model' => CONTENT_MODEL_WIKITEXT], ['rev_page' => $row->page_id, 'rev_id' => $chunk]);
                 wfWaitForSlaves();
             }
             $this->output("done.\n");
         }
     } else {
         $this->output("not a JSON page? Skipping\n");
     }
 }
Esempio n. 10
0
function fixLinksFromArticle( $id ) {
	global $wgTitle, $wgParser;

	$wgTitle = Title::newFromID( $id );
	$dbw = wfGetDB( DB_MASTER );

	$linkCache =& LinkCache::singleton();
	$linkCache->clear();

	if ( is_null( $wgTitle ) ) {
		return;
	}
	$dbw->begin();

	$revision = Revision::newFromTitle( $wgTitle );
	if ( !$revision ) {
		return;
	}

	$options = new ParserOptions;
	$parserOutput = $wgParser->parse( $revision->getText(), $wgTitle, $options, true, true, $revision->getId() );
	$update = new LinksUpdate( $wgTitle, $parserOutput, false );
	$update->doUpdate();
	$dbw->commit();
}
Esempio n. 11
0
 function formatResult($skin, $result)
 {
     global $wgContLang;
     # Make a link to the redirect itself
     $rd_title = Title::makeTitle($result->namespace, $result->title);
     $rd_link = $skin->makeKnownLinkObj($rd_title, '', 'redirect=no');
     # Find out where the redirect leads
     $revision = Revision::newFromTitle($rd_title);
     if ($revision) {
         # Make a link to the destination page
         $target = Title::newFromRedirect($revision->getText());
         if ($target) {
             $targetLink = $skin->makeLinkObj($target);
         } else {
             /** @todo Put in some decent error display here */
             $targetLink = '*';
         }
     } else {
         /** @todo Put in some decent error display here */
         $targetLink = '*';
     }
     # Check the language; RTL wikis need a &larr;
     $arr = $wgContLang->isRTL() ? ' &larr; ' : ' &rarr; ';
     # Format the whole thing and return it
     return $rd_link . $arr . $targetLink;
 }
Esempio n. 12
0
	/**
	 * Run a refreshLinks job
	 * @return boolean success
	 */
	function run() {
		$linkCache = LinkCache::singleton();
		$linkCache->clear();

		if ( is_null( $this->title ) ) {
			$this->error = "refreshLinks: Invalid title";
			return false;
		}

		# Wait for the DB of the current/next slave DB handle to catch up to the master.
		# This way, we get the correct page_latest for templates or files that just changed
		# milliseconds ago, having triggered this job to begin with.
		if ( isset( $this->params['masterPos'] ) && $this->params['masterPos'] !== false ) {
			wfGetLB()->waitFor( $this->params['masterPos'] );
		}

		$revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
		if ( !$revision ) {
			$this->error = 'refreshLinks: Article not found "' .
				$this->title->getPrefixedDBkey() . '"';
			return false; // XXX: what if it was just deleted?
		}

		self::runForTitleInternal( $this->title, $revision, __METHOD__ );

		return true;
	}
Esempio n. 13
0
 protected function getHTML($title, $parserParams)
 {
     $restoring = false;
     if ($title->exists()) {
         $latestRevision = Revision::newFromTitle($title);
         if ($latestRevision === null) {
             return false;
         }
         $revision = null;
         if (!isset($parserParams['oldid']) || $parserParams['oldid'] === 0) {
             $parserParams['oldid'] = $latestRevision->getId();
             $revision = $latestRevision;
         } else {
             $revision = Revision::newFromId($parserParams['oldid']);
             if ($revision === null) {
                 return false;
             }
         }
         $restoring = $revision && !$revision->isCurrent();
         $oldid = $parserParams['oldid'];
         $content = $this->requestParsoid('GET', $title, $parserParams);
         if ($content === false) {
             return false;
         }
         $timestamp = $latestRevision->getTimestamp();
     } else {
         $content = '';
         $timestamp = wfTimestampNow();
         $oldid = 0;
     }
     return array('result' => array('content' => $content, 'basetimestamp' => $timestamp, 'starttimestamp' => wfTimestampNow(), 'oldid' => $oldid), 'restoring' => $restoring);
 }
function smwf_et_Access($method, $params)
{
    global $smwgQEnabled, $smwgExtTabEnabled;
    $result = "Semantic ExtTab disabled.";
    if ($method == "internalLoad") {
        if ($smwgExtTabEnabled) {
            $p = explode(',', $params, 2);
            $title = $p[1];
            $html = $title;
            global $wgTitle, $smwgIQRunningNumber;
            // pay attention to $smwgIQRunningNumber
            $smwgIQRunningNumber = intval($p[0]) * 10;
            $wgTitle = Title::newFromText($title);
            $revision = Revision::newFromTitle($wgTitle);
            if ($revision !== NULL) {
                global $wgParser, $wgOut;
                $popts = $wgOut->parserOptions();
                $popts->setTidy(true);
                $popts->enableLimitReport();
                $html = $wgParser->parse($revision->getText(), $wgTitle, $popts)->getText();
            }
            return $html;
        }
    } else {
        return "Operation failed, please retry later.";
    }
    return $result;
}
 public function getExtract($title, $chars = 50)
 {
     $rev = Revision::newFromTitle($title);
     if ($rev) {
         $text = substr($rev->getText(), 0, 16384);
         // Ok, first note this is a TERRIBLE HACK. :D
         //
         // First, we use the system preprocessor to break down the text
         // into text, templates, extensions, and comments:
         global $wgParser;
         $wgParser->mOptions = new ParserOptions();
         $wgParser->clearState();
         $frame = $wgParser->getPreprocessor()->newFrame();
         $dom = $wgParser->preprocessToDom($text);
         $imageArgs = array('image', 'image_skyline', 'img', 'Img');
         // Now, we strip out everything that's not text.
         // This works with both DOM and Hash parsers, but feels fragile.
         $node = $dom->getFirstChild();
         $out = '';
         while ($node) {
             if ($node->getName() == '#text') {
                 $out .= $frame->expand($node, PPFrame::RECOVER_ORIG);
             }
             $node = $node->getNextSibling();
         }
         // The remaining text may still contain wiki and HTML markup.
         // We'll use our shitty hand parser to strip most of those from
         // the beginning of the text.
         $stripped = $this->_stripMarkup($out);
         // And now, we'll grab just the first sentence as text, and
         // also try to rip out a badge image.
         return $this->_extractStart($stripped);
     }
     return '';
 }
Esempio n. 16
0
 public static function adminPostTalkMessage($to_user, $from_user, $comment)
 {
     global $wgLang;
     $existing_talk = '';
     //make sure we have everything we need...
     if (empty($to_user) || empty($from_user) || empty($comment)) {
         return false;
     }
     $from = $from_user->getName();
     if (!$from) {
         return false;
     }
     //whoops
     $from_realname = $from_user->getRealName();
     $dateStr = $wgLang->date(wfTimestampNow());
     $formattedComment = wfMsg('postcomment_formatted_comment', $dateStr, $from, $from_realname, $comment);
     $talkPage = $to_user->getUserPage()->getTalkPage();
     if ($talkPage->getArticleId() > 0) {
         $r = Revision::newFromTitle($talkPage);
         $existing_talk = $r->getText() . "\n\n";
     }
     $text = $existing_talk . $formattedComment . "\n\n";
     $flags = EDIT_FORCE_BOT | EDIT_SUPPRESS_RC;
     $article = new Article($talkPage);
     $result = $article->doEdit($text, "", $flags);
     return $result;
 }
 function getRS()
 {
     $t = Title::newFromText('wikiHow:Rising-star-feed');
     if ($t->getArticleId() > 0) {
         $r = Revision::newFromTitle($t);
         $text = $r->getText();
     } else {
         return false;
     }
     $rsout = array();
     $rs = $text;
     $rs = preg_replace("/==\n/", ',', $rs);
     $rs = preg_replace("/^==/", "", $rs);
     $lines = preg_split("/\r|\n/", $rs, null, PREG_SPLIT_NO_EMPTY);
     $count = 0;
     foreach ($lines as $line) {
         if (preg_match('/^==(.*?),(.*?)$/', $line, $matches)) {
             $dt = $matches[1];
             $pattern = "/{$wgServer}/";
             $title = preg_replace("/http:\\/\\/www\\.wikihow\\.com\\//", "", $matches[2]);
             $rsout[$title] = $dt;
         }
     }
     return $rsout;
 }
 /**
  * Run a refreshLinks job
  * @return boolean success
  */
 function run()
 {
     global $wgParser;
     wfProfileIn(__METHOD__);
     $linkCache =& LinkCache::singleton();
     $linkCache->clear();
     if (is_null($this->title)) {
         $this->error = "refreshLinks: Invalid title";
         wfProfileOut(__METHOD__);
         return false;
     }
     $revision = Revision::newFromTitle($this->title);
     if (!$revision) {
         $this->error = 'refreshLinks: Article not found "' . $this->title->getPrefixedDBkey() . '"';
         wfProfileOut(__METHOD__);
         return false;
     }
     wfProfileIn(__METHOD__ . '-parse');
     $options = new ParserOptions();
     $parserOutput = $wgParser->parse($revision->getText(), $this->title, $options, true, true, $revision->getId());
     wfProfileOut(__METHOD__ . '-parse');
     wfProfileIn(__METHOD__ . '-update');
     $update = new LinksUpdate($this->title, $parserOutput, false);
     $update->doUpdate();
     wfProfileOut(__METHOD__ . '-update');
     wfProfileOut(__METHOD__);
     return true;
 }
Esempio n. 19
0
 private function handleImageFeedback()
 {
     global $wgRequest, $wgOut, $wgName, $wgUser;
     $dbw = wfGetDB(DB_MASTER);
     $reason = $wgRequest->getVal('reason');
     // Remove / chars from reason since this will be our delimeter in the ii_reason field
     $reason = $dbw->strencode(trim(str_replace("/", "", $reason)));
     // Add user who reported
     $reason = $wgUser->getName() . " says: {$reason}";
     $voteTypePrefix = $wgRequest->getVal('voteType') == 'good' ? 'ii_good' : 'ii_bad';
     $aid = $dbw->addQuotes($wgRequest->getVal('aid'));
     $imgUrl = substr(trim($wgRequest->getVal('imgUrl')), 1);
     $isWikiPhotoImg = 0;
     // Check if image is a wikiphoto image
     $t = Title::newFromUrl($imgUrl);
     if ($t && $t->exists()) {
         $r = Revision::newFromTitle($t);
         $userText = $r->getUserText();
         if (strtolower($r->getUserText()) == self::WIKIPHOTO_USER_NAME) {
             $isWikiPhotoImg = 1;
         }
         $url = substr($t->getLocalUrl(), 1);
         $voteField = $voteTypePrefix . "_votes";
         $reasonField = $voteTypePrefix . "_reasons";
         $sql = "INSERT INTO image_feedback \n\t\t\t\t(ii_img_page_id, ii_wikiphoto_img, ii_page_id, ii_img_url, {$voteField}, {$reasonField}) VALUES \n\t\t\t\t({$t->getArticleId()}, {$isWikiPhotoImg}, {$aid}, '{$url}', 1, '{$reason}') \n\t\t\t\tON DUPLICATE KEY UPDATE\n\t\t\t\t{$voteField} = {$voteField} + 1, {$reasonField} = CONCAT({$reasonField}, '/{$reason}')";
         $dbw->query($sql, __METHOD__);
         $wgOut->setArticleBodyOnly(true);
     }
 }
 /**
  * check for plagiarism with copyscape
  * return true if there's an issue
  */
 private static function copyCheck($t)
 {
     $threshold = 0.05;
     $result = '';
     $r = Revision::newFromTitle($t);
     if (!$r) {
         return 'No such article';
     }
     $text = Wikitext::flatten($r->getText());
     $res = copyscape_api_text_search_internet($text, 'ISO-8859-1', 2);
     if ($res['count']) {
         $words = $res['querywords'];
         foreach ($res['result'] as $r) {
             if (!preg_match("@^http://[a-z0-9]*.(wikihow|whstatic|youtube).com@i", $r['url'])) {
                 //if ($r['minwordsmatched'] / $words > $threshold) {
                 //we got one!
                 $result .= '<b>Plagiarized:</b> <a href="' . $r['url'] . '">' . $r['url'] . '</a><br />';
                 //}
             }
         }
     } else {
         $result = '';
     }
     return $result;
 }
Esempio n. 21
0
 /**
  * Run job
  * @return boolean success
  */
 function run()
 {
     wfProfileIn('SMWUpdateJob::run (SMW)');
     global $wgParser;
     LinkCache::singleton()->clear();
     if (is_null($this->title)) {
         $this->error = "SMWUpdateJob: Invalid title";
         wfProfileOut('SMWUpdateJob::run (SMW)');
         return false;
     } elseif (!$this->title->exists()) {
         smwfGetStore()->deleteSubject($this->title);
         // be sure to clear the data
         wfProfileOut('SMWUpdateJob::run (SMW)');
         return true;
     }
     $revision = Revision::newFromTitle($this->title);
     if (!$revision) {
         $this->error = 'SMWUpdateJob: Page exists but no revision was found for "' . $this->title->getPrefixedDBkey() . '"';
         wfProfileOut('SMWUpdateJob::run (SMW)');
         return false;
     }
     wfProfileIn(__METHOD__ . '-parse');
     $options = new ParserOptions();
     $output = $wgParser->parse($revision->getText(), $this->title, $options, true, true, $revision->getID());
     wfProfileOut(__METHOD__ . '-parse');
     wfProfileIn(__METHOD__ . '-update');
     SMWParseData::storeData($output, $this->title, false);
     wfProfileOut(__METHOD__ . '-update');
     wfProfileOut('SMWUpdateJob::run (SMW)');
     return true;
 }
Esempio n. 22
0
 /**
  * Loads the mapping table.
  */
 private function loadTable()
 {
     // no need to load multiple times.
     if ($this->loaded) {
         return;
     }
     $this->loaded = true;
     $title = Title::newFromText(self::$tablePageName);
     if (!$title->exists()) {
         return;
     }
     $tablePageRev = Revision::newFromTitle($title);
     if (is_object($tablePageRev)) {
         $tablePage = $tablePageRev->getText();
         global $wgUser;
         $parser = new Parser();
         $parser->setFunctionHook('tag_to_template', array($this, 'mg_tag_to_template'));
         // this will populate the 'map' variable
         // assuming of course that the page was edited with
         // {{#tag_to_template| ... }} instructions.
         $this->initPhase = true;
         $parser->parse($tablePage, $title, new ParserOptions($wgUser));
         $this->initPhase = false;
     }
 }
Esempio n. 23
0
 function formatResult($skin, $result)
 {
     global $wgContLang;
     # Make a link to the redirect itself
     $rd_title = Title::makeTitle($result->namespace, $result->title);
     $arr = $wgContLang->getArrow() . $wgContLang->getDirMark();
     $rd_link = $skin->makeKnownLinkObj($rd_title, '', 'redirect=no');
     # Find out where the redirect leads
     $revision = Revision::newFromTitle($rd_title);
     if ($revision) {
         # Make a link to the destination page
         $target = Title::newFromRedirect($revision->getText());
         if ($target) {
             $targetLink = $skin->makeLinkObj($target);
         } else {
             /** @todo Put in some decent error display here */
             $targetLink = '*';
         }
     } else {
         /** @todo Put in some decent error display here */
         $targetLink = '*';
     }
     # Format the whole thing and return it
     return "{$rd_link} {$arr} {$targetLink}";
 }
 /**
  * ToC rendering for non-hubs
  * @param $title Title of hub the ToC is generated off
  * @return string html
  */
 public function renderSubpageToC(Title $title)
 {
     $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
     // We assume $title is sane. This is supposed to be called with a $title gotten from CollaborationHubContent::getParentHub, which already checks if it is.
     $rev = Revision::newFromTitle($title);
     $content = $rev->getContent();
     $colour = $content->getThemeColour();
     $image = $content->getImage();
     $html = Html::openElement('div', ['class' => "mw-ck-theme-{$colour}"]);
     $html .= Html::openElement('div', ['class' => "mw-ck-subpage-toc"]);
     // ToC label
     $html .= Html::rawElement('div', ['class' => 'mw-ck-toc-label'], Html::rawElement('span', [], wfMessage('collaborationkit-subpage-toc-label')->inContentLanguage()->text()));
     // hubpage
     $name = $content->getDisplayName() == '' ? $title->getText() : $content->getDisplayName();
     $link = $this->renderItem($title, $name, $image, 16);
     $html .= Html::rawElement('div', ['class' => 'mw-ck-toc-subpage-hub'], $link);
     // Contents
     $html .= Html::openElement('ul', ['class' => 'mw-ck-toc-contents']);
     foreach ($content->getContent() as $item) {
         $itemTitle = Title::newFromText($item['title']);
         if (isset($item['display_title'])) {
             $itemDisplayTitle = $item['display_title'];
         } else {
             $itemDisplayTitle = $itemTitle->getSubpageText();
         }
         $itemImage = isset($item['image']) ? $item['image'] : $itemDisplayTitle;
         $itemLink = $this->renderItem($itemTitle, $itemDisplayTitle, $itemImage, $colour, 16);
         $html .= Html::rawElement('li', ['class' => 'mw-ck-toc-item'], $itemLink);
     }
     $html .= Html::closeElement('ul');
     $html .= Html::closeElement('div');
     $html .= Html::closeElement('div');
     return $html;
 }
 private function removeImagesFromArticle($articleId)
 {
     $title = Title::newFromID($articleId);
     if ($title) {
         $revision = Revision::newFromTitle($title);
         $text = $revision->getText();
         //regular expressions copied out of maintenance/wikiphotoProcessImages.php
         //but modified to remove the leading BR tags if they exist
         //In the callback we keep track of each image name that we remove
         $text = preg_replace_callback('@(<\\s*br\\s*[\\/]?>)*\\s*\\[\\[Image:([^\\]]*)\\]\\]@im', function ($matches) {
             $image = $matches[2];
             $pipeLoc = strpos($image, "|");
             if ($pipeLoc !== false) {
                 $image = substr($image, 0, $pipeLoc);
             }
             AdminImageRemoval::$imagesRemoved[] = $image;
             return '';
         }, $text);
         $text = preg_replace_callback('@(<\\s*br\\s*[\\/]?>)*\\s*\\{\\{largeimage\\|([^\\}]*)\\}\\}@im', function ($matches) {
             $image = $matches[2];
             AdminImageRemoval::$imagesRemoved[] = $image;
             return '';
         }, $text);
         $text = preg_replace('@(<\\s*br\\s*[\\/]?>)*\\s*\\{\\{largeimage\\|[^\\}]*\\}\\}@im', '', $text);
         $article = new Article($title);
         $saved = $article->doEdit($text, 'Removing all images from article.');
     }
 }
Esempio n. 26
0
 /**
  * @param WebRequest $request
  */
 function show($request)
 {
     global $wgOut, $wgUser;
     $first = $this->revisions[0];
     $wgOut->addWikiText(wfMsg('revdelete-selected', $this->page->getPrefixedText()));
     $wgOut->addHtml("<ul>");
     foreach ($this->revisions as $revid) {
         $rev = Revision::newFromTitle($this->page, $revid);
         $wgOut->addHtml($this->historyLine($rev));
         $bitfields[] = $rev->mDeleted;
         // FIXME
     }
     $wgOut->addHtml("</ul>");
     $wgOut->addWikiText(wfMsg('revdelete-text'));
     $items = array(wfInputLabel(wfMsg('revdelete-log'), 'wpReason', 'wpReason', 60), wfSubmitButton(wfMsg('revdelete-submit')));
     $hidden = array(wfHidden('wpEditToken', $wgUser->editToken()), wfHidden('target', $this->page->getPrefixedText()));
     foreach ($this->revisions as $revid) {
         $hidden[] = wfHidden('oldid[]', $revid);
     }
     $special = Title::makeTitle(NS_SPECIAL, 'Revisiondelete');
     $wgOut->addHtml(wfElement('form', array('method' => 'post', 'action' => $special->getLocalUrl('action=submit'))));
     $wgOut->addHtml('<fieldset><legend>' . wfMsgHtml('revdelete-legend') . '</legend>');
     foreach ($this->checks as $item) {
         list($message, $name, $field) = $item;
         $wgOut->addHtml('<div>' . wfCheckLabel(wfMsg($message), $name, $name, $rev->isDeleted($field)) . '</div>');
     }
     $wgOut->addHtml('</fieldset>');
     foreach ($items as $item) {
         $wgOut->addHtml('<p>' . $item . '</p>');
     }
     foreach ($hidden as $item) {
         $wgOut->addHtml($item);
     }
     $wgOut->addHtml('</form>');
 }
Esempio n. 27
0
 /**
  * Clear the info cache for a given Title.
  *
  * @since 1.22
  * @param Title $title Title to clear cache for
  */
 public static function invalidateCache(Title $title)
 {
     global $wgMemc;
     $revision = Revision::newFromTitle($title, 0, Revision::READ_LATEST);
     if ($revision !== null) {
         $key = wfMemcKey('infoaction', sha1($title->getPrefixedText()), $revision->getId());
         $wgMemc->delete($key);
     }
 }
Esempio n. 28
0
 /**
  * Clear the info cache for a given Title.
  *
  * @since 1.22
  * @param Title $title Title to clear cache for
  */
 public static function invalidateCache(Title $title)
 {
     $cache = ObjectCache::getMainWANInstance();
     $revision = Revision::newFromTitle($title, 0, Revision::READ_LATEST);
     if ($revision !== null) {
         $key = wfMemcKey('infoaction', sha1($title->getPrefixedText()), $revision->getId());
         $cache->delete($key);
     }
 }
Esempio n. 29
0
 /**
  * Retrieves a local page.
  */
 protected function getLocalPage(&$title, $error_msg)
 {
     $contents = $error_msg;
     $rev = Revision::newFromTitle($title);
     if (is_object($rev)) {
         $contents = $rev->getText();
     }
     return $contents;
 }
Esempio n. 30
0
 /**
  * @return bool
  */
 function run()
 {
     if (!$this->redirTitle) {
         $this->setLastError('Invalid title');
         return false;
     }
     $targetRev = Revision::newFromTitle($this->title, false, Revision::READ_LATEST);
     if (!$targetRev) {
         wfDebug(__METHOD__ . ": target redirect already deleted, ignoring\n");
         return true;
     }
     $content = $targetRev->getContent();
     $currentDest = $content ? $content->getRedirectTarget() : null;
     if (!$currentDest || !$currentDest->equals($this->redirTitle)) {
         wfDebug(__METHOD__ . ": Redirect has changed since the job was queued\n");
         return true;
     }
     # Check for a suppression tag (used e.g. in periodically archived discussions)
     $mw = MagicWord::get('staticredirect');
     if ($content->matchMagicWord($mw)) {
         wfDebug(__METHOD__ . ": skipping: suppressed with __STATICREDIRECT__\n");
         return true;
     }
     # Find the current final destination
     $newTitle = self::getFinalDestination($this->redirTitle);
     if (!$newTitle) {
         wfDebug(__METHOD__ . ": skipping: single redirect, circular redirect or invalid redirect destination\n");
         return true;
     }
     if ($newTitle->equals($this->redirTitle)) {
         # The redirect is already right, no need to change it
         # This can happen if the page was moved back (say after vandalism)
         wfDebug(__METHOD__ . " : skipping, already good\n");
     }
     # Preserve fragment (bug 14904)
     $newTitle = Title::makeTitle($newTitle->getNamespace(), $newTitle->getDBkey(), $currentDest->getFragment(), $newTitle->getInterwiki());
     # Fix the text
     $newContent = $content->updateRedirect($newTitle);
     if ($newContent->equals($content)) {
         $this->setLastError('Content unchanged???');
         return false;
     }
     $user = $this->getUser();
     if (!$user) {
         $this->setLastError('Invalid user');
         return false;
     }
     # Save it
     global $wgUser;
     $oldUser = $wgUser;
     $wgUser = $user;
     $article = WikiPage::factory($this->title);
     $reason = wfMessage('double-redirect-fixed-' . $this->reason, $this->redirTitle->getPrefixedText(), $newTitle->getPrefixedText())->inContentLanguage()->text();
     $article->doEditContent($newContent, $reason, EDIT_UPDATE | EDIT_SUPPRESS_RC, false, $user);
     $wgUser = $oldUser;
     return true;
 }