/** add a user follow site action to the database.
  *
  *  @param $follower User object: the user who initiates the follow
  *  @param $followee User object: the user to be followed
  *	@return mixed: false if unsuccessful, id if successful
  */
 public function addUserUserFollow($follower, $followee)
 {
     if ($follower == null || $followee == null) {
         return false;
     }
     if ($follower == $followee) {
         return false;
     }
     if ($this->checkUserUserFollow($follower, $followee) != false) {
         return 0;
     }
     $dbw = wfGetDB(DB_MASTER);
     $dbw->insert('user_user_follow', array('f_user_id' => $follower->getId(), 'f_user_name' => $follower->getName(), 'f_target_user_id' => $followee->getId(), 'f_target_user_name' => $followee->getName(), 'f_date' => date('Y-m-d H:i:s')), __METHOD__);
     $followId = $dbw->insertId();
     $this->incFollowCount($follower, $followee);
     $stats = new UserStatsTrack($follower->getId(), $follower->getName());
     $stats->incStatField('friend');
     //use friend record to count the number of people followed.
     $stats = new UserStatsTrack($followee->getId(), $followee->getName());
     $stats->incStatField('foe');
     // use foe record to count the number of people following.
     // TODO: Notify the followee?
     EchoEvent::create(array('type' => 'follow-msg', 'extra' => array('followee-user-id' => $followee->getId(), 'agent-page' => $follower->getUserPage()), 'agent' => $follower, 'title' => $followee->getUserPage()));
     return $followId;
 }
	/**
	 * 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
 /**
  * Sends a user board message to another user.
  * Performs the insertion to user_board table, sends e-mail notification
  * (if appliable), and increases social statistics as appropriate.
  *
  * @param $user_id_from Integer: user ID of the sender
  * @param $user_name_from Mixed: user name of the sender
  * @param $user_id_to Integer: user ID of the reciever
  * @param $user_name_to Mixed: user name of the reciever
  * @param $message Mixed: message text
  * @param $message_type Integer: 0 for public message
  * @return Integer: the inserted value of ub_id row
  */
 public function sendBoardMessage($user_id_from, $user_name_from, $user_id_to, $user_name_to, $message, $message_type = 0)
 {
     // convert '@' to wiki link;
     $message = CommentFunctions::preprocessText($message);
     $dbw = wfGetDB(DB_MASTER);
     $user_name_from = stripslashes($user_name_from);
     $user_name_to = stripslashes($user_name_to);
     $dbw->insert('user_board', array('ub_user_id_from' => $user_id_from, 'ub_user_name_from' => $user_name_from, 'ub_user_id' => $user_id_to, 'ub_user_name' => $user_name_to, 'ub_message' => $message, 'ub_type' => $message_type, 'ub_date' => date('Y-m-d H:i:s')), __METHOD__);
     // Send e-mail notification (if user is not writing on own board)
     if ($user_id_from != $user_id_to) {
         $this->sendBoardNotificationEmail($user_id_to, $user_name_from, $message);
         $this->incNewMessageCount($user_id_to);
     }
     $mentionedUsers = CommentFunctions::getMentionedUsers($message);
     if (count($mentionedUsers) && $message_type == 0) {
         $this->sendMentionedNotification($user_id_from, $user_name_from, $user_id_to, $user_name_to, $message, $mentionedUsers);
     }
     $stats = new UserStatsTrack($user_id_to, $user_name_to);
     if ($message_type == 0) {
         // public message count
         $stats->incStatField('user_board_count');
     } else {
         // private message count
         $stats->incStatField('user_board_count_priv');
     }
     $stats = new UserStatsTrack($user_id_from, $user_name_from);
     $stats->incStatField('user_board_sent');
     return $dbw->insertId();
 }
	public function addStatus( $sport_id, $team_id, $text ) {
		global $wgUser;

		$dbw = wfGetDB( DB_MASTER );

		if( $wgUser->isBlocked() ) {
			return '';
		}

		$dbw->insert(
			'user_status',
			array(
				'us_user_id' => $wgUser->getID(),
				'us_user_name' => $wgUser->getName(),
				'us_sport_id' => $sport_id,
				'us_team_id' => $team_id,
				'us_text' => $text,
				'us_date' => date( 'Y-m-d H:i:s' ),
			),
			__METHOD__
		);
		$us_id = $dbw->insertId();

		$stats = new UserStatsTrack( $wgUser->getID(), $wgUser->getName() );
		$stats->incStatField( 'user_status_count' );

		$this->updateUserCache( $text, $sport_id, $team_id );

		return $us_id;
	}
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;
}
 /** add a user follow site action to the database.
  *
  *  @param $user User object: the user_name who initiates the follow
  *  @param $huijiPrefix string: the wiki to be followed, use prefix as identifier.
  *	@return bool: true if successfully followed
  */
 public function addUserSiteFollow($user, $huijiPrefix)
 {
     global $wgMemc;
     if ($this->checkUserSiteFollow($user, $huijiPrefix) != false) {
         return 0;
     }
     $dbw = wfGetDB(DB_MASTER);
     $dbw->insert('user_site_follow', array('f_user_id' => $user->getId(), 'f_user_name' => $user->getName(), 'f_wiki_domain' => $huijiPrefix, 'f_date' => date('Y-m-d H:i:s')), __METHOD__);
     $followId = $dbw->insertId();
     $this->incFollowCount($user, $huijiPrefix);
     $stats = new UserStatsTrack($user->getId(), $user->getName());
     $stats->incStatField('friend');
     //store result in cache
     if ($followId > 0) {
         $key = wfForeignMemcKey('huiji', '', 'user_site_follow', 'check_follow', $user->getName(), $huijiPrefix);
         $wgMemc->set($key, true);
     }
     // Notify Siteadmin maybe?
     return $followId;
 }
	/**
	 * 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' );
		}
	}
/**
 * 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();
	}
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;
	}

}
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';
}
Example #12
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);
     }
 }
	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 #14
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');
         }
     }
 }
 /**
  * Add a new relationship to the database.
  *
  * @param $relationshipRequestId Integer: relationship request ID number
  * @param $email Boolean: send out email to the recipient of the request?
  * @return Boolean: true if successful, otherwise false
  */
 public function addRelationship($relationshipRequestId, $email = true)
 {
     global $wgMemc;
     $dbw = wfGetDB(DB_MASTER);
     $s = $dbw->selectRow('user_relationship_request', array('ur_user_id_from', 'ur_user_name_from', 'ur_type'), array('ur_id' => $relationshipRequestId), __METHOD__);
     if ($s == true) {
         $ur_user_id_from = $s->ur_user_id_from;
         $ur_user_name_from = $s->ur_user_name_from;
         $ur_type = $s->ur_type;
         if (self::getUserRelationshipByID($this->user_id, $ur_user_id_from) > 0) {
             return '';
         }
         $dbw->insert('user_relationship', array('r_user_id' => $this->user_id, 'r_user_name' => $this->user_name, 'r_user_id_relation' => $ur_user_id_from, 'r_user_name_relation' => $ur_user_name_from, 'r_type' => $ur_type, 'r_date' => date('Y-m-d H:i:s')), __METHOD__);
         $dbw->insert('user_relationship', array('r_user_id' => $ur_user_id_from, 'r_user_name' => $ur_user_name_from, 'r_user_id_relation' => $this->user_id, 'r_user_name_relation' => $this->user_name, 'r_type' => $ur_type, 'r_date' => date('Y-m-d H:i:s')), __METHOD__);
         $stats = new UserStatsTrack($this->user_id, $this->user_name);
         if ($ur_type == 1) {
             $stats->incStatField('friend');
         } else {
             $stats->incStatField('foe');
         }
         $stats = new UserStatsTrack($ur_user_id_from, $ur_user_name_from);
         if ($ur_type == 1) {
             $stats->incStatField('friend');
         } else {
             $stats->incStatField('foe');
         }
         if ($email) {
             $this->sendRelationshipAcceptEmail($ur_user_id_from, $this->user_name, $ur_type);
         }
         // Purge caches
         $wgMemc->delete(wfForeignMemcKey('huiji', '', 'relationship', 'profile', "{$this->user_id}-{$ur_type}"));
         $wgMemc->delete(wfForeignMemcKey('huiji', '', 'relationship', 'profile', "{$ur_user_id_from}-{$ur_type}"));
         // Hooks (for Semantic SocialProfile mostly)
         if ($ur_type == 1) {
             wfRunHooks('NewFriendAccepted', array($ur_user_name_from, $this->user_name));
         } else {
             wfRunHooks('NewFoeAccepted', array($ur_user_name_from, $this->user_name));
         }
         return true;
     } else {
         return false;
     }
 }
    /**
     * 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);
    }
	/**
	 * 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}" );
	}
 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');
     }
 }