/** * Create a new poll * @param wgRequest question * @param wgRequest answer (expects PHP array style in the form <input name=answer[]>) * Page Content should be of a different style so we have to translate * *question 1\n * *question 2\n */ public static function create() { wfProfileIn(__METHOD__); $app = F::app(); $title = $app->wg->Request->getVal('question'); $answers = $app->wg->Request->getArray('answer'); // array $title_object = Title::newFromText($title, NS_WIKIA_POLL); if (is_object($title_object) && $title_object->exists()) { $res = array('success' => false, 'error' => $app->renderView('Error', 'Index', array(wfMsg('wikiapoll-error-duplicate')))); } else { if ($title_object == null) { $res = array('success' => false, 'error' => $app->renderView('Error', 'Index', array(wfMsg('wikiapoll-error-invalid-title')))); } else { $content = ""; foreach ($answers as $answer) { $content .= "*{$answer}\n"; } /* @var $article WikiPage */ $article = new Article($title_object, NS_WIKIA_POLL); $article->doEdit($content, 'Poll Created', EDIT_NEW, false, $app->wg->User); $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; }
/** * Run a refreshLinks job * @return boolean success */ function run() { global $wgTitle, $wgUser, $wgLang, $wrGedcomExportDirectory; $wgTitle = $this->title; // FakeTitle (the default) generates errors when accessed, and sometimes I log wgTitle, so set it to something else $wgUser = User::newFromName('WeRelate agent'); // set the user $treeId = $this->params['tree_id']; $treeName = $this->params['name']; $treeUser = $this->params['user']; $filename = "{$wrGedcomExportDirectory}/{$treeId}.ged"; $ge = new GedcomExporter(); $error = $ge->exportGedcom($treeId, $filename); if ($error) { $this->error = $error; return false; } // leave a message for the tree requester $userTalkTitle = Title::newFromText($treeUser, NS_USER_TALK); $article = new Article($userTalkTitle, 0); if ($article->getID() != 0) { $text = $article->getContent(); } else { $text = ''; } $title = Title::makeTitle(NS_SPECIAL, 'Trees'); $msg = wfMsg('GedcomExportReady', $wgLang->date(wfTimestampNow(), true, false), $treeName, $title->getFullURL(wfArrayToCGI(array('action' => 'downloadExport', 'user' => $treeUser, 'name' => $treeName)))); $text .= "\n\n" . $msg; $success = $article->doEdit($text, 'GEDCOM export ready'); if (!$success) { $this->error = 'Unable to edit user talk page: ' . $treeUser; return false; } return true; }
/** Gets the 'raw' content from an article page. */ public function getRawPage(&$obj) { if (!isset($obj) || empty($obj)) { return null; } if (!is_a($obj, 'Title')) { $title = self::getTitle($obj); } else { $title = $obj; } $article = new Article($title); if ($article->getID() == 0) { return null; } return $article->getContent(); }
function wfUndeleteNFD(&$title, $create) { if ($title->getNamespace() != NS_MAIN) { return true; } $article = new Article($title); $revision = Revision::newFromTitle($title); // if an article becomes a redirect, vanquish all previous nfd entries if (preg_match("@^#REDIRECT@", $revision->getText())) { NFDProcessor::markPreviousAsInactive($article->getID()); return true; } // do the templates wfDebug("NFD: Looking for NFD templates\n"); $l = new NFDProcessor($revision, $article); $l->process(); return true; }
/** * Gets a plain text snippet from an article. An optional second argument allows a break limit. * When given, if the text is greater than $breakLimit, truncate it to $length, if its less than * $breakLimit, return the whole snippet. This allows better snippets for text that is very close * in character count to $length. * * For example if $length=100 and $breakLimit=200 and the source text is 205 characters, the content * will be truncated at the word closest to 100 characters. If the source text is 150 characters, * then this method will return all 150 characters. * * If however we only give one parameter, $length=200 and the source text is 205 characters, we * will return text truncated at the word nearest 200 characters, likely only leaving out a single * word from the snippet. This can lead to a strange user experience in some cases (e.g. a user * clicks a link in a notification email to see the full edit and finds that there's only one word * they weren't able to read from the email) * * @param integer $length [OPTIONAL] The maximum snippet length, defaults to 100 * @param integer $breakLimit A breakpoint for showing the full snippet. * * @return string The plain text snippet, it includes SUFFIX at the end of the string * if the length of the article's content is longer than $length, the text will be cut * respecting the integrity of the words * * @throws WikiaException If $length is bigger than MAX_LENGTH * * @example * $service = new ArticleService( $article ); * $snippet = $service->getTextSnippet( 250, 400 ); * * $service->setArticleById( $title->getArticleID() ); * $snippet = $service->getTextSnippet( 50 ); * * $service->setArticle( $anotherArticle ); * $snippet = $service->getTextSnippet(); */ public function getTextSnippet($length = 100, $breakLimit = null) { // don't allow more than the maximum to avoid flooding Memcached if ($length > self::MAX_LENGTH) { throw new WikiaException('Maximum allowed length is ' . self::MAX_LENGTH); } // It may be that the article is just not there if (!$this->article instanceof Article) { return ''; } $id = $this->article->getID(); if ($id <= 0) { return ''; } $text = $this->getTextSnippetSource($id); $length = $this->adjustTextSnippetLength($text, $length, $breakLimit); $snippet = wfShortenText($text, $length, $useContentLanguage = true); return $snippet; }
public function approveLink($id) { $link = $this->getLink($id); // Create the wiki page for the newly-approved link $linkTitle = Title::makeTitleSafe(NS_LINK, $link['title']); $article = new Article($linkTitle); $article->doEdit($link['url'], wfMsgForContent('linkfilter-edit-summary')); $newPageId = $article->getID(); // Tie link record to wiki page $dbw = wfGetDB(DB_MASTER); wfSuppressWarnings(); $date = date('Y-m-d H:i:s'); wfRestoreWarnings(); $dbw->update('link', array('link_page_id' => intval($newPageId), 'link_approved_date' => $date), array('link_id' => intval($id)), __METHOD__); $dbw->commit(); if (class_exists('UserStatsTrack')) { $stats = new UserStatsTrack($link['user_id'], $link['user_name']); $stats->incStatField('links_approved'); } }
protected function setup($par) { global $wgRequest, $wgUser; // Options $opts = new FormOptions(); $this->opts = $opts; // bind $opts->add('page1', ''); $opts->add('page2', ''); $opts->add('rev1', ''); $opts->add('rev2', ''); $opts->add('action', ''); // Set values $opts->fetchValuesFromRequest($wgRequest); $title1 = Title::newFromText($opts->getValue('page1')); $title2 = Title::newFromText($opts->getValue('page2')); if ($title1 && $title1->exists() && $opts->getValue('rev1') == '') { $pda = new Article($title1); $pdi = $pda->getID(); $pdLastRevision = Revision::loadFromPageId(wfGetDB(DB_SLAVE), $pdi); $opts->setValue('rev1', $pdLastRevision->getId()); } elseif ($opts->getValue('rev1') != '') { $pdrev = Revision::newFromId($opts->getValue('rev1')); if ($pdrev) { $opts->setValue('page1', $pdrev->getTitle()->getPrefixedText()); } } if ($title2 && $title2->exists() && $opts->getValue('rev2') == '') { $pda = new Article($title2); $pdi = $pda->getID(); $pdLastRevision = Revision::loadFromPageId(wfGetDB(DB_SLAVE), $pdi); $opts->setValue('rev2', $pdLastRevision->getId()); } elseif ($opts->getValue('rev2') != '') { $pdrev = Revision::newFromId($opts->getValue('rev2')); if ($pdrev) { $opts->setValue('page2', $pdrev->getTitle()->getPrefixedText()); } } // Store some objects $this->skin = $wgUser->getSkin(); }
function bwVirtualPageSwitchInit(&$title, &$article) { // let mediawiki handle those. $ns = $title->getNamespace(); if (NS_MEDIA == $ns || NS_CATEGORY == $ns || NS_IMAGE == $ns) { return true; } // let mediawiki handle those also. global $bwVirtualPageExcludeNamespaces; if (in_array($ns, $bwVirtualPageExcludeNamespaces)) { return true; } $article = new Article($title); // let mediawiki handle the articles that already exist if ($article->getID() != 0) { return true; } // now, we are interested in non-existing articles! wfRunHooks('VirtualPage', array(&$title, &$article)); return true; }
function UW_Authors_List ( &$out, &$text ) { global $wgTitle, $wgRequest, $wgShowAuthorsNamespaces, $wgShowAuthors; /* do nothing if the option is disabled * (but why would the extension be enabled?) */ if ( !$wgShowAuthors ) return true; // only build authors on namespaces in $wgShowAuthorsNamespaces if ( !in_array ( $wgTitle->getNamespace(), $wgShowAuthorsNamespaces ) ) return true; /* get the contribs from the database (don't use the default * MediaWiki one since it ignores the current user) */ $article = new Article ( $wgTitle ); $contribs = array(); $db = wfGetDB ( DB_MASTER ); $rev_table = $db->tableName ( "revision" ); $user_table = $db->tableName ( "user" ); $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp FROM $rev_table LEFT JOIN $user_table ON rev_user = user_id WHERE rev_page = {$article->getID()} GROUP BY rev_user, rev_user_text, user_real_name ORDER BY timestamp DESC"; $results = $db->query ( $sql, __METHOD__ ); while ( $line = $db->fetchObject ( $results ) ) { $contribs[] = array( $line->rev_user, $line->rev_user_text, $line->user_real_name ); } $db->freeResult ( $results ); // return if there are no authors if ( sizeof ( $results ) <= 0 ) return true; // now build a sensible authors display in HTML require_once ( "includes/Credits.php" ); $authors = "\n<div class='authors'>" . "<h4>" . wfMsg( 'authors_authors' ) . "</h4>" . "<ul>"; $anons = 0; foreach ( $contribs as $author ) { $id = $author[0]; $username = $author[1]; $realname = $author[2]; if ( $id != "0" ) { // user with an id // FIME: broken. Incompatible with 1.14. Method creditLink() was renamed and changed. $author_link = $realname ? creditLink( $username, $realname ) : creditLink( $username ); $authors .= "<li>$author_link</li>"; } else { // anonymous $anons++; } } // add the anonymous entries if ( $anons > 0 ) $authors .= "<li>" . wfMsg( 'authors_anonymous' ) . "</li>"; $authors .= "</ul></div>"; $text .= $authors; return true; }
/** * Show the special page * * @param $par Mixed: parameter passed to the page or null */ public function execute($par) { global $wgUser, $wgOut, $wgRequest, $wgMemc, $wgContLang, $wgHooks, $wgSupressPageTitle, $wgPollScripts; $wgSupressPageTitle = true; // Blocked users cannot create polls if ($wgUser->isBlocked()) { $wgOut->blockedPage(false); return false; } // Check that the DB isn't locked if (wfReadOnly()) { $wgOut->readOnlyPage(); return; } /** * Redirect anonymous users to login page * It will automatically return them to the CreatePoll page */ if ($wgUser->getID() == 0) { $wgOut->setPageTitle(wfMsgHtml('poll-woops')); $login = SpecialPage::getTitleFor('Userlogin'); $wgOut->redirect($login->getLocalURL('returnto=Special:CreatePoll')); return false; } /** * Create Poll Thresholds based on User Stats */ global $wgCreatePollThresholds; if (is_array($wgCreatePollThresholds) && count($wgCreatePollThresholds) > 0) { $canCreate = true; $stats = new UserStats($wgUser->getID(), $wgUser->getName()); $stats_data = $stats->getUserStats(); $threshold_reason = ''; foreach ($wgCreatePollThresholds as $field => $threshold) { if ($stats_data[$field] < $threshold) { $canCreate = false; $threshold_reason .= ($threshold_reason ? ', ' : '') . "{$threshold} {$field}"; } } if ($canCreate == false) { $wgSupressPageTitle = false; $wgOut->setPageTitle(wfMsg('poll-create-threshold-title')); $wgOut->addHTML(wfMsg('poll-create-threshold-reason', $threshold_reason)); return ''; } } // i18n for JS $wgHooks['MakeGlobalVariablesScript'][] = 'CreatePoll::addJSGlobals'; // Add CSS & JS $wgOut->addScriptFile($wgPollScripts . '/Poll.js'); $wgOut->addExtensionStyle($wgPollScripts . '/Poll.css'); // If the request was POSTed, try creating the poll if ($wgRequest->wasPosted() && $_SESSION['alreadysubmitted'] == false) { $_SESSION['alreadysubmitted'] = true; // Add poll $poll_title = Title::makeTitleSafe(NS_POLL, $wgRequest->getVal('poll_question')); if (is_null($poll_title) && !$poll_title instanceof Title) { $wgSupressPageTitle = false; $wgOut->setPageTitle(wfMsg('poll-create-threshold-title')); $wgOut->addHTML(wfMsg('poll-create-threshold-reason', $threshold_reason)); return ''; } // Put choices in wikitext (so we can track changes) $choices = ''; for ($x = 1; $x <= 10; $x++) { if ($wgRequest->getVal("answer_{$x}")) { $choices .= $wgRequest->getVal("answer_{$x}") . "\n"; } } // Create poll wiki page $localizedCategoryNS = $wgContLang->getNsText(NS_CATEGORY); $article = new Article($poll_title); $article->doEdit("<userpoll>\n{$choices}</userpoll>\n\n[[" . $localizedCategoryNS . ':' . wfMsgForContent('poll-category') . "]]\n" . '[[' . $localizedCategoryNS . ':' . wfMsgForContent('poll-category-user', $wgUser->getName()) . "]]\n" . '[[' . $localizedCategoryNS . ":{{subst:CURRENTMONTHNAME}} {{subst:CURRENTDAY}}, {{subst:CURRENTYEAR}}]]\n\n__NOEDITSECTION__", wfMsgForContent('poll-edit-desc')); $newPageId = $article->getID(); $p = new Poll(); $poll_id = $p->addPollQuestion($wgRequest->getVal('poll_question'), $wgRequest->getVal('poll_image_name'), $newPageId); // Add choices for ($x = 1; $x <= 10; $x++) { if ($wgRequest->getVal("answer_{$x}")) { $p->addPollChoice($poll_id, $wgRequest->getVal("answer_{$x}"), $x); } } // Clear poll cache $key = wfMemcKey('user', 'profile', 'polls', $wgUser->getID()); $wgMemc->delete($key); // Redirect to new poll page $wgOut->redirect($poll_title->getFullURL()); } else { $_SESSION['alreadysubmitted'] = false; include 'create-poll.tmpl.php'; $template = new CreatePollTemplate(); $wgOut->addTemplate($template); } }
static function updateUndelete($title, $isnewid) { $article = new Article($title); $id = $article->getID(); self::setKey($id, $title); return true; }
/** * Create a new quiz eleemnt * @see WikiaQuizElement.class.php */ public static function createQuizArticle() { wfProfileIn(__METHOD__); $wgRequest = F::app()->getGlobal('wgRequest'); $wgUser = F::app()->getGlobal('wgUser'); $title = $wgRequest->getVal('question'); $title_object = Title::newFromText($title, NS_WIKIA_QUIZARTICLE); if (is_object($title_object) && $title_object->exists()) { $res = array('success' => false, 'error' => F::app()->renderView('Error', 'Index', array(wfMsg('wikiaquiz-error-duplicate-question')))); } else { if ($title_object == null) { $res = array('success' => false, 'error' => F::app()->renderView('Error', 'Index', array(wfMsg('wikiaquiz-error-invalid-question')))); } else { $error = null; $content = self::parseCreateEditQuizArticleRequest($wgRequest, null, $error); if ($error) { $res = array('success' => false, 'error' => F::app()->renderView('Error', 'Index', array($error))); } else { $article = new Article($title_object); $status = $article->doEdit($content, 'Quiz Article Created', EDIT_NEW, false, $wgUser); $title_object = $article->getTitle(); // fixme: check status object $res = array('success' => true, 'quizElementId' => $article->getID(), 'url' => $title_object->getLocalUrl(), 'question' => $title_object->getPrefixedText()); } } } wfProfileOut(__METHOD__); return $res; }
/** * Fetch initial editing page content. * * @param $def_text string * @returns mixed string on success, $def_text for invalid sections * @private */ function getContent($def_text = '') { global $wgOut, $wgRequest, $wgParser; wfProfileIn(__METHOD__); # Get variables from query string :P $section = $wgRequest->getVal('section'); $preload = $wgRequest->getVal('preload', $section === 'new' ? 'MediaWiki:addsection-preload' : ''); $undoafter = $wgRequest->getVal('undoafter'); $undo = $wgRequest->getVal('undo'); // For message page not locally set, use the i18n message. // For other non-existent articles, use preload text if any. if (!$this->mTitle->exists()) { if ($this->mTitle->getNamespace() == NS_MEDIAWIKI) { # If this is a system message, get the default text. $text = $this->mTitle->getDefaultMessageText(); if ($text === false) { $text = $this->getPreloadedText($preload); } } else { # If requested, preload some text. $text = $this->getPreloadedText($preload); } // For existing pages, get text based on "undo" or section parameters. } else { $text = $this->mArticle->getContent(); if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) { # If they got undoafter and undo round the wrong way, switch them list($undo, $undoafter) = array($undoafter, $undo); } if ($undo > 0 && $undo > $undoafter) { # Undoing a specific edit overrides section editing; section-editing # doesn't work with undoing. if ($undoafter) { $undorev = Revision::newFromId($undo); $oldrev = Revision::newFromId($undoafter); } else { $undorev = Revision::newFromId($undo); $oldrev = $undorev ? $undorev->getPrevious() : null; } # Sanity check, make sure it's the right page, # the revisions exist and they were not deleted. # Otherwise, $text will be left as-is. if (!is_null($undorev) && !is_null($oldrev) && $undorev->getPage() == $oldrev->getPage() && $undorev->getPage() == $this->mArticle->getID() && !$undorev->isDeleted(Revision::DELETED_TEXT) && !$oldrev->isDeleted(Revision::DELETED_TEXT)) { $undotext = $this->mArticle->getUndoText($undorev, $oldrev); if ($undotext === false) { # Warn the user that something went wrong $this->editFormPageTop .= $wgOut->parse('<div class="error mw-undo-failure">' . wfMsgNoTrans('undo-failure') . '</div>'); } else { $text = $undotext; # Inform the user of our success and set an automatic edit summary $this->editFormPageTop .= $wgOut->parse('<div class="mw-undo-success">' . wfMsgNoTrans('undo-success') . '</div>'); $firstrev = $oldrev->getNext(); # If we just undid one rev, use an autosummary if ($firstrev->mId == $undo) { $this->summary = wfMsgForContent('undo-summary', $undo, $undorev->getUserText()); $this->undidRev = $undo; } $this->formtype = 'diff'; } } else { // Failed basic sanity checks. // Older revisions may have been removed since the link // was created, or we may simply have got bogus input. $this->editFormPageTop .= $wgOut->parse('<div class="error mw-undo-norev">' . wfMsgNoTrans('undo-norev') . '</div>'); } } elseif ($section != '') { if ($section == 'new') { $text = $this->getPreloadedText($preload); } else { // Get section edit text (returns $def_text for invalid sections) $text = $wgParser->getSection($text, $section, $def_text); } } } wfProfileOut(__METHOD__); return $text; }
function execute($par) { global $wgUser, $wgOut, $wgLang, $wgTitle, $wgMemc, $wgDBname; global $wgRequest, $wgSitename, $wgLanguageCode, $IP; global $wgScript, $wgFilterCallback, $wgScriptPath; $this->setHeaders(); require_once "{$IP}/extensions/wikihow/EditPageWrapper.php"; require_once "{$IP}/includes/EditPage.php"; $target = isset($par) ? $par : $wgRequest->getVal('target'); if (!$target) { $wgOut->addHTML("No target specified. In order to thank a group of authors, a page must be provided."); return; } $title = Title::newFromDBKey($target); $me = Title::makeTitle(NS_SPECIAL, "ThankAuthors"); if (!$wgRequest->getVal('token')) { $sk = $wgUser->getSkin(); $talk_page = $title->getTalkPage(); $token = $this->getToken1(); $thanks_msg = wfMsg('thank-you-kudos', $title->getFullURL(), wfMsg('howto', $title->getText())); // add the form HTML $wgOut->addHTML(<<<EOHTML \t\t\t\t<script type='text/javascript'> \t\t\t\t\tfunction submitThanks () { \t\t\t\t\t\tvar message = \$('#details').val(); \t\t\t\t\t\tif(message == "") { \t\t\t\t\t\t\talert("Please enter a message."); \t\t\t\t\t\t\treturn false; \t\t\t\t\t\t} \t\t\t\t\t\tvar url = '{$me->getFullURL()}?token=' + \$('#token')[0].value + '&target=' + \$('#target')[0].value + '&details=' + \$('#details')[0].value; \t\t\t\t\t\tvar form = \$('#thanks_form'); \t\t\t\t\t\tform.html(\$('#thanks_response').html()); \t\t\t\t\t\t\$.get(url); \t\t\t\t\t\treturn true; \t\t\t\t\t} \t\t\t\t</script> \t\t\t\t<div id="thanks_response" style="display:none;">{$thanks_msg}</div> \t\t\t\t<div id="thanks_form"><div class="section_text"> EOHTML ); $wgOut->addWikiText(wfMsg('enjoyed-reading-article', $title->getFullText(), $talk_page->getFullText())); $wgOut->addHTML("<input id=\"target\" type=\"hidden\" name=\"target\" value=\"{$target}\"/>\n\t\t\t\t<input id=\"token\" type=\"hidden\" name=\"{$token}\" value=\"{$token}\"/>\n\t\t\t\t"); $wgOut->addHTML("<br />\n\t\t\t\t<textarea style='width:98%;' id=\"details\" rows=\"5\" cols=\"100\" name=\"details\"></textarea><br/>\n\t\t\t\t<br /><button onclick='submitThanks();' class='button primary'>" . wfMsg('submit') . "</button>\n\t\t\t\t</div></div>"); } else { // this is a post, accept the POST data and create the // Request article wfLoadExtensionMessages('PostComment'); $wgOut->setArticleBodyOnly(true); $user = $wgUser->getName(); $real_name = User::whoIsReal($wgUser->getID()); if ($real_name == "") { $real_name = $user; } $dateStr = $wgLang->timeanddate(wfTimestampNow()); $comment = $wgRequest->getVal("details"); $text = $title->getFullText(); wfDebug("STA: got text..."); // filter out links $preg = "/[^\\s]*\\.[a-z][a-z][a-z]?[a-z]?/i"; $matches = array(); if (preg_match($preg, $comment, $matches) > 0) { $wgOut->addHTML(wfMsg('no_urls_in_kudos', $matches[0])); return; } $comment = strip_tags($comment); $formattedComment = wfMsg('postcomment_formatted_thanks', $dateStr, $user, $real_name, $comment, $text); wfDebug("STA: comment {$formattedComment}\n"); wfDebug("STA: Checking blocks..."); $tmp = ""; if ($wgUser->isBlocked()) { $this->blockedIPpage(); return; } if (!$wgUser->getID() && $wgWhitelistEdit) { $this->userNotLoggedInPage(); return; } if ($target == "Spam-Blacklist") { $wgOut->readOnlyPage(); return; } wfDebug("STA: checking read only\n"); if (wfReadOnly()) { $wgOut->readOnlyPage(); return; } wfDebug("STA: checking rate limiter\n"); if ($wgUser->pingLimiter('userkudos')) { $wgOut->rateLimited(); return; } wfDebug("STA: checking blacklist\n"); if ($wgFilterCallback && $wgFilterCallback($title, $comment, "")) { // Error messages or other handling should be // performed by the filter function return; } wfDebug("STA: checking tokens\n"); $usertoken = $wgRequest->getVal('token'); $token1 = $this->getToken1(); $token2 = $this->getToken2(); if ($usertoken != $token1 && $usertoken != $token2) { wfDebug("STA: User kudos token doesn't match user: {$usertoken} token1: {$token1} token2: {$token2}"); return; } wfDebug("STA: going through contributors\n"); $article = new Article($title); //$contributors = $article->getContributors(0, 0, true); $contributors = ArticleAuthors::getAuthors($article->getID()); foreach ($contributors as $k => $v) { $u = User::newFromName($k); $id = $u->getID(); //$id = $c->getID(); //$u = $c; wfDebug("STA: going through contributors {$u} {$id}\n"); if ($id == "0") { continue; } // forget the anon users. //notify via the echo notification system if (class_exists('EchoEvent')) { EchoEvent::create(array('type' => 'kudos', 'title' => $title, 'extra' => array('kudoed-user-id' => $id), 'agent' => $wgUser)); } $t = Title::newFromText("User_kudos:" . $u); $a = new Article($t); $update = $t->getArticleID() > 0; $text = ""; if ($update) { $text = $a->getContent(true); $text .= "\n\n" . $formattedComment; if ($wgFilterCallback && $wgFilterCallback($t, $text, $text)) { // Error messages or other handling should be // performed by the filter function return; } } if ($update) { $a->updateArticle($text, "", true, false, false, '', false); } else { $a->insertNewArticle($text, "", true, false, false, false, false); } } wfDebug("STA: done\n"); $wgOut->addHTML("Done."); $wgOut->redirect(''); } }
function printPage($form_name, $embedded = false) { global $wgOut, $wgRequest, $sfgFormPrinter, $wgParser, $sfgRunQueryFormAtTop; global $wgUser, $wgTitle; // Get contents of form-definition page. $form_title = Title::makeTitleSafe(SF_NS_FORM, $form_name); if (!$form_title || !$form_title->exists()) { if ($form_name === '') { $text = Html::element('p', array('class' => 'error'), wfMessage('sf_runquery_badurl')->text()) . "\n"; } else { $text = Html::rawElement('p', array('class' => 'error'), wfMessage('sf_formstart_badform', SFUtils::linkText(SF_NS_FORM, $form_name))->parse()) . "\n"; } $wgOut->addHTML($text); return; } // Initialize variables. $form_article = new Article($form_title, 0); $form_definition = $form_article->getContent(); if ($embedded) { $run_query = false; $content = null; $raw = false; } else { $run_query = $wgRequest->getCheck('wpRunQuery'); $content = $wgRequest->getVal('wpTextbox1'); $raw = $wgRequest->getBool('raw', false); } $form_submitted = $run_query; if ($raw) { $wgOut->setArticleBodyOnly(true); } // If user already made some action, ignore the edited // page and just get data from the query string. if (!$embedded && $wgRequest->getVal('query') == 'true') { $edit_content = null; $is_text_source = false; } elseif ($content != null) { $edit_content = $content; $is_text_source = true; } else { $edit_content = null; $is_text_source = true; } list($form_text, $javascript_text, $data_text, $form_page_title) = $sfgFormPrinter->formHTML($form_definition, $form_submitted, $is_text_source, $form_article->getID(), $edit_content, null, null, true, $embedded); $text = ""; // Get the text of the results. $resultsText = ''; if ($form_submitted) { // @TODO - fix RunQuery's parsing so that this check // isn't needed. if ($wgParser->getOutput() == null) { $headItems = array(); } else { $headItems = $wgParser->getOutput()->getHeadItems(); } foreach ($headItems as $key => $item) { $wgOut->addHeadItem($key, "\t\t" . $item . "\n"); } $wgParser->mOptions = ParserOptions::newFromUser($wgUser); $resultsText = $wgParser->parse($data_text, $wgTitle, $wgParser->mOptions)->getText(); } // Get the full text of the form. $fullFormText = ''; $additionalQueryHeader = ''; $dividerText = ''; if (!$raw) { // Create the "additional query" header, and the // divider text - one of these (depending on whether // the query form is at the top or bottom) is displayed // if the form has already been submitted. if ($form_submitted) { $additionalQueryHeader = "\n" . Html::element('h2', null, wfMessage('sf_runquery_additionalquery')->text()) . "\n"; $dividerText = "\n<hr style=\"margin: 15px 0;\" />\n"; } $action = htmlspecialchars($this->getTitle($form_name)->getLocalURL()); $fullFormText .= <<<END \t<form id="sfForm" name="createbox" action="{$action}" method="post" class="createbox"> END; $fullFormText .= Html::hidden('query', 'true'); $fullFormText .= $form_text; } // Either don't display a query form at all, or display the // query form at the top, and the results at the bottom, or the // other way around, depending on the settings. if ($wgRequest->getVal('additionalquery') == 'false') { $text .= $resultsText; } elseif ($sfgRunQueryFormAtTop) { $text .= $fullFormText; $text .= $dividerText; $text .= $resultsText; } else { $text .= $resultsText; $text .= $additionalQueryHeader; $text .= $fullFormText; } if ($embedded) { $text = "<div class='runQueryEmbedded'>{$text}</div>"; } // Armor against doBlockLevels() $text = preg_replace('/^ +/m', '', $text); // Now write everything to the screen. $wgOut->addHTML($text); SFUtils::addJavascriptAndCSS($embedded ? $wgParser : null); $script = "\t\t" . '<script type="text/javascript">' . "\n" . $javascript_text . '</script>' . "\n"; if ($embedded) { $wgParser->getOutput()->addHeadItem($script); } else { $wgOut->addScript($script); $po = $wgParser->getOutput(); if ($po) { $wgOut->addParserOutputNoText($po); } } // Finally, set the page title - previously, this had to be // called after addParserOutputNoText() for it to take effect; // now the order doesn't matter. if (!$embedded) { if ($form_page_title != null) { $wgOut->setPageTitle($form_page_title); } else { $s = wfMessage('sf_runquery_title', $form_title->getText())->text(); $wgOut->setPageTitle($s); } } }
/** * * Enter description here ... * @param String $articleID or titleText * Return a list of categories this article belongs to */ public static function getPageCategory($page, $ns = NS_MAIN) { if (!is_int($page)) { $title = Title::makeTitleSafe($ns, $page); $article = new Article($title); $page = $article->getID(); } $result = array(); $dbr = wfGetDB(DB_SLAVE); $res = $dbr->select(array('categorylinks'), array('cl_to'), array('cl_from' => $page), __METHOD__); if ($res !== false) { foreach ($res as $row) { $result[] = str_replace("_", " ", $row->cl_to); } } $dbr->freeResult($res); return $result; }
function submitEdit() { global $wgRequest, $wgUser; $t = Title::newFromID($wgRequest->getVal('articleId')); if ($t) { $a = new Article($t); $text = $wgRequest->getVal('wpTextbox1'); $text = self::removeWordWraps($text); $text = self::insertNewlines($text); $text = self::unmarkBreaks($text); $text = self::removeSpaces($text); $text = self::removeHTMLentities($text); $text = self::fixReferences($text); $text = self::removeTableBodyTags($text); $summary = $wgRequest->getVal('wpSummary'); if ($a) { $params = array(); if ($wgRequest->getVal('isIE') == "true") { $IE = ", IE"; } else { $IE = ""; } $log = new LogPage('spellcheck', false); // false - dont show in recentchanges, it'll show up for the doEdit call $msg = wfMsgHtml('spch-edit-message', "[[{$t->getText()}]]", $IE); $log->addEntry('edit', $t, $msg, $params); //save the edit $a->doEdit($text, $summary, EDIT_UPDATE); wfRunHooks("Spellchecked", array($wgUser, $t, '0')); $this->skipTool->unUseItem($a->getID()); } } }
static function printForm(&$form_name, &$target_name, $alt_forms = array(), $redirectOnError = false) { global $wgOut, $wgRequest, $wgUser, $sfgFormPrinter; // initialize some variables $target_title = null; $page_name_formula = null; $form_title = Title::makeTitleSafe(SF_NS_FORM, $form_name); // If the given form is not a valid title, bail out. if (!$form_title) { return 'sf_formedit_badurl'; } $form_article = new Article($form_title, 0); $form_definition = $form_article->getContent(); // If the form page is a redirect, use the other form // instead. if ($form_title->isRedirect()) { $form_title = Title::newFromRedirectRecurse($form_definition); $form_article = new Article($form_title, 0); $form_definition = $form_article->getContent(); } $form_definition = StringUtils::delimiterReplace('<noinclude>', '</noinclude>', '', $form_definition); if (is_null($target_name)) { $target_name = ''; } if ($target_name === '') { // parse the form to see if it has a 'page name' value set $matches; if (preg_match('/{{{info.*page name\\s*=\\s*(.*)}}}/m', $form_definition, $matches)) { $page_name_elements = SFUtils::getFormTagComponents($matches[1]); $page_name_formula = $page_name_elements[0]; } elseif (count($alt_forms) == 0) { return 'sf_formedit_badurl'; } } else { $target_title = Title::newFromText($target_name); if ($target_title && $target_title->exists()) { if ($wgRequest->getVal('query') == 'true') { $page_contents = null; //$page_is_source = false; } else { // If page already exists and 'redlink' // is in the query string, redirect to // the actual page, just like // MediaWiki does it. if ($wgRequest->getBool('redlink')) { $wgOut->redirect($target_title->getFullURL()); wfProfileOut(__METHOD__); return; } $target_article = new Article($target_title, 0); $page_contents = $target_article->getContent(); //$page_is_source = true; } } else { $target_name = str_replace('_', ' ', $target_name); } } if (!$form_title || !$form_title->exists()) { if (count($alt_forms) > 0) { $text = '<div class="infoMessage">' . wfMsg('sf_formedit_altformsonly') . ' ' . self::printAltFormsList($alt_forms, $form_name) . "</div>\n"; } else { $text = Html::rawElement('p', array('class' => 'error'), wfMsgExt('sf_formstart_badform', 'parseinline', SFUtils::linkText(SF_NS_FORM, $form_name))) . "\n"; } } elseif ($target_name === '' && $page_name_formula === '') { $text = Html::element('p', array('class' => 'error'), wfMsg('sf_formedit_badurl')) . "\n"; } else { $save_page = $wgRequest->getCheck('wpSave'); $preview_page = $wgRequest->getCheck('wpPreview'); $diff_page = $wgRequest->getCheck('wpDiff'); $form_submitted = $save_page || $preview_page || $diff_page; // get 'preload' query value, if it exists if (!$form_submitted) { if ($wgRequest->getCheck('preload')) { $page_is_source = true; $page_contents = SFFormUtils::getPreloadedText($wgRequest->getVal('preload')); } else { // let other extensions preload the page, if they want wfRunHooks('sfEditFormPreloadText', array(&$page_contents, $target_title, $form_title)); $page_is_source = $page_contents != null; } } else { $page_is_source = false; $page_contents = null; } list($form_text, $javascript_text, $data_text, $form_page_title, $generated_page_name) = $sfgFormPrinter->formHTML($form_definition, $form_submitted, $page_is_source, $form_article->getID(), $page_contents, $target_name, $page_name_formula); // Before we do anything else, set the form header // title - this needs to be done after formHTML() is // called, because otherwise it doesn't take hold // for some reason if the form is disabled. if (empty($target_title)) { $s = wfMsg('sf_formedit_createtitlenotarget', $form_title->getText()); } elseif ($target_title->exists()) { $s = wfMsg('sf_formedit_edittitle', $form_title->getText(), $target_title->getPrefixedText()); } else { $s = wfMsg('sf_formedit_createtitle', $form_title->getText(), $target_title->getPrefixedText()); } $wgOut->setPageTitle($s); if ($form_submitted) { if (!is_null($page_name_formula) && $page_name_formula !== '') { $target_name = $generated_page_name; // prepend a super-page, if one was specified if ($wgRequest->getCheck('super_page')) { $target_name = $wgRequest->getVal('super_page') . '/' . $target_name; } // prepend a namespace, if one was specified if ($wgRequest->getCheck('namespace')) { $target_name = $wgRequest->getVal('namespace') . ':' . $target_name; } // replace "unique number" tag with one // that won't get erased by the next line $target_name = preg_replace('/<unique number(.*)>/', '{num\\1}', $target_name, 1); // if any formula stuff is still in the // name after the parsing, just remove it $target_name = StringUtils::delimiterReplace('<', '>', '', $target_name); // now run the parser on it global $wgParser; // ...but first, replace spaces back // with underlines, in case a magic word // or parser function name contains // underlines - hopefully this won't // cause problems of its own $target_name = str_replace(' ', '_', $target_name); $target_name = $wgParser->preprocess($target_name, $wgOut->getTitle(), ParserOptions::newFromUser(null)); $title_number = ""; $isRandom = false; $randomNumHasPadding = false; $randomNumDigits = 6; if (strpos($target_name, '{num') !== false) { // Random number if (preg_match('/{num;random(;(0)?([1-9][0-9]*))?}/', $target_name, $matches)) { $isRandom = true; $randomNumHasPadding = array_key_exists(2, $matches); $randomNumDigits = array_key_exists(3, $matches) ? $matches[3] : $randomNumDigits; $title_number = self::makeRandomNumber($randomNumDigits, $randomNumHasPadding); } else { // get unique number start value // from target name; if it's not // there, or it's not a positive // number, start it out as blank preg_match('/{num.*start[_]*=[_]*([^;]*).*}/', $target_name, $matches); if (count($matches) == 2 && is_numeric($matches[1]) && $matches[1] >= 0) { // the "start" value" $title_number = $matches[1]; } } // set target title $target_title = Title::newFromText(preg_replace('/{num.*}/', $title_number, $target_name)); // if title exists already // cycle through numbers for // this tag until we find one // that gives a nonexistent page // title while ($target_title->exists()) { if ($isRandom) { $title_number = self::makeRandomNumber($randomNumDigits, $randomNumHasPadding); } elseif ($title_number == "") { $title_number = 2; } else { $title_number = str_pad($title_number + 1, strlen($title_number), '0', STR_PAD_LEFT); } $target_title = Title::newFromText(preg_replace('/{num.*}/', $title_number, $target_name)); } $target_name = $target_title->getPrefixedText(); } else { $target_title = Title::newFromText($target_name); } } if (is_null($target_title)) { if ($target_name) { return array('sf_formstart_badtitle', array($target_name)); } else { return 'sf_formedit_emptytitle'; } } if ($save_page) { $permErrors = $target_title->getUserPermissionsErrors('edit', $wgUser); if ($permErrors) { // just return the first error and let them fix it one by one return array_shift($permErrors); } // Set up all the variables for the // page save. $data = array('wpTextbox1' => $data_text, 'wpSummary' => $wgRequest->getVal('wpSummary'), 'wpStarttime' => $wgRequest->getVal('wpStarttime'), 'wpEdittime' => $wgRequest->getVal('wpEdittime'), 'wpEditToken' => $wgUser->isLoggedIn() ? $wgUser->editToken() : EDIT_TOKEN_SUFFIX, 'wpSave' => '', 'action' => 'submit'); if ($wgRequest->getCheck('wpMinoredit')) { $data['wpMinoredit'] = true; } if ($wgRequest->getCheck('wpWatchthis')) { $data['wpWatchthis'] = true; } $request = new FauxRequest($data, true); // Find existing article if it exists, // or create a new one. $article = new Article($target_title, 0); $editor = new EditPage($article); $editor->importFormData($request); // Try to save the page! $resultDetails = array(); $saveResult = $editor->internalAttemptSave($resultDetails); // Return value was made an object in MW 1.19 if (is_object($saveResult)) { $saveResultCode = $saveResult->value; } else { $saveResultCode = $saveResult; } if (($saveResultCode == EditPage::AS_HOOK_ERROR || $saveResultCode == EditPage::AS_HOOK_ERROR_EXPECTED) && $redirectOnError) { $wgOut->clearHTML(); $wgOut->setArticleBodyOnly(true); // Lets other code process additional form-definition syntax wfRunHooks('sfWritePageData', array($form_name, $target_title, &$data_text)); $text = SFUtils::printRedirectForm($target_title, $data_text, $wgRequest->getVal('wpSummary'), $save_page, $preview_page, $diff_page, $wgRequest->getCheck('wpMinoredit'), $wgRequest->getCheck('wpWatchthis'), $wgRequest->getVal('wpStarttime'), $wgRequest->getVal('wpEdittime')); } else { if ($saveResultCode == EditPage::AS_SUCCESS_UPDATE || $saveResultCode == EditPage::AS_SUCCESS_NEW_ARTICLE) { $wgOut->redirect($target_title->getFullURL()); } return SFUtils::processEditErrors($saveResultCode); } } else { // Lets other code process additional form-definition syntax wfRunHooks('sfWritePageData', array($form_name, $target_title, &$data_text)); $text = SFUtils::printRedirectForm($target_title, $data_text, $wgRequest->getVal('wpSummary'), $save_page, $preview_page, $diff_page, $wgRequest->getCheck('wpMinoredit'), $wgRequest->getCheck('wpWatchthis'), $wgRequest->getVal('wpStarttime'), $wgRequest->getVal('wpEdittime')); // extract its data } } else { // override the default title for this page if // a title was specified in the form if ($form_page_title != null) { if ($target_name === '') { $wgOut->setPageTitle($form_page_title); } else { $wgOut->setPageTitle("{$form_page_title}: {$target_title->getPrefixedText()}"); } } $text = ""; if (count($alt_forms) > 0) { $text .= '<div class="infoMessage">' . wfMsg('sf_formedit_altforms') . ' '; $text .= self::printAltFormsList($alt_forms, $target_name); $text .= "</div>\n"; } $text .= '<form name="createbox" id="sfForm" method="post" class="createbox">'; $pre_form_html = ''; wfRunHooks('sfHTMLBeforeForm', array(&$target_title, &$pre_form_html)); $text .= $pre_form_html; $text .= $form_text; } } SFUtils::addJavascriptAndCSS(); if (!empty($javascript_text)) { $wgOut->addScript(' <script type="text/javascript">' . "\n{$javascript_text}\n" . '</script>' . "\n"); } $wgOut->addHTML($text); return null; }
/** * Show the special page * * @param $par Mixed: parameter passed to the special page or null */ public function execute($par) { global $wgOut, $wgUser, $wgRequest, $wgContLang; // If the user can't create blog posts, display an error if (!$wgUser->isAllowed('createblogpost')) { $wgOut->permissionRequired('createblogpost'); return; } // Show a message if the database is in read-only mode if (wfReadOnly()) { $wgOut->readOnlyPage(); return; } // If user is blocked, s/he doesn't need to access this page if ($wgUser->isBlocked()) { $wgOut->blockedPage(false); return false; } // Set page title, robot policies, etc. $this->setHeaders(); // Add CSS & JS $wgOut->addModules('ext.blogPage.create'); // If the request was POSTed, we haven't submitted a request yet AND // we have a title, create the page...otherwise just display the // creation form if ($wgRequest->wasPosted() && $_SESSION['alreadysubmitted'] == false) { $_SESSION['alreadysubmitted'] = true; // Protect against cross-site request forgery (CSRF) if (!$wgUser->matchEditToken($wgRequest->getVal('wpEditToken'))) { $wgOut->addHTML(wfMsg('sessionfailure')); return; } // Create a Title object, or try to, anyway $userSuppliedTitle = $wgRequest->getVal('title2'); $title = Title::makeTitleSafe(NS_BLOG, $userSuppliedTitle); // @todo CHECKME: are these still needed? The JS performs these // checks already but then again JS is also easy to fool... // The user didn't supply a title? Ask them to supply one. if (!$userSuppliedTitle) { $wgOut->setPageTitle(wfMsg('errorpagetitle')); $wgOut->addWikiMsg('blog-create-error-need-title'); $wgOut->addReturnTo($this->getTitle()); return; } // The user didn't supply the blog post text? Ask them to supply it. if (!$wgRequest->getVal('pageBody')) { $wgOut->setPageTitle(wfMsg('errorpagetitle')); $wgOut->addWikiMsg('blog-create-error-need-content'); $wgOut->addReturnTo($this->getTitle()); return; } // Localized variables that will be used when creating the page $localizedCatNS = $wgContLang->getNsText(NS_CATEGORY); $today = $wgContLang->date(wfTimestampNow()); // Create the blog page if it doesn't already exist $article = new Article($title, 0); if ($article->exists()) { $wgOut->setPageTitle(wfMsg('errorpagetitle')); $wgOut->addWikiMsg('blog-create-error-page-exists'); $wgOut->addReturnTo($this->getTitle()); return; } else { // The blog post will be by default categorized into two // categories, "Articles by User $1" and "(today's date)", // but the user may supply some categories themselves, so // we need to take those into account, too. $categories = array('[[' . $localizedCatNS . ':' . wfMsgForContent('blog-by-user-category', wfMsgForContent('blog-category')) . wfMsgForContent('word-separator') . $wgUser->getName() . ']]', "[[{$localizedCatNS}:{$today}]]"); $userSuppliedCategories = $wgRequest->getVal('pageCtg'); if (!empty($userSuppliedCategories)) { // Explode along commas so that we will have an array that // we can loop over $userSuppliedCategories = explode(',', $userSuppliedCategories); foreach ($userSuppliedCategories as $cat) { $cat = trim($cat); // GTFO@excess whitespace if (!empty($cat)) { $categories[] = "[[{$localizedCatNS}:{$cat}]]"; } } } // Convert the array into a string $wikitextCategories = implode("\n", $categories); // Perform the edit $article->doEdit('<vote />' . "\n" . '<!--start text-->' . "\n" . $wgRequest->getVal('pageBody') . "\n\n" . '<comments />' . "\n\n" . $wikitextCategories . "\n__NOEDITSECTION__", wfMsgForContent('blog-create-summary')); $articleId = $article->getID(); // Add a vote for the page // This was originally in its own global function, // wfFinishCreateBlog and after that in the BlogHooks class but // it just wouldn't work with Special:CreateBlogPost so I // decided to move it here since this is supposed to be like // the primary way of creating new blog posts... // Using OutputPageBeforeHTML hook, which, according to its // manual page, runs on *every* page view was such a stupid // idea IMHO. $vote = new Vote($articleId); $vote->insert(1); $stats = new UserStatsTrack($wgUser->getID(), $wgUser->getName()); $stats->updateWeeklyPoints($stats->point_values['opinions_created']); $stats->updateMonthlyPoints($stats->point_values['opinions_created']); //if( $wgEnableFacebook ) { // BlogHooks::updateFacebookProfile(); //} //if( $wgSendNewArticleToFriends ) { // $invite = SpecialPage::getTitleFor( 'EmailNewArticle' ); // $wgOut->redirect( // $invite->getFullURL( 'page=' . $title->getPrefixedText() ) // ); //} // Redirect the user to the new blog post they just created $wgOut->redirect($title->getFullURL()); } } else { $_SESSION['alreadysubmitted'] = false; // Start building the HTML $output = ''; // Show the blog rules, if the message containing them ain't empty $message = trim(wfMsgExt('blog-create-rules', array('parse', 'content'))); // Yes, the strlen() is needed, I dunno why wfEmptyMsg() won't work if (!wfEmptyMsg('blog-create-rules', $message) && strlen($message) > 0) { $output .= $message . '<br />'; } // Main form $output .= $this->displayForm(); // Show everything to the user $wgOut->addHTML($output); } }
/** * Saves comment data in the database. */ public function saveComment() { $dbw = wfGetDB( DB_MASTER ); $dbw->begin(); $data = array( 'wlc_parent' => $this->mParent, 'wlc_post' => $this->mItem->getID(), 'wlc_user' => $this->mUserID, 'wlc_user_text' => $this->mUserText, 'wlc_anon_name' => $this->mAnonName, 'wlc_status' => $this->mStatus, 'wlc_timestamp' => $dbw->timestamp( $this->mTimestamp ), 'wlc_updated' => $dbw->timestamp( $this->mUpdated ) ); $delayed = array(); # Main update. if ( $this->mID ) { $dbw->update( 'wikilog_comments', $data, array( 'wlc_id' => $this->mID ), __METHOD__ ); } else { $cid = $dbw->nextSequenceValue( 'wikilog_comments_wlc_id' ); $data = array( 'wlc_id' => $cid ) + $data; $dbw->insert( 'wikilog_comments', $data, __METHOD__ ); $this->mID = $dbw->insertId(); # Now that we have an ID, we can generate the thread. $this->mThread = self::getThreadHistory( $this->mID, $this->mParent ); $delayed['wlc_thread'] = implode( '/', $this->mThread ); } # Save article with comment text. if ( $this->mTextChanged ) { $this->mCommentTitle = $this->getCommentArticleTitle(); $art = new Article( $this->mCommentTitle ); $art->doEdit( $this->mText, $this->getAutoSummary() ); $this->mTextChanged = false; $this->mCommentPage = $art->getID(); $delayed['wlc_comment_page'] = $this->mCommentPage; } # Delayed updates. if ( !empty( $delayed ) ) { $dbw->update( 'wikilog_comments', $delayed, array( 'wlc_id' => $this->mID ), __METHOD__ ); } # Update number of comments $this->mItem->updateNumComments( true ); # Commit $dbw->commit(); # Invalidate some caches. $this->mCommentTitle->invalidateCache(); $this->mItem->mTitle->invalidateCache(); $this->mItem->mTitle->getTalkPage()->invalidateCache(); $this->mItem->mParentTitle->invalidateCache(); }
/** * Get the javascript or css text content from a given classKey * * @param {String} $resourceName Resource Key to grab text for * @param {String} [$filePath] Optional file path to get js text * @return unknown */ function getResourceText($resourceName) { $output = ''; // Special case: title classes if (substr($resourceName, 0, 3) == 'WT:') { global $wgUser; // Get just the title part $titleBlock = substr($resourceName, 3); if ($titleBlock[0] == '-') { // Special case of "-" title $parts = explode('|', $titleBlock); $title = array_shift($parts); $titleParams = array(); foreach ($parts as $titleParam) { list($key, $val) = explode('=', $titleParam); $titleParams[$key] = $val; } /* * The "-" is a special key to user / site js system sucks * here is some code to handle it ... but it really * should be depreciated for some more logical system * like directly referencing the titles that we have a script-loader */ $sk = $wgUser->getSkin(); if (isset($titleParams['useskin'])) { // Make sure the skin name is valid $skinNames = Skin::getSkinNames(); $skinNames = array_keys($skinNames); if (in_array(strtolower($titleParams['useskin']), $skinNames)) { if ($titleParams['gen'] == 'css') { return $sk->generateUserStylesheet(); } // If in debug mode, add a comment with wiki title and rev: if ($this->debug) { $output .= "\n/**\n* GenerateUserJs: \n*/\n"; } return $sk->generateUserJs($titleParams['useskin']) . "\n"; } } else { if (isset($titleParams['gen']) && $titleParams['gen'] == 'css') { return $sk->generateUserStylesheet(); } } } else { $ext = substr($titleBlock, strrpos($titleBlock, '.') + 1); // Make sure the wiki title ends with .js or .css if (self::validFileExtension($ext)) { $this->errorMsg .= 'WikiTitle includes should end with .js or .css'; return false; } // It's a wiki title, append the output of the wikitext: $t = Title::newFromText($titleBlock); $a = new Article($t); // Only get the content if the page is not empty: if ($a->getID() !== 0) { // If in debug mode, add a comment with wiki title and rev: if ($this->debug) { $output .= "\n/**\n* ScriptLoader WikiPage: " . xml::escapeJsString($titleBlock) . " rev: " . $a->getID() . " \n*/\n"; } $fileContents = $a->getContent() . "\n"; // transform the output if the file is of type css: $output .= $ext == 'css' ? $this->transformCssOutput($resourceName, $fileContents) : $fileContents; return $output; } } } // Deal with the classKey as a file: $filePath = self::getPathFromClass($resourceName); if (!$filePath) { $this->errorMsg .= "\nError could not get file path: " . xml::escapeJsString($resourceName) . "\n"; return false; } // Get the file extension: $ext = substr($filePath, strrpos($filePath, '.') + 1); // Dealing with files if (trim($filePath) != '') { $fileContents = $this->getFileContents($filePath) . "\n"; if ($fileContents) { // Add the file name if debug is enabled if ($this->debug) { $output .= "\n\n/**\n* File: " . xml::escapeJsString($filePath) . "\n*/\n"; } // Transform the css output if the file is css $output .= $ext == 'css' ? $this->transformCssOutput($resourceName, $fileContents, $filePath) : $fileContents; return $output; } else { $this->errorMsg .= "\nError could not read file: " . xml::escapeJsString($filePath) . "\n"; return false; } } // If we did not return some js $this->errorMsg .= "\nUnknown error in getting scriptText for key: " . xml::escapeJsString($resourceName) . "\n"; return false; }
/** Just returns the page content. Accepts either: - a namespace id in $ns parameter OR - a string corresponding to a 'prefixed DBkey' serving as page title name. */ public function getPageContent(&$ns, &$pagename = null, &$article = null, &$title = null) { if ($ns === null) { return null; } if (is_string($ns)) { $title = Title::newFromText($ns); } else { $title = Title::makeTitle($ns, $pagename); } // paranoia. if (!is_object($title)) { return null; } $article = new Article($title); if ($article->getID() == 0) { return null; } return $article->getContent(); }
function execute( $par ) { global $wgRequest, $wgOut, $wgMemc, $wgUser; global $wgYTAS_User, $wgYTAS_Password, $wgYTAS_DeveloperId; global $wgYTAS_DefaultCategory, $wgYTAS_UseClientLogin, $wgYTAS_EnableLogging, $wgYTAS_UseNamespace, $wgYTAS_ClientId; $this->setHeaders(); $spTitle = $this->getTitle(); # Check permissions if( !$wgUser->isAllowed( 'upload' ) ) { if( !$wgUser->isLoggedIn() ) { $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' ); } else { $wgOut->permissionRequired( 'upload' ); } return; } if ($wgRequest->getVal('status') == '200' && $wgRequest->getVal('id') != null) { $wgOut->addHTML(wfMsg('youtubeauthsub_success', $wgRequest->getVal('id'))); $descTitle = null; $desc = wfMsg('youtubeauthsub_summary'); //TODO: can we grab the keywords and description the user has submitted? if ($wgYTAS_UseNamespace) { $descTitle = Title::makeTitle(NS_YOUTUBE, $wgRequest->getVal('id')); $a = new Article($descTitle); if ($a->getID() == 0) { $title = $keywords = $description = $category = ""; if ($wgRequest->getVal('metaid') != null) { $dbr = wfGetDB(DB_SLAVE); $row = $dbr->selectRow('ytas_meta', array('ytas_title', 'ytas_description', 'ytas_keywords', 'ytas_category'), array("ytas_id={$wgRequest->getVal('metaid')}")); if ($row) { $title = $row->ytas_title; $keywords = $row->ytas_keywords; $description = $row->ytas_description; $category = $row->ytas_category; } } $content = "{{YoutubeVideo|{$wgRequest->getVal('id')}|{$title}|{$keywords}|{$description}|{$category}}}"; $a->doEdit( $content, wfMsg( 'youtubeauthsub_summary' ), EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY ); } $wgOut->addWikiText(wfMsg('youtubeauthsub_viewpage', $descTitle->getFullText()) ); } if ($wgYTAS_EnableLogging) { # Add the log entry $log = new LogPage( 'upload' ); $log->addEntry( 'upload', $descTitle, $desc ); } } if ($wgYTAS_UseClientLogin) { $key = wfMemcKey('youtube', 'authsub', 'token', $wgYTAS_User); $token = $wgMemc->get( $key ); // regenerate the token if (!$token) { $result = wfSpecialYouTubePost("https://www.google.com/youtube/accounts/ClientLogin?" , "Email={$wgYTAS_User}&Passwd={$wgYTAS_Password}&service=youtube&source=wikiHow"); $YouTubeUser = ""; $lines = split("\n", $result); foreach ($lines as $line) { $params = split("=", $line); switch ($params[0]) { case "Auth": $token = $params[1]; break; case "YouTubeUser": $YouTubeUser = $params[1]; break; } } if (!$token) { $wgOut->addHTML(wfMsg('youtubeauthsub_tokenerror')); return; } $wgMemc->set($key, $token, 3600); } } else { $token = $wgRequest->getVal('token'); if (!$token) { $wgOut->addHTML(wfMsg('youtubeauthsub_authsubinstructions') . " <script type='text/javascript'> var gYTAS_nokeywords = '" . wfMsg('youtubeauthsub_jserror_nokeywords') . "'; var gYTAS_notitle = '" . wfMsg('youtubeauthsub_jserror_notitle') . "'; </script> <script type='text/javascript' src='/extensions/YouTubeAuthSub/youtubeauthsub.js'> </script> <form action='https://www.google.com/accounts/AuthSubRequest' method='POST' onsubmit='return checkYTASForm();' name='ytas_form'/> <input type='hidden' name='next' value='{$spTitle()->getFullURL()}'/> <input type='hidden' name='scope' value='http://gdata.youtube.com/feeds'/> <input type='hidden' name='session' value='0'/> <input type='hidden' name='secure' value='0'/> <input type='submit' value='" . wfMsg('youtubeauthsub_clickhere') . "'/>" ); return; } } if ($wgRequest->wasPosted()) { $url = "http://uploads.gdata.youtube.com/feeds/api/users/{$wgYTAS_User}/uploads"; $url = "http://gdata.youtube.com/action/GetUploadToken"; $data = "<?xml version='1.0'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007'> <media:group> <media:title type='plain'>" . FeedItem::xmlEncode($wgRequest->getVal('youtube_title')) . "</media:title> <media:description type='plain'>" . FeedItem::xmlEncode($wgRequest->getVal('youtube_description')) . "</media:description> <media:keywords>" . FeedItem::xmlEncode($wgRequest->getVal('youtube_keywords')) . "</media:keywords> <media:category scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>" . FeedItem::xmlEncode($wgRequest->getVal('youtube_category')) . "</media:category> </media:group> </entry> "; $headers = array ( "GData-Version: 2", "X-GData-Client: key={$wgYTAS_ClientId}", "X-GData-Key: key={$wgYTAS_DeveloperId}", "Content-Type: application/atom+xml; charset=UTF-8", "Content-Length: " . strlen($data), ); if ($wgYTAS_UseClientLogin) $headers[] = "Authorization: GoogleLogin auth=$token"; else $headers[] = "Authorization: AuthSub token=$token"; $results = wfSpecialYouTubePost($url, $data, $headers); $url = preg_replace("@.*<url>(.*)</url>.*@", "$1", $results); $token = preg_replace("@.*<token>(.*)</token>.*@", "$1", $results); if ($url == "") { $wgOut->addHTML("Unable to extract URL, results where <pre>{$results}</pre>"); return; } // CAPTURE THE META INFO AND STORE IT $meta_id = ''; $dbw = wfGetDB(DB_MASTER); $fields = array ( 'ytas_user' => $wgUser->getID(), 'ytas_timestamp' => $dbw->timestamp( time() ), 'ytas_title' => $wgRequest->getVal('youtube_title'), 'ytas_description' => $wgRequest->getVal('youtube_description'), 'ytas_keywords' => $wgRequest->getVal('youtube_keywords'), 'ytas_category' => $wgRequest->getVal('youtube_category') ); $dbw->insert( 'ytas_meta', $fields, __METHOD__, array( 'IGNORE' ) ); if ( $dbw->affectedRows() ) { $meta_id =$dbw->insertId(); } $next_url = urlencode($spTitle()->getFullURL() . "?metaid={$meta_id}"); $wgOut->addHTML(wfMsg('youtubeauthsub_uploadhere') . "<br /><br /> <form action='{$url}?nexturl={$next_url}' METHOD='post' enctype='multipart/form-data' name='videoupload'> <input type='file' name='file' size='50'/> <input type='hidden' name='token' value='{$token}'/><br /> <input type='submit' name='submitbtn' value='" . wfMsg('youtubeauthsub_uploadbutton') . "'/> </form> <center> <div id='upload_image' style='display:none;'> " . wfMsg('youtubeauthsub_uploading') . " <img src='/extensions/YouTubeAuthSub/upload.gif'> </div> </center> "); } else { $wgOut->addHTML( wfMsg('youtubeauthsub_info') . " <script type='text/javascript'> var gYTAS_nokeywords = '" . wfMsg('youtubeauthsub_jserror_nokeywords') . "'; var gYTAS_nodesc = '" . wfMsg('youtubeauthsub_jserror_nodesc') . "'; var gYTAS_notitle = '" . wfMsg('youtubeauthsub_jserror_notitle') . "'; </script> <script type='text/javascript' src='/extensions/YouTubeAuthSub/youtubeauthsub.js'> </script> <form action='{$spTitle->getFullURL()}' method='POST' name='ytas_form' onsubmit='return checkYTASForm();'> <table cellpadding='10'> "); if (!$wgYTAS_UseClientLogin) { $wgOut->addHTML("<input type='hidden' name='token' value='{$wgRequest->getVal('token')}'/>"); } $wgOut->addHTML(" <tr> <td>" . wfMsg('youtubeauthsub_title') . ":</td> <td><input type='text' name='youtube_title' size='40'/></td> </tr> <tr> <td valign='top'>" . wfMsg('youtubeauthsub_description') . ":</td> <td><textarea cols='100' rows='4' name='youtube_description'></textarea></td> </tr> <tr> <td>" . wfMsg('youtubeauthsub_keywords') . ":</td> <td><input type='text' name='youtube_keywords' size='40'/></td> </tr>"); if (!$wgYTAS_DefaultCategory) { $cats = wfSpecialYouTubeGetCategories(); $wgOut->addHTML(" <tr> <td>" . wfMsg('youtubeauthsub_category') . ":</td> <td><select type='text' name='youtube_category'/>{$cats}</select></td> </tr>"); } else { $wgOut->addHTML("<input type='hidden' name='youtube_category' value='{$wgYTAS_DefaultCategory}'/>"); } $wgOut->addHTML(" <tr> <td><input type='submit' value='" . wfMsg('youtubeauthsub_submit') . "'></td> </tr> </table> </form>"); } }
/** * Return instance of this class for given article from RelatedVideos namespace */ public static function newFromArticle(Article $article) { $id = $article->getID(); return self::newFromId($id); }
private function printForm(&$parameters, WebRequest &$request) { global $wgOut, $sfgFormPrinter; // Prepare parameters for SFFormPrinter::formHTML // there is no ONE target page $targetTitle = null; // formDefinition $formName = $request->getText('form'); // if query string did not contain these variables, try the URL if ($formName === '') { $queryparts = explode('/', $parameters); $formName = isset($queryparts[0]) ? $queryparts[0] : null; // if the form name wasn't in the URL either, throw an error if (is_null($formName) || $formName === '') { throw new SPSException(SPSUtils::buildMessage('spserror-noformname')); } } $formTitle = Title::makeTitleSafe(SF_NS_FORM, $formName); if (!$formTitle->exists()) { throw new SPSException(SPSUtils::buildMessage('spserror-formunknown', $formName)); } $formArticle = new Article($formTitle); $formDefinition = StringUtils::delimiterReplace('<noinclude>', '</noinclude>', '', $formArticle->getContent()); // formSubmitted $formSubmitted = false; // pageContents $pageContents = null; // get 'preload' query value, if it exists if ($request->getCheck('preload')) { $pageContents = SFFormUtils::getPreloadedText($request->getVal('preload')); } else { // let other extensions preload the page, if they want wfRunHooks('sfEditFormPreloadText', array(&$pageContents, $targetTitle, $formTitle)); } // pageIsSource $pageIsSource = $pageContents != null; // pageNameFormula // parse the form to see if it has a 'page name' value set $matches; if (preg_match('/{{{info.*page name\\s*=\\s*(.*)}}}/m', $formDefinition, $matches)) { $pageNameElements = SFUtils::getFormTagComponents($matches[1]); $pageNameFormula = $pageNameElements[0]; } else { return 'sf_formedit_badurl'; } // get the iterator parameters $iteratorData = $this->buildIteratorParameters($request); // Call SFFormPrinter::formHTML list($formText, $javascriptText, $dataText, $formPageTitle, $generatedPageName) = $sfgFormPrinter->formHTML($formDefinition, $formSubmitted, $pageIsSource, $formArticle->getID(), $pageContents, '', $pageNameFormula); // Set Special page main header; // override the default title for this page if a title was specified in the form if ($formPageTitle != null) { $wgOut->setPageTitle($formPageTitle); } else { $wgOut->setPageTitle(SPSUtils::buildMessage('sf_formedit_createtitlenotarget', $formTitle->getText())); } $preFormHtml = ''; wfRunHooks('sfHTMLBeforeForm', array(&$targetTitle, &$preFormHtml)); $text = '<form name="createbox" id="sfForm" action="" method="post" class="createbox">' . $preFormHtml . "\n" . SFFormUtils::hiddenFieldHTML('iteratordata', $iteratorData) . $formText; SFUtils::addJavascriptAndCSS(); if (!empty($javascriptText)) { $wgOut->addScript(' <script type="text/javascript">' . "\n{$javascriptText}\n" . '</script>' . "\n"); } $wgOut->addHTML($text); return null; }
/** * @param Article $article * @return mixed|string */ protected function getOptionsKey($article) { $pageid = $article->getID(); return wfMemcKey('pcache', 'idoptions', "{$pageid}"); }
public function store() { wfProfileIn(__METHOD__); if ($this->isEnabled !== false) { $oTitle = F::build('Title', array($this->sTitle), 'newFromText'); if ($oTitle instanceof Title) { $oTitle->exists(); $this->pageId = $oTitle->getArticleID(); if ($this->pageId == 0) { $oArticle = new Article($oTitle); $oArticle->doEdit('', wfMsg('places-updated-geolocation'), EDIT_NEW); $this->pageId = $oArticle->getID(); } $this->app->wf->setWikiaPageProp(WPP_PLACES_CATEGORY_GEOTAGGED, $this->pageId, (int) $this->isEnabled); // update the cache $this->memc->set($this->getMemcKey(), $this->isEnabled, self::CACHE_TTL); } } wfProfileOut(__METHOD__); }
static function getXMLForPage($title, $simplified_format, $groupings, $depth = 0) { if ($depth > 5) { return ""; } global $wgContLang, $dtgContLang; $namespace_labels = $wgContLang->getNamespaces(); $template_label = $namespace_labels[NS_TEMPLATE]; $namespace_str = str_replace(' ', '_', wfMsgForContent('dt_xml_namespace')); $page_str = str_replace(' ', '_', wfMsgForContent('dt_xml_page')); $field_str = str_replace(' ', '_', wfMsgForContent('dt_xml_field')); $name_str = str_replace(' ', '_', wfMsgForContent('dt_xml_name')); $title_str = str_replace(' ', '_', wfMsgForContent('dt_xml_title')); $id_str = str_replace(' ', '_', wfMsgForContent('dt_xml_id')); $free_text_str = str_replace(' ', '_', wfMsgForContent('dt_xml_freetext')); // if this page belongs to the exclusion category, exit $parent_categories = $title->getParentCategoryTree(array()); $dt_props = $dtgContLang->getPropertyLabels(); // $exclusion_category = $title->newFromText($dt_props[DT_SP_IS_EXCLUDED_FROM_XML], NS_CATEGORY); $exclusion_category = $wgContLang->getNSText(NS_CATEGORY) . ':' . str_replace(' ', '_', $dt_props[DT_SP_IS_EXCLUDED_FROM_XML]); if (self::treeContainsElement($parent_categories, $exclusion_category)) { return ""; } $article = new Article($title); $page_title = str_replace('"', '"', $title->getText()); $page_title = str_replace('&', '&', $page_title); $page_namespace = $title->getNamespace(); if ($simplified_format) { $text = "<{$page_str}><{$id_str}>{$article->getID()}</{$id_str}><{$title_str}>{$page_title}</{$title_str}>\n"; } else { $text = "<{$page_str} {$id_str}=\"" . $article->getID() . "\" {$title_str}=\"" . $page_title . '" >'; } // traverse the page contents, one character at a time $uncompleted_curly_brackets = 0; $page_contents = $article->getContent(); // escape out variables like "{{PAGENAME}}" $page_contents = str_replace('{{PAGENAME}}', '{{PAGENAME}}', $page_contents); // escape out parser functions $page_contents = preg_replace('/{{(#.+)}}/', '{{$1}}', $page_contents); // escape out transclusions $page_contents = preg_replace('/{{(:.+)}}/', '{{$1}}', $page_contents); // escape out variable names $page_contents = str_replace('{{{', '{{{', $page_contents); $page_contents = str_replace('}}}', '}}}', $page_contents); // escape out tables $page_contents = str_replace('{|', '{|', $page_contents); $page_contents = str_replace('|}', '|}', $page_contents); $free_text = ""; $free_text_id = 1; $template_name = ""; $field_name = ""; $field_value = ""; $field_has_name = false; for ($i = 0; $i < strlen($page_contents); $i++) { $c = $page_contents[$i]; if ($uncompleted_curly_brackets == 0) { if ($c == "{" || $i == strlen($page_contents) - 1) { if ($i == strlen($page_contents) - 1) { $free_text .= $c; } $uncompleted_curly_brackets++; $free_text = trim($free_text); $free_text = str_replace('&', '&', $free_text); $free_text = str_replace('[', '[', $free_text); $free_text = str_replace(']', ']', $free_text); $free_text = str_replace('<', '<', $free_text); $free_text = str_replace('>', '>', $free_text); if ($free_text != "") { $text .= "<{$free_text_str} id=\"{$free_text_id}\">{$free_text}</{$free_text_str}>"; $free_text = ""; $free_text_id++; } } elseif ($c == "{") { // do nothing } else { $free_text .= $c; } } elseif ($uncompleted_curly_brackets == 1) { if ($c == "{") { $uncompleted_curly_brackets++; $creating_template_name = true; } elseif ($c == "}") { $uncompleted_curly_brackets--; // is this needed? // if ($field_name != "") { // $field_name = ""; // } if ($page_contents[$i - 1] == '}') { if ($simplified_format) { $text .= "</" . $template_name . ">"; } else { $text .= "</{$template_label}>"; } } $template_name = ""; } } else { // 2 or greater - probably 2 if ($c == "}") { $uncompleted_curly_brackets--; } if ($c == "{") { $uncompleted_curly_brackets++; } else { if ($creating_template_name) { if ($c == "|" || $c == "}") { $template_name = str_replace(' ', '_', trim($template_name)); $template_name = str_replace('&', '&', $template_name); if ($simplified_format) { $text .= "<" . $template_name . ">"; } else { $text .= "<{$template_label} {$name_str}=\"{$template_name}\">"; } $creating_template_name = false; $creating_field_name = true; $field_id = 1; } else { $template_name .= $c; } } else { if ($c == "|" || $c == "}") { if ($field_has_name) { $field_value = str_replace('&', '&', $field_value); if ($simplified_format) { $field_name = str_replace(' ', '_', trim($field_name)); $text .= "<" . $field_name . ">"; $text .= trim($field_value); $text .= "</" . $field_name . ">"; } else { $text .= "<{$field_str} {$name_str}=\"" . trim($field_name) . "\">"; $text .= trim($field_value); $text .= "</{$field_str}>"; } $field_value = ""; $field_has_name = false; } else { // "field_name" is actually the value if ($simplified_format) { $field_name = str_replace(' ', '_', $field_name); // add "Field" to the beginning of the file name, since // XML tags that are simply numbers aren't allowed $text .= "<" . $field_str . '_' . $field_id . ">"; $text .= trim($field_name); $text .= "</" . $field_str . '_' . $field_id . ">"; } else { $text .= "<{$field_str} {$name_str}=\"{$field_id}\">"; $text .= trim($field_name); $text .= "</{$field_str}>"; } $field_id++; } $creating_field_name = true; $field_name = ""; } elseif ($c == "=") { // handle case of = in value if (!$creating_field_name) { $field_value .= $c; } else { $creating_field_name = false; $field_has_name = true; } } elseif ($creating_field_name) { $field_name .= $c; } else { $field_value .= $c; } } } } } // handle groupings, if any apply here; first check if SMW is installed global $smwgIP; if (isset($smwgIP)) { $store = smwfGetStore(); foreach ($groupings as $pair) { list($property_page, $grouping_label) = $pair; $options = new SMWRequestOptions(); $options->sort = "subject_title"; // get actual property from the wiki-page of the property if (class_exists('SMWDIProperty')) { $wiki_page = new SMWDIWikiPage($page_title, $page_namespace, null); $property = SMWDIProperty::newFromUserLabel($property_page->getTitle()->getText()); } else { $wiki_page = SMWDataValueFactory::newTypeIDValue('_wpg', $page_title); $property = SMWPropertyValue::makeProperty($property_page->getTitle()->getText()); } $res = $store->getPropertySubjects($property, $wiki_page, $options); $num = count($res); if ($num > 0) { $grouping_label = str_replace(' ', '_', $grouping_label); $text .= "<{$grouping_label}>\n"; foreach ($res as $subject) { $subject_title = $subject->getTitle(); $text .= self::getXMLForPage($subject_title, $simplified_format, $groupings, $depth + 1); } $text .= "</{$grouping_label}>\n"; } } } $text .= "</{$page_str}>\n"; // escape back the curly brackets that were escaped out at the beginning $text = str_replace('&#123;', '{', $text); $text = str_replace('&#125;', '}', $text); return $text; }
public function execute() { global $wgUser; $params = $this->extractRequestParams(); if (is_null($params['text']) && is_null($params['appendtext']) && is_null($params['prependtext']) && $params['undo'] == 0) { $this->dieUsageMsg(array('missingtext')); } $titleObj = Title::newFromText($params['title']); if (!$titleObj || $titleObj->isExternal()) { $this->dieUsageMsg(array('invalidtitle', $params['title'])); } if ($params['redirect']) { if ($titleObj->isRedirect()) { $oldTitle = $titleObj; $titles = Title::newFromRedirectArray(Revision::newFromTitle($oldTitle)->getText(Revision::FOR_THIS_USER)); $redirValues = array(); foreach ($titles as $id => $newTitle) { if (!isset($titles[$id - 1])) { $titles[$id - 1] = $oldTitle; } $redirValues[] = array('from' => $titles[$id - 1]->getPrefixedText(), 'to' => $newTitle->getPrefixedText()); $titleObj = $newTitle; } $this->getResult()->setIndexedTagName($redirValues, 'r'); $this->getResult()->addValue(null, 'redirects', $redirValues); } } // Some functions depend on $wgTitle == $ep->mTitle global $wgTitle; $wgTitle = $titleObj; if ($params['createonly'] && $titleObj->exists()) { $this->dieUsageMsg(array('createonly-exists')); } if ($params['nocreate'] && !$titleObj->exists()) { $this->dieUsageMsg(array('nocreate-missing')); } // Now let's check whether we're even allowed to do this $errors = $titleObj->getUserPermissionsErrors('edit', $wgUser); if (!$titleObj->exists()) { $errors = array_merge($errors, $titleObj->getUserPermissionsErrors('create', $wgUser)); } if (count($errors)) { $this->dieUsageMsg($errors[0]); } $articleObj = new Article($titleObj); $toMD5 = $params['text']; if (!is_null($params['appendtext']) || !is_null($params['prependtext'])) { // For non-existent pages, Article::getContent() // returns an interface message rather than '' // We do want getContent()'s behavior for non-existent // MediaWiki: pages, though if ($articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI) { $content = ''; } else { $content = $articleObj->getContent(); } if (!is_null($params['section'])) { // Process the content for section edits global $wgParser; $section = intval($params['section']); $content = $wgParser->getSection($content, $section, false); if ($content === false) { $this->dieUsage("There is no section {$section}.", 'nosuchsection'); } } $params['text'] = $params['prependtext'] . $content . $params['appendtext']; $toMD5 = $params['prependtext'] . $params['appendtext']; } if ($params['undo'] > 0) { if ($params['undoafter'] > 0) { if ($params['undo'] < $params['undoafter']) { list($params['undo'], $params['undoafter']) = array($params['undoafter'], $params['undo']); } $undoafterRev = Revision::newFromID($params['undoafter']); } $undoRev = Revision::newFromID($params['undo']); if (is_null($undoRev) || $undoRev->isDeleted(Revision::DELETED_TEXT)) { $this->dieUsageMsg(array('nosuchrevid', $params['undo'])); } if ($params['undoafter'] == 0) { $undoafterRev = $undoRev->getPrevious(); } if (is_null($undoafterRev) || $undoafterRev->isDeleted(Revision::DELETED_TEXT)) { $this->dieUsageMsg(array('nosuchrevid', $params['undoafter'])); } if ($undoRev->getPage() != $articleObj->getID()) { $this->dieUsageMsg(array('revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText())); } if ($undoafterRev->getPage() != $articleObj->getID()) { $this->dieUsageMsg(array('revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText())); } $newtext = $articleObj->getUndoText($undoRev, $undoafterRev); if ($newtext === false) { $this->dieUsageMsg(array('undo-failure')); } $params['text'] = $newtext; // If no summary was given and we only undid one rev, // use an autosummary if (is_null($params['summary']) && $titleObj->getNextRevisionID($undoafterRev->getID()) == $params['undo']) { $params['summary'] = wfMsgForContent('undo-summary', $params['undo'], $undoRev->getUserText()); } } // See if the MD5 hash checks out if (!is_null($params['md5']) && md5($toMD5) !== $params['md5']) { $this->dieUsageMsg(array('hashcheckfailed')); } $ep = new EditPage($articleObj); // EditPage wants to parse its stuff from a WebRequest // That interface kind of sucks, but it's workable $reqArr = array('wpTextbox1' => $params['text'], 'wpEditToken' => $params['token'], 'wpIgnoreBlankSummary' => ''); if (!is_null($params['summary'])) { $reqArr['wpSummary'] = $params['summary']; } // Watch out for basetimestamp == '' // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict if (!is_null($params['basetimestamp']) && $params['basetimestamp'] != '') { $reqArr['wpEdittime'] = wfTimestamp(TS_MW, $params['basetimestamp']); } else { $reqArr['wpEdittime'] = $articleObj->getTimestamp(); } if (!is_null($params['starttimestamp']) && $params['starttimestamp'] != '') { $reqArr['wpStarttime'] = wfTimestamp(TS_MW, $params['starttimestamp']); } else { $reqArr['wpStarttime'] = wfTimestampNow(); // Fake wpStartime } if ($params['minor'] || !$params['notminor'] && $wgUser->getOption('minordefault')) { $reqArr['wpMinoredit'] = ''; } if ($params['recreate']) { $reqArr['wpRecreate'] = ''; } if (!is_null($params['section'])) { $section = intval($params['section']); if ($section == 0 && $params['section'] != '0' && $params['section'] != 'new') { $this->dieUsage("The section parameter must be set to an integer or 'new'", "invalidsection"); } $reqArr['wpSection'] = $params['section']; } else { $reqArr['wpSection'] = ''; } $watch = $this->getWatchlistValue($params['watchlist'], $titleObj); // Deprecated parameters if ($params['watch']) { $watch = true; } elseif ($params['unwatch']) { $watch = false; } if ($watch) { $reqArr['wpWatchthis'] = ''; } $req = new FauxRequest($reqArr, true); $ep->importFormData($req); // Run hooks // Handle CAPTCHA parameters global $wgRequest; if (!is_null($params['captchaid'])) { $wgRequest->setVal('wpCaptchaId', $params['captchaid']); } if (!is_null($params['captchaword'])) { $wgRequest->setVal('wpCaptchaWord', $params['captchaword']); } $r = array(); if (!wfRunHooks('APIEditBeforeSave', array($ep, $ep->textbox1, &$r))) { if (count($r)) { $r['result'] = 'Failure'; $this->getResult()->addValue(null, $this->getModuleName(), $r); return; } else { $this->dieUsageMsg(array('hookaborted')); } } // Do the actual save $oldRevId = $articleObj->getRevIdFetched(); $result = null; // Fake $wgRequest for some hooks inside EditPage // FIXME: This interface SUCKS $oldRequest = $wgRequest; $wgRequest = $req; $retval = $ep->internalAttemptSave($result, $wgUser->isAllowed('bot') && $params['bot']); $wgRequest = $oldRequest; global $wgMaxArticleSize; switch ($retval) { case EditPage::AS_HOOK_ERROR: case EditPage::AS_HOOK_ERROR_EXPECTED: $this->dieUsageMsg(array('hookaborted')); case EditPage::AS_IMAGE_REDIRECT_ANON: $this->dieUsageMsg(array('noimageredirect-anon')); case EditPage::AS_IMAGE_REDIRECT_LOGGED: $this->dieUsageMsg(array('noimageredirect-logged')); case EditPage::AS_SPAM_ERROR: $this->dieUsageMsg(array('spamdetected', $result['spam'])); case EditPage::AS_FILTERING: $this->dieUsageMsg(array('filtered')); case EditPage::AS_BLOCKED_PAGE_FOR_USER: $this->dieUsageMsg(array('blockedtext')); case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED: case EditPage::AS_CONTENT_TOO_BIG: $this->dieUsageMsg(array('contenttoobig', $wgMaxArticleSize)); case EditPage::AS_READ_ONLY_PAGE_ANON: $this->dieUsageMsg(array('noedit-anon')); case EditPage::AS_READ_ONLY_PAGE_LOGGED: $this->dieUsageMsg(array('noedit')); case EditPage::AS_READ_ONLY_PAGE: $this->dieReadOnly(); case EditPage::AS_RATE_LIMITED: $this->dieUsageMsg(array('actionthrottledtext')); case EditPage::AS_ARTICLE_WAS_DELETED: $this->dieUsageMsg(array('wasdeleted')); case EditPage::AS_NO_CREATE_PERMISSION: $this->dieUsageMsg(array('nocreate-loggedin')); case EditPage::AS_BLANK_ARTICLE: $this->dieUsageMsg(array('blankpage')); case EditPage::AS_CONFLICT_DETECTED: $this->dieUsageMsg(array('editconflict')); // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary case EditPage::AS_TEXTBOX_EMPTY: $this->dieUsageMsg(array('emptynewsection')); case EditPage::AS_SUCCESS_NEW_ARTICLE: $r['new'] = ''; case EditPage::AS_SUCCESS_UPDATE: $r['result'] = 'Success'; $r['pageid'] = intval($titleObj->getArticleID()); $r['title'] = $titleObj->getPrefixedText(); // HACK: We create a new Article object here because getRevIdFetched() // refuses to be run twice, and because Title::getLatestRevId() // won't fetch from the master unless we select for update, which we // don't want to do. $newArticle = new Article($titleObj); $newRevId = $newArticle->getRevIdFetched(); if ($newRevId == $oldRevId) { $r['nochange'] = ''; } else { $r['oldrevid'] = intval($oldRevId); $r['newrevid'] = intval($newRevId); $r['newtimestamp'] = wfTimestamp(TS_ISO_8601, $newArticle->getTimestamp()); } break; case EditPage::AS_SUMMARY_NEEDED: $this->dieUsageMsg(array('summaryrequired')); case EditPage::AS_END: // This usually means some kind of race condition // or DB weirdness occurred. Fall through to throw an unknown // error. // This needs fixing higher up, as Article::doEdit should be // used rather than Article::updateArticle, so that specific // error conditions can be returned // This usually means some kind of race condition // or DB weirdness occurred. Fall through to throw an unknown // error. // This needs fixing higher up, as Article::doEdit should be // used rather than Article::updateArticle, so that specific // error conditions can be returned default: $this->dieUsageMsg(array('unknownerror', $retval)); } $this->getResult()->addValue(null, $this->getModuleName(), $r); }
private function rollbackTitle($title, $users, $time, $summary, &$messages = '') { global $wgUser; // build article object and find article id $a = new Article($title); $pageId = $a->getID(); // check if article exists if ($pageId <= 0) { $messages = 'page not found'; return false; } // fetch revisions from this article $dbw = wfGetDB(DB_MASTER); $res = $dbw->select('revision', array('rev_id', 'rev_user_text', 'rev_timestamp'), array('rev_page' => $pageId), __METHOD__, array('ORDER BY' => 'rev_id DESC')); // find the newest edit done by other user $revertRevId = false; while ($row = $dbw->fetchObject($res)) { if (!in_array($row->rev_user_text, $users) || $row->rev_timestamp < $time) { $revertRevId = $row->rev_id; break; } } $dbw->freeResult($res); if ($revertRevId) { // found an edit by other user - reverting $rev = Revision::newFromId($revertRevId); $text = $rev->getRawText(); $status = $a->doEdit($text, $summary, EDIT_UPDATE | EDIT_MINOR | EDIT_FORCE_BOT); if ($status->isOK()) { $messages = 'reverted'; return true; } else { $messages = "edit errors: " . implode(', ', $status->getErrorsArray()); } } else { // no edits by other users - deleting page $errorDelete = ''; $status = $this->deleteArticle($a, $summary, false, $errorDelete); if ($status) { $messages = 'deleted'; return true; } else { $messages = "delete errors: " . $errorDelete; } } return false; }