/** * @param $skin DummyLinker * @param $target Title * @param $text String * @param $customAttribs array * @param $query array * @param $options string|array * @param $ret * @return bool */ function efCategoryBlueLinks($skin, $target, &$text, &$customAttribs, &$query, &$options, &$ret) { // paranoia if (is_null($target)) { return true; } // only affects non-existing Category pages that has content if ($target->exists() || $target->getNamespace() != NS_CATEGORY || Category::newFromTitle($target)->getPageCount() == 0) { return true; } // remove "broken" assumption/override $brokenKey = array_search('broken', $options); if ($brokenKey !== false) { unset($options[$brokenKey]); } // make the link "blue" $options[] = 'known'; // add a class to identify non-existing links, in case we (or our users) want to modify display if (array_key_exists('class', $customAttribs)) { $customAttribs['class'] = $customAttribs['class'] . ' newcategory'; } else { $customAttribs['class'] = 'newcategory'; } return true; }
/** * set appropriate status code for deleted pages * * @author ADi * @author Władysław Bodzek <*****@*****.**> * @param Title $title * @param Article $article * @return bool */ public static function onAfterInitialize(&$title, &$article, &$output) { if (!$title->exists() && $title->isDeleted()) { $setDeletedStatusCode = true; // handle special cases switch ($title->getNamespace()) { case NS_CATEGORY: // skip non-empty categories if (Category::newFromTitle($title)->getPageCount() > 0) { $setDeletedStatusCode = false; } break; case NS_FILE: // skip existing file with deleted description $file = wfFindFile($title); if ($file && $file->exists()) { $setDeletedStatusCode = false; } break; } if ($setDeletedStatusCode) { $output->setStatusCode(SEOTweaksHooksHelper::DELETED_PAGES_STATUS_CODE); } } return true; }
/** * Don't return a 404 for categories in use. */ function hasViewableContent() { if (parent::hasViewableContent()) { return true; } else { $cat = Category::newFromTitle($this->mTitle); return $cat->getId() != 0; } }
function __construct($title, $from = '', $until = '') { global $wgCategoryPagingLimit; $this->title = $title; $this->from = $from; $this->until = $until; $this->limit = $wgCategoryPagingLimit; $this->cat = Category::newFromTitle($title); }
/** * @since 1.19 $context is a second, required parameter * @param Title $title * @param IContextSource $context * @param array $from An array with keys page, subcat, * and file for offset of results of each section (since 1.17) * @param array $until An array with 3 keys for until of each section (since 1.17) * @param array $query */ function __construct($title, IContextSource $context, $from = array(), $until = array(), $query = array()) { $this->title = $title; $this->setContext($context); $this->from = $from; $this->until = $until; $this->limit = $context->getConfig()->get('CategoryPagingLimit'); $this->cat = Category::newFromTitle($title); $this->query = $query; $this->collation = Collation::singleton(); unset($this->query['title']); }
/** * Don't return a 404 for categories in use. * In use defined as: either the actual page exists * or the category currently has members. */ public function hasViewableContent() { if (parent::hasViewableContent()) { return true; } else { $cat = Category::newFromTitle($this->mTitle); // If any of these are not 0, then has members if ($cat->getPageCount() || $cat->getSubcatCount() || $cat->getFileCount()) { return true; } } return false; }
/** * @since 1.19 $context is a second, required parameter * @param Title $title * @param IContextSource $context * @param array $from An array with keys page, subcat, * and file for offset of results of each section (since 1.17) * @param array $until An array with 3 keys for until of each section (since 1.17) * @param array $query */ function __construct($title, IContextSource $context, $from = array(), $until = array(), $query = array()) { $this->title = $title; $this->setContext($context); $this->getOutput()->addModuleStyles(array('mediawiki.action.view.categoryPage.styles')); $this->from = $from; $this->until = $until; $this->limit = $context->getConfig()->get('CategoryPagingLimit'); $this->cat = Category::newFromTitle($title); $this->query = $query; $this->collation = Collation::singleton(); unset($this->query['title']); }
public function pagesInCategory($category = null, $which = null) { $this->checkType('pagesInCategory', 1, $category, 'string'); $this->checkTypeOptional('pagesInCategory', 2, $which, 'string', 'all'); $title = Title::makeTitleSafe(NS_CATEGORY, $category); if (!$title) { return array(0); } $cacheKey = $title->getDBkey(); if (!isset($this->pagesInCategoryCache[$cacheKey])) { $this->incrementExpensiveFunctionCount(); $category = Category::newFromTitle($title); $counts = array('all' => (int) $category->getPageCount(), 'subcats' => (int) $category->getSubcatCount(), 'files' => (int) $category->getFileCount()); $counts['pages'] = $counts['all'] - $counts['subcats'] - $counts['files']; $this->pagesInCategoryCache[$cacheKey] = $counts; } if ($which === '*') { return array($this->pagesInCategoryCache[$cacheKey]); } if (!isset($this->pagesInCategoryCache[$cacheKey][$which])) { $this->checkType('pagesInCategory', 2, $which, "one of '*', 'all', 'pages', 'subcats', or 'files'"); } return array($this->pagesInCategoryCache[$cacheKey][$which]); }
/** * Add a subcategory to the internal lists, using a title object * @deprecated since 1.17 kept for compatibility, please use addSubcategoryObject instead */ function addSubcategory(Title $title, $sortkey, $pageLength) { wfDeprecated(__METHOD__, '1.17'); $this->addSubcategoryObject(Category::newFromTitle($title), $sortkey, $pageLength); }
/** * Format a single hit result * * @param $result SearchResult * @param array $terms terms to highlight * * @return string */ protected function showHit( $result, $terms ) { wfProfileIn( __METHOD__ ); if ( $result->isBrokenTitle() ) { wfProfileOut( __METHOD__ ); return "<!-- Broken link in search result -->\n"; } $t = $result->getTitle(); $titleSnippet = $result->getTitleSnippet( $terms ); if ( $titleSnippet == '' ) { $titleSnippet = null; } $link_t = clone $t; wfRunHooks( 'ShowSearchHitTitle', array( &$link_t, &$titleSnippet, $result, $terms, $this ) ); $link = Linker::linkKnown( $link_t, $titleSnippet ); //If page content is not readable, just return the title. //This is not quite safe, but better than showing excerpts from non-readable pages //Note that hiding the entry entirely would screw up paging. if ( !$t->userCan( 'read', $this->getUser() ) ) { wfProfileOut( __METHOD__ ); return "<li>{$link}</li>\n"; } // If the page doesn't *exist*... our search index is out of date. // The least confusing at this point is to drop the result. // You may get less results, but... oh well. :P if ( $result->isMissingRevision() ) { wfProfileOut( __METHOD__ ); return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n"; } // format redirects / relevant sections $redirectTitle = $result->getRedirectTitle(); $redirectText = $result->getRedirectSnippet( $terms ); $sectionTitle = $result->getSectionTitle(); $sectionText = $result->getSectionSnippet( $terms ); $redirect = ''; if ( !is_null( $redirectTitle ) ) { if ( $redirectText == '' ) { $redirectText = null; } $redirect = "<span class='searchalttitle'>" . $this->msg( 'search-redirect' )->rawParams( Linker::linkKnown( $redirectTitle, $redirectText ) )->text() . "</span>"; } $section = ''; if ( !is_null( $sectionTitle ) ) { if ( $sectionText == '' ) { $sectionText = null; } $section = "<span class='searchalttitle'>" . $this->msg( 'search-section' )->rawParams( Linker::linkKnown( $sectionTitle, $sectionText ) )->text() . "</span>"; } // format text extract $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>"; $lang = $this->getLanguage(); // format score if ( is_null( $result->getScore() ) ) { // Search engine doesn't report scoring info $score = ''; } else { $percent = sprintf( '%2.1f', $result->getScore() * 100 ); $score = $this->msg( 'search-result-score' )->numParams( $percent )->text() . ' - '; } // format description $byteSize = $result->getByteSize(); $wordCount = $result->getWordCount(); $timestamp = $result->getTimestamp(); $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) ) ->numParams( $wordCount )->escaped(); if ( $t->getNamespace() == NS_CATEGORY ) { $cat = Category::newFromTitle( $t ); $size = $this->msg( 'search-result-category-size' ) ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() ) ->escaped(); } $date = $lang->userTimeAndDate( $timestamp, $this->getUser() ); // link to related articles if supported $related = ''; if ( $result->hasRelated() ) { $st = SpecialPage::getTitleFor( 'Search' ); $stParams = array_merge( $this->powerSearchOptions(), array( 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() . ':' . $t->getPrefixedText(), 'fulltext' => $this->msg( 'search' )->text() ) ); $related = ' -- ' . Linker::linkKnown( $st, $this->msg( 'search-relatedarticle' )->text(), array(), $stParams ); } // Include a thumbnail for media files... if ( $t->getNamespace() == NS_FILE ) { $img = wfFindFile( $t ); if ( $img ) { $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) ); if ( $thumb ) { $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped(); wfProfileOut( __METHOD__ ); // Float doesn't seem to interact well with the bullets. // Table messes up vertical alignment of the bullets. // Bullets are therefore disabled (didn't look great anyway). return "<li>" . '<table class="searchResultImage">' . '<tr>' . '<td style="width: 120px; text-align: center; vertical-align: top;">' . $thumb->toHtml( array( 'desc-link' => true ) ) . '</td>' . '<td style="vertical-align: top;">' . $link . $extract . "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" . '</td>' . '</tr>' . '</table>' . "</li>\n"; } } } $html = null; if ( wfRunHooks( 'ShowSearchHit', array( $this, $result, $terms, &$link, &$redirect, &$section, &$extract, &$score, &$size, &$date, &$related, &$html ) ) ) { $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" . "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" . "</li>\n"; } wfProfileOut( __METHOD__ ); return $html; }
/** * Add a subcategory to the internal lists, using a title object * @deprecated kept for compatibility, please use addSubcategoryObject instead */ function addSubcategory(Title $title, $sortkey, $pageLength) { $this->addSubcategoryObject(Category::newFromTitle($title), $sortkey, $pageLength); }
/** * Returns a string with a HTML represenation of the given page. * @param $title Title * @param int $children * @param bool $loadchildren * @return string */ function renderNode($title, $children = 0, $loadchildren = false) { global $wgCategoryTreeUseCategoryTable; if ($wgCategoryTreeUseCategoryTable && $title->getNamespace() == NS_CATEGORY && !$this->isInverse()) { $cat = Category::newFromTitle($title); } else { $cat = null; } return $this->renderNodeInfo($title, $cat, $children, $loadchildren); }
/** * Returns page information in an easily-manipulated format. Array keys are used so extensions * may add additional information in arbitrary positions. Array values are arrays with one * element to be rendered as a header, arrays with two elements to be rendered as a table row. * * @return array */ protected function pageInfo() { global $wgContLang; $user = $this->getUser(); $lang = $this->getLanguage(); $title = $this->getTitle(); $id = $title->getArticleID(); $config = $this->context->getConfig(); $cache = ObjectCache::getMainWANInstance(); $memcKey = wfMemcKey('infoaction', sha1($title->getPrefixedText()), $this->page->getLatest()); $pageCounts = $cache->get($memcKey); $version = isset($pageCounts['cacheversion']) ? $pageCounts['cacheversion'] : false; if ($pageCounts === false || $version !== self::CACHE_VERSION) { // Get page information that would be too "expensive" to retrieve by normal means $pageCounts = $this->pageCounts($title); $pageCounts['cacheversion'] = self::CACHE_VERSION; $cache->set($memcKey, $pageCounts); } // Get page properties $dbr = wfGetDB(DB_SLAVE); $result = $dbr->select('page_props', array('pp_propname', 'pp_value'), array('pp_page' => $id), __METHOD__); $pageProperties = array(); foreach ($result as $row) { $pageProperties[$row->pp_propname] = $row->pp_value; } // Basic information $pageInfo = array(); $pageInfo['header-basic'] = array(); // Display title $displayTitle = $title->getPrefixedText(); if (isset($pageProperties['displaytitle'])) { $displayTitle = $pageProperties['displaytitle']; } $pageInfo['header-basic'][] = array($this->msg('pageinfo-display-title'), $displayTitle); // Is it a redirect? If so, where to? if ($title->isRedirect()) { $pageInfo['header-basic'][] = array($this->msg('pageinfo-redirectsto'), Linker::link($this->page->getRedirectTarget()) . $this->msg('word-separator')->escaped() . $this->msg('parentheses')->rawParams(Linker::link($this->page->getRedirectTarget(), $this->msg('pageinfo-redirectsto-info')->escaped(), array(), array('action' => 'info')))->escaped()); } // Default sort key $sortKey = $title->getCategorySortkey(); if (isset($pageProperties['defaultsort'])) { $sortKey = $pageProperties['defaultsort']; } $sortKey = htmlspecialchars($sortKey); $pageInfo['header-basic'][] = array($this->msg('pageinfo-default-sort'), $sortKey); // Page length (in bytes) $pageInfo['header-basic'][] = array($this->msg('pageinfo-length'), $lang->formatNum($title->getLength())); // Page ID (number not localised, as it's a database ID) $pageInfo['header-basic'][] = array($this->msg('pageinfo-article-id'), $id); // Language in which the page content is (supposed to be) written $pageLang = $title->getPageLanguage()->getCode(); if ($config->get('PageLanguageUseDB') && $this->getTitle()->userCan('pagelang', $this->getUser())) { // Link to Special:PageLanguage with pre-filled page title if user has permissions $titleObj = SpecialPage::getTitleFor('PageLanguage', $title->getPrefixedText()); $langDisp = Linker::link($titleObj, $this->msg('pageinfo-language')->escaped()); } else { // Display just the message $langDisp = $this->msg('pageinfo-language')->escaped(); } $pageInfo['header-basic'][] = array($langDisp, Language::fetchLanguageName($pageLang, $lang->getCode()) . ' ' . $this->msg('parentheses', $pageLang)->escaped()); // Content model of the page $pageInfo['header-basic'][] = array($this->msg('pageinfo-content-model'), htmlspecialchars(ContentHandler::getLocalizedName($title->getContentModel()))); // Search engine status $pOutput = new ParserOutput(); if (isset($pageProperties['noindex'])) { $pOutput->setIndexPolicy('noindex'); } if (isset($pageProperties['index'])) { $pOutput->setIndexPolicy('index'); } // Use robot policy logic $policy = $this->page->getRobotPolicy('view', $pOutput); $pageInfo['header-basic'][] = array($this->msg('pageinfo-robot-policy'), $this->msg("pageinfo-robot-{$policy['index']}")); $unwatchedPageThreshold = $config->get('UnwatchedPageThreshold'); if ($user->isAllowed('unwatchedpages') || $unwatchedPageThreshold !== false && $pageCounts['watchers'] >= $unwatchedPageThreshold) { // Number of page watchers $pageInfo['header-basic'][] = array($this->msg('pageinfo-watchers'), $lang->formatNum($pageCounts['watchers'])); if ($config->get('ShowUpdatedMarker') && isset($pageCounts['visitingWatchers'])) { $minToDisclose = $config->get('UnwatchedPageSecret'); if ($pageCounts['visitingWatchers'] > $minToDisclose || $user->isAllowed('unwatchedpages')) { $pageInfo['header-basic'][] = array($this->msg('pageinfo-visiting-watchers'), $lang->formatNum($pageCounts['visitingWatchers'])); } else { $pageInfo['header-basic'][] = array($this->msg('pageinfo-visiting-watchers'), $this->msg('pageinfo-few-visiting-watchers')); } } } elseif ($unwatchedPageThreshold !== false) { $pageInfo['header-basic'][] = array($this->msg('pageinfo-watchers'), $this->msg('pageinfo-few-watchers')->numParams($unwatchedPageThreshold)); } // Redirects to this page $whatLinksHere = SpecialPage::getTitleFor('Whatlinkshere', $title->getPrefixedText()); $pageInfo['header-basic'][] = array(Linker::link($whatLinksHere, $this->msg('pageinfo-redirects-name')->escaped(), array(), array('hidelinks' => 1, 'hidetrans' => 1, 'hideimages' => $title->getNamespace() == NS_FILE)), $this->msg('pageinfo-redirects-value')->numParams(count($title->getRedirectsHere()))); // Is it counted as a content page? if ($this->page->isCountable()) { $pageInfo['header-basic'][] = array($this->msg('pageinfo-contentpage'), $this->msg('pageinfo-contentpage-yes')); } // Subpages of this page, if subpages are enabled for the current NS if (MWNamespace::hasSubpages($title->getNamespace())) { $prefixIndex = SpecialPage::getTitleFor('Prefixindex', $title->getPrefixedText() . '/'); $pageInfo['header-basic'][] = array(Linker::link($prefixIndex, $this->msg('pageinfo-subpages-name')->escaped()), $this->msg('pageinfo-subpages-value')->numParams($pageCounts['subpages']['total'], $pageCounts['subpages']['redirects'], $pageCounts['subpages']['nonredirects'])); } if ($title->inNamespace(NS_CATEGORY)) { $category = Category::newFromTitle($title); // $allCount is the total number of cat members, // not the count of how many members are normal pages. $allCount = (int) $category->getPageCount(); $subcatCount = (int) $category->getSubcatCount(); $fileCount = (int) $category->getFileCount(); $pagesCount = $allCount - $subcatCount - $fileCount; $pageInfo['category-info'] = array(array($this->msg('pageinfo-category-total'), $lang->formatNum($allCount)), array($this->msg('pageinfo-category-pages'), $lang->formatNum($pagesCount)), array($this->msg('pageinfo-category-subcats'), $lang->formatNum($subcatCount)), array($this->msg('pageinfo-category-files'), $lang->formatNum($fileCount))); } // Page protection $pageInfo['header-restrictions'] = array(); // Is this page affected by the cascading protection of something which includes it? if ($title->isCascadeProtected()) { $cascadingFrom = ''; $sources = $title->getCascadeProtectionSources(); // Array deferencing is in PHP 5.4 :( foreach ($sources[0] as $sourceTitle) { $cascadingFrom .= Html::rawElement('li', array(), Linker::linkKnown($sourceTitle)); } $cascadingFrom = Html::rawElement('ul', array(), $cascadingFrom); $pageInfo['header-restrictions'][] = array($this->msg('pageinfo-protect-cascading-from'), $cascadingFrom); } // Is out protection set to cascade to other pages? if ($title->areRestrictionsCascading()) { $pageInfo['header-restrictions'][] = array($this->msg('pageinfo-protect-cascading'), $this->msg('pageinfo-protect-cascading-yes')); } // Page protection foreach ($title->getRestrictionTypes() as $restrictionType) { $protectionLevel = implode(', ', $title->getRestrictions($restrictionType)); if ($protectionLevel == '') { // Allow all users $message = $this->msg('protect-default')->escaped(); } else { // Administrators only // Messages: protect-level-autoconfirmed, protect-level-sysop $message = $this->msg("protect-level-{$protectionLevel}"); if ($message->isDisabled()) { // Require "$1" permission $message = $this->msg("protect-fallback", $protectionLevel)->parse(); } else { $message = $message->escaped(); } } $expiry = $title->getRestrictionExpiry($restrictionType); $formattedexpiry = $this->msg('parentheses', $this->getLanguage()->formatExpiry($expiry))->escaped(); $message .= $this->msg('word-separator')->escaped() . $formattedexpiry; // Messages: restriction-edit, restriction-move, restriction-create, // restriction-upload $pageInfo['header-restrictions'][] = array($this->msg("restriction-{$restrictionType}"), $message); } if (!$this->page->exists()) { return $pageInfo; } // Edit history $pageInfo['header-edits'] = array(); $firstRev = $this->page->getOldestRevision(); $lastRev = $this->page->getRevision(); $batch = new LinkBatch(); if ($firstRev) { $firstRevUser = $firstRev->getUserText(Revision::FOR_THIS_USER); if ($firstRevUser !== '') { $batch->add(NS_USER, $firstRevUser); $batch->add(NS_USER_TALK, $firstRevUser); } } if ($lastRev) { $lastRevUser = $lastRev->getUserText(Revision::FOR_THIS_USER); if ($lastRevUser !== '') { $batch->add(NS_USER, $lastRevUser); $batch->add(NS_USER_TALK, $lastRevUser); } } $batch->execute(); if ($firstRev) { // Page creator $pageInfo['header-edits'][] = array($this->msg('pageinfo-firstuser'), Linker::revUserTools($firstRev)); // Date of page creation $pageInfo['header-edits'][] = array($this->msg('pageinfo-firsttime'), Linker::linkKnown($title, htmlspecialchars($lang->userTimeAndDate($firstRev->getTimestamp(), $user)), array(), array('oldid' => $firstRev->getId()))); } if ($lastRev) { // Latest editor $pageInfo['header-edits'][] = array($this->msg('pageinfo-lastuser'), Linker::revUserTools($lastRev)); // Date of latest edit $pageInfo['header-edits'][] = array($this->msg('pageinfo-lasttime'), Linker::linkKnown($title, htmlspecialchars($lang->userTimeAndDate($this->page->getTimestamp(), $user)), array(), array('oldid' => $this->page->getLatest()))); } // Total number of edits $pageInfo['header-edits'][] = array($this->msg('pageinfo-edits'), $lang->formatNum($pageCounts['edits'])); // Total number of distinct authors if ($pageCounts['authors'] > 0) { $pageInfo['header-edits'][] = array($this->msg('pageinfo-authors'), $lang->formatNum($pageCounts['authors'])); } // Recent number of edits (within past 30 days) $pageInfo['header-edits'][] = array($this->msg('pageinfo-recent-edits', $lang->formatDuration($config->get('RCMaxAge'))), $lang->formatNum($pageCounts['recent_edits'])); // Recent number of distinct authors $pageInfo['header-edits'][] = array($this->msg('pageinfo-recent-authors'), $lang->formatNum($pageCounts['recent_authors'])); // Array of MagicWord objects $magicWords = MagicWord::getDoubleUnderscoreArray(); // Array of magic word IDs $wordIDs = $magicWords->names; // Array of IDs => localized magic words $localizedWords = $wgContLang->getMagicWords(); $listItems = array(); foreach ($pageProperties as $property => $value) { if (in_array($property, $wordIDs)) { $listItems[] = Html::element('li', array(), $localizedWords[$property][1]); } } $localizedList = Html::rawElement('ul', array(), implode('', $listItems)); $hiddenCategories = $this->page->getHiddenCategories(); if (count($listItems) > 0 || count($hiddenCategories) > 0 || $pageCounts['transclusion']['from'] > 0 || $pageCounts['transclusion']['to'] > 0) { $options = array('LIMIT' => $config->get('PageInfoTransclusionLimit')); $transcludedTemplates = $title->getTemplateLinksFrom($options); if ($config->get('MiserMode')) { $transcludedTargets = array(); } else { $transcludedTargets = $title->getTemplateLinksTo($options); } // Page properties $pageInfo['header-properties'] = array(); // Magic words if (count($listItems) > 0) { $pageInfo['header-properties'][] = array($this->msg('pageinfo-magic-words')->numParams(count($listItems)), $localizedList); } // Hidden categories if (count($hiddenCategories) > 0) { $pageInfo['header-properties'][] = array($this->msg('pageinfo-hidden-categories')->numParams(count($hiddenCategories)), Linker::formatHiddenCategories($hiddenCategories)); } // Transcluded templates if ($pageCounts['transclusion']['from'] > 0) { if ($pageCounts['transclusion']['from'] > count($transcludedTemplates)) { $more = $this->msg('morenotlisted')->escaped(); } else { $more = null; } $pageInfo['header-properties'][] = array($this->msg('pageinfo-templates')->numParams($pageCounts['transclusion']['from']), Linker::formatTemplates($transcludedTemplates, false, false, $more)); } if (!$config->get('MiserMode') && $pageCounts['transclusion']['to'] > 0) { if ($pageCounts['transclusion']['to'] > count($transcludedTargets)) { $more = Linker::link($whatLinksHere, $this->msg('moredotdotdot')->escaped(), array(), array('hidelinks' => 1, 'hideredirs' => 1)); } else { $more = null; } $pageInfo['header-properties'][] = array($this->msg('pageinfo-transclusions')->numParams($pageCounts['transclusion']['to']), Linker::formatTemplates($transcludedTargets, false, false, $more)); } } return $pageInfo; }
/** * Format a single hit result * * @param SearchResult $result * @param array $terms Terms to highlight * * @return string */ protected function showHit($result, $terms) { if ($result->isBrokenTitle()) { return ''; } $title = $result->getTitle(); $titleSnippet = $result->getTitleSnippet(); if ($titleSnippet == '') { $titleSnippet = null; } $link_t = clone $title; Hooks::run('ShowSearchHitTitle', array(&$link_t, &$titleSnippet, $result, $terms, $this)); $link = Linker::linkKnown($link_t, $titleSnippet); //If page content is not readable, just return the title. //This is not quite safe, but better than showing excerpts from non-readable pages //Note that hiding the entry entirely would screw up paging. if (!$title->userCan('read', $this->getUser())) { return "<li>{$link}</li>\n"; } // If the page doesn't *exist*... our search index is out of date. // The least confusing at this point is to drop the result. // You may get less results, but... oh well. :P if ($result->isMissingRevision()) { return ''; } // format redirects / relevant sections $redirectTitle = $result->getRedirectTitle(); $redirectText = $result->getRedirectSnippet(); $sectionTitle = $result->getSectionTitle(); $sectionText = $result->getSectionSnippet(); $categorySnippet = $result->getCategorySnippet(); $redirect = ''; if (!is_null($redirectTitle)) { if ($redirectText == '') { $redirectText = null; } $redirect = "<span class='searchalttitle'>" . $this->msg('search-redirect')->rawParams(Linker::linkKnown($redirectTitle, $redirectText))->text() . "</span>"; } $section = ''; if (!is_null($sectionTitle)) { if ($sectionText == '') { $sectionText = null; } $section = "<span class='searchalttitle'>" . $this->msg('search-section')->rawParams(Linker::linkKnown($sectionTitle, $sectionText))->text() . "</span>"; } $category = ''; if ($categorySnippet) { $category = "<span class='searchalttitle'>" . $this->msg('search-category')->rawParams($categorySnippet)->text() . "</span>"; } // format text extract $extract = "<div class='searchresult'>" . $result->getTextSnippet($terms) . "</div>"; $lang = $this->getLanguage(); // format description $byteSize = $result->getByteSize(); $wordCount = $result->getWordCount(); $timestamp = $result->getTimestamp(); $size = $this->msg('search-result-size', $lang->formatSize($byteSize))->numParams($wordCount)->escaped(); if ($title->getNamespace() == NS_CATEGORY) { $cat = Category::newFromTitle($title); $size = $this->msg('search-result-category-size')->numParams($cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount())->escaped(); } $date = $lang->userTimeAndDate($timestamp, $this->getUser()); $fileMatch = ''; // Include a thumbnail for media files... if ($title->getNamespace() == NS_FILE) { $img = $result->getFile(); $img = $img ?: wfFindFile($title); if ($result->isFileMatch()) { $fileMatch = "<span class='searchalttitle'>" . $this->msg('search-file-match')->escaped() . "</span>"; } if ($img) { $thumb = $img->transform(array('width' => 120, 'height' => 120)); if ($thumb) { $desc = $this->msg('parentheses')->rawParams($img->getShortDesc())->escaped(); // Float doesn't seem to interact well with the bullets. // Table messes up vertical alignment of the bullets. // Bullets are therefore disabled (didn't look great anyway). return "<li>" . '<table class="searchResultImage">' . '<tr>' . '<td style="width: 120px; text-align: center; vertical-align: top;">' . $thumb->toHtml(array('desc-link' => true)) . '</td>' . '<td style="vertical-align: top;">' . "{$link} {$redirect} {$category} {$section} {$fileMatch}" . $extract . "<div class='mw-search-result-data'>{$desc} - {$date}</div>" . '</td>' . '</tr>' . '</table>' . "</li>\n"; } } } $html = null; $score = ''; if (Hooks::run('ShowSearchHit', array($this, $result, $terms, &$link, &$redirect, &$section, &$extract, &$score, &$size, &$date, &$related, &$html))) { $html = "<li><div class='mw-search-result-heading'>" . "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" . "<div class='mw-search-result-data'>{$size} - {$date}</div>" . "</li>\n"; } return $html; }
public function getUploadedMediaCount() { return Category::newFromTitle($this->getTrackingCategory())->getFileCount(); }
public function getBatch() { //see Category::newFromName for valid format $categoryName = str_replace(' ', '_', $this->request->getVal('category')); $index = $this->request->getVal('index'); $batch = $this->request->getInt('batch'); $err = false; if (!empty($categoryName) && isset($index) && !empty($batch)) { $category = Category::newFromTitle(Title::newFromText($categoryName, NS_CATEGORY)); if ($category instanceof Category) { $this->initModel(); $data = wfPaginateArray($this->model->getCollection($category)['items'][$index], WikiaMobileCategoryModel::BATCH_SIZE, $batch); if (!empty($data['items'])) { //cache response for 3 hours in varnish and browser $this->response->setCacheValidity(WikiaMobileCategoryService::CACHE_TIME); $this->response->setVal('itemsBatch', $data['items']); } else { $err = "No Data for given index or batch"; } } else { $err = "Wrong category"; } } else { $err = "Wrong values given"; } if ($err) { Wikia::log(__METHOD__, false, "Error loading batch {$batch} for index {$index} in Category {$categoryName}. Msg: {$err}"); header('Status: 404 Not Found', true, 404); } }
/** * The onArticle*() functions are supposed to be a kind of hooks * which should be called whenever any of the specified actions * are done. * * This is a good place to put code to clear caches, for instance. * * This is called on page move and undelete, as well as edit * * @param Title $title */ public static function onArticleCreate(Title $title) { // Update existence markers on article/talk tabs... $other = $title->getOtherPage(); $other->purgeSquid(); $title->touchLinks(); $title->purgeSquid(); $title->deleteTitleProtection(); MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle($title); if ($title->getNamespace() == NS_CATEGORY) { // Load the Category object, which will schedule a job to create // the category table row if necessary. Checking a replica DB is ok // here, in the worst case it'll run an unnecessary recount job on // a category that probably doesn't have many members. Category::newFromTitle($title)->getID(); } }
/** * @param $article Article * * @return bool */ public static function onBeforeDisplayNoArticleText($article) { wfProfileIn(__METHOD__); if (F::app()->checkSkin('wikiamobile')) { $title = $article->getTitle(); $ns = $title->getNamespace(); if ($ns == NS_USER) { //if user exists and it is not subpage display masthead //otherwise show 404 page $user = User::newFromName($title->getBaseText()); if ($user instanceof User && $user->getId() > 0 && !$title->isSubpage()) { wfProfileOut(__METHOD__); return true; } } else { if ($ns == NS_CATEGORY) { //if it is a category that has some pages display it as well $category = Category::newFromTitle($title); if ($category instanceof Category && $category->getPageCount() + $category->getSubcatCount() + $category->getFileCount() > 0) { wfProfileOut(__METHOD__); return true; } //Do not show error on non-blank help pages (including shared help) } else { if ($ns == NS_HELP && ($title->isKnown() || is_callable('SharedHelpArticleExists') && SharedHelpArticleExists($title))) { wfProfileOut(__METHOD__); return true; } } } WikiaMobileErrorService::$displayErrorPage = true; } wfProfileOut(__METHOD__); return true; }
private function getInfoFromRow(&$row) { $title = Title::newFromText($row['title']); if (!empty($title)) { $articleId = $title->getArticleId(); $namespaceId = $title->getNamespace(); $type = $this->getType($namespaceId); $image_id = (int) $row['image_id']; $info = []; switch ($type) { case self::STR_FILE: list($type, $info) = $this->getVideoInfo($title); break; case self::STR_CATEGORY: $category = Category::newFromTitle($title); if (!empty($category)) { $count = $category->getPageCount(); if (empty($count)) { $type = 'emptyCategory'; } } break; } if ($image_id === 0) { $imageTitle = $this->findFirstImageTitleFromArticle($articleId); if (!empty($imageTitle)) { $image_id = $imageTitle->getArticleId(); } } return [$articleId, $namespaceId, $type, $info, $image_id]; } return [null, null, null, null, null]; }
/** * Handler for CategoryPageView hook * Add JavaScript to the page if there are images in the category * @param CategoryPage $catPage * @return bool */ public static function getModulesForCategory(&$catPage) { $title = $catPage->getTitle(); $cat = Category::newFromTitle($title); if ($cat->getFileCount() > 0) { $out = $catPage->getContext()->getOutput(); return self::getModules($out); } return true; }
/** * Return the number of pages, files or subcats in the given category, * or 0 if it's nonexistent. This is an expensive parser function and * can't be called too many times per page. * @param Parser $parser * @param string $name * @param string $arg1 * @param string $arg2 * @return string */ public static function pagesincategory($parser, $name = '', $arg1 = null, $arg2 = null) { global $wgContLang; static $magicWords = null; if (is_null($magicWords)) { $magicWords = new MagicWordArray(['pagesincategory_all', 'pagesincategory_pages', 'pagesincategory_subcats', 'pagesincategory_files']); } static $cache = []; // split the given option to its variable if (self::matchAgainstMagicword('rawsuffix', $arg1)) { // {{pagesincategory:|raw[|type]}} $raw = $arg1; $type = $magicWords->matchStartToEnd($arg2); } else { // {{pagesincategory:[|type[|raw]]}} $type = $magicWords->matchStartToEnd($arg1); $raw = $arg2; } if (!$type) { // backward compatibility $type = 'pagesincategory_all'; } $title = Title::makeTitleSafe(NS_CATEGORY, $name); if (!$title) { # invalid title return self::formatRaw(0, $raw); } $wgContLang->findVariantLink($name, $title, true); // Normalize name for cache $name = $title->getDBkey(); if (!isset($cache[$name])) { $category = Category::newFromTitle($title); $allCount = $subcatCount = $fileCount = $pagesCount = 0; if ($parser->incrementExpensiveFunctionCount()) { // $allCount is the total number of cat members, // not the count of how many members are normal pages. $allCount = (int) $category->getPageCount(); $subcatCount = (int) $category->getSubcatCount(); $fileCount = (int) $category->getFileCount(); $pagesCount = $allCount - $subcatCount - $fileCount; } $cache[$name]['pagesincategory_all'] = $allCount; $cache[$name]['pagesincategory_pages'] = $pagesCount; $cache[$name]['pagesincategory_subcats'] = $subcatCount; $cache[$name]['pagesincategory_files'] = $fileCount; } $count = $cache[$name][$type]; return self::formatRaw($count, $raw); }
/** * Format a single hit result * * @param $result SearchResult * @param $fieldSets Array: terms to highlight */ protected function showHit($result, $fieldSets) { global $wgLang, $wgUser; wfProfileIn(__METHOD__); if ($result->isBrokenTitle()) { wfProfileOut(__METHOD__); return "<!-- Broken link in search result -->\n"; } $sk = $wgUser->getSkin(); $t = $result->getTitle(); $titleSnippet = $result->getTitleSnippet($fieldSets); if ($titleSnippet == '') { $titleSnippet = null; } $link_t = clone $t; wfRunHooks('ShowSearchHitTitle', array(&$link_t, &$titleSnippet, $result, $fieldSets, $this)); $link = $this->sk->linkKnown($link_t, $titleSnippet); // FÜLLEN //If page content is not readable, just return the title. //This is not quite safe, but better than showing excerpts from non-readable pages //Note that hiding the entry entirely would screw up paging. // ---- HIER if (!$t->userCanRead()) { wfProfileOut(__METHOD__); return "<li>{$link}</li>\n"; } //return "<li>{$link}</li>\n"; // If the page doesn't *exist*... our search index is out of date. // The least confusing at this point is to drop the result. // You may get less results, but... oh well. :P // ---- HIER if ($result->isMissingRevision()) { wfProfileOut(__METHOD__); return "<!-- missing page " . htmlspecialchars($t->getPrefixedText()) . "-->\n"; } // format redirects / relevant sections $redirectTitle = $result->getRedirectTitle(); $redirectText = $result->getRedirectSnippet($fieldSets); $sectionTitle = $result->getSectionTitle(); $sectionText = $result->getSectionSnippet($fieldSets); $redirect = ''; if (!is_null($redirectTitle)) { if ($redirectText == '') { $redirectText = null; } $redirect = "<span class='searchalttitle'>" . wfMsg('search-redirect', $this->sk->linkKnown($redirectTitle, $redirectText)) . "</span>"; } $section = ''; if (!is_null($sectionTitle)) { if ($sectionText == '') { $sectionText = null; } $section = "<span class='searchalttitle'>" . wfMsg('search-section', $this->sk->linkKnown($sectionTitle, $sectionText)) . "</span>"; } // format text extract $extract = "<div class='searchresult'>" . $result->getTextSnippet($fieldSets) . "</div>"; // format score if (is_null($result->getScore())) { // Search engine doesn't report scoring info $score = ''; } else { $percent = sprintf('%2.1f', $result->getScore() * 100); $score = wfMsg('search-result-score', $wgLang->formatNum($percent)) . ' - '; } // format description $byteSize = $result->getByteSize(); $wordCount = $result->getWordCount(); $timestamp = $result->getTimestamp(); $size = wfMsgExt('search-result-size', array('parsemag', 'escape'), $this->sk->formatSize($byteSize), $wgLang->formatNum($wordCount)); if ($t->getNamespace() == NS_CATEGORY) { $cat = Category::newFromTitle($t); $size = wfMsgExt('search-result-category-size', array('parsemag', 'escape'), $wgLang->formatNum($cat->getPageCount()), $wgLang->formatNum($cat->getSubcatCount()), $wgLang->formatNum($cat->getFileCount())); } $date = $wgLang->timeanddate($timestamp); // link to related articles if supported $related = ''; if ($result->hasRelated()) { $st = SpecialPage::getTitleFor('SolrSearch'); $stParams = array('solrsearch' => wfMsgForContent('searchrelated') . ':' . $t->getPrefixedText()); $related = ' -- ' . $sk->linkKnown($st, wfMsg('search-relatedarticle'), array(), $stParams); } // Include a thumbnail for media files... // WE HAVE NEVER TESTED THIS HERE!!! if ($t->getNamespace() == NS_FILE) { $img = wfFindFile($t); if ($img) { $thumb = $img->transform(array('width' => 120, 'height' => 120)); if ($thumb) { $desc = wfMsg('parentheses', $img->getShortDesc()); wfProfileOut(__METHOD__); // Float doesn't seem to interact well with the bullets. // Table messes up vertical alignment of the bullets. // Bullets are therefore disabled (didn't look great anyway). return "<li>" . '<table class="searchResultImage">' . '<tr>' . '<td width="120" align="center" valign="top">' . $thumb->toHtml(array('desc-link' => true)) . '</td>' . '<td valign="top">' . $link . $extract . "<div class='mw-search-result-data'>{$score}{$desc}{$date}{$related}</div>" . '</td>' . '</tr>' . '</table>' . "</li>\n"; } } } wfProfileOut(__METHOD__); // HIER kommt die score ausgabe: return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" . "<div class='mw-search-result-data'>{$score}{$date}{$related}</div>" . "</li>\n"; }