/**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the page or null
  */
 public function execute($par)
 {
     global $wgOut, $wgUser;
     $wgOut->setPageTitle('Update Edit Counts');
     // Check permissions -- we must be allowed to access this special page
     // before we can run any database queries
     if (!$wgUser->isAllowed('updatepoints')) {
         throw new ErrorPageError('error', 'badaccess');
     }
     // And obviously the database needs to be writable before we start
     // running INSERT/UPDATE queries against it...
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return;
     }
     $dbw = wfGetDB(DB_MASTER);
     $this->updateMainEditsCount();
     global $wgUserLevels;
     $wgUserLevels = '';
     $res = $dbw->select('user_stats', array('stats_user_id', 'stats_user_name', 'stats_total_points'), array(), __METHOD__, array('ORDER BY' => 'stats_user_name'));
     $out = '';
     $x = 0;
     foreach ($res as $row) {
         $x++;
         $stats = new UserStatsTrack($row->stats_user_id, $row->stats_user_name);
         $stats->updateTotalPoints();
     }
     $out = "Updated stats for <b>{$x}</b> users";
     $wgOut->addHTML($out);
 }
	/**
	 * Sends a gift to the specified user.
	 *
	 * @param $user_to Integer: user ID of the recipient
	 * @param $gift_id Integer: gift ID number
	 * @param $type Integer: gift type
	 * @param $message Mixed: message as supplied by the sender
	 */
	public function sendGift( $user_to, $gift_id, $type, $message ) {
		$user_id_to = User::idFromName( $user_to );
		$dbw = wfGetDB( DB_MASTER );

		$dbw->insert(
			'user_gift',
			array(
				'ug_gift_id' => $gift_id,
				'ug_user_id_from' => $this->user_id,
				'ug_user_name_from' => $this->user_name,
				'ug_user_id_to' => $user_id_to,
				'ug_user_name_to' => $user_to,
				'ug_type' => $type,
				'ug_status' => 1,
				'ug_message' => $message,
				'ug_date' => date( 'Y-m-d H:i:s' ),
			), __METHOD__
		);
		$ug_gift_id = $dbw->insertId();
		$this->incGiftGivenCount( $gift_id );
		$this->sendGiftNotificationEmail( $user_id_to, $this->user_name, $gift_id, $type );

		// Add to new gift count cache for receiving user
		$this->incNewGiftCount( $user_id_to );

		$stats = new UserStatsTrack( $user_id_to, $user_to );
		$stats->incStatField( 'gift_rec' );

		$stats = new UserStatsTrack( $this->user_id, $this->user_name );
		$stats->incStatField( 'gift_sent' );
		return $ug_gift_id;
	}
Example #3
0
function incEditCount()
{
    global $wgUser, $IP;
    require_once "{$IP}/extensions/UserStats/UserStatsClass.php";
    $stats = new UserStatsTrack(1, $wgUser->mId, $wgUser->mName);
    $stats->incEditCount();
    return true;
}
 /**
  * Remove a follower from site and clear caches afterwards.
  *
  * @param $user1 User object: user to be removed
  * @param $user2 string: site prefix
  */
 public function deleteUserSiteFollow($user, $huijiPrefix)
 {
     global $wgMemc;
     $dbw = wfGetDB(DB_MASTER);
     $dbw->delete('user_site_follow', array('f_user_id' => $user->getId(), 'f_wiki_domain' => $huijiPrefix), __METHOD__);
     $stats = new UserStatsTrack($user->getId(), $user->getName());
     $stats->decStatField('friend');
     $this->decFollowCount($user, $huijiPrefix);
     //store result in cache
     $key = wfForeignMemcKey('huiji', '', 'user_site_follow', 'check_follow', $user->getName(), $huijiPrefix);
     $wgMemc->set($key, false);
     return true;
 }
function restoreDeletedEdits(&$title, $new)
{
    global $wgNamespacesForEditPoints;
    // only keep tally for allowable namespaces
    if (!is_array($wgNamespacesForEditPoints) || in_array($title->getNamespace(), $wgNamespacesForEditPoints)) {
        $dbr = wfGetDB(DB_MASTER);
        $res = $dbr->select('revision', array('rev_user_text', 'rev_user', 'COUNT(*) AS the_count'), array('rev_page' => $title->getArticleID(), 'rev_user <> 0'), __METHOD__, array('GROUP BY' => 'rev_user_text'));
        foreach ($res as $row) {
            $stats = new UserStatsTrack($row->rev_user, $row->rev_user_text);
            $stats->incStatField('edit', $row->the_count);
        }
    }
    return true;
}
 /**
  * Remove a follower from followee
  *
  * @param $user1 User object: user to be removed
  * @param $user2 string: site prefix
  * @return bool: true if successfully deleted
  */
 public function deleteUserUserFollow($follower, $followee)
 {
     if ($follower == null || $followee == null) {
         return false;
     }
     $dbw = wfGetDB(DB_MASTER);
     $dbw->delete('user_user_follow', array('f_user_id' => $follower->getId(), 'f_target_user_id' => $followee->getId()), __METHOD__);
     $this->decFollowCount($follower, $followee);
     $stats = new UserStatsTrack($follower->getId(), $follower->getName());
     $stats->decStatField('friend');
     //use friend record to count the number of people followed.
     $stats = new UserStatsTrack($followee->getId(), $followee->getName());
     $stats->decStatField('foe');
     // use foe record to count the number of people following.
     return true;
 }
 /**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the page or null
  */
 public function execute($par)
 {
     $out = $this->getOutput();
     // Check permissions -- we must be allowed to access this special page
     // before we can run any database queries
     if (!$this->getUser()->isAllowed('updatepoints')) {
         throw new ErrorPageError('error', 'badaccess');
     }
     // And obviously the database needs to be writable before we start
     // running INSERT/UPDATE queries against it...
     if (wfReadOnly()) {
         $out->readOnlyPage();
         return;
     }
     // Set the page title, robot policies, etc.
     $this->setHeaders();
     $dbw = wfGetDB(DB_MASTER);
     $this->updateMainEditsCount();
     global $wgUserLevels;
     $wgUserLevels = '';
     $res = $dbw->select('user_stats', array('stats_user_id', 'stats_user_name', 'stats_total_points'), array(), __METHOD__, array('ORDER BY' => 'stats_user_name'));
     $x = 0;
     foreach ($res as $row) {
         $x++;
         $stats = new UserStatsTrack($row->stats_user_id, $row->stats_user_name);
         $stats->updateTotalPoints();
     }
     $out->addWikiMsg('updateeditcounts-updated', $x);
 }
Example #8
0
 function execute()
 {
     global $wgUser, $wgOut, $wgVoteDirectory, $wgCommentsDirectory, $IP;
     require_once "{$wgVoteDirectory}/VoteClass.php";
     require_once "{$wgVoteDirectory}/Publish.php";
     require_once "{$wgVoteDirectory}/RSS.php";
     require_once "{$wgCommentsDirectory}/CommentClass.php";
     if ($_POST["mk"] == md5($_POST["pid"] . 'pants' . $wgUser->mName)) {
         require_once "{$IP}/extensions/UserStats/UserStatsClass.php";
         $stats = new UserStatsTrack(1, $wgUser->mId, $wgUser->mName);
         if (($_GET["Action"] == 1 || $_GET["Action"] == 2) && is_numeric($_POST["pid"]) && (is_numeric($_POST["TheVote"]) || $_GET["Action"] == 2)) {
             //echo 'test2';
             $Vote = new Vote($_POST["pid"]);
             $Vote->setUser($wgUser->mName, $wgUser->mId);
             if ($_GET["Action"] == 1) {
                 $Vote->insert($_POST["TheVote"]);
                 $stats->incVoteCount();
             } else {
                 $Vote->delete();
             }
             $CommentList = new Comment($_POST["pid"]);
             $publish = new Publish();
             $publish->PageID = $_POST["pid"];
             $publish->VoteCount = $Vote->count(1);
             $publish->CommentCount = $CommentList->count();
             $publish->check_score();
             echo $Vote->count(1);
         }
         if ($_GET["Action"] == 3) {
             $Vote = new VoteStars($_POST["pid"]);
             $Vote->setUser($wgUser->mName, $wgUser->mId);
             $Vote->insert($_POST["TheVote"]);
             $stats->incVoteCount();
             echo $Vote->display();
         }
         if ($_GET["Action"] == 4) {
             $Vote = new VoteStars($_POST["pid"]);
             $Vote->setUser($wgUser->mName, $wgUser->mId);
             $Vote->delete();
             echo $Vote->display();
         }
     }
     // This line removes the navigation and everything else from the
     // page, if you don't set it, you get what looks like a regular wiki
     // page, with the body you defined above.
     $wgOut->setArticleBodyOnly(true);
 }
 function execute()
 {
     global $wgUser, $wgOut;
     $dbr =& wfGetDB(DB_MASTER);
     $sql = "SELECT stats_user_id,stats_user_name, stats_total_points from user_stats where stats_year_id = 1 ORDER BY stats_user_name";
     $res = $dbr->query($sql);
     $row = $dbr->fetchObject($res);
     $out = "";
     while ($row = $dbr->fetchObject($res)) {
         $x++;
         $stats = new UserStatsTrack(1, $row->stats_user_id, $row->stats_user_name);
         $stats->updatePublishedOpinionsCount();
         // $stats->updateTotalPoints();
     }
     $out = "Updated stats for <b>{$x}</b> users";
     $wgOut->addHTML($out);
 }
Example #10
0
 function incOpinionsPublished()
 {
     $dbr =& wfGetDB(DB_MASTER);
     $sql = "SELECT cl_to FROM " . $dbr->tableName('categorylinks') . "  WHERE cl_from=" . $this->PageID;
     $res = $dbr->query($sql);
     while ($row = $dbr->fetchObject($res)) {
         $ctg = Title::makeTitle(14, $row->cl_to);
         $ctgname = $ctg->getText();
         if (strpos(strtoupper($ctgname), 'OPINIONS BY USER') !== false) {
             $user_name = trim(str_replace("Opinions by User", "", $ctgname));
             $u = User::idFromName($user_name);
             if ($u) {
                 $stats = new UserStatsTrack(1, $u, $user_name);
                 $stats->incOpinionsPublished();
             }
         }
     }
 }
function updateCreatedOpinionsCount()
{
    global $wgOut, $wgTitle;
    $dbr =& wfGetDB(DB_SLAVE);
    $sql = "SELECT cl_to FROM " . $dbr->tableName('categorylinks') . "  WHERE cl_from=" . $wgTitle->mArticleID;
    $res = $dbr->query($sql);
    while ($row = $dbr->fetchObject($res)) {
        $ctg = Title::makeTitle(14, $row->cl_to);
        $ctgname = $ctg->getText();
        if (strpos(strtoupper($ctgname), 'OPINIONS BY USER') !== false) {
            $user_name = trim(str_replace("Opinions by User", "", $ctgname));
            $u = User::idFromName($user_name);
            if ($u) {
                $stats = new UserStatsTrack(1, $u, $user_name);
                $stats->updateCreatedOpinionsCount();
            }
        }
    }
    return true;
}
 /**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the page or null
  */
 public function execute($par)
 {
     global $wgUser, $wgOut, $wgRequest;
     $user_name = $wgRequest->getVal('user');
     /**
      * Redirect anonymous users to Login Page
      * It will automatically return them to the CommentIgnoreList page
      */
     if ($wgUser->getID() == 0 && $user_name == '') {
         $loginPage = SpecialPage::getTitleFor('Userlogin');
         $wgOut->redirect($loginPage->getLocalURL('returnto=Special:CommentIgnoreList'));
         return false;
     }
     $wgOut->setPageTitle(wfMsg('comment-ignore-title'));
     $out = '';
     // Prevent E_NOTICE
     if ($user_name == '') {
         $out .= $this->displayCommentBlockList();
     } else {
         if ($wgRequest->wasPosted()) {
             $user_name = htmlspecialchars_decode($user_name);
             $user_id = User::idFromName($user_name);
             // Anons can be comment-blocked, but idFromName returns nothing
             // for an anon, so...
             if (!$user_id) {
                 $user_id = 0;
             }
             $c = new Comment(0);
             $c->deleteBlock($wgUser->getID(), $user_id);
             if ($user_id && class_exists('UserStatsTrack')) {
                 $stats = new UserStatsTrack($user_id, $user_name);
                 $stats->decStatField('comment_ignored');
             }
             $out .= $this->displayCommentBlockList();
         } else {
             $out .= $this->confirmCommentBlockDelete();
         }
     }
     $wgOut->addHTML($out);
 }
	/**
	 * Adds a record to the poll_user_vote tabel to signify that the user has
	 * already voted.
	 *
	 * @param $pollID Integer: ID number of the poll
	 * @param $choiceID Integer: number of the choice
	 */
	public function addPollVote( $pollID, $choiceID ) {
		global $wgUser;
		$dbw = wfGetDB( DB_MASTER );
		$dbw->insert(
			'poll_user_vote',
			array(
				'pv_poll_id' => $pollID,
				'pv_pc_id' => $choiceID,
				'pv_user_id' => $wgUser->getID(),
				'pv_user_name' => $wgUser->getName(),
				'pv_date' => date( 'Y-m-d H:i:s' )
			),
			__METHOD__
		);
		$dbw->commit();
		if( $choiceID > 0 ) {
			$this->incPollVoteCount( $pollID );
			$this->incChoiceVoteCount( $choiceID );
			$stats = new UserStatsTrack( $wgUser->getID(), $wgUser->getName() );
			$stats->incStatField( 'poll_vote' );
		}
	}
 /**
  * Remove a relationship between two users and clear caches afterwards.
  *
  * @param $user1 Integer: user ID of the first user
  * @param $user2 Integer: user ID of the second user
  */
 public function removeRelationshipByUserID($user1, $user2)
 {
     global $wgUser, $wgMemc;
     if ($user1 != $wgUser->getID() && $user2 != $wgUser->getID()) {
         return false;
         // only logged in user should be able to delete
     }
     // must delete record for each user involved in relationship
     $dbw = wfGetDB(DB_MASTER);
     $dbw->delete('user_relationship', array('r_user_id' => $user1, 'r_user_id_relation' => $user2), __METHOD__);
     $dbw->delete('user_relationship', array('r_user_id' => $user2, 'r_user_id_relation' => $user1), __METHOD__);
     $wgMemc->delete(wfForeignMemcKey('huiji', '', 'relationship', 'profile', "{$user1}-1"));
     $wgMemc->delete(wfForeignMemcKey('huiji', '', 'relationship', 'profile', "{$user2}-1"));
     $wgMemc->delete(wfForeignMemcKey('huiji', '', 'relationship', 'profile', "{$user1}-2"));
     $wgMemc->delete(wfForeignMemcKey('huiji', '', 'relationship', 'profile', "{$user2}-2"));
     // RelationshipRemovedByUserID hook
     wfRunHooks('RelationshipRemovedByUserID', array($user1, $user2));
     // Update social statistics for both users
     $stats = new UserStatsTrack($user1, '');
     $stats->updateRelationshipCount(1);
     $stats->updateRelationshipCount(2);
     $stats->clearCache();
     $stats = new UserStatsTrack($user2, '');
     $stats->updateRelationshipCount(1);
     $stats->updateRelationshipCount(2);
     $stats->clearCache();
 }
 /**
  * Deletes a user board message from the database and decreases social
  * statistics as appropriate (either 'user_board_count' or
  * 'user_board_count_priv' is decreased by one).
  *
  * @param $ub_id Integer: ID number of the board message that we want to delete
  */
 public function deleteMessage($ub_id)
 {
     if ($ub_id) {
         $dbw = wfGetDB(DB_MASTER);
         $s = $dbw->selectRow('user_board', array('ub_user_id', 'ub_user_name', 'ub_type'), array('ub_id' => $ub_id), __METHOD__);
         if ($s !== false) {
             $dbw->delete('user_board', array('ub_id' => $ub_id), __METHOD__);
             $stats = new UserStatsTrack($s->ub_user_id, $s->ub_user_name);
             if ($s->ub_type == 0) {
                 $stats->decStatField('user_board_count');
             } else {
                 $stats->decStatField('user_board_count_priv');
             }
         }
     }
 }
/**
 * Track new user registrations to the user_register_track database table if
 * $wgRegisterTrack is set to true.
 *
 * @param $user Object: the User object representing the newly-created user
 * @return Boolean: true
 */
function fnRegisterTrack($user)
{
    global $wgRequest, $wgRegisterTrack, $wgMemc;
    if ($wgRegisterTrack) {
        $wgMemc->delete(wfMemcKey('users', 'new', '1'));
        // How the user registered (via email from friend, just on the site etc.)?
        $from = $wgRequest->getInt('from');
        if (!$from) {
            $from = 0;
        }
        // Track if the user clicked on email from friend
        $user_id_referral = 0;
        $user_name_referral = '';
        $referral_user = $wgRequest->getVal('referral');
        if ($referral_user) {
            $user_registering_title = Title::makeTitle(NS_USER, $user->getName());
            $user_title = Title::newFromDBkey($referral_user);
            $user_id_referral = User::idFromName($user_title->getText());
            if ($user_id_referral) {
                $user_name_referral = $user_title->getText();
            }
            $stats = new UserStatsTrack($user_id_referral, $user_title->getText());
            $stats->incStatField('referral_complete');
            if (class_exists('UserSystemMessage')) {
                $m = new UserSystemMessage();
                // Nees to be forContent because addMessage adds this into a
                // database table - we don't want to display Japanese text
                // to English users
                $message = wfMsgForContent('login-reg-recruited', $user_registering_title->getFullURL(), $user->getName());
                $m->addMessage($user_title->getText(), 1, $message);
            }
        }
        // Track registration
        $dbw = wfGetDB(DB_MASTER);
        $dbw->insert('user_register_track', array('ur_user_id' => $user->getID(), 'ur_user_name' => $user->getName(), 'ur_user_id_referral' => $user_id_referral, 'ur_user_name_referral' => $user_name_referral, 'ur_from' => $from, 'ur_date' => date('Y-m-d H:i:s')), __METHOD__);
        $dbw->commit();
        // Just in case...
    }
    return true;
}
	/**
	 * Create the thumbnails and delete old files
	 */
	public function performUpload( $comment, $pageText, $watch, $user ) {
		global $wgUploadDirectory, $wgUser, $wgDBname, $wgMemc;

		$this->avatarUploadDirectory = $wgUploadDirectory . '/avatars';

		$imageInfo = getimagesize( $this->mTempPath );
		switch ( $imageInfo[2] ) {
			case 1:
				$ext = 'gif';
				break;
			case 2:
				$ext = 'jpg';
				break;
			case 3:
				$ext = 'png';
				break;
			default:
				return Status::newFatal( 'filetype-banned-type' );
		}

		$dest = $this->avatarUploadDirectory;

		$uid = $wgUser->getId();
		$avatar = new wAvatar( $uid, 'l' );
		// If this is the user's first custom avatar, update statistics (in
		// case if we want to give out some points to the user for uploading
		// their first avatar)
		if ( strpos( $avatar->getAvatarImage(), 'default_' ) !== false ) {
			$stats = new UserStatsTrack( $uid, $wgUser->getName() );
			$stats->incStatField( 'user_image' );
		}

		$this->createThumbnail( $this->mTempPath, $imageInfo, $wgDBname . '_' . $uid . '_l', 75 );
		$this->createThumbnail( $this->mTempPath, $imageInfo, $wgDBname . '_' . $uid . '_ml', 50 );
		$this->createThumbnail( $this->mTempPath, $imageInfo, $wgDBname . '_' . $uid . '_m', 30 );
		$this->createThumbnail( $this->mTempPath, $imageInfo, $wgDBname . '_' . $uid . '_s', 16 );

		if ( $ext != 'jpg' ) {
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_s.jpg' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_s.jpg' );
			}
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_m.jpg' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_m.jpg' );
			}
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_l.jpg' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_l.jpg' );
			}
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_ml.jpg' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_ml.jpg' );
			}
		}
		if ( $ext != 'gif' ) {
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_s.gif' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_s.gif' );
			}
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_m.gif' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_m.gif' );
			}
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_l.gif' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_l.gif' );
			}
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_ml.gif' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_ml.gif' );
			}
		}
		if ( $ext != 'png' ) {
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_s.png' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_s.png' );
			}
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_m.png' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_m.png' );
			}
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_l.png' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_l.png' );
			}
			if ( is_file( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_ml.png' ) ) {
				unlink( $this->avatarUploadDirectory . '/' . $wgDBname . '_' . $uid . '_ml.png' );
			}
		}

		$key = wfMemcKey( 'user', 'profile', 'avatar', $uid, 's' );
		$data = $wgMemc->delete( $key );

		$key = wfMemcKey( 'user', 'profile', 'avatar', $uid, 'm' );
		$data = $wgMemc->delete( $key );

		$key = wfMemcKey( 'user', 'profile', 'avatar', $uid , 'l' );
		$data = $wgMemc->delete( $key );

		$key = wfMemcKey( 'user', 'profile', 'avatar', $uid, 'ml' );
		$data = $wgMemc->delete( $key );

		$this->mExtension = $ext;
		return Status::newGood();
	}
 /**
  * This function was originally in the UserStats directory, in the file
  * CreatedOpinionsCount.php.
  * This function here updates the stats_opinions_created column in the
  * user_stats table every time the user creates a new blog post.
  *
  * This is hooked into two separate hooks (todo: find out why), ArticleSave
  * and ArticleSaveComplete. Their arguments are mostly the same and both
  * have $article as the first argument.
  *
  * @param $article Object: Article object representing the page that was/is
  *                         (being) saved
  * @return Boolean: true
  */
 public static function updateCreatedOpinionsCount(&$article)
 {
     global $wgOut, $wgUser;
     $aid = $article->getTitle()->getArticleID();
     // Shortcut, in order not to perform stupid queries (cl_from = 0...)
     if ($aid == 0) {
         return true;
     }
     $dbr = wfGetDB(DB_SLAVE);
     $res = $dbr->select('categorylinks', 'cl_to', array('cl_from' => $aid), __METHOD__);
     foreach ($res as $row) {
         $ctg = Title::makeTitle(NS_CATEGORY, $row->cl_to);
         $ctgname = $ctg->getText();
         $blogCat = wfMsgForContent('blog-category');
         $userBlogCat = wfMsgForContent('blog-by-user-category', $blogCat);
         if (strpos($ctgname, $userBlogCat) !== false) {
             $user_name = trim(str_replace($userBlogCat, '', $ctgname));
             $u = User::idFromName($user_name);
             if ($u) {
                 $stats = new UserStatsTrack($u, $user_name);
                 // Copied from UserStatsTrack::updateCreatedOpinionsCount()
                 // Throughout this code, we could use $u and $user_name
                 // instead of $stats->user_id and $stats->user_name but
                 // there's no point in doing that because we have to call
                 // clearCache() in any case
                 if (!$wgUser->isAnon() && $stats->user_id) {
                     $ctg = $userBlogCat . ' ' . $stats->user_name;
                     $parser = new Parser();
                     $ctgTitle = Title::newFromText($parser->preprocess(trim($ctg), $wgOut->getTitle(), $wgOut->parserOptions()));
                     $ctgTitle = $ctgTitle->getDBkey();
                     $dbw = wfGetDB(DB_MASTER);
                     $opinions = $dbw->select(array('page', 'categorylinks'), array('COUNT(*) AS CreatedOpinions'), array('cl_to' => $ctgTitle, 'page_namespace' => NS_BLOG), __METHOD__, array(), array('categorylinks' => array('INNER JOIN', 'page_id = cl_from')));
                     // Please die in a fire, PHP.
                     // selectField() would be ideal above but it returns
                     // insane results (over 300 when the real count is
                     // barely 10) so we have to f**k around with a
                     // foreach() loop that we don't even need in theory
                     // just because PHP is...PHP.
                     $opinionsCreated = 0;
                     foreach ($opinions as $opinion) {
                         $opinionsCreated = $opinion->CreatedOpinions;
                     }
                     $res = $dbw->update('user_stats', array('stats_opinions_created' => $opinionsCreated), array('stats_user_id' => $stats->user_id), __METHOD__);
                     $stats->clearCache();
                 }
             }
         }
     }
     return true;
 }
	/**
	 * Delete a status message via its ID.
	 *
	 * @param $us_id Integer: ID number of the status message to delete
	 */
	public function deleteStatus( $us_id ) {
		if( $us_id ) {
			$dbw = wfGetDB( DB_MASTER );
			$s = $dbw->selectRow(
				'user_status',
				array(
					'us_user_id', 'us_user_name', 'us_sport_id', 'us_team_id'
				),
				array( 'us_id' => $us_id ),
				__METHOD__
			);
			if ( $s !== false ) {
				$dbw->delete(
					'user_status',
					array( 'us_id' => $us_id ),
					__METHOD__
				);

				$stats = new UserStatsTrack( $s->us_user_id, $s->us_user_name );
				$stats->decStatField( 'user_status_count' );
			}
		}
	}
function wfQuestionGameVote( $answer, $key, $id, $points ) {
	global $wgUser;

	if( $key != md5( 'SALT' . $id ) ) {
		$err = '
		{
			"status": "500",
			"error": "Key is invalid!"
		}';

		return $err;
	}

	if( !is_numeric( $answer ) ) {
		$err = '
		{
			"status": "500",
			"error": "Answer choice is not numeric."
		}';

		return $err;
	}

	$dbw = wfGetDB( DB_MASTER );

	// Check if they already answered
	$s = $dbw->selectRow(
		'quizgame_answers',
		array( 'a_choice_id' ),
		array( 'a_q_id' => intval( $id ), 'a_user_name' => $wgUser->getName() ),
		__METHOD__
	);
	if ( $s !== false ) {
		$err = '
		{
			"status": "500",
			"error": "You already answered this question."
		}';
		return $err;
	}

	// Add answer by user
	$dbw->insert(
		'quizgame_answers',
		array(
			'a_q_id' => intval( $id ),
			'a_user_id' => $wgUser->getID(),
			'a_user_name' => $wgUser->getName(),
			'a_choice_id' => $answer,
			'a_points' => $points,
			'a_date' => date( 'Y-m-d H:i:s' )
		),
		__METHOD__
	);

	// If the question is being skipped, stop here
	if( $answer == -1 ) {
		return 'ok';
	}

	// Clear out anti-cheating table
	$dbw->delete(
		'quizgame_user_view',
		array( 'uv_user_id' => $wgUser->getID(), 'uv_q_id' => intval( $id ) ),
		__METHOD__
	);
	$dbw->commit();

	// Update answer picked
	$dbw->update(
		'quizgame_choice',
		array( 'choice_answer_count = choice_answer_count+1' ),
		array( 'choice_id' => $answer ),
		__METHOD__
	);

	// Update question answered
	$dbw->update(
		'quizgame_questions',
		array( 'q_answer_count = q_answer_count+1' ),
		array( 'q_id' => intval( $id ) ),
		__METHOD__
	);

	// Add to stats how many quizzes the user has answered
	$stats = new UserStatsTrack( $wgUser->getID(), $wgUser->getName() );
	$stats->incStatField( 'quiz_answered' );

	// Check if the answer was right
	$s = $dbw->selectRow(
		'quizgame_questions',
		array( 'q_answer_count' ),
		array( 'q_id' => intval( $id ) ),
		__METHOD__
	);
	if ( $s !== false ) {
		$answer_count = $s->q_answer_count;
	}

	// Check if the answer was right
	$s = $dbw->selectRow(
		'quizgame_choice',
		array( 'choice_id', 'choice_text', 'choice_answer_count' ),
		array( 'choice_q_id' => intval( $id ), 'choice_is_correct' => 1 ),
		__METHOD__
	);

	if ( $s !== false ) {
		if( $answer_count ) {
			$formattedNumber = number_format( $s->choice_answer_count / $answer_count * 100, 1 );
			$percent = str_replace( '.0', '', $formattedNumber );
		} else {
			$percent = 0;
		}

		$isRight = ( ( $s->choice_id == $answer ) ? 'true' : 'false' );
		$output = "{'isRight': '{$isRight}', 'rightAnswer':'" .
			addslashes( $s->choice_text ) . "', 'percentRight':'{$percent}'}";

		if( $s->choice_id == $answer ) {
			// Update question answered correctly for entire question
			$dbw->update(
				'quizgame_questions',
				array( 'q_answer_correct_count = q_answer_correct_count+1' ),
				array( 'q_id' => $id ),
				__METHOD__
			);

			// Add to stats how many quizzes the user has answered correctly
			$stats->incStatField( 'quiz_correct' );

			// Add to point total
			if( !$wgUser->isBlocked() && is_numeric( $points ) ) {
				$stats->incStatField( 'quiz_points', $points );
			}
		}

		// Update the users % correct
		$dbw->update(
			'user_stats',
			array( 'stats_quiz_questions_correct_percent = stats_quiz_questions_correct/stats_quiz_questions_answered' ),
			array( 'stats_user_id' => $wgUser->getID() ),
			__METHOD__
		);

		return $output;
	} else {
		$err = '
		{
			"status": "500",
			"error": "There is no question by that ID."
		}';
		return $err;
	}

}
Example #21
0
 /**
  * Inserts a new vote into the Vote database table
  *
  * @param int $voteValue
  */
 function insert($voteValue)
 {
     global $wgRequest;
     $dbw = wfGetDB(DB_MASTER);
     wfSuppressWarnings();
     // E_STRICT whining
     $voteDate = date('Y-m-d H:i:s');
     wfRestoreWarnings();
     if ($this->UserAlreadyVoted() == false) {
         $dbw->begin();
         $dbw->insert('Vote', array('username' => $this->Username, 'vote_user_id' => $this->Userid, 'vote_page_id' => $this->PageID, 'vote_value' => $voteValue, 'vote_date' => $voteDate, 'vote_ip' => $wgRequest->getIP()), __METHOD__);
         $dbw->commit();
         $this->clearCache();
         // Update social statistics if SocialProfile extension is enabled
         if (class_exists('UserStatsTrack')) {
             $stats = new UserStatsTrack($this->Userid, $this->Username);
             $stats->incStatField('vote');
         }
     }
 }
 /**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the special page or null
  */
 public function execute($par)
 {
     global $wgOut, $wgUser, $wgRequest, $wgContLang;
     // If the user can't create blog posts, display an error
     if (!$wgUser->isAllowed('createblogpost')) {
         $wgOut->permissionRequired('createblogpost');
         return;
     }
     // Show a message if the database is in read-only mode
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return;
     }
     // If user is blocked, s/he doesn't need to access this page
     if ($wgUser->isBlocked()) {
         $wgOut->blockedPage(false);
         return false;
     }
     // Set page title, robot policies, etc.
     $this->setHeaders();
     // Add CSS & JS
     $wgOut->addModules('ext.blogPage.create');
     // If the request was POSTed, we haven't submitted a request yet AND
     // we have a title, create the page...otherwise just display the
     // creation form
     if ($wgRequest->wasPosted() && $_SESSION['alreadysubmitted'] == false) {
         $_SESSION['alreadysubmitted'] = true;
         // Protect against cross-site request forgery (CSRF)
         if (!$wgUser->matchEditToken($wgRequest->getVal('wpEditToken'))) {
             $wgOut->addHTML(wfMsg('sessionfailure'));
             return;
         }
         // Create a Title object, or try to, anyway
         $userSuppliedTitle = $wgRequest->getVal('title2');
         $title = Title::makeTitleSafe(NS_BLOG, $userSuppliedTitle);
         // @todo CHECKME: are these still needed? The JS performs these
         // checks already but then again JS is also easy to fool...
         // The user didn't supply a title? Ask them to supply one.
         if (!$userSuppliedTitle) {
             $wgOut->setPageTitle(wfMsg('errorpagetitle'));
             $wgOut->addWikiMsg('blog-create-error-need-title');
             $wgOut->addReturnTo($this->getTitle());
             return;
         }
         // The user didn't supply the blog post text? Ask them to supply it.
         if (!$wgRequest->getVal('pageBody')) {
             $wgOut->setPageTitle(wfMsg('errorpagetitle'));
             $wgOut->addWikiMsg('blog-create-error-need-content');
             $wgOut->addReturnTo($this->getTitle());
             return;
         }
         // Localized variables that will be used when creating the page
         $localizedCatNS = $wgContLang->getNsText(NS_CATEGORY);
         $today = $wgContLang->date(wfTimestampNow());
         // Create the blog page if it doesn't already exist
         $article = new Article($title, 0);
         if ($article->exists()) {
             $wgOut->setPageTitle(wfMsg('errorpagetitle'));
             $wgOut->addWikiMsg('blog-create-error-page-exists');
             $wgOut->addReturnTo($this->getTitle());
             return;
         } else {
             // The blog post will be by default categorized into two
             // categories, "Articles by User $1" and "(today's date)",
             // but the user may supply some categories themselves, so
             // we need to take those into account, too.
             $categories = array('[[' . $localizedCatNS . ':' . wfMsgForContent('blog-by-user-category', wfMsgForContent('blog-category')) . wfMsgForContent('word-separator') . $wgUser->getName() . ']]', "[[{$localizedCatNS}:{$today}]]");
             $userSuppliedCategories = $wgRequest->getVal('pageCtg');
             if (!empty($userSuppliedCategories)) {
                 // Explode along commas so that we will have an array that
                 // we can loop over
                 $userSuppliedCategories = explode(',', $userSuppliedCategories);
                 foreach ($userSuppliedCategories as $cat) {
                     $cat = trim($cat);
                     // GTFO@excess whitespace
                     if (!empty($cat)) {
                         $categories[] = "[[{$localizedCatNS}:{$cat}]]";
                     }
                 }
             }
             // Convert the array into a string
             $wikitextCategories = implode("\n", $categories);
             // Perform the edit
             $article->doEdit('<vote />' . "\n" . '<!--start text-->' . "\n" . $wgRequest->getVal('pageBody') . "\n\n" . '<comments />' . "\n\n" . $wikitextCategories . "\n__NOEDITSECTION__", wfMsgForContent('blog-create-summary'));
             $articleId = $article->getID();
             // Add a vote for the page
             // This was originally in its own global function,
             // wfFinishCreateBlog and after that in the BlogHooks class but
             // it just wouldn't work with Special:CreateBlogPost so I
             // decided to move it here since this is supposed to be like
             // the primary way of creating new blog posts...
             // Using OutputPageBeforeHTML hook, which, according to its
             // manual page, runs on *every* page view was such a stupid
             // idea IMHO.
             $vote = new Vote($articleId);
             $vote->insert(1);
             $stats = new UserStatsTrack($wgUser->getID(), $wgUser->getName());
             $stats->updateWeeklyPoints($stats->point_values['opinions_created']);
             $stats->updateMonthlyPoints($stats->point_values['opinions_created']);
             //if( $wgEnableFacebook ) {
             //	BlogHooks::updateFacebookProfile();
             //}
             //if( $wgSendNewArticleToFriends ) {
             //	$invite = SpecialPage::getTitleFor( 'EmailNewArticle' );
             //	$wgOut->redirect(
             //		$invite->getFullURL( 'page=' . $title->getPrefixedText() )
             //	);
             //}
             // Redirect the user to the new blog post they just created
             $wgOut->redirect($title->getFullURL());
         }
     } else {
         $_SESSION['alreadysubmitted'] = false;
         // Start building the HTML
         $output = '';
         // Show the blog rules, if the message containing them ain't empty
         $message = trim(wfMsgExt('blog-create-rules', array('parse', 'content')));
         // Yes, the strlen() is needed, I dunno why wfEmptyMsg() won't work
         if (!wfEmptyMsg('blog-create-rules', $message) && strlen($message) > 0) {
             $output .= $message . '<br />';
         }
         // Main form
         $output .= $this->displayForm();
         // Show everything to the user
         $wgOut->addHTML($output);
     }
 }
function wfCommentBlock($comment_id, $user_id)
{
    // Load user_name and user_id for person we want to block from the comment it originated from
    $dbr = wfGetDB(DB_SLAVE);
    $s = $dbr->selectRow('Comments', array('comment_username', 'comment_user_id'), array('CommentID' => $comment_id), __METHOD__);
    if ($s !== false) {
        $user_id = $s->comment_user_id;
        $user_name = $s->comment_username;
    }
    $comment = new Comment(0);
    $comment->blockUser($user_id, $user_name);
    if (class_exists('UserStatsTrack')) {
        $stats = new UserStatsTrack($user_id, $user_name);
        $stats->incStatField('comment_ignored');
    }
    return 'ok';
}
    /**
     * Show the special page
     *
     * @param $period String: either weekly or monthly
     */
    public function execute($period)
    {
        global $wgContLang, $wgUser;
        global $wgUserStatsPointValues;
        $out = $this->getOutput();
        $request = $this->getRequest();
        $user = $this->getUser();
        // Blocked through Special:Block? Tough luck.
        if ($user->isBlocked()) {
            $out->blockedPage(false);
            return false;
        }
        // Is the database locked or not?
        if (wfReadOnly()) {
            $out->readOnlyPage();
            return false;
        }
        // Check for the correct permission
        if (!$user->isAllowed('generatetopusersreport')) {
            $out->permissionRequired('generatetopusersreport');
            return false;
        }
        // Set the page title, robot policy, etc.
        $this->setHeaders();
        $period = $request->getVal('period', $period);
        // If we don't have a period, default to weekly or else we'll be
        // hitting a database error because when constructing table names
        // later on in the code, we assume that $period is set to something
        if (!$period) {
            $period = 'weekly';
        }
        // Make sure that we are actually going to give out some extra points
        // for weekly and/or monthly wins, depending on which report we're
        // generating here. If not, there's no point in continuing.
        if (empty($wgUserStatsPointValues["points_winner_{$period}"])) {
            $out->addHTML($this->msg('user-stats-report-error-variable-not-set', $period)->escaped());
            return;
        }
        // There used to be a lot of inline CSS here in the original version.
        // I removed that, because most of it is already in TopList.css, inline
        // CSS (and JS, for that matter) is evil, there were only 5 CSS
        // declarations that weren't in TopList.css and it was making the
        // display look worse, not better.
        // Add CSS
        $out->addModuleStyles('ext.socialprofile.userstats.css');
        // Used as the LIMIT for SQL queries; basically, show this many users
        // in the generated reports.
        $user_count = $request->getInt('user_count', 10);
        if ($period == 'weekly') {
            $period_title = $wgContLang->date(wfTimestamp(TS_MW, strtotime('-1 week'))) . '-' . $wgContLang->date(wfTimestampNow());
        } elseif ($period == 'monthly') {
            $date = getdate();
            // It's a PHP core function
            $period_title = $wgContLang->getMonthName($date['mon']) . ' ' . $date['year'];
        }
        $dbw = wfGetDB(DB_MASTER);
        // Query the appropriate points table
        $res = $dbw->select("user_points_{$period}", array('up_user_id', 'up_user_name', 'up_points'), array(), __METHOD__, array('ORDER BY' => 'up_points DESC', 'LIMIT' => $user_count));
        $last_rank = 0;
        $last_total = 0;
        $x = 1;
        $users = array();
        // Initial run is a special case
        if ($dbw->numRows($res) <= 0) {
            // For the initial run, everybody's a winner!
            // Yes, I know that this isn't ideal and I'm sorry about that.
            // The original code just wouldn't work if the first query
            // (the $res above) returned nothing so I had to work around that
            // limitation.
            $res = $dbw->select('user_stats', array('stats_user_id', 'stats_user_name', 'stats_total_points'), array(), __METHOD__, array('ORDER BY' => 'stats_total_points DESC', 'LIMIT' => $user_count));
            $output = '<div class="top-users">';
            foreach ($res as $row) {
                if ($row->stats_total_points == $last_total) {
                    $rank = $last_rank;
                } else {
                    $rank = $x;
                }
                $last_rank = $x;
                $last_total = $row->stats_total_points;
                $x++;
                $userObj = User::newFromId($row->stats_user_id);
                $user_group = $userObj->getEffectiveGroups();
                if (!in_array('bot', $user_group) && !in_array('bot-global', $user_group)) {
                    $users[] = array('user_id' => $row->stats_user_id, 'user_name' => $row->stats_user_name, 'points' => $row->stats_total_points, 'rank' => $rank);
                }
            }
        } else {
            $output = '<div class="top-users">';
            foreach ($res as $row) {
                if ($row->up_points == $last_total) {
                    $rank = $last_rank;
                } else {
                    $rank = $x;
                }
                $last_rank = $x;
                $last_total = $row->up_points;
                $x++;
                $userObj = User::newFromId($row->up_user_id);
                $user_group = $userObj->getEffectiveGroups();
                if (!in_array('bot', $user_group) && !in_array('bot-global', $user_group)) {
                    $users[] = array('user_id' => $row->up_user_id, 'user_name' => $row->up_user_name, 'points' => $row->up_points, 'rank' => $rank);
                }
            }
        }
        $winner_count = 0;
        $winners = '';
        if (!empty($users)) {
            $localizedUserNS = $wgContLang->getNsText(NS_USER);
            foreach ($users as $user) {
                if ($user['rank'] == 1) {
                    // Mark the user ranked #1 as the "winner" for the given
                    // period
                    if ($period == 'weekly') {
                        $systemGiftID = 9;
                    } elseif ($period == 'monthly') {
                        $systemGiftID = 10;
                    }
                    $sg = new UserSystemGifts($user['user_name']);
                    $sg->sendSystemGift($systemGiftID);
                    $stats = new UserStatsTrack($user['user_id'], $user['user_name']);
                    $stats->incStatField("points_winner_{$period}");
                    if ($winners) {
                        $winners .= ', ';
                    }
                    $winners .= "[[{$localizedUserNS}:{$user['user_name']}|{$user['user_name']}]]";
                    $winner_count++;
                } elseif ($user['rank'] == 2 || $user['rank'] == 3) {
                    if ($period == 'weekly') {
                        $systemGiftID = 13;
                    } elseif ($period == 'monthly') {
                        $systemGiftID = 15;
                    }
                    $sg = new UserSystemGifts($user['user_name']);
                    $sg->sendSystemGift($systemGiftID);
                } else {
                    if ($period == 'weekly') {
                        $systemGiftID = 14;
                    } elseif ($period == 'monthly') {
                        $systemGiftID = 16;
                    }
                    $sg = new UserSystemGifts($user['user_name']);
                    $sg->sendSystemGift($systemGiftID);
                }
            }
        }
        // Start building the content of the report page
        $pageContent = "__NOTOC__\n";
        // For grep: user-stats-weekly-winners, user-stats-monthly-winners
        $pageContent .= '==' . $this->msg("user-stats-{$period}-winners")->numParams($winner_count)->inContentLanguage()->parse() . "==\n\n";
        // For grep: user-stats-weekly-win-congratulations, user-stats-monthly-win-congratulations
        $pageContent .= $this->msg("user-stats-{$period}-win-congratulations")->numParams($winner_count, $wgContLang->formatNum($wgUserStatsPointValues["points_winner_{$period}"]))->inContentLanguage()->parse() . "\n\n";
        $pageContent .= "=={$winners}==\n\n<br />\n";
        $pageContent .= '==' . $this->msg('user-stats-full-top')->numParams($wgContLang->formatNum($user_count))->inContentLanguage()->parse() . "==\n\n";
        foreach ($users as $user) {
            $userTitle = Title::makeTitle(NS_USER, $user['user_name']);
            $pageContent .= $this->msg('user-stats-report-row', $wgContLang->formatNum($user['rank']), $user['user_name'], $wgContLang->formatNum($user['points']))->inContentLanguage()->parse() . "\n\n";
            $output .= "<div class=\"top-fan-row\">\n\t\t\t<span class=\"top-fan-num\">{$user['rank']}</span><span class=\"top-fan\"> <a href='" . $userTitle->getFullURL() . "' >" . $user['user_name'] . "</a>\n\t\t\t</span>";
            $output .= '<span class="top-fan-points">' . $this->msg('user-stats-report-points', $wgContLang->formatNum($user['points']))->inContentLanguage()->parse() . '</span>
		</div>';
        }
        // Make the edit as MediaWiki default
        $oldUser = $wgUser;
        $wgUser = User::newFromName('MediaWiki default');
        $wgUser->addGroup('bot');
        // Add a note to the page that it was automatically generated
        $pageContent .= "\n\n''" . $this->msg('user-stats-report-generation-note')->parse() . "''\n\n";
        // Create the Title object that represents the report page
        // For grep: user-stats-report-weekly-page-title, user-stats-report-monthly-page-title
        $title = Title::makeTitleSafe(NS_PROJECT, $this->msg("user-stats-report-{$period}-page-title", $period_title)->inContentLanguage()->escaped());
        $article = new Article($title);
        // If the article doesn't exist, create it!
        // @todo Would there be any point in updating a pre-existing article?
        // I think not, but...
        if (!$article->exists()) {
            // For grep: user-stats-report-weekly-edit-summary, user-stats-report-monthly-edit-summary
            $article->doEdit($pageContent, $this->msg("user-stats-report-{$period}-edit-summary")->inContentLanguage()->escaped());
            $date = date('Y-m-d H:i:s');
            // Archive points from the weekly/monthly table into the archive
            // table
            $dbw->insertSelect('user_points_archive', "user_points_{$period}", array('up_user_name' => 'up_user_name', 'up_user_id' => 'up_user_id', 'up_points' => 'up_points', 'up_period' => $period == 'weekly' ? 1 : 2, 'up_date' => $dbw->addQuotes($date)), '*', __METHOD__);
            // Clear the current point table to make way for the next period
            $res = $dbw->delete("user_points_{$period}", '*', __METHOD__);
        }
        // Switch the user back
        $wgUser = $oldUser;
        $output .= '</div>';
        // .top-users
        $out->addHTML($output);
    }
Example #25
0
 function execute()
 {
     global $wgUser, $wgOut, $wgVoteDirectory, $IP;
     require_once 'CommentClass.php';
     require_once "{$wgVoteDirectory}/VoteClass.php";
     require_once "{$wgVoteDirectory}/Publish.php";
     require_once "{$IP}/extensions/UserStats/UserStatsClass.php";
     $stats = new UserStatsTrack(1, $wgUser->mId, $wgUser->mName);
     // Vote for a Comment
     if ($_POST["mk"] == md5($_POST["cid"] . 'pants' . $wgUser->mName)) {
         if (is_numeric($_GET["Action"]) && $_GET["Action"] == 1 && is_numeric($_POST["cid"])) {
             if (is_numeric($_POST["cid"]) && is_numeric($_POST["vt"])) {
                 $dbr =& wfGetDB(DB_MASTER);
                 $sql = "SELECT comment_page_id,comment_user_id, comment_username FROM Comments WHERE CommentID = " . $_POST["cid"];
                 $res = $dbr->query($sql);
                 $row = $dbr->fetchObject($res);
                 if ($row) {
                     $PageID = $row->comment_page_id;
                     $Comment = new Comment($PageID);
                     $Comment->setUser($wgUser->mName, $wgUser->mId);
                     $Comment->CommentID = $_POST["cid"];
                     $Comment->setCommentVote($_POST["vt"]);
                     $Comment->setVoting($_POST["vg"]);
                     $Comment->addVote();
                     $out = $Comment->getCommentScore();
                     //must update stats for user doing the voting
                     $stats->incCommentScoreGiven($_POST["vt"]);
                     //also must update the stats for user receiving the vote
                     $stats_comment_owner = new UserStatsTrack(1, $row->comment_user_id, $row->comment_username);
                     $stats_comment_owner->updateCommentScoreRec($_POST["vt"]);
                     echo $out;
                 }
             }
         }
     }
     // get new Comment list
     if (is_numeric($_GET["Action"]) && $_GET["Action"] == 2 && is_numeric($_POST["pid"])) {
         $Comment = new Comment($_POST["pid"]);
         $Comment->setUser($wgUser->mName, $wgUser->mId);
         $Comment->setOrderBy($_POST["ord"]);
         if ($_POST["shwform"] == 1) {
             $output .= $Comment->displayOrderForm();
         }
         $output .= $Comment->display();
         if ($_POST["shwform"] == 1) {
             $output .= $Comment->diplayForm();
         }
         echo $output;
     }
     if ($_POST['ct'] != "" && is_numeric($_GET["Action"]) && $_GET["Action"] == 3) {
         $input = $_POST['ct'];
         $host = $_SERVER['SERVER_NAME'];
         $input = str_replace($host, "", $input);
         $AddComment = true;
         if ($AddComment == true) {
             $Comment = new Comment($_POST["pid"]);
             $Comment->setUser($wgUser->mName, $wgUser->mId);
             $Comment->setCommentText($_POST['ct']);
             $Comment->setCommentParentID($_POST['par']);
             $Comment->add();
             //$stats->incCommentCount();
             //score check after comment add
             $Vote = new Vote($_POST["pid"]);
             $publish = new Publish();
             $publish->PageID = $_POST["pid"];
             $publish->VoteCount = $Vote->count(1);
             $publish->CommentCount = $Comment->count();
             $publish->check_score();
         }
     }
     if (is_numeric($_GET["Action"]) && $_GET["Action"] == 4 && is_numeric($_GET["pid"])) {
         $Comment = new Comment($_GET["pid"]);
         $Comment->setUser($wgUser->mName, $wgUser->mId);
         echo $Comment->getLatestCommentID();
     }
     // This line removes the navigation and everything else from the
     // page, if you don't set it, you get what looks like a regular wiki
     // page, with the body you defined above.
     $wgOut->setArticleBodyOnly(true);
 }
	/**
	 * Insert information about the new picture game into the database,
	 * increase social statistics, purge memcached entries and redirect the
	 * user to the newly-created picture game.
	 */
	function createGame() {
		global $wgRequest, $wgUser;

		// @todo FIXME: as per Tim: http://www.mediawiki.org/wiki/Special:Code/MediaWiki/59183#c4709
		$title = addslashes( $wgRequest->getVal( 'picGameTitle' ) );

		$img1 = addslashes( $wgRequest->getVal( 'picOneURL' ) );
		$img2 = addslashes( $wgRequest->getVal( 'picTwoURL' ) );
		$img1_caption = addslashes( $wgRequest->getVal( 'picOneDesc' ) );
		$img2_caption = addslashes( $wgRequest->getVal( 'picTwoDesc' ) );

		$key = $wgRequest->getVal( 'key' );
		$chain = $wgRequest->getVal( 'chain' );
		$id = -1;

		$dbr = wfGetDB( DB_MASTER );

		// make sure no one is trying to do bad things
		if( $key == md5( $chain . $this->SALT ) ) {
			$sql = "SELECT COUNT(*) AS mycount FROM {$dbr->tableName( 'picturegame_images' )} WHERE
				( img1 = \"" . $img1 . "\" OR img2 = \"" . $img1 . "\" ) AND
				( img1 = \"" . $img2 . "\" OR img2 = \"" . $img2 . "\" ) GROUP BY id;";

			$res = $dbr->query( $sql, __METHOD__ );
			$row = $dbr->fetchObject( $res );

			// if these image pairs don't exist, insert them
			if( $row->mycount == 0 ) {
				$dbr->insert(
					'picturegame_images',
					array(
						'userid' => $wgUser->getID(),
						'username' => $wgUser->getName(),
						'img1' => $img1,
						'img2' => $img2,
						'title' => $title,
						'img1_caption' => $img1_caption,
						'img2_caption' => $img2_caption,
						'pg_date' => date( 'Y-m-d H:i:s' )
					),
					__METHOD__
				);

				$id = $dbr->selectField(
					'picturegame_images',
					'MAX(id) AS maxid',
					array(),
					__METHOD__
				);

				// Increase social statistics
				$stats = new UserStatsTrack( $wgUser->getID(), $wgUser->getName() );
				$stats->incStatField( 'picturegame_created' );

				// Purge memcached
				global $wgMemc;
				$key = wfMemcKey( 'user', 'profile', 'picgame', $wgUser->getID() );
				$wgMemc->delete( $key );
			}
		}

		header( "Location: ?title=Special:PictureGameHome&picGameAction=startGame&id={$id}" );
	}
	function createQuizGame() {
		global $wgRequest, $wgUser, $wgMemc, $wgQuizLogs;

		$key = $wgRequest->getText( 'key' );
		$chain = $wgRequest->getText( 'chain' );

		$max_answers = 8;

		if( $key != md5( $this->SALT . $chain ) ) {
			header( 'Location: ' . $this->getTitle()->getFullURL() );
			return;
		}

		$question = $wgRequest->getText( 'quizgame-question' );
		$imageName = $wgRequest->getText( 'quizGamePictureName' );

		// Add quiz question
		$dbw = wfGetDB( DB_MASTER );
		$dbw->insert(
			'quizgame_questions',
			array(
				'q_user_id' => $wgUser->getID(),
				'q_user_name' => $wgUser->getName(),
				'q_text' => strip_tags( $question ), // make sure nobody inserts malicious code
				'q_picture' => $imageName,
				'q_date' => date( 'Y-m-d H:i:s' ),
				'q_random' => wfRandom()
			),
			__METHOD__
		);
		$questionId = $dbw->insertId();

		// Add Quiz Choices
		for( $x = 1; $x <= $max_answers; $x++ ) {
			if( $wgRequest->getVal( "quizgame-answer-{$x}" ) ) {
				if( $wgRequest->getVal( "quizgame-isright-{$x}" ) == 'on' ) {
					$is_correct = 1;
				} else {
					$is_correct = 0;
				}
				$dbw->insert(
					'quizgame_choice',
					array(
						'choice_q_id' => $questionId,
						'choice_text' => strip_tags( $wgRequest->getVal( "quizgame-answer-{$x}" ) ), // make sure nobody inserts malicious code
						'choice_order' => $x,
						'choice_is_correct' => $is_correct
					),
					__METHOD__
				);
				$dbw->commit();
			}
		}
		$stats = new UserStatsTrack( $wgUser->getID(), $wgUser->getName() );
		$stats->incStatField( 'quiz_created' );

		// Add a log entry if quiz logging is enabled
		if( $wgQuizLogs ) {
			$message = wfMsgForContent(
				'quiz-questions-log-create-text',
				"Special:QuizGameHome/{$questionId}"
			);
			$log = new LogPage( 'quiz' );
			$log->addEntry( 'create', $wgUser->getUserPage(), $message );
		}

		// Delete memcached key
		$key = wfMemcKey( 'user', 'profile', 'quiz', $wgUser->getID() );
		$wgMemc->delete( $key );

		// Redirect the user
		header( 'Location: ' . $this->getTitle()->getFullURL( "questionGameAction=renderPermalink&permalinkID={$questionId}" ) );
	}
Example #28
0
 private function setFile($file)
 {
     global $wgUploadDirectory, $wgAvatarKey, $wgMemc, $wgUser, $wgSiteAvatarKey, $wgHuijiPrefix;
     if (!$this->isUserAvatar) {
         $uid = $wgHuijiPrefix;
         $avatarKey = $wgSiteAvatarKey;
         $avatar = new wSiteAvatar($uid, 'l');
     } else {
         $uid = $wgUser->getId();
         $avatarKey = $wgAvatarKey;
         $avatar = new wAvatar($uid, 'l');
     }
     // $dest = $this->avatarUploadDirectory;
     $imageInfo = getimagesize($file->getTempName());
     $errorCode = $file->getError();
     if ($errorCode === UPLOAD_ERR_OK) {
         $type = exif_imagetype($file->getTempName());
         if ($type) {
             $extension = image_type_to_extension($type);
             $src = $this->avatarUploadDirectory . '/' . date('YmdHis') . '.original' . $extension;
             if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) {
                 if (file_exists($src)) {
                     unlink($src);
                 }
                 // If this is the user's first custom avatar, update statistics (in
                 // case if we want to give out some points to the user for uploading
                 // their first avatar)
                 if ($this->isUserAvatar && strpos($avatar->getAvatarImage(), 'default_') !== false) {
                     $stats = new UserStatsTrack($uid, $wgUser->getName());
                     $stats->incStatField('user_image');
                 }
                 $this->createThumbnail($file->getTempName(), $imageInfo, $avatarKey . '_' . $uid . '_l', 200);
                 $this->createThumbnail($file->getTempName(), $imageInfo, $avatarKey . '_' . $uid . '_ml', 50);
                 $this->createThumbnail($file->getTempName(), $imageInfo, $avatarKey . '_' . $uid . '_m', 30);
                 $this->createThumbnail($file->getTempName(), $imageInfo, $avatarKey . '_' . $uid . '_s', 16);
                 switch ($imageInfo[2]) {
                     case 1:
                         $ext = 'gif';
                         break;
                     case 2:
                         $ext = 'jpg';
                         break;
                     case 3:
                         $ext = 'png';
                         break;
                     default:
                         return $this->msg = '请上传如下类型的图片: JPG, PNG, GIF(错误代码:14)';
                 }
                 $this->cleanUp($ext, $avatarKey, $uid);
                 /* I know this is bad but whatever */
                 $result = true;
                 if ($result) {
                     $this->src = $src;
                     $this->type = $type;
                     $this->extension = $extension;
                     //$this -> setDst();
                 } else {
                     $this->msg = '无法保存文件(错误代码:13)';
                 }
             } else {
                 $this->msg = '请上传如下类型的图片: JPG, PNG, GIF(错误代码:12)';
             }
         } else {
             $this->msg = '请上传一个图片文件(错误代码:11)';
         }
     } else {
         $this->msg = $this->codeToMessage($errorCode);
     }
 }
 public function approveLink($id)
 {
     $link = $this->getLink($id);
     // Create the wiki page for the newly-approved link
     $linkTitle = Title::makeTitleSafe(NS_LINK, $link['title']);
     $article = new Article($linkTitle);
     $article->doEdit($link['url'], wfMsgForContent('linkfilter-edit-summary'));
     $newPageId = $article->getID();
     // Tie link record to wiki page
     $dbw = wfGetDB(DB_MASTER);
     wfSuppressWarnings();
     $date = date('Y-m-d H:i:s');
     wfRestoreWarnings();
     $dbw->update('link', array('link_page_id' => intval($newPageId), 'link_approved_date' => $date), array('link_id' => intval($id)), __METHOD__);
     $dbw->commit();
     if (class_exists('UserStatsTrack')) {
         $stats = new UserStatsTrack($link['user_id'], $link['user_name']);
         $stats->incStatField('links_approved');
     }
 }