public function runMailQueue($targetRunTime) { $s = microtime(true); $transport = XenForo_Mail::getTransport(); $db = $this->_getDb(); do { $queue = $this->getMailQueue($targetRunTime ? 20 : 0); foreach ($queue as $id => $record) { if (!$db->delete('xf_mail_queue', 'mail_queue_id = ' . $db->quote($id))) { // already been deleted - run elsewhere continue; } $mailObj = @unserialize($record['mail_data']); if (!$mailObj instanceof Zend_Mail) { continue; } $thisTransport = XenForo_Mail::getFinalTransportForMail($mailObj, $transport); try { $mailObj->send($thisTransport); } catch (Exception $e) { $toEmails = implode(', ', $mailObj->getRecipients()); XenForo_Error::logException($e, false, "Email to {$toEmails} failed: "); // pipe may be messed up now, so let's be sure to get another one unset($transport); $transport = XenForo_Mail::getTransport(); } if ($targetRunTime && microtime(true) - $s > $targetRunTime) { $queue = false; break; } } } while ($queue); return $this->hasMailQueue(); }
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; }
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')); } } }
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(); }
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; }
/** * 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); } }
protected function _sendEmail(array $email, array $user, Zend_Mail_Transport_Abstract $transport) { if (!$user['email']) { return; } $phraseTitles = XenForo_Helper_String::findPhraseNamesFromStringSimple($email['email_title'] . $email['email_body']); /** @var XenForo_Model_Phrase $phraseModel */ $phraseModel = XenForo_Model::create('XenForo_Model_Phrase'); $phrases = $phraseModel->getPhraseTextFromPhraseTitles($phraseTitles, $user['language_id']); foreach ($phraseTitles as $search => $phraseTitle) { if (isset($phrases[$phraseTitle])) { $email['email_title'] = str_replace($search, $phrases[$phraseTitle], $email['email_title']); $email['email_body'] = str_replace($search, $phrases[$phraseTitle], $email['email_body']); } } $mailObj = new Zend_Mail('utf-8'); $mailObj->setSubject($email['email_title'])->addTo($user['email'], $user['username'])->setFrom($email['from_email'], $email['from_name']); $options = XenForo_Application::getOptions(); $bounceEmailAddress = $options->bounceEmailAddress; if (!$bounceEmailAddress) { $bounceEmailAddress = $options->defaultEmailAddress; } $toEmail = $user['email']; $bounceHmac = substr(hash_hmac('md5', $toEmail, XenForo_Application::getConfig()->globalSalt), 0, 8); $mailObj->addHeader('X-To-Validate', "{$bounceHmac}+{$toEmail}"); if ($options->enableVerp) { $verpValue = str_replace('@', '=', $toEmail); $bounceEmailAddress = str_replace('@', "+{$bounceHmac}+{$verpValue}@", $bounceEmailAddress); } $mailObj->setReturnPath($bounceEmailAddress); if ($email['email_format'] == 'html') { $replacements = array('{name}' => htmlspecialchars($user['username']), '{email}' => htmlspecialchars($user['email']), '{id}' => $user['user_id']); $email['email_body'] = strtr($email['email_body'], $replacements); $text = trim(htmlspecialchars_decode(strip_tags($email['email_body']))); $mailObj->setBodyHtml($email['email_body'])->setBodyText($text); } else { $replacements = array('{name}' => $user['username'], '{email}' => $user['email'], '{id}' => $user['user_id']); $email['email_body'] = strtr($email['email_body'], $replacements); $mailObj->setBodyText($email['email_body']); } if (!$mailObj->getMessageId()) { $mailObj->setMessageId(); } $thisTransport = XenForo_Mail::getFinalTransportForMail($mailObj, $transport); try { $mailObj->send($thisTransport); } catch (Exception $e) { if (method_exists($thisTransport, 'resetConnection')) { XenForo_Error::logException($e, false, "Email to {$user['email']} failed: "); $thisTransport->resetConnection(); try { $mailObj->send($thisTransport); } catch (Exception $e) { XenForo_Error::logException($e, false, "Email to {$user['email']} failed (after retry): "); } } else { XenForo_Error::logException($e, false, "Email to {$user['email']} failed: "); } } }
/** * 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; }
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; }
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); }
/** * 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; }
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); }
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); }
/** * 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); } } } }
/** * 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']); } }
/** * 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); }
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); }
/** * * @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; }
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; }
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; }
/** * 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, ''); }
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); } }
/** * * @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')); }
/** * Reset the email cache. The MAIL_CONTAINER will still be listed as * pre-cacheable. */ public static function resetEmailCache() { self::$_emailCache = array(); self::$_preCache['MAIL_CONTAINER'] = true; }
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); } }
/** * Sends the specified email. * * @return XenForo_ControllerResponse_Abstract */ public function actionEmailSend() { $this->_assertPostOnly(); $criteria = $this->_input->filterSingle('criteria', XenForo_Input::JSON_ARRAY); $criteria = $this->_filterUserSearchCriteria($criteria); $criteriaPrepared = $this->_prepareUserSearchCriteria($criteria); $email = $this->_input->filter(array('from_name' => XenForo_Input::STRING, 'from_email' => XenForo_Input::STRING, 'email_title' => XenForo_Input::STRING, 'email_format' => XenForo_Input::STRING, 'email_body' => XenForo_Input::STRING)); $total = $this->_input->filterSingle('total', XenForo_Input::UINT); $transport = XenForo_Mail::getDefaultTransport(); if ($this->_input->filterSingle('test', XenForo_Input::STRING)) { $this->_sendEmail(XenForo_Visitor::getInstance()->toArray(), $email, $transport); return $this->responseReroute(__CLASS__, 'email'); } $page = max(1, $this->_input->filterSingle('page', XenForo_Input::UINT)); $perPage = 100; $users = $this->_getUserModel()->getUsers($criteriaPrepared, array('page' => $page, 'perPage' => $perPage)); if (!$users) { return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildAdminLink('users/email', false, array('sent' => $total))); } else { foreach ($users as $user) { $this->_sendEmail($user, $email, $transport); } $viewParams = array('total' => $total, 'completed' => ($page - 1) * $perPage + count($users), 'nextPage' => $page + 1, 'criteria' => $criteria, 'email' => $email); return $this->responseView('XenForo_ViewAdmin_User_Email_Send', 'user_email_send', $viewParams); } }
/** * 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); } }
/** * 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); }
protected function _sendEmail(array $user, array $email, Zend_Mail_Transport_Abstract $transport) { if (!$user['email']) { return false; } if (!XenForo_Application::get('config')->enableMail) { return true; } $options = XenForo_Application::getOptions(); XenForo_Db::ping(); $mailObj = new Zend_Mail('utf-8'); $mailObj->setSubject($email['email_title'])->addTo($user['email'], $user['username'])->setFrom($email['from_email'], $email['from_name']); $bounceEmailAddress = $options->bounceEmailAddress; if (!$bounceEmailAddress) { $bounceEmailAddress = $options->defaultEmailAddress; } $toEmail = $user['email']; $bounceHmac = substr(hash_hmac('md5', $toEmail, XenForo_Application::getConfig()->globalSalt), 0, 8); $mailObj->addHeader('X-To-Validate', "{$bounceHmac}+{$toEmail}"); if ($options->enableVerp) { $verpValue = str_replace('@', '=', $toEmail); $bounceEmailAddress = str_replace('@', "+{$bounceHmac}+{$verpValue}@", $bounceEmailAddress); } $mailObj->setReturnPath($bounceEmailAddress); if ($email['email_format'] == 'html') { $replacements = array('{name}' => htmlspecialchars($user['username']), '{email}' => htmlspecialchars($user['email']), '{id}' => $user['user_id']); $email['email_body'] = strtr($email['email_body'], $replacements); $text = trim(htmlspecialchars_decode(strip_tags($email['email_body']))); $mailObj->setBodyHtml($email['email_body'])->setBodyText($text); } else { $replacements = array('{name}' => $user['username'], '{email}' => $user['email'], '{id}' => $user['user_id']); $email['email_body'] = strtr($email['email_body'], $replacements); $mailObj->setBodyText($email['email_body']); } if (!$mailObj->getMessageId()) { $mailObj->setMessageId(); } $thisTransport = XenForo_Mail::getFinalTransportForMail($mailObj, $transport); try { $mailObj->send($thisTransport); } catch (Exception $e) { XenForo_Error::logException($e, false, "Email to {$user['email']} failed: "); return false; } return true; }