function redircite_render($input, $args, &$parser) { // Generate HTML code and add it to the $redirciteMarkerList array // Add "xx-redircite-marker-NUMBER-redircite-xx" to the output, // which will be translated to the HTML stored in $redirciteMarkerList by // redircite_afterTidy() global $redirciteMarkerList; # Verify that $input is a valid title $inputTitle = Title::newFromText($input); if(!$inputTitle) return $input; $link1 = $parser->recursiveTagParse("[[$input]]"); $title1 = Title::newFromText($input); if(!$title1->exists()) // Page doesn't exist // Just output a normal (red) link return $link1; $articleObj = new Article($title1); $title2 = Title::newFromRedirect($articleObj->fetchContent()); if(!$title2) // Page is not a redirect // Just output a normal link return $link1; $link2 = $parser->recursiveTagParse("[[{$title2->getPrefixedText()}|$input]]"); $marker = "xx-redircite-marker-" . count($redirciteMarkerList) . "-redircite-xx"; $onmouseout = 'this.firstChild.innerHTML = "'. Xml::escapeJsString($input) . '";'; $onmouseover = 'this.firstChild.innerHTML = "' . Xml::escapeJsString($title2->getPrefixedText()) . '";'; return Xml::tags('span', array( 'onmouseout' => $onmouseout, 'onmouseover' => $onmouseover), $link2); }
function execute($query) { global $wgRequest, $wgOut; $wgOut->disable(); $this->setHeaders(); $page_name = $query; $title = Title::newFromText($page_name); if (is_null($title)) { return; } if (!$title->userCan('read')) { return; } $article = new Article($title); $page_text = $article->fetchContent(); // Remove <noinclude> sections and <includeonly> tags from text $page_text = StringUtils::delimiterReplace('<noinclude>', '</noinclude>', '', $page_text); $page_text = strtr($page_text, array('<includeonly>' => '', '</includeonly>' => '')); $orig_lines = explode("\n", $page_text); // ignore lines that are either blank or start with a semicolon $page_lines = array(); foreach ($orig_lines as $i => $line) { if ($line != '' && $line[0] != ';') { $page_lines[] = $line; } } $headers = EDUtils::getValuesFromCSVLine($page_lines[0]); $queried_headers = array(); foreach ($wgRequest->getValues() as $key => $value) { foreach ($headers as $header_index => $header_value) { $header_value = str_replace(' ', '_', $header_value); if ($key == $header_value) { $queried_headers[$header_index] = $value; } } } // include header in output $text = $page_lines[0]; foreach ($page_lines as $i => $line) { if ($i == 0) { continue; } $row_values = EDUtils::getValuesFromCSVLine($line); $found_match = true; foreach ($queried_headers as $i => $query_value) { $single_value = str_replace(' ', '_', $row_values[$i]); if ($single_value != $query_value) { $found_match = false; } } if ($found_match) { if ($text != '') { $text .= "\n"; } $text .= $line; } } print $text; }
/** * Take a bit of WikiText that looks like * <rss max=5>http://example.com/</rss> * and return an object that can produce rendered output. */ function __construct($url, $args) { $this->url = $url; # Get max number of headlines from argument-array if (isset($args['max'])) { $this->maxheads = $args['max']; } # Get reverse flag from argument array if (isset($args['reverse'])) { $this->reversed = true; } # Get date format from argument array # FIXME: not used yet if (isset($args['date'])) { $this->date = $args['date']; } # Get highlight terms from argument array if (isset($args['highlight'])) { # mapping to lowercase here so the regex can be case insensitive below. $this->highlight = self::explodeOnSpaces($args['highlight']); } # Get filter terms from argument array if (isset($args['filter'])) { $this->filter = self::explodeOnSpaces($args['filter']); } if (isset($args['filterout'])) { $this->filterOut = self::explodeOnSpaces($args['filterout']); } // 'template' is the pagename of a user's itemTemplate including // a further pagename for the feedTemplate // In that way everything is handled via these two pages // and no default pages or templates are used. // 'templatename' is an optional pagename of a user's feedTemplate // In that way it substitutes $1 (default: RSSPost) in MediaWiki:Rss-item if (isset($args['template'])) { $itemTemplateTitleObject = Title::newFromText($args['template'], NS_TEMPLATE); $itemTemplateArticleObject = new Article($itemTemplateTitleObject, 0); $this->itemTemplate = $itemTemplateArticleObject->fetchContent(); } else { if (isset($args['templatename'])) { $feedTemplatePagename = $args['templatename']; } else { // compatibility patch for rss extension $feedTemplatePagename = 'RSSPost'; $feedTemplateTitleObject = Title::newFromText($feedTemplatePagename, NS_TEMPLATE); if (!$feedTemplateTitleObject->exists()) { $feedTemplatePagename = Title::makeTitleSafe(NS_MEDIAWIKI, 'Rss-feed'); } } // MediaWiki:Rss-item = {{ feedTemplatePagename | title = {{{title}}} | ... }} // if the attribute parameter templatename= is not present // then it defaults to // {{ Template:RSSPost | title = {{{title}}} | ... }} - if Template:RSSPost exists from pre-1.9 versions // {{ MediaWiki:Rss-feed | title = {{{title}}} | ... }} - otherwise $this->itemTemplate = wfMsgNoTrans('rss-item', $feedTemplatePagename); } }
function addImageToArticle($name) { $title = Title::newFromText($name); echo $title->getText() . "\n"; $article = new Article($title, 0); if (!$article) { echo 'replaceText: Article not found.' . "\n"; return false; } $content = $article->fetchContent(); }
/** * Parses 'MediaWiki:Flagarticle-templatelist' with replaceLinks() and normal mediawiki parser * Shows a selection of different templates (which are defined in the above message) * * @param $page String: title of the page that needs to be edited */ function selection($page) { global $wgOut; $templatelist = new Article(Title::newFromText('flagpage-templatelist', NS_MEDIAWIKI)); $templatelistcontent = $templatelist->fetchContent(); if ($templatelistcontent == "") { $wgOut->showErrorPage('flagpage-emptylisttitle', 'flagpage-emptylist'); } $templatelistcontent = $this->replaceLinks($page, $templatelistcontent); $wgOut->addWikiText('<div class="plainlinks">' . $templatelistcontent . '</div>'); }
function getRS() { global $wgMemc; $key_rs = wfMemcKey("risingstar-feed3:" . date('YmdG') . ":" . number_format(date('i') / 10, 0, '', '')); $rsOut = $wgMemc->get($key_rs); if (!empty($rsOut)) { return $rsOut; } $t = Title::newFromText('wikiHow:Rising-star-feed'); if ($t->getArticleId() > 0) { $r = Revision::newFromTitle($t); $text = $r->getText(); } else { return false; } //NOTE: temporary patch to handle archives. the authoritative source for RS needs to be moved to the DB versus the feed article. add archive to array. $archives = array('wikiHow:Rising-star-feed/archive1'); foreach ($archives as $archive) { $tarch = Title::newFromText($archive); if ($tarch->getArticleId() > 0) { $r = Revision::newFromTitle($tarch); $text = $r->getText() . "\n" . $text; } } $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]); $title = preg_replace("/http:\\/\\/.*?\\.com\\//", "", $matches[2]); $t = Title::newFromText($title); if (!isset($t)) { continue; } $a = new Article($t); if ($a->isRedirect()) { $t = Title::newFromRedirect($a->fetchContent()); $a = new Article($t); } $rsout[$t->getPartialURL()] = $dt; } } // sort by most recent first $rsout = array_reverse($rsout); $wgMemc->set($key_rs, $rsout); return $rsout; }
/** * Gets the content of the article with the provided page name, * or an empty string when there is no such article. * * @since 0.1 * * @param string $pageName * * @return string */ public static function getParsedArticleContent($pageName) { $title = Title::newFromText($pageName); if (is_null($title)) { return ''; } $article = new Article($title, 0); global $wgParser, $wgContestEmailParse; $wgContestEmailParse = true; $text = $wgParser->parse($article->fetchContent(), $article->getTitle(), $article->getParserOptions())->getText(); $wgContestEmailParse = false; return $text; }
public function execute() { global $wgTitle; $res = $this->queryPages(); if (!$res || count($res) === 0) { $this->log('No results'); } else { $this->log(count($res) . ' results found'); } if ($this->hasOption('from')) { $from = trim($this->getOption('from')); $skip = true; } //echo $from; exit; //$this->log(print_r($res,true)); foreach ($res as $row) { if (isset($from)) { if (trim($row->page_title) == $from) { $skip = false; } if ($skip) { $this->log('Skipping ' . $row->page_title); continue; } } $title = Title::newFromText($row->page_title); $article = new Article($title, 0); if (!$article) { $this->log('Page title not found: ' . $row->page_title); return false; } $content = $article->fetchContent(); if (preg_match('%{{(Plant|Cultivar|Cultivar group|Variety|Subspecies)%ui', $content, $m)) { $has_tpl = preg_match('%{{Article state%ui', $content, $matched); if (!$has_tpl) { $this->log($title->getText()); $this->log('Adding article state template'); $content .= "{{Article state\n|article cleanup=Yes\n|article incomplete=Yes\n|article citations=No\n}}"; $edit_summary = 'Adding article state template.'; $article->doEdit($content, $edit_summary, EDIT_MINOR); } else { $this->log($row->page_title . ' already has article state template. Skipping.'); } } } }
/** * Get a diff between the current contents of the edit box and the * version of the page we're editing from. * * If this is a section edit, we'll replace the section as for final * save and then make a comparison. */ function showDiff() { $oldtext = $this->mArticle->fetchContent(); $newtext = $this->mArticle->replaceSection($this->section, $this->textbox1, $this->summary, $this->edittime); wfRunHooks('EditPageGetDiffText', array($this, &$newtext)); $newtext = $this->mArticle->preSaveTransform($newtext); $oldtitle = wfMsgExt('currentrev', array('parseinline')); $newtitle = wfMsgExt('yourtext', array('parseinline')); if ($oldtext !== false || $newtext != '') { $de = new DifferenceEngine($this->mTitle); $de->setText($oldtext, $newtext); $difftext = $de->getDiff($oldtitle, $newtitle); $de->showDiffStyle(); } else { $difftext = ''; } global $wgOut; $wgOut->addHTML('<div id="wikiDiff">' . $difftext . '</div>'); }
function convert($source, $target, $startdate) { $date = getdate(strtotime($startdate)); $month = $date['mon']; $day = $date['mday']; $year = $date['year']; //$date = "$month-$day-$year"; $search = $source; $pages = PrefixSearch::titleSearch($search, '10000'); $count = 0; foreach ($pages as $page) { $article = new Article(Title::newFromText($page)); $title = $article->getTitle()->getText(); $body = $article->fetchContent(0, false, false); $titles .= $this->create_event($title, $body, $target); $count++; } return $titles; //return "$count records converted!"; }
/** * Take a bit of WikiText that looks like * <rss max=5>http://example.com/</rss> * and return an object that can produce rendered output. */ function __construct($url, $args) { $this->url = $url; # Get max number of headlines from argument-array if (isset($args['max'])) { $this->maxheads = $args['max']; } # Get reverse flag from argument array if (isset($args['reverse'])) { $this->reversed = true; } # Get date format from argument array # FIXME: not used yet if (isset($args['date'])) { $this->date = $args['date']; } # Get highlight terms from argument array if (isset($args['highlight'])) { # mapping to lowercase here so the regex can be case insensitive below. $this->highlight = self::explodeOnSpaces($args['highlight']); } # Get filter terms from argument array if (isset($args['filter'])) { $this->filter = self::explodeOnSpaces($args['filter']); } if (isset($args['filterout'])) { $this->filterOut = self::explodeOnSpaces($args['filterout']); } if (isset($args['template'])) { $titleObject = Title::newFromText($args['template'], NS_TEMPLATE); $article = new Article($titleObject, 0); $this->itemTemplate = $article->fetchContent(); } else { $templateName = isset($args['templatename']) ? $args['templatename'] : 'RSSPost'; $this->itemTemplate = wfMsgNoTrans('rss-item', $templateName); } }
/** * Generate the form to be displayed at the top of the edit page and insert it. * @param $form EditPage object. * @return true */ function efMultiBoilerplate($form) { // Get various variables needed for this extension. global $wgMultiBoilerplateOptions, $wgMultiBoilerplateOverwrite, $wgTitle, $wgRequest; // If $wgMultiBoilerplateOverwrite is true then detect whether // the current page exists or not and if it does return true // to end execution of this function. if (!$wgMultiBoilerplateOverwrite && $wgTitle->exists($wgTitle->getArticleID())) { return true; } // Generate the options list used inside the boilerplate selection box. // If $wgMultiBoilerplateOptions is an array then use that, else fall back // to the MediaWiki:Multiboilerplate message. if (is_array($wgMultiBoilerplateOptions)) { $options = ''; foreach ($wgMultiBoilerplateOptions as $name => $template) { $selected = false; if ($wgRequest->getVal('boilerplate') == $template) { $selected = true; } $options .= Xml::option($name, $template, $selected); } } else { $things = wfMsgForContent('multiboilerplate'); $options = ''; $things = explode("\n", str_replace("\r", "\n", str_replace("\r\n", "\n", $things))); // Ensure line-endings are \n foreach ($things as $row) { if (substr(ltrim($row), 0, 1) === "*") { $row = ltrim($row, '* '); // Remove the asterix (and a space if found) from the start of the line. $row = explode('|', $row); if (!isset($row[1])) { return true; } // Invalid syntax, abort. $selected = false; if ($wgRequest->getVal('boilerplate') == $row[1]) { $selected = true; } $options .= Xml::option($row[0], $row[1], $selected); } } } // No options found in either configuration file, abort. if ($options == '') { return true; } // Append the selection form to the top of the edit page. $form->editFormPageTop .= Xml::openElement('form', array('id' => 'multiboilerplateform', 'name' => 'multiboilerplateform', 'method' => 'get', 'action' => $wgTitle->getEditURL())) . Xml::openElement('fieldset') . Xml::element('legend', null, wfMsg('multiboilerplate-legend')) . Xml::openElement('label') . wfMsg('multiboilerplate-label') . Xml::openElement('select', array('name' => 'boilerplate')) . $options . Xml::closeElement('select') . Xml::closeElement('label') . ' ' . Html::Hidden('action', 'edit') . Html::Hidden('title', $wgRequest->getText('title')) . Xml::submitButton(wfMsg('multiboilerplate-submit')) . Xml::closeElement('fieldset') . Xml::closeElement('form'); // If the Load button has been pushed replace the article text with the boilerplate. if ($wgRequest->getText('boilerplate', false)) { $plate = new Article(Title::newFromURL($wgRequest->getVal('boilerplate'))); $content = $plate->fetchContent(); /* Strip out noinclude tags and contained data, and strip includeonly * tags (but retain contained data). If a function exists in the * parser exists to do this it would be nice to replace this with it (I * found one with a name as if it would do this, but it didn't seam to * work). */ $content = preg_replace('#<noinclude>(.*?)</noinclude>#ims', '', $content); $content = preg_replace('#<includeonly>(.*?)</includeonly>#ims', '$1', $content); // TODO: Handle <onlyinclude> tags. $form->textbox1 = $content; } // Return true so things don't break. return true; }
function execute($param) { global $wgOut, $wgRequest, $wgTitle, $wgUser, $wgMessageCache; $this->setHeaders(); $title = Title::makeTitle(NS_SPECIAL, 'EasyGallery'); $par = 8; # The $param is the number of text inputs to be replicated in the form if (isset($param)) { $par = $param; } else { if ($wgRequest->getText('wpParam', "")) { $par = $wgRequest->getText('wpParam', ""); } else { $par = 8; } } # Extract any posted data $posted = $wgRequest->getText('wpSubmit', false); # Extract any contents of fields $gtitle = $wgRequest->getText('wpGtitle', ""); $width = $wgRequest->getText('wpWidth', ""); $column = $wgRequest->getText('wpColumn', ""); # Render the form $wgOut->addWikiText(wfMsg('easygalleryMessage', 'easygalleryParameter')); $wgOut->addHTML(wfElement('form', array('action' => $title->getLocalURL('action=submit'), 'method' => 'post'), null) . "<br /><p><b>Usage</b></p>\n\t\t<p>This form creates a gallery in the page you enter below, whether the page exists or not.</p>\n\t\t<p>If there is already text in the page it will be retained but an existing gallery will be replaced by this one. You can have one gallery per page.</p>\n\t\t<p>This extension defaults to 8 pictures (plus captions), unless the number of pictures in your intended gallery is added to the address bar title, for example for five images:\n\t\thttp://localhost/wiki/index.php/Special:EasyGallery/5</p>\n\t\t<p>Here is the expected form of the picture and the caption:\n\t\tImage:Example.jpg\n Example Caption</p>\n\t\t<p>You can upload your pictures by clicking <a href='" . $wgServer . $wgScript . "/Special:Upload' target='_blank'>Special:Upload</a>.</p>\n\t\t<p>You can access the names of images already uploaded by clicking <a href='" . $wgServer . $wgScript . "/Special:ImageList' target='_blank'>Special:ImageList</a>.</p>\n\t\t<p>Press the Submit Query button, then you can go to the page and edit it normally if you want.</p>\n\t\t<br/ >\n\t\t<p><b>Page Setup</b></p>\n\t\t<p>What is the title of the page your gallery will be in? This is a compulsory field.</p>\n\t\t<input name='wpGtitle' size = '35' />\n\t\t<p>How many columns do you want the easygallery to have? If you leave the field empty it is 2.</p>\n\t\t<input name='wpColumn' size = '10' />\n\t\t<p>How wide do you want each thumbnail to be (in pixels)? Empty field is 150.</p>\n\t\t<input name='wpWidth' size = '10' />\n\t\t<input type='hidden' name='wpParam' value={$par}><br /><br />"); # Render multiple inputs using the /$par from the url for ($ctr = 1; $ctr <= $par; $ctr++) { $wgOut->addHTML("<p><b>Gallery " . $ctr . "</b></p>\n\t\t\t<p>The image you want for the thumbnail.</p>\n\t\t\t<input name='wpUrl" . $ctr . "' size = '50' />\n\t\t\t<p>The caption for this image.</p>\n\t\t\t<input name='wpCaption" . $ctr . "' size = '50' />"); } # Post $wgOut->addHTML("<br /><br />" . wfElement('input', array('name' => 'wpSubmit', 'type' => 'submit')) . "<br /><br />"); # Process results if data posted if ($posted) { # Defaults for posted style elements if ($width == "") { $width = 200; } if ($column == "") { $column = 2; } # Build tag $tag = "<\ngallery widths='" . $width . "px' perrow='" . $column . "'>\n"; # Some arrays to populate with loops $url[] = array(); $caption[] = array(); # Make some variables out of the posted fields for ($n = 1; $n <= $par; $n++) { $url[$n] = $wgRequest->getText('wpUrl' . $n, ""); $caption[$n] = $wgRequest->getText('wpCaption' . $n, ""); } for ($n = 1; $n <= $par; $n++) { if ($url[$n] != "") { $tag .= $url[$n] . "|<center>" . $caption[$n] . "</center>\n"; } } $tag .= "</gallery>"; if ($wgUser->isAllowed('edit')) { $title = Title::newFromText($gtitle); if (trim($wgRequest->getText('wpGtitle')) == '') { $wgTitle = Title::newFromText(wfMsgForContent('badtitle')); $wgOut->errorpage('badtitle', 'badtitletext'); } # Make the new page if no page exists. if (isset($title) && $title->getArticleID() == 0) { $article = new Article($title); $article->doEdit($tag, "", EDIT_NEW); $wgOut->addHTML(wfMsg('easygallerySuccessMessage')); } elseif (isset($title) && $title->getArticleID() != 0) { $article = new Article($title, 0); $original = $article->fetchContent(0); $intro = preg_replace("%<gallery.*%is", "", $original); $outro = preg_replace("%.*</gallery>%is", "", $original); $tag = $intro . $tag . $outro; $article->doEdit($tag, "", EDIT_UPDATE); $wgOut->addHTML(wfMsg('easygallerySuccessMessage')); } else { $wgTitle = Title::newFromText(wfMsgForContent('badtitle')); $wgOut->errorpage('error', 'badtitletext'); } } else { $wgTitle = Title::newFromText(wfMsgForContent('badtitle')); $wgOut->errorpage('error', 'badarticleerror'); } } }
public function doMerge() { global $wgOut, $wgUser; $skin =& $wgUser->getSkin(); if ($this->isGedcom()) { $editFlags = EDIT_UPDATE; $mergeText = 'updated'; } else { // create a mergelog record $mergeScore = $this->getMergeScore(); $isTrustedUser = CompareForm::isTrustedMerger($wgUser, false); $isTrustedMerge = MergeForm::isTrustedMerge($mergeScore, $isTrustedUser); $mergeLogId = $this->logMerge($mergeScore, $isTrustedMerge); wfDebug("MERGESCORE mergeLogId={$mergeLogId} total score={$mergeScore}\n"); if (!$isTrustedUser && $mergeScore < self::$LOW_MATCH_THRESHOLD) { error_log("WARNING suspect merge: id={$mergeLogId} user={$wgUser->getName()} score={$mergeScore}"); } $editFlags = EDIT_UPDATE | EDIT_FORCE_BOT; $mergeText = 'merged'; } // get merging people and families // add merging people and families to blacklist so propagation doesn't also try to update them $mergingPeople = array(); $mergingFamilies = array(); for ($m = 0; $m < count($this->data); $m++) { for ($p = 0; $p < count($this->data[$m]); $p++) { $titleString = $this->data[$m][$p]['title']; if ($this->namespace == 'Family' && $m == 0) { if ($p > 0) { $mergingFamilies[$titleString] = $this->data[$m][0]['title']; } $ns = NS_FAMILY; } else { if ($p > 0) { $mergingPeople[$titleString] = $this->data[$m][0]['title']; } $ns = NS_PERSON; } if (!GedcomUtil::isGedcomTitle($titleString)) { $title = Title::newFromText($titleString, $ns); PropagationManager::addBlacklistPage($title); } } } $output = "<H2>Pages {$mergeText} successfully</H2>"; $output .= $this->getWarnings(); $output .= '<ul>'; $outputRows = array(); $emptyRequest = new FauxRequest(array(), true); $mergeCmtSuffix = $this->isGedcom() ? '' : " - [[Special:ReviewMerge/{$mergeLogId}|review/undo]]"; if ($this->namespace == 'Family' && !$this->isGedcom()) { $t = Title::newFromText($this->data[0][0]['title'], NS_FAMILY); $mergeCmtFamily = $this->namespace == 'Family' ? " in merge of [[{$t->getPrefixedText()}]]" : ''; } else { $mergeCmtFamily = ''; } // backwards, because you must merge family last, so that propagated person data in family xml is correct // and so that mergeCmtFamily can be cleared at the end and mergeSummary and mergeTargetTitle are correct after the for loop for ($m = count($this->data) - 1; $m >= 0; $m--) { $requestData = array(); $contents = ''; $talkContents = ''; $outputRow = ''; $mainOutput = ''; $talkOutput = ''; $nameCount = $eventCount = $sourceCount = $imageCount = $noteCount = $husbandCount = $wifeCount = $childrenCount = $parentFamilyCount = $spouseFamilyCount = 0; $primaryNameFound = $primaryImageFound = $birthFound = $christeningFound = $deathFound = $burialFound = $marriageFound = false; if ($this->namespace == 'Family' && $m == 0) { $mergeTargetNs = NS_FAMILY; $mergeTargetTalkNs = NS_FAMILY_TALK; $mergeCmtFamily = ''; } else { $mergeTargetNs = NS_PERSON; $mergeTargetTalkNs = NS_PERSON_TALK; } $mergeTargetTitle = Title::newFromText($this->data[$m][0]['title'], $mergeTargetNs); if ($mergeTargetTitle->getNamespace() != $mergeTargetNs) { error_log("Merge glitch:{$mergeTargetNs}:{$this->data[$m][0]['title']}:{$mergeTargetTitle->getNamespace()}:"); } $mergeTargetTalkTitle = Title::newFromText($this->data[$m][0]['title'], $mergeTargetTalkNs); $mergeSummary = ''; $talkMergeSummary = ''; $keepKeys = $this->generateKeepKeys($this->data[$m], $this->add[$m], $this->key[$m]); $notesMap = array(); $noteAdoptions = array(); $this->generateMapAdoptions('notes', 'N', $mergeTargetNs, $this->data[$m], $this->add[$m], $this->key[$m], $keepKeys, $notesMap, $noteAdoptions); $sourcesMap = array(); $sourceAdoptions = array(); $this->generateMapAdoptions('sources', 'S', $mergeTargetNs, $this->data[$m], $this->add[$m], $this->key[$m], $keepKeys, $sourcesMap, $sourceAdoptions); $imagesMap = array(); $imageAdoptions = array(); $this->generateMapAdoptions('images', 'I', $mergeTargetNs, $this->data[$m], $this->add[$m], $this->key[$m], $keepKeys, $imagesMap, $imageAdoptions); // get request data for merge target for ($p = 0; $p < count($this->data[$m]); $p++) { if ($this->isMergeable($this->data[$m][$p])) { $this->addNotesToRequestData($requestData, $keepKeys[$p], $noteCount, $notesMap[$p], $this->data[$m][$p]['notes']); $this->addImagesToRequestData($requestData, $keepKeys[$p], $imageCount, $imagesMap[$p], $primaryImageFound, $this->data[$m][$p]['images']); $this->addSourcesToRequestData($requestData, $keepKeys[$p], $sourceCount, $sourcesMap[$p], $notesMap[$p], $imagesMap[$p], $this->data[$m][$p]['sources'], $noteAdoptions, $imageAdoptions); $this->addEventsToRequestData($requestData, $keepKeys[$p], $eventCount, $mergeTargetNs == NS_PERSON ? Person::$STD_EVENT_TYPES : Family::$STD_EVENT_TYPES, $birthFound, $christeningFound, $deathFound, $burialFound, $marriageFound, $notesMap[$p], $imagesMap[$p], $sourcesMap[$p], $this->data[$m][$p]['events'], $noteAdoptions, $sourceAdoptions, $imageAdoptions); if ($mergeTargetNs == NS_PERSON) { $this->addNamesToRequestData($requestData, $keepKeys[$p], $nameCount, $primaryNameFound, $notesMap[$p], $sourcesMap[$p], $this->data[$m][$p]['names'], $noteAdoptions, $sourceAdoptions); $this->addFamilyToRequestData($requestData, $mergingFamilies, 'child_of_family', $parentFamilyCount, $this->data[$m][$p]['child_of_families']); $this->addFamilyToRequestData($requestData, $mergingFamilies, 'spouse_of_family', $spouseFamilyCount, $this->data[$m][$p]['spouse_of_families']); } else { $this->addFamilyMembersToRequestData($requestData, $mergingPeople, 'husband', $husbandCount, $this->data[$m][$p]['husbands']); $this->addFamilyMembersToRequestData($requestData, $mergingPeople, 'wife', $wifeCount, $this->data[$m][$p]['wives']); $this->addFamilyMembersToRequestData($requestData, $mergingPeople, 'child', $childrenCount, $this->data[$m][$p]['children']); } $pageContents = $this->mapContents($sourcesMap[$p], $imagesMap[$p], $notesMap[$p], $this->data[$m][$p]['contents']); $this->addContents($contents, $keepKeys[$p], $pageContents); if ($p > 0) { if ($mergeSummary) { $mergeSummary .= ', '; } if ($mainOutput) { $mainOutput .= ', '; } if ($this->data[$m][$p]['gedcom']) { $mergeSummary .= 'gedcom'; $mainOutput .= htmlspecialchars(($mergeTargetNs == NS_FAMILY ? 'Family:' : 'Person:') . $this->data[$m][$p]['title']); } else { $title = Title::newFromText($this->data[$m][$p]['title'], $mergeTargetNs); $mergeSummary .= "[[" . $title->getPrefixedText() . "]]"; $mainOutput .= $skin->makeKnownLinkObj($title, htmlspecialchars($title->getPrefixedText()), 'redirect=no'); } } } } // redirect other pages to merge target $redir = "#REDIRECT [[" . $mergeTargetTitle->getPrefixedText() . "]]"; $talkRedir = "#REDIRECT [[" . $mergeTargetTalkTitle->getPrefixedText() . "]]"; for ($p = 1; $p < count($this->data[$m]); $p++) { if (!$this->data[$m][$p]['gedcom']) { $obj = $this->data[$m][$p]['object']; $comment = $this->makeComment($this->userComment, "merge into [[" . $mergeTargetTitle->getPrefixedText() . "]]" . $mergeCmtFamily, $mergeCmtSuffix); $obj->editPage($emptyRequest, $redir, $comment, $editFlags, false); // redir talk page as well if ($this->data[$m][$p]['talkrevid']) { // if talk page exists $talkTitle = Title::newFromText($this->data[$m][$p]['title'], $mergeTargetTalkNs); $article = new Article($talkTitle, 0); if ($article) { $this->addTalkContents($talkContents, $talkTitle, $article->fetchContent()); if ($talkMergeSummary) { $talkMergeSummary .= ', '; } if ($talkOutput) { $talkOutput .= ', '; } $talkMergeSummary .= "[[" . $talkTitle->getPrefixedText() . "]]"; $talkOutput .= $skin->makeKnownLinkObj($talkTitle, htmlspecialchars($talkTitle->getPrefixedText()), 'redirect=no'); $comment = $this->makeComment($this->userComment, "merge into [[" . $mergeTargetTalkTitle->getPrefixedText() . "]]" . $mergeCmtFamily, $mergeCmtSuffix); $article->doEdit($talkRedir, $comment, $editFlags); } } } } // update merge target talk if ($talkContents) { $article = new Article($mergeTargetTalkTitle, 0); if ($article) { $mergeTargetTalkContents = $article->fetchContent(); if ($mergeTargetTalkContents) { $mergeTargetTalkContents = rtrim($mergeTargetTalkContents) . "\n\n"; } $comment = $this->makeComment($this->userComment, 'merged with ' . $talkMergeSummary . $mergeCmtFamily, $mergeCmtSuffix); $article->doEdit($mergeTargetTalkContents . $talkContents, $comment, $editFlags); if ($this->addWatches) { StructuredData::addWatch($wgUser, $article, true); } } $outputRow .= '<li>Merged ' . $talkOutput . ' into ' . $skin->makeKnownLinkObj($mergeTargetTalkTitle, htmlspecialchars($mergeTargetTalkTitle->getPrefixedText())) . "</li>"; } $obj = $this->data[$m][0]['object']; if ($mergeTargetNs == NS_PERSON) { Person::addGenderToRequestData($requestData, $this->data[$m][0]['gender']); } else { // family $obj->isMerging(true); // to read propagated data from person pages, not from prev family revision } // update merge target $req = new FauxRequest($requestData, true); $comment = $this->makeComment($this->userComment, ($mergeSummary == 'gedcom' ? 'Add data from gedcom' : 'merged with ' . $mergeSummary) . $mergeCmtFamily, $mergeCmtSuffix); $obj->editPage($req, $contents, $comment, $editFlags, $this->addWatches); $outputRow .= '<li>Merged ' . $mainOutput . ' into ' . $skin->makeKnownLinkObj($mergeTargetTitle, htmlspecialchars($mergeTargetTitle->getPrefixedText())) . "</li>"; $outputRows[] = $outputRow; } // add log and recent changes if (!$this->isGedcom()) { if (!$mergeSummary) { $mergeSummary = 'members of other families'; } $mergeComment = 'Merge [[' . $mergeTargetTitle->getPrefixedText() . ']] and ' . $mergeSummary; $log = new LogPage('merge', false); $t = Title::makeTitle(NS_SPECIAL, "ReviewMerge/{$mergeLogId}"); $log->addEntry('merge', $t, $mergeComment); RecentChange::notifyLog(wfTimestampNow(), $t, $wgUser, $mergeComment, '', 'merge', 'merge', $t->getPrefixedText(), $mergeComment, '', $isTrustedMerge, 0); } $nonmergedPages = $this->getNonmergedPages(); $output .= join("\n", array_reverse($outputRows)) . '</ul>' . ($nonmergedPages ? '<p>In addition to the people listed above, the following have also been included in the target family' . ($this->isGedcom() ? '<br/>(GEDCOM people listed will be added when the GEDCOM is imported)' : '') . $nonmergedPages . "</p>\n" : '') . ($this->isGedcom() ? '' : '<p>' . $skin->makeKnownLinkObj(Title::makeTitle(NS_SPECIAL, 'ReviewMerge/' . $mergeLogId), htmlspecialchars("Review/undo merge")) . '<br>' . $skin->makeKnownLinkObj(Title::makeTitle(NS_SPECIAL, 'ShowDuplicates'), htmlspecialchars("Show more duplicates")) . '</p>'); return $output; }
/** * Template filter callback for MonoBook skin. * Takes an associative array of data set from a SkinTemplate-based * class, and a wrapper for MediaWiki's localization database, and * outputs a formatted page. * * @access private */ function execute() { global $wgRequest; $this->skin = $skin = $this->data['skin']; $action = $wgRequest->getText('action'); // Suppress warnings to prevent notices about missing indexes in $this->data wfSuppressWarnings(); $this->html('headelement'); ?> <body<?php if ($this->data['body_ondblclick']) { ?> ondblclick="<?php $this->text('body_ondblclick'); ?> "<?php } if ($this->data['body_onload']) { ?> onload="<?php $this->text('body_onload'); ?> "<?php } ?> class="mediawiki <?php $this->text('nsclass'); ?> <?php $this->text('dir'); ?> <?php $this->text('pageclass'); ?> "> <div id="globalWrapper"> <div id="p-cactions" class="portlet"> <h5><?php $this->msg('views'); ?> </h5> <div class="pBody"> <ul> <?php foreach ($this->data['content_actions'] as $key => $tab) { echo ' <li id="ca-' . Sanitizer::escapeId($key) . '"'; if ($tab['class']) { echo ' class="' . htmlspecialchars($tab['class']) . '"'; } echo '><a href="' . htmlspecialchars($tab['href']) . '"'; # We don't want to give the watch tab an accesskey if the # page is being edited, because that conflicts with the # accesskey on the watch checkbox. We also don't want to # give the edit tab an accesskey, because that's fairly su- # perfluous and conflicts with an accesskey (Ctrl-E) often # used for editing in Safari. if (in_array($action, array('edit', 'submit')) && in_array($key, array('edit', 'watch', 'unwatch'))) { echo $skin->tooltip("ca-{$key}"); } else { echo $skin->tooltipAndAccesskey("ca-{$key}"); } echo '>' . htmlspecialchars($tab['text']) . '</a></li>'; } ?> </ul> </div> </div> <?php $this->searchBox(); ?> <div class="portlet" id="p-personal"> <h5><?php $this->msg('personaltools'); ?> </h5> <div class="pBody"> <ul> <?php foreach ($this->data['personal_urls'] as $key => $item) { ?> <li id="pt-<?php echo Sanitizer::escapeId($key); ?> "<?php if ($item['active']) { ?> class="active"<?php } ?> ><a href="<?php echo htmlspecialchars($item['href']); ?> "<?php echo $skin->tooltipAndAccesskey('pt-' . $key); if (!empty($item['class'])) { ?> class="<?php echo htmlspecialchars($item['class']); ?> "<?php } ?> ><?php echo htmlspecialchars($item['text']); ?> </a></li> <?php } ?> </ul> </div> </div> <div class="portlet" id="p-logo"> <a style="background-image: url(<?php $this->text('logopath'); ?> );" <?php ?> href="<?php echo htmlspecialchars($this->data['nav_urls']['mainpage']['href']); ?> "<?php echo $skin->tooltipAndAccesskey('n-mainpage'); ?> ></a> </div> <table id="column-content" width="!00%" cellpadding="0" cellspacing="0"> <tr> <td colspan="2"> <div id="top-div" /> </td> <tr> <td id="column-one"> <script type="<?php $this->text('jsmimetype'); ?> "> if (window.isMSIE55) fixalpha(); </script> <?php # MediaWiki:Sidebar global $wgUser, $wgTitle, $wgParser; $title = 'sidebar'; $article = new Article(Title::newFromText($title, NS_MEDIAWIKI)); $text = $article->fetchContent(); if (empty($text)) { $text = wfMsg($title); } if (is_object($wgParser)) { $psr = $wgParser; $opt = $wgParser->mOptions; } else { $psr = new Parser(); $opt = NULL; } if (!is_object($opt)) { $opt = ParserOptions::newFromUser($wgUser); } echo $psr->parse($text, $wgTitle, $opt, true, true)->getText(); ?> </td><!-- end of the left (by default at least) column --> <td id="content" width="100%"> <a name="top" id="top"></a> <?php if ($this->data['sitenotice']) { ?> <div id="siteNotice"><?php $this->html('sitenotice'); ?> </div><?php } ?> <h1 class="firstHeading"><?php $this->html('title'); ?> </h1> <div id="bodyContent"> <h3 id="siteSub"><?php $this->msg('tagline'); ?> </h3> <div id="contentSub"><?php $this->html('subtitle'); ?> </div> <?php if ($this->data['undelete']) { ?> <div id="contentSub2"><?php $this->html('undelete'); ?> </div><?php } ?> <?php if ($this->data['newtalk']) { ?> <div class="usermessage"><?php $this->html('newtalk'); ?> </div><?php } ?> <?php if ($this->data['showjumplinks']) { ?> <div id="jump-to-nav"><?php $this->msg('jumpto'); ?> <a href="#column-one"><?php $this->msg('jumptonavigation'); ?> </a>, <a href="#searchInput"><?php $this->msg('jumptosearch'); ?> </a></div><?php } ?> <!-- start content --> <?php $this->html('bodytext'); ?> <?php if ($this->data['catlinks']) { $this->html('catlinks'); } ?> <!-- end content --> <div class="visualClear"></div> </div> </div> </td> </tr> </table> <div class="visualClear"></div> <div id="footer"> <?php global $wgUser, $wgTitle, $wgParser; $title = 'footer'; $article = new Article(Title::newFromText($title, NS_MEDIAWIKI)); $text = $article->fetchContent(); if (empty($text)) { $text = wfMsg($title); } if (is_object($wgParser)) { $psr = $wgParser; $opt = $wgParser->mOptions; } else { $psr = new Parser(); $opt = NULL; } if (!is_object($opt)) { $opt = ParserOptions::newFromUser($wgUser); } echo $psr->parse($text, $wgTitle, $opt, true, true)->getText(); ?> </div> </div> <?php $this->html('bottomscripts'); /* JS call to runBodyOnloadHook */ $this->html('reporttime'); if ($this->data['debug']) { ?> <!-- Debug output: <?php $this->text('debug'); ?> --> <?php } ?> </body></html> <?php wfRestoreWarnings(); }
static function getAvatarRaw($name) { $u = User::newFromName($name); if (!$u) { return array('type' => 'df', 'url' => ''); } $u->load(); $dbr = wfGetDB(DB_SLAVE); // check for facebook if ($u->isFacebookUser()) { $row = $dbr->selectRow('avatar', array('av_image', 'av_patrol'), array('av_user' => $u->getID()), __METHOD__); if ($row->av_image && ($row->av_patrol == 0 || $row->av_patrol == 1)) { return array('type' => 'fb', 'url' => $row->av_image); } } //check for Google+ if ($u->isGPlusUser()) { $row = $dbr->selectRow('avatar', array('av_image', 'av_patrol'), array('av_user' => $u->getID()), __METHOD__); if ($row->av_image && ($row->av_patrol == 0 || $row->av_patrol == 1)) { return array('type' => 'gp', 'url' => $row->av_image); } } //checks for redirects for users that go that route //rather than just changing the username $up = $u->getUserPage(); $a = new Article($up, 0); //need to put 0 as the oldID b/c Article gets the old id out of the URL if ($a->isRedirect()) { $t = Title::newFromRedirect($a->fetchContent()); if (!($u = User::newFromName($t->getText()))) { return array('type' => 'df', 'url' => ''); } } $row = $dbr->selectRow('avatar', array('av_dateAdded'), array('av_user' => $u->getID(), 'av_patrol' => 0), __METHOD__); $filename = $u->getID() . ".jpg"; $cropout = self::getAvatarOutFilePath($filename) . $filename; if ($row && $row->av_dateAdded) { return array('type' => 'av', 'url' => "{$filename}?" . $row->av_dateAdded); } return array('type' => 'df', 'url' => ''); }
/** * Propagate an article rollback * Sets xml property and calls the abstract function propagateRollbackData($title) * @param Article $article contains text being replaced * @return bool true if propagate succeeded */ public function propagateRollback($article) { global $wgUser, $wrBotUserID; $result = true; // we do propagate bot edits // if ($wgUser->getID() != $wrBotUserID) { $title = $article->getTitle(); $oldText =& $article->fetchContent(); // $article contains the text being replaced; $rollbackRevision contains the new text $rollbackRevision = StructuredData::getRevision($title, false, true); $text =& $rollbackRevision->getText(); $this->xml = StructuredData::getXml($this->tagName, $text); $textChanged = false; $result = $this->propagateEditData($oldText, $text, $textChanged); if ($result && $textChanged) { PropagationManager::enablePropagation(false); $result = $article->doEdit($text, self::PROPAGATE_MESSAGE, PROPAGATE_EDIT_FLAGS); PropagationManager::enablePropagation(true); } // } return $result; }
function updateRecurrence($page, $rrule, $event, $summary, $overwrite = false) { $article = new Article(Title::newFromText($page)); $bExists = $article->exists(); $ret = 0; $rrule = trim($rrule); if ($bExists) { if ($overwrite) { $article->doEdit("{$rrule}", $summary, EDIT_UPDATE); $ret = 1; } else { $body = trim($article->fetchContent(0, false, false)); if (stripos($body, $rrule) === false) { // lets not re-add duplicate rrule lines $article->doEdit("{$body}\n" . "{$rrule}", $summary, EDIT_UPDATE); $ret = 1; } } } else { $article->doEdit("{$event}", $summary, EDIT_NEW); $ret = 1; } return $ret; }
/** * Query for RisingStars Written **/ function getRisingStar($starttimestamp, $lb_user = '', $getArticles = false) { global $wgMemc; if ($getArticles) { $key = "leaderboard:risingstars_received:{$starttimestamp}:{$lb_user}"; } else { $key = "leaderboard:risingstars_received:{$starttimestamp}"; } $cachekey = wfMemcKey($key); $val = $wgMemc->get($cachekey); if (is_array($val)) { return $val; } $dbr = wfGetDB(DB_SLAVE); $data = array(); $bots = WikihowUser::getBotIDs(); $bot = ""; if (sizeof($bots) > 0) { $bot = " AND rc_user NOT IN (" . $dbr->makeList($bots) . ") "; } $sql = "SELECT distinct(rc_title) " . "FROM recentchanges " . "WHERE rc_timestamp >= '{$starttimestamp}' AND rc_comment like 'Marking new article as a Rising Star from From%' " . $bot . "AND rc_namespace=" . NS_TALK . " "; $res = $dbr->query($sql, __METHOD__); foreach ($res as $row) { $t = Title::newFromText($row->rc_title); $a = new Article($t); if ($a->isRedirect()) { $t = Title::newFromRedirect($a->fetchContent()); $a = new Article($t); } $author = $a->getContributors()->current(); $username = $author ? $author->getName() : ''; if ($getArticles) { if ($lb_user == $username) { $data[$t->getPartialURL()] = $t->getPrefixedText(); } } else { $data[$username]++; } } $wgMemc->set($cachekey, $data, 3600); return $data; }
/** * Run a replaceText job * @return boolean success */ function run() { wfProfileIn( __METHOD__ ); if ( is_null( $this->title ) ) { $this->error = "replaceText: Invalid title"; wfProfileOut( __METHOD__ ); return false; } if ( array_key_exists( 'move_page', $this->params ) ) { global $wgUser; $actual_user = $wgUser; $wgUser = User::newFromId( $this->params['user_id'] ); $cur_page_name = $this->title->getText(); if ( $this->params['use_regex'] ) { $new_page_name = preg_replace( "/".$this->params['target_str']."/U", $this->params['replacement_str'], $cur_page_name ); } else { $new_page_name = str_replace( $this->params['target_str'], $this->params['replacement_str'], $cur_page_name ); } $new_title = Title::newFromText( $new_page_name, $this->title->getNamespace() ); $reason = $this->params['edit_summary']; $create_redirect = $this->params['create_redirect']; $this->title->moveTo( $new_title, true, $reason, $create_redirect ); if ( $this->params['watch_page'] ) { if ( class_exists( 'WatchAction' ) ) { // Class was added in MW 1.19 WatchAction::doWatch( $new_title, $wgUser ); } elseif ( class_exists( 'Action' ) ) { // Class was added in MW 1.18 Action::factory( 'watch', new Article( $new_title, 0 ) )->execute(); } else { $article = new Article( $new_title, 0 ); $article->doWatch(); } } $wgUser = $actual_user; } else { $article = new Article( $this->title, 0 ); if ( !$article ) { $this->error = 'replaceText: Article not found "' . $this->title->getPrefixedDBkey() . '"'; wfProfileOut( __METHOD__ ); return false; } wfProfileIn( __METHOD__ . '-replace' ); $article_text = $article->fetchContent(); $target_str = $this->params['target_str']; $replacement_str = $this->params['replacement_str']; $num_matches; if ( $this->params['use_regex'] ) { $new_text = preg_replace( '/'.$target_str.'/U', $replacement_str, $article_text, -1, $num_matches ); } else { $new_text = str_replace( $target_str, $replacement_str, $article_text, $num_matches ); } // if there's at least one replacement, modify the page, // using the passed-in edit summary if ( $num_matches > 0 ) { // change global $wgUser variable to the one // specified by the job only for the extent of // this replacement global $wgUser; $actual_user = $wgUser; $wgUser = User::newFromId( $this->params['user_id'] ); $edit_summary = $this->params['edit_summary']; $flags = EDIT_MINOR; if ( $wgUser->isAllowed( 'bot' ) ) $flags |= EDIT_FORCE_BOT; $article->doEdit( $new_text, $edit_summary, $flags ); $wgUser = $actual_user; } wfProfileOut( __METHOD__ . '-replace' ); } wfProfileOut( __METHOD__ ); return true; }
/** * Save categories sent via AJAX into article */ public function save() { wfProfileIn(__METHOD__); $articleId = $this->request->getVal('articleId', 0); $categories = $this->request->getVal('categories', array()); $response = array(); $title = Title::newFromID($articleId); if (wfReadOnly()) { $response['error'] = wfMessage('categoryselect-error-db-locked')->text(); } else { if (is_null($title)) { $response['error'] = wfMessage('categoryselect-error-article-doesnt-exist', $articleId)->text(); } else { if (!$title->userCan('edit') || $this->wg->User->isBlocked()) { $response['error'] = wfMessage('categoryselect-error-user-rights')->text(); } else { if (!empty($categories) && is_array($categories)) { Wikia::setVar('EditFromViewMode', 'CategorySelect'); $article = new Article($title); $wikitext = $article->fetchContent(); // Pull in categories from templates inside of the article (BugId:100980) $options = new ParserOptions(); $preprocessedWikitext = ParserPool::preprocess($wikitext, $title, $options); $preprocessedData = CategoryHelper::extractCategoriesFromWikitext($preprocessedWikitext, true); // Compare the new categories with those already in the article to weed out duplicates $newCategories = CategoryHelper::getDiffCategories($preprocessedData['categories'], $categories); // Append the new categories to the end of the article wikitext $wikitext .= CategoryHelper::changeFormat($newCategories, 'array', 'wikitext'); // Update the array of categories for the front-end $categories = array_merge($preprocessedData['categories'], $newCategories); $dbw = wfGetDB(DB_MASTER); $dbw->begin(); $editPage = new EditPage($article); $editPage->edittime = $article->getTimestamp(); $editPage->recreate = true; $editPage->textbox1 = $wikitext; $editPage->summary = wfMessage('categoryselect-edit-summary')->inContentLanguage()->text(); $editPage->watchthis = $editPage->mTitle->userIsWatching(); $bot = $this->wg->User->isAllowed('bot'); $status = $editPage->internalAttemptSave($result, $bot)->value; $response['status'] = $status; switch ($status) { case EditPage::AS_SUCCESS_UPDATE: case EditPage::AS_SUCCESS_NEW_ARTICLE: $dbw->commit(); $title->invalidateCache(); Article::onArticleEdit($title); $response['html'] = $this->app->renderView('CategorySelectController', 'categories', array('categories' => $categories)); wfRunHooks('CategorySelectSave', array($title, $newCategories)); break; case EditPage::AS_SPAM_ERROR: $dbw->rollback(); $response['error'] = wfMessage('spamprotectiontext')->text() . '<p>( Case #8 )</p>'; break; default: $dbw->rollback(); $response['error'] = wfMessage('categoryselect-error-edit-abort')->text(); } } } } } $this->response->setData($response); wfProfileOut(__METHOD__); }
function UW_Layouts_preFillTextBox ( &$text, $title ) { global $wgRequest, $wgAddLayoutLink; /* fetch the layout from the query string, * or abort this hook if it is missing */ $layout_slug = $wgRequest->getVal ( "layout" ); if ( $layout_slug === null ) return true; // fetch the layout object $layout_title = Title::newFromURL ( "Layout:" . $layout_slug ); $layout_article = new Article ( $layout_title ); $layout_cats = ''; /* if the layout article exists, pre-fill the textarea with its * wiki text. if it doesn't exist, do nothing (no error) */ if ( ( $layout_text = $layout_article->fetchContent() ) !== false ) { $layout_text = UW_Layouts_stripCats($layout_text, $layout_cats); $text .= $layout_cats; /* break the layout text into sections by splitting * at header level =one= or ==two==, and iterate */ $nodes = preg_split ( "/^(==?[^=].*)$/mi", $layout_text, - 1, PREG_SPLIT_DELIM_CAPTURE ); for ( $i = 0; $i < count( $nodes ); $i++ ) { /* if the next node is OPTIONAL, then skip over it * (it will be included if using GenericEditor) */ if ( preg_match ( "/^@optional$/m", $nodes[$i + 1] ) ) { $i++; /* not an optional section, or * text that hasn't been skipped */ } else { // DO NOT copy over directives. remove them all! $text .= preg_replace ( "/^@.*/m", "", $nodes[$i] ); } } } if ( $wgAddLayoutLink && $layout_slug != 'none' ) $text .= "\n\n<layout name=\"$layout_slug\" />"; return true; }
<?php /** * @todo document * @addtogroup Maintenance */ /** */ require_once "commandLine.inc"; require_once "importLogs.inc"; #print $text; #exit(); foreach (LogPage::validTypes() as $type) { if ($type == '') { continue; } $page = LogPage::logName($type); $log = new Article(Title::makeTitleSafe(NS_PROJECT, $page)); $text = $log->fetchContent(); $importer = new LogImporter($type); $importer->dummy = true; $importer->importText($text); }
/** * Save categories sent via AJAX into article * * @author Maciej Błaszkowski <marooned at wikia-inc.com> */ function CategorySelectAjaxSaveCategories($articleId, $categories) { global $wgUser; if (wfReadOnly()) { $result['error'] = wfMsg('categoryselect-error-db-locked'); return json_encode($result); } wfProfileIn(__METHOD__); Wikia::setVar('EditFromViewMode', 'CategorySelect'); $categories = CategorySelectChangeFormat($categories, 'json', 'wiki'); if ($categories == '') { $result['info'] = 'Nothing to add.'; } else { $title = Title::newFromID($articleId); if (is_null($title)) { $result['error'] = wfMsg('categoryselect-error-not-exist', $articleId); } else { if ($title->userCan('edit') && !$wgUser->isBlocked()) { $result = null; $article = new Article($title); $article_text = $article->fetchContent(); $article_text .= $categories; $dbw = wfGetDB(DB_MASTER); $dbw->begin(); $editPage = new EditPage($article); $editPage->edittime = $article->getTimestamp(); $editPage->recreate = true; $editPage->textbox1 = $article_text; $editPage->summary = wfMsgForContent('categoryselect-edit-summary'); $editPage->watchthis = $editPage->mTitle->userIsWatching(); $bot = $wgUser->isAllowed('bot'); $status = $editPage->internalAttemptSave($result, $bot); $retval = $status->value; Wikia::log(__METHOD__, "editpage", "Returned value {$retval}"); switch ($retval) { case EditPage::AS_SUCCESS_UPDATE: case EditPage::AS_SUCCESS_NEW_ARTICLE: $dbw->commit(); $title->invalidateCache(); Article::onArticleEdit($title); $skin = RequestContext::getMain()->getSkin(); // return HTML with new categories // OutputPage::tryParserCache become deprecated in MW1.17 and removed in MW1.18 (BugId:30443) $parserOutput = ParserCache::singleton()->get($article, $article->getParserOptions()); if ($parserOutput !== false) { $skin->getOutput()->addParserOutput($parserOutput); } $cats = $skin->getCategoryLinks(); $result['info'] = 'ok'; $result['html'] = $cats; break; case EditPage::AS_SPAM_ERROR: $dbw->rollback(); $result['error'] = wfMsg('spamprotectiontext') . '<p>( Case #8 )</p>'; break; default: $dbw->rollback(); $result['error'] = wfMsg('categoryselect-edit-abort'); } } else { $result['error'] = wfMsg('categoryselect-error-user-rights'); } } } wfProfileOut(__METHOD__); return json_encode($result); }
/** * Perform the export operation */ public static function onUnknownAction($action, $article) { global $wgOut, $wgUser, $wgParser, $wgRequest; global $wgServer, $wgArticlePath, $wgScriptPath, $wgUploadPath, $wgUploadDirectory, $wgScript; if ($action == 'pdfbook') { $title = $article->getTitle(); $opt = ParserOptions::newFromUser($wgUser); // Log the export $msg = wfMsg('pdfbook-log', $wgUser->getUserPage()->getPrefixedText()); $log = new LogPage('pdf', false); $log->addEntry('book', $article->getTitle(), $msg); // Initialise PDF variables $format = $wgRequest->getText('format'); $notitle = $wgRequest->getText('notitle'); $layout = $format == 'single' ? '--webpage' : '--firstpage toc'; $charset = self::setProperty('Charset', 'iso-8859-1'); $left = self::setProperty('LeftMargin', '1cm'); $right = self::setProperty('RightMargin', '1cm'); $top = self::setProperty('TopMargin', '1cm'); $bottom = self::setProperty('BottomMargin', '1cm'); $font = self::setProperty('Font', 'Arial'); $size = self::setProperty('FontSize', '8'); $ls = self::setProperty('LineSpacing', 1); $linkcol = self::setProperty('LinkColour', '217A28'); $levels = self::setProperty('TocLevels', '2'); $exclude = self::setProperty('Exclude', array()); $width = self::setProperty('Width', ''); $width = $width ? "--browserwidth {$width}" : ''; if (!is_array($exclude)) { $exclude = split('\\s*,\\s*', $exclude); } // Select articles from members if a category or links in content if not if ($format == 'single') { $articles = array($title); } else { $articles = array(); if ($title->getNamespace() == NS_CATEGORY) { $db = wfGetDB(DB_SLAVE); $cat = $db->addQuotes($title->getDBkey()); $result = $db->select('categorylinks', 'cl_from', "cl_to = {$cat}", 'PdfBook', array('ORDER BY' => 'cl_sortkey')); if ($result instanceof ResultWrapper) { $result = $result->result; } while ($row = $db->fetchRow($result)) { $articles[] = Title::newFromID($row[0]); } } else { $text = $article->fetchContent(); $text = $wgParser->preprocess($text, $title, $opt); if (preg_match_all("/^\\*\\s*\\[{2}\\s*([^\\|\\]]+)\\s*.*?\\]{2}/m", $text, $links)) { foreach ($links[1] as $link) { $articles[] = Title::newFromText($link); } } } } // Format the article(s) as a single HTML document with absolute URL's $book = $title->getText(); $html = ''; $wgArticlePath = $wgServer . $wgArticlePath; $wgPdfBookTab = false; $wgScriptPath = $wgServer . $wgScriptPath; $wgUploadPath = $wgServer . $wgUploadPath; $wgScript = $wgServer . $wgScript; foreach ($articles as $title) { $ttext = $title->getPrefixedText(); if (!in_array($ttext, $exclude)) { $article = new Article($title); $text = $article->fetchContent(); $text = preg_replace("/<!--([^@]+?)-->/s", "@@" . "@@\$1@@" . "@@", $text); # preserve HTML comments if ($format != 'single') { $text .= "__NOTOC__"; } $opt->setEditSection(false); # remove section-edit links $out = $wgParser->parse($text, $title, $opt, true, true); $text = $out->getText(); $text = preg_replace("|(<img[^>]+?src=\")(/.+?>)|", "\$1{$wgServer}\$2", $text); # make image urls absolute $text = preg_replace("|<div\\s*class=['\"]?noprint[\"']?>.+?</div>|s", "", $text); # non-printable areas $text = preg_replace("|@{4}([^@]+?)@{4}|s", "<!--\$1-->", $text); # HTML comments hack $ttext = basename($ttext); $h1 = $notitle ? "" : "<center><h1>{$ttext}</h1></center>"; $html .= utf8_decode("{$h1}{$text}\n"); } } // $wgPdfBookTab = false; If format=html in query-string, return html content directly if ($format == 'html') { $wgOut->disable(); header("Content-Type: text/html"); header("Content-Disposition: attachment; filename=\"{$book}.html\""); print $html; } else { // Write the HTML to a tmp file if (!is_dir($wgUploadDirectory)) { mkdir($wgUploadDirectory); } $file = "{$wgUploadDirectory}/" . uniqid('pdf-book'); file_put_contents($file, $html); $footer = $format == 'single' ? "..." : ".1."; $toc = $format == 'single' ? "" : " --toclevels {$levels}"; // Send the file to the client via htmldoc converter $wgOut->disable(); header("Content-Type: application/pdf"); header("Content-Disposition: attachment; filename=\"{$book}.pdf\""); $cmd = "--left {$left} --right {$right} --top {$top} --bottom {$bottom}"; $cmd .= " --header ... --footer {$footer} --headfootsize 8 --quiet --jpeg --color"; $cmd .= " --bodyfont {$font} --fontsize {$size} --fontspacing {$ls} --linkstyle plain --linkcolor {$linkcol}"; $cmd .= "{$toc} --no-title --format pdf14 --webpage --numbered {$layout} {$width}"; // added the webpage option $cmd = "htmldoc -t pdf --charset {$charset} {$cmd} {$file}"; putenv("HTMLDOC_NOCGI=1"); passthru($cmd); @unlink($file); } return false; } return true; }
$conds = array($comparisonCond, 'rev_id = page_latest', 'rev_text_id = old_id'); $sort = array('ORDER BY' => 'page_namespace, page_title'); return $dbr->select($tables, $vars, $conds, __METHOD__, $sort); } $res = findPagesByRegex($regex); $titles_for_edit = array(); $user = isset($options['user']) ? $options['user'] : '******'; foreach ($res as $row) { $title = Title::newFromDBkey($row->page_title); echo $title->getText() . "\n"; $article = new Article($title, 0); if (!$article) { echo 'replaceText: Article not found.' . "\n"; return false; } $content = $article->fetchContent(); if (preg_match('%' . $regex . '%', $content, $m)) { $functions = explode(',', $m[1]); echo 'Matched ' . $m[1] . "\n"; $new_functions = '|shelter='; foreach ($functions as $f) { if ($f === 'Soil stabilization') { $f = 'Earth stabiliser'; } if ($f === 'Soil reclamation') { $f = 'Soil builder'; } $new_functions .= '{{Plant provides shelter for|function=' . ucfirst(trim($f)) . '}}'; } echo 'Changing ' . $m[0] . ' to ' . $new_functions . "\n"; $new_content = preg_replace('%' . $regex . '%', $new_functions, $content);
public function addVCalEvents($page, $year, $month) { $arrRRULES = array(); $ical_short_day = array("SU" => 0, "MO" => 1, "TU" => 2, "WE" => 3, "TH" => 4, "FR" => 5, "SA" => 6); $articleName = "{$page}/recurrence"; $article = new Article(Title::newFromText($articleName)); $bExists = $article->exists(); if ($bExists) { $body = trim($article->fetchContent(0, false, false)); $arrRRULES = $this->convertRRULEs($body); } else { return; } foreach ($arrRRULES as $rules) { $bExpired = false; if (isset($rules['UNTIL'])) { $bExpired = $this->checkExpiredRRULE($rules['UNTIL']); } if ($bExpired) { continue; } // skip the rest of the current loop iteration if ($rules['FREQ'] == 'YEARLY' && !isset($rules['BYDAY']) && $rules['BYMONTH'] == $month) { //std sameday recurrence $this->buildEvent($month, $rules['DAY'], $year, $rules['SUMMARY'], $articleName, "", 'recurrence'); } else { if ($rules['FREQ'] == 'YEARLY' && isset($rules['BYDAY']) && $rules['BYMONTH'] == $month) { $num = $rules['BYDAY']; // parse the ical format for BYDAY (1MO, 4TH, 2WE, etc) settype($num, 'integer'); //get the numeric value of BYDAY $ical_weekday = str_replace($num, "", $rules['BYDAY']); //get the weekday text value of BYDAY $day = $ical_short_day[$ical_weekday]; // take the text and get the 0-6 numeric value (SU=0, MO=1, etc) $wday_info = Common::wdayOffset($month, $year, $day); $offset = $wday_info['offset']; // if we have something like -1SU; then handle it here... if ($num < 0) { $num = $wday_info['weeks'] + 1 + $num; } // kick back the week count if needed if ($offset > 0 && $num != 0) { $num--; } $theday = $offset + 7 * $num; $this->buildEvent($month, $theday, $year, $rules['SUMMARY'], $articleName, "", 'recurrence'); } } } unset($rules); }
function doRedirect($form_name, $page_name, $params) { global $wgOut; $page_title = Title::newFromText($page_name); if ($page_title->exists()) { // It exists - see if page is a redirect; if // it is, edit the target page instead. $article = new Article($page_title, 0); $article->loadContent(); $redirect_title = Title::newFromRedirect($article->fetchContent()); if ($redirect_title != null) { $page_title = $redirect_title; $page_name = SFUtils::titleURLString($redirect_title); } // HACK - if this is the default form for // this page, send to the regular 'formedit' // tab page; otherwise, send to the 'Special:FormEdit' // page, with the form name hardcoded. // Is this logic necessary? Or should we just // out-guess the user and always send to the // standard form-edit page, with the 'correct' form? $default_forms = SFFormLinker::getDefaultFormsForPage($page_title); if (count($default_forms) > 0) { $default_form_name = $default_forms[0]; } else { $default_form_name = null; } if ($form_name == $default_form_name) { $redirect_url = $page_title->getLocalURL('action=formedit'); } else { $redirect_url = self::getFormEditURL($form_name, $page_name); } } else { $redirect_url = self::getFormEditURL($form_name, $page_name); // Of all the request values, send on to 'FormEdit' // only 'preload' and specific form fields - we can // identify the latter because they show up as arrays. foreach ($_REQUEST as $key => $val) { if (is_array($val)) { $template_name = urlencode($key); foreach ($val as $field_name => $value) { $field_name = urlencode($field_name); $value = urlencode($value); $redirect_url .= strpos($redirect_url, '?') > -1 ? '&' : '?'; $redirect_url .= $template_name . '[' . $field_name . ']=' . $value; } } elseif ($key == 'preload') { $redirect_url .= strpos($redirect_url, '?') > -1 ? '&' : '?'; $redirect_url .= "{$key}={$val}"; } } } if (!is_null($params) && $params !== '') { $redirect_url .= strpos($redirect_url, '?') > -1 ? '&' : '?'; $redirect_url .= $params; } $wgOut->setArticleBodyOnly(true); // Show "loading" animated image while people wait for the // redirect. global $sfgScriptPath; $text = "<p style=\"position: absolute; left: 45%; top: 45%;\"><img src=\"{$sfgScriptPath}/skins/loading.gif\" /></p>\n"; $text .= <<<END \t\t<script type="text/javascript"> \t\twindow.onload = function() { \t\t\twindow.location="{$redirect_url}"; \t\t} \t\t</script> END; $wgOut->addHTML($text); return; }
function view($u = null) { global $wgOut, $wgTitle, $wgUser, $wgRequest; $diff = $wgRequest->getVal('diff'); $rcid = $wgRequest->getVal('rcid'); $this->user = $u ? $u : User::newFromName($wgTitle->getDBKey()); if (!$u && $this->mTitle->getNamespace() != NS_USER || !$this->user || isset($diff) || isset($rcid)) { return Article::view(); } if ($this->user->getID() == 0) { header('HTTP/1.1 404 Not Found'); $wgOut->setRobotpolicy('noindex,nofollow'); $wgOut->errorpage('nosuchuser', 'Noarticletext_user'); return; } $this->isPageOwner = $wgUser->getID() == $this->user->getID(); if ($this->user->isBlocked() && $this->isPageOwner) { $wgOut->blockedPage(); return; } $wgOut->setRobotpolicy('index,follow'); $skin = $wgUser->getSkin(); //user settings $checkStats = $this->user->getOption('profilebox_stats') == 1; $checkStartedEdited = $this->user->getOption('profilebox_startedEdited') == 1; $wgOut->addScript(HtmlSnips::makeUrlTags('js', array('profilebox.js'), '/extensions/wikihow/profilebox/', false)); $wgOut->addHTML(HtmlSnips::makeUrlTags('css', array('profilebox.css'), '/extensions/wikihow/profilebox/', false)); $wgOut->addHTML(HtmlSnips::makeUrlTags('css', array('rcwidget.css'), '/extensions/wikihow/rcwidget/', false)); $profileStats = new ProfileStats($this->user); $badgeData = $profileStats->getBadges(); $wgOut->addHTML(ProfileBox::getDisplayBadge($badgeData)); if (!$u) { $skin->addWidget($this->getRCUserWidget()); } if ($checkStats || $checkStartedEdited) { $createdData = $profileStats->getArticlesCreated(0); } //stats if ($checkStats) { $stats = ProfileBox::fetchStats("User:"******"<div class='clearall'></div>"); } }
function doRedirect($form_name, $page_name, $params) { global $wgOut; $page_title = Title::newFromText($page_name); if ($page_title->exists()) { // It exists - see if page is a redirect; if // it is, edit the target page instead. $article = new Article($page_title, 0); $article->loadContent(); $redirect_title = Title::newFromRedirect($article->fetchContent()); if ($redirect_title != null) { $page_title = $redirect_title; $page_name = SFUtils::titleURLString($redirect_title); } // HACK - if this is the default form for // this page, send to the regular 'formedit' // tab page; otherwise, send to the 'Special:FormEdit' // page, with the form name hardcoded. // Is this logic necessary? Or should we just // out-guess the user and always send to the // standard form-edit page, with the 'correct' form? $default_forms = SFFormLinker::getDefaultFormsForPage($page_title); if (count($default_forms) > 0) { $default_form_name = $default_forms[0]; } else { $default_form_name = null; } if ($form_name == $default_form_name) { $redirect_url = $page_title->getLocalURL('action=formedit'); } else { $redirect_url = self::getFormEditURL($form_name, $page_name); } } else { $redirect_url = self::getFormEditURL($form_name, $page_name); // Of all the request values, send on to 'FormEdit' // only 'preload' and specific form fields - we can // identify the latter because they show up as arrays. foreach ($_REQUEST as $key => $val) { if (is_array($val)) { $redirect_url .= strpos($redirect_url, '?') > -1 ? '&' : '?'; // Re-add the key (i.e. the template // name), so we can make a nice query // string snippet out of the whole // thing. $wrapperArray = array($key => $val); $redirect_url .= urldecode(http_build_query($wrapperArray)); } elseif ($key == 'preload') { $redirect_url .= strpos($redirect_url, '?') > -1 ? '&' : '?'; $redirect_url .= "{$key}={$val}"; } } } if (!is_null($params) && $params !== '') { $redirect_url .= strpos($redirect_url, '?') > -1 ? '&' : '?'; $redirect_url .= $params; } $wgOut->setArticleBodyOnly(true); // Show "loading" animated image while people wait for the // redirect. global $sfgScriptPath; $text = <<<END \t<p style="position: absolute; left: 45%; top: 45%;"> \t<img src="{$sfgScriptPath}/skins/loading.gif" /> \t</p> \t<meta http-equiv="refresh" content="0; url={$redirect_url}" /> END; $wgOut->addHTML($text); return; }