public function getMessageParameters()
 {
     $params = parent::getMessageParameters();
     $type = $this->entry->getFullType();
     if ($type === 'translationreview/message') {
         $targetPage = $this->makePageLink($this->entry->getTarget(), array('oldid' => $params[3]));
         $params[2] = Message::rawParam($targetPage);
     } elseif ($type === 'translationreview/group') {
         /*
          * - 3: language code
          * - 4: label of the message group
          * - 5: old state
          * - 6: new state
          */
         $uiLanguage = $this->context->getLanguage();
         $language = $params[3];
         $targetPage = $this->makePageLinkWithText($this->entry->getTarget(), $params[4], array('language' => $language));
         $params[2] = Message::rawParam($targetPage);
         $params[3] = TranslateUtils::getLanguageName($language, $uiLanguage->getCode());
         $params[5] = $this->formatStateMessage($params[5]);
         $params[6] = $this->formatStateMessage($params[6]);
     } elseif ($type === 'translatorsandbox/rejected') {
         // No point linking to the user page which cannot have existed
         $params[2] = $this->entry->getTarget()->getText();
     } elseif ($type === 'translatorsandbox/promoted') {
         // Gender for the target
         $params[3] = User::newFromId($params[3])->getName();
     }
     return $params;
 }
	/**
	 * Sends the notification about a new gift to the user who received the
	 * gift, if the user wants notifications about new gifts and their e-mail
	 * is confirmed.
	 *
	 * @param $user_id_to Integer: user ID of the receiver of the gift
	 * @param $user_from Mixed: name of the user who sent the gift
	 * @param $gift_id Integer: ID number of the given gift
	 * @param $type Integer: gift type; unused
	 */
	public function sendGiftNotificationEmail( $user_id_to, $user_from, $gift_id, $type ) {
		$gift = Gifts::getGift( $gift_id );
		$user = User::newFromId( $user_id_to );
		$user->loadFromDatabase();
		if ( $user->isEmailConfirmed() && $user->getIntOption( 'notifygift', 1 ) ) {
			$giftsLink = SpecialPage::getTitleFor( 'ViewGifts' );
			$updateProfileLink = SpecialPage::getTitleFor( 'UpdateProfile' );
			if ( trim( $user->getRealName() ) ) {
				$name = $user->getRealName();
			} else {
				$name = $user->getName();
			}
			$subject = wfMsgExt( 'gift_received_subject', 'parsemag',
				$user_from,
				$gift['gift_name']
			);
			$body = wfMsgExt( 'gift_received_body', 'parsemag',
				$name,
				$user_from,
				$gift['gift_name'],
				$giftsLink->getFullURL(),
				$updateProfileLink->getFullURL()
			);

			$user->sendMail( $subject, $body );
		}
	}
    /**
     * Handles group notification.
     * 
     * @since 0.1
     *
     * @param SWLGroup $group
     * @param array $userIDs
     * @param SMWChangeSet $changes
     *
     * @return true
     */    
    public static function onGroupNotify( SWLGroup $group, array $userIDs, SWLChangeSet $changes ) {
    	global $egSWLMailPerChange, $egSWLMaxMails;
    	
    	foreach ( $userIDs as $userID ) {
    		$user = User::newFromId( $userID );
    		
    		if ( $user->getOption( 'swl_email', false ) ) {
    			if ( !method_exists( 'Sanitizer', 'validateEmail' ) || Sanitizer::validateEmail( $user->getEmail() ) ) {
					$lastNotify = $user->getOption( 'swl_last_notify' );
					$lastWatch = $user->getOption( 'swl_last_watch' );
	    		
		    		if ( is_null( $lastNotify ) || is_null( $lastWatch ) || $lastNotify < $lastWatch ) {
		    			$mailCount = $user->getOption( 'swl_mail_count', 0 );
		    			
		    			if ( $egSWLMailPerChange || $mailCount < $egSWLMaxMails ) {
			    			SWLEmailer::notifyUser( $group, $user, $changes, $egSWLMailPerChange );
			    			$user->setOption( 'swl_last_notify', wfTimestampNow() );
			    			$user->setOption( 'swl_mail_count', $mailCount + 1 );
			    			$user->saveSettings();	    				
		    			}
		    		}      				
    			}
    		}
    	}
    	
        return true;
    }
 public function execute()
 {
     $this->output("Remove test accounts\n\n");
     $users_to_remove = array('noemail', 'bobtest', 'iamslow');
     $del = array();
     $dbr = wfGetDB(DB_SLAVE);
     $res = $dbr->select('user', array('user_id', 'user_name'), '', __METHOD__);
     foreach ($res as $row) {
         $instance = User::newFromId($row->user_id);
         if (in_array($row->user_name, $users_to_remove)) {
             $del[] = $row->user_id;
             $this->output($row->user_name . "\n");
         }
     }
     $count = count($del);
     $this->output("...found {$count}.\n");
     # If required, go back and delete each marked account
     if ($count > 0 && $this->hasOption('delete')) {
         $this->output("\nDeleting unused accounts...");
         $dbw = wfGetDB(DB_MASTER);
         $dbw->delete('user', array('user_id' => $del), __METHOD__);
         $dbw->delete('user_groups', array('ug_user' => $del), __METHOD__);
         $dbw->delete('user_former_groups', array('ufg_user' => $del), __METHOD__);
         $dbw->delete('user_properties', array('up_user' => $del), __METHOD__);
         $dbw->delete('logging', array('log_user' => $del), __METHOD__);
         $dbw->delete('recentchanges', array('rc_user' => $del), __METHOD__);
         $this->output("done.\n");
         # Update the site_stats.ss_users field
         $users = $dbw->selectField('user', 'COUNT(*)', array(), __METHOD__);
         $dbw->update('site_stats', array('ss_users' => $users), array('ss_row_id' => 1), __METHOD__);
     } elseif ($count > 0) {
         $this->output("\nRun the script again with --delete to remove them from the database.\n");
     }
     $this->output("\n");
 }
 /**
  * Perform the queries necessary to update the social point counts and
  * purge memcached entries.
  */
 function updateMainEditsCount()
 {
     global $wgOut, $wgNamespacesForEditPoints;
     $whereConds = array();
     $whereConds[] = 'rev_user <> 0';
     // If points are given out for editing non-main namespaces, take that
     // into account too.
     if (isset($wgNamespacesForEditPoints) && is_array($wgNamespacesForEditPoints)) {
         foreach ($wgNamespacesForEditPoints as $pointNamespace) {
             $whereConds[] = 'page_namespace = ' . (int) $pointNamespace;
         }
     }
     $dbw = wfGetDB(DB_MASTER);
     $res = $dbw->select(array('revision', 'page'), array('rev_user_text', 'rev_user', 'COUNT(*) AS the_count'), $whereConds, __METHOD__, array('GROUP BY' => 'rev_user_text'), array('page' => array('INNER JOIN', 'page_id = rev_page')));
     foreach ($res as $row) {
         $user = User::newFromId($row->rev_user);
         $user->loadFromId();
         if (!$user->isAllowed('bot')) {
             $editCount = $row->the_count;
         } else {
             $editCount = 0;
         }
         $s = $dbw->selectRow('user_stats', array('stats_user_id'), array('stats_user_id' => $row->rev_user), __METHOD__);
         if (!$s->stats_user_id || $s === false) {
             $dbw->insert('user_stats', array('stats_year_id' => 0, 'stats_user_id' => $row->rev_user, 'stats_user_name' => $row->rev_user_text, 'stats_total_points' => 1000), __METHOD__);
         }
         $wgOut->addHTML("<p>Updating {$row->rev_user_text} with {$editCount} edits</p>");
         $dbw->update('user_stats', array('stats_edit_count = ' . $editCount), array('stats_user_id' => $row->rev_user), __METHOD__);
         global $wgMemc;
         // clear stats cache for current user
         $key = wfMemcKey('user', 'stats', $row->rev_user);
         $wgMemc->delete($key);
     }
 }
 /**
  * Transforms content to be mobile friendly version.
  * Filters out various elements and runs the MobileFormatter.
  * @param OutputPage $out
  * @param string $mode mobile mode, i.e. stable or beta
  *
  * @return string
  */
 public static function DOMParse(OutputPage $out, $text = null, $isBeta = false)
 {
     $html = $text ? $text : $out->getHTML();
     $context = MobileContext::singleton();
     $formatter = MobileFormatter::newFromContext($context, $html);
     Hooks::run('MobileFrontendBeforeDOM', array($context, $formatter));
     $title = $out->getTitle();
     $isSpecialPage = $title->isSpecialPage();
     $formatter->enableExpandableSections($out->canUseWikiPage() && $out->getWikiPage()->getContentModel() == CONTENT_MODEL_WIKITEXT && array_search($title->getNamespace(), $context->getMFConfig()->get('MFNamespacesWithoutCollapsibleSections')) === false && $context->getRequest()->getText('action', 'view') == 'view');
     if ($context->getContentTransformations()) {
         // Remove images if they're disabled from special pages, but don't transform otherwise
         $formatter->filterContent(!$isSpecialPage);
     }
     $contentHtml = $formatter->getText();
     // If the page is a user page which has not been created, then let the
     // user know about it with pretty graphics and different texts depending
     // on whether the user is the owner of the page or not.
     if ($isBeta && $title->inNamespace(NS_USER) && !$title->isSubpage()) {
         $pageUserId = User::idFromName($title->getText());
         if ($pageUserId && !$title->exists()) {
             $pageUser = User::newFromId($pageUserId);
             $contentHtml = ExtMobileFrontend::getUserPageContent($out, $pageUser);
         }
     }
     return $contentHtml;
 }
 function execute()
 {
     $dbw = wfGetDB(DB_MASTER);
     $batchSize = 100;
     $total = 0;
     $lastUserID = 0;
     while (true) {
         $res = $dbw->select('user_properties', array('up_user'), array('up_property' => 'vector-noexperiments', "up_user > {$lastUserID}"), __METHOD__, array('LIMIT' => $batchSize));
         if (!$res->numRows()) {
             $dbw->commit();
             break;
         }
         $total += $res->numRows();
         $ids = array();
         foreach ($res as $row) {
             $ids[] = $row->up_user;
         }
         $lastUserID = max($ids);
         foreach ($ids as $id) {
             $user = User::newFromId($id);
             if (!$user->isLoggedIn()) {
                 continue;
             }
             $user->setOption($this->getOption('pref'), $this->getOption('value'));
             $user->saveSettings();
         }
         echo "{$total}\n";
         wfWaitForSlaves();
         // Must be wfWaitForSlaves_masterPos(); on 1.17wmf1
     }
     echo "Done\n";
 }
Example #8
0
 /**
  * (non-PHPdoc)
  * @see EPPager::getFormattedValue()
  */
 protected function getFormattedValue($name, $value)
 {
     switch ($name) {
         case 'id':
             $value = Linker::linkKnown(SpecialPage::getTitleFor('Student', $value), htmlspecialchars($this->getLanguage()->formatNum($value, true)));
             break;
         case 'user_id':
             $user = User::newFromId($value);
             $name = $user->getRealName() === '' ? $user->getName() : $user->getRealName();
             $value = Linker::userLink($value, $name) . Linker::userToolLinks($value, $name);
             break;
         case 'first_enroll':
         case 'last_active':
             $value = htmlspecialchars($this->getLanguage()->date($value));
             break;
         case 'active_enroll':
             $value = wfMsgHtml($value === '1' ? 'epstudentpager-yes' : 'epstudentpager-no');
             break;
         case '_courses_current':
             $value = $this->getLanguage()->pipeList(array_map(function (EPCourse $course) {
                 return $course->getLink();
             }, $this->currentObject->getCoursesWithState('current', 'name')));
             break;
     }
     return $value;
 }
 public static function calcRecommendations($filename, $limit = false)
 {
     $f = fopen($filename, "w");
     $stubs = Recommendations::findStubs($limit);
     $r = new Recommendations();
     $r->excludeWorstRelated(250);
     $userScore = array();
     foreach ($stubs as $stub) {
         if ($stub) {
             $userScore = $r->getSuggestedUsers($stub);
             arsort($userScore);
             foreach ($userScore as $username => $score) {
                 if (Recommendations::isAvailableUser($username)) {
                     print wfTimestampNow() . " Adding recommendation to edit " . $stub->getText() . " for user " . $username . "\n";
                     $u = User::newFromId($username);
                     if ($u && $u->getId()) {
                         fwrite($f, $u->getId() . "\t" . $stub->getArticleId() . "\t" . $score);
                         $reasons = $r->getSuggestionReason($username, $stub->getArticleId());
                         foreach ($reasons as $reason) {
                             fwrite($f, "\t" . $reason);
                         }
                         fwrite($f, "\n");
                     }
                 }
             }
         }
     }
 }
 /**
  * Run a dtImport job
  * @return boolean success
  */
 function run()
 {
     wfProfileIn(__METHOD__);
     if (is_null($this->title)) {
         $this->error = "dtImport: Invalid title";
         wfProfileOut(__METHOD__);
         return false;
     }
     $article = new Article($this->title);
     if (!$article) {
         $this->error = 'dtImport: Article not found "' . $this->title->getPrefixedDBkey() . '"';
         wfProfileOut(__METHOD__);
         return false;
     }
     $for_pages_that_exist = $this->params['for_pages_that_exist'];
     if ($for_pages_that_exist == 'skip' && $this->title->exists()) {
         return true;
     }
     // change global $wgUser variable to the one specified by
     // the job only for the extent of this import
     global $wgUser;
     $actual_user = $wgUser;
     $wgUser = User::newFromId($this->params['user_id']);
     $text = $this->params['text'];
     if ($for_pages_that_exist == 'append' && $this->title->exists()) {
         $text = $article->getContent() . "\n" . $text;
     }
     $edit_summary = $this->params['edit_summary'];
     $article->doEdit($text, $edit_summary);
     $wgUser = $actual_user;
     wfProfileOut(__METHOD__);
     return true;
 }
Example #11
0
 public function execute()
 {
     global $wgUser;
     $this->checkPermission($wgUser);
     $params = $this->extractRequestParams();
     $res = array();
     $concurrencyCheck = new ConcurrencyCheck($params['resourcetype'], $wgUser);
     switch ($params['ccaction']) {
         case 'checkout':
         case 'checkin':
             if ($concurrencyCheck->{$params}['ccaction']($params['record'])) {
                 $res['result'] = 'success';
             } else {
                 $res['result'] = 'failure';
             }
             // data to be utilized by the caller for checkout
             if ($params['ccaction'] === 'checkout') {
                 $lastCheckout = $concurrencyCheck->checkoutResult();
                 if ($res['result'] === 'success') {
                     $user = $wgUser;
                 } else {
                     $user = User::newFromId(intval($lastCheckout['userId']));
                 }
                 if (!$user->isAnon()) {
                     $res['userid'] = $user->getId();
                     $res['username'] = $user->getName();
                 }
                 $res['expiration'] = $lastCheckout['expiration'];
             }
             break;
         default:
             ApiBase::dieDebug(__METHOD__, "Unhandled concurrency action: {$params['ccaction']}");
     }
     $this->getResult()->addValue(null, $this->getModuleName(), $res);
 }
Example #12
0
 function execute($params = null)
 {
     global $IP, $wgWikiaLocalSettingsPath;
     $this->mTaskID = $params->task_id;
     $oUser = User::newFromId($params->task_user_id);
     $oUser->load();
     $this->mUser = $oUser->getName();
     $data = unserialize($params->task_arguments);
     $articles = $data["articles"];
     $username = escapeshellarg($data["username"]);
     $this->addLog("Starting task.");
     $this->addLog("List of restored articles (by " . $this->mUser . ' as ' . $username . "):");
     for ($i = 0; $i < count($articles); $i++) {
         $titleobj = Title::makeTitle($articles[$i]["namespace"], $articles[$i]["title"]);
         $article_to_do = $titleobj->getText();
         $namespace = intval($articles[$i]["namespace"]);
         $reason = $articles[$i]['reason'] ? ' -r ' . escapeshellarg($articles[$i]['reason']) : '';
         $sCommand = "SERVER_ID=" . $articles[$i]["wikiid"] . " php {$IP}/maintenance/wikia/restoreOn.php -u " . $username . " -t " . escapeshellarg($article_to_do) . " -n " . $namespace . $reason . " --conf " . escapeshellarg($wgWikiaLocalSettingsPath);
         $city_url = WikiFactory::getVarValueByName("wgServer", $articles[$i]["wikiid"]);
         if (empty($city_url)) {
             $city_url = 'wiki id in WikiFactory: ' . $articles[$i]["wikiid"];
         }
         $city_path = WikiFactory::getVarValueByName("wgScript", $articles[$i]["wikiid"]);
         $actual_title = wfShellExec($sCommand, $retval);
         if ($retval) {
             $this->addLog('Article undeleting error! (' . $city_url . '). Error code returned: ' . $retval . ' Error was: ' . $actual_title);
         } else {
             $this->addLog('<a href="' . $city_url . $city_path . '?title=' . $actual_title . '">' . $city_url . $city_path . '?title=' . $actual_title . '</a>');
         }
     }
     return true;
 }
Example #13
0
 /**
  * Methods builds User object depending on Ids and Names in ids array
  * @param $ids array list of user ids and names to look for
  * @return array with User objects
  */
 private function getUsersObjects($ids)
 {
     wfProfileIn(__METHOD__);
     $result = array();
     if (isset($ids['user_id'])) {
         foreach ($ids['user_id'] as $id) {
             $user = User::newFromId($id);
             //skip default user
             if ($user->getTouched() != 0) {
                 $result[] = $user;
                 $this->cacheUser($user);
             }
         }
     }
     if (isset($ids['user_name'])) {
         foreach ($ids['user_name'] as $name) {
             $user = User::newFromName($name);
             //skip default user
             if ($user->getTouched() != 0) {
                 $result[] = $user;
                 $this->cacheUser($user);
             }
         }
     }
     wfProfileOut(__METHOD__);
     return array_unique($result);
 }
 /**
  * Returns the user that this instructor is.
  * 
  * @since 0.1
  * 
  * @return User
  */
 public function getUser()
 {
     if ($this->user === false) {
         $this->user = User::newFromId($this->userId);
     }
     return $this->user;
 }
function efImageReviewDisplayStatus($imagePage, &$html)
{
    global $wgCityId, $wgExternalDatawareDB, $wgUser;
    if (!$wgUser->isAllowed('imagereviewstats')) {
        return true;
    }
    $html .= Xml::element('h2', array(), wfMsg('imagereview-imagepage-header'));
    $reviews = array();
    $headers = array('Reviewer', 'State', 'Time');
    $where = array('wiki_id' => $wgCityId, 'page_id' => $imagePage->getId());
    $dbr = wfGetDB(DB_SLAVE, array(), $wgExternalDatawareDB);
    $res = $dbr->select('image_review_stats', '*', $where);
    if ($dbr->numRows($res) == 0) {
        //check if image is in the queue at all!
        $imgCurState = $dbr->selectField('image_review', 'state', $where);
        if (false === $imgCurState) {
            // oh oh, image is not in queue at all
            $html .= wfMsg('imagereview-imagepage-not-in-queue');
        } else {
            // image is in the queue but not reviewed yet
            $html .= wfMsg('imagereview-state-0');
        }
    } else {
        // go through the list and display review states
        while ($row = $dbr->fetchObject($res)) {
            $data = array();
            $data[] = User::newFromId($row->reviewer_id)->getName();
            $data[] = wfMsg('imagereview-state-' . $row->review_state);
            $data[] = $row->review_end . ' (UTC)';
            $reviews[] = $data;
        }
        $html .= Xml::buildTable($reviews, array('class' => 'wikitable filehistory sortable', 'style' => 'width: 60%'), $headers);
    }
    return true;
}
/**
 * Send the message if the UserBoard class exists (duh!) and the welcome
 * message has some content.
 *
 * @param $user User: the new User object being created
 * @param $byEmail Boolean: true if the account was created by e-mail
 * @return Boolean: true
 */
function wfSendUserBoardMessageOnRegistration($user, $byEmail)
{
    if (class_exists('UserBoard') && $user instanceof User) {
        $message = trim(wfMsgForContent('user-board-welcome-message'));
        // If the welcome message is empty, short-circuit right away.
        if (wfEmptyMsg('user-board-welcome-message', $message)) {
            return true;
        }
        // Just quit if we're in read-only mode
        if (wfReadOnly()) {
            return true;
        }
        $dbr = wfGetDB(DB_SLAVE);
        // Get all users who are in the 'sysop' group and aren't blocked from
        // the database
        $res = $dbr->select(array('user_groups', 'ipblocks'), array('ug_group', 'ug_user'), array('ug_group' => 'sysop', 'ipb_user' => null), __METHOD__, array(), array('ipblocks' => array('LEFT JOIN', 'ipb_user = ug_user')));
        $adminUids = array();
        foreach ($res as $row) {
            $adminUids[] = $row->ug_user;
        }
        // Pick one UID from the array of admin user IDs
        $random = array_rand(array_flip($adminUids), 1);
        $sender = User::newFromId($random);
        $senderUid = $sender->getId();
        $senderName = $sender->getName();
        // Send the message
        $b = new UserBoard();
        $b->sendBoardMessage($senderUid, $senderName, $user->getId(), $user->getName(), wfMsgForContent('user-board-welcome-message', $senderName));
    }
    return true;
}
Example #17
0
 public function execute($subpage)
 {
     global $wgOut, $wgRequest, $wgUser, $wgCacheEpoch, $wgCityId;
     wfProfileIn(__METHOD__);
     $this->setHeaders();
     $this->mTitle = SpecialPage::getTitleFor('UserData');
     if ($this->isRestricted() && !$this->userCanExecute($wgUser)) {
         $this->displayRestrictionError();
         wfProfileOut(__METHOD__);
         return;
     }
     $result = '';
     $userId = $wgRequest->getInt('userId');
     if ($userId) {
         $user = User::newFromId($userId);
         if (!empty($user)) {
             //todo: add nicer result - right now only name and link to user page
             $result = Xml::element('a', array('href' => $user->getUserPage()->getLocalURL()), $user->getName(), false);
         }
     }
     $wgOut->addHTML(Xml::openElement('form', array('action' => $this->mTitle->getFullURL(), 'method' => 'get')));
     $wgOut->addHTML(Xml::inputLabel(wfMsg('userdata-userid-label'), 'userId', 'user-id', false, $userId));
     $wgOut->addHTML('<br>' . Xml::submitButton(wfMsg('userdata-submit')));
     $wgOut->addHTML(Xml::closeElement('form'));
     if ($result) {
         $wgOut->addHTML('<hr>' . $result);
     }
     wfProfileOut(__METHOD__);
 }
	/**
	 * Run a pageSchemasCreatePage job
	 * @return boolean success
	 */
	function run() {
		wfProfileIn( __METHOD__ );

		if ( is_null( $this->title ) ) {
			$this->error = "pageSchemasCreatePage: Invalid title";
			wfProfileOut( __METHOD__ );
			return false;
		}
		$article = new Article( $this->title );
		if ( !$article ) {
			$this->error = 'pageSchemasCreatePage: Article not found "' . $this->title->getPrefixedDBkey() . '"';
			wfProfileOut( __METHOD__ );
			return false;
		}

		$page_text = $this->params['page_text'];
		// change global $wgUser variable to the one
		// specified by the job only for the extent of this
		// replacement
		global $wgUser;
		$actual_user = $wgUser;
		$wgUser = User::newFromId( $this->params['user_id'] );
		$edit_summary = wfMsgForContent( 'ps-generatepages-editsummary' );
		$article->doEdit( $page_text, $edit_summary );
		$wgUser = $actual_user;
		wfProfileOut( __METHOD__ );
		return true;
	}
Example #19
0
 /**
  * Execute the job
  *
  * @return bool
  */
 public function run()
 {
     // Load data from $this->params and $this->title
     $article = new WikiPage($this->title);
     $user_ids_to = $this->params['user_ids_to'];
     $message = $this->params['message'];
     $sender = $this->params['sender'];
     $user = User::newFromId($sender);
     $b = new UserBoard();
     $count = 0;
     $i = count($user_ids_to);
     $per_num = 100;
     $num = $i / $per_num;
     $int_num = ceil($num);
     for ($k = 1; $k <= $int_num; $k++) {
         $star = $per_num * ($k - 1);
         $res_arr = array_slice($user_ids_to, $star, $per_num);
         foreach ($res_arr as $user_id) {
             $user_to = User::newFromId($user_id);
             $user->loadFromId();
             $user_name = $user_to->getName();
             $b->sendBoardMessage($user->getID(), $user->getName(), $user_id, $user_name, $message, 1);
             // $count++;
         }
         wfDebug('Sending Board Blast batch ' . $k . '............................................');
         // ob_flush();
         //    flush();
     }
     return true;
 }
Example #20
0
 /**
  * Returns the user that authored this revision.
  *
  * @since 0.1
  *
  * @return User
  */
 public function getUser()
 {
     if ($this->user === false) {
         $this->user = User::newFromId($this->loadAndGetField('user_id'));
     }
     return $this->user;
 }
 function getUser($userId)
 {
     $name = null;
     $realName = null;
     $userPageLink = null;
     $emailAddress = null;
     $emailAddressValid = false;
     $timeCorrection = null;
     $user = $this->cacheManager->retrieveUser($userId);
     if (!isset($user)) {
         $mediaWikiUser = \User::newFromId($userId);
         $name = $mediaWikiUser->getName();
         if ($this->rtc->isShowUserRealName()) {
             $realName = $mediaWikiUser->getRealName();
         }
         if (!isset($realName) || isset($realName) && strlen(trim($realName)) == 0) {
             $realName = $name;
         }
         $emailAddress = $mediaWikiUser->getEmail();
         $emailAddressValid = $mediaWikiUser->isEmailConfirmed() ? true : false;
         $userPageLink = \PageAttachment\UI\Command::getViewUserPageCommandLink($name, $realName);
         $timeCorrection = $mediaWikiUser->getOption('timecorrection');
         $languageCode = $mediaWikiUser->getOption('language');
         $dateFormat = $mediaWikiUser->getOption('date');
         $user = new User($userId, $name, $realName, $userPageLink, $emailAddress, $emailAddressValid, $timeCorrection, $languageCode, $dateFormat);
         $this->cacheManager->storeUser($user);
     }
     return $user;
 }
Example #22
0
 /**
  * Run a createPage job
  * @return boolean success
  */
 function run()
 {
     if (is_null($this->title)) {
         $this->error = "createPage: Invalid title";
         return false;
     }
     $article = new Article($this->title, 0);
     if (!$article) {
         $this->error = 'createPage: Article not found "' . $this->title->getPrefixedDBkey() . '"';
         return false;
     }
     $page_text = $this->params['page_text'];
     // change global $wgUser variable to the one
     // specified by the job only for the extent of this
     // replacement
     global $wgUser;
     $actual_user = $wgUser;
     $wgUser = User::newFromId($this->params['user_id']);
     $edit_summary = '';
     if (array_key_exists('edit_summary', $this->params)) {
         $edit_summary = $this->params['edit_summary'];
     }
     $article->doEdit($page_text, $edit_summary);
     $wgUser = $actual_user;
     return true;
 }
 public function execute()
 {
     $this->commit = $this->hasOption('commit');
     $dbr = $this->getDB(DB_SLAVE);
     $dbw = $this->getDB(DB_MASTER);
     $lastId = 0;
     do {
         $rows = $dbr->select('user', array('user_id', 'user_email'), array('user_id > ' . $dbr->addQuotes($lastId), 'user_email != ""', 'user_email_authenticated IS NULL'), __METHOD__, array('LIMIT' => $this->mBatchSize));
         $count = $rows->numRows();
         $badIds = array();
         foreach ($rows as $row) {
             if (!Sanitizer::validateEmail(trim($row->user_email))) {
                 $this->output("Found bad email: {$row->user_email} for user #{$row->user_id}\n");
                 $badIds[] = $row->user_id;
             }
             if ($row->user_id > $lastId) {
                 $lastId = $row->user_id;
             }
         }
         if ($badIds) {
             $badCount = count($badIds);
             if ($this->commit) {
                 $this->output("Removing {$badCount} emails from the database.\n");
                 $dbw->update('user', array('user_email' => ''), array('user_id' => $badIds), __METHOD__);
                 foreach ($badIds as $badId) {
                     User::newFromId($badId)->invalidateCache();
                 }
                 wfWaitForSlaves();
             } else {
                 $this->output("Would have removed {$badCount} emails from the database.\n");
             }
         }
     } while ($count !== 0);
     $this->output("Done.\n");
 }
 /**
  * execute -- main entry point to api method
  *
  * use secret hash for checking if api is called by proper engine
  *
  * @access public
  *
  * @return api result
  */
 public function execute()
 {
     global $wgTheSchwartzSecretToken, $wgCityId, $wgServer, $wgExtensionMessagesFiles;
     $params = $this->extractRequestParams();
     $status = 0;
     if (isset($params["token"]) && $params["token"] === $wgTheSchwartzSecretToken) {
         /**
          * get creator from param
          */
         $founder = User::newFromId($params["user_id"]);
         $founder->load();
         /**
          * get city_founding_user from city_list
          */
         if (!$founder) {
             $wiki = WikiFactory::getWikiByID($wgCityId);
             $founder = User::newFromId($wiki->city_founding_user);
         }
         Wikia::log(__METHOD__, "user", $founder->getName());
         if ($founder && $founder->isEmailConfirmed()) {
             if ($founder->sendMail(wfMsg("autocreatewiki-reminder-subject"), wfMsg("autocreatewiki-reminder-body", array($founder->getName(), $wgServer)), null, null, "AutoCreateWikiReminder", wfMsg("autocreatewiki-reminder-body-HTML", array($founder->getName(), $wgServer)))) {
                 $status = 1;
             }
         }
     } else {
         $this->dieUsageMsg(array("sessionfailure"));
     }
     $result = array("status" => $status);
     $this->getResult()->setIndexedTagName($result, 'status');
     $this->getResult()->addValue(null, $this->getModuleName(), $result);
 }
 public function votersListItems()
 {
     //TODO: imaplmant load more button
     /**
      * @var $mw WallMessage
      */
     $mw = $this->request->getVal('mw');
     if (empty($mw)) {
         $mw = F::build('WallMessage', array($this->request->getVal('id')), 'newFromId');
     }
     $from = (int) $this->request->getVal('from', 0);
     $list = $mw->getVotersList($from, 1000);
     if (count($list) == 26) {
         $this->response->setVal('hasmore', true);
     } else {
         $this->response->setVal('hasmore', false);
     }
     $out = array();
     for ($i = 0; $i < min(count($list), 24); $i++) {
         $user = User::newFromId($list[$i]);
         if (!empty($user)) {
             $out[] = array('profilepage' => $user->getUserPage()->getFullUrl(), 'name' => $user->getName(), 'avatar' => AvatarService::getAvatarUrl($user->getName(), 50));
         }
     }
     $this->response->setVal('hasmore', false);
     $this->response->setVal('last', $from);
     $this->response->setVal('list', $out);
 }
 /**
  * Adds users to watchlist if:
  * - User is watching parent page
  * - User has 'watchlistsubpages' turned on
  *
  * @param $watchers array of user ID
  * @param $title Title object
  * @param $editor User object
  * @param $notificationTimeoutSql string timeout to the watchlist
  *
  * @author Jakub Kurcek <*****@*****.**>
  */
 public static function NotifyOnSubPageChange($watchers, $title, $editor, $notificationTimeoutSql)
 {
     wfProfileIn(__METHOD__);
     // Gets parent data
     $arrTitle = explode('/', $title->getDBkey());
     if (empty($arrTitle)) {
         wfProfileOut(__METHOD__);
         return true;
     }
     // make Title
     $t = reset($arrTitle);
     $newTitle = Title::newFromDBkey($t);
     if (!$newTitle instanceof Title) {
         return true;
     }
     $dbw = wfGetDB(DB_MASTER);
     /** @var $dbw Database */
     $res = $dbw->select(array('watchlist'), array('wl_user'), array('wl_title' => $newTitle->getDBkey(), 'wl_namespace' => $newTitle->getNamespace(), 'wl_user != ' . intval($editor->getID()), $notificationTimeoutSql), __METHOD__);
     // Gets user settings
     $parentpageWatchers = array();
     while ($row = $dbw->fetchObject($res)) {
         $userId = intval($row->wl_user);
         $tmpUser = User::newFromId($userId);
         if ($tmpUser->getBoolOption(self::PREFERENCES_ENTRY)) {
             $parentpageWatchers[] = $userId;
         }
         unset($tmpUser);
     }
     // Updates parent watchlist timestamp for $parentOnlyWatchers.
     $parentOnlyWatchers = array_diff($parentpageWatchers, $watchers);
     $wl = WatchedItem::fromUserTitle($editor, $newTitle);
     $wl->updateWatch($parentOnlyWatchers);
     wfProfileOut(__METHOD__);
     return true;
 }
 public function execute()
 {
     $dbw = $this->getDB(DB_MASTER);
     $lastId = 0;
     do {
         // Get user IDs which need fixing
         $res = $dbw->select('user', 'user_id', array('user_id > ' . $dbw->addQuotes($lastId), 'user_registration IS NULL'), __METHOD__, array('LIMIT' => $this->mBatchSize, 'ORDER BY' => 'user_id'));
         foreach ($res as $row) {
             $id = $row->user_id;
             $lastId = $id;
             // Get first edit time
             $timestamp = $dbw->selectField('revision', 'MIN(rev_timestamp)', array('rev_user' => $id), __METHOD__);
             // Update
             if ($timestamp !== null) {
                 $dbw->update('user', array('user_registration' => $timestamp), array('user_id' => $id), __METHOD__);
                 $user = User::newFromId($id);
                 $user->invalidateCache();
                 $this->output("Set registration for #{$id} to {$timestamp}\n");
             } else {
                 $this->output("Could not find registration for #{$id} NULL\n");
             }
         }
         $this->output("Waiting for slaves...");
         wfWaitForSlaves();
         $this->output(" done.\n");
     } while ($res->numRows() >= $this->mBatchSize);
 }
 public function refreshBatch(DatabaseBase $dbr, UUID $continue, $countableActions, UUID $stop)
 {
     $rows = $dbr->select('flow_revision', array('rev_id', 'rev_user_id'), array('rev_id > ' . $dbr->addQuotes($continue->getBinary()), 'rev_id <= ' . $dbr->addQuotes($stop->getBinary()), 'rev_user_id > 0', 'rev_user_wiki' => wfWikiID(), 'rev_change_type' => $countableActions), __METHOD__, array('ORDER BY' => 'rev_id ASC', 'LIMIT' => $this->mBatchSize));
     // end of data
     if (!$rows || $rows->numRows() === 0) {
         return false;
     }
     foreach ($rows as $row) {
         // User::incEditCount only allows for edit count to be increased 1
         // at a time. It'd be better to immediately be able to increase the
         // edit count by the exact number it should be increased with, but
         // I'd rather re-use existing code, especially in a run-once script,
         // where performance is not the most important thing ;)
         $user = User::newFromId($row->rev_user_id);
         $user->incEditCount();
         // save updates so we can print them when the script is done running
         if (!isset($this->updates[$user->getId()])) {
             $this->updates[$user->getId()] = 0;
         }
         $this->updates[$user->getId()]++;
         // set value for next batch to continue at
         $continue = $row->rev_id;
     }
     return UUID::create($continue);
 }
Example #29
0
 /**
  * 
  * @return User
  */
 public function getUser()
 {
     if (is_null($this->user)) {
         $this->user = User::newFromId($this->wpm_user_id);
     }
     return $this->user;
 }
 protected function setUp()
 {
     parent::setUp();
     $langObj = Language::factory('en');
     $localZone = 'UTC';
     $localOffset = date('Z') / 60;
     $this->setMwGlobals(array('wgMemc' => new EmptyBagOStuff(), 'wgContLang' => $langObj, 'wgLanguageCode' => 'en', 'wgLang' => $langObj, 'wgLocaltimezone' => $localZone, 'wgLocalTZoffset' => $localOffset, 'wgNamespaceProtection' => array(NS_MEDIAWIKI => 'editinterface')));
     // Without this testUserBlock will use a non-English context on non-English MediaWiki
     // installations (because of how Title::checkUserBlock is implemented) and fail.
     RequestContext::resetMain();
     $this->userName = '******';
     $this->altUserName = '******';
     date_default_timezone_set($localZone);
     $this->title = Title::makeTitle(NS_MAIN, "Main Page");
     if (!isset($this->userUser) || !$this->userUser instanceof User) {
         $this->userUser = User::newFromName($this->userName);
         if (!$this->userUser->getID()) {
             $this->userUser = User::createNew($this->userName, array("email" => "*****@*****.**", "real_name" => "Test User"));
             $this->userUser->load();
         }
         $this->altUser = User::newFromName($this->altUserName);
         if (!$this->altUser->getID()) {
             $this->altUser = User::createNew($this->altUserName, array("email" => "*****@*****.**", "real_name" => "Test User Alt"));
             $this->altUser->load();
         }
         $this->anonUser = User::newFromId(0);
         $this->user = $this->userUser;
     }
 }