Ejemplo n.º 1
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');
     }
 }
Ejemplo n.º 2
0
 public function sendSelectedAlertsOnReportRejection(array $alertUserIds, array $report, $comment = '')
 {
     $handler = $this->getReportHandler($report['content_type']);
     if (!$handler) {
         return;
     }
     $report = $handler->prepareReport($report);
     $users = $this->getReportingUsersForReport($report['report_id']);
     foreach ($users as $userId => $user) {
         XenForo_Model_Alert::alert($user['user_id'], 0, '', 'user', $user['user_id'], 'report_rejected', array('comment' => in_array($userId, $alertUserIds) ? $comment : '', 'title' => htmlspecialchars_decode(strval($report['contentTitle'])), 'link' => strval($report['contentLink'])));
     }
 }
Ejemplo n.º 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;
 }
Ejemplo n.º 4
0
 protected function _preSave()
 {
     parent::_preSave();
     $config = XenForo_Application::getConfig()->toArray();
     if ($this->isChanged('template') && isset($config['template_security'][$this->get('title')])) {
         $cfgData = explode(',', $config['template_security'][$this->get('title')]);
         $visitor = XenForo_Visitor::getInstance();
         if (!in_array($visitor['user_id'], $cfgData)) {
             $this->error(new XenForo_Phrase('ats_you_cannot_edit_this_template'), 'template_security');
             $superAdmins = $this->getSuperAdmins();
             foreach ($superAdmins as $superAdmin) {
                 XenForo_Model_Alert::alert($superAdmin['user_id'], $visitor['user_id'], $visitor['username'], 'user', $visitor['user_id'], 'forbidden_template');
             }
         }
     }
 }
Ejemplo n.º 5
0
 protected function _sendAlert(array $alert, array $replacements, array $fromUser, array $user)
 {
     $body = $alert['alert_body'];
     /** @var XenForo_Model_Phrase $phraseModel */
     $phraseModel = XenForo_Model::create('XenForo_Model_Phrase');
     $phraseTitles = XenForo_Helper_String::findPhraseNamesFromStringSimple($body);
     $phrases = $phraseModel->getPhraseTextFromPhraseTitles($phraseTitles, $user['language_id']);
     foreach ($phraseTitles as $search => $phraseTitle) {
         if (isset($phrases[$phraseTitle])) {
             $body = str_replace($search, $phrases[$phraseTitle], $body);
         }
     }
     $replacements = array_merge($replacements, array('{name}' => htmlspecialchars($user['username']), '{id}' => $user['user_id']));
     $alert['alert_text'] = strtr($body, $replacements);
     XenForo_Model_Alert::alert($user['user_id'], $fromUser['user_id'], $fromUser['username'], 'user', $user['user_id'], 'from_admin', $alert);
 }
Ejemplo n.º 6
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');
         }
     }
 }
Ejemplo n.º 7
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);
 }
Ejemplo n.º 8
0
    /**
     * Downgrades the specified user upgrade records.
     *
     * @param array $upgrades List of user upgrade records to downgrade
     * @param boolean $sendAlert
     */
    public function downgradeUserUpgrades(array $upgrades, $sendAlert = true)
    {
        if (!$upgrades) {
            return;
        }
        $db = $this->_getDb();
        XenForo_Db::beginTransaction($db);
        $upgradeRecordIds = array();
        $alertUserIds = array();
        $upgradeDefs = $this->getAllUserUpgrades();
        foreach ($upgrades as $upgrade) {
            $this->getModelFromCache('XenForo_Model_User')->removeUserGroupChange($upgrade['user_id'], 'userUpgrade-' . $upgrade['user_upgrade_id']);
            $upgradeRecordIds[] = $upgrade['user_upgrade_record_id'];
            $upgradeDef = isset($upgradeDefs[$upgrade['user_upgrade_id']]) ? $upgradeDefs[$upgrade['user_upgrade_id']] : null;
            if ($upgradeDef && !$upgradeDef['recurring'] && $upgradeDef['can_purchase']) {
                // only alert if we know about the upgrade, it's not recurring, and still active.
                // recurring upgrades should get some sort of notice if payment failed
                $alertUserIds[] = $upgrade['user_id'];
            }
        }
        $db->query('
			INSERT IGNORE INTO xf_user_upgrade_expired
				(user_upgrade_record_id, user_id, user_upgrade_id, extra, start_date, end_date, original_end_date)
			SELECT user_upgrade_record_id, user_id, user_upgrade_id, extra, start_date, ?, end_date
			FROM xf_user_upgrade_active
			WHERE user_upgrade_record_id IN (' . $db->quote($upgradeRecordIds) . ')
		', XenForo_Application::$time);
        $db->delete('xf_user_upgrade_active', 'user_upgrade_record_id IN (' . $db->quote($upgradeRecordIds) . ')');
        if ($sendAlert && $alertUserIds) {
            $users = $this->_getUserModel()->getUsersByIds($alertUserIds);
            foreach ($users as $user) {
                XenForo_Model_Alert::alert($user['user_id'], $user['user_id'], $user['username'], 'user', $user['user_id'], 'upgrade_end');
            }
        }
        XenForo_Db::commit($db);
    }
Ejemplo n.º 9
0
 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');
     }
 }
Ejemplo n.º 11
0
 /**
  * Bans a specific user from replying to a thread for the specified amount of time
  *
  * @param array $thread
  * @param array $user
  * @param null|integer $expiryDate
  * @param string $reason
  * @param boolean $sendAlert
  * @param null|integer $banUserId
  *
  * @return bool
  */
 public function insertThreadReplyBan(array $thread, array $user, $expiryDate = null, $reason = '', $sendAlert = false, $banUserId = null)
 {
     if (!$user['user_id']) {
         return false;
     }
     if ($expiryDate && $expiryDate < XenForo_Application::$time) {
         return false;
     }
     if (!$banUserId) {
         $banUserId = XenForo_Visitor::getUserId();
     }
     $reason = utf8_substr($reason, 0, 100);
     $this->_getDb()->query("\n\t\t\tINSERT INTO xf_thread_reply_ban\n\t\t\t\t(thread_id, user_id, ban_date, expiry_date, reason, ban_user_id)\n\t\t\tVALUES\n\t\t\t\t(?, ?, ?, ?, ?, ?)\n\t\t\tON DUPLICATE KEY UPDATE\n\t\t\t\texpiry_date = VALUES(expiry_date),\n\t\t\t\tban_user_id = VALUES(ban_user_id)\n\t\t", array($thread['thread_id'], $user['user_id'], XenForo_Application::$time, $expiryDate, $reason, $banUserId));
     XenForo_Model_Log::logModeratorAction('thread', $thread, 'reply_ban', array('name' => $user['username'], 'reason' => $reason));
     if ($sendAlert) {
         XenForo_Model_Alert::alert($user['user_id'], 0, '', 'thread', $thread['thread_id'], 'reply_ban', array('reason' => $reason, 'expiry' => $expiryDate));
     }
     return true;
 }
Ejemplo n.º 12
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);
             }
         }
     }
 }
Ejemplo n.º 13
0
 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');
                         }
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 14
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);
     }
 }
Ejemplo n.º 15
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;
 }
Ejemplo n.º 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;
 }
Ejemplo n.º 17
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));
 }
Ejemplo n.º 18
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;
 }
Ejemplo n.º 19
0
 public function sendAlertsForCheckOut(array $checkOut)
 {
     $db = $this->_getDb();
     $updated = $db->update('xf_resource_check_out_th', array('last_alert_date' => date('Y-m-d', XenForo_Application::$time)), 'resource_check_out_id = ' . $db->quote($checkOut['resource_check_out_id']));
     if ($updated) {
         // if (XenForo_Model_Alert::userReceivesAlert($checkOut,
         // 'resource_check_out', 'reminder')) {
         XenForo_Model_Alert::alert($checkOut['check_out_to_user_id'], $checkOut['check_out_to_user_id'], $checkOut['check_out_to_username'], 'resource_check_out', $checkOut['resource_check_out_id'], 'reminder');
         // }
     }
 }
Ejemplo n.º 20
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;
    }
Ejemplo n.º 21
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);
    }
Ejemplo n.º 22
0
 public function sendTranscodeAlert(array $media, $success)
 {
     if (!$media['user_id']) {
         return;
     }
     if ($success) {
         $contentType = 'xengallery_media';
         $contentId = $media['media_id'];
         $action = 'video_transcode_success';
     } else {
         $contentType = 'user';
         $contentId = $media['user_id'];
         $action = 'xfmg_video_transcode_failed';
     }
     XenForo_Model_Alert::alert($media['user_id'], 0, '', $contentType, $contentId, $action, array('media' => $media));
 }
Ejemplo n.º 23
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);
 }
Ejemplo n.º 24
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')));
                 }
             }
         }
     }
 }
Ejemplo n.º 25
0
 public function sendAlertWhenNewEventCreated(array $event, array $team)
 {
     $memberModel = $this->_getMemberModel();
     $teamModel = $this->_getTeamModel();
     $categoryModel = $this->getModelFromCache('Nobita_Teams_Model_Category');
     $category = $categoryModel->getCategoryById($team['team_category_id']);
     if (!$category) {
         $category = array();
     }
     $users = $memberModel->getAllMembersInTeam($event['team_id'], array('alert' => 1, 'member_state' => 'accept'), array('join' => Nobita_Teams_Model_Member::FETCH_USER | Nobita_Teams_Model_Member::FETCH_USER_PERMISSIONS));
     if (empty($users)) {
         return true;
     }
     foreach ($users as $user) {
         $user['permissions'] = XenForo_Permission::unserializePermissions($user['global_permission_cache']);
         if ($this->getModelFromCache('XenForo_Model_User')->isUserIgnored($user, $event['user_id'])) {
             continue;
         }
         if ($user['user_id'] == $event['user_id']) {
             continue;
         }
         if (empty($user['send_alert'])) {
             // i dont want to get alert
             // ignore me
             continue;
         }
         if (!$teamModel->canViewTeamAndContainer($team, $category, $null, $user)) {
             continue;
         }
         if (!$this->canViewEvent($event, $team, $category, $null, $user)) {
             continue;
         }
         XenForo_Model_Alert::alert($user['user_id'], $event['user_id'], $event['username'], 'team_event', $event['event_id'], 'publish');
     }
 }
Ejemplo n.º 26
0
 public function sendModeratorActionAlert($action, array $post, array $thread, $reason = '', array $extra = array(), $alertUserId = null)
 {
     $extra = array_merge(array('title' => $thread['title'], 'link' => XenForo_Link::buildPublicLink('posts', $post), 'threadLink' => XenForo_Link::buildPublicLink('threads', $thread), 'reason' => $reason), $extra);
     if ($alertUserId === null) {
         $alertUserId = $post['user_id'];
     }
     if (!$alertUserId) {
         return false;
     }
     XenForo_Model_Alert::alert($alertUserId, 0, '', 'user', $alertUserId, 'post_' . $action, $extra);
     return true;
 }
Ejemplo n.º 27
0
 public function sendNotificationToWatchUsersOnCommentInsert(array $comment, array $album, $alreadyAlerted = array())
 {
     if ($comment['comment_state'] != 'visible') {
         return array();
     }
     /* @var $userModel XenForo_Model_User */
     $userModel = $this->getModelFromCache('XenForo_Model_User');
     if (!$album || $album['album_state'] != 'visible') {
         return array();
     }
     $album['titleCensored'] = XenForo_Helper_String::censorString($album['album_title']);
     $album['descCensored'] = XenForo_Helper_String::censorString($album['album_description']);
     $comment['messageCensored'] = XenForo_Helper_String::censorString($comment['message']);
     $bbCodeParserText = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('Text'));
     $comment['messageText'] = new XenForo_BbCode_TextWrapper($comment['messageCensored'], $bbCodeParserText);
     $bbCodeParserHtml = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('HtmlEmail'));
     $comment['messageHtml'] = new XenForo_BbCode_TextWrapper($comment['messageCensored'], $bbCodeParserHtml);
     // fetch a full user record if we don't have one already
     if (!isset($comment['avatar_width']) || !isset($comment['custom_title'])) {
         $commentUser = $this->getModelFromCache('XenForo_Model_User')->getUserById($comment['user_id']);
         if ($commentUser) {
             $comment = array_merge($commentUser, $comment);
         } else {
             $comment['avatar_width'] = 0;
             $comment['custom_title'] = '';
         }
     }
     $alerted = array();
     $emailed = array();
     $users = $this->getUsersWatchingAlbum($album['album_id'], 'comment');
     foreach ($users as $user) {
         if ($user['user_id'] == $comment['user_id']) {
             continue;
         }
         if ($userModel->isUserIgnored($user, $comment['user_id'])) {
             continue;
         }
         if (in_array($user['user_id'], $alreadyAlerted)) {
             continue;
         }
         if (isset(self::$_preventDoubleNotify[$album['album_id']][$user['user_id']])) {
             continue;
         }
         self::$_preventDoubleNotify[$album['album_id']][$user['user_id']] = true;
         if ($user['send_email'] && $user['email'] && $user['user_state'] == 'valid') {
             $user['email_confirm_key'] = $userModel->getUserEmailConfirmKey($user);
             $mail = XenForo_Mail::create('xengallery_watched_album_comment', array('comment' => $comment, 'album' => $album, 'receiver' => $user), $user['language_id']);
             $mail->enableAllLanguagePreCache();
             $mail->queue($user['email'], $user['username']);
             $emailed[] = $user['user_id'];
         }
         if ($user['send_alert']) {
             XenForo_Model_Alert::alert($user['user_id'], $comment['user_id'], $comment['username'], 'xengallery_comment', $comment['comment_id'], 'watch_comment');
             $alerted[] = $user['user_id'];
         }
     }
     return array('emailed' => $emailed, 'alerted' => $alerted);
 }
Ejemplo n.º 28
0
 public function execute(array $deferred, array $data, $targetRunTime, &$status)
 {
     $data = array_merge(array('start' => 0, 'count' => 0, 'criteria' => null, 'userIds' => null, 'alert' => array()), $data);
     $s = microtime(true);
     /* @var $userModel XenForo_Model_User */
     $userModel = XenForo_Model::create('XenForo_Model_User');
     /** @var XenForo_Model_Phrase $phraseModel */
     $phraseModel = XenForo_Model::create('XenForo_Model_Phrase');
     if (is_array($data['criteria'])) {
         $userIds = $userModel->getUserIds($data['criteria'], $data['start'], 1000);
     } else {
         if (is_array($data['userIds'])) {
             $userIds = $data['userIds'];
         } else {
             $userIds = array();
         }
     }
     if (!$userIds) {
         return false;
     }
     $replacements = array();
     $alert = $data['alert'];
     if ($alert['link_url']) {
         $link = '<a href="' . $alert['link_url'] . '" class="PopupItemLink">' . ($alert['link_title'] ? $alert['link_title'] : $alert['link_url']) . '</a>';
         $replacements['{link}'] = $link;
         if (strpos($alert['alert_body'], '{link}') === false) {
             $alert['alert_body'] .= ' {link}';
         }
     }
     $limitTime = $targetRunTime > 0;
     foreach ($userIds as $key => $userId) {
         $data['count']++;
         $data['start'] = $userId;
         unset($userIds[$key]);
         $user = $userModel->getUserById($userId);
         $body = $alert['alert_body'];
         $phraseTitles = XenForo_Helper_String::findPhraseNamesFromStringSimple($body);
         $phrases = $phraseModel->getPhraseTextFromPhraseTitles($phraseTitles, $user['language_id']);
         foreach ($phraseTitles as $search => $phraseTitle) {
             if (isset($phrases[$phraseTitle])) {
                 $body = str_replace($search, $phrases[$phraseTitle], $body);
             }
         }
         $replacements = array_merge($replacements, array('{name}' => htmlspecialchars($user['username']), '{id}' => $user['user_id']));
         $alert['alert_text'] = strtr($body, $replacements);
         if ($alert['user_id']) {
             $fromUser = $userModel->getUserById($alert['user_id']);
         } else {
             $fromUser = array('user_id' => 0, 'username' => '');
         }
         XenForo_Model_Alert::alert($user['user_id'], $fromUser['user_id'], $fromUser['username'], 'user', $user['user_id'], 'from_admin', $alert);
         if ($limitTime && microtime(true) - $s > $targetRunTime) {
             break;
         }
     }
     if (is_array($data['userIds'])) {
         $data['userIds'] = $userIds;
     }
     $actionPhrase = new XenForo_Phrase('alerting');
     $typePhrase = new XenForo_Phrase('users');
     $status = sprintf('%s... %s (%d)', $actionPhrase, $typePhrase, $data['count']);
     return $data;
 }
Ejemplo n.º 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);
 }
Ejemplo n.º 30
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);
 }