Exemple #1
0
 public function Process()
 {
     // Newsletter component disabled or not found. Aborting.
     if (!$this->enabled) {
         return true;
     }
     $config = acymailing_config();
     // Build subscriber object
     $subscriber = new stdClass();
     // Name field may be absent. AcyMailing will guess the user's name from his email address
     $subscriber->name = isset($this->FieldsBuilder->Fields['sender0']) ? $this->FieldsBuilder->Fields['sender0']['Value'] : "";
     // AcyMailing refuses to save the user (return false) if the email address is empty, so we don't care to check it
     $subscriber->email = empty($this->FieldsBuilder->Fields['sender1']['Value']) ? NULL : JMailHelper::cleanAddress($this->FieldsBuilder->Fields['sender1']['Value']);
     // It seems that $subscriber->confirmed defaults to unconfirmed if unset, so we need to read and pass the actual value from the configuration
     //ADRIEN : not necessary, you should keep the user as unconfirmed, Acy will take care of that
     //$subscriber->confirmed = !(bool)$config->get('require_confirmation');
     $userClass = acymailing_get('class.subscriber');
     $userClass->checkVisitor = false;
     // Add or update the user
     $sub_id = $userClass->save($subscriber);
     if (empty($sub_id)) {
         // User save failed. Probably email address is empty or invalid
         $this->logger->Write(get_class($this) . " Process(): User save failed");
         return true;
     }
     // Lists
     $cumulative = JRequest::getVar("acymailing_subscribe_cumulative", NULL, "POST");
     $checkboxes = array(FAcyMailing::subscribe => JRequest::getVar("acymailing_subscribe", array(), "POST"));
     $lists = $cumulative ? $checkboxes : array();
     // Subscription
     //$listsubClass = acymailing_get('class.listsub');
     //$listsubClass->addSubscription($sub_id, $lists);
     // ADRIEN : we use an other function so Acy will check the subscription and only subscribe the user if he was not already subscribed to that list.
     /*
     $newSubscription = array();
     if(!empty($lists)){
     foreach($lists[FAcyMailing::subscribe] as $listId){
     $newList = array();
     $newList['status'] = FAcyMailing::subscribe;
     $newSubscription[$listId] = $newList;
     }
     $userClass->saveSubscription($sub_id, $newSubscription);
     }
     */
     // When in mode "one checkbox for each list" and no lists selected the code above produce an SQL error because passes an empty array to saveSubscription()
     $newSubscription = array();
     foreach ($lists[FAcyMailing::subscribe] as $listId) {
         $newList = array();
         $newList['status'] = FAcyMailing::subscribe;
         $newSubscription[$listId] = $newList;
     }
     if (!empty($newSubscription)) {
         $userClass->saveSubscription($sub_id, $newSubscription);
     }
     // implode() doesn't accept NULL values :(
     @$lists[FAcyMailing::subscribe] or $lists[FAcyMailing::subscribe] = array();
     // Log
     $this->logger->Write(get_class($this) . " Process(): subscribed " . $this->FieldsBuilder->Fields['sender0']['Value'] . " (" . $this->FieldsBuilder->Fields['sender1']['Value'] . ") to lists " . implode(",", $lists[FAcyMailing::subscribe]));
     return true;
 }
	/**
	 * @group	     framework.mail
	 * @dataProvider getCleanAddressData
	 */
	public function testCleanAddress( $input, $expected )
	{
		$this->assertThat(
			JMailHelper::cleanAddress( $input ),
			$this->equalTo( $expected )
		);
	}
Exemple #3
0
 protected function submitteraddress()
 {
     // Bug: http://www.fox.ra.it/forum/3-bugs/2399-error-when-email-is-optional-and-field-is-left-empty.html
     // $from = isset($this->FieldsBuilder->Fields['sender1']['Value']) ? $this->FieldsBuilder->Fields['sender1']['Value'] : $this->Application->getCfg("mailfrom");
     // If submitter address is present and not empty, we can use it
     // otherwise system global address will be used
     $addr = isset($this->FieldsBuilder->Fields['sender1']['Value']) && !empty($this->FieldsBuilder->Fields['sender1']['Value']) ? $this->FieldsBuilder->Fields['sender1']['Value'] : $this->Application->getCfg("mailfrom");
     return JMailHelper::cleanAddress($addr);
 }
Exemple #4
0
 public function Process()
 {
     // Newsletter component disabled or not found. Aborting.
     if (!$this->enabled) {
         return true;
     }
     $config = new jNews_Config();
     // Build subscriber object
     $subscriber = new stdClass();
     // Lists
     $cumulative = $this->JInput->post->get("jnews_subscribe_cumulative", NULL, "int");
     $checkboxes = $this->JInput->post->get("jnews_subscribe", array(), "array");
     $subscriber->list_id = $cumulative ? $checkboxes : array();
     // No lists selected. Skip here to avoid annoying the user with email confirmation. It is useless to confirm a subscription to no lists.
     if (empty($subscriber->list_id)) {
         return true;
     }
     // Name field may be absent. JNews will assign an empty name to the user.
     $subscriber->name = isset($this->FieldsBuilder->Fields['sender0']) ? $this->FieldsBuilder->Fields['sender0']['Value'] : "";
     $subscriber->email = empty($this->FieldsBuilder->Fields['sender1']['Value']) ? NULL : JMailHelper::cleanAddress($this->FieldsBuilder->Fields['sender1']['Value']);
     // JNews saves users with empty email address, so we have to check it
     if (empty($subscriber->email)) {
         $this->logger->Write(get_class($this) . " Process(): Email address empty. User save aborted.");
         return true;
     }
     // It seems that $subscriber->confirmed defaults to unconfirmed if unset, so we need to read and pass the actual value from the configuration
     $subscriber->confirmed = !(bool) $config->get('require_confirmation');
     $subscriber->receive_html = 1;
     // Avoid Notice: Undefined property while JNews libraries access undefined properties
     $subscriber->ip = jNews_Subscribers::getIP();
     $subscriber->subscribe_date = jnews::getNow();
     $subscriber->language_iso = "eng";
     $subscriber->timezone = "00:00:00";
     $subscriber->blacklist = 0;
     $subscriber->user_id = JFactory::getUser()->id;
     // Subscription
     $sub_id = null;
     jNews_Subscribers::saveSubscriber($subscriber, $sub_id, true);
     if (empty($sub_id)) {
         // User save failed. Probably email address is empty or invalid
         $this->logger->Write(get_class($this) . " Process(): User save failed");
         return true;
     }
     // Subscribe $subscriber to $subscriber->list_id
     //$subscriber->id = $sub_id;
     // jNews_ListsSubs::saveToListSubscribers() doesn't work well. When only one list is passed to, it reads the value $listids[0],
     // but the element 0 is not always the first element of the array. In our case is $listids[1]
     //jNews_ListsSubs::saveToListSubscribers($subscriber);
     $this->SaveSubscription($subscriber);
     // Log
     $this->logger->Write(get_class($this) . " Process(): subscribed " . $this->FieldsBuilder->Fields['sender0']['Value'] . " (" . $this->FieldsBuilder->Fields['sender1']['Value'] . ") to lists " . implode(",", $subscriber->list_id));
     return true;
 }
 public function Process()
 {
     // Newsletter component disabled or not found. Aborting.
     if (!$this->enabled) {
         return true;
     }
     //$config = acymailing_config();
     // Lists
     $cumulative = $this->JInput->post->get("acymailing_subscribe_cumulative", NULL, "int");
     $checkboxes = array(FAcyMailing::subscribe => $this->JInput->post->get("acymailing_subscribe", array(), "array"));
     $lists = $cumulative ? $checkboxes : array();
     // When subscription requires confirmation (double opt-in) AcyMailing sends a confirmation request to the user as soon as the user himself is saved. $userClass->save($subscriber)
     // Even in case of no list selected the user will be annoyed with a confirmation email
     // The confirmation status doesn't depend on the lists, which will be passed to AcyMailing only a few lines later. $userClass->saveSubscription($sub_id, $newSubscription)
     if (empty($lists[FAcyMailing::subscribe])) {
         return true;
     }
     // Build subscriber object
     $subscriber = new stdClass();
     // Name field may be absent. AcyMailing will guess the user's name from his email address
     $subscriber->name = isset($this->FieldsBuilder->Fields['sender0']) ? $this->FieldsBuilder->Fields['sender0']['Value'] : "";
     // AcyMailing refuses to save the user (return false) if the email address is empty, so we don't care to check it
     $subscriber->email = empty($this->FieldsBuilder->Fields['sender1']['Value']) ? NULL : JMailHelper::cleanAddress($this->FieldsBuilder->Fields['sender1']['Value']);
     $userClass = acymailing_get('class.subscriber');
     $userClass->checkVisitor = false;
     // Add or update the user
     $sub_id = $userClass->save($subscriber);
     if (empty($sub_id)) {
         // User save failed. Probably email address is empty or invalid
         $this->logger->Write(get_class($this) . " Process(): User save failed");
         return true;
     }
     // When in mode "one checkbox for each list" and no lists selected the code above produce an SQL error because passes an empty array to saveSubscription()
     $newSubscription = array();
     foreach ($lists[FAcyMailing::subscribe] as $listId) {
         $newList = array();
         $newList['status'] = FAcyMailing::subscribe;
         $newSubscription[$listId] = $newList;
     }
     if (!empty($newSubscription)) {
         $userClass->saveSubscription($sub_id, $newSubscription);
     }
     // implode() doesn't accept NULL values :(
     @$lists[FAcyMailing::subscribe] or $lists[FAcyMailing::subscribe] = array();
     // Log
     $this->logger->Write(get_class($this) . " Process(): subscribed " . $this->FieldsBuilder->Fields['sender0']['Value'] . " (" . $this->FieldsBuilder->Fields['sender1']['Value'] . ") to lists " . implode(",", $lists[FAcyMailing::subscribe]));
     return true;
 }
Exemple #6
0
 /**
  * @param  JMail  $mail
  * @param  array  $receivers
  *
  * @return boolean
  */
 public static function send(JMail $mail, array $receivers)
 {
     $config = KunenaFactory::getConfig();
     if (!empty($config->email_recipient_count)) {
         $email_recipient_count = $config->email_recipient_count;
     } else {
         $email_recipient_count = 1;
     }
     $email_recipient_privacy = $config->get('email_recipient_privacy', 'bcc');
     // If we hide email addresses from other users, we need to add TO address to prevent email from becoming spam.
     if ($email_recipient_count > 1 && $email_recipient_privacy == 'bcc' && JMailHelper::isEmailAddress($config->get('email_visible_address'))) {
         $mail->AddAddress($config->email_visible_address, JMailHelper::cleanAddress($config->board_title));
         // Also make sure that email receiver limits are not violated (TO + CC + BCC = limit).
         if ($email_recipient_count > 9) {
             $email_recipient_count--;
         }
     }
     $chunks = array_chunk($receivers, $email_recipient_count);
     $success = true;
     foreach ($chunks as $emails) {
         if ($email_recipient_count == 1 || $email_recipient_privacy == 'to') {
             echo 'TO ';
             $mail->ClearAddresses();
             $mail->addRecipient($emails);
         } elseif ($email_recipient_privacy == 'cc') {
             echo 'CC ';
             $mail->ClearCCs();
             $mail->addCC($emails);
         } else {
             echo 'BCC ';
             $mail->ClearBCCs();
             $mail->addBCC($emails);
         }
         try {
             $mail->Send();
         } catch (Exception $e) {
             $success = false;
             JLog::add($e->getMessage(), JLog::ERROR, 'kunena');
         }
     }
     return $success;
 }
Exemple #7
0
 /**
  * @param EventgalleryLibraryOrder $order
  *
  * @return mixed|string
  */
 protected function _sendOrderConfirmationMail($order)
 {
     $config = JFactory::getConfig();
     $params = JComponentHelper::getParams('com_eventgallery');
     $sitename = $config->get('sitename');
     $view = $this->getView('Mail', 'html', 'EventgalleryView', array('layout' => 'confirm'));
     $view->set('order', $order);
     $view->set('params', $params);
     $body = $view->loadTemplate();
     $mailer = JFactory::getMailer();
     $config = JFactory::getConfig();
     $subject = JText::sprintf('COM_EVENTGALLERY_CART_CHECKOUT_ORDER_MAIL_CONFIRMATION_SUBJECT', $order->getBillingAddress()->getFirstName() . ' ' . $order->getBillingAddress()->getLastName(), $order->getLineItemsTotalCount(), $order->getLineItemsCount());
     $mailer->setSubject("{$sitename} - " . $subject);
     $mailer->isHTML(true);
     $mailer->Encoding = 'base64';
     $mailer->setBody($body);
     // Customer Mail
     $sender = array($config->get('mailfrom'), $config->get('fromname'));
     $mailer->setSender($sender);
     $mailer->addRecipient($order->getEMail(), $order->getBillingAddress()->getFirstName() . ' ' . $order->getBillingAddress()->getLastName());
     $send = $mailer->Send();
     if ($send !== true) {
         return $mailer->ErrorInfo;
     }
     // Admin Mail
     $mailer->ClearAllRecipients();
     $sender = array($order->getEMail(), $order->getBillingAddress()->getFirstName() . ' ' . $order->getBillingAddress()->getLastName());
     $mailer->setSender($sender);
     $userids = JAccess::getUsersByGroup($params->get('admin_usergroup'));
     foreach ($userids as $userid) {
         $user = JUser::getInstance($userid);
         if ($user->sendEmail == 1) {
             $mailadresses = JMailHelper::cleanAddress($user->email);
             $mailer->addRecipient($mailadresses);
         }
     }
     $send = $mailer->Send();
     if ($send !== true) {
         return $mailer->ErrorInfo;
     }
     return $send;
 }
Exemple #8
0
 protected function submitteraddress()
 {
     $addr = isset($this->FieldsBuilder->senderEmail->b2jFieldValue) && !empty($this->FieldsBuilder->senderEmail->b2jFieldValue) ? $this->FieldsBuilder->senderEmail->b2jFieldValue : $this->Application->getCfg("mailfrom");
     return JMailHelper::cleanAddress($addr);
 }
 function sendReply()
 {
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     // read the data from the form
     $postData = JRequest::get('post');
     $postData = $this->securityCheck($postData);
     // clear body and subject
     jimport('joomla.mail.helper');
     // make sure the data is valid
     $isOk = true;
     if (!JMailHelper::isEmailAddress($postData['reply_email_address'])) {
         $this->_app->_session->set('isOK:' . $this->_sTask, false);
         $this->_app->_session->set('errorMsg:' . $this->_sTask, JText::_('COM_AICONTACTSAFE_PLEASE_ENTER_A_VALID_EMAIL_ADDRESS'));
     } else {
         if (strlen(trim($postData['reply_subject'])) == 0) {
             $this->_app->_session->set('isOK:' . $this->_sTask, false);
             $this->_app->_session->set('errorMsg:' . $this->_sTask, JText::_('COM_AICONTACTSAFE_PLEASE_SPECIFY_A_SUBJECT'));
         } else {
             if (strlen(trim($postData['reply_message'])) == 0) {
                 $this->_app->_session->set('isOK:' . $this->_sTask, false);
                 $this->_app->_session->set('errorMsg:' . $this->_sTask, JText::_('COM_AICONTACTSAFE_PLEASE_SPECIFY_A_MESSAGE'));
             }
         }
     }
     $isOk = $this->_app->_session->get('isOK:' . $this->_sTask);
     if ($isOk) {
         $from = $this->_app->getCfg('mailfrom');
         $fromname = $this->_app->getCfg('fromname');
         $email_recipient = JMailHelper::cleanAddress($postData['reply_email_address']);
         $subject = JMailHelper::cleanSubject($postData['reply_subject']);
         if (array_key_exists('send_plain_text', $postData) && $postData['send_plain_text']) {
             $mode = false;
             $body = JMailHelper::cleanBody($postData['reply_message']);
         } else {
             $mode = true;
             $body = JMailHelper::cleanBody(str_replace("\n", '<br />', $postData['reply_message']));
         }
         $cc = null;
         $bcc = null;
         $replyto = $from;
         $replytoname = $fromname;
         $file_attachments = null;
         $isOK = JUtility::sendMail($from, $fromname, $email_recipient, $subject, $body, $mode, $cc, $bcc, $file_attachments, $replyto, $replytoname);
     }
     if ($isOk) {
         // initialize the database
         $db = JFactory::getDBO();
         // update the reply
         $query = 'UPDATE #__aicontactsafe_messages SET email_reply = \'' . $this->replace_specialchars($email_recipient) . '\', subject_reply = \'' . $this->replace_specialchars($subject) . '\' , message_reply = \'' . $this->replace_specialchars($body) . '\' WHERE id = ' . (int) $postData['id'];
         $db->setQuery($query);
         $db->query();
         // modify the status of the message accordingly
         $this->changeStatusToReplied((int) $postData['id']);
     }
     return $isOk;
 }
Exemple #10
0
 private function set_to(&$mail)
 {
     //$addr = $this->FieldsBuilder->Fields['sender1']['Value'];
     $addr = $this->FieldsBuilder->senderEmail->b2jFieldValue;
     $mail->addRecipient(JMailHelper::cleanAddress($addr));
 }
 protected function sendEmail($mail, $receivers)
 {
     if (empty($receivers)) {
         return;
     }
     $email_recipient_count = !empty($this->_config->email_recipient_count) ? $this->_config->email_recipient_count : 1;
     $email_recipient_privacy = !empty($this->_config->email_recipient_privacy) ? $this->_config->email_recipient_privacy : 'bcc';
     // If we hide email addresses from other users, we need to add TO address to prevent email from becoming spam
     if ($email_recipient_count > 1 && $email_recipient_privacy == 'bcc' && !empty($this->_config->email_visible_address) && JMailHelper::isEmailAddress($this->_config->email_visible_address)) {
         $mail->AddAddress($this->_config->email_visible_address, JMailHelper::cleanAddress($this->_config->board_title));
         // Also make sure that email receiver limits are not violated (TO + CC + BCC = limit)
         if ($email_recipient_count > 9) {
             $email_recipient_count--;
         }
     }
     $chunks = array_chunk($receivers, $email_recipient_count);
     foreach ($chunks as $emails) {
         if ($email_recipient_count == 1 || $email_recipient_privacy == 'to') {
             $mail->ClearAddresses();
             $mail->addRecipient($emails);
         } elseif ($email_recipient_privacy == 'cc') {
             $mail->ClearCCs();
             $mail->addCC($emails);
         } else {
             $mail->ClearBCCs();
             $mail->addBCC($emails);
         }
         $mail->Send();
     }
 }
Exemple #12
0
 /**
  * Send email with download (file) link, to the given email address
  *
  * @access public
  * @since 1.0
  */
 function share_file_email()
 {
     // Check for request forgeries
     JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
     $user = JFactory::getUser();
     $db = JFactory::getDbo();
     $app = JFactory::getApplication();
     $session = JFactory::getSession();
     $document = JFactory::getDocument();
     $timeout = $session->get('com_flexicontent.formtime', 0);
     if ($timeout == 0 || time() - $timeout < 2) {
         JError::raiseNotice(500, JText::_('FLEXI_FIELD_FILE_EMAIL_NOT_SENT'));
         return $this->share_file_form();
     }
     $SiteName = $app->getCfg('sitename');
     $MailFrom = $app->getCfg('mailfrom');
     $FromName = $app->getCfg('fromname');
     $file_id = (int) JRequest::getInt('file_id', 0);
     $content_id = (int) JRequest::getInt('content_id', 0);
     $field_id = (int) JRequest::getInt('field_id', 0);
     $tpl = JRequest::getCmd('$tpl', 'default');
     // Check for missing file id
     if (!$file_id) {
         jexit(JText::_('file id is missing'));
     }
     // Check file exists
     $query = ' SELECT * FROM #__flexicontent_files WHERE id=' . $file_id;
     $db->setQuery($query);
     $file = $db->loadObject();
     if ($db->getErrorNum()) {
         jexit(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()));
     }
     if (!$file) {
         jexit(JText::_('file id no ' . $file_id . ', was not found'));
     }
     // Create SELECT OR JOIN / AND clauses for checking Access
     $access_clauses['select'] = '';
     $access_clauses['join'] = '';
     $access_clauses['and'] = '';
     $access_clauses = $this->_createFieldItemAccessClause($get_select_access = false, $include_file = true);
     // Get field's configuration
     $q = 'SELECT attribs, name FROM #__flexicontent_fields WHERE id = ' . (int) $field_id;
     $db->setQuery($q);
     $fld = $db->loadObject();
     $field_params = new JRegistry($fld->attribs);
     // Get all needed data related to the given file
     $query = 'SELECT f.id, f.filename, f.altname, f.secure, f.url,' . ' i.title as item_title, i.introtext as item_introtext, i.fulltext as item_fulltext, u.email as item_owner_email, ' . ' CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END as itemslug,' . ' CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as catslug' . ' FROM #__flexicontent_fields_item_relations AS rel' . ' LEFT JOIN #__flexicontent_files AS f ON f.id = rel.value' . ' LEFT JOIN #__flexicontent_fields AS fi ON fi.id = rel.field_id' . ' LEFT JOIN #__content AS i ON i.id = rel.item_id' . ' LEFT JOIN #__categories AS c ON c.id = i.catid' . ' LEFT JOIN #__flexicontent_items_ext AS ie ON ie.item_id = i.id' . ' LEFT JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id' . ' LEFT JOIN #__users AS u ON u.id = i.created_by' . $access_clauses['join'] . ' WHERE rel.item_id = ' . $content_id . ' AND rel.field_id = ' . $field_id . ' AND f.id = ' . $file_id . ' AND f.published= 1' . $access_clauses['and'];
     $db->setQuery($query);
     $file = $db->loadObject();
     if ($db->getErrorNum()) {
         jexit(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()));
     }
     if (empty($file)) {
         // this is normally not reachable because the share link should not have been displayed for the user, but it is reachable if e.g. user session has expired
         jexit(JText::_('FLEXI_ALERTNOTAUTH') . "File data not found OR no access for file #: " . $file_id . " of content #: " . $content_id . " in field #: " . $field_id);
     }
     $coupon_vars = '';
     if ($field_params->get('enable_coupons', 0)) {
         // Insert new download coupon into the DB, in the case the file is sent to a user with no ACCESS
         $coupon_token = uniqid();
         // create coupon token
         $query = ' INSERT #__flexicontent_download_coupons ' . 'SET user_id = ' . (int) $user->id . ', file_id = ' . $file_id . ', token = ' . $db->Quote($coupon_token) . ', hits = 0' . ', hits_limit = ' . (int) $field_params->get('coupon_hits_limit', 3) . ', expire_on = NOW() + INTERVAL ' . (int) $field_params->get('coupon_expiration_days', 15) . ' DAY';
         $db->setQuery($query);
         $db->execute();
         $coupon_id = $db->insertid();
         // get id of newly created coupon
         $coupon_vars = '&conid=' . $coupon_id . '&contok=' . $coupon_token;
     }
     $uri = JURI::getInstance();
     $base = $uri->toString(array('scheme', 'host', 'port'));
     $vars = '&id=' . $file_id . '&cid=' . $content_id . '&fid=' . $field_id . $coupon_vars;
     $link = $base . JRoute::_('index.php?option=com_flexicontent&task=download' . $vars, false);
     // Verify that this is a local link
     if (!$link || !JURI::isInternal($link)) {
         //Non-local url...
         JError::raiseNotice(500, JText::_('FLEXI_FIELD_FILE_EMAIL_NOT_SENT'));
         return $this->share_file_form();
     }
     // An array of email headers we do not want to allow as input
     $headers = array('Content-Type:', 'MIME-Version:', 'Content-Transfer-Encoding:', 'bcc:', 'cc:');
     // An array of the input fields to scan for injected headers
     $fields = array('mailto', 'sender', 'from', 'subject');
     /*
      * Here is the meat and potatoes of the header injection test.  We
      * iterate over the array of form input and check for header strings.
      * If we find one, send an unauthorized header and die.
      */
     foreach ($fields as $field) {
         foreach ($headers as $header) {
             if (strpos($_POST[$field], $header) !== false) {
                 JError::raiseError(403, '');
             }
         }
     }
     /*
      * Free up memory
      */
     unset($headers, $fields);
     $email = JRequest::getString('mailto', '', 'post');
     echo "<br>";
     $sender = JRequest::getString('sender', '', 'post');
     echo "<br>";
     $from = JRequest::getString('from', '', 'post');
     echo "<br>";
     $_subject = JText::sprintf('FLEXI_FIELD_FILE_SENT_BY', $sender);
     echo "<br>";
     $subject = JRequest::getString('subject', $_subject, 'post');
     echo "<br>";
     $desc = JRequest::getString('desc', '', 'post');
     echo "<br>";
     // Check for a valid to address
     $error = false;
     if (!$email || !JMailHelper::isEmailAddress($email)) {
         $error = JText::sprintf('FLEXI_FIELD_FILE_EMAIL_INVALID', $email);
         JError::raiseWarning(0, $error);
     }
     // Check for a valid from address
     if (!$from || !JMailHelper::isEmailAddress($from)) {
         $error = JText::sprintf('FLEXI_FIELD_FILE_EMAIL_INVALID', $from);
         JError::raiseWarning(0, $error);
     }
     if ($error) {
         return $this->share_file_form();
     }
     // Build the message to send
     $body = JText::sprintf('FLEXI_FIELD_FILE_EMAIL_MSG', $SiteName, $sender, $from, $link);
     $body .= "\n\n" . JText::_('FLEXI_FIELD_FILE_EMAIL_SENDER_NOTES') . ":\n\n" . $desc;
     // Clean the email data
     $subject = JMailHelper::cleanSubject($subject);
     $body = JMailHelper::cleanBody($body);
     $sender = JMailHelper::cleanAddress($sender);
     $html_mode = false;
     $cc = null;
     $bcc = null;
     $attachment = null;
     $replyto = null;
     $replytoname = null;
     // Send the email
     $send_result = JFactory::getMailer()->sendMail($from, $sender, $email, $subject, $body, $html_mode, $cc, $bcc, $attachment, $replyto, $replytoname);
     if ($send_result !== true) {
         JError::raiseNotice(500, JText::_('FLEXI_FIELD_FILE_EMAIL_NOT_SENT'));
         return $this->share_file_form();
     }
     $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontent.css', FLEXI_VHASH);
     include 'file' . DS . 'share_result.php';
 }
 protected function _sendReportToMail($message, $subject, $emailToList)
 {
     jimport('joomla.mail.helper');
     $sender = JMailHelper::cleanAddress($this->config->board_title . ' ' . JText::_('COM_KUNENA_GEN_FORUM') . ': ' . $this->_getSenderName());
     $subject = JMailHelper::cleanSubject($subject);
     $message = JMailHelper::cleanBody($message);
     foreach ($emailToList as $emailTo) {
         if (!$emailTo->email || !JMailHelper::isEmailAddress($emailTo->email)) {
             continue;
         }
         JUtility::sendMail($this->config->email, $sender, $emailTo->email, $subject, $message);
     }
     $this->app->enqueueMessage(JText::_('COM_KUNENA_REPORT_SUCCESS'));
     while (@ob_end_clean()) {
     }
     $this->app->redirect(CKunenaLink::GetThreadPageURL('view', $this->catid, $this->id, NULL, NULL, $this->id, false));
 }
Exemple #14
0
 /**
  * Do the plug-in action
  *
  * @param   object  $params  plugin parameters
  * @param   object  &$model  list model
  * @param   array   $opts    custom options
  *
  * @return  bool
  */
 public function process($params, &$model, $opts = array())
 {
     $db = $model->getDb();
     $user = JFactory::getUser();
     $update = json_decode($params->get('update_col_updates'));
     if (!$update) {
         return false;
     }
     // $$$ rob moved here from bottom of func see http://fabrikar.com/forums/showthread.php?t=15920&page=7
     $dateCol = $params->get('update_date_element');
     $userCol = $params->get('update_user_element');
     $item = $model->getTable();
     // Array_unique for left joined table data
     $ids = array_unique(JRequest::getVar('ids', array(), 'method', 'array'));
     JArrayHelper::toInteger($ids);
     $this->_row_count = count($ids);
     $ids = implode(',', $ids);
     $model->reset();
     $model->_pluginQueryWhere[] = $item->db_primary_key . ' IN ( ' . $ids . ')';
     $data = $model->getData();
     // $$$servantek reordered the update process in case the email routine wants to kill the updates
     $emailColID = $params->get('update_email_element', '');
     if (!empty($emailColID)) {
         $w = new FabrikWorker();
         jimport('joomla.mail.helper');
         $message = $params->get('update_email_msg');
         $subject = $params->get('update_email_subject');
         $eval = $params->get('eval', 0);
         $config = JFactory::getConfig();
         $from = $config->getValue('mailfrom');
         $fromname = $config->getValue('fromname');
         $elementModel = FabrikWorker::getPluginManager()->getElementPlugin($emailColID);
         $emailElement = $elementModel->getElement(true);
         $emailField = $elementModel->getFullName(false, true, false);
         $emailColumn = $elementModel->getFullName(false, false, false);
         $emailFieldRaw = $emailField . '_raw';
         $emailWhich = $emailElement->plugin == 'user' ? 'user' : 'field';
         $tbl = array_shift(explode('.', $emailColumn));
         $db = JFactory::getDBO();
         $aids = explode(',', $ids);
         // If using a user element, build a lookup list of emails from #__users,
         // so we're only doing one query to grab all involved emails.
         if ($emailWhich == 'user') {
             $userids_emails = array();
             $query = $db->getQuery();
             $query->select('#__users.id AS id, #__users.email AS email')->from('#__users')->join('LEFT', $tbl . ' ON #__users.id = ' . $emailColumn)->where(_primary_key . ' IN (' . $ids . ')');
             $db->setQuery($query);
             $results = $db->loadObjectList();
             foreach ($results as $result) {
                 $userids_emails[(int) $result->id] = $result->email;
             }
         }
         foreach ($aids as $id) {
             $row = $model->getRow($id);
             if ($emailWhich == 'user') {
                 $userid = (int) $row->{$emailFieldRaw};
                 $to = JArrayHelper::getValue($userids_emails, $userid);
             } else {
                 $to = $row->{$emailField};
             }
             if (JMailHelper::cleanAddress($to) && JMailHelper::isEmailAddress($to)) {
                 // $tofull = '"' . JMailHelper::cleanLine($toname) . '" <' . $to . '>';
                 // $$$servantek added an eval option and rearranged placeholder call
                 $thissubject = $w->parseMessageForPlaceholder($subject, $row);
                 $thismessage = $w->parseMessageForPlaceholder($message, $row);
                 if ($eval) {
                     $thismessage = @eval($thismessage);
                     FabrikWorker::logEval($thismessage, 'Caught exception on eval in updatecol::process() : %s');
                 }
                 $res = JUtility::sendMail($from, $fromname, $to, $thissubject, $thismessage, true);
                 if ($res) {
                     $this->_sent++;
                 } else {
                     ${$this}->_notsent++;
                 }
             } else {
                 $this->_notsent++;
             }
         }
     }
     // $$$servantek reordered the update process in case the email routine wants to kill the updates
     if (!empty($dateCol)) {
         $date = JFactory::getDate();
         $this->_process($model, $dateCol, $date->toSql());
     }
     if (!empty($userCol)) {
         $this->_process($model, $userCol, (int) $user->get('id'));
     }
     foreach ($update->coltoupdate as $i => $col) {
         $this->_process($model, $col, $update->update_value[$i]);
     }
     $this->msg = $params->get('update_message', '');
     if (empty($this->msg)) {
         $this->msg = JText::sprintf('PLG_LIST_UPDATE_COL_UPDATE_MESSAGE', $this->_row_count, $this->_sent);
     } else {
         $this->msg = JText::sprintf($this->msg, $this->_row_count, $this->_sent);
     }
     // Clean the cache.
     $cache = JFactory::getCache(JRequest::getCmd('option'));
     $cache->clean();
     return true;
 }
    /**
     * Download logic
     *
     * @access public
     * @since 1.0
     */
    function download()
    {
        // Import and Initialize some joomla API variables
        jimport('joomla.filesystem.file');
        $app = JFactory::getApplication();
        $db = JFactory::getDBO();
        $user = JFactory::getUser();
        $task = JRequest::getVar('task', 'download');
        $session = JFactory::getSession();
        $method = JRequest::getVar('method', 'download');
        if ($method != 'view' && $method != 'download') {
            die('unknown download method:' . $method);
        }
        // *******************************************************************************************************************
        // Single file download (via HTTP request) or multi-file downloaded (via a folder structure in session or in DB table)
        // *******************************************************************************************************************
        if ($task == 'download_tree') {
            // TODO: maybe move this part in module
            $cart_id = JRequest::getVar('cart_id', 0);
            if (!$cart_id) {
                // Get zTree data and parse JSON string
                $tree_var = JRequest::getVar('tree_var', "");
                if ($session->has($tree_var, 'flexicontent')) {
                    $ztree_nodes_json = $session->get($tree_var, false, 'flexicontent');
                }
                $nodes = json_decode($ztree_nodes_json);
            } else {
                $cart_token = JRequest::getVar('cart_token', '');
                $query = ' SELECT * FROM #__flexicontent_downloads_cart WHERE id=' . $cart_id;
                $db->setQuery($query);
                $cart = $db->loadObject();
                if ($db->getErrorNum()) {
                    JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()), 'error');
                }
                if (!$cart) {
                    echo JText::_('cart id no ' . $cart_id . ', was not found');
                    jexit();
                }
                $cart_token_matches = $cart_token == $cart->token;
                // no access will be checked
                $nodes = json_decode($cart->json);
            }
            // Some validation check
            if (!is_array($nodes)) {
                $app->enqueueMessage("Tree structure is empty or invalid", 'notice');
                $this->setRedirect('index.php', '');
                return;
            }
            $app = JFactory::getApplication();
            $tmp_ffname = 'fcmd_uid_' . $user->id . '_' . date('Y-m-d__H-i-s');
            $targetpath = JPath::clean($app->getCfg('tmp_path') . DS . $tmp_ffname);
            $tree_files = $this->_traverseFileTree($nodes, $targetpath);
            //echo "<pre>"; print_r($tree_files); jexit();
            if (empty($tree_files)) {
                $app->enqueueMessage("No files selected for download", 'notice');
                $this->setRedirect('index.php', '');
                return;
            }
        } else {
            $file_node = new stdClass();
            $file_node->fieldid = JRequest::getInt('fid', 0);
            $file_node->contentid = JRequest::getInt('cid', 0);
            $file_node->fileid = JRequest::getInt('id', 0);
            $coupon_id = JRequest::getInt('conid', 0);
            $coupon_token = JRequest::getString('contok', '');
            if ($coupon_id) {
                $_nowDate = 'UTC_TIMESTAMP()';
                $_nullDate = $db->Quote($db->getNullDate());
                $query = ' SELECT *' . ', CASE WHEN ' . '   expire_on = ' . $_nullDate . '   OR   expire_on > ' . $_nowDate . '  THEN 0 ELSE 1 END AS has_expired' . ', CASE WHEN ' . '   hits_limit = -1   OR   hits < hits_limit' . '  THEN 0 ELSE 1 END AS has_reached_limit' . ' FROM #__flexicontent_download_coupons' . ' WHERE id=' . $coupon_id . ' AND token=' . $db->Quote($coupon_token);
                $db->setQuery($query);
                $coupon = $db->loadObject();
                if ($db->getErrorNum()) {
                    echo __FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg());
                    jexit();
                }
                if ($coupon) {
                    $slink_valid_coupon = !$coupon->has_reached_limit && !$coupon->has_expired;
                    if (!$slink_valid_coupon) {
                        $query = ' DELETE FROM #__flexicontent_download_coupons WHERE id=' . $coupon->id;
                        $db->setQuery($query);
                        $db->execute();
                    }
                }
                $file_node->coupon = !empty($coupon) ? $coupon : false;
                // NULL will not be catched by isset()
            }
            $tree_files = array($file_node);
        }
        // **************************************************
        // Create and Execute SQL query to retrieve file info
        // **************************************************
        // Create SELECT OR JOIN / AND clauses for checking Access
        $access_clauses['select'] = '';
        $access_clauses['join'] = '';
        $access_clauses['and'] = '';
        $using_access = empty($cart_token_matches) && empty($slink_valid_coupon);
        if ($using_access) {
            // note CURRENTLY multi-download feature does not use coupons
            $access_clauses = $this->_createFieldItemAccessClause($get_select_access = true, $include_file = true);
        }
        // ***************************
        // Get file data for all files
        // ***************************
        $fields_props = array();
        $fields_conf = array();
        $valid_files = array();
        $email_recipients = array();
        foreach ($tree_files as $file_node) {
            // Get file variable shortcuts (reforce being int)
            $field_id = (int) $file_node->fieldid;
            $content_id = (int) $file_node->contentid;
            $file_id = (int) $file_node->fileid;
            if (!isset($fields_conf[$field_id])) {
                $q = 'SELECT attribs, name, field_type FROM #__flexicontent_fields WHERE id = ' . (int) $field_id;
                $db->setQuery($q);
                $fld = $db->loadObject();
                $fields_conf[$field_id] = new JRegistry($fld->attribs);
                $fields_props[$field_id] = $fld;
            }
            $field_type = $fields_props[$field_id]->field_type;
            $query = 'SELECT f.id, f.filename, f.filename_original, f.altname, f.secure, f.url, f.hits' . ', i.title as item_title, i.introtext as item_introtext, i.fulltext as item_fulltext, u.email as item_owner_email' . ', i.access as item_access, i.language as item_language, ie.type_id as item_type_id' . ', CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END as itemslug' . ', CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as catslug' . ', dh.id as history_id' . $access_clauses['select'] . ' FROM #__flexicontent_files AS f ' . ($field_type == 'file' ? ' LEFT JOIN #__flexicontent_fields_item_relations AS rel ON rel.field_id = ' . $field_id : '') . ' LEFT JOIN #__flexicontent_fields AS fi ON fi.id = ' . $field_id . ' LEFT JOIN #__content AS i ON i.id = ' . $content_id . ' LEFT JOIN #__categories AS c ON c.id = i.catid' . ' LEFT JOIN #__flexicontent_items_ext AS ie ON ie.item_id = i.id' . ' LEFT JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id' . ' LEFT JOIN #__users AS u ON u.id = i.created_by' . ' LEFT JOIN #__flexicontent_download_history AS dh ON dh.file_id = f.id AND dh.user_id = ' . (int) $user->id . $access_clauses['join'] . ' WHERE i.id = ' . $content_id . ' AND fi.id = ' . $field_id . ' AND f.id = ' . $file_id . ' AND f.published= 1' . $access_clauses['and'];
            $db->setQuery($query);
            $file = $db->loadObject();
            if ($db->getErrorNum()) {
                echo __FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg());
                jexit();
            }
            //echo "<pre>". print_r($file, true) ."</pre>"; exit;
            // **************************************************************
            // Check if file was found AND IF user has required Access Levels
            // **************************************************************
            if (empty($file) || $using_access && (!$file->has_content_access || !$file->has_field_access || !$file->has_file_access)) {
                if (empty($file)) {
                    $msg = JText::_('FLEXI_FDC_FAILED_TO_FIND_DATA');
                    // Failed to match DB data to the download URL data
                } else {
                    $msg = JText::_('FLEXI_ALERTNOTAUTH');
                    if (!empty($file_node->coupon)) {
                        if ($file_node->coupon->has_expired) {
                            $msg .= JText::_('FLEXI_FDC_COUPON_HAS_EXPIRED');
                        } else {
                            if ($file_node->coupon->has_reached_limit) {
                                $msg .= JText::_('FLEXI_FDC_COUPON_REACHED_USAGE_LIMIT');
                            } else {
                                $msg = "unreachable code in download coupon handling";
                            }
                        }
                    } else {
                        if (isset($file_node->coupon)) {
                            $msg .= "<br/> <small>" . JText::_('FLEXI_FDC_COUPON_NO_LONGER_USABLE') . "</small>";
                        }
                        $msg .= '' . (!$file->has_content_access ? "<br/><br/> " . JText::_('FLEXI_FDC_NO_ACCESS_TO') . " -- " . JText::_('FLEXI_FDC_CONTENT_CONTAINS') . " " . JText::_('FLEXI_FDC_WEBLINK') . "<br/><small>(" . JText::_('FLEXI_FDC_CONTENT_EXPLANATION') . ")</small>" : '') . (!$file->has_field_access ? "<br/><br/> " . JText::_('FLEXI_FDC_NO_ACCESS_TO') . " -- " . JText::_('FLEXI_FDC_FIELD_CONTAINS') . " " . JText::_('FLEXI_FDC_WEBLINK') : '') . (!$file->has_file_access ? "<br/><br/> " . JText::_('FLEXI_FDC_NO_ACCESS_TO') . " -- " . JText::_('FLEXI_FDC_FILE') . " " : '');
                    }
                    $msg .= "<br/><br/> " . JText::sprintf('FLEXI_FDC_FILE_DATA', $file_id, $content_id, $field_id);
                    $app->enqueueMessage($msg, 'notice');
                }
                // Only abort for single file download
                if ($task != 'download_tree') {
                    $this->setRedirect('index.php', '');
                    return;
                }
            }
            // ****************************************************
            // (for non-URL) Create file path and check file exists
            // ****************************************************
            if (!$file->url) {
                $basePath = $file->secure ? COM_FLEXICONTENT_FILEPATH : COM_FLEXICONTENT_MEDIAPATH;
                $file->abspath = str_replace(DS, '/', JPath::clean($basePath . DS . $file->filename));
                if (!JFile::exists($file->abspath)) {
                    $msg = JText::_('FLEXI_REQUESTED_FILE_DOES_NOT_EXIST_ANYMORE');
                    $app->enqueueMessage($msg, 'notice');
                    // Only abort for single file download
                    if ($task != 'download_tree') {
                        $this->setRedirect('index.php', '');
                        return;
                    }
                }
            }
            // *********************************************************************
            // Increment hits counter of file, and hits counter of file-user history
            // *********************************************************************
            $filetable = JTable::getInstance('flexicontent_files', '');
            $filetable->hit($file_id);
            if (empty($file->history_id)) {
                $query = ' INSERT #__flexicontent_download_history ' . ' SET user_id = ' . (int) $user->id . '  , file_id = ' . $file_id . '  , last_hit_on = NOW()' . '  , hits = 1';
            } else {
                $query = ' UPDATE #__flexicontent_download_history ' . ' SET last_hit_on = NOW()' . '  , hits = hits + 1' . ' WHERE id = ' . (int) $file->history_id;
            }
            $db->setQuery($query);
            $db->execute();
            // **************************************************************************************************
            // Increment hits on download coupon or delete the coupon if it has expired due to date or hits limit
            // **************************************************************************************************
            if (!empty($file_node->coupon)) {
                if (!$file_node->coupon->has_reached_limit && !$file_node->coupon->has_expired) {
                    $query = ' UPDATE #__flexicontent_download_coupons' . ' SET hits = hits + 1' . ' WHERE id=' . $file_node->coupon->id;
                    $db->setQuery($query);
                    $db->execute();
                }
            }
            // **************************
            // Special case file is a URL
            // **************************
            if ($file->url) {
                // Check for empty URL
                $url = $file->filename_original ? $file->filename_original : $file->filename;
                if (empty($url)) {
                    $msg = "File URL is empty: " . $file->url;
                    $app->enqueueMessage($msg, 'error');
                    return false;
                }
                // skip url-based file if downloading multiple files
                if ($task == 'download_tree') {
                    $msg = "Skipped URL based file: " . $url;
                    $app->enqueueMessage($msg, 'notice');
                    continue;
                }
                // redirect to the file download link
                @header("Location: " . $url . "");
                $app->close();
            }
            // *********************************************************************
            // Set file (tree) node and assign file into valid files for downloading
            // *********************************************************************
            $file->node = $file_node;
            $valid_files[$file_id] = $file;
            $file->hits++;
            $per_downloads = $fields_conf[$field_id]->get('notifications_hits_step', 20);
            if ($fields_conf[$field_id]->get('send_notifications') && $file->hits % $per_downloads == 0) {
                // Calculate (once per file) some text used for notifications
                $file->__file_title__ = $file->altname && $file->altname != $file->filename ? $file->altname . ' [' . $file->filename . ']' : $file->filename;
                $item = new stdClass();
                $item->access = $file->item_access;
                $item->type_id = $file->item_type_id;
                $item->language = $file->item_language;
                $file->__item_url__ = JRoute::_(FlexicontentHelperRoute::getItemRoute($file->itemslug, $file->catslug, 0, $item));
                // Parse and identify language strings and then make language replacements
                $notification_tmpl = $fields_conf[$field_id]->get('notification_tmpl');
                if (empty($notification_tmpl)) {
                    $notification_tmpl = JText::_('FLEXI_HITS') . ": " . $file->hits;
                    $notification_tmpl .= '%%FLEXI_FDN_FILE_NO%% __file_id__:  "__file_title__" ' . "\n";
                    $notification_tmpl .= '%%FLEXI_FDN_FILE_IN_ITEM%% "__item_title__":' . "\n";
                    $notification_tmpl .= '__item_url__';
                }
                $result = preg_match_all("/\\%\\%([^%]+)\\%\\%/", $notification_tmpl, $translate_matches);
                $translate_strings = $result ? $translate_matches[1] : array();
                foreach ($translate_strings as $translate_string) {
                    $notification_tmpl = str_replace('%%' . $translate_string . '%%', JText::_($translate_string), $notification_tmpl);
                }
                $file->notification_tmpl = $notification_tmpl;
                // Send to hard-coded email list
                $send_all_to_email = $fields_conf[$field_id]->get('send_all_to_email');
                if ($send_all_to_email) {
                    $emails = preg_split("/[\\s]*;[\\s]*/", $send_all_to_email);
                    foreach ($emails as $email) {
                        $email_recipients[$email][] = $file;
                    }
                }
                // Send to item owner
                $send_to_current_item_owner = $fields_conf[$field_id]->get('send_to_current_item_owner');
                if ($send_to_current_item_owner) {
                    $email_recipients[$file->item_owner_email][] = $file;
                }
                // Send to email assigned to email field in same content item
                $send_to_email_field = (int) $fields_conf[$field_id]->get('send_to_email_field');
                if ($send_to_email_field) {
                    $q = 'SELECT value ' . ' FROM #__flexicontent_fields_item_relations ' . ' WHERE field_id = ' . $send_to_email_field . ' AND item_id=' . $content_id;
                    $db->setQuery($q);
                    $email_values = $db->loadColumn();
                    foreach ($email_values as $i => $email_value) {
                        if (@unserialize($email_value) !== false || $email_value === 'b:0;') {
                            $email_values[$i] = unserialize($email_value);
                        } else {
                            $email_values[$i] = array('addr' => $email_value, 'text' => '');
                        }
                        $addr = @$email_values[$i]['addr'];
                        if ($addr) {
                            $email_recipients[$addr][] = $file;
                        }
                    }
                }
            }
        }
        //echo "<pre>". print_r($valid_files, true) ."</pre>";
        //echo "<pre>". print_r($email_recipients, true) ."</pre>";
        //sjexit();
        if (!empty($email_recipients)) {
            ob_start();
            $sendermail = $app->getCfg('mailfrom');
            $sendermail = JMailHelper::cleanAddress($sendermail);
            $sendername = $app->getCfg('sitename');
            $subject = JText::_('FLEXI_FDN_FILE_DOWNLOAD_REPORT');
            $message_header = JText::_('FLEXI_FDN_FILE_DOWNLOAD_REPORT_BY') . ': ' . $user->name . ' [' . $user->username . ']';
            // ****************************************************
            // Send email notifications about file being downloaded
            // ****************************************************
            // Personalized email per subscribers
            foreach ($email_recipients as $email_addr => $files_arr) {
                $to = JMailHelper::cleanAddress($email_addr);
                $_message = $message_header;
                foreach ($files_arr as $filedata) {
                    $_mssg_file = $filedata->notification_tmpl;
                    $_mssg_file = str_ireplace('__file_id__', $filedata->id, $_mssg_file);
                    $_mssg_file = str_ireplace('__file_title__', $filedata->__file_title__, $_mssg_file);
                    $_mssg_file = str_ireplace('__item_title__', $filedata->item_title, $_mssg_file);
                    //$_mssg_file = str_ireplace('__item_title_linked__', $filedata->password, $_mssg_file);
                    $_mssg_file = str_ireplace('__item_url__', $filedata->__item_url__, $_mssg_file);
                    $count = 0;
                    $_mssg_file = str_ireplace('__file_hits__', $filedata->hits, $_mssg_file, $count);
                    if ($count == 0) {
                        $_mssg_file = JText::_('FLEXI_HITS') . ": " . $file->hits . "\n" . $_mssg_file;
                    }
                    $_message .= "\n\n" . $_mssg_file;
                }
                //echo "<pre>". $_message ."</pre>";
                $from = $sendermail;
                $fromname = $sendername;
                $recipient = array($to);
                $html_mode = false;
                $cc = null;
                $bcc = null;
                $attachment = null;
                $replyto = null;
                $replytoname = null;
                $send_result = FLEXI_J16GE ? JFactory::getMailer()->sendMail($from, $fromname, $recipient, $subject, $_message, $html_mode, $cc, $bcc, $attachment, $replyto, $replytoname) : JUtility::sendMail($from, $fromname, $recipient, $subject, $_message, $html_mode, $cc, $bcc, $attachment, $replyto, $replytoname);
            }
            ob_end_clean();
        }
        // * Required for IE, otherwise Content-disposition is ignored
        if (ini_get('zlib.output_compression')) {
            ini_set('zlib.output_compression', 'Off');
        }
        if ($task == 'download_tree') {
            // Create target (top level) folder
            JFolder::create($targetpath, 0755);
            // Copy Files
            foreach ($valid_files as $file) {
                JFile::copy($file->abspath, $file->node->targetpath);
            }
            // Create text/html file with ITEM title / descriptions
            // TODO replace this with a TEMPLATE file ...
            $desc_filename = $targetpath . DS . "_descriptions";
            $handle_txt = fopen($desc_filename . ".txt", "w");
            $handle_htm = fopen($desc_filename . ".htm", "w");
            fprintf($handle_htm, '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" dir="ltr" >
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />		
</head>
<body>
');
            foreach ($valid_files as $file) {
                fprintf($handle_txt, "%s", $file->item_title . "\n\n");
                fprintf($handle_txt, "%s", flexicontent_html::striptagsandcut($file->item_introtext) . "\n\n");
                if (strlen($file->item_fulltext)) {
                    fprintf($handle_txt, "%s", flexicontent_html::striptagsandcut($file->item_fulltext) . "\n\n");
                }
                fprintf($handle_htm, "%s", "<h2>" . $file->item_title . "</h2>");
                fprintf($handle_htm, "%s", "<blockquote>" . $file->item_introtext . "</blockquote><br/>");
                if (strlen($file->item_fulltext)) {
                    fprintf($handle_htm, "%s", "<blockquote>" . $file->item_fulltext . "</blockquote><br/>");
                }
                fprintf($handle_htm, "<hr/><br/>");
            }
            fclose($handle_txt);
            fclose($handle_htm);
            // Get file list recursively, and calculate archive filename
            $fileslist = JFolder::files($targetpath, '.', $recurse = true, $fullpath = true);
            $archivename = $tmp_ffname . '.zip';
            $archivepath = JPath::clean($app->getCfg('tmp_path') . DS . $archivename);
            // ******************
            // Create the archive
            // ******************
            /*$app = JFactory::getApplication('administrator');
            		$files = array();
            		foreach ($fileslist as $i => $filename) {
            			$files[$i]=array();
            			$files[$i]['name'] = preg_replace("%^(\\\|/)%", "", str_replace($targetpath, "", $filename) );  // STRIP PATH for filename inside zip
            			$files[$i]['data'] = implode('', file($filename));   // READ contents into string, here we use full path
            			$files[$i]['time'] = time();
            		}
            		
            		$packager = JArchive::getAdapter('zip');
            		if (!$packager->create($archivepath, $files)) {
            			$msg = JText::_('FLEXI_OPERATION_FAILED'). ": compressed archive could not be created";
            			$app->enqueueMessage($msg, 'notice');
            			$this->setRedirect('index.php', '');
            			return;
            		}*/
            $za = new flexicontent_zip();
            $res = $za->open($archivepath, ZipArchive::CREATE);
            if ($res !== true) {
                $msg = JText::_('FLEXI_OPERATION_FAILED') . ": compressed archive could not be created";
                $app->enqueueMessage($msg, 'notice');
                $this->setRedirect('index.php', '');
                return;
            }
            $za->addDir($targetpath, "");
            $za->close();
            // *********************************
            // Remove temporary folder structure
            // *********************************
            if (!JFolder::delete($targetpath)) {
                $msg = "Temporary folder " . $targetpath . " could not be deleted";
                $app->enqueueMessage($msg, 'notice');
            }
            // Delete old files (they can not be deleted during download time ...)
            $tmp_path = JPath::clean($app->getCfg('tmp_path'));
            $matched_files = JFolder::files($tmp_path, 'fcmd_uid_.*', $recurse = false, $fullpath = true);
            foreach ($matched_files as $archive_file) {
                //echo "Seconds passed:". (time() - filemtime($tmp_folder)) ."<br>". "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($tmp_folder)) . "<br>";
                if (time() - filemtime($archive_file) > 3600) {
                    JFile::delete($archive_file);
                }
            }
            // Delete old tmp folder (in case that the some archiving procedures were interrupted thus their tmp folder were not deleted)
            $matched_folders = JFolder::folders($tmp_path, 'fcmd_uid_.*', $recurse = false, $fullpath = true);
            foreach ($matched_folders as $tmp_folder) {
                //echo "Seconds passed:". (time() - filemtime($tmp_folder)) ."<br>". "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($tmp_folder)) . "<br>";
                JFolder::delete($tmp_folder);
            }
            $dlfile = new stdClass();
            $dlfile->filename = 'cart_files_' . date('m-d-Y_H-i-s') . '.zip';
            // a friendly name instead of  $archivename
            $dlfile->abspath = $archivepath;
        } else {
            $dlfile = reset($valid_files);
        }
        // Get file filesize and extension
        $dlfile->size = filesize($dlfile->abspath);
        $dlfile->ext = strtolower(JFile::getExt($dlfile->filename));
        // Set content type of file (that is an archive for multi-download)
        $ctypes = array("pdf" => "application/pdf", "exe" => "application/octet-stream", "rar" => "application/zip", "zip" => "application/zip", "txt" => "text/plain", "doc" => "application/msword", "xls" => "application/vnd.ms-excel", "ppt" => "application/vnd.ms-powerpoint", "gif" => "image/gif", "png" => "image/png", "jpeg" => "image/jpg", "jpg" => "image/jpg", "mp3" => "audio/mpeg");
        $dlfile->ctype = isset($ctypes[$dlfile->ext]) ? $ctypes[$dlfile->ext] : "application/force-download";
        // *****************************************
        // Output an appropriate Content-Type header
        // *****************************************
        header("Pragma: public");
        // required
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);
        // required for certain browsers
        header("Content-Type: " . $dlfile->ctype);
        //quotes to allow spaces in filenames
        $download_filename = strlen($dlfile->filename_original) ? $dlfile->filename_original : $dlfile->filename;
        if ($method == 'view') {
            header("Content-Disposition: inline; filename=\"" . $download_filename . "\";");
        } else {
            header("Content-Disposition: attachment; filename=\"" . $download_filename . "\";");
        }
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . $dlfile->size);
        // *******************************
        // Finally read file and output it
        // *******************************
        if (!FLEXIUtilities::funcIsDisabled('set_time_limit')) {
            @set_time_limit(0);
        }
        $chunksize = 1 * (1024 * 1024);
        // 1MB, highest possible for fread should be 8MB
        if (1 || $dlfile->size > $chunksize) {
            $handle = @fopen($dlfile->abspath, "rb");
            while (!feof($handle)) {
                print @fread($handle, $chunksize);
                ob_flush();
                flush();
            }
            fclose($handle);
        } else {
            // This is good for small files, it will read an output the file into
            // memory and output it, it will cause a memory exhausted error on large files
            ob_clean();
            flush();
            readfile($dlfile->abspath);
        }
        // ****************************************************
        // In case of multi-download clear the session variable
        // ****************************************************
        //if ($task=='download_tree') $session->set($tree_var, false,'flexicontent');
        // Done ... terminate execution
        $app->close();
    }
Exemple #16
0
 function validateFields()
 {
     $message->sender_email = JRequest::getVar('sender_email', '', '', 'string');
     $message->sender_name = JRequest::getVar('sender_name', '', '', 'string');
     $message->rec_emails = JRequest::getVar('rec_emails', '', '', 'string');
     $msg = JText::_('REQ_PROCESSING_ERR') . '<ul>';
     $errors = false;
     if ($message->sender_email == '') {
         $msg .= '<li>' . JText::_('VALID_EMAIL_ERR') . '</li>';
         $errors = true;
     }
     if ($message->sender_name == '') {
         $msg .= '<li>' . JText::_('VALID_SENDER_ERR') . '</li>';
         $errors = true;
     }
     if (stristr($message->rec_emails, ',') === TRUE) {
         $rec_emailarray = explode(',', $message->rec_emails);
         foreach ($rec_emailarray as $email_recipient) {
             if (trim($email_recipient) == '' || !JMailHelper::cleanAddress(trim($email_recipient)) || !JMailHelper::isEmailAddress(trim($email_recipient))) {
                 $addr_errors = true;
                 $errors = true;
             }
         }
         if ($addr_errors === true) {
             $errors = true;
             $msg .= '<li>' . JText::_('ONEOR_MORE_EMAILS_INVALID') . '</li>';
         }
     } else {
         if (stristr($message->rec_emails, ',') === FALSE && (trim($message->rec_emails) == '' || !JMailHelper::cleanAddress(trim($message->rec_emails)) || !JMailHelper::isEmailAddress(trim($message->rec_emails)))) {
             $errors = true;
             $msg .= '<li>' . JText::_('EMAIL_EMPTY_OR_INVALID') . '</li>';
         }
     }
     $results = new JObject();
     $results->sender_email = $message->sender_email;
     $results->sender_name = $message->sender_name;
     $results->rec_emails = $message->rec_emails;
     if ($errors) {
         $results->errors = $errors;
         $results->errmsg = $msg;
     } else {
         $results->errors = false;
     }
     return $results;
 }
Exemple #17
0
 /**
  * do the plugin action
  * @param object parameters
  * @param object table model
  */
 function process(&$params, &$model, $opts = array())
 {
     $db =& $model->getDb();
     $user =& JFactory::getUser();
     $updateTo = $params->get('update_value');
     $updateCol = $params->get('coltoupdate');
     $updateTo_2 = $params->get('update_value_2');
     $updateCol_2 = $params->get('coltoupdate_2');
     // $$$ rob moved here from bottom of func see http://fabrikar.com/forums/showthread.php?t=15920&page=7
     $tbl = array_shift(explode('.', $updateCol));
     $dateCol = $params->get('update_date_element');
     $userCol = $params->get('update_user_element');
     $table =& $model->getTable();
     // array_unique for left joined table data
     $ids = array_unique(JRequest::getVar('ids', array(), 'method', 'array'));
     JArrayHelper::toInteger($ids);
     $this->_row_count = count($ids);
     $ids = implode(',', $ids);
     $model->_pluginQueryWhere[] = $table->db_primary_key . ' IN ( ' . $ids . ')';
     $data =& $model->getData();
     //$$$servantek reordered the update process in case the email routine wants to kill the updates
     $emailColID = $params->get('update_email_element', '');
     if (!empty($emailColID)) {
         $w = new FabrikWorker();
         jimport('joomla.mail.helper');
         $message = $params->get('update_email_msg');
         $subject = $params->get('update_email_subject');
         $eval = $params->get('eval', 0);
         $config =& JFactory::getConfig();
         $from = $config->getValue('mailfrom');
         $fromname = $config->getValue('fromname');
         $elementModel =& JModel::getInstance('element', 'FabrikModel');
         $elementModel->setId($emailColID);
         $emailElement =& $elementModel->getElement(true);
         $emailField = $elementModel->getFullName(false, true, false);
         $emailColumn = $elementModel->getFullName(false, false, false);
         $emailFieldRaw = $emailField . '_raw';
         $emailWhich = $emailElement->plugin == 'fabrikuser' ? 'user' : 'field';
         $db =& JFactory::getDBO();
         $aids = explode(',', $ids);
         // if using a user element, build a lookup list of emails from jos_users,
         // so we're only doing one query to grab all involved emails.
         if ($emailWhich == 'user') {
             $userids_emails = array();
             $query = 'SELECT #__users.id AS id, #__users.email AS email FROM #__users LEFT JOIN ' . $tbl . ' ON #__users.id = ' . $emailColumn . ' WHERE ' . $table->db_primary_key . ' IN (' . $ids . ')';
             $db->setQuery($query);
             $results = $db->loadObjectList();
             foreach ($results as $result) {
                 $userids_emails[(int) $result->id] = $result->email;
             }
         }
         foreach ($aids as $id) {
             $row = $model->getRow($id);
             if ($emailWhich == 'user') {
                 $userid = (int) $row->{$emailFieldRaw};
                 $to = $userids_emails[$userid];
             } else {
                 $to = $row->{$emailField};
             }
             if (JMailHelper::cleanAddress($to) && JMailHelper::isEmailAddress($to)) {
                 //$tofull = '"' . JMailHelper::cleanLine($toname) . '" <' . $to . '>';
                 //$$$servantek added an eval option and rearranged placeholder call
                 $thissubject = $w->parseMessageForPlaceholder($subject, $row);
                 $thismessage = $w->parseMessageForPlaceholder($message, $row);
                 if ($eval) {
                     $thismessage = @eval($thismessage);
                     FabrikWorker::logEval($thismessage, 'Caught exception on eval in updatecol::process() : %s');
                 }
                 $res = JUtility::sendMail($from, $fromname, $to, $thissubject, $thismessage, true);
                 if ($res) {
                     $this->_sent++;
                 } else {
                     ${$this}->_notsent++;
                 }
             } else {
                 $this->_notsent++;
             }
         }
     }
     //$$$servantek reordered the update process in case the email routine wants to kill the updates
     if (!empty($dateCol)) {
         $date =& JFactory::getDate();
         $this->_process($model, $dateCol, $date->toMySQL());
     }
     if (!empty($userCol)) {
         $this->_process($model, $userCol, (int) $user->get('id'));
     }
     $this->_process($model, $updateCol, $updateTo);
     if (!empty($updateCol_2)) {
         $this->_process($model, $updateCol_2, $updateTo_2);
     }
     // $$$ hugh - this stuff has to go in process_result()
     //$msg = $params->get( 'update_message' );
     //return JText::sprintf( $msg, count($ids));
     $this->msg = $params->get('update_message', '');
     if (empty($this->msg)) {
         $this->msg = JText::sprintf('%d ROWS UPDATED, %d EMAILS SENT', $this->_row_count, $this->_sent);
     } else {
         $this->msg = JText::sprintf($this->msg, $this->_row_count, $this->_sent);
     }
     return true;
 }
Exemple #18
0
function mail_notification($subscription)
{
    if (in_array(15, $subscription->courses)) {
        jimport('joomla.mail.helper');
        $JLMS_CONFIG =& JLMSFactory::getConfig();
        $SiteName = $JLMS_CONFIG->get('sitename');
        $MailFrom = $JLMS_CONFIG->get('mailfrom');
        $FromName = $JLMS_CONFIG->get('fromname');
        JLoader::import('autoresponder_spu', JPATH_SITE, '');
        $subject = AutoResponder::getSubject();
        $body = AutoResponder::getBody();
        $body = sprintf($body);
        $subject = JMailHelper::cleanSubject($subject);
        $body = JMailHelper::cleanBody($body);
        $from = $SiteName . ' ' . $FromName;
        $sender = JMailHelper::cleanAddress($MailFrom);
        $email = JMailHelper::cleanAddress(JRequest::getVar('x_email', ''));
        $user =& JFactory::getUser();
        $name = explode(' ', $user->name);
        $firstname = isset($name[0]) && $name[0] ? $name[0] : $user->name;
        $body = str_replace('{firstname}', $firstname, $body);
        if (JUtility::sendMail($from, $sender, $email, $subject, $body, true) !== true) {
            JError::raiseNotice(500, JText::_('EMAIL_NOT_SENT'));
        }
    }
}
Exemple #19
0
 function sendNotifications($item, $subscribers, $params)
 {
     global $globalcats;
     $app = JFactory::getApplication();
     // Get the route helper
     require_once JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'route.php';
     // Import utility class that contains the send mail helper function
     if (!FLEXI_J16GE) {
         jimport('joomla.utilities.utility');
     }
     jimport('joomla.mail.helper');
     if (FLEXI_J16GE) {
         $mailer = JFactory::getMailer();
         $mailer->Encoding = 'base64';
     }
     // Parameters for 'message' language string
     //
     // 1: $subname	Name of the subscriber
     // 2: $itemid		ID of the item
     // 3: $title		Title of the item
     // 4: $maincat	Main category of the item
     // 5: $link			Link of the item
     // 6: $sitename	Website
     $send_personalized = $params->get('send_personalized', 1);
     if ($send_personalized) {
         // Disable personalized messages if subscriber limit for personal messages is exceeded
         $personalized_limit = $params->get('personalized_limit', 50);
         $personalized_limit = $personalized_limit <= 100 ? $personalized_limit : 100;
         $send_personalized = count($subscribers) <= $personalized_limit ? true : false;
     }
     $include_fullname = $params->get('include_fullname', 1);
     $user_autologin = $params->get('autologin', 1);
     $debug_notifications = $params->get('debug_notifications', 0);
     // *********************************
     // Create variables need for subject
     // *********************************
     $subname = $send_personalized && $include_fullname ? '__SUBSCRIBER_NAME__' : JText::_('FLEXI_SUBSCRIBER');
     $itemid = $item->id;
     $title = $item->title;
     $maincat = $globalcats[$item->catid]->title;
     // Domain URL and autologin vars
     $server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
     $autologin = $send_personalized && $user_autologin ? '&fcu=__SUBSCRIBER_USERNAME__&fcp=__SUBSCRIBER_PASSWORD__' : '';
     // Check if we are in the backend, in the back end we need to set the application to the site app instead
     $isAdmin = JFactory::getApplication()->isAdmin();
     if ($isAdmin && FLEXI_J16GE) {
         JFactory::$application = JApplication::getInstance('site');
     }
     // Create the URL
     $item_url = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->id . ':' . $item->alias, $globalcats[$item->catid]->slug) . $autologin);
     // Check if we are in the backend again
     // In backend we need to remove administrator from URL as it is added even though we've set the application to the site app
     if ($isAdmin) {
         if (FLEXI_J16GE) {
             $admin_folder = str_replace(JURI::root(true), '', JURI::base(true));
             $item_url = str_replace($admin_folder, '', $item_url);
             // Restore application
             JFactory::$application = JApplication::getInstance('administrator');
         } else {
             $item_url = JURI::root(true) . '/' . $item_url;
         }
     }
     $link = $server . $item_url;
     $link = str_replace('&amp;', '&', $link);
     $sitename = $app->getCfg('sitename') . ' - ' . JURI::root();
     // ************************************************
     // Create parameters passed to mail helper function
     // ************************************************
     $sendermail = $params->get('sendermail', $app->getCfg('mailfrom'));
     $sendermail = JMailHelper::cleanAddress($sendermail);
     $sendername = $params->get('sendername', $app->getCfg('sitename'));
     $subject = $params->get('mailsubject', '') ? JMailHelper::cleanSubject($params->get('mailsubject')) : JText::_('FLEXI_SUBJECT_DEFAULT');
     $message = JText::sprintf('FLEXI_NOTIFICATION_MESSAGE', $subname, $itemid, $title, $maincat, '<a href="' . $link . '">' . $link . '</a>', $sitename);
     $message = nl2br($message);
     // *************************************************
     // Send email notifications about item being updated
     // *************************************************
     // Personalized email per subscribers
     if ($send_personalized) {
         $count_sent = 0;
         $to_arr = array();
         foreach ($subscribers as $subscriber) {
             $to = JMailHelper::cleanAddress($subscriber->email);
             $to_arr[] = $to;
             $_message = $message;
             if ($include_fullname) {
                 $_message = str_replace('__SUBSCRIBER_NAME__', $subscriber->name, $_message);
             }
             if ($user_autologin) {
                 $_message = str_replace('__SUBSCRIBER_USERNAME__', $subscriber->username, $_message);
                 $_message = str_replace('__SUBSCRIBER_PASSWORD__', $subscriber->password, $_message);
             }
             $from = $sendermail;
             $fromname = $sendername;
             $recipient = array($to);
             $html_mode = true;
             $cc = null;
             $bcc = null;
             $attachment = null;
             $replyto = null;
             $replytoname = null;
             $send_result = FLEXI_J16GE ? $mailer->sendMail($from, $fromname, $recipient, $subject, $_message, $html_mode, $cc, $bcc, $attachment, $replyto, $replytoname) : JUtility::sendMail($from, $fromname, $recipient, $subject, $_message, $html_mode, $cc, $bcc, $attachment, $replyto, $replytoname);
             if ($send_result) {
                 $count_sent++;
             }
         }
         $send_result = (bool) $count_sent;
         if ($debug_notifications) {
             JFactory::getApplication()->enqueueMessage("** Favourites Notification Plugin: &nbsp; Sent personalized message per subscriber", 'message');
         }
     } else {
         $to_arr = array();
         $count = 0;
         foreach ($subscribers as $subscriber) {
             $to = JMailHelper::cleanAddress($subscriber->email);
             $to_arr[] = $to;
             $to_100_arr[intval($count / 100)][] = $to;
             $count++;
         }
         $count_sent = 0;
         foreach ($to_100_arr as $to_100) {
             $from = $sendermail;
             $fromname = $sendername;
             $recipient = array($from);
             $html_mode = true;
             $cc = null;
             $bcc = $to_100;
             $attachment = null;
             $replyto = null;
             $replytoname = null;
             $send_result = FLEXI_J16GE ? $mailer->sendMail($from, $fromname, $recipient, $subject, $message, $html_mode, $cc, $bcc, $attachment, $replyto, $replytoname) : JUtility::sendMail($from, $fromname, $recipient, $subject, $message, $html_mode, $cc, $bcc, $attachment, $replyto, $replytoname);
             if ($send_result) {
                 $count_sent += count($to_100);
             }
         }
         $send_result = (bool) $count_sent;
         if ($debug_notifications) {
             JFactory::getApplication()->enqueueMessage("** Favourites Notification Plugin: &nbsp; Sent same message to all subscribers", 'message');
         }
     }
     // Finally give some feedback to current editor, optionally including emails of receivers if debug is enabled
     $msg = $send_result ? JText::sprintf('FLEXI_NOTIFY_SUCCESS', $count_sent, count($subscribers)) : JText::sprintf('FLEXI_NOTIFY_FAILURE', count($subscribers));
     $msg_receivers = !$debug_notifications ? "" : " <br/> Subscribers List: " . implode(", ", $to_arr);
     $app->enqueueMessage($msg . $msg_receivers, $send_result ? 'message' : 'warning');
 }
 /**
  * Send the message and display a notice
  *
  * @access public
  * @since 1.5
  */
 function send()
 {
     global $mainframe;
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     $session =& JFactory::getSession();
     $db =& JFactory::getDBO();
     // we return time() instead of 0 (as it previously was), so that the session variable has to be set in order to send the mail
     $timeout = $session->get('com_mailto.formtime', time());
     if ($timeout == 0 || time() - $timeout < MAILTO_TIMEOUT) {
         JError::raiseNotice(500, JText::_('EMAIL_NOT_SENT'));
         return $this->mailto();
     }
     // here we unset the counter right away so that you have to wait again, and you have to visit mailto() first
     $session->set('com_mailto.formtime', null);
     jimport('joomla.mail.helper');
     $SiteName = $mainframe->getCfg('sitename');
     $MailFrom = $mainframe->getCfg('mailfrom');
     $FromName = $mainframe->getCfg('fromname');
     $link = base64_decode(JRequest::getVar('link', '', 'post', 'base64'));
     // Verify that this is a local link
     if (!JURI::isInternal($link)) {
         //Non-local url...
         JError::raiseNotice(500, JText::_('EMAIL_NOT_SENT'));
         return $this->mailto();
     }
     // An array of e-mail headers we do not want to allow as input
     $headers = array('Content-Type:', 'MIME-Version:', 'Content-Transfer-Encoding:', 'bcc:', 'cc:');
     // An array of the input fields to scan for injected headers
     $fields = array('mailto', 'sender', 'from', 'subject');
     /*
      * Here is the meat and potatoes of the header injection test.  We
      * iterate over the array of form input and check for header strings.
      * If we find one, send an unauthorized header and die.
      */
     foreach ($fields as $field) {
         foreach ($headers as $header) {
             if (strpos($_POST[$field], $header) !== false) {
                 JError::raiseError(403, '');
             }
         }
     }
     /*
      * Free up memory
      */
     unset($headers, $fields);
     $email = JRequest::getString('mailto', '', 'post');
     $sender = JRequest::getString('sender', '', 'post');
     $from = JRequest::getString('from', '', 'post');
     $subject_default = JText::sprintf('Item sent by', $sender);
     $subject = JRequest::getString('subject', $subject_default, 'post');
     // Check for a valid to address
     $error = false;
     if (!$email || !JMailHelper::isEmailAddress($email)) {
         $error = JText::sprintf('EMAIL_INVALID', $email);
         JError::raiseWarning(0, $error);
     }
     // Check for a valid from address
     if (!$from || !JMailHelper::isEmailAddress($from)) {
         $error = JText::sprintf('EMAIL_INVALID', $from);
         JError::raiseWarning(0, $error);
     }
     if ($error) {
         return $this->mailto();
     }
     // Build the message to send
     $msg = JText::_('EMAIL_MSG');
     $body = sprintf($msg, $SiteName, $sender, $from, $link);
     // Clean the email data
     $subject = JMailHelper::cleanSubject($subject);
     $body = JMailHelper::cleanBody($body);
     $sender = JMailHelper::cleanAddress($sender);
     // Send the email
     if (JUtility::sendMail($from, $sender, $email, $subject, $body) !== true) {
         JError::raiseNotice(500, JText::_('EMAIL_NOT_SENT'));
         return $this->mailto();
     }
     JRequest::setVar('view', 'sent');
     $this->display();
 }
Exemple #21
0
 function report()
 {
     if (!JSession::checkToken('post')) {
         $this->app->enqueueMessage(JText::_('COM_KUNENA_ERROR_TOKEN'), 'error');
         $this->setRedirectBack();
         return;
     }
     if (!$this->me->exists() || $this->config->reportmsg == 0) {
         // Deny access if report feature has been disabled or user is guest
         $this->app->enqueueMessage(JText::_('COM_KUNENA_NO_ACCESS'), 'notice');
         $this->setRedirectBack();
         return;
     }
     if (!$this->config->get('send_emails')) {
         // Emails have been disabled
         $this->app->enqueueMessage(JText::_('COM_KUNENA_EMAIL_DISABLED'), 'notice');
         $this->setRedirectBack();
         return;
     }
     if (!$this->config->getEmail() || !JMailHelper::isEmailAddress($this->config->getEmail())) {
         // Error: email address is invalid
         $this->app->enqueueMessage(JText::_('COM_KUNENA_EMAIL_INVALID'), 'error');
         $this->setRedirectBack();
         return;
     }
     // Get target object for the report
     if ($this->mesid) {
         $message = $target = KunenaForumMessageHelper::get($this->mesid);
         $topic = $target->getTopic();
     } else {
         $topic = $target = KunenaForumTopicHelper::get($this->id);
         $message = KunenaForumMessageHelper::get($topic->first_post_id);
     }
     $messagetext = $message->message;
     $baduser = KunenaFactory::getUser($message->userid);
     if (!$target->authorise('read')) {
         // Deny access if user cannot read target
         $this->app->enqueueMessage($target->getError(), 'notice');
         $this->setRedirectBack();
         return;
     }
     $reason = JRequest::getString('reason');
     $text = JRequest::getString('text');
     $template = KunenaTemplate::getInstance();
     if (method_exists($template, 'reportMessage')) {
         $template->reportMessage($message, $reason, $text);
     }
     // Load language file from the template.
     KunenaFactory::getTemplate()->loadLanguage();
     if (empty($reason) && empty($text)) {
         // Do nothing: empty subject or reason is empty
         $this->app->enqueueMessage(JText::_('COM_KUNENA_REPORT_FORG0T_SUB_MES'));
         $this->setRedirectBack();
         return;
     } else {
         $acl = KunenaAccess::getInstance();
         $emailToList = $acl->getSubscribers($topic->category_id, $topic->id, false, true, false);
         if (!empty($emailToList)) {
             $mailsender = JMailHelper::cleanAddress($this->config->board_title . ' ' . JText::_('COM_KUNENA_FORUM') . ': ' . $this->me->getName());
             $mailsubject = "[" . $this->config->board_title . " " . JText::_('COM_KUNENA_FORUM') . "] " . JText::_('COM_KUNENA_REPORT_MSG') . ": ";
             if ($reason) {
                 $mailsubject .= $reason;
             } else {
                 $mailsubject .= $topic->subject;
             }
             jimport('joomla.environment.uri');
             $msglink = JUri::getInstance()->toString(array('scheme', 'host', 'port')) . $target->getPermaUrl(null, false);
             $mail = JFactory::getMailer();
             $mail->setSender(array($this->me->username, $this->me->email));
             $mail->setSubject($mailsubject);
             // Render the email.
             $layout = KunenaLayout::factory('Email/Report')->debug(false)->set('mail', $mail)->set('message', $message)->set('me', $this->me)->set('title', $reason)->set('content', $text)->set('messageLink', $msglink);
             try {
                 $body = trim($layout->render());
                 $mail->setBody($body);
             } catch (Exception $e) {
                 // TODO: Deprecated in K4.0, remove in K5.0
                 $mailmessage = "" . JText::_('COM_KUNENA_REPORT_RSENDER') . " {$this->me->username} ({$this->me->name})";
                 $mailmessage .= "\n";
                 $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_RREASON') . " " . $reason;
                 $mailmessage .= "\n";
                 $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_RMESSAGE') . " " . $text;
                 $mailmessage .= "\n\n";
                 $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_POST_POSTER') . " {$baduser->username} ({$baduser->name})";
                 $mailmessage .= "\n";
                 $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_POST_SUBJECT') . ": " . $topic->subject;
                 $mailmessage .= "\n";
                 $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_POST_MESSAGE') . "\n-----\n" . KunenaHtmlParser::stripBBCode($messagetext, 0, false);
                 $mailmessage .= "\n-----\n\n";
                 $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_POST_LINK') . " " . $msglink;
                 $mailmessage = JMailHelper::cleanBody(strtr($mailmessage, array('&#32;' => '')));
                 $mail->setBody($mailmessage);
             }
             $receivers = array();
             foreach ($emailToList as $emailTo) {
                 if (!$emailTo->email || !JMailHelper::isEmailAddress($emailTo->email)) {
                     continue;
                 }
                 $receivers[] = $emailTo->email;
             }
             KunenaEmail::send($mail, $receivers);
             $this->app->enqueueMessage(JText::_('COM_KUNENA_REPORT_SUCCESS'));
         } else {
             $this->app->enqueueMessage(JText::_('COM_KUNENA_REPORT_NOT_SEND'));
         }
     }
     $this->setRedirect($target->getUrl($this->return, false));
 }
Exemple #22
0
 function save_comment($cachable = false, $urlparams = array())
 {
     JRequest::checkToken();
     $app = JFactory::getApplication();
     $view = $this->getView('singleimage', 'html');
     /**
      * @var EventgalleryModelSingleimage $model
      */
     $model = $this->getModel('singleimage');
     $view->setModel($model);
     $modelComment = $this->getModel('comment');
     $buzzwords = $model->getBuzzwords();
     $buzzwordsClean = BuzzwordsHelper::validateBuzzwords($buzzwords, JRequest::getVar('text'));
     $data = JRequest::getVar('jform', array(), 'post', 'array');
     $form = $modelComment->getForm();
     $validate = $modelComment->validate($form, $data);
     if ($validate === false || !$buzzwordsClean) {
         // Get the validation messages.
         $errors = $modelComment->getErrors();
         // Push up to three validation messages out to the user.
         for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
             if ($errors[$i] instanceof Exception) {
                 $app->enqueueMessage($errors[$i]->getMessage(), 'warning');
             } else {
                 $app->enqueueMessage($errors[$i], 'warning');
             }
         }
         // Save the data in the session.
         $app->setUserState('com_eventgallery.comment.data', $data);
         // Redirect back to the contact form.
         $msg = JText::_('COM_EVENTGALLERY_SINGLEIMAGE_COMMENT_SAVE_FAILED');
         $this->setRedirect(JRoute::_("index.php?view=singleimage&success=false&folder=" . JRequest::getVar('folder') . "&file=" . JRequest::getVar('file'), false), $msg, 'error');
         return false;
     }
     $validate['file'] = JRequest::getString('file');
     $validate['folder'] = JRequest::getString('folder');
     $row = $model->store_comment($validate, $buzzwordsClean ? 1 : 0);
     // reset the user state
     $app->setUserState('com_eventgallery.comment.data', null);
     $msg = JText::_('COM_EVENTGALLERY_SINGLEIMAGE_COMMENT_SAVE_SUCCESS');
     $this->setRedirect(JRoute::_("index.php?view=singleimage&success=true&folder=" . JRequest::getVar('folder') . "&file=" . JRequest::getVar('file'), false), $msg, 'success');
     $mailer = JFactory::getMailer();
     $params = JComponentHelper::getParams('com_eventgallery');
     $userids = JAccess::getUsersByGroup($params->get('admin_usergroup'));
     if (count($userids) == 0) {
         return;
     }
     foreach ($userids as $userid) {
         $user = JUser::getInstance($userid);
         if ($user->sendEmail == 1) {
             $mailadress = JMailHelper::cleanAddress($user->email);
             $mailer->addRecipient($mailadress);
         }
     }
     $config = JFactory::getConfig();
     $sender = array($config->get('mailfrom'), $config->get('fromname'));
     $mailer->setSender($sender);
     JRequest::setVar('newCommentId', $row->id);
     $mailview = $this->getView('commentmail', 'html');
     /**
      *
      * @var EventgalleryModelComment $commentModel
      */
     $commentModel = $this->getModel('comment');
     $mailview->setModel($commentModel, true);
     $bodytext = $mailview->loadTemplate();
     #$mailer->LE = "\r\n";
     $mailer->LE = "\n";
     $bodytext = JMailHelper::cleanBody($bodytext);
     $mailer->setSubject(JMailHelper::cleanSubject($row->folder . "|" . $row->file . ' - ' . JText::_('COM_EVENTGALLERY_COMMENT_ADD_MAIL_SUBJECT') . ' - ' . $app->getCfg('sitename')));
     $mailer->SetBody($bodytext);
     $mailer->IsHTML(true);
     $mailer->Send();
 }
Exemple #23
0
 public function sendContactForm()
 {
     jimport('joomla.mail.helper');
     $app = JFactory::getApplication();
     // Get a JMail instance
     $mailer = JFactory::getMailer();
     $params = $app->getParams();
     $defaultFrom = $mailer->From;
     $defaultFromname = $mailer->FromName;
     $data = array('name' => JMailHelper::cleanLine($this->getState('contact.name')), 'email' => JMailHelper::cleanAddress($this->getState('contact.email')), 'telephone' => JMailHelper::cleanLine($this->getState('contact.telephone')), 'subject' => JMailHelper::cleanSubject($this->getState('contact.subject')) . ' [' . $defaultFromname . ']', 'message' => JMailHelper::cleanText($this->getState('contact.message')), 'propertyURL' => $this->getState('contact.propertyURL'));
     $dispatcher = JDispatcher::getInstance();
     JPluginHelper::importPlugin('jea');
     if ($params->get('use_captcha')) {
         $plugin = JFactory::getConfig()->get('captcha');
         if ($plugin == '0') {
             $plugin = 'recaptcha';
         }
         $captcha = JCaptcha::getInstance($plugin);
         // Test the value.
         if (!$captcha->checkAnswer('')) {
             $error = $captcha->getError();
             if ($error instanceof Exception) {
                 $this->setError($error->getMessage());
             } else {
                 $this->setError($error);
             }
         }
     }
     // Check data
     if (empty($data['name'])) {
         $this->setError(JText::_('COM_JEA_YOU_MUST_TO_ENTER_YOUR_NAME'));
     }
     if (empty($data['message'])) {
         $this->setError(JText::_('COM_JEA_YOU_MUST_TO_ENTER_A_MESSAGE'));
     }
     if (!JMailHelper::isEmailAddress($data['email'])) {
         $this->setError(JText::sprintf('COM_JEA_INVALID_EMAIL_ADDRESS', $data['email']));
     }
     if ($this->getErrors()) {
         return false;
     }
     $result = $dispatcher->trigger('onBeforeSendContactForm', array($data));
     if (in_array(false, $result, true)) {
         return false;
     }
     $recipients = array();
     $defaultMail = $params->get('default_mail');
     $agentMail = '';
     if ($params->get('send_form_to_agent') == 1) {
         $item = $this->getItem();
         $db = $this->getDbo();
         $q = 'SELECT `email` FROM `#__users` WHERE `id`=' . (int) $item->created_by;
         $db->setQuery($q);
         $agentMail = $db->loadResult();
     }
     if (!empty($defaultMail) && !empty($agentMail)) {
         $recipients[] = $defaultMail;
         $recipients[] = $agentMail;
     } elseif (!empty($defaultMail)) {
         $recipients[] = $defaultMail;
     } elseif (!empty($agentMail)) {
         $recipients[] = $agentMail;
     } else {
         // Send to the webmaster email
         $recipients[] = $defaultFrom;
     }
     $body = $data['message'] . "\n";
     if (!empty($data['telephone'])) {
         $body .= "\n" . JText::_('COM_JEA_TELEPHONE') . ' : ' . $data['telephone'];
     }
     $body .= "\n" . JText::_('COM_JEA_PROPERTY_URL') . ' : ' . $data['propertyURL'];
     $mailer->setBody($body);
     $ret = $mailer->sendMail($data['email'], $data['name'], $recipients, $data['subject'], $body, false);
     if ($ret == true) {
         $app->setUserState('contact.name', '');
         $app->setUserState('contact.email', '');
         $app->setUserState('contact.telephone', '');
         $app->setUserState('contact.subject', '');
         $app->setUserState('contact.message', '');
         return true;
     }
     return false;
 }
Exemple #24
0
 function report()
 {
     if (!JRequest::checkToken()) {
         $this->app->enqueueMessage(JText::_('COM_KUNENA_ERROR_TOKEN'), 'error');
         $this->redirectBack();
     }
     if (!$this->me->exists() || $this->config->reportmsg == 0) {
         // Deny access if report feature has been disabled or user is guest
         $this->app->enqueueMessage(JText::_('COM_KUNENA_NO_ACCESS'), 'notice');
         $this->redirectBack();
     }
     if (!$this->config->get('send_emails')) {
         // Emails have been disabled
         $this->app->enqueueMessage(JText::_('COM_KUNENA_EMAIL_DISABLED'), 'notice');
         $this->redirectBack();
     }
     jimport('joomla.mail.helper');
     if (!$this->config->getEmail() || !JMailHelper::isEmailAddress($this->config->getEmail())) {
         // Error: email address is invalid
         $this->app->enqueueMessage(JText::_('COM_KUNENA_EMAIL_INVALID'), 'error');
         $this->redirectBack();
     }
     // Get target object for the report
     if ($this->mesid) {
         $message = $target = KunenaForumMessageHelper::get($this->mesid);
         $topic = $target->getTopic();
     } else {
         $topic = $target = KunenaForumTopicHelper::get($this->id);
         $message = KunenaForumMessageHelper::get($topic->first_post_id);
     }
     $messagetext = $message->message;
     $baduser = KunenaFactory::getUser($message->userid);
     if (!$target->authorise('read')) {
         // Deny access if user cannot read target
         $this->app->enqueueMessage($target->getError(), 'notice');
         $this->redirectBack();
     }
     $category = $topic->getCategory();
     $reason = JRequest::getString('reason');
     $text = JRequest::getString('text');
     if (empty($reason) && empty($text)) {
         // Do nothing: empty subject or reason is empty
         $this->app->enqueueMessage(JText::_('COM_KUNENA_REPORT_FORG0T_SUB_MES'));
         $this->redirectBack();
     } else {
         $acl = KunenaAccess::getInstance();
         $emailToList = $acl->getSubscribers($topic->category_id, $topic->id, false, true, false, $this->me->userid);
         if (!empty($emailToList)) {
             $mailsender = JMailHelper::cleanAddress($this->config->board_title . ' ' . JText::_('COM_KUNENA_FORUM') . ': ' . $this->me->getName());
             $mailsubject = "[" . $this->config->board_title . " " . JText::_('COM_KUNENA_FORUM') . "] " . JText::_('COM_KUNENA_REPORT_MSG') . ": ";
             if ($reason) {
                 $mailsubject .= $reason;
             } else {
                 $mailsubject .= $topic->subject;
             }
             jimport('joomla.environment.uri');
             $uri = JURI::getInstance(JURI::base());
             $msglink = $uri->toString(array('scheme', 'host', 'port')) . $target->getPermaUrl(null, false);
             $mailmessage = "" . JText::_('COM_KUNENA_REPORT_RSENDER') . " {$this->me->username} ({$this->me->name})";
             $mailmessage .= "\n";
             $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_RREASON') . " " . $reason;
             $mailmessage .= "\n";
             $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_RMESSAGE') . " " . $text;
             $mailmessage .= "\n\n";
             $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_POST_POSTER') . " {$baduser->username} ({$baduser->name})";
             $mailmessage .= "\n";
             $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_POST_SUBJECT') . ": " . $topic->subject;
             $mailmessage .= "\n";
             $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_POST_MESSAGE') . "\n-----\n" . KunenaHtmlParser::stripBBCode($messagetext, 0, false);
             $mailmessage .= "\n-----\n\n";
             $mailmessage .= "" . JText::_('COM_KUNENA_REPORT_POST_LINK') . " " . $msglink;
             $mailmessage = JMailHelper::cleanBody(strtr($mailmessage, array('&#32;' => '')));
             foreach ($emailToList as $emailTo) {
                 if (!$emailTo->email || !JMailHelper::isEmailAddress($emailTo->email)) {
                     continue;
                 }
                 JUtility::sendMail($this->config->getEmail(), $mailsender, $emailTo->email, $mailsubject, $mailmessage);
             }
             $this->app->enqueueMessage(JText::_('COM_KUNENA_REPORT_SUCCESS'));
         } else {
             $this->app->enqueueMessage(JText::_('COM_KUNENA_REPORT_NOT_SEND'));
         }
     }
     $this->app->redirect($target->getUrl($this->return, false));
 }
Exemple #25
0
 /**
  * Send email notifications from the message.
  *
  * @param null|string $url
  *
  * @return bool|null
  */
 public function sendNotification($url = null)
 {
     $config = KunenaFactory::getConfig();
     if (!$config->get('send_emails')) {
         return null;
     }
     if ($this->hold > 1) {
         return null;
     } elseif ($this->hold == 1) {
         $mailsubs = 0;
         $mailmods = $config->mailmod >= 0;
         $mailadmins = $config->mailadmin >= 0;
     } else {
         $mailsubs = (bool) $config->allowsubscriptions;
         $mailmods = $config->mailmod >= 1;
         $mailadmins = $config->mailadmin >= 1;
     }
     $once = false;
     if ($mailsubs) {
         if (!$this->parent) {
             // New topic: Send email only to category subscribers
             $mailsubs = $config->category_subscriptions != 'disabled' ? KunenaAccess::CATEGORY_SUBSCRIPTION : 0;
             $once = $config->category_subscriptions == 'topic';
         } elseif ($config->category_subscriptions != 'post') {
             // Existing topic: Send email only to topic subscribers
             $mailsubs = $config->topic_subscriptions != 'disabled' ? KunenaAccess::TOPIC_SUBSCRIPTION : 0;
             $once = $config->topic_subscriptions == 'first';
         } else {
             // Existing topic: Send email to both category and topic subscribers
             $mailsubs = $config->topic_subscriptions == 'disabled' ? KunenaAccess::CATEGORY_SUBSCRIPTION : KunenaAccess::CATEGORY_SUBSCRIPTION | KunenaAccess::TOPIC_SUBSCRIPTION;
             // FIXME: category subscription can override topic
             $once = $config->topic_subscriptions == 'first';
         }
     }
     if (!$url) {
         $url = JUri::getInstance()->toString(array('scheme', 'host', 'port')) . $this->getPermaUrl();
     }
     // Get all subscribers, moderators and admins who should get the email.
     $emailToList = KunenaAccess::getInstance()->getSubscribers($this->catid, $this->thread, $mailsubs, $mailmods, $mailadmins, KunenaUserHelper::getMyself()->userid);
     if ($emailToList) {
         if (!$config->getEmail()) {
             KunenaError::warning(JText::_('COM_KUNENA_EMAIL_DISABLED'));
             return false;
         } elseif (!JMailHelper::isEmailAddress($config->getEmail())) {
             KunenaError::warning(JText::_('COM_KUNENA_EMAIL_INVALID'));
             return false;
         }
         $topic = $this->getTopic();
         // Make a list from all receivers; split the receivers into two distinct groups.
         $sentusers = array();
         $receivers = array(0 => array(), 1 => array());
         foreach ($emailToList as $emailTo) {
             if (!$emailTo->email || !JMailHelper::isEmailAddress($emailTo->email)) {
                 continue;
             }
             $receivers[$emailTo->subscription][] = $emailTo->email;
             $sentusers[] = $emailTo->id;
         }
         $mailsender = JMailHelper::cleanAddress($config->board_title);
         $mailsubject = JMailHelper::cleanSubject($config->board_title . ' ' . $topic->subject . " (" . $this->getCategory()->name . ")");
         $subject = $this->subject ? $this->subject : $topic->subject;
         // Create email.
         $mail = JFactory::getMailer();
         $mail->setSubject($mailsubject);
         $mail->setSender(array($config->getEmail(), $mailsender));
         // Send email to all subscribers.
         if (!empty($receivers[1])) {
             $this->attachEmailBody($mail, 1, $subject, $url, $once);
             KunenaEmail::send($mail, $receivers[1]);
         }
         // Send email to all moderators.
         if (!empty($receivers[0])) {
             $this->attachEmailBody($mail, 0, $subject, $url, $once);
             KunenaEmail::send($mail, $receivers[0]);
         }
         // Update subscriptions.
         if ($once && $sentusers) {
             $sentusers = implode(',', $sentusers);
             $db = JFactory::getDbo();
             $query = $db->getQuery(true)->update('#__kunena_user_topics')->set('subscribed=2')->where("topic_id={$this->thread}")->where("user_id IN ({$sentusers})")->where('subscribed=1');
             $db->setQuery($query);
             $db->execute();
             KunenaError::checkDatabaseError();
         }
     }
     return true;
 }
Exemple #26
0
 /**
  * Helper wrapper method for cleanAddress
  *
  * @param   string  $address  email address.
  *
  * @return  mixed   email address string or boolean false if injected headers are present
  *
  * @see     JMailHelper::cleanAddress()
  * @since   3.4
  */
 public function cleanAddress($address)
 {
     return JMailHelper::cleanAddress($address);
 }
Exemple #27
0
 function doemail()
 {
     jimport('joomla.mail.helper');
     jimport('joomla.filesystem.file');
     jimport('joomla.client.helper');
     global $mainframe;
     JClientHelper::setCredentialsFromRequest('ftp');
     $config =& JFactory::getConfig();
     $folder = '';
     $filepaths = array();
     $attached = 0;
     $notattached = 0;
     foreach (JRequest::get('FILES') as $elname => $file) {
         if ($file['name'] != '') {
             if ($folder == '') {
                 $folder = $config->getValue('config.tmp_path') . DS . uniqid('com_fabrik.plg.table.emailtableplus.');
                 if (!JFolder::create($folder)) {
                     JError::raiseWarning(E_NOTICE, JText::_('Could not upload files'));
                     break;
                 }
             }
             $filepath = $folder . DS . JFile::makeSafe($file['name']);
             if (JFile::upload($file['tmp_name'], $filepath)) {
                 $filepaths[count($filepaths)] = $filepath;
                 $attached++;
             } else {
                 JError::raiseWarning(E_NOTICE, JText::sprintf('Could not upload file %s', $file['name']));
             }
         }
     }
     $renderOrder = JRequest::getInt('renderOrder', 0);
     $subject = JMailHelper::cleanSubject(JRequest::getVar('subject'));
     $message = JMailHelper::cleanBody(JRequest::getVar('message'));
     $recordids = explode(',', JRequest::getVar('recordids'));
     $tableModel =& $this->getModel('Table');
     $tableModel->setId(JRequest::getVar('id', 0));
     $formModel =& $tableModel->getForm();
     $this->formModel =& $formModel;
     $params =& $tableModel->getParams();
     $elementModel =& JModel::getInstance('element', 'FabrikModel');
     $field_name = $params->get('emailtableplus_field_name');
     if (is_array($field_name)) {
         $field_name = $field_name[$renderOrder];
     }
     $elementModel->setId($field_name);
     $element =& $elementModel->getElement(true);
     $tonamefield = $elementModel->getFullName(false, true, false);
     $field_email = $params->get('emailtableplus_field_email');
     if (is_array($field_email)) {
         $field_email = $field_email[$renderOrder];
     }
     $elementModel->setId($field_email);
     $element =& $elementModel->getElement(true);
     $tofield = $elementModel->getFullName(false, true, false);
     $fromUser = $params->get('emailtableplus_from_user');
     if (is_array($fromUser)) {
         $fromUser = $fromUser[$renderOrder];
     }
     if ($fromUser[0]) {
         $my =& JFactory::getUser();
         $from = $my->get('email');
         $fromname = $my->get('name');
     } else {
         $config =& JFactory::getConfig();
         $from = $config->getValue('mailfrom');
         $fromname = $config->getValue('fromname');
     }
     $ubcc = $params->get('emailtableplus_use_BCC');
     if (is_array($ubcc)) {
         $ubcc = $ubcc[$renderOrder];
     }
     $useBCC = $ubcc && count($recordids) > 0 && !preg_match('/{[^}]*}/', $subject) && !preg_match('/{[^}]*}/', $message);
     /*
     $include_rowdata = $params->get('emailtableplus_include_rowdata');
     if (is_array($include_rowdata)) {
     	$include_rowdata = $include_rowdata[$renderOrder];
     }
     */
     $sent = 0;
     $notsent = 0;
     if ($useBCC) {
         $bcc = array();
         foreach ($recordids as $id) {
             $row = $tableModel->getRow($id);
             //$message .= $this->_getTextEmail( JArrayHelper::fromObject($row));
             $to = $row->{$tofield};
             $toname = $row->{$tonamefield};
             if (JMailHelper::cleanAddress($to) && JMailHelper::isEmailAddress($to)) {
                 $tofull = '"' . JMailHelper::cleanLine($toname) . '" <' . $to . '>';
                 $bcc[$sent] = $tofull;
                 $sent++;
             } else {
                 $notsent++;
             }
         }
         // $$$ hugh - working round bug in the SMTP mailer method:
         // http://forum.joomla.org/viewtopic.php?f=199&t=530189&p=2190233#p2190233
         // ... which basically means if using the SMTP method, we MUST specify a To addrees,
         // so if mailer is smtp, we'll set the To address to the same as From address
         if ($config->getValue('mailer') == 'smtp') {
             $res = JUtility::sendMail($from, $fromname, $from, $subject, $message, 0, null, $bcc, $filepaths);
         } else {
             $res = JUtility::sendMail($from, $fromname, null, $subject, $message, 0, null, $bcc, $filepaths);
         }
         if (!$res) {
             $notsent += $sent;
             $sent = 0;
         }
     } else {
         $w = new FabrikWorker();
         foreach ($recordids as $id) {
             $row = $tableModel->getRow($id);
             $to = $row->{$tofield};
             $toname = $row->{$tonamefield};
             if (JMailHelper::cleanAddress($to) && JMailHelper::isEmailAddress($to)) {
                 $tofull = '"' . JMailHelper::cleanLine($toname) . '" <' . $to . '>';
                 $thissubject = $w->parseMessageForPlaceholder($subject, $row);
                 $thismessage = $w->parseMessageForPlaceholder($message, $row);
                 $res = JUtility::sendMail($from, $fromname, $tofull, $thissubject, $thismessage, 0, null, null, $filepaths);
                 if ($res) {
                     $sent++;
                 } else {
                     $notsent++;
                 }
             } else {
                 $notsent++;
             }
         }
     }
     if ($folder != '') {
         JFolder::delete($folder);
     }
     if ($attached > 0) {
         $mainframe->enqueueMessage(JText::sprintf('%s files attached', $attached));
     }
     $mainframe->enqueueMessage(JText::sprintf('%s emails sent', $sent));
     if ($notsent != 0) {
         JError::raiseWarning(E_NOTICE, JText::sprintf('%s emails not sent', $notsent));
     }
 }
 /**
  * Send the message and display a notice
  *
  * @access public
  * @since 1.5
  */
 function send()
 {
     // Check for request forgeries
     Session::checkToken() or exit(Lang::txt('JINVALID_TOKEN'));
     $timeout = Session::get('com_mailto.formtime', 0);
     if ($timeout == 0 || time() - $timeout < 20) {
         throw new Exception(Lang::txt('COM_MAILTO_EMAIL_NOT_SENT'), 500);
         return $this->mailto();
     }
     $SiteName = Config::get('sitename');
     $MailFrom = Config::get('mailfrom');
     $FromName = Config::get('fromname');
     $link = MailtoHelper::validateHash(Request::getCMD('link', '', 'post'));
     // Verify that this is a local link
     if (!$link || !JURI::isInternal($link)) {
         //Non-local url...
         throw new Exception(Lang::txt('COM_MAILTO_EMAIL_NOT_SENT'), 500);
         return $this->mailto();
     }
     // An array of email headers we do not want to allow as input
     $headers = array('Content-Type:', 'MIME-Version:', 'Content-Transfer-Encoding:', 'bcc:', 'cc:');
     // An array of the input fields to scan for injected headers
     $fields = array('mailto', 'sender', 'from', 'subject');
     /*
      * Here is the meat and potatoes of the header injection test.  We
      * iterate over the array of form input and check for header strings.
      * If we find one, send an unauthorized header and die.
      */
     foreach ($fields as $field) {
         foreach ($headers as $header) {
             if (strpos($_POST[$field], $header) !== false) {
                 App::abort(403, '');
             }
         }
     }
     // Free up memory
     unset($headers, $fields);
     $email = Request::getString('mailto', '', 'post');
     $sender = Request::getString('sender', '', 'post');
     $from = Request::getString('from', '', 'post');
     $subject_default = Lang::txt('COM_MAILTO_SENT_BY', $sender);
     $subject = Request::getString('subject', $subject_default, 'post');
     // Check for a valid to address
     $error = false;
     if (!$email || !JMailHelper::isEmailAddress($email)) {
         $error = Lang::txt('COM_MAILTO_EMAIL_INVALID', $email);
         Notify::warning($error);
     }
     // Check for a valid from address
     if (!$from || !JMailHelper::isEmailAddress($from)) {
         $error = Lang::txt('COM_MAILTO_EMAIL_INVALID', $from);
         Notify::warning($error);
     }
     if ($error) {
         return $this->mailto();
     }
     // Build the message to send
     $msg = Lang::txt('COM_MAILTO_EMAIL_MSG');
     $body = sprintf($msg, $SiteName, $sender, $from, $link);
     // Clean the email data
     $subject = JMailHelper::cleanSubject($subject);
     $body = JMailHelper::cleanBody($body);
     $sender = JMailHelper::cleanAddress($sender);
     // Send the email
     if (JFactory::getMailer()->sendMail($from, $sender, $email, $subject, $body) !== true) {
         throw new Exception(Lang::txt('COM_MAILTO_EMAIL_NOT_SENT'), 500);
         return $this->mailto();
     }
     Request::setVar('view', 'sent');
     $this->display();
 }
Exemple #29
0
 /**
  * Send the message and display a notice
  *
  * @access public
  * @since 1.5
  */
 function send()
 {
     // Check for request forgeries
     JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
     $app = JFactory::getApplication();
     $session = JFactory::getSession();
     $db = JFactory::getDbo();
     $timeout = $session->get('com_mailto.formtime', 0);
     if ($timeout == 0 || time() - $timeout < 20) {
         JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
         return $this->mailto();
     }
     jimport('joomla.mail.helper');
     $SiteName = $app->getCfg('sitename');
     $MailFrom = $app->getCfg('mailfrom');
     $FromName = $app->getCfg('fromname');
     $link = MailtoHelper::validateHash(JRequest::getCMD('link', '', 'post'));
     // Verify that this is a local link
     if (!$link || !JURI::isInternal($link)) {
         //Non-local url...
         JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
         return $this->mailto();
     }
     // An array of email headers we do not want to allow as input
     $headers = array('Content-Type:', 'MIME-Version:', 'Content-Transfer-Encoding:', 'bcc:', 'cc:');
     // An array of the input fields to scan for injected headers
     $fields = array('mailto', 'sender', 'from', 'subject');
     /*
      * Here is the meat and potatoes of the header injection test.  We
      * iterate over the array of form input and check for header strings.
      * If we find one, send an unauthorized header and die.
      */
     foreach ($fields as $field) {
         foreach ($headers as $header) {
             if (strpos($_POST[$field], $header) !== false) {
                 JError::raiseError(403, '');
             }
         }
     }
     /*
      * Free up memory
      */
     unset($headers, $fields);
     $email = JRequest::getString('mailto', '', 'post');
     $sender = JRequest::getString('sender', '', 'post');
     $from = JRequest::getString('from', '', 'post');
     $subject_default = JText::sprintf('COM_MAILTO_SENT_BY', $sender);
     $subject = JRequest::getString('subject', $subject_default, 'post');
     // Check for a valid to address
     $error = false;
     if (!$email || !JMailHelper::isEmailAddress($email)) {
         $error = JText::sprintf('COM_MAILTO_EMAIL_INVALID', $email);
         JError::raiseWarning(0, $error);
     }
     // Check for a valid from address
     if (!$from || !JMailHelper::isEmailAddress($from)) {
         $error = JText::sprintf('COM_MAILTO_EMAIL_INVALID', $from);
         JError::raiseWarning(0, $error);
     }
     if ($error) {
         return $this->mailto();
     }
     // Build the message to send
     $msg = JText::_('COM_MAILTO_EMAIL_MSG');
     $body = sprintf($msg, $SiteName, $sender, $from, $link);
     // Clean the email data
     $subject = JMailHelper::cleanSubject($subject);
     $body = JMailHelper::cleanBody($body);
     $sender = JMailHelper::cleanAddress($sender);
     // Send the email
     if (JUtility::sendMail($from, $sender, $email, $subject, $body) !== true) {
         JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
         return $this->mailto();
     }
     JRequest::setVar('view', 'sent');
     $this->display();
 }
Exemple #30
0
 function sendEmailToModeratorsPostWFM()
 {
     // get settings from com_discussions parameters
     $params = JComponentHelper::getParams('com_discussions');
     $SiteName = $params->get('emailSiteName', '');
     $from = $params->get('emailFrom', '');
     $sender = $params->get('emailSender', '');
     $link = $params->get('emailLink', '');
     $subject = $params->get('emailWFMSubject', '');
     $msgparam = $params->get('emailWFMMessage', '');
     jimport('joomla.mail.helper');
     $db =& JFactory::getDBO();
     // get all moderators with email notifications set
     $sql = "SELECT u.username, u.email FROM " . $db->nameQuote('#__users') . " u, " . $db->nameQuote('#__discussions_users') . " d" . " WHERE u.id = d.id AND d.moderator = 1 AND d.email_notification = 1";
     $db->setQuery($sql);
     $_moderator_list = $db->loadAssocList();
     reset($_moderator_list);
     while (list($key, $val) = each($_moderator_list)) {
         $username = $_moderator_list[$key]['username'];
         $email = $_moderator_list[$key]['email'];
         if (JMailHelper::isEmailAddress($email)) {
             // construct email
             $msg = $username . ", \n\n" . $msgparam;
             $body = sprintf($msg, $SiteName, $sender, $from, $link);
             // Clean the email data
             $subject = JMailHelper::cleanSubject($subject);
             $body = JMailHelper::cleanBody($body);
             $sender = JMailHelper::cleanAddress($sender);
             JUtility::sendMail($from, $sender, $email, $subject, $body);
         }
     }
     return 0;
 }