/**
  * get video detail
  * @param array $videoInfo [ array( 'title' => title, 'addedAt' => addedAt , 'addedBy' => addedBy ) ]
  * @return array $videoDetail
  */
 public function getVideoDetail($videoInfo)
 {
     $this->wf->ProfileIn(__METHOD__);
     $videoDetail = array();
     $title = F::build('Title', array($videoInfo['title'], NS_FILE), 'newFromText');
     if ($title instanceof Title) {
         $file = $this->wf->FindFile($title);
         if ($file instanceof File && $file->exists() && F::build('WikiaFileHelper', array($file), 'isFileTypeVideo')) {
             // get thumbnail
             $thumb = $file->transform(array('width' => self::THUMBNAIL_WIDTH, 'height' => self::THUMBNAIL_HEIGHT));
             $thumbUrl = $thumb->getUrl();
             // get user
             $user = F::build('User', array($videoInfo['addedBy']), 'newFromId');
             $userName = User::isIP($user->getName()) ? $this->wf->Msg('oasis-anon-user') : $user->getName();
             $userUrl = $user->getUserPage()->getFullURL();
             // get article list
             $mediaQuery = F::build('ArticlesUsingMediaQuery', array($title));
             $articleList = $mediaQuery->getArticleList();
             list($truncatedList, $isTruncated) = F::build('WikiaFileHelper', array($articleList, self::POSTED_IN_ARTICLES), 'truncateArticleList');
             // video details
             $videoDetail = array('title' => $title->getDBKey(), 'fileTitle' => $title->getText(), 'fileUrl' => $title->getLocalUrl(), 'thumbUrl' => $thumbUrl, 'userName' => $userName, 'userUrl' => $userUrl, 'truncatedList' => $truncatedList, 'isTruncated' => $isTruncated, 'timestamp' => $videoInfo['addedAt'], 'embedUrl' => $file->getHandler()->getEmbedUrl());
         }
     }
     $this->wf->ProfileOut(__METHOD__);
     return $videoDetail;
 }
Example #2
0
/**
 * wfSetWikiaNewtalk
 *
 * Hook, set new wikia shared message
 *
 * @author
 * @author Krzysztof Krzyżaniak <*****@*****.**> (changes)
 * @access public
 *
 * @param Article $article: edited article
 *
 * @return false: don't go to next hook
 */
function wfSetWikiaNewtalk(&$article)
{
    global $wgMemc, $wgWikiaNewtalkExpiry, $wgExternalSharedDB;
    $name = $article->mTitle->getDBkey();
    $other = User::newFromName($name);
    if (!$other instanceof User && User::isIP($name)) {
        // An anonymous user
        $other = new User();
        $other->setName($name);
    }
    if ($other instanceof User) {
        $other->setNewtalk(true);
        $other->load();
        $dbw = wfGetDB(DB_MASTER, array(), $wgExternalSharedDB);
        $dbw->begin();
        /**
         * first delete
         */
        $dbw->delete("shared_newtalks", array('sn_wiki' => wfWikiID(), 'sn_user_id' => $other->getID(), 'sn_user_ip' => $other->getName()), __METHOD__);
        /**
         * then insert
         */
        $dbw->insert("shared_newtalks", array('sn_wiki' => wfWikiID(), 'sn_user_id' => $other->getID(), 'sn_user_ip' => $other->getName()), __METHOD__);
        $dbw->commit();
        $key = 'wikia:shared_newtalk:' . $other->getID() . ':' . str_replace(' ', '_', $other->getName());
        $wgMemc->delete($key);
    }
    return false;
}
Example #3
0
function wfSpecialRestrictUser($par = null)
{
    global $wgOut, $wgRequest;
    $user = $userOrig = null;
    if ($par) {
        $userOrig = $par;
    } elseif ($wgRequest->getVal('user')) {
        $userOrig = $wgRequest->getVal('user');
    } else {
        $wgOut->addHTML(RestrictUserForm::selectUserForm());
        return;
    }
    $isIP = User::isIP($userOrig);
    $user = $isIP ? $userOrig : User::getCanonicalName($userOrig);
    $uid = User::idFromName($user);
    if (!$uid && !$isIP) {
        $err = '<strong class="error">' . wfMsgHtml('restrictuser-notfound') . '</strong>';
        $wgOut->addHTML(RestrictUserForm::selectUserForm($userOrig, $err));
        return;
    }
    $wgOut->addHTML(RestrictUserForm::selectUserForm($user));
    UserRestriction::purgeExpired();
    $old = UserRestriction::fetchForUser($user, true);
    RestrictUserForm::pageRestrictionForm($uid, $user, $old);
    RestrictUserForm::namespaceRestrictionForm($uid, $user, $old);
    // Renew it after possible changes in previous two functions
    $old = UserRestriction::fetchForUser($user, true);
    if ($old) {
        $wgOut->addHTML(RestrictUserForm::existingRestrictions($old));
    }
}
Example #4
0
 public function save()
 {
     wfProfileIn(__METHOD__);
     $action = "";
     if ($this->data['type'] & self::TYPE_USER && User::isIP($this->data['text'])) {
         $this->data['ip_hex'] = IP::toHex($this->data['text']);
     }
     $dbw = wfGetDB(DB_MASTER, array(), $this->wg->ExternalSharedDB);
     if (empty($this->data['id'])) {
         /* add block */
         $dbw->insert($this->db_table, $this->mapToDB(), __METHOD__);
         $action = 'add';
     } else {
         $dbw->update($this->db_table, $this->mapToDB(), array('p_id' => $this->data['id']), __METHOD__);
         $action = 'edit';
     }
     if ($dbw->affectedRows()) {
         if ($action == 'add') {
             $this->data['id'] = $dbw->insertId();
         }
         $this->log($action);
     } else {
         $action = '';
     }
     $dbw->commit();
     wfProfileOut(__METHOD__);
     return $action ? $this->data['id'] : false;
 }
Example #5
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 getUserDetails()
 {
     if (is_null($this->usersData)) {
         $users = preg_split("/[\r\n]+/", $this->users);
         foreach ($users as $k => $v) {
             if (trim($v) == '') {
                 unset($users[$k]);
             }
         }
         $users = array_values($users);
         foreach ($users as $k => $name) {
             $userName = User::isIP($name) ? $name : User::getCanonicalName($name);
             $user = null;
             if ($userName !== false) {
                 $user = F::build('User', array($userName), 'newFromName');
                 if (empty($user) || $user->getId() == 0) {
                     $user = null;
                 }
             }
             $users[$k] = array('id' => !empty($user) ? $user->getId() : 0, 'ip' => User::isIP($name) ? $name : '', 'name' => $name, 'canonical' => $userName);
         }
         $this->usersData = $users;
     }
     return $this->usersData;
 }
function efNoBogusUserpagesUserCan($title, $user, $action, &$result)
{
    // If we're not in the user namespace,
    // or we're not trying to edit,
    // or the page already exists,
    // or we are allowed to create bogus userpages
    // then just let MediaWiki continue.
    if ($title->getNamespace() != NS_USER || $action != 'create' || $user->isAllowed('createbogususerpage')) {
        return true;
    }
    $userTitle = explode('/', $title->getText(), 2);
    $userName = $userTitle[0];
    // Don't block the creation of IP userpages if the page is for a IPv4 or IPv6 page.
    if (User::isIP($userName)) {
        return true;
    }
    // Check if the user exists, if it says the user is anon,
    // but we know we're not on an ip page, then the user does not exist.
    // And therefore, we block creation.
    $user = User::newFromName($userName);
    if ($user->isAnon()) {
        $result = 'badaccess-bogususerpage';
        return false;
    }
    return true;
}
 /**
  * Render the special page boddy
  * @param string $par The username
  */
 public function executeWhenAvailable($par = '')
 {
     $this->offset = $this->getRequest()->getVal('offset', false);
     if ($par) {
         // enter article history view
         $this->user = User::newFromName($par, false);
         if ($this->user && ($this->user->idForName() || User::isIP($par))) {
             // set page title as on desktop site - bug 66656
             $username = $this->user->getName();
             $out = $this->getOutput();
             $out->addModuleStyles(array('mobile.pagelist.styles', 'mobile.pagesummary.styles'));
             $out->setHTMLTitle($this->msg('pagetitle', $this->msg('contributions-title', $username)->plain())->inContentLanguage());
             if (User::isIP($par)) {
                 $this->renderHeaderBar($par);
             } else {
                 $this->renderHeaderBar($this->user->getUserPage());
             }
             $res = $this->doQuery();
             $out->addHtml(Html::openElement('div', array('class' => 'content-unstyled')));
             $this->showContributions($res);
             $out->addHtml(Html::closeElement('div'));
             return;
         }
     }
     $this->showPageNotFound();
 }
Example #9
0
 public function execute()
 {
     $params = $this->extractRequestParams();
     $titleObj = null;
     if (!isset($params['title'])) {
         $this->dieUsageMsg(array('missingparam', 'title'));
     }
     if (!isset($params['user'])) {
         $this->dieUsageMsg(array('missingparam', 'user'));
     }
     $titleObj = Title::newFromText($params['title']);
     if (!$titleObj) {
         $this->dieUsageMsg(array('invalidtitle', $params['title']));
     }
     if (!$titleObj->exists()) {
         $this->dieUsageMsg(array('notanarticle'));
     }
     // We need to be able to revert IPs, but getCanonicalName rejects them
     $username = User::isIP($params['user']) ? $params['user'] : User::getCanonicalName($params['user']);
     if (!$username) {
         $this->dieUsageMsg(array('invaliduser', $params['user']));
     }
     $articleObj = new Article($titleObj);
     $summary = isset($params['summary']) ? $params['summary'] : "";
     $details = null;
     $retval = $articleObj->doRollback($username, $summary, $params['token'], $params['markbot'], $details);
     if ($retval) {
         // We don't care about multiple errors, just report one of them
         $this->dieUsageMsg(reset($retval));
     }
     $info = array('title' => $titleObj->getPrefixedText(), 'pageid' => intval($details['current']->getPage()), 'summary' => $details['summary'], 'revid' => intval($details['newid']), 'old_revid' => intval($details['current']->getID()), 'last_revid' => intval($details['target']->getID()));
     $this->getResult()->addValue(null, $this->getModuleName(), $info);
 }
Example #10
0
 public function execute()
 {
     global $wgUser, $wgSharedDB;
     if ($this->getOption('onlyshared', false) && empty($wgSharedDB)) {
         $this->output("Skipping wiki due to non-shared users database\n");
         return;
     }
     $wgUser = User::newFromName(self::USER_NAME);
     $bot = true;
     $time = $this->getOption('time');
     $time = wfTimestamp(TS_UNIX, $time);
     if (!$time) {
         $this->error('Invalid time', true);
     }
     $time = wfTimestamp(TS_MW, $time);
     $users = explode('|', $this->getOption('users'));
     foreach ($users as $user) {
         $username = User::isIP($user) ? $user : User::getCanonicalName($user);
         if (!$username) {
             $this->error('Invalid username', true);
         }
     }
     $summary = $this->getOption('summary', 'mass rollback');
     $titles = array();
     $results = array();
     if ($this->hasOption('titles')) {
         foreach (explode('|', $this->getOption('titles')) as $title) {
             $t = Title::newFromText($title);
             if (!$t) {
                 $this->error('Invalid title, ' . $title);
             } else {
                 $titles[] = $t;
             }
         }
     } else {
         $titles = $this->getRollbackTitles($users, $time);
     }
     if (!$titles) {
         $this->output("No suitable titles to be rolled back\n");
         return;
     }
     $this->output("Found " . count($titles) . " title(s) to process\n");
     global $wgTitle;
     foreach ($titles as $t) {
         $wgTitle = $t;
         $this->output('Processing ' . $t->getPrefixedText() . '...');
         $messages = '';
         $status = $this->rollbackTitle($t, $users, $time, $summary, $messages);
         if ($status) {
             $this->output("done ({$messages})\n");
         } else {
             $this->output("failed ({$messages})\n");
         }
     }
 }
 public function validate($value, $alldata)
 {
     // check, if a user exists with the given username
     $user = User::newFromName($value, false);
     if (!$user) {
         return $this->msg('htmlform-user-not-valid', $value)->parse();
     } elseif ($this->mParams['exists'] && $user->getId() === 0 && !($this->mParams['ipallowed'] && User::isIP($value))) {
         return $this->msg('htmlform-user-not-exists', $user->getName())->parse();
     }
     return parent::validate($value, $alldata);
 }
 public function getRedirect($par)
 {
     if (User::isIP($par)) {
         return SpecialPage::getTitleFor('Contributions', $par);
     } else {
         $user = User::newFromName($par);
         if (!$user) {
             throw new BadTitleError();
         }
         if ($user->getId()) {
             return $user->getUserPage();
         } else {
             return SpecialPage::getTitleFor('Contributions', $par);
         }
     }
 }
	public function execute() {
		$params = $this->extractRequestParams();
		$result = OnlineStatusBar::getUserInfoFromString( $params['user'] );
		// if user is IP and we track them
		if ( User::isIP( $params['user'] ) && $result === false ) {
			$result = OnlineStatusBar::getAnonFromString( $params['user'] );
		}
		if ( $result === false ) {
			$ret = 'unknown';
		} else {
			$ret = $result[0];
		}

		$this->getResult()->addValue(
			null, $this->getModuleName(), array( 'result' => $ret ) );
	}
 function buildNavUrls()
 {
     global $wgTitle, $wgUser, $wgRequest;
     global $wgSiteSupportPage;
     $action = $wgRequest->getText('action');
     $oldid = $wgRequest->getVal('oldid');
     $diff = $wgRequest->getVal('diff');
     // XXX: remove htmlspecialchars when tal:attributes works with i18n:attributes
     $nav_urls = array();
     $nav_urls['mainpage'] = array('href' => htmlspecialchars($this->makeI18nUrl('mainpage')));
     $nav_urls['randompage'] = wfMsgForContent('randompage') != '-' ? array('href' => htmlspecialchars($this->makeSpecialUrl('Randompage'))) : false;
     $nav_urls['recentchanges'] = wfMsgForContent('recentchanges') != '-' ? array('href' => htmlspecialchars($this->makeSpecialUrl('Recentchanges'))) : false;
     $nav_urls['whatlinkshere'] = array('href' => htmlspecialchars($this->makeSpecialUrl('Whatlinkshere', 'target=' . urlencode($this->thispage))));
     $nav_urls['currentevents'] = wfMsgForContent('currentevents') != '-' ? array('href' => htmlspecialchars($this->makeI18nUrl('currentevents'))) : false;
     $nav_urls['portal'] = wfMsgForContent('portal') != '-' ? array('href' => htmlspecialchars($this->makeI18nUrl('portal-url'))) : false;
     $nav_urls['recentchangeslinked'] = array('href' => htmlspecialchars($this->makeSpecialUrl('Recentchangeslinked', 'target=' . urlencode($this->thispage))));
     $nav_urls['bugreports'] = wfMsgForContent('bugreports') != '-' ? array('href' => htmlspecialchars($this->makeI18nUrl('bugreportspage'))) : false;
     $nav_urls['sitesupport'] = array('href' => htmlspecialchars($wgSiteSupportPage));
     $nav_urls['help'] = array('href' => htmlspecialchars($this->makeI18nUrl('helppage')));
     $nav_urls['upload'] = array('href' => htmlspecialchars($this->makeSpecialUrl('Upload')));
     $nav_urls['specialpages'] = array('href' => htmlspecialchars($this->makeSpecialUrl('Specialpages')));
     # Specific for mediawiki.org menu
     $nav_urls['aboutmediawiki'] = wfMsgForContent('aboutmediawiki') != '-' ? array('href' => htmlspecialchars($this->makeI18nUrl('aboutmediawiki-url'))) : false;
     $nav_urls['projects'] = wfMsgForContent('projects') != '-' ? array('href' => htmlspecialchars($this->makeI18nUrl('projects-url'))) : false;
     $nav_urls['membership'] = wfMsgForContent('membership') != '-' ? array('href' => htmlspecialchars($this->makeI18nUrl('membership-url'))) : false;
     $nav_urls['pressroom'] = wfMsgForContent('pressroom') != '-' ? array('href' => htmlspecialchars($this->makeI18nUrl('pressroom-url'))) : false;
     $nav_urls['software'] = wfMsgForContent('software') != '-' ? array('href' => htmlspecialchars($this->makeI18nUrl('software-url'))) : false;
     $nav_urls['localchapters'] = wfMsgForContent('localchapters') != '-' ? array('href' => htmlspecialchars($this->makeI18nUrl('localchapters-url'))) : false;
     $nav_urls['contactus'] = wfMsgForContent('contactus') != '-' ? array('href' => htmlspecialchars($this->makeI18nUrl('contactus-url'))) : false;
     if ($wgTitle->getNamespace() == NS_USER || $wgTitle->getNamespace() == NS_USER_TALK) {
         $id = User::idFromName($wgTitle->getText());
         $ip = User::isIP($wgTitle->getText());
     } else {
         $id = 0;
         $ip = false;
     }
     if (0 != $wgUser->getID()) {
         # show only to signed in users
         if ($id) {
             # can only email non-anons
             $nav_urls['emailuser'] = array('href' => htmlspecialchars($this->makeSpecialUrl('Emailuser', "target=" . $wgTitle->getPartialURL())));
             # only non-anons have contrib list
             $nav_urls['contributions'] = array('href' => htmlspecialchars($this->makeSpecialUrl('Contributions', "target=" . $wgTitle->getPartialURL())));
         }
     }
     return $nav_urls;
 }
Example #15
0
 protected static function blockCheckInternal(User $user, $blocksData, $text, $isBlockIP = false, $writeStats = true)
 {
     global $wgMemc;
     wfProfileIn(__METHOD__);
     foreach ($blocksData as $blockData) {
         if ($isBlockIP && !$user->isIP($blockData['text'])) {
             continue;
         }
         $result = Phalanx::isBlocked($text, $blockData, $writeStats);
         if ($result['blocked']) {
             Wikia::log(__METHOD__, __LINE__, "Block '{$result['msg']}' blocked '{$text}'.");
             self::setUserData($user, $blockData, $text, $isBlockIP);
             $cachedState = array('timestamp' => wfTimestampNow(), 'block' => $blockData, 'return' => false);
             $wgMemc->set(self::getCacheKey($user), $cachedState);
             wfProfileOut(__METHOD__);
             return false;
         }
     }
     wfProfileOut(__METHOD__);
     return true;
 }
Example #16
0
 /**
  * save
  *
  * @return boolean: true on success, false on failure
  */
 public static function save($data, $updateCache = true)
 {
     global $wgExternalSharedDB, $wgMemc;
     $result = false;
     wfProfileIn(__METHOD__);
     if ($data['type'] & Phalanx::TYPE_USER && User::isIP($data['text'])) {
         $data['ip_hex'] = IP::toHex($data['text']);
     }
     $dbw = wfGetDB(DB_MASTER, array(), $wgExternalSharedDB);
     $dbw->insert('phalanx', self::convertDataToDB($data), __METHOD__);
     if ($dbw->affectedRows()) {
         $data['id'] = $result = $dbw->insertId();
         $dbw->commit();
         if ($updateCache) {
             self::updateCache(null, $data);
         }
         self::logAdd($data);
         self::reload($data['id']);
     }
     wfProfileOut(__METHOD__);
     return $result;
 }
 public function index()
 {
     if (self::$skipRendering) {
         return false;
     }
     $this->response->setTemplateEngine(WikiaResponse::TEMPLATE_ENGINE_MUSTACHE);
     $wg = $this->wg;
     $out = $wg->Out;
     $titleText = $out->getPageTitle();
     $title = $out->getTitle();
     $namespace = $title instanceof Title ? $title->getNamespace() : -1;
     $this->response->setVal('pageTitle', $this->getTitleText($titleText, $namespace));
     $article = $this->wg->Article;
     if ($article instanceof Article) {
         $revision = $article->getPage()->getRevision();
         if ($revision instanceof Revision) {
             $user = User::newFromId($revision->getRawUser());
             $userName = $user->getName();
             if (User::isIP($userName)) {
                 //For anonymous users don't display IP
                 $userName = wfMessage('wikiamobile-anonymous-edited-by')->text();
             } else {
                 //Wrap username in a link to user page
                 $userName = "******";
             }
             $this->response->setVal('lastEditedOn', wfMessage('wikiamobile-last-edited-on')->params($this->wg->Lang->date($revision->getTimestamp()))->text());
             $this->response->setVal('lastEditedBy', wfMessage('wikiamobile-last-edited-by')->params($userName)->text());
         }
     }
     if ($wg->EnableArticleCommentsExt && in_array($title->getNamespace(), $wg->ContentNamespaces) && !$wg->Title->isMainPage() && $wg->request->getVal('action', 'view') == 'view') {
         $numberOfComments = ArticleCommentList::newFromTitle($title)->getCountAllNested();
         $this->response->setVal('commentCounter', wfMessage('wikiamobile-article-comments-counter')->params($numberOfComments)->text());
     }
     $this->response->setVal('editLink', $this->getTitleEditUrl());
     if ($namespace == NS_CATEGORY) {
         $this->response->setVal('categoryPage', wfMessage('wikiamobile-categories-tagline')->inContentLanguage()->plain());
     }
     return true;
 }
Example #18
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::makeTitleSafe(NS_USER, $userName);
         if (is_null($nt)) {
             $this->outputUserDoesNotExist($userName);
         } else {
             $this->mUserName = $nt->getText();
             $user = User::newFromName($this->mUserName, false);
             if ($user) {
                 $this->mUser = $user;
             }
             if (!$user || $user->isAnon() && !User::isIP($user->getName())) {
                 $this->outputUserDoesNotExist($userName);
             }
         }
     }
     if ($search !== '' && !$this->getConfig()->get('MiserMode')) {
         $this->mSearch = $search;
         $nt = Title::newFromText($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($params)
 {
     global $wgOut, $wgUser;
     $skin = $wgUser->getSkin();
     $this->setHeaders();
     $this->loadRequest($params);
     $wgOut->addHTML($this->makeForm());
     if ($this->target) {
         if (User::isIP($this->target)) {
             $this->showResults($this->countEditsReal(0, $this->target));
         } else {
             $id = User::idFromName($this->target);
             if ($id) {
                 $this->showResults($this->countEditsReal($id, false), $id);
             } else {
                 $wgOut->addHTML('<p>' . wfMsgHtml('countedits-nosuchuser', htmlspecialchars($this->target)) . '</p>');
             }
         }
     }
     $this->showTopTen($wgOut);
     return true;
 }
Example #20
0
 public function execute()
 {
     $user = $this->getOption('user');
     $username = User::isIP($user) ? $user : User::getCanonicalName($user);
     if (!$username) {
         $this->error('Invalid username', true);
     }
     $bot = $this->hasOption('bot');
     $summary = $this->getOption('summary', $this->mSelf . ' mass rollback');
     $titles = array();
     $results = array();
     if ($this->hasOption('titles')) {
         foreach (explode('|', $this->getOption('titles')) as $title) {
             $t = Title::newFromText($title);
             if (!$t) {
                 $this->error('Invalid title, ' . $title);
             } else {
                 $titles[] = $t;
             }
         }
     } else {
         $titles = $this->getRollbackTitles($user);
     }
     if (!$titles) {
         $this->output('No suitable titles to be rolled back');
         return;
     }
     $doer = User::newFromName('Maintenance script');
     foreach ($titles as $t) {
         $page = WikiPage::factory($t);
         $this->output('Processing ' . $t->getPrefixedText() . '... ');
         if (!$page->commitRollback($user, $summary, $bot, $results, $doer)) {
             $this->output("done\n");
         } else {
             $this->output("failed\n");
         }
     }
 }
	/**
	 * Retrieves and shows the user language and test wiki
	 * @param $target Mixed: user whose language and test wiki we're looking up
	 */
	function showInfo( $target ) {
		global $wgOut, $wmincPref, $wmincProjectSite;
		if( User::isIP( $target ) ) {
			# show error if it is an IP address
			$wgOut->addHTML( Xml::span( wfMsg( 'wminc-ip', $target ), 'error' ) );
			return;
		}
		$user = User::newFromName( $target );
		$name = $user->getName();
		$id = $user->getId();
		$langNames = Language::getLanguageNames();
		$linker = class_exists( 'DummyLinker' ) ? new DummyLinker : new Linker;
		if ( $user == null || $id == 0 ) {
			# show error if a user with that name does not exist
			$wgOut->addHTML( Xml::span( wfMsg( 'wminc-userdoesnotexist', $target ), 'error' ) );
			return;
		}
		$userproject = $user->getOption( $wmincPref . '-project' );
		$userproject = ( $userproject ? $userproject : 'none' );
		$usercode = $user->getOption( $wmincPref . '-code' );
		$prefix = IncubatorTest::displayPrefix( $userproject, $usercode ? $usercode : 'none' );
		if ( IncubatorTest::isContentProject( $userproject ) ) {
			$testwiki = $linker->link( Title::newFromText( $prefix ) );
		} elseif ( $prefix == $wmincProjectSite['short'] ) {
			$testwiki = htmlspecialchars( $wmincProjectSite['name'] );
		} else {
			$testwiki = wfMsgHtml( 'wminc-testwiki-none' );
		}
		$wgOut->addHtml(
			Xml::openElement( 'ul' ) .
			'<li>' . wfMsgHtml( 'username' ) . ' ' .
				$linker->userLink( $id, $name ) . $linker->userToolLinks( $id, $name, true ) . '</li>' .
			'<li>' . wfMsgHtml( 'loginlanguagelabel', $langNames[$user->getOption( 'language' )] .
				' (' . $user->getOption( 'language' ) . ')' ) . '</li>' .
			'<li>' . wfMsgHtml( 'wminc-testwiki' ) . ' ' . $testwiki . '</li>' .
			Xml::closeElement( 'ul' )
		);
	}
 /**
  * Render the special page boddy
  * @param string $par The username
  */
 public function executeWhenAvailable($par = '')
 {
     $this->offset = $this->getRequest()->getVal('offset', false);
     if ($par) {
         // enter article history view
         $this->user = User::newFromName($par, false);
         if ($this->user && ($this->user->idForName() || User::isIP($par))) {
             // set page title as on desktop site - bug 66656
             $username = $this->user->getName();
             $out = $this->getOutput();
             $out->setHTMLTitle($this->msg('pagetitle', $this->msg('contributions-title', $username)->plain())->inContentLanguage());
             if (User::isIP($par)) {
                 $this->renderHeaderBar($par);
             } else {
                 $this->renderHeaderBar($this->user->getUserPage());
             }
             $res = $this->doQuery();
             $this->showContributions($res);
             return;
         }
     }
     $this->showPageNotFound();
 }
Example #23
0
function efCurrentUsersMagic(&$parser)
{
    global $egCurrentUsers, $egCurrentUsersTemplate, $wgTitle;
    $parser->disableCache();
    $users = '';
    $guests = 0;
    $bots = 0;
    foreach ($egCurrentUsers as $item) {
        list($h, $m, $u, $b) = explode(':', $item);
        if (User::isIP($u)) {
            $b ? $bots++ : $guests++;
        } else {
            $users .= "{" . "{" . "{$egCurrentUsersTemplate}|{$h}:{$m}|{$u}|}" . "}\n";
        }
    }
    if ($guests) {
        $users .= "{" . "{" . "{$egCurrentUsersTemplate}|Guests||{$guests}}" . "}\n";
    }
    if ($bots) {
        $users .= "{" . "{" . "{$egCurrentUsersTemplate}|Robots||{$bots}}" . "}\n";
    }
    $users = $parser->preprocess($users, $wgTitle, $parser->mOptions);
    return array($users, 'found' => true, 'nowiki' => false, 'noparse' => false, 'noargs' => false, 'isHTML' => false);
}
Example #24
0
 private function getRbUser()
 {
     if ($this->mUser !== null) {
         return $this->mUser;
     }
     $params = $this->extractRequestParams();
     // We need to be able to revert IPs, but getCanonicalName rejects them
     $this->mUser = User::isIP($params['user']) ? $params['user'] : User::getCanonicalName($params['user']);
     if (!$this->mUser) {
         $this->dieUsageMsg(array('invaliduser', $params['user']));
     }
     return $this->mUser;
 }
Example #25
0
	/**
	 * Do standard deferred updates after page edit.
	 * Update links tables, site stats, search index and message cache.
	 * Purges pages that include this page if the text was changed here.
	 * Every 100th edit, prune the recent changes table.
	 *
	 * @param $revision Revision object
	 * @param $user User object that did the revision
	 * @param array $options of options, following indexes are used:
	 * - changed: boolean, whether the revision changed the content (default true)
	 * - created: boolean, whether the revision created the page (default false)
	 * - oldcountable: boolean or null (default null):
	 *   - boolean: whether the page was counted as an article before that
	 *     revision, only used in changed is true and created is false
	 *   - null: don't change the article count
	 */
	public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
		global $wgEnableParserCache;

		wfProfileIn( __METHOD__ );

		$options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
		$content = $revision->getContent();

		// Parse the text
		// Be careful not to do pre-save transform twice: $text is usually
		// already pre-save transformed once.
		if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
			wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
			$editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
		} else {
			wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
			$editInfo = $this->mPreparedEdit;
		}

		// Save it to the parser cache
		if ( $wgEnableParserCache ) {
			$parserCache = ParserCache::singleton();
			$parserCache->save( $editInfo->output, $this, $editInfo->popts );
		}

		// Update the links tables and other secondary data
		if ( $content ) {
			$recursive = $options['changed']; // bug 50785
			$updates = $content->getSecondaryDataUpdates(
				$this->getTitle(), null, $recursive, $editInfo->output );
			DataUpdate::runUpdates( $updates );
		}

		wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );

		if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
			if ( 0 == mt_rand( 0, 99 ) ) {
				// Flush old entries from the `recentchanges` table; we do this on
				// random requests so as to avoid an increase in writes for no good reason
				RecentChange::purgeExpiredChanges();
			}
		}

		if ( !$this->exists() ) {
			wfProfileOut( __METHOD__ );
			return;
		}

		$id = $this->getId();
		$title = $this->mTitle->getPrefixedDBkey();
		$shortTitle = $this->mTitle->getDBkey();

		if ( !$options['changed'] ) {
			$good = 0;
			$total = 0;
		} elseif ( $options['created'] ) {
			$good = (int)$this->isCountable( $editInfo );
			$total = 1;
		} elseif ( $options['oldcountable'] !== null ) {
			$good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
			$total = 0;
		} else {
			$good = 0;
			$total = 0;
		}

		DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
		DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );

		// If this is another user's talk page, update newtalk.
		// Don't do this if $options['changed'] = false (null-edits) nor if
		// it's a minor edit and the user doesn't want notifications for those.
		if ( $options['changed']
			&& $this->mTitle->getNamespace() == NS_USER_TALK
			&& $shortTitle != $user->getTitleKey()
			&& !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
		) {
			$recipient = User::newFromName( $shortTitle, false );
			if ( !$recipient ) {
				wfDebug( __METHOD__ . ": invalid username\n" );
			} else {
				// Allow extensions to prevent user notification when a new message is added to their talk page
				if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
					if ( User::isIP( $shortTitle ) ) {
						// An anonymous user
						$recipient->setNewtalk( true, $revision );
					} elseif ( $recipient->isLoggedIn() ) {
						$recipient->setNewtalk( true, $revision );
					} else {
						wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
					}
				}
			}
		}

		if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
			// XXX: could skip pseudo-messages like js/css here, based on content model.
			$msgtext = $content ? $content->getWikitextForTransclusion() : null;
			if ( $msgtext === false || $msgtext === null ) {
				$msgtext = '';
			}

			MessageCache::singleton()->replace( $shortTitle, $msgtext );
		}

		if ( $options['created'] ) {
			self::onArticleCreate( $this->mTitle );
		} else {
			self::onArticleEdit( $this->mTitle );
		}

		wfProfileOut( __METHOD__ );
	}
Example #26
0
 /**
  * Is the input a valid username?
  *
  * Checks if the input is a valid username, we don't want an empty string,
  * an IP address, anything that containins slashes (would mess up subpages),
  * is longer than the maximum allowed username size or doesn't begin with
  * a capital letter.
  *
  * @param string $name
  * @return bool
  * @static
  */
 function isValidUserName($name)
 {
     global $wgContLang, $wgMaxNameChars;
     if ($name == '' || User::isIP($name) || strpos($name, '/') !== false || strlen($name) > $wgMaxNameChars || $name != $wgContLang->ucfirst($name)) {
         return false;
     }
     // Ensure that the name can't be misresolved as a different title,
     // such as with extra namespace keys at the start.
     $parsed = Title::newFromText($name);
     if (is_null($parsed) || $parsed->getNamespace() || strcmp($name, $parsed->getPrefixedText())) {
         return false;
     }
     // Check an additional blacklist of troublemaker characters.
     // Should these be merged into the title char list?
     $unicodeBlacklist = '/[' . '\\x{0080}-\\x{009f}' . '\\x{00a0}' . '\\x{2000}-\\x{200f}' . '\\x{2028}-\\x{202f}' . '\\x{3000}' . '\\x{e000}-\\x{f8ff}' . ']/u';
     if (preg_match($unicodeBlacklist, $name)) {
         return false;
     }
     return true;
 }
 protected function prepareUsername($user)
 {
     if (!$user) {
         $this->dieUsage('User parameter may not be empty', 'param_user');
     }
     $name = User::isIP($user) ? $user : User::getCanonicalName($user, 'valid');
     if ($name === false) {
         $this->dieUsage("User name {$user} is not valid", 'param_user');
     }
     $this->usernames[] = $name;
 }
Example #28
0
 /**
  * Get the user's ID.
  * @return Int The user's ID; 0 if the user is anonymous or nonexistent
  */
 public function getId()
 {
     if ($this->mId === null && $this->mName !== null && User::isIP($this->mName)) {
         // Special case, we know the user is anonymous
         return 0;
     } elseif (!$this->isItemLoaded('id')) {
         // Don't load if this was initialized from an ID
         $this->load();
     }
     return $this->mId;
 }
Example #29
0
 /**
  * Show the error text for a missing article. For articles in the MediaWiki
  * namespace, show the default message text. To be called from Article::view().
  */
 public function showMissingArticle()
 {
     global $wgSend404Code;
     $outputPage = $this->getContext()->getOutput();
     // Whether the page is a root user page of an existing user (but not a subpage)
     $validUserPage = false;
     $title = $this->getTitle();
     # Show info in user (talk) namespace. Does the user exist? Is he blocked?
     if ($title->getNamespace() == NS_USER || $title->getNamespace() == NS_USER_TALK) {
         $parts = explode('/', $title->getText());
         $rootPart = $parts[0];
         $user = User::newFromName($rootPart, false);
         $ip = User::isIP($rootPart);
         $block = Block::newFromTarget($user, $user);
         if (!($user && $user->isLoggedIn()) && !$ip) {
             # User does not exist
             $outputPage->wrapWikiMsg("<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>", array('userpage-userdoesnotexist-view', wfEscapeWikiText($rootPart)));
         } elseif (!is_null($block) && $block->getType() != Block::TYPE_AUTO) {
             # Show log extract if the user is currently blocked
             LogEventsList::showLogExtract($outputPage, 'block', MWNamespace::getCanonicalName(NS_USER) . ':' . $block->getTarget(), '', array('lim' => 1, 'showIfEmpty' => false, 'msgKey' => array('blocked-notice-logextract', $user->getName())));
             $validUserPage = !$title->isSubpage();
         } else {
             $validUserPage = !$title->isSubpage();
         }
     }
     Hooks::run('ShowMissingArticle', array($this));
     # Show delete and move logs if there were any such events.
     # The logging query can DOS the site when bots/crawlers cause 404 floods,
     # so be careful showing this. 404 pages must be cheap as they are hard to cache.
     $cache = ObjectCache::getMainStashInstance();
     $key = wfMemcKey('page-recent-delete', md5($title->getPrefixedText()));
     $loggedIn = $this->getContext()->getUser()->isLoggedIn();
     if ($loggedIn || $cache->get($key)) {
         $logTypes = array('delete', 'move');
         $conds = array("log_action != 'revision'");
         // Give extensions a chance to hide their (unrelated) log entries
         Hooks::run('Article::MissingArticleConditions', array(&$conds, $logTypes));
         LogEventsList::showLogExtract($outputPage, $logTypes, $title, '', array('lim' => 10, 'conds' => $conds, 'showIfEmpty' => false, 'msgKey' => array($loggedIn ? 'moveddeleted-notice' : 'moveddeleted-notice-recent')));
     }
     if (!$this->mPage->hasViewableContent() && $wgSend404Code && !$validUserPage) {
         // If there's no backing content, send a 404 Not Found
         // for better machine handling of broken links.
         $this->getContext()->getRequest()->response()->statusHeader(404);
     }
     // Also apply the robot policy for nonexisting pages (even if a 404 was used for sanity)
     $policy = $this->getRobotPolicy('view');
     $outputPage->setIndexPolicy($policy['index']);
     $outputPage->setFollowPolicy($policy['follow']);
     $hookResult = Hooks::run('BeforeDisplayNoArticleText', array($this));
     if (!$hookResult) {
         return;
     }
     # Show error message
     $oldid = $this->getOldID();
     if (!$oldid && $title->getNamespace() === NS_MEDIAWIKI && $title->hasSourceText()) {
         $outputPage->addParserOutput($this->getContentObject()->getParserOutput($title));
     } else {
         if ($oldid) {
             $text = wfMessage('missing-revision', $oldid)->plain();
         } elseif ($title->quickUserCan('create', $this->getContext()->getUser()) && $title->quickUserCan('edit', $this->getContext()->getUser())) {
             $message = $this->getContext()->getUser()->isLoggedIn() ? 'noarticletext' : 'noarticletextanon';
             $text = wfMessage($message)->plain();
         } else {
             $text = wfMessage('noarticletext-nopermission')->plain();
         }
         $dir = $this->getContext()->getLanguage()->getDir();
         $lang = $this->getContext()->getLanguage()->getCode();
         $outputPage->addWikiText(Xml::openElement('div', array('class' => "noarticletext mw-content-{$dir}", 'dir' => $dir, 'lang' => $lang)) . "\n{$text}\n</div>");
     }
 }
Example #30
0
 function bottomLinks()
 {
     global $wgOut, $wgUser, $wgTitle, $wgUseTrackbacks;
     $sep = wfMsgExt('pipe-separator', 'escapenoentities') . "\n";
     $s = '';
     if ($wgOut->isArticleRelated()) {
         $element[] = '<strong>' . $this->editThisPage() . '</strong>';
         if ($wgUser->isLoggedIn()) {
             $element[] = $this->watchThisPage();
         }
         $element[] = $this->talkLink();
         $element[] = $this->historyLink();
         $element[] = $this->whatLinksHere();
         $element[] = $this->watchPageLinksLink();
         if ($wgUseTrackbacks) {
             $element[] = $this->trackbackLink();
         }
         if ($wgTitle->getNamespace() == NS_USER || $wgTitle->getNamespace() == NS_USER_TALK) {
             $id = User::idFromName($wgTitle->getText());
             $ip = User::isIP($wgTitle->getText());
             if ($id || $ip) {
                 # both anons and non-anons have contri list
                 $element[] = $this->userContribsLink();
             }
             if ($this->showEmailUser($id)) {
                 $element[] = $this->emailUserLink();
             }
         }
         $s = implode($element, $sep);
         if ($wgTitle->getArticleId()) {
             $s .= "\n<br />";
             if ($wgUser->isAllowed('delete')) {
                 $s .= $this->deleteThisPage();
             }
             if ($wgUser->isAllowed('protect')) {
                 $s .= $sep . $this->protectThisPage();
             }
             if ($wgUser->isAllowed('move')) {
                 $s .= $sep . $this->moveThisPage();
             }
         }
         $s .= "<br />\n" . $this->otherLanguages();
     }
     return $s;
 }