Example #1
0
	/**
	 * @param $title Title
	 * @param $repo ForeignApiRepo
	 * @return ForeignAPIFile|null
	 */
	static function newFromTitle( Title $title, $repo ) {
		$data = $repo->fetchImageQuery( array(
			'titles' => 'File:' . $title->getDBkey(),
			'iiprop' => self::getProps(),
			'prop' => 'imageinfo',
			'iimetadataversion' => MediaHandler::getMetadataVersion()
		) );

		$info = $repo->getImageInfo( $data );

		if ( $info ) {
			$lastRedirect = isset( $data['query']['redirects'] )
				? count( $data['query']['redirects'] ) - 1
				: -1;
			if ( $lastRedirect >= 0 ) {
				$newtitle = Title::newFromText( $data['query']['redirects'][$lastRedirect]['to'] );
				$img = new self( $newtitle, $repo, $info, true );
				if ( $img ) {
					$img->redirectedFrom( $title->getDBkey() );
				}
			} else {
				$img = new self( $title, $repo, $info, true );
			}
			return $img;
		} else {
			return null;
		}
	}
Example #2
0
 /**
  * @return bool|int|null
  */
 protected function saveContent()
 {
     global $wgLogRestrictions;
     $dbw = wfGetDB(DB_MASTER);
     $log_id = $dbw->nextSequenceValue('logging_log_id_seq');
     $this->timestamp = $now = wfTimestampNow();
     $data = array('log_id' => $log_id, 'log_type' => $this->type, 'log_action' => $this->action, 'log_timestamp' => $dbw->timestamp($now), 'log_user' => $this->doer->getId(), 'log_user_text' => $this->doer->getName(), 'log_namespace' => $this->target->getNamespace(), 'log_title' => $this->target->getDBkey(), 'log_page' => $this->target->getArticleId(), 'log_comment' => $this->comment, 'log_params' => $this->params);
     $dbw->insert('logging', $data, __METHOD__);
     $newId = !is_null($log_id) ? $log_id : $dbw->insertId();
     # And update recentchanges
     if ($this->updateRecentChanges) {
         $titleObj = SpecialPage::getTitleFor('Log', $this->type);
         RecentChange::notifyLog($now, $titleObj, $this->doer, $this->getRcComment(), '', $this->type, $this->action, $this->target, $this->comment, $this->params, $newId);
     } elseif ($this->sendToUDP) {
         # Don't send private logs to UDP
         if (isset($wgLogRestrictions[$this->type]) && $wgLogRestrictions[$this->type] != '*') {
             return true;
         }
         # Notify external application via UDP.
         # We send this to IRC but do not want to add it the RC table.
         $titleObj = SpecialPage::getTitleFor('Log', $this->type);
         $rc = RecentChange::newLogEntry($now, $titleObj, $this->doer, $this->getRcComment(), '', $this->type, $this->action, $this->target, $this->comment, $this->params, $newId);
         $rc->notifyRC2UDP();
     }
     return $newId;
 }
	/**
	 * Invalidate the base pages for this title, so that any SubPageList
	 * there gets refreshed after doing a subpage delete, move or creation.
	 * 
	 * @since 0.3
	 * 
	 * @param Title $title
	 */
	protected static function invalidateBasePages( Title $title ) {
		global $egSPLAutorefresh;
		
		if ( !$egSPLAutorefresh ) {
			return;
		}
		
		$slashPosition = strpos( $title->getDBkey(), '/' );

		if ( $slashPosition !== false ) {
			$baseTitleText = substr( $title->getDBkey(), 0, $slashPosition );
			
			$titleArray = self::getBaseSubPages(
				$baseTitleText,
				$title->getNamespace()
			);
			
			foreach ( $titleArray as $parentTitle ) {
				// No point in invalidating the page itself
				if ( $parentTitle->getArticleID() != $title->getArticleID() ) {
					$parentTitle->invalidateCache();
				}
			}
			
			$baseTitle = Title::newFromText( $baseTitleText, $title->getNamespace() );
			if ( $baseTitle->getArticleID() != $title->getArticleID() ) {
				$baseTitle->invalidateCache();
			}					
		}
	}
 /**
  * Creates the category service object
  * @param $title Title|string Title object os category name
  */
 public function __construct($title)
 {
     if (!$title instanceof Title) {
         $title = Title::makeTitle(NS_CATEGORY, $title);
     }
     $this->title = $title;
     $this->dbkey = $this->title->getDBkey();
 }
 /**
  * Check if the page is sitemap page
  * @param Title $title
  * @return bool
  */
 public function isSitemapPage($title)
 {
     if (WikiaPageType::isCorporatePage() && $title->getDBkey() == self::SITEMAP_PAGE) {
         return true;
     }
     return false;
 }
 public function getExhibitionItems(Title $title)
 {
     wfProfileIn(__METHOD__);
     if (class_exists('CategoryDataService')) {
         $cacheKey = $this->getExhibitionItemsCacheKey($title->getText());
         $items = $this->wg->memc->get($cacheKey);
         if (!is_array($items)) {
             $exh = CategoryDataService::getMostVisited($title->getDBkey(), null, self::EXHIBITION_ITEMS_LIMIT);
             $ids = array_keys($exh);
             $length = count($ids);
             $items = array();
             for ($i = 0; $i < $length; $i++) {
                 $pageId = $ids[$i];
                 $imgRespnse = $this->app->sendRequest('ImageServing', 'index', array('ids' => array($pageId), 'height' => 150, 'width' => 150, 'count' => 1));
                 $img = $imgRespnse->getVal('result');
                 if (!empty($img[$pageId])) {
                     $img = $img[$pageId][0]['url'];
                 } else {
                     $img = false;
                 }
                 $oTitle = Title::newFromID($pageId);
                 $items[] = ['img' => $img, 'title' => $oTitle->getText(), 'url' => $oTitle->getFullURL()];
             }
             $this->wg->memc->set($cacheKey, $items, self::CACHE_TTL_EXHIBITION);
         }
         wfProfileOut(__METHOD__);
         return $items;
     }
     wfProfileOut(__METHOD__);
     return false;
 }
Example #7
0
 /**
  * Get the text to display in the language box for specific language and
  * level.
  *
  * @param $name string
  * @param $language String: Language code of language to use.
  * @param $level String: Level to use.
  * @return String: Text for display, in wikitext format.
  */
 protected static function mGetText($name, $language, $level)
 {
     wfProfileIn(__METHOD__);
     global $wgBabelMainCategory, $wgBabelCategoryNames;
     if ($wgBabelCategoryNames[$level] === false) {
         $categoryLevel = self::$title->getFullText();
     } else {
         $categoryLevel = ':Category:' . self::mReplaceCategoryVariables($wgBabelCategoryNames[$level], $language);
     }
     if ($wgBabelMainCategory === false) {
         $categoryMain = self::$title->getFullText();
     } else {
         $categoryMain = ':Category:' . self::mReplaceCategoryVariables($wgBabelMainCategory, $language);
     }
     // Give grep a chance to find the usages:
     // babel-0-n, babel-1-n, babel-2-n, babel-3-n, babel-4-n, babel-5-n, babel-N-n
     $text = wfMessage("babel-{$level}-n", $categoryLevel, $categoryMain, '', self::$title->getDBkey())->inLanguage($language)->text();
     $fallbackLanguage = Language::getFallbackfor($language);
     $fallback = wfMessage("babel-{$level}-n", $categoryLevel, $categoryMain, '', self::$title->getDBkey())->inLanguage($fallbackLanguage ? $fallbackLanguage : $language)->text();
     // Give grep a chance to find the usages:
     // babel-0, babel-1, babel-2, babel-3, babel-4, babel-5, babel-N
     if ($text == $fallback) {
         $text = wfMessage("babel-{$level}", $categoryLevel, $categoryMain, $name, self::$title->getDBkey())->inLanguage($language)->text();
     }
     wfProfileOut(__METHOD__);
     return $text;
 }
 /**
  * Check if the given local page title is a spam regex source.
  * @param Title $title
  * @return bool
  */
 function isLocalSource($title)
 {
     global $wgDBname;
     if ($title->getNamespace() == NS_MEDIAWIKI) {
         $sources = array("Spam-blacklist", "Spam-whitelist");
         if (in_array($title->getDBkey(), $sources)) {
             return true;
         }
     }
     $thisHttp = wfExpandUrl($title->getFullUrl('action=raw'), PROTO_HTTP);
     $thisHttpRegex = '/^' . preg_quote($thisHttp, '/') . '(?:&.*)?$/';
     foreach ($this->files as $fileName) {
         $matches = array();
         if (preg_match('/^DB: (\\w*) (.*)$/', $fileName, $matches)) {
             if ($wgDBname == $matches[1]) {
                 if ($matches[2] == $title->getPrefixedDbKey()) {
                     // Local DB fetch of this page...
                     return true;
                 }
             }
         } elseif (preg_match($thisHttpRegex, $fileName)) {
             // Raw view of this page
             return true;
         }
     }
     return false;
 }
 /**
  * Get the lowest and highest timestamp for a category.
  *
  * @param Title $category
  * @return array The lowest and highest timestamp
  * @throws MWException If category has no entries.
  */
 protected function getMinAndMaxForCat(Title $category)
 {
     $dbr = wfGetDB(DB_REPLICA);
     $res = $dbr->selectRow('categorylinks', ['low' => 'MIN( cl_timestamp )', 'high' => 'MAX( cl_timestamp )'], ['cl_to' => $this->category->getDBkey()], __METHOD__, ['LIMIT' => 1]);
     if (!$res) {
         throw new MWException('No entries in category');
     }
     return [wfTimestamp(TS_UNIX, $res->low), wfTimestamp(TS_UNIX, $res->high)];
 }
	/**
	 * return the page titles of the subpages in an array
	 * @return array all titles
	 * @private
	 */
	function getTitles() {
		wfProfileIn( __METHOD__ );

		$dbr = wfGetDB( DB_SLAVE );

		$conditions = array();
		$options = array();
		$order = strtoupper( $this->order );

		if( $this->ordermethod == 'title' ) {
			$options['ORDER BY'] = 'page_title ' . $order;
		} elseif( $this->ordermethod == 'lastedit' ) {
			$options['ORDER BY'] = 'page_touched ' . $order;
		}
		if( $this->parent !== -1) {
			$this->ptitle = Title::newFromText( $this->parent );
			# note that non-existent pages may nevertheless have valid subpages
			# on the other hand, not checking that the page exists can let input through which causes database errors
			if ( $this->ptitle instanceof Title && $this->ptitle->exists() && $this->ptitle->userCanRead() ) {
				$parent = $this->ptitle->getDBkey();
				$this->parent = $parent;
				$this->namespace = $this->ptitle->getNsText();
				$nsi = $this->ptitle->getNamespace();
			} else {
				$this->error( wfMsg('spl3_debug','parent') );
				return null;
			}
		} else {
			$this->ptitle = $this->title;
			$parent = $this->title->getDBkey();
			$this->parent = $parent;
			$this->namespace = $this->title->getNsText();
			$nsi = $this->title->getNamespace();
		}

		// don't let list cross namespaces
		if ( strlen( $nsi ) > 0 ) {
			$conditions['page_namespace'] = $nsi;
		}
		$conditions['page_is_redirect'] = 0;
		$conditions[] = 'page_title ' . $dbr->buildLike( $parent . '/', $dbr->anyString() );

		$fields = array();
		$fields[] = 'page_title';
		$fields[] = 'page_namespace';
		$res = $dbr->select( 'page', $fields, $conditions, __METHOD__, $options );

		$titles = array();
		foreach ( $res as $row ) {
			$title = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
			if( $title ) {
				$titles[] = $title;
			}
		}
		wfProfileOut( __METHOD__ );
		return $titles;
	}
 /**
  * Check if a title is marked as fuzzy.
  * @return bool If title is marked fuzzy.
  */
 public function isFuzzy()
 {
     $dbr = wfGetDB(DB_SLAVE);
     $tables = array('page', 'revtag');
     $field = 'rt_type';
     $conds = array('page_namespace' => $this->title->getNamespace(), 'page_title' => $this->title->getDBkey(), 'rt_type' => RevTag::getType('fuzzy'), 'page_id=rt_page', 'page_latest=rt_revision');
     $res = $dbr->selectField($tables, $field, $conds, __METHOD__);
     return $res !== false;
 }
Example #12
0
 /**
  * Compose a mail to a given user and either queue it for sending, or send it now,
  * depending on settings.
  *
  * Call sendMails() to send any mails that were queued.
  * @param $user User
  */
 private function compose(\User $user)
 {
     if ($this->getEmailExtensionController() !== false) {
         $this->sendUsingEmailExtension($user);
     } else {
         \Wikia\Logger\WikiaLogger::instance()->notice('Sending via UserMailer', ['page' => $this->title->getDBkey(), 'summary' => $this->summary, 'action' => $this->action, 'subject' => $this->subject]);
         $this->sendUsingUserMailer($user);
     }
     wfRunHooks('NotifyOnPageChangeComplete', [$this->title, $this->timestamp, &$user]);
 }
Example #13
0
 function doCategoryQuery()
 {
     $dbr = wfGetDB(DB_SLAVE, 'category');
     $this->nextPage = array('page' => null, 'subcat' => null, 'file' => null);
     $this->flip = array('page' => false, 'subcat' => false, 'file' => false);
     foreach (array('page', 'subcat', 'file') as $type) {
         # Get the sortkeys for start/end, if applicable.  Note that if
         # the collation in the database differs from the one
         # set in $wgCategoryCollation, pagination might go totally haywire.
         $extraConds = array('cl_type' => $type);
         if ($this->from[$type] !== null) {
             $extraConds[] = 'cl_sortkey >= ' . $dbr->addQuotes($this->collation->getSortKey($this->from[$type]));
         } elseif ($this->until[$type] !== null) {
             $extraConds[] = 'cl_sortkey < ' . $dbr->addQuotes($this->collation->getSortKey($this->until[$type]));
             $this->flip[$type] = true;
         }
         /* Wikia change begin - @author: TomekO */
         /* Changed by MoLi (1.19 ugrade) */
         wfRunHooks('CategoryViewer::beforeCategoryData', array(&$extraConds));
         /* Wikia change end */
         $res = $dbr->select(array('page', 'categorylinks', 'category'), array('page_id', 'page_title', 'page_namespace', 'page_len', 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title', 'cat_subcats', 'cat_pages', 'cat_files', 'cl_sortkey_prefix', 'cl_collation'), array_merge(array('cl_to' => $this->title->getDBkey()), $extraConds), __METHOD__, array('USE INDEX' => array('categorylinks' => 'cl_sortkey'), 'LIMIT' => is_integer($this->limit) ? $this->limit + 1 : null, 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey'), array('categorylinks' => array('INNER JOIN', 'cl_from = page_id'), 'category' => array('LEFT JOIN', 'cat_title = page_title AND page_namespace = ' . NS_CATEGORY)));
         $count = 0;
         foreach ($res as $row) {
             $title = Title::newFromRow($row);
             if ($row->cl_collation === '') {
                 // Hack to make sure that while updating from 1.16 schema
                 // and db is inconsistent, that the sky doesn't fall.
                 // See r83544. Could perhaps be removed in a couple decades...
                 $humanSortkey = $row->cl_sortkey;
             } else {
                 $humanSortkey = $title->getCategorySortkey($row->cl_sortkey_prefix);
             }
             if (++$count > $this->limit && is_integer($this->limit)) {
                 # We've reached the one extra which shows that there
                 # are additional pages to be had. Stop here...
                 $this->nextPage[$type] = $humanSortkey;
                 break;
             }
             if ($title->getNamespace() == NS_CATEGORY) {
                 $cat = Category::newFromRow($row, $title);
                 $this->addSubcategoryObject($cat, $humanSortkey, $row->page_len);
             } elseif ($title->getNamespace() == NS_FILE) {
                 $this->addImage($title, $humanSortkey, $row->page_len, $row->page_is_redirect);
             } else {
                 # <Wikia>
                 if (wfRunHooks("CategoryViewer::addPage", array(&$this, &$title, &$row, $humanSortkey))) {
                     $this->addPage($title, $humanSortkey, $row->page_len, $row->page_is_redirect);
                 }
                 # </Wikia>
             }
         }
     }
 }
Example #14
0
 /**
  * Loads a file object from the filearchive table
  * @return true on success or null
  */
 public function load()
 {
     if ($this->dataLoaded) {
         return true;
     }
     $conds = array();
     if ($this->id > 0) {
         $conds['fa_id'] = $this->id;
     }
     if ($this->key) {
         $conds['fa_storage_group'] = $this->group;
         $conds['fa_storage_key'] = $this->key;
     }
     if ($this->title) {
         $conds['fa_name'] = $this->title->getDBkey();
     }
     if (!count($conds)) {
         throw new MWException("No specific information for retrieving archived file");
     }
     if (!$this->title || $this->title->getNamespace() == NS_FILE) {
         $dbr = wfGetDB(DB_SLAVE);
         $res = $dbr->select('filearchive', array('fa_id', 'fa_name', 'fa_archive_name', 'fa_storage_key', 'fa_storage_group', 'fa_size', 'fa_bits', 'fa_width', 'fa_height', 'fa_metadata', 'fa_media_type', 'fa_major_mime', 'fa_minor_mime', 'fa_description', 'fa_user', 'fa_user_text', 'fa_timestamp', 'fa_deleted'), $conds, __METHOD__, array('ORDER BY' => 'fa_timestamp DESC'));
         if ($res == false || $dbr->numRows($res) == 0) {
             // this revision does not exist?
             return;
         }
         $ret = $dbr->resultObject($res);
         $row = $ret->fetchObject();
         // initialize fields for filestore image object
         $this->id = intval($row->fa_id);
         $this->name = $row->fa_name;
         $this->archive_name = $row->fa_archive_name;
         $this->group = $row->fa_storage_group;
         $this->key = $row->fa_storage_key;
         $this->size = $row->fa_size;
         $this->bits = $row->fa_bits;
         $this->width = $row->fa_width;
         $this->height = $row->fa_height;
         $this->metadata = $row->fa_metadata;
         $this->mime = "{$row->fa_major_mime}/{$row->fa_minor_mime}";
         $this->media_type = $row->fa_media_type;
         $this->description = $row->fa_description;
         $this->user = $row->fa_user;
         $this->user_text = $row->fa_user_text;
         $this->timestamp = $row->fa_timestamp;
         $this->deleted = $row->fa_deleted;
     } else {
         throw new MWException('This title does not correspond to an image page.');
     }
     $this->dataLoaded = true;
     $this->exists = true;
     return true;
 }
Example #15
0
 /**
  * @param User $editor The editor that triggered the update.  Their notification
  *  timestamp will not be updated(they have already seen it)
  * @param Title $title The title to update timestamps for
  * @param string $timestamp Set the update timestamp to this value
  * @return int[]
  */
 public static function updateWatchlistTimestamp(User $editor, Title $title, $timestamp)
 {
     global $wgEnotifWatchlist, $wgShowUpdatedMarker;
     if (!$wgEnotifWatchlist && !$wgShowUpdatedMarker) {
         return array();
     }
     $dbw = wfGetDB(DB_MASTER);
     $res = $dbw->select(array('watchlist'), array('wl_user'), array('wl_user != ' . intval($editor->getID()), 'wl_namespace' => $title->getNamespace(), 'wl_title' => $title->getDBkey(), 'wl_notificationtimestamp IS NULL'), __METHOD__);
     $watchers = array();
     foreach ($res as $row) {
         $watchers[] = intval($row->wl_user);
     }
     if ($watchers) {
         // Update wl_notificationtimestamp for all watching users except the editor
         $fname = __METHOD__;
         $dbw->onTransactionIdle(function () use($dbw, $timestamp, $watchers, $title, $fname) {
             $dbw->update('watchlist', array('wl_notificationtimestamp' => $dbw->timestamp($timestamp)), array('wl_user' => $watchers, 'wl_namespace' => $title->getNamespace(), 'wl_title' => $title->getDBkey()), $fname);
         });
     }
     return $watchers;
 }
Example #16
0
 /**
  * @return array
  */
 protected function insertFields()
 {
     /**
      * @author Piotr Molski (moli)
      * trap for BugId: 11897
      */
     if (!$this->title instanceof Title) {
         $log = "MOLI JOB@invalid title: " . $this->command . " . params: " . print_r($this->params, true) . "\n";
         error_log($log);
     } else {
         $dbw = wfGetDB(DB_MASTER);
         return array('job_id' => $dbw->nextSequenceValue('job_job_id_seq'), 'job_cmd' => $this->command, 'job_namespace' => $this->title->getNamespace(), 'job_title' => $this->title->getDBkey(), 'job_timestamp' => $dbw->timestamp(), 'job_params' => Job::makeBlob($this->params));
     }
 }
 protected function makePageLink(Title $title = null, $parameters = [], $html = null)
 {
     global $wgContLang, $wgUserrightsInterwikiDelimiter;
     if (!$this->plaintext) {
         $text = $wgContLang->ucfirst($title->getDBkey());
         $parts = explode($wgUserrightsInterwikiDelimiter, $text, 2);
         if (count($parts) === 2) {
             $titleLink = WikiMap::foreignUserLink($parts[1], $parts[0], htmlspecialchars(strtr($parts[0], '_', ' ') . $wgUserrightsInterwikiDelimiter . $parts[1]));
             if ($titleLink !== false) {
                 return $titleLink;
             }
         }
     }
     return parent::makePageLink($title, $parameters, $title ? $title->getText() : null);
 }
 protected function getLastDelete()
 {
     $dbr = wfGetDB(DB_SLAVE);
     $data = $dbr->selectRow(array('logging', 'user'), array('log_type', 'log_action', 'log_timestamp', 'log_user', 'log_namespace', 'log_title', 'log_comment', 'log_params', 'log_deleted', 'user_name'), array('log_namespace' => $this->mTitle->getNamespace(), 'log_title' => $this->mTitle->getDBkey(), 'log_type' => 'delete', 'log_action' => 'delete', 'user_id=log_user'), __METHOD__, array('LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC'));
     // Quick paranoid permission checks...
     if (is_object($data)) {
         if ($data->log_deleted & LogPage::DELETED_USER) {
             $data->user_name = wfMsgHtml('rev-deleted-user');
         }
         if ($data->log_deleted & LogPage::DELETED_COMMENT) {
             $data->log_comment = wfMsgHtml('rev-deleted-comment');
         }
     }
     return $data;
 }
 /**
  * Get a VideoInfo object given a Title object
  * @param Title|string $title
  * @param boolean $premiumOnly
  * @return VideoInfo|null $videoInfo
  */
 public function getVideoInfoFromTitle($title, $premiumOnly = false)
 {
     wfProfileIn(__METHOD__);
     // Attempt to retrieve this information from the video_info table first
     $videoInfo = VideoInfo::newFromTitle($title instanceof Title ? $title->getDBkey() : $title);
     // If its not in the DB, recreate it from existing file data
     if (empty($videoInfo)) {
         $videoData = $this->getVideoDataFromTitle($title, $premiumOnly);
         if (!empty($videoData)) {
             $videoInfo = new VideoInfo($videoData);
         }
     }
     wfProfileOut(__METHOD__);
     return $videoInfo;
 }
 /**
  * Get an executed query for use on image pages
  *
  * @param Title $title File to query for
  * @return GlobalUsageQuery Query object, already executed
  */
 private static function getImagePageQuery($title)
 {
     $name = $title->getDBkey();
     if (!isset(self::$queryCache[$name])) {
         $query = new GlobalUsageQuery($title);
         $query->filterLocal();
         $query->execute();
         self::$queryCache[$name] = $query;
         // Limit cache size to 100
         if (count(self::$queryCache) > 100) {
             array_shift(self::$queryCache);
         }
     }
     return self::$queryCache[$name];
 }
Example #21
0
 /**
  * @param $dbw DatabaseBase
  * @param $timestamp
  * @return string
  */
 function hideArchivedRevision($dbw, $timestamp)
 {
     $archive = new PageArchive($this->mTarget);
     $rev = $archive->getRevision($timestamp);
     if (!$rev) {
         $dbw->rollback();
         return 'hiderevision-error-missing';
     }
     $this->insertRevision($dbw, $this->mTarget, $rev);
     if ($dbw->affectedRows() != 1) {
         $dbw->rollback();
         return 'hiderevision-error-delete';
     }
     $dbw->delete('archive', array('ar_namespace' => $this->mTarget->getNamespace(), 'ar_title' => $this->mTarget->getDBkey(), 'ar_timestamp' => $dbw->timestamp($timestamp)), __METHOD__);
     $dbw->commit();
     return 'hiderevision-success';
 }
Example #22
0
 /**
  * Create a SquidUpdate from the given Title object.
  *
  * The resulting SquidUpdate will purge the given Title's URLs as well as
  * the pages that link to it. Capped at $wgMaxSquidPurgeTitles total URLs.
  *
  * @param Title $title
  * @return SquidUpdate
  */
 public static function newFromLinksTo(Title $title)
 {
     global $wgMaxSquidPurgeTitles;
     wfProfileIn(__METHOD__);
     # Get a list of URLs linking to this page
     $dbr = wfGetDB(DB_SLAVE);
     $res = $dbr->select(array('links', 'page'), array('page_namespace', 'page_title'), array('pl_namespace' => $title->getNamespace(), 'pl_title' => $title->getDBkey(), 'pl_from=page_id'), __METHOD__);
     $blurlArr = $title->getSquidURLs();
     if ($res->numRows() <= $wgMaxSquidPurgeTitles) {
         foreach ($res as $BL) {
             $tobj = Title::makeTitle($BL->page_namespace, $BL->page_title);
             $blurlArr[] = $tobj->getInternalURL();
         }
     }
     wfProfileOut(__METHOD__);
     return new SquidUpdate($blurlArr);
 }
Example #23
0
	/**
	 * Loads a file object from the filearchive table
	 * @throws MWException
	 * @return bool|null True on success or null
	 */
	public function load() {
		if ( $this->dataLoaded ) {
			return true;
		}
		$conds = array();

		if ( $this->id > 0 ) {
			$conds['fa_id'] = $this->id;
		}
		if ( $this->key ) {
			$conds['fa_storage_group'] = $this->group;
			$conds['fa_storage_key'] = $this->key;
		}
		if ( $this->title ) {
			$conds['fa_name'] = $this->title->getDBkey();
		}

		if ( !count( $conds ) ) {
			throw new MWException( "No specific information for retrieving archived file" );
		}

		if ( !$this->title || $this->title->getNamespace() == NS_FILE ) {
			$this->dataLoaded = true; // set it here, to have also true on miss
			$dbr = wfGetDB( DB_SLAVE );
			$row = $dbr->selectRow(
				'filearchive',
				self::selectFields(),
				$conds,
				__METHOD__,
				array( 'ORDER BY' => 'fa_timestamp DESC' )
			);
			if ( !$row ) {
				// this revision does not exist?
				return null;
			}

			// initialize fields for filestore image object
			$this->loadFromRow( $row );
		} else {
			throw new MWException( 'This title does not correspond to an image page.' );
		}
		$this->exists = true;

		return true;
	}
 public static function newFromTitle(Title $indextitle)
 {
     $ns = $indextitle->getNamespace();
     $t = $indextitle->getDBkey();
     $dbr = wfGetDB(DB_SLAVE);
     $res = $dbr->select('indexes', 'in_from', array('in_namespace' => $ns, 'in_title' => $t), __METHOD__);
     if (!$res->numRows()) {
         return null;
     }
     $ind = new IndexFunction();
     $ids = array();
     foreach ($res as $row) {
         $ids[] = $row->in_from;
     }
     $ind->mTo = Title::newFromIDs($ids);
     $ind->mFrom = $indextitle;
     return $ind;
 }
 /**
  * Build a single link for a given title
  *
  * @param Title $title
  * @param string $op
  * @param string $label
  * @return mixed
  */
 private static function buildLink($title, $op, $label)
 {
     wfProfileIn(__METHOD__);
     $dbr = wfGetDB(DB_SLAVE);
     $res = $dbr->select('page', array('page_namespace', 'page_title'), array('page_is_redirect' => 0, 'page_namespace' => $title->getNamespace(), "page_title {$op} " . $dbr->addQuotes($title->getDBkey())), __METHOD__, array('ORDER BY' => 'page_title' . ($op == '<' ? ' DESC' : ''), 'LIMIT' => 1));
     if ($dbr->numRows($res) > 0) {
         $row = $dbr->fetchObject($res);
         $dbr->freeResult($res);
         $target = Title::makeTitleSafe($row->page_namespace, $row->page_title);
         if ($target instanceof Title) {
             $label = htmlspecialchars(wfMsg("backforth-{$label}", $target->getPrefixedText()));
             wfProfileOut(__METHOD__);
             return $GLOBALS['wgUser']->getSkin()->makeKnownLinkObj($target, $label);
         }
     }
     wfProfileOut(__METHOD__);
     return false;
 }
 /**
  * @brief Helper function which determines whether to display the Admin Dashboard Chrome in the Oasis Skin
  * @param WikiaApp $app
  * @param Title $title Title of page we are on
  * @return boolean
  */
 public static function displayAdminDashboard($app, $title)
 {
     // Admin Dashboard is only for logged in plus a list of groups
     if (!$app->wg->User->isLoggedIn()) {
         return false;
     }
     if (!$app->wg->User->isAllowed('admindashboard')) {
         return false;
     }
     if ($title && $title->isSpecialPage()) {
         $bits = explode('/', $title->getDBkey(), 2);
         $alias = array_shift(SpecialPageFactory::resolveAlias($bits[0]));
         // NOTE: keep this list in alphabetical order
         static $exclusionList = array("AbTesting", "ApiExplorer", "ApiGate", "Chat", "CloseWiki", "Code", "Confirmemail", "Connect", "Contact", "Contributions", "CreateBlogPage", "CreatePage", "CreateNewWiki", "CreateTopList", "Crunchyroll", "EditAccount", "EditTopList", "Following", "Forum", "ImageReview", "Invalidateemail", "LandingPageSmurfs", "LayoutBuilder", "LayoutBuilderForm", "Leaderboard", "LookupContribs", "LookupUser", "ManageWikiaHome", "MiniEditor", "MovePage", "MultiLookup", "NewFiles", "Newimages", "Our404Handler", "PageLayoutBuilder", "PageLayoutBuilderForm", "Phalanx", "PhalanxStats", "PhotoPopSetup", "Places", "Play", "Preferences", "PromoteImageReview", "ScavengerHunt", "Search", "Signup", "SiteWideMessages", "SponsorshipDashboard", "StructuredData", "TaskManager", "ThemeDesigner", "ThemeDesignerPreview", "UserLogin", "UserManagement", "UserPathPrediction", "UserSignup", "Version", "Videos", "WhereIsExtension", "WikiActivity", "WikiaHubsV2", "WikiaSearch", "WikiaStyleGuide", "WikiFactory", "WikiFactoryReporter", "WikiStats");
         return !in_array($alias, $exclusionList);
     }
     return false;
 }
 /**
  * Get number of active users watching a page
  * @param Title $title
  * @return int
  */
 public static function numUsersWatchingPage(Title $title)
 {
     global $wgMemc, $wgCookieExpiration;
     # Check the cache...
     $key = wfMemcKey('flaggedrevs', 'usersWatching', $title->getArticleID());
     $val = $wgMemc->get($key);
     if (is_int($val)) {
         return $val;
         // cache hit
     }
     # Get number of active editors watching this page...
     $dbr = wfGetDB(DB_SLAVE);
     $cutoff = $dbr->timestamp(wfTimestamp(TS_UNIX) - 2 * $wgCookieExpiration);
     $count = (int) $dbr->selectField(array('watchlist', 'user'), 'COUNT(*)', array('wl_namespace' => $title->getNamespace(), 'wl_title' => $title->getDBkey(), 'wl_user = user_id', 'user_touched > ' . $dbr->addQuotes($cutoff)), __METHOD__);
     if ($count > 10) {
         # Save new value to cache (more aggresive for larger counts)
         $wgMemc->set($key, $count, $count > 200 ? 30 * 60 : 5 * 60);
     }
     return $count;
 }
Example #28
0
 /**
  * @param Title $title Title object that this entry is for.
  * @param String $pubDate Publish date formattable by wfTimestamp.
  * @param Array $keywords list of (String) keywords
  * @param Mixed Boolean or Integer. Namespace containing comments page for entry.
  *   True for the corresponding talk page of $title
  *   False for none
  *   An integer for the page name of $title in the specific namespace denoted by that integer.
  */
 public function __construct($title, $pubDate, $keywords = '', $comment = true)
 {
     if (!$title || !$title instanceof Title) {
         // Paranoia
         throw new MWException('Invalid title object passed to FeedSMItem');
     }
     $commentsURL = '';
     if ($comment === true) {
         // The comment ns is this article's talk namespace.
         $commentsURL = $title->getTalkPage()->getFullUrl();
     } elseif (is_int($comment)) {
         // There's a specific comments namespace.
         $commentsTitle = Title::makeTitle($comment, $title->getDBkey());
         if ($commentsTitle) {
             $commentsURL = $commentsTitle->getFullUrl();
         }
     }
     $this->keywords = $keywords;
     $this->titleObj = $title;
     parent::__construct($title->getText(), '', $title->getFullURL(), $pubDate, '', $commentsURL);
 }
Example #29
0
 /**
  * Do some database updates after deletion
  *
  * @param $id Int: page_id value of the page being deleted
  */
 public function doDeleteUpdates($id)
 {
     DeferredUpdates::addUpdate(new SiteStatsUpdate(0, 1, -(int) $this->isCountable(), -1));
     $dbw = wfGetDB(DB_MASTER);
     # Delete restrictions for it
     $dbw->delete('page_restrictions', array('pr_page' => $id), __METHOD__);
     # Fix category table counts
     $cats = array();
     $res = $dbw->select('categorylinks', 'cl_to', array('cl_from' => $id), __METHOD__);
     foreach ($res as $row) {
         $cats[] = $row->cl_to;
     }
     $this->updateCategoryCounts(array(), $cats);
     # If using cascading deletes, we can skip some explicit deletes
     if (!$dbw->cascadingDeletes()) {
         $dbw->delete('revision', array('rev_page' => $id), __METHOD__);
         # Delete outgoing links
         $dbw->delete('pagelinks', array('pl_from' => $id), __METHOD__);
         $dbw->delete('imagelinks', array('il_from' => $id), __METHOD__);
         $dbw->delete('categorylinks', array('cl_from' => $id), __METHOD__);
         $dbw->delete('templatelinks', array('tl_from' => $id), __METHOD__);
         $dbw->delete('externallinks', array('el_from' => $id), __METHOD__);
         $dbw->delete('langlinks', array('ll_from' => $id), __METHOD__);
         $dbw->delete('iwlinks', array('iwl_from' => $id), __METHOD__);
         $dbw->delete('redirect', array('rd_from' => $id), __METHOD__);
         $dbw->delete('page_props', array('pp_page' => $id), __METHOD__);
     }
     # If using cleanup triggers, we can skip some manual deletes
     if (!$dbw->cleanupTriggers()) {
         # Clean up recentchanges entries...
         $dbw->delete('recentchanges', array('rc_type != ' . RC_LOG, 'rc_namespace' => $this->mTitle->getNamespace(), 'rc_title' => $this->mTitle->getDBkey()), __METHOD__);
         $dbw->delete('recentchanges', array('rc_type != ' . RC_LOG, 'rc_cur_id' => $id), __METHOD__);
     }
     # Clear caches
     self::onArticleDelete($this->mTitle);
     # Clear the cached article id so the interface doesn't act like we exist
     $this->mTitle->resetArticleID(0);
 }
Example #30
0
/**
 * @param Title $title
 * @param $timestamp
 * @param User $watcher
 * @return bool
 */
function wfNotifyOnPageChangeComplete($title, $timestamp, $watcher)
{
    global $wgCityId, $wgDBname, $wgUser, $wgCityId, $wgDefaultExternalStore, $wgExternalDatawareDB;
    wfProfileIn(__METHOD__);
    if (!$wgDefaultExternalStore) {
        wfProfileOut(__METHOD__);
        return true;
    }
    $watcher_id = intval($watcher->getID());
    $editor_id = intval($wgUser->getID());
    if (empty($watcher)) {
        wfProfileOut(__METHOD__);
        return true;
    }
    if (!empty($watcher) && empty($watcher_id)) {
        wfProfileOut(__METHOD__);
        return true;
    }
    if (empty($title) || !$title instanceof Title) {
        wfProfileOut(__METHOD__);
        return true;
    }
    $namespace = $title->getNamespace();
    if ($namespace < 0) {
        wfProfileOut(__METHOD__);
        return true;
    }
    if (empty($wgCityId)) {
        wfProfileOut(__METHOD__);
        return true;
    }
    $notify_type = "notifyonpagechange";
    $dbw = wfGetDB(DB_MASTER, array(), $wgExternalDatawareDB);
    $nl_id = $dbw->nextSequenceValue('notify_log_nl_id_seq');
    $dbw->insert("notify_log", array('nl_id' => $nl_id, 'nl_city' => intval($wgCityId), 'nl_type' => $notify_type, 'nl_editor' => $editor_id, 'nl_watcher' => $watcher_id, 'nl_title' => $title->getDBkey(), 'nl_namespace' => $namespace, 'nl_timestamp' => $dbw->timestamp($timestamp)), __METHOD__);
    wfProfileOut(__METHOD__);
    return true;
}