/**
  * Sends a reminder mail to definined member groups.
  */
 public function sendReminderMail()
 {
     // first check if required extension 'associategroups' is installed
     if (!in_array('associategroups', $this->Config->getActiveModules())) {
         $this->log('RscNewsletterReminder: Extension "associategroups" is required!', 'RscNewsletterReminder sendReminderMail()', TL_ERROR);
         return false;
     }
     $this->loadLanguageFile("tl_settings");
     if ($this->timeleadReached()) {
         $objEmail = new \Email();
         $objEmail->logFile = 'RscNewsletterReminderEmail.log';
         $objEmail->from = $GLOBALS['TL_CONFIG']['rscNewsletterReminderEmailSenderAddress'];
         $objEmail->fromName = strlen($GLOBALS['TL_CONFIG']['rscNewsletterReminderEmailSenderName']) > 0 ? $GLOBALS['TL_CONFIG']['rscNewsletterReminderEmailSenderName'] : $GLOBALS['TL_CONFIG']['websiteTitle'];
         $objEmail->subject = $this->replaceEmailInsertTags($GLOBALS['TL_CONFIG']['rscNewsletterReminderEmailSubject']);
         $objEmail->html = $this->replaceEmailInsertTags($GLOBALS['TL_CONFIG']['rscNewsletterReminderEmailContent']);
         $objEmail->text = $this->transformEmailHtmlToText($objEmail->html);
         try {
             $objEmail->sendTo($this->getReceiverEmails());
             $this->log('Monthly sending newsletter reminder finished successfully.', 'RscNewsletterReminder sendReminderMail()', TL_CRON);
             return true;
         } catch (Swift_RfcComplianceException $e) {
             $this->log("Mail could not be send: " . $e->getMessage(), "RscNewsletterReminder sendReminderMail()", TL_ERROR);
             return false;
         }
     }
     return true;
 }
Exemplo n.º 2
0
 public function sendEmail($subject, $body)
 {
     $email = $this->email;
     $e = new Email();
     $e->subject = $subject;
     $e->body = $body;
     $e->sendTo($email);
 }
Exemplo n.º 3
0
 /**
  * Execute the default Events (send mail / add/remove groups)
  * @param string $strEvent
  * @param object $objMember
  * @param object $objAbo
  * @param object $objAboOrder
  */
 public function defaultEvents($strEvent, $objMember, $objAbo, $objAboOrder)
 {
     $objEvents = \Database::getInstance()->prepare("\n\t\t\tSELECT\t* FROM tl_abo_events as e\n\t\t\t\tLEFT JOIN tl_abo as a\n\t\t\t\tON a.id = e.pid\n\t\t\tWHERE a.id = ?\n\t\t\t\tAND e.published = 1\n\t\t\t\tAND e.event = ?")->execute($objAbo->id, $strEvent);
     if (!$objEvents->numRows) {
         return;
     }
     $this->aboLog("Event: " . $strEvent . " ausgeführt", __METHOD__, 'INFO', $objMember->id);
     // Load Current Abo
     $this->setAbo($objAbo);
     $this->setMember($objMember);
     $this->setAboOrder($objAboOrder);
     while ($objEvents->next()) {
         // send mail ?
         if ($objEvents->use_email) {
             $objMail = new \Email();
             $objMail->subject = $this->replaceInsertTagsAbo($objEvents->email_subject, $objMember);
             $objMail->text = $this->replaceInsertTagsAbo($objEvents->email_text, $objMember);
             if ($objEvents->email_template) {
                 $strTemplatePath = $objEvents->email_template;
                 if (VERSION >= 3) {
                     $objFile = \FilesModel::findByPk($strTemplatePath);
                     $strTemplatePath = $objFile->path;
                 }
                 $objMailTemplate = new File($strTemplatePath);
                 $objMail->html = $this->replaceInsertTagsAbo($objMailTemplate->getContent(), $objMember);
             }
             $objMail->from = $objEvents->email_from;
             $objMail->fromName = $objEvents->email_fromname;
             if ($objEvents->email_bcc) {
                 $objMail->sendBcc($objEvents->email_bcc);
             }
             $objMail->sendTo($objMember->email);
             $this->aboLog("E-Mail an " . $objMember->email . ' versendet.', __METHOD__, 'INFO', $objMember->id);
         }
         // set groups ?
         if ($objEvents->use_groups) {
             $arrMergedGroups = $this->groupManager($objMember, $objEvents->addGroups, $objEvents->removeGroups);
             Database::getInstance()->prepare("UPDATE tl_member SET groups = ? WHERE id = ?")->execute(serialize($arrMergedGroups), $objMember->id);
             $this->aboLog("Mitgliedergruppen: Aktiviert (" . implode(',', deserialize($objEvents->addGroups, true)) . ') / Deaktiviert: (' . implode(',', deserialize($objEvents->removeGroups, true)) . ')', __METHOD__, 'INFO', $objMember->id);
         }
     }
 }
Exemplo n.º 4
0
 public function showPopup()
 {
     $objTemplate = new \BackendTemplate('be_formbox');
     $objUser = \BackendUser::getInstance();
     if (\Input::post('FORM_SUBMIT') == 'formbox') {
         $objDate = new \Date();
         $objEmail = new \Email();
         $objEmail->subject = $GLOBALS['TL_CONFIG']['websiteTitle'] . ' - ' . $GLOBALS['TL_CONFIG']['be_formbox_button_text'];
         $strHtml = '<p>User: '******' (' . $objUser->email . ')</p>';
         $strHtml .= '<p>Site: ' . \Input::post('url') . '</p>';
         $strHtml .= '<p>Datum: ' . $objDate->datim . '</p>';
         $strHtml .= '<p>Message: ' . \Input::post('message') . '</p>';
         $objEmail->html = $strHtml;
         $objEmail->replyTo($objUser->name . ' <' . $objUser->email . '>');
         $objEmail->sendTo($GLOBALS['TL_CONFIG']['be_formbox_email']);
         $objTemplate->strMessageSent = $GLOBALS['TL_CONFIG']['be_formbox_message_sent'];
     }
     $objTemplate->strFormUrl = 'contao/main.php?do=undo&key=be-formbox&nb=1&popup=1';
     $objTemplate->strUrl = base64_decode(\Input::get('link'));
     $objTemplate->strFormboxMessage = $GLOBALS['TL_CONFIG']['be_formbox_message'];
     return $objTemplate->parse();
 }
Exemplo n.º 5
0
 /**
  * Compile the newsletter and send it
  * @param object
  * @param object
  * @param array
  * @param string
  * @param string
  * @param string
  * @return string
  */
 protected function sendNewsletter(Email $objEmail, Database_Result $objNewsletter, $arrRecipient, $text, $html, $css)
 {
     // Prepare text content
     $objEmail->text = $this->parseSimpleTokens($text, $arrRecipient);
     // Add HTML content
     if (!$objNewsletter->sendText) {
         // Get the mail template
         $objTemplate = new BackendTemplate(strlen($objNewsletter->template) ? $objNewsletter->template : 'mail_default');
         $objTemplate->setData($objNewsletter->row());
         $objTemplate->title = $objNewsletter->subject;
         $objTemplate->body = $this->parseSimpleTokens($html, $arrRecipient);
         $objTemplate->charset = $GLOBALS['TL_CONFIG']['characterSet'];
         $objTemplate->css = $css;
         // Parse template
         $objEmail->html = $objTemplate->parse();
         $objEmail->imageDir = TL_ROOT . '/';
     }
     // Deactivate invalid addresses
     try {
         $objEmail->sendTo($arrRecipient['email']);
     } catch (Swift_RfcComplianceException $e) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
     // Rejected recipients
     if (count($objEmail->failures)) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
 }
Exemplo n.º 6
0
Arquivo: User.php Projeto: rikaix/core
 /**
  * Try to login the current user
  * 
  * @return boolean True if the user could be logged in
  */
 public function login()
 {
     $this->loadLanguageFile('default');
     // Do not continue if username or password are missing
     if (!\Input::post('username') || !\Input::post('password')) {
         return false;
     }
     // Load the user object
     if ($this->findBy('username', \Input::post('username')) == false) {
         $blnLoaded = false;
         // HOOK: pass credentials to callback functions
         if (isset($GLOBALS['TL_HOOKS']['importUser']) && is_array($GLOBALS['TL_HOOKS']['importUser'])) {
             foreach ($GLOBALS['TL_HOOKS']['importUser'] as $callback) {
                 $this->import($callback[0], 'objImport', true);
                 $blnLoaded = $this->objImport->{$callback}[1](\Input::post('username'), \Input::post('password'), $this->strTable);
                 // Load successfull
                 if ($blnLoaded === true) {
                     break;
                 }
             }
         }
         // Return if the user still cannot be loaded
         if (!$blnLoaded || $this->findBy('username', \Input::post('username')) == false) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['invalidLogin']);
             $this->log('Could not find user "' . \Input::post('username') . '"', get_class($this) . ' login()', TL_ACCESS);
             return false;
         }
     }
     $time = time();
     // Set the user language
     if (\Input::post('language')) {
         $this->language = \Input::post('language');
     }
     // Lock the account if there are too many login attempts
     if ($this->loginCount < 1) {
         $this->locked = $time;
         $this->loginCount = $GLOBALS['TL_CONFIG']['loginCount'];
         $this->save();
         // Add a log entry
         $this->log('The account has been locked for security reasons', get_class($this) . ' login()', TL_ACCESS);
         // Send admin notification
         if (strlen($GLOBALS['TL_CONFIG']['adminEmail'])) {
             $objEmail = new \Email();
             $objEmail->subject = $GLOBALS['TL_LANG']['MSC']['lockedAccount'][0];
             $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['lockedAccount'][1], $this->username, TL_MODE == 'FE' ? $this->firstname . " " . $this->lastname : $this->name, \Environment::get('base'), ceil($GLOBALS['TL_CONFIG']['lockPeriod'] / 60));
             $objEmail->sendTo($GLOBALS['TL_CONFIG']['adminEmail']);
         }
         return false;
     }
     // Check the account status
     if ($this->checkAccountStatus() == false) {
         return false;
     }
     $blnAuthenticated = false;
     list($strPassword, $strSalt) = explode(':', $this->password);
     // Password is correct but not yet salted
     if (!strlen($strSalt) && $strPassword == sha1(\Input::post('password'))) {
         $strSalt = substr(md5(uniqid(mt_rand(), true)), 0, 23);
         $strPassword = sha1($strSalt . \Input::post('password'));
         $this->password = $strPassword . ':' . $strSalt;
     }
     // Check the password against the database
     if (strlen($strSalt) && $strPassword == sha1($strSalt . \Input::post('password'))) {
         $blnAuthenticated = true;
     } elseif (isset($GLOBALS['TL_HOOKS']['checkCredentials']) && is_array($GLOBALS['TL_HOOKS']['checkCredentials'])) {
         foreach ($GLOBALS['TL_HOOKS']['checkCredentials'] as $callback) {
             $this->import($callback[0], 'objAuth', true);
             $blnAuthenticated = $this->objAuth->{$callback}[1](\Input::post('username'), \Input::post('password'), $this);
             // Authentication successfull
             if ($blnAuthenticated === true) {
                 break;
             }
         }
     }
     // Redirect if the user could not be authenticated
     if (!$blnAuthenticated) {
         --$this->loginCount;
         $this->save();
         \Message::addError($GLOBALS['TL_LANG']['ERR']['invalidLogin']);
         $this->log('Invalid password submitted for username "' . $this->username . '"', get_class($this) . ' login()', TL_ACCESS);
         return false;
     }
     $this->setUserFromDb();
     // Update the record
     $this->lastLogin = $this->currentLogin;
     $this->currentLogin = $time;
     $this->loginCount = $GLOBALS['TL_CONFIG']['loginCount'];
     $this->save();
     // Generate the session
     $this->generateSession();
     $this->log('User "' . $this->username . '" has logged in', get_class($this) . ' login()', TL_ACCESS);
     // HOOK: post login callback
     if (isset($GLOBALS['TL_HOOKS']['postLogin']) && is_array($GLOBALS['TL_HOOKS']['postLogin'])) {
         foreach ($GLOBALS['TL_HOOKS']['postLogin'] as $callback) {
             $this->import($callback[0], 'objLogin', true);
             $this->objLogin->{$callback}[1]($this);
         }
     }
     return true;
 }
 /**
  * Send a newsletter.
  */
 protected function sendNewsletter(Email $email, $plain, $html, $recipientData, $personalized)
 {
     // set text content
     $email->text = $plain;
     // Prepare html content
     $email->html = $html;
     $email->imageDir = TL_ROOT . '/';
     $failed = false;
     // Deactivate invalid addresses
     try {
         if ($GLOBALS['TL_CONFIG']['avisota_developer_mode']) {
             $email->sendTo($GLOBALS['TL_CONFIG']['avisota_developer_email']);
         } else {
             $email->sendTo($recipientData['email']);
         }
     } catch (Swift_RfcComplianceException $e) {
         $failed = true;
     }
     // Rejected recipients
     if (count($email->failures)) {
         $failed = true;
     }
     $this->Static->resetRecipient();
     return !$failed;
 }
Exemplo n.º 8
0
	/**
	 * Edit a task
	 */
	protected function editTask()
	{
		$this->Template = new BackendTemplate('be_task_edit');
		$fs = $this->Session->get('fieldset_states');

		$this->Template->titleClass = (isset($fs['tl_tasks']['title_legend']) && !$fs['tl_tasks']['title_legend']) ? ' collapsed' : '';
		$this->Template->assignClass = (isset($fs['tl_tasks']['assign_legend']) && !$fs['tl_tasks']['assign_legend']) ? ' collapsed' : '';
		$this->Template->statusClass = (isset($fs['tl_tasks']['status_legend']) && !$fs['tl_tasks']['status_legend']) ? ' collapsed' : '';
		$this->Template->historyClass = (isset($fs['tl_tasks']['history_legend']) && !$fs['tl_tasks']['history_legend']) ? ' collapsed' : '';

		$this->Template->goBack = $GLOBALS['TL_LANG']['MSC']['goBack'];
		$this->Template->headline = sprintf($GLOBALS['TL_LANG']['tl_task']['edit'][1], $this->Input->get('id'));

		$objTask = $this->Database->prepare("SELECT *, (SELECT name FROM tl_user u WHERE u.id=t.createdBy) AS creator FROM tl_task t WHERE id=?")
								  ->limit(1)
								  ->execute($this->Input->get('id'));

		if ($objTask->numRows < 1)
		{
			$this->log('Invalid task ID "' . $this->Input->get('id') . '"', 'ModuleTask editTask()', TL_ERROR);
			$this->redirect('contao/main.php?act=error');
		}

		// Check if the user is allowed to edit the task
		if (!$this->User->isAdmin && $objTask->createdBy != $this->User->id)
		{
			$this->log('Not enough permissions to edit task ID "' . $this->Input->get('id') . '"', 'ModuleTask editTask()', TL_ERROR);
			$this->redirect('contao/main.php?act=error');
		}

		// Advanced options
		$this->blnAdvanced = ($this->User->isAdmin || $objTask->createdBy == $this->User->id);
		$this->Template->advanced = $this->blnAdvanced;

		$this->Template->title = $this->blnAdvanced ? $this->getTitleWidget($objTask->title) : $objTask->title;
		$this->Template->deadline = $this->blnAdvanced ? $this->getDeadlineWidget($this->parseDate($GLOBALS['TL_CONFIG']['dateFormat'], $objTask->deadline)) : $this->parseDate($GLOBALS['TL_CONFIG']['dateFormat'], $objTask->deadline);

		$arrHistory = array();

		// Get the status
		$objStatus = $this->Database->prepare("SELECT *, (SELECT name FROM tl_user u WHERE u.id=s.assignedTo) AS name FROM tl_task_status s WHERE pid=? ORDER BY tstamp")
									->execute($this->Input->get('id'));

		while($objStatus->next())
		{
			$arrHistory[] = array
			(
				'creator' => $objTask->creator,
				'date' => $this->parseDate($GLOBALS['TL_CONFIG']['dateFormat'], $objStatus->tstamp),
				'status' => (($GLOBALS['TL_LANG']['tl_task_status'][$objStatus->status] != '') ? $GLOBALS['TL_LANG']['tl_task_status'][$objStatus->status] : $objStatus->status),
				'comment' => (($objStatus->comment != '') ? nl2br_html5($objStatus->comment) : '&nbsp;'),
				'assignedTo' => $objStatus->assignedTo,
				'progress' => $objStatus->progress,
				'class' => $objStatus->status,
				'name' => $objStatus->name
			);
		}

		$this->Template->assignedTo = $this->getAssignedToWidget($objStatus->assignedTo);
		$this->Template->notify = $this->getNotifyWidget();
		$this->Template->status = $this->getStatusWidget($objStatus->status, $objStatus->progress);
		$this->Template->progress = $this->getProgressWidget($objStatus->progress);
		$this->Template->comment = $this->getCommentWidget();

		// Update task
		if ($this->Input->post('FORM_SUBMIT') == 'tl_tasks' && $this->blnSave)
		{
			// Update task
			if ($this->blnAdvanced)
			{
				$deadline = new Date($this->Template->deadline->value, $GLOBALS['TL_CONFIG']['dateFormat']);

				$this->Database->prepare("UPDATE tl_task SET title=?, deadline=? WHERE id=?")
							   ->execute($this->Template->title->value, $deadline->dayBegin, $this->Input->get('id'));
			}

			// Insert status
			$arrSet = array
			(
				'pid' => $this->Input->get('id'),
				'tstamp' => time(),
				'assignedTo' => $this->Template->assignedTo->value,
				'status' => $this->Template->status->value,
				'progress' => (($this->Template->status->value == 'completed') ? 100 : $this->Template->progress->value),
				'comment' => trim($this->Template->comment->value)
			);

			$this->Database->prepare("INSERT INTO tl_task_status %s")->set($arrSet)->execute();

			// Notify user
			if ($this->Input->post('notify'))
			{
				$objUser = $this->Database->prepare("SELECT email FROM tl_user WHERE id=?")
										  ->limit(1)
										  ->execute($this->Template->assignedTo->value);

				if ($objUser->numRows)
				{
					$objEmail = new Email();

					$objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
					$objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
					$objEmail->subject = $objTask->title;

					$objEmail->text = trim($this->Template->comment->value);
					$objEmail->text .= sprintf($GLOBALS['TL_LANG']['tl_task']['message'], $this->User->name, $this->Environment->base . 'contao/main.php?do=tasks&act=edit&id=' . $objTask->id);

					$objEmail->sendTo($objUser->email);
				}
			}

			// Go back
			$this->redirect('contao/main.php?do=tasks');
		}

		$this->Template->history = $arrHistory;
		$this->Template->historyLabel = $GLOBALS['TL_LANG']['tl_task']['history'];
		$this->Template->deadlineLabel = $GLOBALS['TL_LANG']['tl_task']['deadline'][0];
		$this->Template->dateLabel = $GLOBALS['TL_LANG']['tl_task']['date'];
		$this->Template->assignedToLabel = $GLOBALS['TL_LANG']['tl_task']['assignedTo'];
		$this->Template->createdByLabel = $GLOBALS['TL_LANG']['tl_task']['creator'];
		$this->Template->statusLabel = $GLOBALS['TL_LANG']['tl_task']['status'][0];
		$this->Template->progressLabel = $GLOBALS['TL_LANG']['tl_task']['progress'][0];
		$this->Template->submit = $GLOBALS['TL_LANG']['tl_task']['editSubmit'];
		$this->Template->titleLabel = $GLOBALS['TL_LANG']['tl_task']['title'][0];
		$this->Template->assignLabel = $GLOBALS['TL_LANG']['tl_task']['assignedTo'];
	}
 /**
  * Add a new recipient
  */
 protected function addRecipient()
 {
     if (!\Environment::get('isAjaxRequest')) {
         return parent::addRecipient();
     }
     $arrChannels = \Input::post('channels');
     if (!is_array($arrChannels)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['noChannels'];
         return false;
     }
     $arrChannels = array_intersect($arrChannels, $this->nl_channels);
     // see #3240
     // Check the selection
     if (!is_array($arrChannels) || empty($arrChannels)) {
         $_SESSION['SUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['noChannels'];
         return false;
     }
     $varInput = \Idna::encodeEmail(\Input::post('email', true));
     // Validate the e-mail address
     if (!\Validator::isEmail($varInput)) {
         $_SESSION['SUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['email'];
         return false;
     }
     $arrSubscriptions = array();
     // Get the existing active subscriptions
     if (($objSubscription = \NewsletterRecipientsModel::findBy(array("email=? AND active=1"), $varInput)) !== null) {
         $arrSubscriptions = $objSubscription->fetchEach('pid');
     }
     $arrNew = array_diff($arrChannels, $arrSubscriptions);
     // Return if there are no new subscriptions
     if (!is_array($arrNew) || empty($arrNew)) {
         $_SESSION['SUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['subscribed'];
         return false;
     }
     // Remove old subscriptions that have not been activated yet
     if (($objOld = \NewsletterRecipientsModel::findBy(array("email=? AND active=''"), $varInput)) !== null) {
         while ($objOld->next()) {
             $objOld->delete();
         }
     }
     $time = time();
     $strToken = md5(uniqid(mt_rand(), true));
     // Add the new subscriptions
     foreach ($arrNew as $id) {
         $objRecipient = new \NewsletterRecipientsModel();
         $objRecipient->pid = $id;
         $objRecipient->tstamp = $time;
         $objRecipient->email = $varInput;
         $objRecipient->active = '';
         $objRecipient->addedOn = $time;
         $objRecipient->ip = $this->anonymizeIp(\Environment::get('ip'));
         $objRecipient->token = $strToken;
         $objRecipient->confirmed = '';
         $objRecipient->save();
     }
     // Get the channels
     $objChannel = \NewsletterChannelModel::findByIds($arrChannels);
     // Prepare the e-mail text
     $strText = str_replace('##token##', $strToken, $this->nl_subscribe);
     $strText = str_replace('##domain##', \Idna::decode(\Environment::get('host')), $strText);
     $strText = str_replace('##link##', \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (\Config::get('disableAlias') || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $strToken, $strText);
     $strText = str_replace(array('##channel##', '##channels##'), implode("\n", $objChannel->fetchEach('title')), $strText);
     // Activation e-mail
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['nl_subject'], \Idna::decode(\Environment::get('host')));
     $objEmail->text = $strText;
     $objEmail->sendTo($varInput);
     // Redirect to the jumpTo page
     if ($this->jumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->redirect($this->generateFrontendUrl($objTarget->row()));
     }
     $_SESSION['SUBSCRIBE_CONFIRM'] = $GLOBALS['TL_LANG']['MSC']['nl_confirm'];
     return true;
 }
Exemplo n.º 10
0
 /**
  * onsubmit_callback
  * send email
  */
 public function onSubmitCbSendEmail()
 {
     // the save-button is a fileupload-button
     if (!\Input::post('saveNclose')) {
         return;
     }
     $email = new Email();
     $fromMail = $this->User->email;
     $subject = \Input::post('subject');
     $email->replyTo($fromMail);
     $email->from = $fromMail;
     $email->subject = $subject;
     $email->html = base64_decode($_POST['content']);
     //save attachment
     $arrFiles = array();
     $db = $this->Database->prepare('SELECT attachment FROM tl_be_email WHERE id=?')->execute(\Input::get('id'));
     // Attachment
     if ($db->attachment != '') {
         $arrFiles = unserialize($db->attachment);
         foreach ($arrFiles as $filekey => $filename) {
             if (file_exists(TL_ROOT . '/' . BE_EMAIL_UPLOAD_DIR . '/' . $filekey)) {
                 $this->Files->copy(BE_EMAIL_UPLOAD_DIR . '/' . $filekey, 'system/tmp/' . $filename);
                 $email->attachFile(TL_ROOT . '/system/tmp/' . $filename);
             }
         }
     }
     // Cc
     $cc_recipients = array_unique($this->validateEmailAddresses(\Input::post('recipientsCc'), 'recipientsCc'));
     if (count($cc_recipients)) {
         $email->sendCc($cc_recipients);
     }
     // Bcc
     $bcc_recipients = array_unique($this->validateEmailAddresses(\Input::post('recipientsBcc'), 'recipientsBcc'));
     if (count($bcc_recipients)) {
         $email->sendBcc($bcc_recipients);
     }
     // To
     $recipients = array_unique($this->validateEmailAddresses(\Input::post('recipientsTo'), 'recipientsTo'));
     if (count($recipients)) {
         $email->sendTo($recipients);
     }
     // Delete attachment from server
     foreach ($arrFiles as $filekey => $filename) {
         // delete file in the tmp-folder
         if (is_file(TL_ROOT . '/system/tmp/' . $filename)) {
             $this->Files->delete('/system/tmp/' . $filename);
         }
     }
 }
 /**
  * Create a new user and redirect
  * @param array
  */
 protected function createNewUser($arrData)
 {
     $arrData['tstamp'] = time();
     $arrData['login'] = $this->reg_allowLogin;
     $arrData['activation'] = md5(uniqid(mt_rand(), true));
     $arrData['dateAdded'] = $arrData['tstamp'];
     if ($this->reg_createLoginCredentials) {
         $this->createLoginCredentials($arrData);
     }
     // Set default groups
     if (!array_key_exists('groups', $arrData)) {
         $arrData['groups'] = $this->reg_groups;
     }
     // Disable account
     $arrData['disable'] = 1;
     // Send activation e-mail
     if ($this->reg_activate) {
         $arrChunks = array();
         $strConfirmation = $this->reg_text;
         preg_match_all('/##[^#]+##/i', $strConfirmation, $arrChunks);
         foreach ($arrChunks[0] as $strChunk) {
             $strKey = substr($strChunk, 2, -2);
             switch ($strKey) {
                 case 'domain':
                     $strConfirmation = str_replace($strChunk, $this->Environment->host, $strConfirmation);
                     break;
                 case 'link':
                     $strConfirmation = str_replace($strChunk, $this->Environment->base . $this->Environment->request . ($GLOBALS['TL_CONFIG']['disableAlias'] || strpos($this->Environment->request, '?') !== false ? '&' : '?') . 'token=' . $arrData['activation'], $strConfirmation);
                     break;
                     // HOOK: support newsletter subscriptions
                 // HOOK: support newsletter subscriptions
                 case 'channel':
                 case 'channels':
                     if (!in_array('newsletter', $this->Config->getActiveModules())) {
                         break;
                     }
                     // Make sure newsletter is an array
                     if (!is_array($arrData['newsletter'])) {
                         if ($arrData['newsletter'] != '') {
                             $arrData['newsletter'] = array($arrData['newsletter']);
                         } else {
                             $arrData['newsletter'] = array();
                         }
                     }
                     // Replace the wildcard
                     if (count($arrData['newsletter']) > 0) {
                         $objChannels = $this->Database->execute("SELECT title FROM tl_newsletter_channel WHERE id IN(" . implode(',', array_map('intval', $arrData['newsletter'])) . ")");
                         $strConfirmation = str_replace($strChunk, implode("\n", $objChannels->fetchEach('title')), $strConfirmation);
                     } else {
                         $strConfirmation = str_replace($strChunk, '', $strConfirmation);
                     }
                     break;
                 default:
                     $strConfirmation = str_replace($strChunk, $arrData[$strKey], $strConfirmation);
                     break;
             }
         }
         $objEmail = new Email();
         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['emailSubject'], $this->Environment->host);
         $objEmail->text = $strConfirmation;
         $objEmail->sendTo($arrData['email']);
     }
     // replace password in database with encrypted version after mail is sent
     if ($this->reg_createLoginCredentials) {
         // ony encrypt password if its not already encrypted
         if (!empty($arrData['password']) && strpos($arrData['password'], ':') != 40) {
             $strSalt = substr(md5(uniqid(mt_rand(), true)), 0, 23);
             $arrData['password'] = sha1($strSalt . $arrData['password']) . ':' . $strSalt;
             $this->Database->prepare("UPDATE tl_member SET password=? WHERE id=?")->execute($arrData['password'], $insertId);
         }
     }
     // Make sure newsletter is an array
     if (isset($arrData['newsletter']) && !is_array($arrData['newsletter'])) {
         $arrData['newsletter'] = array($arrData['newsletter']);
     }
     // Create user
     $objNewUser = $this->Database->prepare("INSERT INTO tl_member %s")->set($arrData)->execute();
     $insertId = $objNewUser->insertId;
     // Assign home directory
     if ($this->reg_assignDir && is_dir(TL_ROOT . '/' . $this->reg_homeDir)) {
         $this->import('Files');
         $strUserDir = strlen($arrData['username']) ? $arrData['username'] : '******' . $insertId;
         // Add the user ID if the directory exists
         if (is_dir(TL_ROOT . '/' . $this->reg_homeDir . '/' . $strUserDir)) {
             $strUserDir .= '_' . $insertId;
         }
         new Folder($this->reg_homeDir . '/' . $strUserDir);
         $this->Database->prepare("UPDATE tl_member SET homeDir=?, assignDir=1 WHERE id=?")->execute($this->reg_homeDir . '/' . $strUserDir, $insertId);
     }
     // HOOK: send insert ID and user data
     if (isset($GLOBALS['TL_HOOKS']['createNewUser']) && is_array($GLOBALS['TL_HOOKS']['createNewUser'])) {
         foreach ($GLOBALS['TL_HOOKS']['createNewUser'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($insertId, $arrData);
         }
     }
     // Inform admin if no activation link is sent
     #		if (!$this->reg_activate)
     #		{
     $this->sendAdminNotification($insertId, $arrData);
     #		}
     $this->jumpToOrReload($this->jumpTo);
 }
Exemplo n.º 12
0
 /**
  * Add a form to create new testimonials
  * @param \FrontendTemplate
  * @param \stdClass
  * @param string
  * @param integer
  * @param array
  */
 protected function renderTestimonialForm(\FrontendTemplate $objTemplate, \stdClass $objConfig, $intParent)
 {
     $this->import('FrontendUser', 'User');
     // Access control
     if ($objConfig->requireLogin && !BE_USER_LOGGED_IN && !FE_USER_LOGGED_IN) {
         $objTemplate->requireLogin = true;
         return;
     }
     // Form fields
     $arrFields = array('name' => array('name' => 'name', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_name'], 'value' => trim($this->User->firstname . ' ' . $this->User->lastname), 'inputType' => 'text', 'eval' => array('mandatory' => true, 'maxlength' => 64, 'placeholder' => $GLOBALS['TL_LANG']['MSC']['tm_name'])), 'email' => array('name' => 'email', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_email'], 'value' => $this->User->email, 'inputType' => 'text', 'eval' => array('rgxp' => 'email', 'mandatory' => true, 'maxlength' => 128, 'decodeEntities' => true, 'placeholder' => $GLOBALS['TL_LANG']['MSC']['tm_email'])), 'url' => array('name' => 'url', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_url'], 'inputType' => 'text', 'eval' => array('rgxp' => 'url', 'maxlength' => 128, 'decodeEntities' => true, 'placeholder' => $GLOBALS['TL_LANG']['MSC']['tm_url'])), 'company' => array('name' => 'company', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_company'], 'inputType' => 'text', 'eval' => array('maxlength' => 128, 'placeholder' => $GLOBALS['TL_LANG']['MSC']['tm_company'])), 'title' => array('name' => 'title', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_title'], 'inputType' => 'text', 'eval' => array('maxlength' => 128, 'placeholder' => $GLOBALS['TL_LANG']['MSC']['tm_title'])));
     if ($objConfig->enableVoteField1 && $objConfig->addVote) {
         $arrFields['votefield1'] = array('name' => 'votefield1', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield1'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     if ($objConfig->enableVoteField2 && $objConfig->addVote) {
         $arrFields['votefield2'] = array('name' => 'votefield2', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield2'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     if ($objConfig->enableVoteField3 && $objConfig->addVote) {
         $arrFields['votefield3'] = array('name' => 'votefield3', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield3'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     if ($objConfig->enableVoteField4 && $objConfig->addVote) {
         $arrFields['votefield4'] = array('name' => 'votefield4', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield4'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     if ($objConfig->enableVoteField5 && $objConfig->addVote) {
         $arrFields['votefield5'] = array('name' => 'votefield5', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield5'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     if ($objConfig->enableVoteField6 && $objConfig->addVote) {
         $arrFields['votefield6'] = array('name' => 'votefield6', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield6'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     // Captcha
     if (!$objConfig->disableCaptcha) {
         $arrFields['captcha'] = array('name' => 'captcha', 'inputType' => 'captcha', 'eval' => array('mandatory' => true));
     }
     // Testimonial field
     $arrFields['testimonial'] = array('name' => 'testimonial', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_testimonial'], 'inputType' => 'textarea', 'eval' => array('mandatory' => true, 'rows' => 15, 'cols' => 40, 'preserveTags' => true));
     $doNotSubmit = false;
     $arrWidgets = array();
     $strFormId = 'jedo_testimonials_' . $intParent;
     // Initialize the widgets
     foreach ($arrFields as $arrField) {
         $strClass = $GLOBALS['TL_FFL'][$arrField['inputType']];
         // Continue if the class is not defined
         if (!class_exists($strClass)) {
             continue;
         }
         $arrField['eval']['required'] = $arrField['eval']['mandatory'];
         $objWidget = new $strClass($this->prepareForWidget($arrField, $arrField['name'], $arrField['value']));
         // Validate the widget
         if (\Input::post('FORM_SUBMIT') == $strFormId) {
             $objWidget->validate();
             if ($objWidget->hasErrors()) {
                 $doNotSubmit = true;
             }
         }
         $arrWidgets[$arrField['name']] = $objWidget;
     }
     $objTemplate->fields = $arrWidgets;
     $objTemplate->submit = $GLOBALS['TL_LANG']['MSC']['com_submit'];
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->messages = '';
     // Backwards compatibility
     $objTemplate->formId = $strFormId;
     $objTemplate->hasError = $doNotSubmit;
     // Do not index or cache the page with the confirmation message
     if ($_SESSION['TL_TESTIMONIAL_ADDED']) {
         global $objPage;
         $objPage->noSearch = 1;
         $objPage->cache = 0;
         $objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['com_confirm'];
         $_SESSION['TL_TESTIMONIAL_ADDED'] = false;
     }
     // Store the testimonial
     if (!$doNotSubmit && \Input::post('FORM_SUBMIT') == $strFormId) {
         $strWebsite = $arrWidgets['url']->value;
         if ($strWebsite == $GLOBALS['TL_LANG']['MSC']['tm_url']) {
             $strWebsite = '';
         }
         // Add http:// to the website
         if ($strWebsite != '' && !preg_match('@^(https?://|ftp://|mailto:|#)@i', $strWebsite)) {
             $strWebsite = 'http://' . $strWebsite;
         }
         // Do not parse any tags in the testimonial
         $strTestimonial = htmlspecialchars(trim($arrWidgets['testimonial']->value));
         $strTestimonial = str_replace(array('&amp;', '&lt;', '&gt;'), array('[&]', '[lt]', '[gt]'), $strTestimonial);
         // Remove multiple line feeds
         $strTestimonial = preg_replace('@\\n\\n+@', "\n\n", $strTestimonial);
         // Parse BBCode
         if ($objConfig->bbcode) {
             $strTestimonial = $this->parseBbCode($strTestimonial);
         }
         // Prevent cross-site request forgeries
         $strTestimonial = preg_replace('/(href|src|on[a-z]+)="[^"]*(contao\\/main\\.php|typolight\\/main\\.php|javascript|vbscri?pt|script|alert|document|cookie|window)[^"]*"+/i', '$1="#"', $strTestimonial);
         $time = time();
         if ($objConfig->addVote) {
             // make the totalvote object
             $fields = 0;
             $value = 0.0;
             if ($objConfig->enableVoteField1) {
                 $arrWidgets['votefield1']->value = $this->getRatingValue($arrWidgets['votefield1']->value);
                 $value = $value + $arrWidgets['votefield1']->value;
                 $fields++;
             }
             if ($objConfig->enableVoteField2) {
                 $arrWidgets['votefield2']->value = $this->getRatingValue($arrWidgets['votefield2']->value);
                 $value = $value + $arrWidgets['votefield2']->value;
                 $fields++;
             }
             if ($objConfig->enableVoteField3) {
                 $arrWidgets['votefield3']->value = $this->getRatingValue($arrWidgets['votefield3']->value);
                 $value = $value + $arrWidgets['votefield3']->value;
                 $fields++;
             }
             if ($objConfig->enableVoteField4) {
                 $arrWidgets['votefield4']->value = $this->getRatingValue($arrWidgets['votefield4']->value);
                 $value = $value + $arrWidgets['votefield4']->value;
                 $fields++;
             }
             if ($objConfig->enableVoteField5) {
                 $arrWidgets['votefield5']->value = $this->getRatingValue($arrWidgets['votefield5']->value);
                 $value = $value + $arrWidgets['votefield5']->value;
                 $fields++;
             }
             if ($objConfig->enableVoteField6) {
                 $arrWidgets['votefield6']->value = $this->getRatingValue($arrWidgets['votefield6']->value);
                 $value = $value + $arrWidgets['votefield6']->value;
                 $fields++;
             }
             $totalvote = $value / $fields;
             $strTVotes = number_format($totalvote, 2);
         }
         if ($arrWidgets['company']->value == $value_company) {
             $arrWidgets['company']->value = '';
         }
         if ($arrWidgets['title']->value == $value_title) {
             $arrWidgets['title']->value = '';
         }
         // Prepare the record
         $arrSet = array('tstamp' => $time, 'name' => $arrWidgets['name']->value, 'email' => $arrWidgets['email']->value, 'company' => $arrWidgets['company']->value, 'title' => $arrWidgets['title']->value, 'url' => $strWebsite, 'testimonial' => $this->convertLineFeeds($strTestimonial), 'ip' => $this->anonymizeIp($this->Environment->ip), 'date' => $time, 'votestotal' => $strTVotes, 'votefield1' => !$objConfig->enableVoteField1 ? '' : $arrWidgets['votefield1']->value, 'votefield2' => !$objConfig->enableVoteField2 ? '' : $arrWidgets['votefield2']->value, 'votefield3' => !$objConfig->enableVoteField3 ? '' : $arrWidgets['votefield3']->value, 'votefield4' => !$objConfig->enableVoteField4 ? '' : $arrWidgets['votefield4']->value, 'votefield5' => !$objConfig->enableVoteField5 ? '' : $arrWidgets['votefield5']->value, 'votefield6' => !$objConfig->enableVoteField6 ? '' : $arrWidgets['votefield6']->value, 'published' => $objConfig->moderate ? '' : 1);
         // Store the testimonial
         $objTestimonials = new \TestimonialsModel();
         $objTestimonials->setRow($arrSet)->save();
         // Prepare the notification mail
         $objEmail = new \Email();
         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['tm_subject'], \Idna::decode(\Environment::get('host')));
         // Convert the testimonial to plain text
         $strTestimonial = strip_tags($strTestimonial);
         $strTestimonial = \StringUtil::decodeEntities($strTestimonial);
         $strTestimonial = str_replace(array('[&]', '[lt]', '[gt]'), array('&', '<', '>'), $strTestimonial);
         // Add the testimonial details
         $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['tm_message'], $arrSet['name'] . ' (' . $arrSet['email'] . ')', $strTestimonial, \Idna::decode(\Environment::get('base')) . \Environment::get('request'), \Idna::decode(\Environment::get('base')) . 'contao/main.php?do=testimonials&act=edit&id=' . $objTestimonials->id);
         $objEmail->sendTo($GLOBALS['TL_ADMIN_EMAIL']);
         // Pending for approval
         if ($objConfig->moderate) {
             // FIXME: notify the subscribers when the testimonial is published
             $_SESSION['TL_TESTIMONIAL_ADDED'] = true;
         }
         $this->reload();
     }
 }
Exemplo n.º 13
0
 /**
  * Compile the newsletter and send it
  * @param \Email
  * @param \Database_Result
  * @param array
  * @param string
  * @param string
  * @param string
  * @return string
  */
 protected function sendNewsletter(\Email $objEmail, \Database_Result $objNewsletter, $arrRecipient, $text, $html, $css = null)
 {
     // Prepare the text content
     $objEmail->text = \String::parseSimpleTokens($text, $arrRecipient);
     // Add the HTML content
     if (!$objNewsletter->sendText) {
         // Default template
         if ($objNewsletter->template == '') {
             $objNewsletter->template = 'mail_default';
         }
         // Load the mail template
         $objTemplate = new \BackendTemplate($objNewsletter->template);
         $objTemplate->setData($objNewsletter->row());
         $objTemplate->title = $objNewsletter->subject;
         $objTemplate->body = \String::parseSimpleTokens($html, $arrRecipient);
         $objTemplate->charset = $GLOBALS['TL_CONFIG']['characterSet'];
         $objTemplate->css = $css;
         // Backwards compatibility
         // Parse template
         $objEmail->html = $objTemplate->parse();
         $objEmail->imageDir = TL_ROOT . '/';
     }
     // Deactivate invalid addresses
     try {
         $objEmail->sendTo($arrRecipient['email']);
     } catch (Swift_RfcComplianceException $e) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
     // Rejected recipients
     if ($objEmail->hasFailures()) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
 }
Exemplo n.º 14
0
 /**
  * Create a new user and redirect
  *
  * @param \MemberModel $objMember
  */
 protected function sendPasswordLink($objMember)
 {
     $confirmationId = md5(uniqid(mt_rand(), true));
     // Store the confirmation ID
     $objMember = \MemberModel::findByPk($objMember->id);
     $objMember->activation = $confirmationId;
     $objMember->save();
     // Prepare the simple token data
     $arrData = $objMember->row();
     $arrData['domain'] = \Idna::decode(\Environment::get('host'));
     $arrData['link'] = \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (\Config::get('disableAlias') || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $confirmationId;
     // Send e-mail
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['passwordSubject'], \Idna::decode(\Environment::get('host')));
     $objEmail->text = \String::parseSimpleTokens($this->reg_password, $arrData);
     $objEmail->sendTo($objMember->email);
     $this->log('A new password has been requested for user ID ' . $objMember->id . ' (' . $objMember->email . ')', __METHOD__, TL_ACCESS);
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
 public function sendUnSubscribeMail($channels, $subject = '', $text = '')
 {
     $objChannel = \Database::getInstance()->prepare("SELECT * FROM tl_newsletter_channel WHERE id IN (" . implode(',', $channels) . ")")->limit(1)->execute();
     $objEmail = new \Email();
     if (empty($subject)) {
         $subject = $objChannel->first()->nl_unsubscribe_subject;
     }
     if (empty($text)) {
         $text = $objChannel->first()->nl_unsubscribe_text;
     }
     $strSubject = str_replace(array('##channel##', '##channels##'), implode(",", $objChannel->fetchEach('title')), $subject);
     $strText = str_replace('##salutation##', $this->getSalutation(), $text);
     $strText = str_replace('##domain##', \Idna::decode(\Environment::get('host')), $strText);
     $strText = str_replace('##link##', \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (\Config::get('disableAlias') || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $this->token, $strText);
     $strText = str_replace(array('##channel##', '##channels##'), implode("\n", $objChannel->fetchEach('title')), $strText);
     $objEmail->from = $objChannel->first()->nl_unsubscribe_sender_mail ? $objChannel->first()->nl_unsubscribe_sender_mail : $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $objChannel->first()->nl_unsubscribe_sender_name ? $objChannel->first()->nl_unsubscribe_sender_name : $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = $this->replaceInsertTags($strSubject);
     $objEmail->text = $this->replaceInsertTags($strText);
     if ($objEmail->sendTo($this->email)) {
         $_SESSION['UNSUBSCRIBE_CONFIRM'] = $GLOBALS['TL_LANG']['MSC']['nl_removed'];
         return true;
     }
     return false;
 }
Exemplo n.º 16
0
 /**
  * Remove the recipient
  */
 protected function removeRecipient()
 {
     $arrChannels = \Input::post('channels');
     $arrChannels = array_intersect($arrChannels, $this->nl_channels);
     // see #3240
     // Check the selection
     if (!is_array($arrChannels) || empty($arrChannels)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['noChannels'];
         $this->reload();
     }
     $varInput = \Idna::encodeEmail(\Input::post('email', true));
     // Validate e-mail address
     if (!\Validator::isEmail($varInput)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['email'];
         $this->reload();
     }
     $arrSubscriptions = array();
     // Get the existing active subscriptions
     if (($objSubscription = \NewsletterRecipientsModel::findBy(array("email=? AND active=1"), $varInput)) !== null) {
         $arrSubscriptions = $objSubscription->fetchEach('pid');
     }
     $arrRemove = array_intersect($arrChannels, $arrSubscriptions);
     // Return if there are no subscriptions to remove
     if (!is_array($arrRemove) || empty($arrRemove)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['unsubscribed'];
         $this->reload();
     }
     // Remove the subscriptions
     if (($objRemove = \NewsletterRecipientsModel::findByEmailAndPids($varInput, $arrRemove)) !== null) {
         while ($objRemove->next()) {
             $objRemove->delete();
         }
     }
     // Get the channels
     $objChannels = \NewsletterChannelModel::findByIds($arrRemove);
     $arrChannels = $objChannels->fetchEach('title');
     // Log activity
     $this->log($varInput . ' unsubscribed from ' . implode(', ', $arrChannels), 'ModuleUnsubscribe removeRecipient()', TL_NEWSLETTER);
     // HOOK: post unsubscribe callback
     if (isset($GLOBALS['TL_HOOKS']['removeRecipient']) && is_array($GLOBALS['TL_HOOKS']['removeRecipient'])) {
         foreach ($GLOBALS['TL_HOOKS']['removeRecipient'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($varInput, $arrRemove);
         }
     }
     // Prepare the e-mail text
     $strText = str_replace('##domain##', \Environment::get('host'), $this->nl_unsubscribe);
     $strText = str_replace(array('##channel##', '##channels##'), implode("\n", $arrChannels), $strText);
     // Confirmation e-mail
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['nl_subject'], \Environment::get('host'));
     $objEmail->text = $strText;
     $objEmail->sendTo($varInput);
     // Redirect to the jumpTo page
     if ($this->jumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->redirect($this->generateFrontendUrl($objTarget->row()));
     }
     $_SESSION['UNSUBSCRIBE_CONFIRM'] = $GLOBALS['TL_LANG']['MSC']['nl_removed'];
     $this->reload();
 }
Exemplo n.º 17
0
Arquivo: User.php Projeto: eknoes/core
 /**
  * Try to login the current user
  *
  * @return boolean True if the user could be logged in
  */
 public function login()
 {
     \System::loadLanguageFile('default');
     // Do not continue if username or password are missing
     if (empty($_POST['username']) || empty($_POST['password'])) {
         return false;
     }
     // Load the user object
     if ($this->findBy('username', \Input::post('username', true)) == false) {
         $blnLoaded = false;
         // HOOK: pass credentials to callback functions
         if (isset($GLOBALS['TL_HOOKS']['importUser']) && is_array($GLOBALS['TL_HOOKS']['importUser'])) {
             foreach ($GLOBALS['TL_HOOKS']['importUser'] as $callback) {
                 $this->import($callback[0], 'objImport', true);
                 $blnLoaded = $this->objImport->{$callback[1]}(\Input::post('username', true), \Input::postUnsafeRaw('password'), $this->strTable);
                 // Load successfull
                 if ($blnLoaded === true) {
                     break;
                 }
             }
         }
         // Return if the user still cannot be loaded
         if (!$blnLoaded || $this->findBy('username', \Input::post('username', true)) == false) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['invalidLogin']);
             $this->log('Could not find user "' . \Input::post('username', true) . '"', __METHOD__, TL_ACCESS);
             return false;
         }
     }
     $time = time();
     // Set the user language
     if (\Input::post('language')) {
         $this->language = \Input::post('language');
     }
     // Lock the account if there are too many login attempts
     if ($this->loginCount < 1) {
         $this->locked = $time;
         $this->loginCount = \Config::get('loginCount');
         $this->save();
         // Add a log entry and the error message, because checkAccountStatus() will not be called (see #4444)
         $this->log('User "' . $this->username . '" has been locked for ' . ceil(\Config::get('lockPeriod') / 60) . ' minutes', __METHOD__, TL_ACCESS);
         \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['accountLocked'], ceil(($this->locked + \Config::get('lockPeriod') - $time) / 60)));
         // Send admin notification
         if (\Config::get('adminEmail') != '') {
             $objEmail = new \Email();
             $objEmail->subject = $GLOBALS['TL_LANG']['MSC']['lockedAccount'][0];
             $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['lockedAccount'][1], $this->username, TL_MODE == 'FE' ? $this->firstname . " " . $this->lastname : $this->name, \Idna::decode(\Environment::get('base')), ceil(\Config::get('lockPeriod') / 60));
             $objEmail->sendTo(\Config::get('adminEmail'));
         }
         return false;
     }
     // Check the account status
     if ($this->checkAccountStatus() == false) {
         return false;
     }
     // The password has been generated with crypt()
     if (\Encryption::test($this->password)) {
         $blnAuthenticated = \Encryption::verify(\Input::postUnsafeRaw('password'), $this->password);
     } else {
         list($strPassword, $strSalt) = explode(':', $this->password);
         $blnAuthenticated = $strSalt == '' ? $strPassword === sha1(\Input::postUnsafeRaw('password')) : $strPassword === sha1($strSalt . \Input::postUnsafeRaw('password'));
         // Store a SHA-512 encrpyted version of the password
         if ($blnAuthenticated) {
             $this->password = \Encryption::hash(\Input::postUnsafeRaw('password'));
         }
     }
     // HOOK: pass credentials to callback functions
     if (!$blnAuthenticated && isset($GLOBALS['TL_HOOKS']['checkCredentials']) && is_array($GLOBALS['TL_HOOKS']['checkCredentials'])) {
         foreach ($GLOBALS['TL_HOOKS']['checkCredentials'] as $callback) {
             $this->import($callback[0], 'objAuth', true);
             $blnAuthenticated = $this->objAuth->{$callback[1]}(\Input::post('username', true), \Input::postUnsafeRaw('password'), $this);
             // Authentication successfull
             if ($blnAuthenticated === true) {
                 break;
             }
         }
     }
     // Redirect if the user could not be authenticated
     if (!$blnAuthenticated) {
         --$this->loginCount;
         $this->save();
         \Message::addError($GLOBALS['TL_LANG']['ERR']['invalidLogin']);
         $this->log('Invalid password submitted for username "' . $this->username . '"', __METHOD__, TL_ACCESS);
         return false;
     }
     $this->setUserFromDb();
     // Update the record
     $this->lastLogin = $this->currentLogin;
     $this->currentLogin = $time;
     $this->loginCount = \Config::get('loginCount');
     $this->save();
     // Generate the session
     $this->generateSession();
     $this->log('User "' . $this->username . '" has logged in', __METHOD__, TL_ACCESS);
     // HOOK: post login callback
     if (isset($GLOBALS['TL_HOOKS']['postLogin']) && is_array($GLOBALS['TL_HOOKS']['postLogin'])) {
         foreach ($GLOBALS['TL_HOOKS']['postLogin'] as $callback) {
             $this->import($callback[0], 'objLogin', true);
             $this->objLogin->{$callback[1]}($this);
         }
     }
     return true;
 }
 /**
  * Sends an information mail about the submission of the new member.
  */
 private function sendInformationMail($member)
 {
     if ($this->isActionAllowed('send_email') && $this->isMemberNew($member)) {
         // first check if required extension 'ExtendedEmailRegex' is installed
         if (!in_array('extendedEmailRegex', $this->Config->getActiveModules())) {
             $this->log('RscMemberSubmissionPostProcessor: Extension "ExtendedEmailRegex" is required!', 'RscMemberSubmissionPostProcessor sendInformationMail()', TL_ERROR);
             return false;
         }
         $this->import('ExtendedEmailRegex', 'Base');
         $objEmail = new Email();
         $objEmail->logFile = 'RscMemberSubmissionPostProcessorEmail.log';
         $objEmail->from = $GLOBALS['TL_CONFIG']['adminEmail'];
         $objEmail->fromName = $GLOBALS['TL_CONFIG']['websiteTitle'];
         $objEmail->subject = $this->replaceEmailInsertTags($GLOBALS['TL_CONFIG']['rscMemberSubmissionPostProcessorEmailSubject'], $member);
         $objEmail->html = $this->replaceEmailInsertTags($GLOBALS['TL_CONFIG']['rscMemberSubmissionPostProcessorEmailContent'], $member);
         $objEmail->text = $this->transformEmailHtmlToText($objEmail->html);
         try {
             $objEmail->sendTo(ExtendedEmailRegex::getEmailsFromList($GLOBALS['TL_CONFIG']['rscMemberSubmissionPostProcessorEmailReceiver']));
             return true;
         } catch (Swift_RfcComplianceException $e) {
             $this->log("Mail could not be send: " . $e->getMessage(), "RscMemberSubmissionPostProcessor sendInformationMail()", TL_ERROR);
             return false;
         }
     }
 }
 protected function createNewUser($arrData)
 {
     $arrData['tstamp'] = time();
     $arrData['login'] = $this->reg_allowLogin;
     $arrData['activation'] = md5(uniqid(mt_rand(), true));
     $arrData['dateAdded'] = $arrData['tstamp'];
     $pw = $this->getRandomPassword(6);
     $arrData['password'] = \Encryption::hash($pw["clear"]);
     $arrData['username'] = strtolower($arrData['email']);
     $arrData['email'] = strtolower($arrData['email']);
     // Set default groups
     if (!array_key_exists('groups', $arrData)) {
         $arrData['groups'] = $this->reg_groups;
     }
     //        // Disable account
     //        $arrData['disable'] = 1;
     // Send activation e-mail
     if ($this->reg_activate) {
         $arrChunks = array();
         $strConfirmation = $this->reg_text;
         preg_match_all('/##[^#]+##/', $strConfirmation, $arrChunks);
         foreach ($arrChunks[0] as $strChunk) {
             $strKey = substr($strChunk, 2, -2);
             switch ($strKey) {
                 case 'domain':
                     $strConfirmation = str_replace($strChunk, \Idna::decode(\Environment::get('host')), $strConfirmation);
                     break;
                 case 'gen_pw':
                     $strConfirmation = str_replace($strChunk, $pw["clear"], $strConfirmation);
                     break;
                 case 'link':
                     $strConfirmation = str_replace($strChunk, \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (\Config::get('disableAlias') || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $arrData['activation'], $strConfirmation);
                     break;
                     // HOOK: support newsletter subscriptions
                 // HOOK: support newsletter subscriptions
                 case 'channel':
                 case 'channels':
                     if (!in_array('newsletter', \ModuleLoader::getActive())) {
                         break;
                     }
                     // Make sure newsletter is an array
                     if (!is_array($arrData['newsletter'])) {
                         if ($arrData['newsletter'] != '') {
                             $arrData['newsletter'] = array($arrData['newsletter']);
                         } else {
                             $arrData['newsletter'] = array();
                         }
                     }
                     // Replace the wildcard
                     if (!empty($arrData['newsletter'])) {
                         $objChannels = \NewsletterChannelModel::findByIds($arrData['newsletter']);
                         if ($objChannels !== null) {
                             $strConfirmation = str_replace($strChunk, implode("\n", $objChannels->fetchEach('title')), $strConfirmation);
                         }
                     } else {
                         $strConfirmation = str_replace($strChunk, '', $strConfirmation);
                     }
                     break;
                 default:
                     $strConfirmation = str_replace($strChunk, $arrData[$strKey], $strConfirmation);
                     break;
             }
         }
         $objEmail = new \Email();
         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['emailSubject'], \Idna::decode(\Environment::get('host')));
         $objEmail->text = $strConfirmation;
         $objEmail->sendTo($arrData['email']);
     }
     // Make sure newsletter is an array
     if (isset($arrData['newsletter']) && !is_array($arrData['newsletter'])) {
         $arrData['newsletter'] = array($arrData['newsletter']);
     }
     // Create the user
     $objNewUser = new \MemberModel();
     $objNewUser->setRow($arrData);
     $objNewUser->save();
     $insertId = $objNewUser->id;
     // Assign home directory
     if ($this->reg_assignDir) {
         $objHomeDir = \FilesModel::findByUuid($this->reg_homeDir);
         if ($objHomeDir !== null) {
             $this->import('Files');
             $strUserDir = standardize($arrData['username']) ?: 'user_' . $insertId;
             // Add the user ID if the directory exists
             while (is_dir(TL_ROOT . '/' . $objHomeDir->path . '/' . $strUserDir)) {
                 $strUserDir .= '_' . $insertId;
             }
             // Create the user folder
             new \Folder($objHomeDir->path . '/' . $strUserDir);
             $objUserDir = \FilesModel::findByPath($objHomeDir->path . '/' . $strUserDir);
             // Save the folder ID
             $objNewUser->assignDir = 1;
             $objNewUser->homeDir = $objUserDir->uuid;
             $objNewUser->save();
         }
     }
     // HOOK: send insert ID and user data
     if (isset($GLOBALS['TL_HOOKS']['createNewUser']) && is_array($GLOBALS['TL_HOOKS']['createNewUser'])) {
         foreach ($GLOBALS['TL_HOOKS']['createNewUser'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($insertId, $arrData, $this);
         }
     }
     // Inform admin if no activation link is sent
     if (!$this->reg_activate) {
         $this->sendAdminNotification($insertId, $arrData);
     }
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
Exemplo n.º 20
0
 /**
  * Send an admin notification e-mail
  * @param integer
  * @param array
  */
 protected function sendAdminNotification($intId, $arrData)
 {
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['adminSubject'], \Environment::get('host'));
     $strData = "\n\n";
     // Add user details
     foreach ($arrData as $k => $v) {
         if ($k == 'password' || $k == 'tstamp' || $k == 'activation') {
             continue;
         }
         $v = deserialize($v);
         if ($k == 'dateOfBirth' && strlen($v)) {
             $v = $this->parseDate($GLOBALS['TL_CONFIG']['dateFormat'], $v);
         }
         $strData .= $GLOBALS['TL_LANG']['tl_member'][$k][0] . ': ' . (is_array($v) ? implode(', ', $v) : $v) . "\n";
     }
     $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['adminText'], $intId, $strData . "\n") . "\n";
     $objEmail->sendTo($GLOBALS['TL_ADMIN_EMAIL']);
     $this->log('A new user (ID ' . $intId . ') has registered on the website', 'ModuleRegistration sendAdminNotification()', TL_ACCESS);
 }
Exemplo n.º 21
0
 /**
  * Notify the subscribers of new comments
  *
  * @param \CommentsModel $objComment
  */
 public static function notifyCommentsSubscribers(\CommentsModel $objComment)
 {
     // Notified already
     if ($objComment->notified) {
         return;
     }
     $objNotify = \CommentsNotifyModel::findActiveBySourceAndParent($objComment->source, $objComment->parent);
     // No subscriptions
     if ($objNotify === null) {
         return;
     }
     while ($objNotify->next()) {
         // Don't notify the commentor about his own comment
         if ($objNotify->email == $objComment->email) {
             continue;
         }
         // Prepare the URL
         $strUrl = \Idna::decode(\Environment::get('base')) . $objNotify->url;
         $objEmail = new \Email();
         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['com_notifySubject'], \Idna::decode(\Environment::get('host')));
         $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['com_notifyMessage'], $objNotify->name, $strUrl, $strUrl . '?token=' . $objNotify->tokenRemove);
         $objEmail->sendTo($objNotify->email);
     }
     $objComment->notified = 1;
     $objComment->save();
 }
Exemplo n.º 22
0
 /**
  * Add a new recipient
  */
 protected function removeRecipient()
 {
     $arrChannels = $this->Input->post('channels');
     $arrChannels = array_intersect($arrChannels, $this->nl_channels);
     // see #3240
     // Check the selection
     if (!is_array($arrChannels) || count($arrChannels) < 1) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['noChannels'];
         $this->reload();
     }
     $varInput = $this->idnaEncodeEmail($this->Input->post('email', true));
     // Validate e-mail address
     if (!$this->isValidEmailAddress($varInput)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['email'];
         $this->reload();
     }
     $arrSubscriptions = array();
     // Get active subscriptions
     $objSubscription = $this->Database->prepare("SELECT pid FROM tl_newsletter_recipients WHERE email=? AND active=1")->execute($varInput);
     if ($objSubscription->numRows) {
         $arrSubscriptions = $objSubscription->fetchEach('pid');
     }
     $arrRemove = array_intersect($arrChannels, $arrSubscriptions);
     // Return if there are no subscriptions to remove
     if (!is_array($arrRemove) || count($arrRemove) < 1) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['unsubscribed'];
         $this->reload();
     }
     // Remove subscriptions
     $this->Database->prepare("DELETE FROM tl_newsletter_recipients WHERE email=? AND pid IN(" . implode(',', array_map('intval', $arrRemove)) . ")")->execute($varInput);
     // Get channels
     $objChannels = $this->Database->execute("SELECT title FROM tl_newsletter_channel WHERE id IN(" . implode(',', array_map('intval', $arrRemove)) . ")");
     $arrChannels = $objChannels->fetchEach('title');
     // Log activity
     $this->log($varInput . ' unsubscribed from ' . implode(', ', $arrChannels), 'ModuleUnsubscribe removeRecipient()', TL_NEWSLETTER);
     // HOOK: post unsubscribe callback
     if (isset($GLOBALS['TL_HOOKS']['removeRecipient']) && is_array($GLOBALS['TL_HOOKS']['removeRecipient'])) {
         foreach ($GLOBALS['TL_HOOKS']['removeRecipient'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($varInput, $arrRemove);
         }
     }
     // Confirmation e-mail
     $objEmail = new Email();
     $strText = str_replace('##domain##', $this->Environment->host, $this->nl_unsubscribe);
     $strText = str_replace(array('##channel##', '##channels##'), implode("\n", $arrChannels), $strText);
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['nl_subject'], $this->Environment->host);
     $objEmail->text = $strText;
     $objEmail->sendTo($varInput);
     global $objPage;
     // Redirect to jumpTo page
     if (strlen($this->jumpTo) && $this->jumpTo != $objPage->id) {
         $objNextPage = $this->Database->prepare("SELECT id, alias FROM tl_page WHERE id=?")->limit(1)->execute($this->jumpTo);
         if ($objNextPage->numRows) {
             $this->redirect($this->generateFrontendUrl($objNextPage->fetchAssoc()));
         }
     }
     $_SESSION['UNSUBSCRIBE_CONFIRM'] = $GLOBALS['TL_LANG']['MSC']['nl_removed'];
     $this->reload();
 }
Exemplo n.º 23
0
 /**
  * Create a new user and redirect
  * @param object
  */
 protected function sendPasswordLink($objMember)
 {
     $arrChunks = array();
     $confirmationId = md5(uniqid(mt_rand(), true));
     // Store the confirmation ID
     $objMember = \MemberModel::findByPk($objMember->id);
     $objMember->activation = $confirmationId;
     $objMember->save();
     $strConfirmation = $this->reg_password;
     preg_match_all('/##[^#]+##/', $strConfirmation, $arrChunks);
     foreach ($arrChunks[0] as $strChunk) {
         $strKey = substr($strChunk, 2, -2);
         switch ($strKey) {
             case 'domain':
                 $strConfirmation = str_replace($strChunk, \Idna::decode(\Environment::get('host')), $strConfirmation);
                 break;
             case 'link':
                 $strConfirmation = str_replace($strChunk, \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (\Config::get('disableAlias') || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $confirmationId, $strConfirmation);
                 break;
             default:
                 try {
                     $strConfirmation = str_replace($strChunk, $objMember->{$strKey}, $strConfirmation);
                 } catch (\Exception $e) {
                     $strConfirmation = str_replace($strChunk, '', $strConfirmation);
                     $this->log('Invalid wildcard "' . $strKey . '" used in password request e-mail', __METHOD__, TL_GENERAL, $e->getMessage());
                 }
                 break;
         }
     }
     // Send e-mail
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['passwordSubject'], \Idna::decode(\Environment::get('host')));
     $objEmail->text = $strConfirmation;
     $objEmail->sendTo($objMember->email);
     $this->log('A new password has been requested for user ID ' . $objMember->id . ' (' . $objMember->email . ')', __METHOD__, TL_ACCESS);
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
 protected function unregisterUser($objEvent)
 {
     \Database::getInstance()->prepare("DELETE FROM tl_event_registrations WHERE pid=? AND userId=?")->execute($objEvent->id, $this->User->id);
     $objMailerText = \Database::getInstance()->prepare("SELECT ser_cancel_subject AS subject, ser_cancel_text AS text, ser_cancel_html AS html FROM tl_calendar WHERE id=?")->execute($objEvent->pid);
     // Send notification
     $objEmail = new \Email();
     $strFrom = $GLOBALS['TL_CONFIG']['adminEmail'];
     $strNotify = $objEvent->ser_email != "" ? $objEvent->ser_email : $GLOBALS['TL_CONFIG']['adminEmail'];
     $span = \Calendar::calculateSpan($objEvent->startTime, $objEvent->endTime);
     // Get date
     if ($span > 0) {
         $objEvent->date = \Date::parse($GLOBALS['TL_CONFIG'][$objEvent->addTime ? 'datimFormat' : 'dateFormat'], $objEvent->startTime) . ' - ' . \Date::parse($GLOBALS['TL_CONFIG'][$objEvent->addTime ? 'datimFormat' : 'dateFormat'], $objEvent->endTime);
     } elseif ($objEvent->startTime == $objEvent->endTime) {
         $objEvent->date = \Date::parse($GLOBALS['TL_CONFIG']['dateFormat'], $objEvent->startTime) . ($objEvent->addTime ? ' (' . \Date::parse($GLOBALS['TL_CONFIG']['timeFormat'], $objEvent->startTime) . ')' : '');
     } else {
         $objEvent->date = \Date::parse($GLOBALS['TL_CONFIG']['dateFormat'], $objEvent->startTime) . ($objEvent->addTime ? ' (' . \Date::parse($GLOBALS['TL_CONFIG']['timeFormat'], $objEvent->startTime) . ' - ' . \Date::parse($GLOBALS['TL_CONFIG']['timeFormat'], $objEvent->endTime) . ')' : '');
     }
     $notifyText = $this->replaceInserts($objEvent, $GLOBALS['TL_LANG']['MSC']['ser_unregister_mail']);
     $notifySubject = $GLOBALS['TL_LANG']['MSC']['ser_unregister_subject'];
     $messageText = $this->replaceInserts($objEvent, html_entity_decode($objMailerText->text));
     $messageHTML = $this->replaceInserts($objEvent, html_entity_decode($objMailerText->html));
     $objEmail->from = $strFrom;
     $objEmail->subject = $this->replaceInserts($objEvent, html_entity_decode($objMailerText->subject));
     $objEmail->text = $messageText;
     $objEmail->html = $messageHTML;
     $objEmail->sendTo($this->User->email);
     $objEmail->subject = $this->replaceInserts($objEvent, html_entity_decode($notifySubject));
     $objEmail->text = $notifyText;
     $objEmail->html = nl2br($notifyText);
     $objEmail->sendTo($strNotify);
     $_SESSION['TL_SER_UNREGISTERED'] = true;
     $this->reload();
 }
Exemplo n.º 25
0
 /**
  * Try to login the current user
  * @return boolean
  */
 public function login()
 {
     $this->loadLanguageFile('default');
     // Do not continue if username or password are missing
     if (!$this->Input->post('username') || !$this->Input->post('password')) {
         return false;
     }
     // Load the user object
     if ($this->findBy('username', $this->Input->post('username')) == false) {
         $blnLoaded = false;
         // HOOK: pass credentials to callback functions
         if (isset($GLOBALS['TL_HOOKS']['importUser']) && is_array($GLOBALS['TL_HOOKS']['importUser'])) {
             foreach ($GLOBALS['TL_HOOKS']['importUser'] as $callback) {
                 $this->import($callback[0], 'objImport', true);
                 $blnLoaded = $this->objImport->{$callback}[1]($this->Input->post('username'), $this->Input->post('password'), $this->strTable);
                 // Load successfull
                 if ($blnLoaded === true) {
                     break;
                 }
             }
         }
         // Return if the user still cannot be loaded
         if (!$blnLoaded || $this->findBy('username', $this->Input->post('username')) == false) {
             $_SESSION['TL_ERROR'][] = $GLOBALS['TL_LANG']['ERR']['invalidLogin'];
             $this->log('Could not find user "' . $this->Input->post('username') . '"', get_class($this) . ' login()', TL_ACCESS);
             return false;
         }
     }
     $time = time();
     // Set the user language
     if ($this->Input->post('language')) {
         $this->language = $this->Input->post('language');
     }
     // Lock the account if there are too many login attempts
     if ($this->loginCount < 1) {
         $this->locked = $time;
         $this->loginCount = 3;
         $this->save();
         // Add a log entry
         $this->log('The account has been locked for security reasons', get_class($this) . ' login()', TL_ACCESS);
         // Send admin notification
         if (strlen($GLOBALS['TL_CONFIG']['adminEmail'])) {
             $objEmail = new Email();
             $objEmail->subject = 'A Contao account has been locked!';
             $objEmail->text = "The following Contao account has been locked for security reasons.\n\nUsername: "******"\nReal name: " . (TL_MODE == 'FE' ? $this->firstname . " " . $this->lastname : $this->name) . "\nWebsite: " . $this->Environment->base . "\n\nThe account has been locked for " . ceil($GLOBALS['TL_CONFIG']['lockPeriod'] / 60) . " minutes because a user has entered an invalid password three times in a row. After this period of time the account will be unlocked automatically.\n\nThis e-mail has been generated by Contao. You can not reply to it directly.\n";
             $objEmail->sendTo($GLOBALS['TL_CONFIG']['adminEmail']);
         }
         return false;
     }
     // Check the account status
     if ($this->checkAccountStatus() == false) {
         return false;
     }
     $blnAuthenticated = false;
     list($strPassword, $strSalt) = explode(':', $this->password);
     // Password is correct but not yet salted
     if (!strlen($strSalt) && $strPassword == sha1($this->Input->post('password'))) {
         $strSalt = substr(md5(uniqid(mt_rand(), true)), 0, 23);
         $strPassword = sha1($strSalt . $this->Input->post('password'));
         $this->password = $strPassword . ':' . $strSalt;
     }
     // Check the password against the database
     if (strlen($strSalt) && $strPassword == sha1($strSalt . $this->Input->post('password'))) {
         $blnAuthenticated = true;
     } elseif (isset($GLOBALS['TL_HOOKS']['checkCredentials']) && is_array($GLOBALS['TL_HOOKS']['checkCredentials'])) {
         foreach ($GLOBALS['TL_HOOKS']['checkCredentials'] as $callback) {
             $this->import($callback[0], 'objAuth', true);
             $blnAuthenticated = $this->objAuth->{$callback}[1]($this->Input->post('username'), $this->Input->post('password'), $this);
             // Authentication successfull
             if ($blnAuthenticated === true) {
                 break;
             }
         }
     }
     // Redirect if the user could not be authenticated
     if (!$blnAuthenticated) {
         --$this->loginCount;
         $this->save();
         $_SESSION['TL_ERROR'][] = $GLOBALS['TL_LANG']['ERR']['invalidLogin'];
         $this->log('Invalid password submitted for username "' . $this->username . '"', get_class($this) . ' login()', TL_ACCESS);
         return false;
     }
     $this->setUserFromDb();
     // Update the record
     $this->loginCount = 3;
     $this->lastLogin = $this->currentLogin;
     $this->currentLogin = $time;
     $this->save();
     // Generate the session
     $this->generateSession();
     $this->log('User "' . $this->username . '" has logged in', get_class($this) . ' login()', TL_ACCESS);
     // HOOK: post login callback
     if (isset($GLOBALS['TL_HOOKS']['postLogin']) && is_array($GLOBALS['TL_HOOKS']['postLogin'])) {
         foreach ($GLOBALS['TL_HOOKS']['postLogin'] as $callback) {
             $this->import($callback[0], 'objLogin', true);
             $this->objLogin->{$callback}[1]($this);
         }
     }
     return true;
 }
Exemplo n.º 26
0
 /**
  * Sends an information mail
  *
  * @param string $subject Subject of email
  * @param string $text    Content of email
  *
  * @return boolean true if sending email was successfull
  */
 protected function inform($subject, $text)
 {
     $this->import('Email');
     $mail = new Email();
     $mail->from = $this->ext404_email_from;
     $mail->subject = sprintf($subject, $this->Environment->host);
     $mail->text = sprintf($text, $this->request, $this->referer) . "\n";
     return $mail->sendTo($this->ext404_email_to);
 }
Exemplo n.º 27
0
 /**
  * Process form data, store it in the session and redirect to the jumpTo page
  *
  * @param array $arrSubmitted
  * @param array $arrLabels
  * @param array $arrFields
  */
 protected function processFormData($arrSubmitted, $arrLabels, $arrFields)
 {
     // HOOK: prepare form data callback
     if (isset($GLOBALS['TL_HOOKS']['prepareFormData']) && is_array($GLOBALS['TL_HOOKS']['prepareFormData'])) {
         foreach ($GLOBALS['TL_HOOKS']['prepareFormData'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($arrSubmitted, $arrLabels, $arrFields, $this);
         }
     }
     // Send form data via e-mail
     if ($this->sendViaEmail) {
         $keys = array();
         $values = array();
         $fields = array();
         $message = '';
         foreach ($arrSubmitted as $k => $v) {
             if ($k == 'cc') {
                 continue;
             }
             $v = deserialize($v);
             // Skip empty fields
             if ($this->skipEmpty && !is_array($v) && !strlen($v)) {
                 continue;
             }
             // Add field to message
             $message .= (isset($arrLabels[$k]) ? $arrLabels[$k] : ucfirst($k)) . ': ' . (is_array($v) ? implode(', ', $v) : $v) . "\n";
             // Prepare XML file
             if ($this->format == 'xml') {
                 $fields[] = array('name' => $k, 'values' => is_array($v) ? $v : array($v));
             }
             // Prepare CSV file
             if ($this->format == 'csv') {
                 $keys[] = $k;
                 $values[] = is_array($v) ? implode(',', $v) : $v;
             }
         }
         $recipients = \StringUtil::splitCsv($this->recipient);
         // Format recipients
         foreach ($recipients as $k => $v) {
             $recipients[$k] = str_replace(array('[', ']', '"'), array('<', '>', ''), $v);
         }
         $email = new \Email();
         // Get subject and message
         if ($this->format == 'email') {
             $message = $arrSubmitted['message'];
             $email->subject = $arrSubmitted['subject'];
         }
         // Set the admin e-mail as "from" address
         $email->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $email->fromName = $GLOBALS['TL_ADMIN_NAME'];
         // Get the "reply to" address
         if (strlen(\Input::post('email', true))) {
             $replyTo = \Input::post('email', true);
             // Add name
             if (strlen(\Input::post('name'))) {
                 $replyTo = '"' . \Input::post('name') . '" <' . $replyTo . '>';
             }
             $email->replyTo($replyTo);
         }
         // Fallback to default subject
         if (!strlen($email->subject)) {
             $email->subject = $this->replaceInsertTags($this->subject, false);
         }
         // Send copy to sender
         if (strlen($arrSubmitted['cc'])) {
             $email->sendCc(\Input::post('email', true));
             unset($_SESSION['FORM_DATA']['cc']);
         }
         // Attach XML file
         if ($this->format == 'xml') {
             /** @var \FrontendTemplate|object $objTemplate */
             $objTemplate = new \FrontendTemplate('form_xml');
             $objTemplate->fields = $fields;
             $objTemplate->charset = \Config::get('characterSet');
             $email->attachFileFromString($objTemplate->parse(), 'form.xml', 'application/xml');
         }
         // Attach CSV file
         if ($this->format == 'csv') {
             $email->attachFileFromString(\StringUtil::decodeEntities('"' . implode('";"', $keys) . '"' . "\n" . '"' . implode('";"', $values) . '"'), 'form.csv', 'text/comma-separated-values');
         }
         $uploaded = '';
         // Attach uploaded files
         if (!empty($_SESSION['FILES'])) {
             foreach ($_SESSION['FILES'] as $file) {
                 // Add a link to the uploaded file
                 if ($file['uploaded']) {
                     $uploaded .= "\n" . \Environment::get('base') . str_replace(TL_ROOT . '/', '', dirname($file['tmp_name'])) . '/' . rawurlencode($file['name']);
                     continue;
                 }
                 $email->attachFileFromString(file_get_contents($file['tmp_name']), $file['name'], $file['type']);
             }
         }
         $uploaded = strlen(trim($uploaded)) ? "\n\n---\n" . $uploaded : '';
         $email->text = \StringUtil::decodeEntities(trim($message)) . $uploaded . "\n\n";
         // Send the e-mail
         try {
             $email->sendTo($recipients);
         } catch (\Swift_SwiftException $e) {
             $this->log('Form "' . $this->title . '" could not be sent: ' . $e->getMessage(), __METHOD__, TL_ERROR);
         }
     }
     // Store the values in the database
     if ($this->storeValues && $this->targetTable != '') {
         $arrSet = array();
         // Add the timestamp
         if ($this->Database->fieldExists('tstamp', $this->targetTable)) {
             $arrSet['tstamp'] = time();
         }
         // Fields
         foreach ($arrSubmitted as $k => $v) {
             if ($k != 'cc' && $k != 'id') {
                 $arrSet[$k] = $v;
                 // Convert date formats into timestamps (see #6827)
                 if ($arrSet[$k] != '' && in_array($arrFields[$k]->rgxp, array('date', 'time', 'datim'))) {
                     $objDate = new \Date($arrSet[$k], \Date::getFormatFromRgxp($arrFields[$k]->rgxp));
                     $arrSet[$k] = $objDate->tstamp;
                 }
             }
         }
         // Files
         if (!empty($_SESSION['FILES'])) {
             foreach ($_SESSION['FILES'] as $k => $v) {
                 if ($v['uploaded']) {
                     $arrSet[$k] = str_replace(TL_ROOT . '/', '', $v['tmp_name']);
                 }
             }
         }
         // HOOK: store form data callback
         if (isset($GLOBALS['TL_HOOKS']['storeFormData']) && is_array($GLOBALS['TL_HOOKS']['storeFormData'])) {
             foreach ($GLOBALS['TL_HOOKS']['storeFormData'] as $callback) {
                 $this->import($callback[0]);
                 $arrSet = $this->{$callback}[0]->{$callback}[1]($arrSet, $this);
             }
         }
         // Set the correct empty value (see #6284, #6373)
         foreach ($arrSet as $k => $v) {
             if ($v === '') {
                 $arrSet[$k] = \Widget::getEmptyValueByFieldType($GLOBALS['TL_DCA'][$this->targetTable]['fields'][$k]['sql']);
             }
         }
         // Do not use Models here (backwards compatibility)
         $this->Database->prepare("INSERT INTO " . $this->targetTable . " %s")->set($arrSet)->execute();
     }
     // Store all values in the session
     foreach (array_keys($_POST) as $key) {
         $_SESSION['FORM_DATA'][$key] = $this->allowTags ? \Input::postHtml($key, true) : \Input::post($key, true);
     }
     $arrFiles = $_SESSION['FILES'];
     // HOOK: process form data callback
     if (isset($GLOBALS['TL_HOOKS']['processFormData']) && is_array($GLOBALS['TL_HOOKS']['processFormData'])) {
         foreach ($GLOBALS['TL_HOOKS']['processFormData'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($arrSubmitted, $this->arrData, $arrFiles, $arrLabels, $this);
         }
     }
     $_SESSION['FILES'] = array();
     // DO NOT CHANGE
     // Add a log entry
     if (FE_USER_LOGGED_IN) {
         $this->import('FrontendUser', 'User');
         $this->log('Form "' . $this->title . '" has been submitted by "' . $this->User->username . '".', __METHOD__, TL_FORMS);
     } else {
         $this->log('Form "' . $this->title . '" has been submitted by ' . \System::anonymizeIp(\Environment::get('ip')) . '.', __METHOD__, TL_FORMS);
     }
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
Exemplo n.º 28
0
 /**
  * Compile the newsletter and send it
  *
  * @param \Email                  $objEmail
  * @param \Database\Result|object $objNewsletter
  * @param array                   $arrRecipient
  * @param string                  $text
  * @param string                  $html
  * @param string                  $css
  *
  * @return string
  */
 protected function sendNewsletter(\Email $objEmail, \Database\Result $objNewsletter, $arrRecipient, $text, $html, $css = null)
 {
     // Prepare the text content
     $objEmail->text = \String::parseSimpleTokens($text, $arrRecipient);
     if (!$objNewsletter->sendText) {
         // Default template
         if ($objNewsletter->template == '') {
             $objNewsletter->template = 'mail_default';
         }
         /** @var \BackendTemplate|object $objTemplate */
         $objTemplate = new \BackendTemplate($objNewsletter->template);
         $objTemplate->setData($objNewsletter->row());
         $objTemplate->title = $objNewsletter->subject;
         $objTemplate->body = \String::parseSimpleTokens($html, $arrRecipient);
         $objTemplate->charset = \Config::get('characterSet');
         $objTemplate->css = $css;
         // Backwards compatibility
         $objTemplate->recipient = $arrRecipient['email'];
         // Parse template
         $objEmail->html = $objTemplate->parse();
         $objEmail->imageDir = TL_ROOT . '/';
     }
     // Deactivate invalid addresses
     try {
         $objEmail->sendTo($arrRecipient['email']);
     } catch (\Swift_RfcComplianceException $e) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
     // Rejected recipients
     if ($objEmail->hasFailures()) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['sendNewsletter']) && is_array($GLOBALS['TL_HOOKS']['sendNewsletter'])) {
         foreach ($GLOBALS['TL_HOOKS']['sendNewsletter'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($objEmail, $objNewsletter, $arrRecipient, $text, $html);
         }
     }
 }
Exemplo n.º 29
0
 /**
  * Add comments to a template
  * @param FrontendTemplate
  * @param stdClass
  * @param string
  * @param integer
  * @param array
  */
 public function addCommentsToTemplate(FrontendTemplate $objTemplate, stdClass $objConfig, $strSource, $intParent, $arrNotifies)
 {
     global $objPage;
     $this->import('String');
     $limit = null;
     $arrComments = array();
     // Pagination
     if ($objConfig->perPage > 0) {
         // Get the total number of comments
         $objTotal = $this->Database->prepare("SELECT COUNT(*) AS count FROM tl_comments WHERE source=? AND parent=?" . (!BE_USER_LOGGED_IN ? " AND published=1" : ""))->execute($strSource, $intParent);
         $total = $objTotal->count;
         // Get the current page
         $page = $this->Input->get('page') ? $this->Input->get('page') : 1;
         // Do not index or cache the page if the page number is outside the range
         if ($page < 1 || $page > max(ceil($total / $objConfig->perPage), 1)) {
             global $objPage;
             $objPage->noSearch = 1;
             $objPage->cache = 0;
             // Send a 404 header
             header('HTTP/1.1 404 Not Found');
             $objTemplate->allowComments = false;
             $objTemplate->comments = array();
             // see #4064
             return;
         }
         // Set limit and offset
         $limit = $objConfig->perPage;
         $offset = ($page - 1) * $objConfig->perPage;
         // Initialize the pagination menu
         $objPagination = new Pagination($objTotal->count, $objConfig->perPage);
         $objTemplate->pagination = $objPagination->generate("\n  ");
     }
     $objTemplate->allowComments = true;
     // Get all published comments
     $objCommentsStmt = $this->Database->prepare("SELECT c.*, u.name as authorName FROM tl_comments c LEFT JOIN tl_user u ON c.author=u.id WHERE c.source=? AND c.parent=?" . (!BE_USER_LOGGED_IN ? " AND c.published=1" : "") . " ORDER BY c.date" . ($objConfig->order == 'descending' ? " DESC" : ""));
     if ($limit) {
         $objCommentsStmt->limit($limit, $offset);
     }
     $objComments = $objCommentsStmt->execute($strSource, $intParent);
     $total = $objComments->numRows;
     if ($total > 0) {
         $count = 0;
         if ($objConfig->template == '') {
             $objConfig->template = 'com_default';
         }
         $objPartial = new FrontendTemplate($objConfig->template);
         while ($objComments->next()) {
             $objPartial->setData($objComments->row());
             // Clean the RTE output
             if ($objPage->outputFormat == 'xhtml') {
                 $objComments->comment = $this->String->toXhtml($objComments->comment);
             } else {
                 $objComments->comment = $this->String->toHtml5($objComments->comment);
             }
             $objPartial->comment = trim(str_replace(array('{{', '}}'), array('&#123;&#123;', '&#125;&#125;'), $objComments->comment));
             $objPartial->datim = $this->parseDate($objPage->datimFormat, $objComments->date);
             $objPartial->date = $this->parseDate($objPage->dateFormat, $objComments->date);
             $objPartial->class = ($count < 1 ? ' first' : '') . ($count >= $total - 1 ? ' last' : '') . ($count % 2 == 0 ? ' even' : ' odd');
             $objPartial->by = $GLOBALS['TL_LANG']['MSC']['comment_by'];
             $objPartial->id = 'c' . $objComments->id;
             $objPartial->timestamp = $objComments->date;
             $objPartial->datetime = date('Y-m-d\\TH:i:sP', $objComments->date);
             $objPartial->addReply = false;
             // Reply
             if ($objComments->addReply && $objComments->reply != '' && $objComments->authorName != '') {
                 $objPartial->addReply = true;
                 $objPartial->rby = $GLOBALS['TL_LANG']['MSC']['reply_by'];
                 $objPartial->reply = $this->replaceInsertTags($objComments->reply);
                 // Clean the RTE output
                 if ($objPage->outputFormat == 'xhtml') {
                     $objPartial->reply = $this->String->toXhtml($objPartial->reply);
                 } else {
                     $objPartial->reply = $this->String->toHtml5($objPartial->reply);
                 }
             }
             $arrComments[] = $objPartial->parse();
             ++$count;
         }
     }
     $objTemplate->comments = $arrComments;
     $objTemplate->addComment = $GLOBALS['TL_LANG']['MSC']['addComment'];
     $objTemplate->name = $GLOBALS['TL_LANG']['MSC']['com_name'];
     $objTemplate->email = $GLOBALS['TL_LANG']['MSC']['com_email'];
     $objTemplate->website = $GLOBALS['TL_LANG']['MSC']['com_website'];
     $objTemplate->commentsTotal = $limit ? $objTotal->count : $total;
     // Get the front end user object
     $this->import('FrontendUser', 'User');
     // Access control
     if ($objConfig->requireLogin && !BE_USER_LOGGED_IN && !FE_USER_LOGGED_IN) {
         $objTemplate->requireLogin = true;
         return;
     }
     // Form fields
     $arrFields = array('name' => array('name' => 'name', 'label' => $GLOBALS['TL_LANG']['MSC']['com_name'], 'value' => trim($this->User->firstname . ' ' . $this->User->lastname), 'inputType' => 'text', 'eval' => array('mandatory' => true, 'maxlength' => 64)), 'email' => array('name' => 'email', 'label' => $GLOBALS['TL_LANG']['MSC']['com_email'], 'value' => $this->User->email, 'inputType' => 'text', 'eval' => array('rgxp' => 'email', 'mandatory' => true, 'maxlength' => 128, 'decodeEntities' => true)), 'website' => array('name' => 'website', 'label' => $GLOBALS['TL_LANG']['MSC']['com_website'], 'inputType' => 'text', 'eval' => array('rgxp' => 'url', 'maxlength' => 128, 'decodeEntities' => true)));
     // Captcha
     if (!$objConfig->disableCaptcha) {
         $arrFields['captcha'] = array('name' => 'captcha', 'inputType' => 'captcha', 'eval' => array('mandatory' => true));
     }
     // Comment field
     $arrFields['comment'] = array('name' => 'comment', 'label' => $GLOBALS['TL_LANG']['MSC']['com_comment'], 'inputType' => 'textarea', 'eval' => array('mandatory' => true, 'rows' => 4, 'cols' => 40, 'preserveTags' => true));
     $doNotSubmit = false;
     $arrWidgets = array();
     $strFormId = 'com_' . $strSource . '_' . $intParent;
     // Initialize widgets
     foreach ($arrFields as $arrField) {
         $strClass = $GLOBALS['TL_FFL'][$arrField['inputType']];
         // Continue if the class is not defined
         if (!$this->classFileExists($strClass)) {
             continue;
         }
         $arrField['eval']['required'] = $arrField['eval']['mandatory'];
         $objWidget = new $strClass($this->prepareForWidget($arrField, $arrField['name'], $arrField['value']));
         // Validate the widget
         if ($this->Input->post('FORM_SUBMIT') == $strFormId) {
             $objWidget->validate();
             if ($objWidget->hasErrors()) {
                 $doNotSubmit = true;
             }
         }
         $arrWidgets[$arrField['name']] = $objWidget;
     }
     $objTemplate->fields = $arrWidgets;
     $objTemplate->submit = $GLOBALS['TL_LANG']['MSC']['com_submit'];
     $objTemplate->action = ampersand($this->Environment->request);
     $objTemplate->messages = '';
     // Backwards compatibility
     $objTemplate->formId = $strFormId;
     $objTemplate->hasError = $doNotSubmit;
     // Do not index or cache the page with the confirmation message
     if ($_SESSION['TL_COMMENT_ADDED']) {
         global $objPage;
         $objPage->noSearch = 1;
         $objPage->cache = 0;
         $objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['com_confirm'];
         $_SESSION['TL_COMMENT_ADDED'] = false;
     }
     // Add the comment
     if ($this->Input->post('FORM_SUBMIT') == $strFormId && !$doNotSubmit) {
         $this->import('String');
         $strWebsite = $arrWidgets['website']->value;
         // Add http:// to the website
         if ($strWebsite != '' && !preg_match('@^(https?://|ftp://|mailto:|#)@i', $strWebsite)) {
             $strWebsite = 'http://' . $strWebsite;
         }
         // Do not parse any tags in the comment
         $strComment = htmlspecialchars(trim($arrWidgets['comment']->value));
         $strComment = str_replace(array('&amp;', '&lt;', '&gt;'), array('[&]', '[lt]', '[gt]'), $strComment);
         // Remove multiple line feeds
         $strComment = preg_replace('@\\n\\n+@', "\n\n", $strComment);
         // Parse BBCode
         if ($objConfig->bbcode) {
             $strComment = $this->parseBbCode($strComment);
         }
         // Prevent cross-site request forgeries
         $strComment = preg_replace('/(href|src|on[a-z]+)="[^"]*(contao\\/main\\.php|typolight\\/main\\.php|javascript|vbscri?pt|script|alert|document|cookie|window)[^"]*"+/i', '$1="#"', $strComment);
         $time = time();
         // Prepare the record
         $arrSet = array('source' => $strSource, 'parent' => $intParent, 'tstamp' => $time, 'name' => $arrWidgets['name']->value, 'email' => $arrWidgets['email']->value, 'website' => $strWebsite, 'comment' => $this->convertLineFeeds($strComment), 'ip' => $this->anonymizeIp($this->Environment->ip), 'date' => $time, 'published' => $objConfig->moderate ? '' : 1);
         $insertId = $this->Database->prepare("INSERT INTO tl_comments %s")->set($arrSet)->execute()->insertId;
         // HOOK: add custom logic
         if (isset($GLOBALS['TL_HOOKS']['addComment']) && is_array($GLOBALS['TL_HOOKS']['addComment'])) {
             foreach ($GLOBALS['TL_HOOKS']['addComment'] as $callback) {
                 $this->import($callback[0]);
                 $this->{$callback}[0]->{$callback}[1]($insertId, $arrSet, $this);
             }
         }
         // Notification
         $objEmail = new Email();
         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['com_subject'], $this->Environment->host);
         // Convert the comment to plain text
         $strComment = strip_tags($strComment);
         $strComment = $this->String->decodeEntities($strComment);
         $strComment = str_replace(array('[&]', '[lt]', '[gt]'), array('&', '<', '>'), $strComment);
         // Add comment details
         $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['com_message'], $arrSet['name'] . ' (' . $arrSet['email'] . ')', $strComment, $this->Environment->base . $this->Environment->request, $this->Environment->base . 'contao/main.php?do=comments&act=edit&id=' . $insertId);
         // Do not send notifications twice
         if (is_array($arrNotifies)) {
             $arrNotifies = array_unique($arrNotifies);
         }
         $objEmail->sendTo($arrNotifies);
         // Pending for approval
         if ($objConfig->moderate) {
             $_SESSION['TL_COMMENT_ADDED'] = true;
         }
         $this->reload();
     }
 }
Exemplo n.º 30
0
 /**
  * Create a new user and redirect
  * @param Database_Result
  */
 protected function sendPasswordLink(Database_Result $objMember)
 {
     $arrChunks = array();
     $confirmationId = md5(uniqid(mt_rand(), true));
     // Store confirmation ID
     $this->Database->prepare("UPDATE tl_member SET activation=? WHERE id=?")->execute($confirmationId, $objMember->id);
     $strConfirmation = $this->reg_password;
     preg_match_all('/##[^#]+##/i', $strConfirmation, $arrChunks);
     foreach ($arrChunks[0] as $strChunk) {
         $strKey = substr($strChunk, 2, -2);
         switch ($strKey) {
             case 'domain':
                 $strConfirmation = str_replace($strChunk, $this->Environment->host, $strConfirmation);
                 break;
             case 'link':
                 $strConfirmation = str_replace($strChunk, $this->Environment->base . $this->Environment->request . ($GLOBALS['TL_CONFIG']['disableAlias'] || strpos($this->Environment->request, '?') !== false ? '&' : '?') . 'token=' . $confirmationId, $strConfirmation);
                 break;
             default:
                 try {
                     $strConfirmation = str_replace($strChunk, $objMember->{$strKey}, $strConfirmation);
                 } catch (Exception $e) {
                     $strConfirmation = str_replace($strChunk, '', $strConfirmation);
                     $this->log('Invalid wildcard "' . $strKey . '" used in password request e-mail', 'ModulePassword sendPasswordLink()', TL_GENERAL, $e->getMessage());
                 }
                 break;
         }
     }
     // Send e-mail
     $objEmail = new Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['passwordSubject'], $this->Environment->host);
     $objEmail->text = $strConfirmation;
     $objEmail->sendTo($objMember->email);
     $this->log('A new password has been requested for user ID ' . $objMember->id . ' (' . $objMember->email . ')', 'ModulePassword sendPasswordLink()', TL_ACCESS);
     $this->jumpToOrReload($this->jumpTo);
 }