Exemplo n.º 1
0
 public function verifyFromInput($context, XenForo_Input $input, array $user, array &$providerData)
 {
     $code = $input->filterSingle('code', XenForo_Input::STRING);
     $code = preg_replace('/[^0-9]/', '', $code);
     if (!$code) {
         return false;
     }
     $matched = null;
     foreach ($providerData['codes'] as $i => $expectedCode) {
         if (XenForo_Application::hashEquals($expectedCode, $code)) {
             $matched = $i;
             break;
         }
     }
     if ($matched === null) {
         return false;
     }
     $providerData['used'][] = $providerData['codes'][$matched];
     unset($providerData['codes'][$matched]);
     if (!$providerData['codes']) {
         // regenerate automatically
         $regenerated = true;
         $this->generateInitialData($user, array());
     } else {
         $regenerated = false;
     }
     $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
     $mail = XenForo_Mail::create('two_step_login_backup', array('user' => $user, 'ip' => $ip, 'regenerated' => $regenerated), $user['language_id']);
     $mail->send($user['email'], $user['username']);
     return true;
 }
Exemplo n.º 2
0
 protected function _postSave()
 {
     parent::_postSave();
     if ($this->getOption(self::OPTION_ADMIN_EDIT) && $this->get('email') && $this->_password) {
         $xenOptions = XenForo_Application::get('options');
         if ($this->isInsert() && $xenOptions->th_emailAdGenPass_newUsers || $this->isUpdate() && $xenOptions->th_emailAdGenPass_existingUsers) {
             $params = array('user' => $this->getMergedData(), 'password' => $this->_password, 'boardTitle' => XenForo_Application::get('options')->boardTitle, 'boardUrl' => XenForo_Application::get('options')->boardUrl);
             $mail = XenForo_Mail::create('th_user_password_emailadgenpass', $params, $this->get('language_id'));
             $mail->send($this->get('email'), $this->get('username'));
         }
     }
 }
Exemplo n.º 3
0
 public function triggerVerification($context, array $user, $ip, array &$providerData)
 {
     $length = 6;
     $random = XenForo_Application::generateRandomString(4, true);
     $code = ((ord($random[0]) & 0x7f) << 24 | (ord($random[1]) & 0xff) << 16 | (ord($random[2]) & 0xff) << 8 | ord($random[3]) & 0xff) % pow(10, $length);
     $code = str_pad($code, $length, '0', STR_PAD_LEFT);
     $providerData['code'] = $code;
     $providerData['codeGenerated'] = time();
     $mail = XenForo_Mail::create('two_step_login_email', array('code' => $code, 'user' => $user, 'ip' => $ip), $user['language_id']);
     $mail->send($user['email'], $user['username']);
     return array();
 }
Exemplo n.º 4
0
 public function log($processorId, $transactionId, $logType, $logMessage, $logDetails)
 {
     $this->_getDb()->insert('xf_bdpaygate_log', array('processor' => $processorId, 'transaction_id' => $transactionId, 'log_type' => $logType, 'log_message' => substr($logMessage, 0, 255), 'log_details' => serialize($logDetails), 'log_date' => XenForo_Application::$time));
     $logId = $this->_getDb()->lastInsertId();
     if ($logType === bdPaygate_Processor_Abstract::PAYMENT_STATUS_REJECTED) {
         $emailOnFailure = XenForo_Application::getOptions()->get('bdPaygate0_emailOnFailure');
         if (!empty($emailOnFailure)) {
             // send email notification to administrator for failed transaction
             $mail = XenForo_Mail::create('bdpaygate_failure', array('processorId' => $processorId, 'transactionId' => $transactionId, 'logType' => $logType, 'logMessage' => $logMessage, 'logDetails' => $logDetails, 'logId' => $logId));
             $mail->queue($emailOnFailure);
         }
     }
     return $logId;
 }
 /**
  * Resets the specified user's parental control password and emails the password to the parent if requested.
  *
  * @param integer $userId
  * @param boolean $sendEmail
  *
  * @return string New password
  */
 public function resetParentPassword($userId, $sendEmail = true)
 {
     $dw = XenForo_DataWriter::create('XenForo_DataWriter_User');
     $dw->setExistingData($userId);
     $password = XenForo_Application::generateRandomString(8);
     $auth = XenForo_Authentication_Abstract::createDefault();
     $dw->set('parent_scheme_class', $auth->getClassName());
     $dw->set('parent_data', $auth->generate($password));
     $dw->save();
     $user = $dw->getMergedData();
     if ($sendEmail) {
         $params = array('user' => $user, 'password' => $password, 'boardTitle' => XenForo_Application::get('options')->boardTitle, 'boardUrl' => XenForo_Application::get('options')->boardUrl);
         $mail = XenForo_Mail::create('th_lost_password_reset_parentalcontrol', $params, $user['language_id']);
         $mail->send($user['parent_email'], (string) new XenForo_Phrase('th_parent_of_x_parentalcontrol', array('username' => $user['username'])));
     }
     return $password;
 }
Exemplo n.º 6
0
 public function actionContact()
 {
     if ($this->_request->isPost()) {
         if (!XenForo_Captcha_Abstract::validateDefault($this->_input)) {
             return $this->responseCaptchaFailed();
         }
         $visitor = XenForo_Visitor::getInstance();
         if ($visitor['user_id']) {
             $email = $visitor['email'];
         } else {
             $email = $this->_input->filterSingle('email', XenForo_Input::STRING);
             if (!Zend_Validate::is($email, 'EmailAddress')) {
                 return $this->responseError(new XenForo_Phrase('please_enter_valid_email'));
             }
         }
         $input = $this->_input->filter(array('subject' => XenForo_Input::STRING, 'message' => XenForo_Input::STRING));
         if (!$visitor['username'] || !$input['subject'] || !$input['message']) {
             return $this->responseError(new XenForo_Phrase('please_complete_required_fields'));
         }
         $this->assertNotFlooding('contact');
         $mailParams = array('name' => $visitor['username'], 'userId' => $visitor['user_id'], 'email' => $email, 'subject' => $input['subject'], 'message' => $input['message']);
         $mail = XenForo_Mail::create('contact', $mailParams, 0);
         $mail->send(XenForo_Application::get('options')->contactEmailAddress, '', array(), $email, $visitor['username']);
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $this->getDynamicRedirect(), new XenForo_Phrase('your_message_has_been_sent'));
     } else {
         $viewParams = array('redirect' => $this->getDynamicRedirect(), 'captcha' => XenForo_Captcha_Abstract::createDefault());
         return $this->responseView('XenForo_ViewPublic_Misc_Contact', 'contact', $viewParams);
     }
 }
Exemplo n.º 7
0
 /**
  *
  * @return XenForo_ControllerResponse_Redirect
  */
 public function actionSecuritySave()
 {
     $this->_assertPostOnly();
     $input = $this->_input->filter(array('old_password' => XenForo_Input::STRING, 'password' => XenForo_Input::STRING, 'password_confirm' => XenForo_Input::STRING));
     $userId = XenForo_Visitor::getUserId();
     $auth = $this->_getUserModel()->getUserAuthenticationObjectByUserId($userId);
     if (!$auth || !$auth->authenticate($userId, $input['old_password'])) {
         return $this->responseError(new XenForo_Phrase('your_existing_password_is_not_correct'));
     }
     $writer = XenForo_DataWriter::create('XenForo_DataWriter_User');
     $writer->setExistingData($userId);
     $writer->setPassword($input['password'], $input['password_confirm'], null, true);
     $writer->save();
     $session = XenForo_Application::getSession();
     if ($session->get('password_date')) {
         $session->set('password_date', $writer->get('password_date'));
     }
     $visitor = XenForo_Visitor::getInstance();
     $mail = XenForo_Mail::create('password_changed', array('user' => $visitor, 'ip' => $this->_request->getClientIp(false)), $visitor['language_id']);
     $mail->send($visitor['email'], $visitor['username']);
     return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildPublicLink('account/security'));
 }
Exemplo n.º 8
0
 protected function _sendNotificationEmail($post, $thread, $email, $emailTemplate)
 {
     $params = array('post' => $post, 'thread' => $thread, 'boardTitle' => XenForo_Application::get('options')->boardTitle, 'boardUrl' => XenForo_Application::get('options')->boardUrl);
     $mail = XenForo_Mail::create($emailTemplate, $params);
     $mail->send($email);
 }
Exemplo n.º 9
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);
 }
Exemplo n.º 10
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;
 }
Exemplo n.º 11
0
 public function actionContact()
 {
     $options = XenForo_Application::get('options');
     if ($options->contactUrl['type'] == 'custom') {
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::RESOURCE_CANONICAL, $options->contactUrl['custom']);
     } else {
         if (!$options->contactUrl['type']) {
             return $this->responseRedirect(XenForo_ControllerResponse_Redirect::RESOURCE_CANONICAL, XenForo_Link::buildPublicLink('index'));
         }
     }
     if ($this->_request->isPost()) {
         if (!XenForo_Captcha_Abstract::validateDefault($this->_input)) {
             return $this->responseCaptchaFailed();
         }
         $user = XenForo_Visitor::getInstance()->toArray();
         if (!$user['user_id']) {
             $user['email'] = $this->_input->filterSingle('email', XenForo_Input::STRING);
             if (!XenForo_Helper_Email::isEmailValid($user['email'])) {
                 return $this->responseError(new XenForo_Phrase('please_enter_valid_email'));
             }
         }
         $input = $this->_input->filter(array('subject' => XenForo_Input::STRING, 'message' => XenForo_Input::STRING));
         if (!$user['username'] || !$input['subject'] || !$input['message']) {
             return $this->responseError(new XenForo_Phrase('please_complete_required_fields'));
         }
         $this->assertNotFlooding('contact');
         $ip = $this->_request->getClientIp(false);
         $mailParams = array('user' => $user, 'subject' => $input['subject'], 'message' => $input['message'], 'ip' => $ip);
         $mail = XenForo_Mail::create('contact', $mailParams, 0);
         $headers = array('X-Contact-IP' => $ip);
         if ($options->contactEmailSenderHeader) {
             $headers['Sender'] = $options->contactEmailAddress;
             $fromEmail = $user['email'];
         } else {
             $fromEmail = '';
         }
         $toEmail = $options->contactEmailAddress ? $options->contactEmailAddress : $options->defaultEmailAddress;
         $mailObj = $mail->getPreparedMailHandler($toEmail, '', $headers, $fromEmail, $user['username']);
         if ($user['email'] && !$options->contactEmailSenderHeader) {
             $mailObj->setReplyTo($user['email'], $user['username']);
         }
         $mail->sendMail($mailObj);
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $this->getDynamicRedirect(), new XenForo_Phrase('your_message_has_been_sent'));
     } else {
         $viewParams = array('redirect' => $this->getDynamicRedirect(), 'isOverlay' => $this->_noRedirect() ? true : false, 'captcha' => XenForo_Captcha_Abstract::createDefault());
         return $this->responseView('XenForo_ViewPublic_Misc_Contact', 'contact', $viewParams);
     }
 }
Exemplo n.º 12
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);
     }
 }
Exemplo n.º 13
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;
 }
Exemplo n.º 14
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;
 }
Exemplo n.º 15
0
 /**
  * Confirms a lost password reset request and resets the password.
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionConfirm()
 {
     $userId = $this->_input->filterSingle('user_id', XenForo_Input::UINT);
     if (!$userId) {
         return $this->responseError(new XenForo_Phrase('no_account_specified'));
     }
     $user = $this->_getUserModel()->getFullUserById($userId);
     if (!$user) {
         return $this->responseError(new XenForo_Phrase('your_password_could_not_be_reset'));
     }
     $confirmationModel = $this->_getUserConfirmationModel();
     $confirmation = $confirmationModel->getUserConfirmationRecord($userId, 'password');
     if (!$confirmation) {
         if (XenForo_Visitor::getUserId()) {
             // probably already been reset
             return $this->responseRedirect(XenForo_ControllerResponse_Redirect::RESOURCE_CANONICAL, XenForo_Link::buildPublicLink('index'));
         } else {
             return $this->responseError(new XenForo_Phrase('your_password_could_not_be_reset'));
         }
     }
     $confirmationKey = $this->_input->filterSingle('c', XenForo_Input::STRING);
     if (!$confirmationModel->validateUserConfirmationRecord($confirmationKey, $confirmation)) {
         return $this->responseError(new XenForo_Phrase('your_password_could_not_be_reset'));
     }
     if ($this->_request->isPost()) {
         $input = $this->_input->filter(array('password' => XenForo_Input::STRING, 'password_confirm' => XenForo_Input::STRING));
         $writer = XenForo_DataWriter::create('XenForo_DataWriter_User');
         $writer->setExistingData($userId);
         $writer->setPassword($input['password'], $input['password_confirm'], null, true);
         switch ($writer->get('user_state')) {
             case 'email_confirm':
                 $writer->advanceRegistrationUserState();
                 break;
             case 'email_confirm_edit':
             case 'email_bounce':
                 $writer->set('user_state', 'valid');
                 break;
         }
         $writer->save();
         $visitor = XenForo_Visitor::getInstance();
         $mail = XenForo_Mail::create('password_changed', array('user' => $visitor, 'ip' => $this->_request->getClientIp(false)), $visitor['language_id']);
         $mail->send($visitor['email'], $visitor['username']);
         $confirmationModel->deleteUserConfirmationRecord($userId, 'password');
         $session = XenForo_Application::getSession();
         $visitorUserId = XenForo_Visitor::getUserId();
         if ($visitorUserId == $user['user_id']) {
             // don't need to do anything -- this can come up when setting a password for a user from external auth
             $session->set('password_date', $writer->get('password_date'));
         } else {
             /** @var XenForo_ControllerHelper_Login $loginHelper */
             $loginHelper = $this->getHelper('Login');
             if ($loginHelper->userTfaConfirmationRequired($user)) {
                 // need to do TFA confirmation before we can log them in
                 $loginHelper->setTfaSessionCheck($user['user_id']);
                 return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildPublicLink('login/two-step', null, array('redirect' => XenForo_Link::buildPublicLink('index'), 'remember' => 0)));
             } else {
                 $session->userLogin($user['user_id'], $writer->get('password_date'));
             }
         }
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildPublicLink('index'));
     } else {
         $viewParams = array('user' => $user, 'confirmation' => $confirmation, 'confirmationKey' => $confirmationKey);
         return $this->responseView('XenForo_ViewPublic_LostPassword_Confirm', 'lost_password_confirm', $viewParams);
     }
 }
Exemplo n.º 16
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 Array containing the text of the message being sent (if applicable) as 'message'
  */
 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' && !$alertUser['is_banned']) {
         if (!isset($conversation['titleCensored'])) {
             $conversation['titleCensored'] = XenForo_Helper_String::censorString($conversation['title']);
         }
         if (isset($messageInfo['message']) && XenForo_Application::get('options')->emailConversationIncludeMessage) {
             if (!isset($messageInfo['messageText'])) {
                 $bbCodeParserText = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('Text'));
                 $messageInfo['messageText'] = new XenForo_BbCode_TextWrapper($messageInfo['message'], $bbCodeParserText);
                 $bbCodeParserHtml = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('HtmlEmail'));
                 $messageInfo['messageHtml'] = new XenForo_BbCode_TextWrapper($messageInfo['message'], $bbCodeParserHtml);
             }
             $emailTemplate = "conversation_{$action}_messagetext";
         } else {
             $emailTemplate = "conversation_{$action}";
         }
         $mail = XenForo_Mail::create($emailTemplate, 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']);
     }
 }
Exemplo n.º 17
0
 /**
  * Send an email to notify the user that they have been spam-cleaned
  *
  * @param array $user
  * @param string $emailText
  * @param array $log
  */
 protected function _emailUser(array $user, $emailText, array &$log)
 {
     $mail = XenForo_Mail::create('spam_cleaner_applied', array('plainText' => $emailText, 'htmlText' => nl2br($emailText)), $user['language_id']);
     $mail->send($user['email'], $user['username']);
     return true;
 }
Exemplo n.º 18
0
 /**
  * Send email invitation to the specified user.
  *
  * @param array $user User to send to
  * @param array|null $confirmation Existing confirmation record; if null, generates a new record
  *
  * @return boolean True if the email was sent successfully
  */
 public function sendEmailInvitation($email, array $user, $affiliateCode)
 {
     $params = array('username' => $user['username'], 'affiliate_code' => $affiliateCode);
     $mail = XenForo_Mail::create('th_affiliate_invitation', $params, $user['language_id']);
     return $mail->send($email, '');
 }
Exemplo n.º 19
0
    public static function runLinkCheck()
    {
        //########################################
        // declare variables
        $results = array();
        $posts = array();
        // get options from Admin CP -> Options -> Link Check -> Limit
        $limit = XenForo_Application::get('options')->linkCheckLimit;
        // get options from Admin CP -> Options -> Link Check -> Offset
        $offset = XenForo_Application::get('options')->linkCheckOffset;
        //########################################
        // exclude forums
        //########################################
        // declare variable
        $whereclause = '';
        // get options from Admin CP -> Options -> Link Check -> Exclude Forums
        $excludeForums = XenForo_Application::get('options')->linkCheckExcludeForums;
        if ($excludeForums != '') {
            // remove trailing comma
            $excludeForums = rtrim($excludeForums, ',');
            $nodeIds = explode(',', $excludeForums);
            // create whereclause1 of excluded forums
            $whereclause = 'AND (xf_thread.node_id <> ' . implode(' AND xf_thread.node_id <> ', $nodeIds);
            $whereclause = $whereclause . ')';
        }
        // get database
        $db = XenForo_Application::get('db');
        // run query
        $results = $db->fetchAll("\n\t\tSELECT xf_post.post_id, \n\t\txf_post.post_date,\n\t\txf_post.message, \n\t\txf_thread.title\n\t\tFROM xf_post\n\t\tINNER JOIN xf_thread ON xf_thread.thread_id = xf_post.thread_id\n\t\tINNER JOIN xf_node ON xf_node.node_id = xf_thread.node_id\n\t\tWHERE xf_post.message LIKE " . XenForo_Db::quoteLike('[URL', 'lr') . "\n\t\t{$whereclause}\n\t\tORDER BY xf_post.post_date DESC\n\t\tLIMIT " . $offset . "," . $limit . "\n\t\t");
        // main loop
        foreach ($results as $result) {
            // define variables
            $currentPostDate = $result['post_date'];
            $currentPostId = $result['post_id'];
            $currentTitle = $result['title'];
            $message = $result['message'];
            $done = '';
            $parsedMessage = '';
            $showStatusCode = '';
            // check for [URL='link'][/URL]
            if (preg_match_all("/\\[URL=\\'(.+?)\\'\\]/i", $message, $out)) {
                for ($i = 0; $i < count($out[1]); $i++) {
                    //########################################
                    // start cURL function
                    //########################################
                    // create a curl handle
                    $ch = curl_init($out[1][$i]);
                    // set options
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_NOBODY, true);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                    // execute curl
                    curl_exec($ch);
                    // get http code
                    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                    // delare variable
                    $show404 = '';
                    // show status code if 404
                    if ($httpcode == 404) {
                        // get headers
                        $headers = @get_headers($out[1][$i]);
                        // get httpcode
                        $httpcode = substr($headers[0], 9, 3);
                        // show status code if 404
                        if ($httpcode == 404) {
                            $show404 = 'yes';
                        }
                    }
                    // close handle
                    curl_close($ch);
                    //########################################
                    // end cURL function
                    //########################################
                    // assign value to posts variable
                    if ($show404 == 'yes') {
                        $posts[] = array('post_date' => $currentPostDate, 'post_id' => $currentPostId, 'title' => $currentTitle, 'status' => $httpcode, 'url' => $out[1][$i]);
                    }
                }
            }
            // clear variables
            $show404 = '';
            unset($out);
            // check for [URL]link[/URL]
            if (preg_match_all("/\\[URL\\](.+?)\\[\\/URL\\]/i", $message, $out)) {
                for ($i = 0; $i < count($out[1]); $i++) {
                    //########################################
                    // start cURL function
                    //########################################
                    // create a curl handle
                    $ch = curl_init($out[1][$i]);
                    // set options
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_NOBODY, true);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                    // execute curl
                    curl_exec($ch);
                    // get http code
                    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                    // delare variable
                    $show404 = '';
                    // show status code if 404
                    if ($httpcode == 404) {
                        // get headers
                        $headers = @get_headers($out[1][$i]);
                        // get httpcode
                        $httpcode = substr($headers[0], 9, 3);
                        // show status code if 404
                        if ($httpcode == 404) {
                            $show404 = 'yes';
                        }
                    }
                    // close handle
                    curl_close($ch);
                    //########################################
                    // end cURL function
                    //########################################
                    // assign values to posts variable
                    if ($show404 == 'yes') {
                        $posts[] = array('post_date' => $currentPostDate, 'post_id' => $currentPostId, 'title' => $currentTitle, 'status' => $httpcode, 'url' => $out[1][$i]);
                    }
                }
            }
        }
        if (count($posts) > 0) {
            //########################################
            // prepare message
            //########################################
            // get options from Admin CP -> Options -> Basic Board Information -> Board Title
            $boardTitle = XenForo_Application::get('options')->boardTitle;
            // get options from Admin CP -> Options -> Link Check -> Language ID
            $languageId = XenForo_Application::get('options')->linkCheckLanguageId;
            // set language
            if ($languageId > 0) {
                XenForo_Phrase::setLanguageId($languageId);
            }
            // get subject
            $subject = new XenForo_Phrase('linkcheck_subject');
            // get postDatePhrase
            $postDatePhrase = new XenForo_Phrase('linkcheck_post_date');
            // get postIdPhrase
            $postIdPhrase = new XenForo_Phrase('linkcheck_post_id');
            // get threadTitlePhrase
            $threadTitlePhrase = new XenForo_Phrase('linkcheck_thread_title');
            // get statusPhrase
            $statusPhrase = new XenForo_Phrase('linkcheck_status');
            // get urlPhrase
            $urlPhrase = new XenForo_Phrase('linkcheck_url');
            // start table
            $message = '
<table cellspacing="5">
<tr>
<th align="left">' . $postDatePhrase . '</th>
<th align="left">' . $postIdPhrase . '</th>
<th align="left">' . $threadTitlePhrase . '</th>
<th align="left">' . $statusPhrase . '</th>
<th align="left">' . $urlPhrase . '</th>
';
            // foreach threads
            foreach ($posts as $post) {
                // format date
                $formatedDate = date("M d Y", $post['post_date']);
                // build link
                $link = XenForo_Link::buildPublicLink('posts', $post);
                // message details
                $message .= '<tr><td>' . $formatedDate . '</td>';
                $message .= '<td>' . '<a href="' . $link . '">' . $post['post_id'] . '</a></td>';
                $message .= '<td>' . $post['title'] . '</td>';
                $message .= '<td>' . $post['status'] . '</td>';
                $message .= '<td>' . '<a href="' . $post['url'] . '">' . $post['url'] . '</a></td></tr>';
            }
            // end table
            $message .= '</tr></table>';
            //########################################
            // prepare mail variables
            //########################################
            // get options from Admin CP -> Options -> Register Email -> Email From Username
            $username = XenForo_Application::get('options')->linkCheckEmailFromUsername;
            // get options from Admin CP -> Options -> Register Email -> Email To
            $emailTo = XenForo_Application::get('options')->linkCheckEmailTo;
            // put into array
            $email = explode(',', $emailTo);
            // subject
            $subject = new XenForo_Phrase('linkcheck_link_check');
            //########################################
            // send mail
            //########################################
            $count = count($email);
            for ($i = 0; $i < $count; $i++) {
                // define user variable
                $user = array('username' => $username, 'email' => $email[$i]);
                // prepare mailParams
                $mailParams = array('user' => $user, 'subject' => $subject, 'message' => $message);
                // prepare mail variable
                $mail = XenForo_Mail::create('linkcheck_contact', $mailParams);
                // send mail
                $mail->queue($user['email'], $user['username']);
            }
        }
    }
Exemplo n.º 20
0
 protected function _sendWelcomeEmail(array $user, array $option)
 {
     $fromName = $option['emailFromName'];
     $fromEmail = $option['emailFromEmail'];
     $title = $option['emailTitle'];
     $format = $option['emailFormat'];
     $body = $option['emailBody'];
     $phraseTitles = XenForo_Helper_String::findPhraseNamesFromStringSimple($title . $body);
     /** @var XenForo_Model_Phrase $phraseModel */
     $phraseModel = $this->getModelFromCache('XenForo_Model_Phrase');
     $phrases = $phraseModel->getPhraseTextFromPhraseTitles($phraseTitles, $user['language_id']);
     foreach ($phraseTitles as $search => $phraseTitle) {
         if (isset($phrases[$phraseTitle])) {
             $title = str_replace($search, $phrases[$phraseTitle], $title);
             $body = str_replace($search, $phrases[$phraseTitle], $body);
         }
     }
     if ($format == 'html') {
         $tokens = array('{name}' => htmlspecialchars($user['username']), '{email}' => htmlspecialchars($user['email']), '{id}' => $user['user_id']);
         $body = strtr($body, $tokens);
         $text = trim(htmlspecialchars_decode(strip_tags($body)));
     } else {
         $tokens = array('{name}' => $user['username'], '{email}' => $user['email'], '{id}' => $user['user_id']);
         $text = strtr($body, $tokens);
         $body = nl2br(htmlspecialchars($text));
     }
     $mail = XenForo_Mail::create('welcome_email', array('title' => $title, 'htmlBody' => $body, 'textBody' => $text), $user['language_id']);
     return $mail->queue($user['email'], $user['username'], array(), $fromEmail, $fromName);
 }
Exemplo n.º 21
0
 /**
  * Resets the specified user's password and emails the password to them if requested.
  *
  * @param integer $userId
  * @param boolean $sendEmail
  *
  * @return string New password
  */
 public function resetPassword($userId, $sendEmail = true)
 {
     $dw = XenForo_DataWriter::create('XenForo_DataWriter_User');
     $dw->setExistingData($userId);
     $password = XenForo_Application::generateRandomString(8);
     $password = strtr($password, array('I' => 'i', 'l' => 'L', '0' => 'O', 'o' => 'O'));
     $password = trim($password, '_-');
     $auth = XenForo_Authentication_Abstract::createDefault();
     $dw->set('scheme_class', $auth->getClassName());
     $dw->set('data', $auth->generate($password));
     $dw->save();
     $user = $dw->getMergedData();
     if ($sendEmail) {
         $params = array('user' => $user, 'password' => $password, 'boardTitle' => XenForo_Application::get('options')->boardTitle, 'boardUrl' => XenForo_Application::get('options')->boardUrl);
         $mail = XenForo_Mail::create('user_lost_password_reset', $params, $user['language_id']);
         $mail->send($user['email'], $user['username']);
     }
     return $password;
 }
Exemplo n.º 22
0
 /**
  *
  * @see XenForo_ControllerPublic_Member::actionWarn()
  */
 public function actionWarn()
 {
     $xenOptions = XenForo_Application::get('options');
     /* @var $warningModel XenForo_Model_Warning */
     $warningModel = $this->getModelFromCache('XenForo_Model_Warning');
     $fill = $this->_input->filterSingle('fill', XenForo_Input::UINT);
     if ($fill) {
         $choice = $this->_input->filterSingle('choice', XenForo_Input::UINT);
         if (!$choice) {
             $userId = $this->_input->filterSingle('user_id', XenForo_Input::UINT);
             $user = $this->getHelper('UserProfile')->getUserOrError($userId);
             $visitor = XenForo_Visitor::getInstance();
             $contentInput = $this->_input->filter(array('content_type' => XenForo_Input::STRING, 'content_id' => XenForo_Input::UINT));
             if (!$contentInput['content_type']) {
                 $contentInput['content_type'] = 'user';
                 $contentInput['content_id'] = $user['user_id'];
             }
             /* @var $warningModel XenForo_Model_Warning */
             $warningModel = $this->getModelFromCache('XenForo_Model_Warning');
             $warningHandler = $warningModel->getWarningHandler($contentInput['content_type']);
             if (!$warningHandler) {
                 return $this->responseNoPermission();
             }
             $content = $warningHandler->getContent($contentInput['content_id']);
             if (!$content || !$warningHandler->canView($content) || !$warningHandler->canWarn($user['user_id'], $content)) {
                 return $this->responseNoPermission();
             }
             $contentTitle = $warningHandler->getContentTitle($content);
             $contentDetails = $warningHandler->getContentDetails($content);
             $warning = array('warning_definition_id' => 0, 'points_default' => $xenOptions->th_customPointsDefault_warnings, 'expiry_type' => $xenOptions->th_customExpiry_warnings['type'], 'expiry_default' => !empty($xenOptions->th_customExpiry_warnings['default']) ? $xenOptions->th_customExpiry_warnings['default'] : '', 'extra_user_group_ids' => '', 'is_editable' => 1, 'title' => '');
             $conversationTitle = new XenForo_Phrase($warningModel->getWarningDefinitionConversationTitlePhraseName(0));
             $conversationMessage = new XenForo_Phrase($warningModel->getWarningDefinitionConversationTextPhraseName(0));
             $replyMessage = new XenForo_Phrase($warningModel->getWarningDefinitionReplyTextPhraseName(0));
             $replace = array('{title}' => $contentTitle, '{content}' => $contentDetails, '{url}' => $warningHandler->getContentUrl($content, true), '{name}' => $user['username'], '{staff}' => $visitor['username']);
             $warning['conversationTitle'] = strtr((string) $conversationTitle, $replace);
             $warning['conversationMessage'] = strtr((string) $conversationMessage, $replace);
             $warning['replyMessage'] = strtr((string) $replyMessage, $replace);
             return $this->responseView('XenForo_ViewPublic_Member_WarnFill', '', array('warning' => $warning));
         }
     }
     $GLOBALS['XenForo_ControllerPublic_Member'] = $this;
     $response = parent::actionWarn();
     if ($response instanceof XenForo_ControllerResponse_View) {
         if ($fill) {
             $userId = $this->_input->filterSingle('user_id', XenForo_Input::UINT);
             $user = $this->getHelper('UserProfile')->getUserOrError($userId);
             $visitor = XenForo_Visitor::getInstance();
             $contentInput = $this->_input->filter(array('content_type' => XenForo_Input::STRING, 'content_id' => XenForo_Input::UINT));
             if (!$contentInput['content_type']) {
                 $contentInput['content_type'] = 'user';
                 $contentInput['content_id'] = $user['user_id'];
             }
             /* @var $warningModel XenForo_Model_Warning */
             $warningModel = $this->getModelFromCache('XenForo_Model_Warning');
             $warningHandler = $warningModel->getWarningHandler($contentInput['content_type']);
             if (!$warningHandler) {
                 return $this->responseNoPermission();
             }
             $content = $warningHandler->getContent($contentInput['content_id']);
             if (!$content || !$warningHandler->canView($content) || !$warningHandler->canWarn($user['user_id'], $content)) {
                 return $this->responseNoPermission();
             }
             $contentTitle = $warningHandler->getContentTitle($content);
             $contentDetails = $warningHandler->getContentDetails($content);
             $warningDefinitionId = $response->params['warning']['warning_definition_id'];
             $replyMessagePhraseName = $warningModel->getWarningDefinitionReplyTextPhraseName($warningDefinitionId);
             $replyMessage = new XenForo_Phrase($replyMessagePhraseName);
             // TODO should probably create blank phrases on installation?
             if ($replyMessage == $replyMessagePhraseName) {
                 $replyMessage = '';
             }
             $replace = array('{title}' => $contentTitle, '{content}' => $contentDetails, '{url}' => $warningHandler->getContentUrl($content, true), '{name}' => $user['username'], '{staff}' => $visitor['username']);
             $response->params['warning']['replyMessage'] = strtr((string) $replyMessage, $replace);
         } elseif (!empty($response->params['contentType'])) {
             $contentType = $response->params['contentType'];
             if ($contentType == 'post' || $contentType == 'profile_post') {
                 if ($xenOptions->th_warnings_allowReplyToContent) {
                     $response->params['canReplyToContent'] = true;
                     if ($contentType == 'post') {
                         $response->params['canLockContent'] = true;
                     }
                 }
             }
         }
     } elseif ($response instanceof XenForo_ControllerResponse_Redirect) {
         if ($this->_request->isPost()) {
             if ($xenOptions->th_warnings_sendEmail) {
                 $userId = $this->_input->filterSingle('user_id', XenForo_Input::UINT);
                 $user = $this->getHelper('UserProfile')->getUserOrError($userId);
                 $emailInput = $this->_input->filter(array('conversation_title' => XenForo_Input::STRING, 'conversation_message' => XenForo_Input::STRING));
                 if ($emailInput['conversation_title'] && $emailInput['conversation_message']) {
                     $visitor = XenForo_Visitor::getInstance();
                     $bbCodeParserText = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('Text'));
                     $messageInfo['messageText'] = new XenForo_BbCode_TextWrapper($emailInput['conversation_message'], $bbCodeParserText);
                     $bbCodeParserHtml = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('HtmlEmail'));
                     $messageInfo['messageHtml'] = new XenForo_BbCode_TextWrapper($emailInput['conversation_message'], $bbCodeParserHtml);
                     $mail = XenForo_Mail::create('th_warning_warnings', array('title' => $emailInput['conversation_title'], 'message' => $messageInfo), $user['language_id']);
                     $mail->enableAllLanguagePreCache();
                     $mail->queue($user['email'], $user['username']);
                 }
             }
         }
     }
     return $response;
 }
Exemplo n.º 23
0
 protected function _checkSpam($spam_check, $options)
 {
     require_once 'CleanTalk/Base/cleantalk.class.php';
     $ct_authkey = $options->get('cleantalk', 'apikey');
     $dataRegistryModel = $this->getModelFromCache('XenForo_Model_DataRegistry');
     $ct_ws = $dataRegistryModel->get('cleantalk_ws');
     if (!$ct_ws) {
         $ct_ws = array('work_url' => 'http://moderate.cleantalk.ru', 'server_url' => 'http://moderate.cleantalk.ru', 'server_ttl' => 0, 'server_changed' => 0);
     }
     $field_name = CleanTalk_Base_CleanTalk::getCheckjsName();
     if (!isset($_COOKIE[$field_name])) {
         $checkjs = NULL;
     } elseif (in_array($_COOKIE[$field_name], CleanTalk_Base_CleanTalk::getCheckJSArray())) {
         $checkjs = 1;
     } else {
         $checkjs = 0;
     }
     $user_agent = $_SERVER['HTTP_USER_AGENT'];
     $refferrer = $_SERVER['HTTP_REFERER'];
     $ct = new Cleantalk();
     $ct->work_url = $ct_ws['work_url'];
     $ct->server_url = $ct_ws['server_url'];
     $ct->server_ttl = $ct_ws['server_ttl'];
     $ct->server_changed = $ct_ws['server_changed'];
     $options = XenForo_Application::getOptions();
     $ct_options = array('enabled' => $options->get('cleantalk', 'enabled'), 'apikey' => $options->get('cleantalk', 'apikey'));
     $sender_info = json_encode(array('cms_lang' => 'en', 'REFFERRER' => $refferrer, 'post_url' => $refferrer, 'USER_AGENT' => $user_agent, 'ct_options' => json_encode($ct_options)));
     $ct_request = new CleantalkRequest();
     $ct_request->auth_key = $ct_authkey;
     $ct_request->agent = 'xenforo-15';
     $ct_request->response_lang = 'en';
     $ct_request->js_on = $checkjs;
     $ct_request->sender_info = $sender_info;
     $ct_request->sender_email = $spam_check['sender_email'];
     $ct_request->sender_nickname = $spam_check['sender_nickname'];
     $ct_request->sender_ip = $ct->ct_session_ip($_SERVER['REMOTE_ADDR']);
     $ct_submit_time = NULL;
     //	session_start();
     switch ($spam_check['type']) {
         case 'comment':
             $stored_time = XenForo_Application::getSession()->get('ct_submit_comment_time');
             if (isset($stored_time)) {
                 $ct_submit_time = time() - $stored_time;
             }
             $timelabels_key = 'e_comm';
             $ct_request->submit_time = $ct_submit_time;
             $ct_request->message = $spam_check['message_title'] . " \n\n" . $spam_check['message_body'];
             $example = '';
             $a_example = array();
             $a_example['title'] = $spam_check['example_title'];
             $a_example['body'] = $spam_check['example_body'];
             $a_example['comments'] = $spam_check['example_comments'];
             // Additional info.
             $post_info = '';
             $a_post_info['comment_type'] = 'comment';
             // JSON format.
             $example = json_encode($a_example);
             $post_info = json_encode($a_post_info);
             // Plain text format.
             if ($example === FALSE) {
                 $example = '';
                 $example .= $a_example['title'] . " \n\n";
                 $example .= $a_example['body'] . " \n\n";
                 $example .= $a_example['comments'];
             }
             if ($post_info === FALSE) {
                 $post_info = '';
             }
             // Example text + last N comments in json or plain text format.
             $ct_request->example = $example;
             $ct_request->post_info = $post_info;
             $ct_result = $ct->isAllowMessage($ct_request);
             break;
         case 'register':
             $stored_time = XenForo_Application::getSession()->get('ct_submit_register_time');
             if (isset($stored_time)) {
                 $ct_submit_time = time() - $stored_time;
             }
             $timelabels_key = 'e_reg';
             $ct_request->submit_time = $ct_submit_time;
             $ct_request->tz = $spam_check['timezone'];
             $ct_result = $ct->isAllowUser($ct_request);
             break;
     }
     $ret_val = array();
     $ret_val['ct_request_id'] = $ct_result->id;
     if ($ct->server_change) {
         $dataRegistryModel->set('cleantalk_ws', array('work_url' => $ct->work_url, 'server_url' => $ct->server_url, 'server_ttl' => $ct->server_ttl, 'server_changed' => time()));
     }
     // First check errstr flag.
     if (!empty($ct_result->errstr) || !empty($ct_result->inactive) && $ct_result->inactive == 1) {
         // Cleantalk error so we go default way (no action at all).
         $ret_val['errno'] = 1;
         // Just inform admin.
         //$err_title = $_SERVER['SERVER_NAME'] . ' - CleanTalk hook error';
         if (!empty($ct_result->errstr)) {
             $ret_val['errstr'] = $this->_filterResponse($ct_result->errstr);
         } else {
             $ret_val['errstr'] = $this->_filterResponse($ct_result->comment);
         }
         $send_flag = FALSE;
         $ct_time = $dataRegistryModel->get('cleantalk_' . $timelabels_key);
         if (!$ct_time) {
             $send_flag = TRUE;
         } elseif (time() - 900 > $ct_time[0]) {
             // 15 minutes.
             $send_flag = TRUE;
         }
         if ($send_flag) {
             $dataRegistryModel->set('cleantalk_' . $timelabels_key, array(time()));
             $mail = XenForo_Mail::create('cleantalk_error', array('plainText' => $ret_val['errstr'], 'htmlText' => nl2br($ret_val['errstr'])));
             $mail->send($options->get('contactEmailAddress'));
         }
         return $ret_val;
     }
     $ret_val['errno'] = 0;
     if ($ct_result->allow == 1) {
         // Not spammer.
         $ret_val['allow'] = 1;
         /*
         	    // Store request_id in globals to store it in DB later.
         	    _cleantalk_ct_result('set', $ct_result->id);
         	    // Don't store 'ct_result_comment', means good comment.
         */
     } else {
         // Spammer.
         $ret_val['allow'] = 0;
         $ret_val['ct_result_comment'] = $this->_filterResponse($ct_result->comment);
         // Check stop_queue flag.
         if ($spam_check['type'] == 'comment' && $ct_result->stop_queue == 0) {
             // Spammer and stop_queue == 0 - to manual approvement.
             $ret_val['stop_queue'] = 0;
             /*
             	      // Store request_id and comment in static to store them in DB later.
             	      // Store 'ct_result_comment' - means bad comment.
             	      _cleantalk_ct_result('set', $ct_result->id, $ret_val['ct_result_comment']);
             */
         } else {
             // New user or Spammer and stop_queue == 1 - display form error message.
             $ret_val['stop_queue'] = 1;
         }
     }
     return $ret_val;
 }
Exemplo n.º 24
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);
 }
Exemplo n.º 25
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);
             }
         }
     }
 }
Exemplo n.º 26
0
 public function sendNotificationToWatchUsersOnMediaInsert(array $media, array $category = null)
 {
     if ($media['media_state'] != 'visible') {
         return array();
     }
     /* @var $userModel XenForo_Model_User */
     $userModel = $this->getModelFromCache('XenForo_Model_User');
     $categoryModel = $this->_getCategoryModel();
     if (!$category) {
         $category = $categoryModel->getCategoryById($media['category_id'], array());
     }
     $media['titleCensored'] = XenForo_Helper_String::censorString($media['media_title']);
     $media['descCensored'] = XenForo_Helper_String::censorString($media['media_description']);
     $category['titleCensored'] = XenForo_Helper_String::censorString($category['category_title']);
     $category['descCensored'] = XenForo_Helper_String::censorString($category['category_description']);
     // fetch a full user record if we don't have one already
     if (!isset($media['avatar_width']) || !isset($media['custom_title'])) {
         $mediaUser = $this->getModelFromCache('XenForo_Model_User')->getUserById($media['user_id']);
         if ($mediaUser) {
             $media = array_merge($mediaUser, $media);
         } else {
             $media['avatar_width'] = 0;
             $media['custom_title'] = '';
         }
     }
     $alerted = array();
     $emailed = array();
     $users = $this->getUsersWatchingCategory($category, 'media');
     foreach ($users as $user) {
         if ($user['user_id'] == $media['user_id']) {
             continue;
         }
         if ($userModel->isUserIgnored($user, $media['user_id'])) {
             continue;
         }
         $user['permissions'] = XenForo_Permission::unserializePermissions($user['global_permission_cache']);
         if (!$categoryModel->canViewCategory($category, $null, $user)) {
             continue;
         }
         if (isset(self::$_preventDoubleNotify[$category['category_id']][$user['user_id']])) {
             continue;
         }
         self::$_preventDoubleNotify[$category['category_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_category_media_insert', array('media' => $media, 'category' => $category, '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'], $media['user_id'], $media['username'], 'xengallery_media', $media['media_id'], 'watch_insert');
             $alerted[] = $user['user_id'];
         }
     }
     return array('emailed' => $emailed, 'alerted' => $alerted);
 }
Exemplo n.º 27
0
 public function sendNotificationToWatchUsersOnTagged($tag, array $contentData = array(), array $contentPermissionConfig = array())
 {
     $userModel = $this->getModelFromCache('XenForo_Model_User');
     list($noEmail, $noAlert) = Tinhte_XenTag_Integration::getNoEmailAndAlert($contentData['content_type'], $contentData['content_id']);
     $emailed = array();
     $alerted = array();
     $emailTemplate = 'tinhte_xentag_watch_tag_' . $contentData['content_type'];
     if (XenForo_Application::get('options')->emailWatchedThreadIncludeMessage) {
         $parseBbCode = true;
     } else {
         $parseBbCode = false;
     }
     // fetch a full user record if we don't have one already
     if (!isset($contentData['avatar_width']) or !isset($contentData['custom_title'])) {
         $contentUser = $userModel->getUserById($contentData['user_id']);
         if ($contentUser) {
             $contentData = array_merge($contentUser, $contentData);
         } else {
             $contentData['avatar_width'] = 0;
             $contentData['custom_title'] = '';
         }
     }
     if (!empty($contentPermissionConfig['content_type']) and !empty($contentPermissionConfig['content_id'])) {
         $users = $this->getUsersWatchingTag($tag['tag_id'], $contentPermissionConfig['content_type'], $contentPermissionConfig['content_id']);
     } else {
         $users = $this->getUsersWatchingTag($tag['tag_id']);
     }
     foreach ($users as $user) {
         if ($user['user_id'] == $contentData['user_id']) {
             // self notification? That's silly
             continue;
         }
         if ($userModel->isUserIgnored($user, $contentData['user_id'])) {
             continue;
         }
         $globalPermissions = XenForo_Permission::unserializePermissions($user['global_permission_cache']);
         if (!XenForo_Permission::hasPermission($globalPermissions, 'general', Tinhte_XenTag_Constants::PERM_USER_WATCH)) {
             // no tag watch permission (or revoked)
             continue;
         }
         if (!empty($contentPermissionConfig['content_type']) and !empty($contentPermissionConfig['content_id']) and !empty($contentPermissionConfig['permissions'])) {
             $contentPermissions = XenForo_Permission::unserializePermissions($user['content_permission_cache']);
             $contentPermissionFound = true;
             foreach ($contentPermissionConfig['permissions'] as $contentPermissionRequired) {
                 if (!XenForo_Permission::hasContentPermission($contentPermissions, $contentPermissionRequired)) {
                     $contentPermissionFound = false;
                 }
             }
             if (!$contentPermissionFound) {
                 // no content permission
                 continue;
             }
         }
         if ($user['send_email'] and $user['email'] and $user['user_state'] == 'valid' and !in_array($user['user_id'], $noEmail)) {
             if (!empty($contentData['message']) and !isset($contentData['messageText']) and $parseBbCode) {
                 $bbCodeParserText = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('Text'));
                 $contentData['messageText'] = new XenForo_BbCode_TextWrapper($contentData['message'], $bbCodeParserText);
                 $bbCodeParserHtml = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('HtmlEmail'));
                 $contentData['messageHtml'] = new XenForo_BbCode_TextWrapper($contentData['message'], $bbCodeParserHtml);
             }
             if (!empty($contentData['title']) and !isset($contentData['titleCensored'])) {
                 $contentData['titleCensored'] = XenForo_Helper_String::censorString($contentData['title']);
             }
             $user['email_confirm_key'] = $userModel->getUserEmailConfirmKey($user);
             $mail = XenForo_Mail::create($emailTemplate, array('tag' => $tag, 'contentType' => $contentData['content_type'], 'contentId' => $contentData['content_id'], 'contentData' => $contentData, 'receiver' => $user), $user['language_id']);
             $mail->enableAllLanguagePreCache();
             $mail->queue($user['email'], $user['username']);
             $emailed[] = $user['user_id'];
         }
         if ($user['send_alert'] and !in_array($user['user_id'], $noAlert)) {
             call_user_func_array(array('XenForo_Model_Alert', 'alert'), array($user['user_id'], $contentData['user_id'], $contentData['username'], $contentData['content_type'], $contentData['content_id'], 'tinhte_xentag_tag_watch', array('tag' => $tag)));
             $alerted[] = $user['user_id'];
         }
     }
     Tinhte_XenTag_Integration::updateNoEmailAndAlert($contentData['content_type'], $contentData['content_id'], $emailed, $alerted);
 }
Exemplo n.º 28
0
 public function sendNotificationsToUser(array $post, array $team = null, array $noAlerts = array())
 {
     if ($post['message_state'] != 'visible') {
         return array();
     }
     if (!$team) {
         $team = $this->_getTeamModel()->getFullTeamById($post['team_id'], array('join' => Nobita_Teams_Model_Team::FETCH_CATEGORY));
     }
     if (!$team || $team['team_state'] != 'visible') {
         return array();
     }
     if (XenForo_Application::get('options')->emailWatchedThreadIncludeMessage) {
         $parseBbCode = true;
         $emailTemplate = 'Team_user_watched_team_messagetext';
     } else {
         $parseBbCode = false;
         $emailTemplate = 'Team_user_watched_team';
     }
     $userModel = $this->getModelFromCache('XenForo_Model_User');
     $memberModel = $this->getModelFromCache('Nobita_Teams_Model_Member');
     $conditions = array('member_state' => 'accept', 'alert' => 1);
     $usersWatch = $memberModel->getAllMembersInTeam($team['team_id'], $conditions, array('join' => Nobita_Teams_Model_Member::FETCH_USER | Nobita_Teams_Model_Member::FETCH_USER_PERMISSIONS));
     // fetch a full user record if we don't have one already
     if (!isset($post['avatar_width']) || !isset($post['custom_title'])) {
         $replyUser = $this->getModelFromCache('XenForo_Model_User')->getUserById($post['user_id']);
         if ($replyUser) {
             $post = array_merge($replyUser, $post);
         } else {
             $post['avatar_width'] = 0;
             $post['custom_title'] = '';
         }
     }
     $alerted = array();
     $emailed = array();
     foreach ($usersWatch as $user) {
         $user['permissions'] = XenForo_Permission::unserializePermissions($user['global_permission_cache']);
         if ($user['user_id'] == $post['user_id']) {
             continue;
         }
         if ($userModel->isUserIgnored($user, $post['user_id'])) {
             continue;
         }
         if (!$this->_getTeamModel()->canViewTeamAndContainer($team, $team, $null, $user)) {
             continue;
         }
         if (isset(self::$_preventDoubleNotify[$team['team_id']][$user['user_id']])) {
             continue;
         }
         self::$_preventDoubleNotify[$team['team_id']][$user['user_id']] = true;
         if ($user['email'] && $user['user_state'] == 'valid' && $user['send_email']) {
             if (!isset($post['messageText']) && $parseBbCode) {
                 $bbCodeParserText = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('Text'));
                 $post['messageText'] = new XenForo_BbCode_TextWrapper($post['message'], $bbCodeParserText);
                 $bbCodeParserHtml = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('HtmlEmail'));
                 $post['messageHtml'] = new XenForo_BbCode_TextWrapper($post['message'], $bbCodeParserHtml);
             }
             if (!isset($team['titleCensored'])) {
                 $team['titleCensored'] = XenForo_Helper_String::censorString($team['title']);
             }
             $user['email_confirm_key'] = $userModel->getUserEmailConfirmKey($user);
             $mail = XenForo_Mail::create($emailTemplate, array('post' => $post, 'team' => $team, 'category' => $team, 'receiver' => $user), $user['language_id']);
             $mail->enableAllLanguagePreCache();
             $mail->queue($user['email'], $user['username']);
             $emailed[] = $user['user_id'];
         }
         if (!in_array($user['user_id'], $noAlerts) && $user['send_alert']) {
             if (XenForo_Model_Alert::userReceivesAlert($user, 'team_post', 'insert')) {
                 XenForo_Model_Alert::alert($user['user_id'], $post['user_id'], $post['username'], 'team_post', $post['post_id'], 'insert');
                 $alerted[$user['user_id']] = true;
             }
         }
     }
     return array('emailed' => $emailed, 'alerted' => $alerted);
 }
Exemplo 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);
 }
Exemplo n.º 30
0
 /**
  * Send a notification to the users watching the team.
  *
  * @param array $team Info about the team 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 sendNotificationToWatchUsers(array $team, array $noAlerts = array(), array $noEmail = array())
 {
     if ($team['team_state'] != 'visible' || $team['privacy_state'] == 'secret') {
         return array();
     }
     $teamModel = $this->_getTeamModel();
     $userModel = $this->getModelFromCache('XenForo_Model_User');
     if (XenForo_Application::get('options')->emailWatchedThreadIncludeMessage) {
         $parseBbCode = true;
         $emailTemplate = 'Team_watched_team_category_messagetext';
     } else {
         $parseBbCode = false;
         $emailTemplate = 'Team_watched_team_category';
     }
     $teamUser = $userModel->getUserById($team['user_id']);
     if (!$teamUser) {
         $teamUser = $userModel->getVisitingGuestUser();
     }
     if (!empty($team['category_breadcrumb'])) {
         $category = $team;
     } else {
         $category = $this->_getCategoryModel()->getCategoryById($team['team_category_id']);
         if (!$category) {
             return array();
         }
     }
     $alerted = array();
     $emailed = array();
     $users = $this->getUsersWatchingCategory($category);
     foreach ($users as $user) {
         if ($user['user_id'] == $team['user_id']) {
             continue;
         }
         $user['permissions'] = XenForo_Permission::unserializePermissions($user['global_permission_cache']);
         if (!$teamModel->canViewTeamAndContainer($team, $category, $null, $user)) {
             continue;
         }
         if ($user['send_email'] && !in_array($user['user_id'], $noEmail) && $user['email'] && $user['user_state'] == 'valid') {
             if (!isset($team['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'));
                 $team['aboutHtml'] = new XenForo_BbCode_TextWrapper($team['about'], $bbCodeParserHtml);
             }
             if (!isset($team['titleCensored'])) {
                 $team['titleCensored'] = XenForo_Helper_String::censorString($team['title']);
                 #$update['titleCensored'] = XenForo_Helper_String::censorString($update['title']);
             }
             $user['email_confirm_key'] = $userModel->getUserEmailConfirmKey($user);
             $mail = XenForo_Mail::create($emailTemplate, array('team' => $team, 'category' => $category, 'teamUser' => $teamUser, 'receiver' => $user), $user['language_id']);
             $mail->enableAllLanguagePreCache();
             $mail->queue($user['email'], $user['username']);
             $emailed[] = $user['user_id'];
             $noEmail[] = $user['user_id'];
         }
         if ($user['send_alert'] && !in_array($user['user_id'], $noAlerts)) {
             XenForo_Model_Alert::alert($user['user_id'], $team['user_id'], $team['username'], 'team', $team['team_id'], 'insert');
             $alerted[] = $user['user_id'];
             $noAlerts[] = $user['user_id'];
         }
     }
     return array('emailed' => $emailed, 'alerted' => $alerted);
 }