function convert($newFormat, $pageName, $calName, $redirect, $go)
 {
     $search = "{$pageName}/{$calName}";
     $pages = PrefixSearch::titleSearch($search, 1000000);
     //search upto 1,000,000 events (no performace issue)
     $count = $erroredCount = 0;
     foreach ($pages as $page) {
         $retval = false;
         $newPage = $this->convertToNewPage($page, $newFormat);
         $article = new Article(Title::newFromText($page));
         if ($newPage != '') {
             $fromTitle = Title::newFromText($page);
             $toTitle = Title::newFromText($newPage);
             $articleNew = new Article(Title::newFromText($newPage));
             if (!$article->isRedirect() && !$articleNew->exists()) {
                 if ($go) {
                     $retval = $fromTitle->moveTo($toTitle, true, 'CalendarConversion', $redirect);
                 } else {
                     if ($count < 10) {
                         $testRun .= '&nbsp;&nbsp;' . $page . '  &rarr;&rarr;  ' . $newPage . '<br>';
                     }
                 }
             }
         }
     }
     unset($pages);
     if ($go) {
         $ret = "Conversion completed.";
     } else {
         $ret = "<b>Test Results, add '<i>go</i>' to the <i>dateConverter</i> tag to convert:</b><br>{$testRun}";
     }
     return $ret;
 }
Ejemplo n.º 2
0
    function testPreferences()
    {
        global $wgUser, $wgOut, $wgTitle;
        // This test makes call to the parser which requires valids Outputpage
        // and Title objects. Set them up there, they will be released at the
        // end of the test.
        $old_wgOut = $wgOut;
        $old_wgTitle = $wgTitle;
        $wgTitle = Title::newFromText('Parser test for Gadgets extension');
        // Proceed with test setup:
        $prefs = array();
        $context = new RequestContext();
        $wgOut = $context->getOutput();
        $wgOut->setTitle(Title::newFromText('test'));
        Gadget::loadStructuredList('* foo | foo.js
==keep-section1==
* bar| bar.js
==remove-section==
* baz [rights=embezzle] |baz.js
==keep-section2==
* quux [rights=read] | quux.js');
        $this->assertTrue(GadgetHooks::getPreferences($wgUser, $prefs), 'GetPrefences hook should return true');
        $options = $prefs['gadgets']['options'];
        $this->assertFalse(isset($options['&lt;gadget-section-remove-section&gt;']), 'Must not show empty sections');
        $this->assertTrue(isset($options['&lt;gadget-section-keep-section1&gt;']));
        $this->assertTrue(isset($options['&lt;gadget-section-keep-section2&gt;']));
        // Restore globals
        $wgOut = $old_wgOut;
        $wgTitle = $old_wgTitle;
    }
Ejemplo n.º 3
0
 function getSQL()
 {
     $dbr =& wfGetDB(DB_SLAVE);
     list($page, $pagelinks, $templatelinks) = $dbr->tableNamesN('page', 'pagelinks', 'templatelinks');
     $dMsgText = wfMsgForContent('disambiguationspage');
     $linkBatch = new LinkBatch();
     # If the text can be treated as a title, use it verbatim.
     # Otherwise, pull the titles from the links table
     $dp = Title::newFromText($dMsgText);
     if ($dp) {
         if ($dp->getNamespace() != NS_TEMPLATE) {
             # FIXME we assume the disambiguation message is a template but
             # the page can potentially be from another namespace :/
             wfDebug("Mediawiki:disambiguationspage message does not refer to a template!\n");
         }
         $linkBatch->addObj($dp);
     } else {
         # Get all the templates linked from the Mediawiki:Disambiguationspage
         $disPageObj = $this->getDisambiguationPageObj();
         $res = $dbr->select(array('pagelinks', 'page'), 'pl_title', array('page_id = pl_from', 'pl_namespace' => NS_TEMPLATE, 'page_namespace' => $disPageObj->getNamespace(), 'page_title' => $disPageObj->getDBkey()), 'DisambiguationsPage::getSQL');
         while ($row = $dbr->fetchObject($res)) {
             $linkBatch->addObj(Title::makeTitle(NS_TEMPLATE, $row->pl_title));
         }
         $dbr->freeResult($res);
     }
     $set = $linkBatch->constructSet('lb.tl', $dbr);
     if ($set === false) {
         $set = 'FALSE';
         # We must always return a valid sql query, but this way DB will always quicly return an empty result
         wfDebug("Mediawiki:disambiguationspage message does not link to any templates!\n");
     }
     $sql = "SELECT 'Disambiguations' AS \"type\", pb.page_namespace AS namespace," . " pb.page_title AS title, la.pl_from AS value" . " FROM {$templatelinks} AS lb, {$page} AS pb, {$pagelinks} AS la, {$page} AS pa" . " WHERE {$set}" . ' AND pa.page_id = la.pl_from' . ' AND pa.page_namespace = ' . NS_MAIN . ' AND pb.page_id = lb.tl_from' . ' AND pb.page_namespace = la.pl_namespace' . ' AND pb.page_title = la.pl_title' . ' ORDER BY lb.tl_namespace, lb.tl_title';
     return $sql;
 }
Ejemplo n.º 4
0
 public function execute()
 {
     global $wgUser;
     if (!$wgUser->isLoggedIn()) {
         $this->dieUsage('You must be logged-in to have a watchlist', 'notloggedin');
     }
     $params = $this->extractRequestParams();
     $title = Title::newFromText($params['title']);
     if (!$title) {
         $this->dieUsageMsg(array('invalidtitle', $params['title']));
     }
     $article = new Article($title);
     $res = array('title' => $title->getPrefixedText());
     if ($params['unwatch']) {
         $res['unwatched'] = '';
         $success = $article->doUnwatch();
     } else {
         $res['watched'] = '';
         $success = $article->doWatch();
     }
     if (!$success) {
         $this->dieUsageMsg(array('hookaborted'));
     }
     $this->getResult()->addValue(null, $this->getModuleName(), $res);
 }
Ejemplo n.º 5
0
 /**
  * Assuming the user's interface language is fi. Given input Page, it
  * returns Page/fi if it exists, otherwise Page. Given input Page/de,
  * it returns Page/fi if it exists, otherwise Page/de if it exists,
  * otherwise Page.
  *
  * @param string|null $subpage
  * @return Title|null
  */
 public function findTitle($subpage)
 {
     // base = title without language code suffix
     // provided = the title as it was given
     $base = $provided = null;
     if ($subpage !== null) {
         $provided = Title::newFromText($subpage);
         $base = $provided;
     }
     if ($provided && strpos($subpage, '/') !== false) {
         $pos = strrpos($subpage, '/');
         $basepage = substr($subpage, 0, $pos);
         $code = substr($subpage, $pos + 1);
         if (strlen($code) && Language::isKnownLanguageTag($code)) {
             $base = Title::newFromText($basepage);
         }
     }
     if (!$base) {
         return null;
     }
     if ($base->isRedirect()) {
         $page = new WikiPage($base);
         $base = $page->getRedirectTarget();
     }
     $uiCode = $this->getLanguage()->getCode();
     $proposed = $base->getSubpage($uiCode);
     if ($proposed && $proposed->exists() && $uiCode !== $base->getPageLanguage()->getCode()) {
         return $proposed;
     } elseif ($provided && $provided->exists()) {
         return $provided;
     } else {
         return $base;
     }
 }
Ejemplo n.º 6
0
 /**
  * Do a prefix search of titles and return a list of matching page names.
  *
  * @param $search String
  * @param $limit Integer
  * @param $namespaces Array: used if query is not explicitely prefixed
  * @return Array of strings
  */
 public static function titleSearch($search, $limit, $namespaces = array())
 {
     $search = trim($search);
     if ($search == '') {
         return array();
         // Return empty result
     }
     $namespaces = self::validateNamespaces($namespaces);
     // Find a Title which is not an interwiki and is in NS_MAIN
     $title = Title::newFromText($search);
     if ($title && $title->getInterwiki() == '') {
         $ns = array($title->getNamespace());
         if ($ns[0] == NS_MAIN) {
             $ns = $namespaces;
         }
         // no explicit prefix, use default namespaces
         return self::searchBackend($ns, $title->getText(), $limit);
     }
     // Is this a namespace prefix?
     $title = Title::newFromText($search . 'Dummy');
     if ($title && $title->getText() == 'Dummy' && $title->getNamespace() != NS_MAIN && $title->getInterwiki() == '') {
         return self::searchBackend(array($title->getNamespace()), '', $limit);
     }
     return self::searchBackend($namespaces, $search, $limit);
 }
Ejemplo n.º 7
0
 function execute($par)
 {
     global $wgOut, $wgUser;
     $wgOut->setRobotPolicy("index,follow");
     $sk = $wgUser->getSkin();
     $topcats = $this->getTopLevelCategories();
     $wgOut->setHTMLTitle('wikiHow Sitemap');
     $count = 0;
     $wgOut->addHTML("\n\t\t\t<style>\n\t\t\t\t#catentry li {\n\t\t\t\t\tmargin-bottom: 0;\n\t\t\t\t}\n\t\t\t\ttable.cats {\n\t\t\t\t\twidth: 100%;\n\t\t\t\t}\n\t\t\t\t.cats td {\n\t\t\t\t\tvertical-align: top;\n\t\t\t\t\tborder: 1px solid #e5e5e5;\n\t\t\t\t\tpadding: 10px;\n\t\t\t\t\tbackground: white;\n\t\t\t\t\t-moz-border-radius: 4px;\n\t\t\t\t\t-webkit-border-radius: 4px;\n\t\t\t\t\t-khtml-border-radius: 4px;\n\t\t\t\t\tborder-radius: 4px;\n\t\t\t\t}\n\t\t\t</style>\n\t\t\t<table align='center' class='cats' cellspacing=10px>");
     foreach ($topcats as $cat) {
         $t = Title::newFromText($cat, NS_CATEGORY);
         $subcats = $this->getSubcategories($t);
         if ($count % 2 == 0) {
             $wgOut->addHTML("<tr>");
         }
         $wgOut->addHTML("<td><h3>" . $sk->makeLinkObj($t, $t->getText()) . "</h3><ul id='catentry'>");
         foreach ($subcats as $sub) {
             $t = Title::newFromText($sub, NS_CATEGORY);
             $wgOut->addHTML("<li>" . $sk->makeLinkObj($t, $t->getText()) . "</li>\n");
         }
         $wgOut->addHTML("</ul></td>\n");
         if ($count % 2 == 1) {
             $wgOut->addHTML("</tr>");
         }
         $count++;
     }
     $wgOut->addHTML("</table>");
 }
 public function getRelated()
 {
     wfProfileIn(__METHOD__);
     $result = array();
     $articleIds = array();
     $thumbnailsReplaced = array();
     //TODO move to PathFinderController
     if ($this->getVal('selectby') == 'byTitle') {
         $title = Title::newFromText($this->getVal('article'));
         $articleId = $title->getArticleID();
     } else {
         $articleId = $this->getVal('article');
     }
     $nodes = $this->model->getRelated($this->wg->CityId, $articleId, $this->getVal('datespan'), $this->getVal('userHaveSeenNumber'), $this->getVal('minCount'));
     if (count($nodes) > 0) {
         foreach ($nodes as $node) {
             $targetTitle = Title::newFromID($node->target_id);
             if ($targetTitle != NULL) {
                 $targetURL = $targetTitle->getLocalURL();
                 $result[] = array('cityid' => $node->city_id, 'targetTitle' => $targetTitle, 'targetURL' => $targetURL, 'count' => $node->count, 'updated' => $node->updated);
                 $articleIds[] = $targetTitle->mArticleID;
             }
         }
         $thumbnails = $this->sendSelfRequest('getThumbnails', array('articleIds' => $articleIds, 'width' => 75))->getVal('thumbnails');
         $this->setVal('thumbnails', $thumbnails);
     } else {
         $result = array("No Result");
     }
     $this->setVal('nodes', $result);
     wfProfileOut(__METHOD__);
 }
 /**
  * Updates wiki specific properties set from wiki creation wizard.
  * Context of this method is on the wiki that the values are changing on.
  * Main wiki creation happens on www, and it will redirect to the newly created wiki.
  * The values are read from the session and only accessible by the admin.
  */
 public function FinishCreate()
 {
     global $wgUser, $wgOut, $wgEnableNjordExt;
     if (!$wgUser->isAllowed('finishcreate')) {
         return false;
     }
     $this->skipRendering();
     $this->LoadState();
     $mainPage = wfMsgForContent('mainpage');
     // set theme
     if (!empty($this->params['color-body'])) {
         $themeSettings = new ThemeSettings();
         $themeSettings->saveSettings($this->params);
     }
     // set description on main page
     if (!empty($this->params['wikiDescription'])) {
         $mainTitle = Title::newFromText($mainPage);
         $mainId = $mainTitle->getArticleID();
         $mainArticle = Article::newFromID($mainId);
         if (!empty($mainArticle)) {
             if (!empty($wgEnableNjordExt)) {
                 $newMainPageText = $this->getMoMMainPage($mainArticle);
             } else {
                 $newMainPageText = $this->getClassicMainPage($mainArticle);
             }
             $mainArticle->doEdit($newMainPageText, '');
             $this->initHeroModule($mainPage);
         }
     }
     $wgOut->enableClientCache(false);
     $this->clearState();
     $wgOut->redirect($mainPage . '?wiki-welcome=1');
 }
Ejemplo n.º 10
0
 function __construct(IContextSource $context, $userName = null, $search = '', $including = false, $showAll = false)
 {
     $this->setContext($context);
     $this->mIncluding = $including;
     $this->mShowAll = $showAll;
     if ($userName !== null && $userName !== '') {
         $nt = Title::newFromText($userName, NS_USER);
         $user = User::newFromName($userName, false);
         if (!is_null($nt)) {
             $this->mUserName = $nt->getText();
         }
         if (!$user || $user->isAnon() && !User::isIP($user->getName())) {
             $this->getOutput()->wrapWikiMsg("<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>", array('listfiles-userdoesnotexist', wfEscapeWikiText($userName)));
         }
     }
     if ($search !== '' && !$this->getConfig()->get('MiserMode')) {
         $this->mSearch = $search;
         $nt = Title::newFromURL($this->mSearch);
         if ($nt) {
             $dbr = wfGetDB(DB_SLAVE);
             $this->mQueryConds[] = 'LOWER(img_name)' . $dbr->buildLike($dbr->anyString(), strtolower($nt->getDBkey()), $dbr->anyString());
         }
     }
     if (!$including) {
         if ($this->getRequest()->getText('sort', 'img_date') == 'img_date') {
             $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
         } else {
             $this->mDefaultDirection = IndexPager::DIR_ASCENDING;
         }
     } else {
         $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
     }
     parent::__construct($context);
 }
	public function execute( $par ) {
		global $wgOut;

		$title = '';
		$params = array();

		if( IncubatorTest::isContentProject() ) {
			global $wgRequest;
			$title = Title::newFromText( IncubatorTest::displayPrefix() );
			if( $wgRequest->getVal( 'goto' ) != 'infopage' ) {
				$params['goto'] = 'mainpage';
			}
			$url = IncubatorTest::getUrlParam();
			if( $url ) {
				$params['testwiki'] = $url['prefix'];
			}
		}

		# Go to the main page if given invalid title, or if it's not a content project
		if ( !$title ) {
			$title = Title::newMainPage();
		}

		$wgOut->redirect( $title->getLocalURL( $params ) );
	}
Ejemplo n.º 12
0
function efFastCatSelector(&$categories)
{
    global $wgTitle, $wgArticle;
    // BugId:26491
    if (empty($wgTitle) || empty($wgArticle)) {
        return true;
    }
    $artname = $wgTitle->getText();
    $artid = $wgArticle->getID();
    $spice = sha1("Kroko-katMeNot-" . $artid . "-" . $artname . "-NotMekat-Schnapp");
    $catUrl = Title::newFromText('FastCat', NS_SPECIAL)->getFullURL();
    $ret = "<form action=\"{$catUrl}\" method='post'>\n<p><b>" . wfMsg('fastcat-box-title') . "</b><br>\n<small>" . wfMsg('fastcat-box-intro') . "</small>\n</p>\n<input type='hidden' name='id' value='{$artid}'>\n<input type='hidden' name='spice' value='{$spice}'>\n<input type='hidden' name='artname' value='{$artname}'>\n<p style=\"text-indent:-1em;margin-left:1em\">";
    $kat = explode("\n", wfMsgForContent('fastcat-categories-list'));
    foreach ($kat as $k) {
        if (strpos($k, '* ') === 0) {
            $k = trim($k, '* ');
            $ret .= "</p><p style=\"text-indent:-1em;margin-left:1em\">\n";
            $ret .= "<button style=\"font-size:smaller;\" name=\"cat\" value=\"{$k}\"><b>{$k}</b></button>\n";
        } else {
            $k = trim($k, '* ');
            $ret .= "<button style=\"font-size:smaller;\" name=\"cat\" value=\"{$k}\">{$k}</button>\n";
        }
    }
    $ret .= <<<EORET
\t\t</p>
\t\t</form>
EORET;
    $categories = $ret;
    return true;
}
Ejemplo n.º 13
0
function efAddResourceSpecialPage($template, $links)
{
    global $wgTitle, $wgRequest, $wgUser, $wgAddResourceTab;
    // return if we are not on the right special page
    if (!$wgTitle->isSpecial('AddResource')) {
        return true;
    }
    // parse subpage-part. We cannot use $wgTitle->getSubpage() because the
    // special namespaces doesn't have real subpages
    $prefixedText = $wgTitle->getPrefixedText();
    if (strpos($prefixedText, '/') === FALSE) {
        return true;
        // no page given
    }
    $parts = explode('/', $prefixedText);
    $pageName = $parts[count($parts) - 1];
    $title = Title::newFromText($pageName)->getSubjectPage();
    $talkTitle = $title->getTalkPage();
    // Get AddResource URL:
    $resourceCount = getResourceCount($title);
    $resourcesUrl = getResourcesUrl($title);
    $resourcesText = getResourceTabText($resourceCount);
    $resourcesClass = $resourceCount > 0 ? 'is_resources' : 'new is_resources';
    $head = array($title->getNamespaceKey('') => array('class' => $title->exists() ? null : 'new', 'text' => $title->getText(), 'href' => $title->getLocalUrl()), 'resources' => array('class' => $resourcesClass, 'text' => $resourcesText, 'href' => $resourcesUrl));
    $tail = array($title->getNamespaceKey('') . '_talk' => array('class' => $talkTitle->exists() ? null : 'new', 'text' => wfMessage('Talk')->text(), 'href' => $talkTitle->getLocalUrl()));
    $resourceCount = getResourceCount($title);
    $links['namespaces'] = array_merge($head, $links['namespaces'], $tail);
    $links['namespaces']['special']['text'] = '+';
    return true;
}
Ejemplo n.º 14
0
function WidgetCategoryCloud($id, $params)
{
    $output = "";
    wfProfileIn(__METHOD__);
    global $wgMemc;
    $key = wfMemcKey("WidgetCategoryCloud", "data");
    $data = $wgMemc->get($key);
    if (is_null($data)) {
        $data = WidgetCategoryCloudCloudizeData(WidgetCategoryCloudGetData());
        $wgMemc->set($key, $data, 3600);
    }
    if (empty($data)) {
        wfProfileOut(__METHOD__);
        return wfMsgForContent("widget-categorycloud-empty");
    }
    foreach ($data as $name => $value) {
        $category = Title::newFromText($name, NS_CATEGORY);
        if (is_object($category)) {
            $class = "cloud" . $value;
            $output .= Xml::openElement("li", array("class" => $class));
            // FIXME fix Wikia:link and use it here
            $output .= Xml::element("a", array("class" => $class, "href" => $category->getLocalURL(), "title" => $category->getFullText()), $category->getBaseText());
            $output .= Xml::closeElement("li");
            $output .= "\n";
        }
    }
    if (empty($output)) {
        wfProfileOut(__METHOD__);
        return wfMsgForContent("widget-categorycloud-empty");
    }
    $output = Xml::openElement("ul") . $output . Xml::closeElement("ul");
    wfProfileOut(__METHOD__);
    return $output;
}
Ejemplo n.º 15
0
 /**
  * @dataProvider provideValidate
  */
 public function testForm($text, $value)
 {
     $form = HTMLForm::factory('ooui', ['restrictions' => ['class' => HTMLRestrictionsField::class]]);
     $request = new FauxRequest(['wprestrictions' => $text], true);
     $context = new DerivativeContext(RequestContext::getMain());
     $context->setRequest($request);
     $form->setContext($context);
     $form->setTitle(Title::newFromText('Main Page'))->setSubmitCallback(function () {
         return true;
     })->prepareForm();
     $status = $form->trySubmit();
     if ($status instanceof StatusValue) {
         $this->assertEquals($value !== false, $status->isGood());
     } elseif ($value === false) {
         $this->assertNotSame(true, $status);
     } else {
         $this->assertSame(true, $status);
     }
     if ($value !== false) {
         $restrictions = $form->mFieldData['restrictions'];
         $this->assertInstanceOf(MWRestrictions::class, $restrictions);
         $this->assertEquals($value, $restrictions->toArray()['IPAddresses']);
     }
     // sanity
     $form->getHTML($status);
 }
Ejemplo n.º 16
0
function renderpageTools($input)
{
    global $wgUser, $wgTitle, $wgOut, $IP;
    require_once "{$IP}/extensions/ListPages/ListPagesClass.php";
    $parser = new Parser();
    $list = new ListPages();
    $list->setBool("ShowCtg", "yes");
    $relatedctgArray = explode(",", strip_tags($list->getCategoryLinks($wgTitle->mArticleID, 7)));
    foreach ($relatedctgArray as $ctg) {
        if ($ctg != "") {
            $ctg = trim(strtoupper($ctg));
            if ($ctg != "NEWS" && $ctg != "OPINIONS") {
                if ($ctgstr != "") {
                    $ctgstr .= ",";
                }
                $CtgTitle = Title::newFromText($parser->transformMsg(trim($ctg), $wgOut->parserOptions()));
                $ctgstr .= $CtgTitle->getDbKey();
            }
        }
    }
    $output = "";
    $output .= '<a href="#pageToolsTop"></a><table cellpadding="0" cellspacing="0" border="0"><tr>';
    $output .= '<td width="100" id="commentsBtn" class="toptabsOn" onmousedown=\'javascript:$("commentsBtn").className="toptabsOn";$("historyBtn").className="toptabs";$("emailBtn").className="toptabs";$("relatedBtn").className="toptabs";getContent("index.php?title=Special:CommentAction&Action=2","pid=' . $wgTitle->mArticleID . '&shwform=1&ord=0","pageToolsContent")\'>Comments</td>';
    $output .= '<td width="5" class="topright">&nbsp;</td>';
    $output .= '<td width="100" id="emailBtn" class="toptabs" onmousedown=\'javascript:$("emailBtn").className="toptabsOn";$("historyBtn").className="toptabs";$("commentsBtn").className="toptabs";$("relatedBtn").className="toptabs";getContent("index.php?title=Special:EmailThis&pageid=' . $wgTitle->mArticleID . '","","pageToolsContent")\'>Email This</td>';
    $output .= '<td width="5" class="topright">&nbsp;</td>';
    $output .= '<td width="100" id="relatedBtn" class="toptabs" onmousedown=\'$("relatedBtn").className="toptabsOn";$("historyBtn").className="toptabs";$("commentsBtn").className="toptabs";$("emailBtn").className="toptabs";javascript:getContent("index.php?title=Special:ListPagesAction","shw=15&ctg=' . $ctgstr . '&ord=PUBLISHEDDATE&lv=1&shwctg=1&det=0&pub=1","pageToolsContent")\'>Related Articles</td>';
    $output .= '<td width="5" class="topright">&nbsp;</td>';
    $output .= '<td width="100" id="historyBtn" class="toptabs" onmousedown=\'$("historyBtn").className="toptabsOn";$("relatedBtn").className="toptabs";$("commentsBtn").className="toptabs";$("emailBtn").className="toptabs";javascript:getContent("index.php?title=Special:PageHistoryAJAX&pid=' . $wgTitle->mArticleID . '","","pageToolsContent")\'>Page History</td><td width="300" class="topright">&nbsp;</td>';
    $output .= '</tr></table><br/><div id="pageToolsContent">';
    return $output;
}
 public function testGetTranslationPageText()
 {
     $title = Title::newFromText(__CLASS__);
     $page = TranslatablePage::newFromText($title, '<translate>Hello <tvar|abc>peter!</></translate>');
     $prefix = $title->getPrefixedDBKey() . '/';
     $parse = $page->getParse();
     $collection = array();
     $expected = 'Hello peter!';
     $actual = $parse->getTranslationPageText($collection);
     $this->assertEquals($expected, $actual, 'Variable declarations are substituted when no translation');
     foreach ($parse->sections as $section) {
         $key = $prefix . $section->id;
         $message = new FatMessage($key, $section->getText());
         $message->setTranslation($section->getText());
         $collection[$key] = $message;
     }
     $actual = $parse->getTranslationPageText($collection);
     $this->assertEquals($expected, $actual, 'Variable declarations are substituted in source language');
     foreach ($parse->sections as $section) {
         $key = $prefix . $section->id;
         $message = new FatMessage($key, $section->getText());
         $message->setTranslation($section->getTextForTrans());
         $collection[$key] = $message;
     }
     $actual = $parse->getTranslationPageText($collection);
     $this->assertEquals($expected, $actual, 'Variable declarations are substituted in translation');
 }
Ejemplo n.º 18
0
 static function formatLogEntry($type, $action, $title, $sk, $parameters)
 {
     $msg = "lqt-log-action-{$action}";
     switch ($action) {
         case 'merge':
             if ($parameters[0]) {
                 $msg = 'lqt-log-action-merge-across';
             } else {
                 $msg = 'lqt-log-action-merge-down';
             }
             break;
         case 'move':
             $smt = new SpecialMoveThread();
             $rightsCheck = $smt->checkUserRights($parameters[1] instanceof Title ? $parameters[1] : Title::newFromText($parameters[1]), $parameters[0] instanceof Title ? $parameters[0] : Title::newFromText($parameters[0]));
             if ($rightsCheck === true) {
                 $parameters[] = Message::rawParam(Linker::link(SpecialPage::getTitleFor('MoveThread', $title), wfMessage('revertmove')->text(), array(), array('dest' => $parameters[0])));
             } else {
                 $parameters[] = '';
             }
             break;
         default:
             // Give grep a chance to find the usages:
             // lqt-log-action-move, lqt-log-action-split, lqt-log-action-subjectedit,
             // lqt-log-action-resort, lqt-log-action-signatureedit
             $msg = "lqt-log-action-{$action}";
             break;
     }
     array_unshift($parameters, $title->getPrefixedText());
     $html = wfMessage($msg, $parameters);
     if ($sk === null) {
         return StringUtils::delimiterReplace('<', '>', '', $html->inContentLanguage()->parse());
     }
     return $html->parse();
 }
Ejemplo n.º 19
0
 /**
  * Gets the HTML for the preview image or null if there is none.
  *
  * @since 2.3.3
  *
  * @param string $imageName
  *
  * @return string|null
  */
 protected static function getPreviewImage($imageName)
 {
     $previewImage = null;
     $imageTitle = Title::newFromText($imageName, NS_FILE);
     if (!is_object($imageTitle)) {
         return $previewImage;
     }
     $api = new ApiMain(new FauxRequest(array('action' => 'query', 'format' => 'json', 'prop' => 'imageinfo', 'iiprop' => 'url', 'titles' => $imageTitle->getFullText(), 'iiurlwidth' => 200), true), true);
     $api->execute();
     $result = $api->getResultData();
     $url = false;
     if (array_key_exists('query', $result) && array_key_exists('pages', $result['query'])) {
         foreach ($result['query']['pages'] as $page) {
             if (array_key_exists('imageinfo', $page)) {
                 foreach ($page['imageinfo'] as $imageInfo) {
                     $url = $imageInfo['thumburl'];
                     break;
                 }
             }
         }
     }
     if ($url !== false) {
         $previewImage = Html::element('img', array('src' => $url));
     }
     return $previewImage;
 }
Ejemplo n.º 20
0
 public function execute()
 {
     # get the current user.
     $context = $this->createContext();
     $user = $context->getUser();
     $params = $this->extractRequestParams();
     $action = $params['action'];
     // check the blacklist, the same way tbhooks does it.
     //
     // Some places check createpage, while others check create.
     // As it stands, upload does createpage, but normalize both
     // to the same action, to stop future similar bugs.
     if ($action === 'createpage' || $action === 'createtalk') {
         $action = 'create';
     }
     $title = Title::newFromText($params['title']);
     if (!$title) {
         $this->dieUsageMsg(array('invalidtitle', $params['title']));
     }
     $blacklisted = TitleBlacklist::singleton()->userCannot($title, $user, $action);
     if ($blacklisted instanceof TitleBlacklistEntry) {
         // this title is blacklisted.
         $result = array(htmlspecialchars($blacklisted->getRaw()), htmlspecialchars($params['title']));
         $res = $this->getResult();
         $res->addValue('titleblacklist', 'result', 'blacklisted');
         // this is hardcoded to 'edit' in Titleblacklist.hooks.php, duplicating that.
         $message = $blacklisted->getErrorMessage('edit');
         $res->addValue('titleblacklist', 'reason', wfMessage($message, $result)->text());
         $res->addValue('titleblacklist', 'message', $message);
         $res->addValue('titleblacklist', 'line', htmlspecialchars($blacklisted->getRaw()));
     } else {
         // not blacklisted
         $this->getResult()->addValue('titleblacklist', 'result', 'ok');
     }
 }
Ejemplo n.º 21
0
 /**
  * @param $context IContextSource
  * @param $pageType
  */
 public static function addNavigationLinks(IContextSource $context, $pageType)
 {
     $linkDefs = array('home' => 'Special:AbuseFilter', 'recentchanges' => 'Special:AbuseFilter/history', 'examine' => 'Special:AbuseFilter/examine', 'log' => 'Special:AbuseLog');
     if ($context->getUser()->isAllowed('abusefilter-modify')) {
         $linkDefs = array_merge($linkDefs, array('test' => 'Special:AbuseFilter/test', 'tools' => 'Special:AbuseFilter/tools', 'import' => 'Special:AbuseFilter/import'));
     }
     // Save some translator work
     $msgOverrides = array('recentchanges' => 'abusefilter-filter-log');
     $links = array();
     foreach ($linkDefs as $name => $page) {
         // Give grep a chance to find the usages:
         // abusefilter-topnav-home, abusefilter-topnav-test, abusefilter-topnav-examine
         // abusefilter-topnav-log, abusefilter-topnav-tools, abusefilter-topnav-import
         $msgName = "abusefilter-topnav-{$name}";
         if (isset($msgOverrides[$name])) {
             $msgName = $msgOverrides[$name];
         }
         $msg = wfMessage($msgName)->parse();
         $title = Title::newFromText($page);
         if ($name == $pageType) {
             $links[] = Xml::tags('strong', null, $msg);
         } else {
             $links[] = Linker::link($title, $msg);
         }
     }
     $linkStr = wfMessage('parentheses', $context->getLanguage()->pipeList($links))->text();
     $linkStr = wfMessage('abusefilter-topnav')->parse() . " {$linkStr}";
     $linkStr = Xml::tags('div', array('class' => 'mw-abusefilter-navigation'), $linkStr);
     $context->getOutput()->setSubtitle($linkStr);
 }
Ejemplo n.º 22
0
 public function execute()
 {
     $search = null;
     extract($this->ExtractRequestParams());
     // Open search results may be stored for a very long time
     $this->getMain()->setCacheMaxAge(1200);
     $title = Title::newFromText($search);
     if (!$title) {
         return;
     }
     // Return empty result
     // Prepare nested request
     $params = new FauxRequest(array('action' => 'query', 'list' => 'allpages', 'apnamespace' => $title->getNamespace(), 'aplimit' => 10, 'apprefix' => $title->getDBkey()));
     // Execute
     $module = new ApiMain($params);
     $module->execute();
     // Get resulting data
     $data = $module->getResultData();
     // Reformat useful data for future printing by JSON engine
     $srchres = array();
     foreach ($data['query']['allpages'] as &$pageinfo) {
         // Note: this data will no be printable by the xml engine
         // because it does not support lists of unnamed items
         $srchres[] = $pageinfo['title'];
     }
     // Set top level elements
     $result = $this->getResult();
     $result->addValue(null, 0, $search);
     $result->addValue(null, 1, $srchres);
 }
 public function executeWordmark()
 {
     $themeSettings = new ThemeSettings();
     $settings = $themeSettings->getSettings();
     $this->wordmarkText = $settings['wordmark-text'];
     $this->wordmarkType = $settings['wordmark-type'];
     $this->wordmarkSize = $settings['wordmark-font-size'];
     $this->wordmarkFont = $settings['wordmark-font'];
     $this->wordmarkFontClass = !empty($settings["wordmark-font"]) ? "font-{$settings['wordmark-font']}" : '';
     $this->wordmarkUrl = '';
     if ($this->wordmarkType == "graphic") {
         wfProfileIn(__METHOD__ . 'graphicWordmark');
         $this->wordmarkUrl = $themeSettings->getWordmarkUrl();
         $imageTitle = Title::newFromText($themeSettings::WordmarkImageName, NS_IMAGE);
         if ($imageTitle instanceof Title) {
             $attributes = array();
             $file = wfFindFile($imageTitle);
             if ($file instanceof File) {
                 $attributes[] = 'width="' . $file->width . '"';
                 $attributes[] = 'height="' . $file->height . '"';
                 if (!empty($attributes)) {
                     $this->wordmarkStyle = ' ' . implode(' ', $attributes) . ' ';
                 }
             }
         }
         wfProfileOut(__METHOD__ . 'graphicWordmark');
     }
     $this->mainPageURL = Title::newMainPage()->getLocalURL();
 }
Ejemplo n.º 24
0
	public function getActionLinks() {
		if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) // Action is hidden
			|| $this->entry->getSubtype() !== 'move'
			|| !$this->context->getUser()->isAllowed( 'move' ) )
		{
			return '';
		}

		$params = $this->extractParameters();
		$destTitle = Title::newFromText( $params[3] );
		if ( !$destTitle ) {
			return '';
		}

		$revert = Linker::linkKnown(
			SpecialPage::getTitleFor( 'Movepage' ),
			$this->msg( 'revertmove' )->escaped(),
			array(),
			array(
				'wpOldTitle' => $destTitle->getPrefixedDBkey(),
				'wpNewTitle' => $this->entry->getTarget()->getPrefixedDBkey(),
				'wpReason' => $this->msg( 'revertmove' )->inContentLanguage()->text(),
				'wpMovetalk' => 0
			)
		);
		return $this->msg( 'parentheses' )->rawParams( $revert )->escaped();
	}
Ejemplo n.º 25
0
 public function execute()
 {
     global $wgUser;
     # Change to current working directory
     $oldCwd = getcwd();
     chdir($oldCwd);
     # Options processing
     $user = $this->getOption('u', 'Delete page script');
     $reason = $this->getOption('r', '');
     $interval = $this->getOption('i', 0);
     if ($this->hasArg()) {
         $file = fopen($this->getArg(), 'r');
     } else {
         $file = $this->getStdin();
     }
     # Setup
     if (!$file) {
         $this->error("Unable to read file, exiting", true);
     }
     $wgUser = User::newFromName($user);
     $dbw = wfGetDB(DB_MASTER);
     # Handle each entry
     for ($linenum = 1; !feof($file); $linenum++) {
         $line = trim(fgets($file));
         if ($line == '') {
             continue;
         }
         $page = Title::newFromText($line);
         if (is_null($page)) {
             $this->output("Invalid title '{$line}' on line {$linenum}\n");
             continue;
         }
         if (!$page->exists()) {
             $this->output("Skipping nonexistent page '{$line}'\n");
             continue;
         }
         $this->output($page->getPrefixedText());
         $dbw->begin();
         if ($page->getNamespace() == NS_FILE) {
             $art = new ImagePage($page);
             $img = wfFindFile($art->mTitle);
             if (!$img || !$img->isLocal() || !$img->delete($reason)) {
                 $this->output(" FAILED to delete image file... ");
             }
         } else {
             $art = new Article($page);
         }
         $success = $art->doDeleteArticle($reason);
         $dbw->commit();
         if ($success) {
             $this->output(" Deleted!\n");
         } else {
             $this->output(" FAILED to delete article\n");
         }
         if ($interval) {
             sleep($interval);
         }
         wfWaitForSlaves();
     }
 }
 /**
  * Get list of links for given username to be shown as tabs
  */
 private function getTabs($userName)
 {
     wfProfileIn(__METHOD__);
     global $wgTitle, $wgEnableWikiaFollowedPages;
     $tabs = array();
     $namespace = $wgTitle->getNamespace();
     // profile
     $tabs[] = array('link' => Wikia::link(Title::newFromText($userName, NS_USER), wfMsg('profile')), 'selected' => $namespace == NS_USER, 'data-id' => 'profile');
     // talk
     $tabs[] = array('link' => Wikia::link(Title::newFromText($userName, NS_USER_TALK), wfMsg('talkpage')), 'selected' => $namespace == NS_USER_TALK, 'data-id' => 'talk');
     // blog
     if (defined('NS_BLOG_ARTICLE') && !User::isIP($this->userName)) {
         $tabs[] = array('link' => Wikia::link(Title::newFromText($userName, NS_BLOG_ARTICLE), wfMsg('blog-page'), array(), array(), 'known'), 'selected' => $namespace == NS_BLOG_ARTICLE, 'data-id' => 'blog');
     }
     // contribs
     $tabs[] = array('link' => Wikia::link(SpecialPage::getTitleFor("Contributions/{$userName}"), wfMsg('contris_s')), 'selected' => $wgTitle->isSpecial('Contributions'), 'data-id' => 'contribs');
     if (self::isItMe($userName)) {
         // following (only render when user is viewing his own user pages)
         if (!empty($wgEnableWikiaFollowedPages)) {
             $tabs[] = array('link' => Wikia::link(SpecialPage::getTitleFor('Following'), wfMsg('wikiafollowedpages-following')), 'selected' => $wgTitle->isSpecial('Following'), 'data-id' => 'following');
         }
         // avatar dropdown menu
         $this->avatarMenu = array(Wikia::link(SpecialPage::getTitleFor('Preferences'), wfMsg('oasis-user-page-change-avatar')));
     }
     wfRunHooks('UserPagesHeaderModuleAfterGetTabs', array(&$tabs, $namespace, $userName));
     wfProfileOut(__METHOD__);
     return $tabs;
 }
Ejemplo n.º 27
0
 public function execute()
 {
     // Cache may vary on $wgUser because ParserOptions gets data from it
     $this->getMain()->setCacheMode('anon-public-user-private');
     // Get parameters
     $params = $this->extractRequestParams();
     //Create title for parser
     $title_obj = Title::newFromText($params['title']);
     if (!$title_obj) {
         $title_obj = Title::newFromText("API");
     }
     // default
     $result = $this->getResult();
     // Parse text
     global $wgParser;
     $options = new ParserOptions();
     if ($params['generatexml']) {
         $wgParser->startExternalParse($title_obj, $options, OT_PREPROCESS);
         $dom = $wgParser->preprocessToDom($params['text']);
         if (is_callable(array($dom, 'saveXML'))) {
             $xml = $dom->saveXML();
         } else {
             $xml = $dom->__toString();
         }
         $xml_result = array();
         $result->setContent($xml_result, $xml);
         $result->addValue(null, 'parsetree', $xml_result);
     }
     $retval = $wgParser->preprocess($params['text'], $title_obj, $options);
     // Return result
     $retval_array = array();
     $result->setContent($retval_array, $retval);
     $result->addValue(null, $this->getModuleName(), $retval_array);
 }
Ejemplo n.º 28
0
 /**
  * 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;
 }
Ejemplo n.º 29
0
 /**
  * Purge URL coming from stdin
  */
 private function doPurge()
 {
     $stdin = $this->getStdin();
     $urls = array();
     while (!feof($stdin)) {
         $page = trim(fgets($stdin));
         if (preg_match('%^https?://%', $page)) {
             $urls[] = $page;
         } elseif ($page !== '') {
             $title = Title::newFromText($page);
             if ($title) {
                 $url = $title->getInternalURL();
                 $this->output("{$url}\n");
                 $urls[] = $url;
                 if ($this->getOption('purge')) {
                     $title->invalidateCache();
                 }
             } else {
                 $this->output("(Invalid title '{$page}')\n");
             }
         }
     }
     $this->output("Purging " . count($urls) . " urls\n");
     $this->sendPurgeRequest($urls);
 }
Ejemplo n.º 30
0
 /**
  * Purges the cache of a page
  */
 public function execute()
 {
     global $wgUser;
     $params = $this->extractRequestParams();
     if (!$wgUser->isAllowed('purge')) {
         $this->dieUsageMsg(array('cantpurge'));
     }
     if (!isset($params['titles'])) {
         $this->dieUsageMsg(array('missingparam', 'titles'));
     }
     $result = array();
     foreach ($params['titles'] as $t) {
         $r = array();
         $title = Title::newFromText($t);
         if (!$title instanceof Title) {
             $r['title'] = $t;
             $r['invalid'] = '';
             $result[] = $r;
             continue;
         }
         ApiQueryBase::addTitleInfo($r, $title);
         if (!$title->exists()) {
             $r['missing'] = '';
             $result[] = $r;
             continue;
         }
         $article = new Article($title);
         $article->doPurge();
         // Directly purge and skip the UI part of purge().
         $r['purged'] = '';
         $result[] = $r;
     }
     $this->getResult()->setIndexedTagName($result, 'page');
     $this->getResult()->addValue(null, $this->getModuleName(), $result);
 }