Example #1
0
 public function notifyUserIds($contentType, $contentId, $contentUserId, $contentUserName, $alertAction, array $userIds, array $noAlertUserIds, array $noEmailUserIds, XenForo_Model_User $userModel, array $options)
 {
     if (!empty($userIds)) {
         $fetchOptions = array();
         if (!empty($options['users']['fetchOptions'])) {
             $fetchOptions = $options['users']['fetchOptions'];
         }
         if (empty($fetchOptions['join'])) {
             $fetchOptions['join'] = 0;
         }
         $fetchOptions['join'] |= XenForo_Model_User::FETCH_USER_OPTION;
         $fetchOptions['join'] |= XenForo_Model_User::FETCH_USER_PROFILE;
         $users = $userModel->getUsersByIds($userIds, $fetchOptions);
     } else {
         $users = array();
     }
     foreach ($users as $user) {
         if ($user['user_id'] == $contentUserId) {
             // it's stupid to notify one's self
             continue;
         }
         if (!empty($options[self::OPTION_USER_CALLBACK])) {
             $userCallbackResult = call_user_func($options[self::OPTION_USER_CALLBACK], $userModel, $user, $options);
             if ($userCallbackResult === false) {
                 // user callback returns false, do not continue
                 continue;
             }
         }
         if (!$userModel->isUserIgnored($user, $contentUserId)) {
             $shouldAlert = true;
             if (!XenForo_Model_Alert::userReceivesAlert($user, $contentType, $alertAction)) {
                 $shouldAlert = false;
             }
             if (in_array($user['user_id'], $noAlertUserIds) || in_array($user['user_id'], $noEmailUserIds)) {
                 $shouldAlert = false;
             }
             if ($shouldAlert) {
                 XenForo_Model_Alert::alert($user['user_id'], $contentUserId, $contentUserName, $contentType, $contentId, $alertAction);
             }
             if (bdTagMe_Option::get('alertEmail') && !empty($user['bdtagme_email'])) {
                 $shouldEmail = true;
                 if (in_array($user['user_id'], $noEmailUserIds)) {
                     $shouldEmail = false;
                 }
                 if ($shouldEmail) {
                     /** @var bdTagMe_XenForo_Model_Alert $alertModel */
                     $alertModel = $userModel->getModelFromCache('XenForo_Model_Alert');
                     $viewLink = $alertModel->bdTagMe_getContentLink($contentType, $contentId);
                     if (!empty($viewLink)) {
                         $mail = XenForo_Mail::create('bdtagme_tagged', array('sender' => array('user_id' => $contentUserId, 'username' => $contentUserName), 'receiver' => $user, 'contentType' => $contentType, 'contentId' => $contentId, 'viewLink' => $viewLink), $user['language_id']);
                         $mail->enableAllLanguagePreCache();
                         $mail->queue($user['email'], $user['username']);
                     }
                 }
             }
         }
     }
     return true;
 }
Example #2
0
 /**
  * Sends an alert to the profile owner
  *
  * Note: ensure that you $dw->setExtraData(self::PROFILE_USER, $profileUser) to save a query
  */
 protected function _alertUser()
 {
     if (!($profileUser = $this->getExtraData(self::DATA_PROFILE_USER))) {
         $profileUser = array('user_id' => $this->get('profile_user_id'));
     }
     if (XenForo_Model_Alert::userReceivesAlert($profileUser, $this->getContentType(), 'insert')) {
         XenForo_Model_Alert::alert($this->get('profile_user_id'), $this->get('user_id'), $this->get('username'), $this->getContentType(), $this->get('profile_post_id'), 'insert');
     }
 }
Example #3
0
 public function sendDeleteAlert($alertType, $postId, array $threadstarters, XenForo_Visitor $visitor = null)
 {
     $visitor = XenForo_Visitor::getInstance();
     if (!$visitor) {
         $visitor = XenForo_Visitor::getInstance();
     }
     if (!empty($threadstarters)) {
         foreach ($threadstarters as $threadstarter) {
             $user = $this->_getUserModel()->getUserByName($threadstarter);
             if (XenForo_Model_Alert::userReceivesAlert($user, 'post', $alertType)) {
                 XenForo_Model_Alert::alert($user['user_id'], $visitor['user_id'], $visitor['username'], 'post', $postId, $alertType);
             }
         }
     }
     return false;
 }
Example #4
0
 protected function _bdApiConsumer_getExternalAlertsForUser(array $viewingUser, $alwaysCheck)
 {
     /** @var bdApiConsumer_XenForo_Model_UserExternal $userExternalModel */
     $userExternalModel = $this->getModelFromCache('XenForo_Model_UserExternal');
     $auths = $userExternalModel->bdApiConsumer_getExternalAuthAssociations($viewingUser['user_id']);
     foreach ($auths as &$authRef) {
         if (!XenForo_Model_Alert::userReceivesAlert($viewingUser, 'bdapi_consumer', $authRef['provider'])) {
             // user opted out for this provider
             continue;
         }
         if (!$alwaysCheck && empty($auth['extra_data']['notification_subscription_callback'])) {
             // do not check to save resources
             continue;
         }
         $provider = bdApiConsumer_Option::getProviderByCode($authRef['provider']);
         if (empty($provider)) {
             continue;
         }
         $accessToken = $userExternalModel->bdApiConsumer_getAccessTokenFromAuth($provider, $authRef);
         if (empty($accessToken)) {
             continue;
         }
         $notifications = bdApiConsumer_Helper_Api::getNotifications($provider, $accessToken);
         $alertUser = true;
         if (!empty($notifications['_headerLinkHub'])) {
             if (empty($notifications['subscription_callback'])) {
                 // subscribe to future notifications
                 if (bdApiConsumer_Helper_Api::postSubscription($provider, $accessToken, $notifications['_headerLinkHub'])) {
                     $authRef['extra_data']['notification_subscription_callback'] = 1;
                     $userExternalModel->bdApiConsumer_updateExternalAuthAssociation($provider, $authRef['provider_key'], $authRef['user_id'], $authRef['extra_data']);
                 }
             } else {
                 // subscribed, do not alert user to avoid duplicates
                 $alertUser = false;
             }
         }
         if ($alertUser && !empty($notifications['notifications'])) {
             // server does not support subscription, we will just put all notifications into
             // user alerts then
             foreach ($notifications['notifications'] as $notification) {
                 $this->bdApiConsumer_alertUser($provider, $viewingUser, $notification);
             }
         }
     }
 }
Example #5
0
 /**
  * Post-save handling.
  */
 protected function _postSave()
 {
     $this->_updateContent($this->get('rating'), $this->get('content_type'));
     if ($this->isInsert()) {
         $contentType = $this->get('content_type');
         if ($contentType == 'media') {
             $content = $this->_getMediaModel()->getMediaById($this->get('content_id'), array('join' => XenGallery_Model_Media::FETCH_USER | XenGallery_Model_Media::FETCH_USER_OPTION));
         }
         if ($contentType == 'album') {
             $content = $this->_getAlbumModel()->getAlbumById($this->get('content_id'), array('join' => XenGallery_Model_Album::FETCH_USER | XenGallery_Model_Album::FETCH_USER_OPTION));
         }
         if ($this->getExtraData(self::DATA_PREVENT_ALERTS) !== true) {
             if ($content && XenForo_Model_Alert::userReceivesAlert($content, 'xengallery_rating', 'insert')) {
                 $ratingUser = array('user_id' => $this->get('user_id'), 'username' => $this->get('username'));
                 XenForo_Model_Alert::alert($content['user_id'], $ratingUser['user_id'], $ratingUser['username'], 'xengallery_rating', $this->get('rating_id'), 'insert');
             }
             $this->_getNewsFeedModel()->publish($this->get('user_id'), $this->get('username'), 'xengallery_rating', $this->get('rating_id'), 'insert');
         }
     }
 }
Example #6
0
 public function alertTaggedMembers($content, $contentId, $contentType, $tagged, array $alreadyAlerted = array())
 {
     $userIds = XenForo_Application::arrayColumn($tagged, 'user_id');
     $userIds = array_diff($userIds, $alreadyAlerted);
     $alertedUserIds = array();
     if ($userIds) {
         $userModel = $this->_getUserModel();
         $users = $userModel->getUsersByIds($userIds, array('join' => XenForo_Model_User::FETCH_USER_OPTION | XenForo_Model_User::FETCH_USER_PROFILE | XenForo_Model_User::FETCH_USER_PERMISSIONS));
         foreach ($users as $user) {
             if (isset($alertedUserIds[$user['user_id']]) || $user['user_id'] == $content['user_id'] || $user['user_id'] == $content['user_id']) {
                 continue;
             }
             $xfContentType = $this->_getXfContentType($contentType);
             if (!$userModel->isUserIgnored($user, $content['user_id']) && !$userModel->isUserIgnored($user, $content['user_id']) && XenForo_Model_Alert::userReceivesAlert($user, $xfContentType, 'tagging')) {
                 $alertedUserIds[$user['user_id']] = true;
                 XenForo_Model_Alert::alert($user['user_id'], $content['user_id'], $content['username'], $contentType, $contentId, 'tagging');
             }
         }
     }
     return array_keys($alertedUserIds);
 }
Example #7
0
 /**
  * Send a notification to the users watching the thread.
  *
  * @param array $reply The reply that has been added
  * @param array|null $thread Info about the thread the reply is in; fetched if null
  * @param array List of user ids to NOT alert (but still send email)
  */
 public function sendNotificationToWatchUsersOnReply(array $reply, array $thread = null, array $noAlerts = array())
 {
     if ($reply['message_state'] != 'visible') {
         return;
     }
     $threadModel = $this->_getThreadModel();
     if (!$thread) {
         $thread = $threadModel->getThreadById($reply['thread_id'], array('join' => XenForo_Model_Thread::FETCH_FORUM));
     }
     if (!$thread || $thread['discussion_state'] != 'visible') {
         return;
     }
     $latestPosts = $this->getModelFromCache('XenForo_Model_Post')->getNewestPostsInThreadAfterDate($thread['thread_id'], 0, array('limit' => 2));
     if (!$latestPosts) {
         return;
     }
     // the reply is likely the last post, so get the one before that and only
     // alert again if read since; note these posts are in newest first order,
     // so end() is last
     $previousPost = end($latestPosts);
     $autoReadDate = XenForo_Application::$time - XenForo_Application::get('options')->readMarkingDataLifetime * 86400;
     $users = $this->getUsersWatchingThread($thread['thread_id'], $thread['node_id']);
     foreach ($users as $user) {
         if ($user['user_id'] == $reply['user_id']) {
             continue;
         }
         if ($previousPost['post_date'] < $autoReadDate) {
             // always alert
         } else {
             if ($previousPost['post_date'] > $user['thread_read_date']) {
                 // user hasn't read the thread since the last alert, don't send another one
                 continue;
             }
         }
         $permissions = XenForo_Permission::unserializePermissions($user['node_permission_cache']);
         if (!$threadModel->canViewThreadAndContainer($thread, $thread, $null, $permissions, $user)) {
             continue;
         }
         if ($user['email_subscribe'] && $user['email'] && $user['user_state'] == 'valid') {
             if (!isset($thread['titleCensored'])) {
                 $thread['titleCensored'] = XenForo_Helper_String::censorString($thread['title']);
             }
             $mail = XenForo_Mail::create('watched_thread_reply', array('reply' => $reply, 'thread' => $thread, 'forum' => $thread, 'receiver' => $user), $user['language_id']);
             $mail->enableAllLanguagePreCache();
             $mail->queue($user['email'], $user['username']);
         }
         if (!in_array($user['user_id'], $noAlerts)) {
             $alertType = $reply['attach_count'] ? 'insert_attachment' : 'insert';
             if (XenForo_Model_Alert::userReceivesAlert($user, 'post', $alertType)) {
                 XenForo_Model_Alert::alert($user['user_id'], $reply['user_id'], $reply['username'], 'post', $reply['post_id'], $alertType);
             }
         }
     }
 }
Example #8
0
 /**
  * Sends an alert to members directly quoted in a post
  *
  * @param array $post
  */
 public function alertQuotedMembers(array $post)
 {
     $quotedUsers = array();
     if (preg_match_all('/\\[quote=("|\'|)([^,]+),\\s*post:\\s*(\\d+)\\1\\]/siU', $post['message'], $quotes)) {
         $quotedPosts = $this->getPostsByIds(array_unique($quotes[3]), array('join' => XenForo_Model_Post::FETCH_USER_OPTIONS));
         foreach ($quotedPosts as $quotedPostId => $quotedPost) {
             if (!isset($quotedUsers[$quotedPost['user_id']]) && $quotedPost['user_id'] && $quotedPost['user_id'] != $post['user_id']) {
                 if (XenForo_Model_Alert::userReceivesAlert($quotedPost, 'post', 'quote')) {
                     $quotedUsers[$quotedPost['user_id']] = true;
                     XenForo_Model_Alert::alert($quotedPost['user_id'], $post['user_id'], $post['username'], 'post', $post['post_id'], 'quote');
                 }
             }
         }
     }
     return array_keys($quotedUsers);
 }
Example #9
0
    /**
     * Award the specified user with a specific trophy.
     *
     * @param array $user
     * @param string $username
     * @param array $trophy
     * @param integer|null $awardDate If null, use current time
     */
    public function awardUserTrophy(array $user, $username, array $trophy, $awardDate = null)
    {
        if ($awardDate === null) {
            $awardDate = XenForo_Application::$time;
        }
        $db = $this->_getDb();
        XenForo_Db::beginTransaction($db);
        $result = $db->query('
			INSERT IGNORE INTO xf_user_trophy
				(user_id, trophy_id, award_date)
			VALUES
				(?, ?, ?)
		', array($user['user_id'], $trophy['trophy_id'], $awardDate));
        if ($result->rowCount()) {
            $db->query('
				UPDATE xf_user SET
					trophy_points = trophy_points + ?
				WHERE user_id = ?
			', array($trophy['trophy_points'], $user['user_id']));
            if (XenForo_Model_Alert::userReceivesAlert($user, 'user', 'trophy')) {
                XenForo_Model_Alert::alert($user['user_id'], $user['user_id'], $username, 'user', $user['user_id'], 'trophy', array('trophy_id' => $trophy['trophy_id']));
            }
        }
        XenForo_Db::commit($db);
    }
 public function alertTaggedMembers(array $profilePost, array $profileUser, array $tagged, array $alreadyAlerted = array(), $commentId = 0, array $taggingUser = null)
 {
     $userIds = XenForo_Application::arrayColumn($tagged, 'user_id');
     $userIds = array_diff($userIds, $alreadyAlerted);
     $alertedUserIds = array();
     if (!$taggingUser) {
         $taggingUser = $profilePost;
     }
     if ($userIds) {
         $userModel = $this->_getUserModel();
         $users = $userModel->getUsersByIds($userIds, array('join' => XenForo_Model_User::FETCH_USER_OPTION | XenForo_Model_User::FETCH_USER_PROFILE | XenForo_Model_User::FETCH_USER_PERMISSIONS));
         foreach ($users as $user) {
             if (isset($alertedUserIds[$user['user_id']])) {
                 continue;
             }
             $user['permissions'] = XenForo_Permission::unserializePermissions($user['global_permission_cache']);
             if ($user['user_id'] != $taggingUser['user_id'] && !$userModel->isUserIgnored($user, $profilePost['user_id']) && !$userModel->isUserIgnored($user, $profileUser['user_id']) && XenForo_Model_Alert::userReceivesAlert($user, 'profile_post', 'tag') && $this->canViewProfilePostAndContainer($profilePost, $profileUser, $null, $user)) {
                 $alertedUserIds[$user['user_id']] = true;
                 XenForo_Model_Alert::alert($user['user_id'], $taggingUser['user_id'], $taggingUser['username'], 'profile_post' . ($commentId ? '_comment' : ''), $commentId ? $commentId : $profilePost['profile_post_id'], 'tag');
             }
         }
     }
     return array_keys($alertedUserIds);
 }
 protected function _postSave()
 {
     $this->_updateDeletionLog();
     $this->_updateModerationQueue();
     $this->_submitSpamLog();
     $this->_indexForSearch();
     $profilePostId = $this->get('profile_post_id');
     $commentId = $this->get('profile_post_comment_id');
     if ($this->isUpdate() && $this->isChanged('message_state')) {
         $this->_rebuildProfilePostCommentCounters();
         if ($this->get('message_state') == 'deleted' && $this->getExisting('message_state') == 'visible') {
             $this->getModelFromCache('XenForo_Model_Alert')->deleteAlerts('profile_post_comment', $commentId);
         }
     }
     if ($this->isInsert()) {
         $dw = XenForo_DataWriter::create('XenForo_DataWriter_DiscussionMessage_ProfilePost');
         $dw->setExistingData($profilePostId);
         $dw->insertNewComment($commentId, $this->get('comment_date'));
         $dw->save();
         $profileUser = $this->getExtraData(self::DATA_PROFILE_USER);
         $profilePost = $this->getExtraData(self::DATA_PROFILE_POST);
         $userModel = $this->_getUserModel();
         $alertedUserIds = array();
         if ($profilePost && $profileUser && $profileUser['user_id'] != $this->get('user_id')) {
             // alert profile owner - only if not ignoring either profile post itself or this comment
             if (!$userModel->isUserIgnored($profileUser, $this->get('user_id')) && !$userModel->isUserIgnored($profileUser, $profilePost['user_id']) && XenForo_Model_Alert::userReceivesAlert($profileUser, 'profile_post_comment', 'your_profile')) {
                 XenForo_Model_Alert::alert($profileUser['user_id'], $this->get('user_id'), $this->get('username'), 'profile_post_comment', $commentId, 'your_profile');
                 $alertedUserIds[] = $profileUser['user_id'];
             }
         }
         if ($profilePost && $profilePost['profile_user_id'] != $profilePost['user_id'] && $profilePost['user_id'] != $this->get('user_id')) {
             // alert post owner
             $user = $userModel->getUserById($profilePost['user_id'], array('join' => XenForo_Model_User::FETCH_USER_OPTION | XenForo_Model_User::FETCH_USER_PROFILE));
             if ($user && !$userModel->isUserIgnored($user, $this->get('user_id')) && XenForo_Model_Alert::userReceivesAlert($user, 'profile_post_comment', 'your_post')) {
                 XenForo_Model_Alert::alert($user['user_id'], $this->get('user_id'), $this->get('username'), 'profile_post_comment', $commentId, 'your_post');
                 $alertedUserIds[] = $user['user_id'];
             }
         }
         $maxTagged = $this->getOption(self::OPTION_MAX_TAGGED_USERS);
         if ($maxTagged && $this->_taggedUsers && $profilePost && $profileUser) {
             if ($maxTagged > 0) {
                 $alertTagged = array_slice($this->_taggedUsers, 0, $maxTagged, true);
             } else {
                 $alertTagged = $this->_taggedUsers;
             }
             $alertedUserIds = array_merge($alertedUserIds, $this->_getProfilePostModel()->alertTaggedMembers($profilePost, $profileUser, $alertTagged, $alertedUserIds, $commentId, array('user_id' => $this->get('user_id'), 'username' => $this->get('username'))));
         }
         $otherCommenterIds = $this->_getProfilePostModel()->getProfilePostCommentUserIds($profilePostId, 'visible');
         $otherCommenters = $userModel->getUsersByIds($otherCommenterIds, array('join' => XenForo_Model_User::FETCH_USER_OPTION | XenForo_Model_User::FETCH_USER_PROFILE));
         $profileUserId = empty($profileUser) ? 0 : $profileUser['user_id'];
         $profilePostUserId = empty($profilePost) ? 0 : $profilePost['user_id'];
         foreach ($otherCommenters as $otherCommenter) {
             if (in_array($otherCommenter['user_id'], $alertedUserIds)) {
                 continue;
             }
             switch ($otherCommenter['user_id']) {
                 case $profileUserId:
                 case $profilePostUserId:
                 case $this->get('user_id'):
                 case 0:
                     break;
                 default:
                     if (!$userModel->isUserIgnored($otherCommenter, $this->get('user_id')) && XenForo_Model_Alert::userReceivesAlert($otherCommenter, 'profile_post_comment', 'other_commenter')) {
                         XenForo_Model_Alert::alert($otherCommenter['user_id'], $this->get('user_id'), $this->get('username'), 'profile_post_comment', $commentId, 'other_commenter');
                         $alertedUserIds[] = $otherCommenter['user_id'];
                     }
             }
         }
         if ($this->getOption(self::OPTION_SET_IP_ADDRESS) && !$this->get('ip_id')) {
             $this->_updateIpData();
         }
         $this->_getNewsFeedModel()->publish($this->get('user_id'), $this->get('username'), 'profile_post_comment', $this->get('profile_post_comment_id'), 'insert');
     }
 }
Example #12
0
 public function alertTaggedMembers(array $post, array $thread, array $forum, array $tagged, array $alreadyAlerted)
 {
     $userIds = XenForo_Application::arrayColumn($tagged, 'user_id');
     $userIds = array_diff($userIds, $alreadyAlerted);
     $alertedUserIds = array();
     if ($userIds) {
         $userModel = $this->_getUserModel();
         $users = $userModel->getUsersByIds($userIds, array('join' => XenForo_Model_User::FETCH_USER_OPTION | XenForo_Model_User::FETCH_USER_PROFILE, 'nodeIdPermissions' => $thread['node_id']));
         foreach ($users as $user) {
             if (!isset($alertedUserIds[$user['user_id']]) && $user['user_id'] != $post['user_id']) {
                 $permissions = XenForo_Permission::unserializePermissions($user['node_permission_cache']);
                 if (!$userModel->isUserIgnored($user, $post['user_id']) && XenForo_Model_Alert::userReceivesAlert($user, 'post', 'tag') && $this->canViewPostAndContainer($post, $thread, $forum, $null, $permissions, $user)) {
                     $alertedUserIds[$user['user_id']] = true;
                     XenForo_Model_Alert::alert($user['user_id'], $post['user_id'], $post['username'], 'post', $post['post_id'], 'tag');
                 }
             }
         }
     }
     return array_keys($alertedUserIds);
 }
Example #13
0
    public function ratePost(array $post, $user_id, $rating, $oldRating = false)
    {
        $db = $this->_getDb();
        $options = XenForo_Application::get('options');
        /** @var $userModel XenForo_Model_User */
        $userModel = $this->getModelFromCache('XenForo_Model_User');
        $postUser = $userModel->getUserById($post['user_id'], array('join' => XenForo_Model_User::FETCH_USER_OPTION | XenForo_Model_User::FETCH_USER_PROFILE));
        $user = $userModel->getUserById($user_id);
        /** @var $likeModel XenForo_Model_Like */
        $likeModel = $this->getModelFromCache('XenForo_Model_Like');
        // Race conditions everywhere
        if (!$this->getLock("postrating_" . $user['user_id'] . "_" . $post['post_id'], 1)) {
            return false;
        }
        // Realistically better for the user to treat this sanely than throw an error
        $existingLike = $likeModel->getContentLikeByLikeUser('post', $post['post_id'], $user_id);
        if ($existingLike) {
            $likeModel->unlikeContent($existingLike);
        }
        $oldRating = $this->getRatingByUserOnPost($user['user_id'], $post['post_id'], false);
        if ($oldRating) {
            if (!$existingLike) {
                $db->query('
					insert into dark_postrating_count set user_id = ?, rating = ?
					on duplicate key update count_given = IF(count_given > 0, count_given - 1, 0)
				', array($user_id, $oldRating));
            }
            if ($postUser) {
                if (!$existingLike) {
                    $db->query('
						insert into dark_postrating_count set user_id = ?, rating = ?
						on duplicate key update count_received = IF(count_received > 0, count_received - 1, 0)
					', array($postUser['user_id'], $oldRating));
                }
                // If it's a like just use xenforo's system
                if ($oldRating != $options->dark_postrating_like_id) {
                    $this->_getAlertModel()->deleteAlerts('postrating', $post['post_id'], $user_id, 'rate');
                    $this->_getNewsFeedModel()->delete('postrating', $post['post_id'], $user_id, 'rate');
                }
            }
        }
        if ($rating == 'del') {
            $db->query('
				delete from dark_postrating where post_id = ? and user_id = ?
			', array($post['post_id'], $user_id));
        } else {
            if ($rating != $options->dark_postrating_like_id) {
                $db->query('
					insert into dark_postrating set post_id = ?, user_id = ?, rating = ?, rated_user_id = ?, date = UNIX_TIMESTAMP() 
					on duplicate key update rating = ?, date = UNIX_TIMESTAMP() 
				', array($post['post_id'], $user_id, $rating, $postUser ? $postUser['user_id'] : null, $rating));
                $db->query('
					insert into dark_postrating_count set user_id = ?, rating = ?, count_given = 1
					on duplicate key update count_given = count_given + 1 
				', array($user_id, $rating));
            }
            if ($rating == $options->dark_postrating_like_id) {
                // If it's a like just use xenforo's system
                $likeModel->likeContent('post', $post['post_id'], $post['user_id']);
            } elseif ($postUser) {
                $db->query('
					insert into dark_postrating_count set user_id = ?, rating = ?, count_received = 1
					on duplicate key update count_received = count_received + 1 
				', array($postUser['user_id'], $rating));
                if ($options->dark_postrating_alerts_integration) {
                    if ((!method_exists($userModel, 'isUserIgnored') || !$userModel->isUserIgnored($postUser, $user_id)) && XenForo_Model_Alert::userReceivesAlert($postUser, 'post', 'like') && ($options->dark_postrating_alert_spam || $this->countUnreadRatingAlertsForPost($post['post_id']) == 0)) {
                        XenForo_Model_Alert::alert($postUser['user_id'], $user_id, $user['username'], 'postrating', $post['post_id'], 'rate');
                    }
                }
                if ($options->dark_postrating_news_integration && !$this->getRatingNewsFeedEntryByUserOnPost($post['post_id'], $user['user_id'])) {
                    $this->_getNewsFeedModel()->publish($user_id, $user['username'], 'postrating', $post['post_id'], 'rate');
                }
            }
        }
        return true;
    }
Example #14
0
 protected function _sendAlertToUsersWatchedOnPost(array $userAlerted, $action, array $alerted = array())
 {
     if (!XenForo_Model_Alert::userReceivesAlert($userAlerted, $this->getContentType(), $action) || XenForo_Model::create('XenForo_Model_User')->isUserIgnored($userAlerted, $this->get('user_id'))) {
         return;
         // not sure about this.
     }
     if ($userAlerted['alert'] !== null and empty($userAlerted['alert'])) {
         return;
         // user don't receive any alerts.
     }
     if (!isset($alerted[$userAlerted['user_id']])) {
         XenForo_Model_Alert::alert($userAlerted['user_id'], $this->get('user_id'), $this->get('username'), $this->getContentType(), $this->getCommentId(), $action);
     }
 }
Example #15
0
 /**
  * Post-save handling.
  */
 protected function _postSave()
 {
     $this->_updateResource($this->get('rating'), null);
     if ($this->isChanged('rating_state')) {
         $this->_updateDeletionLog();
     }
     if ($this->isInsert() && $this->get('is_review')) {
         $resource = $this->_getResourceModel()->getResourceById($this->get('resource_id'), array('join' => XenResource_Model_Resource::FETCH_USER | XenResource_Model_Resource::FETCH_USER_OPTION));
         if ($resource && XenForo_Model_Alert::userReceivesAlert($resource, 'resource_rating', 'review')) {
             $user = $this->getModelFromCache('XenForo_Model_User')->getUserById($this->get('user_id'));
             if ($user) {
                 XenForo_Model_Alert::alert($resource['user_id'], $user['user_id'], $user['username'], 'resource_rating', $this->get('resource_rating_id'), 'review');
             }
         }
     }
     if ($this->isUpdate() && $this->isChanged('author_response') && $this->get('author_response')) {
         $resource = $this->_getResourceModel()->getResourceById($this->get('resource_id'), array('join' => XenResource_Model_Resource::FETCH_USER | XenResource_Model_Resource::FETCH_USER_OPTION));
         $user = $this->getModelFromCache('XenForo_Model_User')->getUserById($this->get('user_id'));
         if ($resource && $user && XenForo_Model_Alert::userReceivesAlert($user, 'resource_rating', 'reply')) {
             XenForo_Model_Alert::alert($user['user_id'], $resource['user_id'], $resource['username'], 'resource_rating', $this->get('resource_rating_id'), 'reply');
         }
     }
 }
Example #16
0
 public function updatePage($input, $bypass = false)
 {
     $dw = XenForo_DataWriter::create('EWRcarta_DataWriter_Pages');
     if (!empty($input['page_id']) && ($page = $this->getPageById($input['page_id']))) {
         $dw->setExistingData($input);
     }
     if ($input['page_type'] == 'bbcode') {
         $input['page_content'] = XenForo_Helper_String::autoLinkBbCode($input['page_content']);
     }
     $dw->bulkSet(array('page_name' => $input['page_name'], 'page_slug' => $input['page_slug'], 'page_type' => $input['page_type'], 'page_content' => $input['page_content'], 'page_parent' => $input['page_parent']));
     if (isset($input['page_index'])) {
         $dw->bulkSet(array('page_index' => $input['page_index'], 'page_protect' => $input['page_protect'], 'page_sidebar' => $input['page_sidebar'], 'page_sublist' => $input['page_sublist']));
     }
     if (isset($input['administrators'])) {
         if ($input['administrators'] !== '') {
             $usernames = explode(',', $input['administrators']);
             $users = $this->getModelFromCache('XenForo_Model_User')->getUsersByNames($usernames);
             $userIDs = array();
             foreach ($users as $user) {
                 $userIDs[] = $user['user_id'];
             }
             $input['page_admins'] = implode(',', $userIDs);
         } else {
             $input['page_admins'] = '';
         }
         if ($input['usernames'] !== '') {
             $usernames = explode(',', $input['usernames']);
             $users = $this->getModelFromCache('XenForo_Model_User')->getUsersByNames($usernames);
             $userIDs = array();
             foreach ($users as $user) {
                 $userIDs[] = $user['user_id'];
             }
             $input['page_users'] = implode(',', $userIDs);
         } else {
             $input['page_users'] = '';
         }
         $dw->bulkSet(array('page_admins' => $input['page_admins'], 'page_groups' => $input['page_groups'], 'page_users' => $input['page_users']));
     }
     $dw->setExtraData(XenForo_DataWriter_DiscussionMessage::DATA_ATTACHMENT_HASH, $input['attachment_hash']);
     $dw->save();
     $input['page_id'] = $dw->get('page_id');
     $input['page_slug'] = $dw->get('page_slug');
     $input['page_date'] = $dw->get('page_date');
     $input['thread_id'] = $dw->get('thread_id');
     if ($input['thread_id'] && ($dw->isChanged('page_title') || $dw->isChanged('page_slug'))) {
         $this->getModelFromCache('EWRcarta_Model_Threads')->updateThread($input);
     }
     if ($dw->isChanged('page_content')) {
         $visitor = XenForo_Visitor::getInstance();
         $history = $this->getModelFromCache('EWRcarta_Model_History')->getHistoryByPage($input);
         if ($bypass || !($history['user_id'] == $visitor['user_id'] && $input['page_date'] < $history['history_date'] + 1800)) {
             $this->getModelFromCache('EWRcarta_Model_History')->updateHistory($input);
             $this->getModelFromCache('XenForo_Model_NewsFeed')->publish($visitor['user_id'], $visitor['user_id'] ? $visitor['username'] : $_SERVER['REMOTE_ADDR'], 'wiki', $input['page_id'], 'update');
             $users = $this->getModelFromCache('EWRcarta_Model_PageWatch')->getUsersWatchingPage($input['page_id']);
             foreach ($users as $user) {
                 if ($user['user_id'] == $visitor['user_id']) {
                     continue;
                 }
                 if ($user['email_subscribe'] && $user['email'] && $user['user_state'] == 'valid') {
                     $mail = XenForo_Mail::create('watched_wiki_update', array('reply' => $visitor, 'page' => $page, 'receiver' => $user), $user['language_id']);
                     $mail->enableAllLanguagePreCache();
                     $mail->queue($user['email'], $user['username']);
                 }
                 if (XenForo_Model_Alert::userReceivesAlert($user, 'wiki', 'update')) {
                     XenForo_Model_Alert::alert($user['user_id'], $visitor['user_id'], $visitor['user_id'] ? $visitor['username'] : $_SERVER['REMOTE_ADDR'], 'wiki', $input['page_id'], 'update');
                 }
             }
         }
     }
     return $input;
 }
Example #17
0
 protected function _postSave()
 {
     $content = $this->_getMediaModel()->getMediaById($this->get('media_id'), array('join' => XenGallery_Model_Media::FETCH_USER | XenGallery_Model_Media::FETCH_USER_OPTION | XenGallery_Model_Media::FETCH_ALBUM));
     $visitor = XenForo_Visitor::getInstance();
     $viewingUser = XenForo_Model::create('XenForo_Model_User')->getUserById($this->get('user_id'), array('join' => XenForo_Model_User::FETCH_USER_FULL | XenForo_Model_User::FETCH_USER_PERMISSIONS));
     $viewingUser['permissions'] = @unserialize($viewingUser['global_permission_cache']);
     $canViewMedia = true;
     if ($content['album_id']) {
         $albumModel = $this->_getAlbumModel();
         $album = $albumModel->getAlbumById($content['album_id']);
         $album = $albumModel->prepareAlbumWithPermissions($album);
         if (!$albumModel->canViewAlbum($album, $null, $viewingUser)) {
             $canViewMedia = false;
         }
     } elseif ($content['category_id']) {
         $categoryModel = $this->_getCategoryModel();
         $category = $categoryModel->getCategoryById($content['category_id']);
         if (!$categoryModel->canViewCategory($category, $null, $viewingUser)) {
             $canViewMedia = false;
         }
     }
     if ($this->isInsert()) {
         if ($this->get('tag_state') == 'pending' && $canViewMedia) {
             XenForo_Model_Alert::alert($this->get('user_id'), $this->get('tag_by_user_id'), $this->get('tag_by_username'), 'xengallery_media', $this->get('media_id'), 'tag_approve', array('tag_id' => $this->get('tag_id')));
             // Just to suppress the second alert.
             $canViewMedia = false;
         }
         if ($content && XenForo_Model_Alert::userReceivesAlert($content, 'xengallery_media', 'tag') && $canViewMedia) {
             if ($visitor->user_id != $this->get('user_id')) {
                 XenForo_Model_Alert::alert($this->get('user_id'), $this->get('tag_by_user_id'), $this->get('tag_by_username'), 'xengallery_media', $this->get('media_id'), 'tag', array('tag_id' => $this->get('tag_id')));
             }
         }
     }
     if ($this->isUpdate()) {
         if ($this->get('tag_state') == 'approved') {
             if ($content && XenForo_Model_Alert::userReceivesAlert($content, 'xengallery_media', 'tag') && $canViewMedia) {
                 if ($visitor->user_id != $this->get('user_id')) {
                     XenForo_Model_Alert::alert($this->get('user_id'), $this->get('tag_by_user_id'), $this->get('tag_by_username'), 'xengallery_media', $this->get('media_id'), 'tag', array('tag_id' => $this->get('tag_id')));
                 }
             }
         }
     }
 }
Example #18
0
 protected function _postSave()
 {
     if ($this->isInsert()) {
         $contentId = $this->get('content_id');
         $contentType = $this->get('content_type');
         $userId = XenForo_Visitor::getUserId();
         $draftKey = $contentType . '-' . $contentId;
         $draftModel = $this->_getDraftModel();
         $draft = $draftModel->getDraftByUserKey($draftKey, $userId);
         if ($draft) {
             $draftModel->deleteDraft($draftKey, array());
         }
         if ($contentType == 'media') {
             $mediaWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Media');
             $mediaWriter->setExistingData($contentId);
             $commentCount = $mediaWriter->getExisting('comment_count');
             $mediaWriter->set('comment_count', $commentCount + 1);
             $mediaWriter->set('last_comment_date', XenForo_Application::$time);
             $mediaWriter->save();
             $content = $this->_getMediaModel()->getMediaById($contentId, array('join' => XenGallery_Model_Media::FETCH_USER | XenGallery_Model_Media::FETCH_USER_OPTION | XenGallery_Model_Media::FETCH_ALBUM));
             $this->_getMediaModel()->markMediaViewed($content);
         } else {
             $albumWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Album');
             $albumWriter->setExistingData($contentId);
             $commentCount = $albumWriter->getExisting('album_comment_count');
             $newValue = $commentCount + 1;
             if (intval($newValue) < 1) {
                 $newValue = 0;
             }
             $albumWriter->set('album_comment_count', $newValue);
             $albumWriter->set('album_last_comment_date', XenForo_Application::$time);
             $albumWriter->save();
             $content = $this->_getAlbumModel()->getAlbumById($contentId, array('join' => XenGallery_Model_Album::FETCH_USER | XenGallery_Model_Album::FETCH_USER_OPTION));
         }
         $commentUser = array('user_id' => $this->get('user_id'), 'username' => $this->get('username'));
         $commentId = $this->get('comment_id');
         $maxTagged = $this->getOption(self::OPTION_MAX_TAGGED_USERS);
         if ($maxTagged && $this->_taggedUsers) {
             if ($maxTagged > 0) {
                 $alertTagged = array_slice($this->_taggedUsers, 0, $maxTagged, true);
             } else {
                 $alertTagged = $this->_taggedUsers;
             }
             $this->_alertedUsers = $this->_getCommentModel()->alertTaggedMembers($this->_getCommentModel()->getCommentById($commentId, array('join' => XenGallery_Model_Comment::FETCH_MEDIA | XenGallery_Model_Comment::FETCH_ALBUM)), $alertTagged);
         }
         if ($content && XenForo_Model_Alert::userReceivesAlert($content, 'xengallery_comment', 'insert') && $content['user_id'] != $commentUser['user_id']) {
             if (!in_array($content['user_id'], $this->_alertedUsers)) {
                 XenForo_Model_Alert::alert($content['user_id'], $commentUser['user_id'], $commentUser['username'], 'xengallery_comment', $commentId, 'insert');
             }
             $this->_alertedUsers[] = $content['user_id'];
         }
         $this->_getNewsFeedModel()->publish($commentUser['user_id'], $commentUser['username'], 'xengallery_comment', $commentId, 'insert');
         $ipId = XenForo_Model_Ip::log($this->get('user_id'), 'xengallery_comment', $this->get('comment_id'), 'insert');
         $this->_db->update('xengallery_comment', array('ip_id' => $ipId), 'comment_id = ' . $this->get('comment_id'));
     }
     if ($this->isChanged('comment_state') && $this->getExisting('comment_state') == 'deleted' || $this->getExisting('comment_state') == 'moderated') {
         $this->updateCommentCount();
         $this->_updateLastCommentDate();
     }
     if ($this->isUpdate() && $this->isChanged('comment_state')) {
         $this->_updateLastCommentDate();
         // $this->_updateMessagePositionList();
     }
     if ($this->isChanged('comment_state') && $this->getExisting('comment_state') == 'visible') {
         $this->updateCommentCount(false);
         $this->_updateLastCommentDate();
         $this->getModelFromCache('XenForo_Model_Alert')->deleteAlerts('xengallery_comment', $this->get('comment_id'));
     }
     $this->_updateModerationQueue($this->getMergedData());
     $this->_updateDeletionLog(true);
 }
Example #19
0
 /**
  * Send a notification to the users watching the thread.
  *
  * @param array $reply The reply that has been added
  * @param array|null $thread Info about the thread the reply is in; fetched if null
  * @param array $noAlerts List of user ids to NOT alert (but still send email)
  *
  * @return array Empty or keys: alerted: user ids alerted, emailed: user ids emailed
  */
 public function sendNotificationToWatchUsersOnReply(array $reply, array $thread = null, array $noAlerts = array())
 {
     if ($reply['message_state'] != 'visible') {
         return array();
     }
     $threadModel = $this->_getThreadModel();
     /* @var $userModel XenForo_Model_User */
     $userModel = $this->getModelFromCache('XenForo_Model_User');
     if (!$thread) {
         $thread = $threadModel->getThreadById($reply['thread_id'], array('join' => XenForo_Model_Thread::FETCH_FORUM));
     }
     if (!$thread || $thread['discussion_state'] != 'visible') {
         return array();
     }
     $autoReadDate = XenForo_Application::$time - XenForo_Application::get('options')->readMarkingDataLifetime * 86400;
     // get last 15 posts that could be relevant - need to go back in time for ignored reply handling
     $latestPosts = $this->getModelFromCache('XenForo_Model_Post')->getNewestPostsInThreadAfterDate($thread['thread_id'], $autoReadDate, array('limit' => 15));
     if (!$latestPosts) {
         return array();
     }
     // the reply is likely the last post, so get the one before that and only
     // alert again if read since; note these posts are in newest first order
     list($key) = each($latestPosts);
     unset($latestPosts[$key]);
     $defaultPreviousPost = reset($latestPosts);
     if (XenForo_Application::get('options')->emailWatchedThreadIncludeMessage) {
         $parseBbCode = true;
         $emailTemplate = 'watched_thread_reply_messagetext';
     } else {
         $parseBbCode = false;
         $emailTemplate = 'watched_thread_reply';
     }
     // fetch a full user record if we don't have one already
     if (!isset($reply['avatar_width']) || !isset($reply['custom_title'])) {
         $replyUser = $this->getModelFromCache('XenForo_Model_User')->getUserById($reply['user_id']);
         if ($replyUser) {
             $reply = array_merge($replyUser, $reply);
         } else {
             $reply['avatar_width'] = 0;
             $reply['custom_title'] = '';
         }
     }
     $alerted = array();
     $emailed = array();
     $noAlertKeys = array_fill_keys($noAlerts, true);
     $users = $this->getUsersWatchingThread($thread['thread_id'], $thread['node_id']);
     foreach ($users as $user) {
         if ($user['user_id'] == $reply['user_id']) {
             continue;
         }
         if ($userModel->isUserIgnored($user, $reply['user_id'])) {
             continue;
         }
         if (!$defaultPreviousPost || !$userModel->isUserIgnored($user, $defaultPreviousPost['user_id'])) {
             $previousPost = $defaultPreviousPost;
         } else {
             // need to recalculate the last post that they would've seen
             $previousPost = false;
             foreach ($latestPosts as $latestPost) {
                 if (!$userModel->isUserIgnored($user, $latestPost['user_id'])) {
                     // this is the most recent post they didn't ignore
                     $previousPost = $latestPost;
                     break;
                 }
             }
         }
         if (!$previousPost || $previousPost['post_date'] < $autoReadDate) {
             // always alert
         } else {
             if ($previousPost['post_date'] > $user['thread_read_date']) {
                 // user hasn't read the thread since the last alert, don't send another one
                 continue;
             }
         }
         $permissions = XenForo_Permission::unserializePermissions($user['node_permission_cache']);
         if (!$threadModel->canViewThreadAndContainer($thread, $thread, $null, $permissions, $user)) {
             continue;
         }
         if (isset(self::$_preventDoubleNotify[$thread['thread_id']][$user['user_id']])) {
             continue;
         }
         self::$_preventDoubleNotify[$thread['thread_id']][$user['user_id']] = true;
         if ($user['email_subscribe'] && $user['email'] && $user['user_state'] == 'valid') {
             if (!isset($reply['messageText']) && $parseBbCode) {
                 $bbCodeParserText = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('Text'));
                 $reply['messageText'] = new XenForo_BbCode_TextWrapper($reply['message'], $bbCodeParserText);
                 $bbCodeParserHtml = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('HtmlEmail'));
                 $reply['messageHtml'] = new XenForo_BbCode_TextWrapper($reply['message'], $bbCodeParserHtml);
             }
             if (!isset($thread['titleCensored'])) {
                 $thread['titleCensored'] = XenForo_Helper_String::censorString($thread['title']);
             }
             $user['email_confirm_key'] = $userModel->getUserEmailConfirmKey($user);
             $mail = XenForo_Mail::create($emailTemplate, array('reply' => $reply, 'thread' => $thread, 'forum' => $thread, 'receiver' => $user), $user['language_id']);
             $mail->enableAllLanguagePreCache();
             $mail->queue($user['email'], $user['username']);
             $emailed[] = $user['user_id'];
         }
         if (!isset($noAlertKeys[$user['user_id']])) {
             $alertType = $reply['attach_count'] ? 'insert_attachment' : 'insert';
             if (XenForo_Model_Alert::userReceivesAlert($user, 'post', $alertType)) {
                 XenForo_Model_Alert::alert($user['user_id'], $reply['user_id'], $reply['username'], 'post', $reply['post_id'], $alertType);
                 $alerted[] = $user['user_id'];
             }
         }
     }
     return array('emailed' => $emailed, 'alerted' => $alerted);
 }
Example #20
0
 protected function _getTaggableUsers($usernames, $contentType, $contentId, $overwrite = false, $viewingUser = null)
 {
     $this->standardizeViewingUserReference($viewingUser);
     if (!is_array($usernames)) {
         $usernames = explode(',', $usernames);
         $usernames = array_filter($usernames);
     }
     $tagUsers = $alertUsers = $directUsers = array();
     if (!empty($usernames)) {
         $userModel = $this->_getUserModel();
         $users = $userModel->getUsersByNames($usernames, array('join' => XenForo_Model_User::FETCH_USER_PRIVACY | XenForo_Model_User::FETCH_USER_OPTION, 'followingUserId' => $viewingUser['user_id']));
         $userKeys = array('user_id', 'username');
         $taggedUsers = array();
         if ($overwrite === false) {
             $taggedUsers = $this->getTagsByContentId($contentType, $contentId);
         }
         $excludeArray = array();
         if ($taggedUsers) {
             foreach ($taggedUsers as $tagUser) {
                 $excludeArray[] = $tagUser['user_id'];
             }
         }
         $xfContentType = '';
         switch ($contentType) {
             case sonnb_XenGallery_Model_Album::$contentType:
                 $xfContentType = sonnb_XenGallery_Model_Album::$xfContentType;
                 break;
             case sonnb_XenGallery_Model_Photo::$contentType:
                 $xfContentType = sonnb_XenGallery_Model_Photo::$xfContentType;
                 break;
         }
         foreach ($users as $key => $user) {
             if (in_array($key, $excludeArray)) {
                 continue;
             }
             $user = $userModel->prepareUser($user);
             if ($this->canTagUser($user, $errorPhraseKey, $viewingUser)) {
                 $tagUsers[$key] = XenForo_Application::arrayFilterKeys($user, $userKeys);
                 if ($this->canDirectTagging($user, $viewingUser)) {
                     $directUsers[$key] = $user;
                 }
             }
             if ($viewingUser['user_id'] != $user['user_id'] && !$userModel->isUserIgnored($user, $viewingUser['user_id']) && XenForo_Model_Alert::userReceivesAlert($user, $xfContentType, 'tag')) {
                 $alertUsers[$key] = $user;
             }
         }
     }
     return array($tagUsers, $alertUsers, $directUsers);
 }
Example #21
0
 protected function _handleUserNotificationPings(array $provider, array &$pings)
 {
     $providerKeys = array();
     foreach ($pings as &$pingRef) {
         $providerKeys[] = $pingRef['topic_id'];
     }
     $auths = $this->getModelFromCache('XenForo_Model_UserExternal')->bdApiConsumer_getExternalAuthAssociationsForProviderUser($provider, $providerKeys);
     $userIds = array();
     foreach ($auths as &$authRef) {
         $provider = bdApiConsumer_Option::getProviderByCode($authRef['provider']);
         if (empty($provider)) {
             continue;
         }
         $authRef['_provider'] = $provider;
         $userIds[] = $authRef['user_id'];
     }
     $users = $this->getModelFromCache('XenForo_Model_User')->getUsersByIds($userIds, array('join' => XenForo_Model_User::FETCH_USER_OPTION));
     foreach ($pings as &$pingRef) {
         $auth = null;
         foreach ($auths as $_auth) {
             if ($_auth['provider_key'] == $pingRef['topic_id']) {
                 $auth = $_auth;
             }
         }
         if (empty($auth)) {
             continue;
         }
         $user = null;
         if (!isset($users[$auth['user_id']])) {
             continue;
         }
         $user = $users[$auth['user_id']];
         if ($pingRef['action'] == 'insert' and !empty($pingRef['object_data']['notification_id'])) {
             if (XenForo_Model_Alert::userReceivesAlert($user, 'bdapi_consumer', $auth['provider'])) {
                 $this->getModelFromCache('XenForo_Model_Alert')->bdApiConsumer_alertUser($auth['_provider'], $user, $pingRef['object_data']);
                 $pingRef['result'] = 'inserted alert';
             } else {
                 $pingRef['result'] = 'user opted out';
             }
         } elseif ($pingRef['action'] = 'read') {
             $this->getModelFromCache('XenForo_Model_Alert')->bdApiConsumer_markAlertsRead($auth['_provider'], $user);
             $pingRef['result'] = 'marked as read';
         }
     }
 }
Example #22
0
 /**
  * Sends an alert to the profile owner
  *
  * Note: ensure that you $dw->setExtraData(self::PROFILE_USER, $profileUser) to save a query
  *
  * @return array List of user IDs alerted
  */
 protected function _alertUser()
 {
     if ($this->get('profile_user_id') == $this->get('user_id')) {
         return array();
     }
     $userModel = $this->_getUserModel();
     $alerted = array();
     if (!($profileUser = $this->getExtraData(self::DATA_PROFILE_USER))) {
         $profileUser = $userModel->getUserById($this->get('profile_user_id'), array('join' => XenForo_Model_User::FETCH_USER_FULL));
     }
     if (!$userModel->isUserIgnored($profileUser, $this->get('user_id')) && XenForo_Model_Alert::userReceivesAlert($profileUser, $this->getContentType(), 'insert')) {
         XenForo_Model_Alert::alert($this->get('profile_user_id'), $this->get('user_id'), $this->get('username'), $this->getContentType(), $this->get('profile_post_id'), 'insert');
         $alerted[] = $this->get('profile_user_id');
     }
     return $alerted;
 }
Example #23
0
    /**
     * Inserts a new like for a piece of content.
     *
     * @param string $contentType
     * @param integer $contentId
     * @param integer $contentUserId User that owns/created the content
     * @param integer|null $likeUserId User liking content; defaults to visitor
     * @param integer|null $likeDate Timestamp of liking; defaults to now.
     *
     * @return array|false List of latest like users or false
     */
    public function likeContent($contentType, $contentId, $contentUserId, $likeUserId = null, $likeDate = null)
    {
        $visitor = XenForo_Visitor::getInstance();
        if ($likeUserId === null) {
            $likeUserId = $visitor['user_id'];
        }
        if (!$likeUserId) {
            return false;
        }
        if ($likeUserId != $visitor['user_id']) {
            $user = $this->getModelFromCache('XenForo_Model_User')->getUserById($likeUserId);
            if (!$user) {
                return false;
            }
            $likeUsername = $user['username'];
        } else {
            $likeUsername = $visitor['username'];
        }
        if ($likeDate === null) {
            $likeDate = XenForo_Application::$time;
        }
        $likeHandler = $this->getLikeHandler($contentType);
        if (!$likeHandler) {
            return false;
        }
        $db = $this->_getDb();
        XenForo_Db::beginTransaction($db);
        $result = $db->query('
			INSERT IGNORE INTO xf_liked_content
				(content_type, content_id, content_user_id, like_user_id, like_date)
			VALUES
				(?, ?, ?, ?, ?)
		', array($contentType, $contentId, $contentUserId, $likeUserId, $likeDate));
        if (!$result->rowCount()) {
            XenForo_Db::commit($db);
            return false;
        }
        if ($contentUserId) {
            $contentUser = $this->getModelFromCache('XenForo_Model_User')->getUserById($contentUserId, array('join' => XenForo_Model_User::FETCH_USER_OPTION));
            if ($contentUser) {
                $db->query('
					UPDATE xf_user
					SET like_count = like_count + 1
					WHERE user_id = ?
				', $contentUserId);
                if (XenForo_Model_Alert::userReceivesAlert($contentUser, $contentType, 'like')) {
                    XenForo_Model_Alert::alert($contentUserId, $likeUserId, $likeUsername, $contentType, $contentId, 'like');
                }
            }
        }
        // publish to news feed
        $this->getModelFromCache('XenForo_Model_NewsFeed')->publish($likeUserId, $likeUsername, $contentType, $contentId, 'like');
        $latestLikeUsers = $this->getLatestContentLikeUsers($contentType, $contentId);
        $likeHandler->incrementLikeCounter($contentId, $latestLikeUsers);
        XenForo_Db::commit($db);
        return $latestLikeUsers;
    }
Example #24
0
 public function actionSaveFeedback()
 {
     $this->_assertCanLeaveFeedback();
     $this->_assertPostOnly();
     $input = $this->_input->filter(array('from_user_id' => XenForo_Input::UINT, 'to_user_id' => XenForo_Input::UINT, 'type' => XenForo_Input::STRING, 'thread_id' => XenForo_Input::UINT, 'rating' => XenForo_Input::INT, 'feedback' => XenForo_Input::STRING));
     $visitor = XenForo_Visitor::getInstance();
     if ($visitor['user_id'] == $input['to_user_id']) {
         throw $this->responseException($this->responseNoPermission());
     }
     $userModel = $this->_getUserModel();
     $toUser = $userModel->getUserById($input['to_user_id'], array('join' => XenForo_Model_User::FETCH_USER_PERMISSIONS));
     $this->_assertCanReceiveFeedback($toUser);
     $xenOptions = XenForo_Application::getOptions();
     $dw = XenForo_DataWriter::create('NixFifty_XenTrader_DataWriter_Feedback');
     if ($xenOptions->nfxtStrictThreadSelection && !$input['thread_id']) {
         $dw->error(new XenForo_Phrase('nfxt_please_select_a_thread_associate_feedback'), 'thread_id');
     }
     if ($input['thread_id']) {
         $thread = $this->getModelFromCache('XenForo_Model_Thread')->getThreadById($input['thread_id'], array('join' => XenForo_Model_Thread::FETCH_FORUM));
         if (!$thread || !in_array($thread['node_id'], $xenOptions->nfxtFeedbackForums)) {
             $dw->error(new XenForo_Phrase('xentrader_selected_thread_invalid_bad_error'), 'thread_id');
         }
         $posts = $this->getModelFromCache('XenForo_Model_Post')->getPostsInThread($input['thread_id'], array('join' => XenForo_Model_Thread::FETCH_USER | XenForo_Model_Thread::FETCH_FORUM));
         $notFound = false;
         foreach ($posts as $post) {
             if ($toUser['user_id'] == $post['user_id']) {
                 $notFound = false;
                 break;
             }
         }
         if ($notFound) {
             $dw->error(new XenForo_Phrase('xentrader_selected_thread_invalid_bad_error'), 'thread_id');
         }
         $input['thread_title'] = $thread['title'];
     }
     switch ($input['type']) {
         case 'buyer':
             $input['type'] = 'sell';
             break;
         case 'seller':
             $input['type'] = 'buy';
             break;
         case 'trader':
             $input['type'] = 'trade';
             break;
         default:
             $dw->error('Please fill out your role.', 'type');
             // TODO: phrase...
     }
     $fromUser = $userModel->getUserById($input['from_user_id']);
     $dw->set('from_username', $fromUser['username']);
     $dw->set('to_username', $toUser['username']);
     $dw->bulkSet($input);
     if ($input['rating'] == '404') {
         $dw->error(new XenForo_Phrase('xentrader_please_select_a_rating'));
     }
     if (empty($input['feedback'])) {
         $dw->error(new XenForo_Phrase('xentrader_please_enter_some_feedback'), 'feedback');
     } else {
         if (strlen($input['feedback']) > 80) {
             $dw->error(new XenForo_Phrase('xentrader_no_more_than_80_characters_allowed'), 'feedback');
         } else {
             if (strlen($input['feedback']) < $xenOptions->nfxtMinFeedbackLength) {
                 $dw->error(new XenForo_Phrase('xentrader_minimum_length_for_feedback_is_x_characters', array('length' => $xenOptions->nfxtMinFeedbackLength)), 'feedback');
             }
         }
     }
     $dw->preSave();
     if (!$dw->hasErrors()) {
         $this->assertNotFlooding('feedback-' . $input['from_user_id'] . '-' . $input['to_user_id'], $xenOptions->xentraderFloodLengthCheck);
     }
     $dw->save();
     $data = $dw->getMergedData();
     if (XenForo_Model_Alert::userReceivesAlert($toUser, 'feedback', 'insert')) {
         XenForo_Model_Alert::alert($input['to_user_id'], $input['from_user_id'], $fromUser['username'], 'feedback', $data['feedback_id'], 'insert');
     }
     $this->_getNewsFeedModel()->publish($input['from_user_id'], $fromUser['username'], 'feedback', $data['feedback_id'], 'insert');
     if ($xenOptions->nfxtReportNegative && $data['rating'] == -1 || $xenOptions->xentraderReportNeutral && $data['rating'] == 0) {
         $reportModel = $this->_getReportModel();
         $data['system_generated'] = true;
         $reportModel->reportContent('feedback', $data, new XenForo_Phrase('nfxt_auto_report_title', array('feedback' => $data['rating'] == 0 ? 'Neutral' : 'Negative', 'forName' => $data['to_username'], 'byName' => $data['from_username'])));
     }
     return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildPublicLink('xentrader', array('user_id' => $data['to_user_id'], 'username' => $data['to_username'])), new XenForo_Phrase('nfxt_your_feedback_has_been_submitted'));
 }
Example #25
0
 /**
  * Creates a new follower record for $userId following $followUserId(s)
  *
  * @param array Users being followed
  * @param boolean Check for and prevent duplicate followers
  * @param array $user User doing the following
  *
  * @return string Comma-separated list of all users now being followed by $userId
  */
 public function follow(array $followUsers, $dupeCheck = true, array $user = null)
 {
     if ($user === null) {
         $user = XenForo_Visitor::getInstance();
     }
     // if we have only a single user, build the multi-user array structure
     if (isset($followUsers['user_id'])) {
         $followUsers = array($followUsers['user_id'] => $followUsers);
     }
     if ($dupeCheck) {
         $followUsers = $this->removeDuplicateFollowUserIds($user['user_id'], $followUsers);
     }
     $db = $this->_getDb();
     $errors = false;
     XenForo_Db::beginTransaction($db);
     foreach ($followUsers as $followUser) {
         if ($user['user_id'] == $followUser['user_id']) {
             continue;
         }
         $writer = XenForo_DataWriter::create('XenForo_DataWriter_Follower');
         $writer->setOption(XenForo_DataWriter_Follower::OPTION_POST_WRITE_UPDATE_USER_FOLLOWING, false);
         $writer->set('user_id', $user['user_id']);
         $writer->set('follow_user_id', $followUser['user_id']);
         $success = $writer->save();
         if ($success && !$this->isUserIgnored($followUser, $user['user_id']) && XenForo_Model_Alert::userReceivesAlert($followUser, 'user', 'following')) {
             XenForo_Model_Alert::alert($followUser['user_id'], $user['user_id'], $user['username'], 'user', $followUser['user_id'], 'following');
         }
     }
     $return = $this->updateFollowingDenormalizedValue($user['user_id']);
     XenForo_Db::commit($db);
     return $return;
 }
 protected function _postSave()
 {
     $albumUserId = $this->getExtraData(self::DATA_ALBUM_USER_ID);
     if ($albumUserId && $this->isChanged('access_type')) {
         $this->_setShareUsers($albumUserId, true);
     }
     if ($this->isChanged('share_users')) {
         $shareUsers = @unserialize($this->get('share_users'));
         if ($shareUsers) {
             $existingUsers = @unserialize($this->getExisting('share_users'));
             if (!$existingUsers) {
                 $existingUsers = array();
             }
             $newUsers = array();
             foreach ($shareUsers as $key => $shareUser) {
                 if (!isset($existingUsers[$key])) {
                     $newUsers[$key] = $shareUser;
                 }
             }
             $users = $this->getModelFromCache('XenForo_Model_User')->getUsersByIds($newUsers, array('join' => XenForo_Model_User::FETCH_USER_OPTION));
             $albumModel = $this->_getAlbumModel();
             $album = $albumModel->getAlbumById($this->get('album_id'));
             foreach ($users as $user) {
                 if ($album['album_user_id'] != $user['user_id']) {
                     if (XenForo_Model_Alert::userReceivesAlert($user, 'xengallery_album', 'share') && !$this->getOption(self::OPTION_SKIP_ALERTS)) {
                         if ($this->get('permission') == 'add') {
                             XenForo_Model_Alert::alert($user['user_id'], $album['album_user_id'], $album['album_username'], 'xengallery_album', $this->get('album_id'), 'share_add');
                         } elseif ($this->get('permission') == 'view') {
                             XenForo_Model_Alert::alert($user['user_id'], $album['album_user_id'], $album['album_username'], 'xengallery_album', $this->get('album_id'), 'share');
                         }
                     }
                 }
             }
         }
     }
 }
Example #27
0
 /**
  * Inserts an alert for this conversation.
  *
  * @param array $conversation
  * @param array $alertUser User to notify
  * @param string $action Action taken out (values: insert, reply, join)
  * @param array|null $triggerUser User triggering the alert; defaults to last user to reply
  * @param array|null $extraData
  * @param array|null $messageInfo
  */
 public function insertConversationAlert(array $conversation, array $alertUser, $action, array $triggerUser = null, array $extraData = null, array &$messageInfo = null)
 {
     if (!$triggerUser) {
         $triggerUser = array('user_id' => $conversation['last_message_user_id'], 'username' => $conversation['last_message_username']);
     }
     if ($triggerUser['user_id'] == $alertUser['user_id']) {
         return;
     }
     if ($alertUser['email_on_conversation'] && $alertUser['user_state'] == 'valid') {
         if (!isset($conversation['titleCensored'])) {
             $conversation['titleCensored'] = XenForo_Helper_String::censorString($conversation['title']);
         }
         $mail = XenForo_Mail::create("conversation_{$action}", array('receiver' => $alertUser, 'sender' => $triggerUser, 'options' => XenForo_Application::get('options'), 'conversation' => $conversation, 'message' => $messageInfo), $alertUser['language_id']);
         $mail->enableAllLanguagePreCache();
         $mail->queue($alertUser['email'], $alertUser['username']);
     }
     // exit before we actually insert an alert, as the unread counter and the "inbox" link provides what's necessary
     return;
     if (XenForo_Model_Alert::userReceivesAlert($alertUser, 'conversation', $action)) {
         XenForo_Model_Alert::alert($alertUser['user_id'], $triggerUser['user_id'], $triggerUser['username'], 'conversation', $conversation['conversation_id'], $action, $extraData);
     }
 }
Example #28
0
 public function postComment($input, $media)
 {
     $dw = XenForo_DataWriter::create('EWRmedio_DataWriter_Comments');
     $dw->bulkSet(array('media_id' => $media['media_id'], 'comment_message' => $input['message'], 'username' => $input['username']));
     $dw->save();
     $input = $dw->getMergedData();
     $input['comment_ip'] = $this->getModelFromCache('XenForo_Model_Ip')->logIp($input['user_id'], 'media', $input['comment_id'], 'comment');
     $dw = XenForo_DataWriter::create('EWRmedio_DataWriter_Comments');
     $dw->setExistingData(array('comment_id' => $input['comment_id']));
     $dw->set('comment_ip', $input['comment_ip']);
     $dw->save();
     $dw = XenForo_DataWriter::create('EWRmedio_DataWriter_Media');
     $dw->setExistingData($media);
     $dw->bulkSet(array('last_comment_date' => $input['comment_date'], 'last_comment_id' => $input['comment_id'], 'last_comment_user_id' => $input['user_id'], 'last_comment_username' => $input['username']));
     $dw->save();
     $this->getModelFromCache('EWRmedio_Model_MediaWatch')->setMediaWatchState($input['user_id'], $input['media_id'], $this->getModelFromCache('EWRmedio_Model_MediaWatch')->getDefaultWatchByUserId($input['user_id']), false);
     $autoReadDate = XenForo_Application::$time - XenForo_Application::get('options')->readMarkingDataLifetime * 86400;
     $latestComments = $this->getNewestCommentsInMediaAfterDate($media['media_id'], $autoReadDate);
     list($key) = each($latestComments);
     unset($latestComments[$key]);
     $defaultPreviousComment = reset($latestComments);
     if (XenForo_Application::get('options')->EWRmedio_emailIncludeMessage) {
         $parseBbCode = true;
         $emailTemplate = 'watched_media_reply_messagetext';
     } else {
         $parseBbCode = false;
         $emailTemplate = 'watched_media_reply';
     }
     $replyUser = $this->getModelFromCache('XenForo_Model_User')->getUserById($input['user_id']);
     $reply = array_merge($replyUser, $input);
     $users = $this->getModelFromCache('EWRmedio_Model_MediaWatch')->getUsersWatchingMedia($media['media_id']);
     foreach ($users as $user) {
         if ($user['user_id'] == $input['user_id']) {
             continue;
         }
         if ($this->getModelFromCache('XenForo_Model_User')->isUserIgnored($user, $input['user_id'])) {
             continue;
         }
         if (!$defaultPreviousComment || !$this->getModelFromCache('XenForo_Model_User')->isUserIgnored($user, $defaultPreviousComment['user_id'])) {
             $previousComment = $defaultPreviousComment;
         } else {
             $previousComment = false;
             foreach ($latestComments as $latestComment) {
                 if (!$this->getModelFromCache('XenForo_Model_User')->isUserIgnored($user, $latestComment['user_id'])) {
                     $previousComment = $latestComment;
                     break;
                 }
             }
         }
         if ($previousComment['comment_date'] > $user['media_read_date']) {
             continue;
         }
         if ($user['email_subscribe'] && $user['email'] && $user['user_state'] == 'valid') {
             if (!isset($reply['messageText']) && $parseBbCode) {
                 $bbCodeParserText = new XenForo_BbCode_Parser(XenForo_BbCode_Formatter_Base::create('Text'));
                 $reply['messageText'] = new XenForo_BbCode_TextWrapper($reply['comment_message'], $bbCodeParserText);
                 $bbCodeParserHtml = new XenForo_BbCode_Parser(XenForo_BbCode_Formatter_Base::create('HtmlEmail'));
                 $reply['messageHtml'] = new XenForo_BbCode_TextWrapper($reply['comment_message'], $bbCodeParserHtml);
             }
             $mail = XenForo_Mail::create($emailTemplate, array('reply' => $reply, 'media' => $media, 'receiver' => $user), $user['language_id']);
             $mail->enableAllLanguagePreCache();
             $mail->queue($user['email'], $user['username']);
         }
         if (XenForo_Model_Alert::userReceivesAlert($user, 'media_comment', 'insert')) {
             XenForo_Model_Alert::alert($user['user_id'], $reply['user_id'], $reply['username'], 'media_comment', $reply['comment_id'], 'insert');
         }
     }
     $this->getModelFromCache('EWRmedio_Model_Media')->updateComments($media);
     if (!($media['thread_id'] && $this->getModelFromCache('EWRmedio_Model_Threads')->postToThread($input, $media))) {
         $this->getModelFromCache('XenForo_Model_NewsFeed')->publish($input['user_id'], $input['username'], 'media_comment', $input['comment_id'], 'insert');
     }
     return $input;
 }
Example #29
0
 /**
  * Send a notification to the users watching the resource.
  *
  * @param array $update The reply that has been added
  * @param array $resource Info about the resource the update is in
  * @param array $noAlerts List of user ids to NOT alert (but still send email)
  * @param array $noEmail List of user ids to not send an email
  *
  * @return array Empty or keys: alerted: user ids alerted, emailed: user ids emailed
  */
 public function sendNotificationToWatchUsersOnUpdate(array $update, array $resource, array $noAlerts = array(), array $noEmail = array())
 {
     if ($update['message_state'] != 'visible' || $resource['resource_state'] != 'visible') {
         return array();
     }
     $resourceModel = $this->_getResourceModel();
     /* @var $userModel XenForo_Model_User */
     $userModel = $this->getModelFromCache('XenForo_Model_User');
     if (XenForo_Application::get('options')->emailWatchedThreadIncludeMessage) {
         $parseBbCode = true;
         $emailTemplate = 'watched_resource_update_messagetext';
     } else {
         $parseBbCode = false;
         $emailTemplate = 'watched_resource_update';
     }
     $resourceUser = $userModel->getUserById($resource['user_id']);
     if (!$resourceUser) {
         $resourceUser = $userModel->getVisitingGuestUser();
     }
     if (!empty($resource['category_breadcrumb'])) {
         $category = $resource;
     } else {
         $category = $this->_getCategoryModel()->getCategoryById($resource['resource_category_id']);
         if (!$category) {
             return array();
         }
     }
     $alerted = array();
     $emailed = array();
     $users = $this->getUsersWatchingResource($resource['resource_id'], $resource['resource_category_id']);
     foreach ($users as $user) {
         if ($user['user_id'] == $resource['user_id']) {
             continue;
         }
         $user['permissions'] = XenForo_Permission::unserializePermissions($user['global_permission_cache']);
         $categoryPermissions = XenForo_Permission::unserializePermissions($user['category_permission_cache']);
         if (!$resourceModel->canViewResourceAndContainer($resource, $category, $null, $user, $categoryPermissions)) {
             continue;
         }
         if ($user['email_subscribe'] && $user['email'] && $user['user_state'] == 'valid') {
             if (!isset($update['messageText']) && $parseBbCode) {
                 $bbCodeParserText = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('Text'));
                 $update['messageText'] = new XenForo_BbCode_TextWrapper($update['message'], $bbCodeParserText);
                 $bbCodeParserHtml = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('HtmlEmail'));
                 $update['messageHtml'] = new XenForo_BbCode_TextWrapper($update['message'], $bbCodeParserHtml);
             }
             if (!isset($resource['titleCensored'])) {
                 $resource['titleCensored'] = XenForo_Helper_String::censorString($resource['title']);
                 $update['titleCensored'] = XenForo_Helper_String::censorString($update['title']);
             }
             $user['email_confirm_key'] = $userModel->getUserEmailConfirmKey($user);
             $mail = XenForo_Mail::create($emailTemplate, array('update' => $update, 'resource' => $resource, 'category' => $category, 'resourceUser' => $resourceUser, 'receiver' => $user), $user['language_id']);
             $mail->enableAllLanguagePreCache();
             $mail->queue($user['email'], $user['username']);
             $emailed[] = $user['user_id'];
             $noEmail[] = $user['user_id'];
         }
         if (XenForo_Model_Alert::userReceivesAlert($user, 'resource_update', 'insert')) {
             XenForo_Model_Alert::alert($user['user_id'], $resource['user_id'], $resource['username'], 'resource_update', $update['resource_update_id'], 'insert');
             $alerted[] = $user['user_id'];
             $noAlerts[] = $user['user_id'];
         }
     }
     return array('emailed' => $emailed, 'alerted' => $alerted);
 }
Example #30
0
 protected function _triggerNewVideosAdded($count, $videoIds)
 {
     $visitor = XenForo_Visitor::getInstance();
     $contentType = sonnb_XenGallery_Model_Album::$contentType;
     $xfContentType = sonnb_XenGallery_Model_Album::$xfContentType;
     /*
      * Massive sending alert to watched users.
      */
     $this->_getWatchModel()->sendAlertToWatchedUsersByContentId($contentType, $this->get('album_id'), $visitor, 'add_video', array('count' => $count, 'videoIds' => $videoIds));
     /*
      * Send alert to owner.
      */
     if ($visitor['user_id'] != $this->get('user_id')) {
         $userModel = $this->_getUserModel();
         $contentUser = $userModel->getUserById($this->get('user_id'), array('join' => XenForo_Model_User::FETCH_USER_OPTION | XenForo_Model_User::FETCH_USER_PROFILE));
         if ($contentUser) {
             if (!$userModel->isUserIgnored($contentUser, $visitor['user_id']) && XenForo_Model_Alert::userReceivesAlert($contentUser, $xfContentType, 'add_video')) {
                 XenForo_Model_Alert::alert($this->get('user_id'), $visitor['user_id'], $visitor['username'], $xfContentType, $this->get('album_id'), 'add_video', array('count' => $count, 'videoIds' => $videoIds));
             }
         }
     }
     /*
      * Publish to newsfeed.
      */
     $this->_getNewsFeedModel()->publish($visitor['user_id'], $visitor['username'], $xfContentType, $this->get('album_id'), 'add_video', array('count' => $count, 'videoIds' => $videoIds));
 }