Exemplo n.º 1
0
 public function preProcess()
 {
     $this->_type = 'unsubscribe';
     $this->_job_id = $job_id = CRM_Utils_Request::retrieve('jid', 'Integer', $this);
     $this->_queue_id = $queue_id = CRM_Utils_Request::retrieve('qid', 'Integer', $this);
     $this->_hash = $hash = CRM_Utils_Request::retrieve('h', 'String', $this);
     if (!$job_id || !$queue_id || !$hash) {
         CRM_Core_Error::fatal(ts("Missing Parameters"));
     }
     // verify that the three numbers above match
     $q = CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     if (!$q) {
         CRM_Core_Error::fatal(ts("There was an error in your request"));
     }
     list($displayName, $email) = CRM_Mailing_Event_BAO_Queue::getContactInfo($queue_id);
     $this->assign('display_name', $displayName);
     $emailMasked = CRM_Utils_String::maskEmail($email);
     $this->assign('email_masked', $emailMasked);
     $this->assign('email', $email);
     $this->_email = $email;
     $groups = CRM_Mailing_Event_BAO_Unsubscribe::unsub_from_mailing($job_id, $queue_id, $hash, TRUE);
     $this->assign('groups', $groups);
     $groupExist = NULL;
     foreach ($groups as $key => $value) {
         if ($value) {
             $groupExist = TRUE;
         }
     }
     if (!$groupExist) {
         $statusMsg = ts('Email: %1 has been successfully unsubscribed from this Mailing List/Group.', array(1 => $email));
         CRM_Core_Session::setStatus($statusMsg, '', 'fail');
     }
     $this->assign('groupExist', $groupExist);
 }
Exemplo n.º 2
0
 function preProcess()
 {
     $job_id = CRM_Utils_Request::retrieve('jid', $this, null);
     $queue_id = CRM_Utils_Request::retrieve('qid', $this, null);
     $hash = CRM_Utils_Request::retrieve('h', $this, null);
     $q =& CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     if ($q == null) {
         /** ERROR **/
         CRM_Utils_System::statusBounce(ts('Invalid form parameters.'));
     }
     $mailing =& $q->getMailing();
     /* Show the subject instead of the name here, since it's being
      * displayed to external contacts/users */
     CRM_Utils_System::setTitle(ts('Forward Mailing: %1', array(1 => $mailing->subject)));
     $this->set('queue_id', $queue_id);
     $this->set('job_id', $job_id);
     $this->set('hash', $hash);
 }
 static function recordBounce($params)
 {
     $isSpam = CRM_Utils_Array::value('is_spam', $params);
     $mailingId = CRM_Utils_Array::value('mailing_id', $params);
     //CiviCRM mailling ID
     $contactId = CRM_Utils_Array::value('contact_id', $params);
     $emailId = CRM_Utils_Array::value('email_id', $params);
     $email = CRM_Utils_Array::value('email', $params);
     $jobId = CRM_Utils_Array::value('job_id', $params);
     $eqParams = array('job_id' => $jobId, 'contact_id' => $contactId, 'email_id' => $emailId);
     $eventQueue = CRM_Mailing_Event_BAO_Queue::create($eqParams);
     $time = date('YmdHis', CRM_Utils_Array::value('date_ts', $params));
     $bounceType = array();
     CRM_Core_PseudoConstant::populate($bounceType, 'CRM_Mailing_DAO_BounceType', TRUE, 'id', NULL, NULL, NULL, 'name');
     $bounce = new CRM_Mailing_Event_BAO_Bounce();
     $bounce->time_stamp = $time;
     $bounce->event_queue_id = $eventQueue->id;
     if ($isSpam) {
         $bounce->bounce_type_id = $bounceType[CRM_Mailjet_Upgrader::SPAM];
         $bounce->bounce_reason = CRM_Utils_Array::value('source', $params);
         //bounce reason when spam occured
     } else {
         $hardBounce = CRM_Utils_Array::value('hard_bounce', $params);
         $blocked = CRM_Utils_Array::value('blocked', $params);
         //  blocked : true if this bounce leads to recipient being blocked
         if ($hardBounce && $blocked) {
             $bounce->bounce_type_id = $bounceType[CRM_Mailjet_Upgrader::BLOCKED];
         } elseif ($hardBounce && !$blocked) {
             $bounce->bounce_type_id = $bounceType[CRM_Mailjet_Upgrader::HARD_BOUNCE];
         } else {
             $bounce->bounce_type_id = $bounceType[CRM_Mailjet_Upgrader::SOFT_BOUNCE];
         }
         $bounce->bounce_reason = $params['error_related_to'] . " - " . $params['error'];
     }
     $bounce->save();
     if ($bounce->bounce_type_id != $bounceType[CRM_Mailjet_Upgrader::SOFT_BOUNCE]) {
         $params = array('id' => $contactId, 'do_not_email' => 1);
         civicrm_api3('Contact', 'create', $params);
     }
     return TRUE;
 }
Exemplo n.º 4
0
 public function preProcess()
 {
     $this->_type = 'optout';
     $this->_job_id = $job_id = CRM_Utils_Request::retrieve('jid', 'Integer', $this);
     $this->_queue_id = $queue_id = CRM_Utils_Request::retrieve('qid', 'Integer', $this);
     $this->_hash = $hash = CRM_Utils_Request::retrieve('h', 'String', $this);
     if (!$job_id || !$queue_id || !$hash) {
         CRM_Core_Error::fatal(ts("Missing input parameters"));
     }
     // verify that the three numbers above match
     $q = CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     if (!$q) {
         CRM_Core_Error::fatal(ts("There was an error in your request"));
     }
     list($displayName, $email) = CRM_Mailing_Event_BAO_Queue::getContactInfo($queue_id);
     $this->assign('display_name', $displayName);
     $emailMasked = CRM_Utils_String::maskEmail($email);
     $this->assign('email_masked', $emailMasked);
     $this->assign('email', $email);
     $this->_email = $email;
 }
Exemplo n.º 5
0
 public function preProcess()
 {
     $job_id = CRM_Utils_Request::retrieve('jid', 'Positive', $this, NULL);
     $queue_id = CRM_Utils_Request::retrieve('qid', 'Positive', $this, NULL);
     $hash = CRM_Utils_Request::retrieve('h', 'String', $this, NULL);
     $q = CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     if ($q == NULL) {
         // ERROR.
         CRM_Core_Error::fatal(ts('Invalid form parameters.'));
         CRM_Core_Error::statusBounce(ts('Invalid form parameters.'));
     }
     $mailing =& $q->getMailing();
     if ($hash) {
         $emailId = CRM_Core_DAO::getfieldValue('CRM_Mailing_Event_DAO_Queue', $hash, 'email_id', 'hash');
         $this->_fromEmail = $fromEmail = CRM_Core_DAO::getfieldValue('CRM_Core_DAO_Email', $emailId, 'email');
         $this->assign('fromEmail', $fromEmail);
     }
     // Show the subject instead of the name here, since it's being
     // displayed to external contacts/users.
     CRM_Utils_System::setTitle(ts('Forward Mailing: %1', array(1 => $mailing->subject)));
     $this->set('queue_id', $queue_id);
     $this->set('job_id', $job_id);
     $this->set('hash', $hash);
 }
Exemplo n.º 6
0
 /**
  * Get the mailing object for this queue event instance
  * 
  * @param
  * @return object           Mailing BAO
  * @access public
  */
 function &getMailing()
 {
     $mailing =& new CRM_Mailing_BAO_Mailing();
     $jobs = CRM_Mailing_BAO_Job::getTableName();
     $mailings = CRM_Mailing_BAO_Mailing::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing->query("\n                SELECT      {$mailings}.*\n                FROM        {$mailings}\n                INNER JOIN  {$jobs}\n                        ON  {$jobs}.mailing_id = {$mailings}.id\n                INNER JOIN  {$queue}\n                        ON  {$queue}.job_id = {$jobs}.id\n                WHERE       {$queue}.id = {$this->id}");
     $mailing->fetch();
     return $mailing;
 }
Exemplo n.º 7
0
 /**
  * Send the mailing.
  *
  * @param object $mailer
  *   A Mail object to send the messages.
  *
  * @param array $testParams
  *
  * @return void
  */
 public function deliver(&$mailer, $testParams = NULL)
 {
     $mailing = new CRM_Mailing_BAO_Mailing();
     $mailing->id = $this->mailing_id;
     $mailing->find(TRUE);
     $mailing->free();
     $eq = new CRM_Mailing_Event_BAO_Queue();
     $eqTable = CRM_Mailing_Event_BAO_Queue::getTableName();
     $emailTable = CRM_Core_BAO_Email::getTableName();
     $phoneTable = CRM_Core_DAO_Phone::getTableName();
     $contactTable = CRM_Contact_BAO_Contact::getTableName();
     $edTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
     $ebTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
     $query = "  SELECT      {$eqTable}.id,\n                                {$emailTable}.email as email,\n                                {$eqTable}.contact_id,\n                                {$eqTable}.hash,\n                                NULL as phone\n                    FROM        {$eqTable}\n                    INNER JOIN  {$emailTable}\n                            ON  {$eqTable}.email_id = {$emailTable}.id\n                    INNER JOIN  {$contactTable}\n                            ON  {$contactTable}.id = {$emailTable}.contact_id\n                    LEFT JOIN   {$edTable}\n                            ON  {$eqTable}.id = {$edTable}.event_queue_id\n                    LEFT JOIN   {$ebTable}\n                            ON  {$eqTable}.id = {$ebTable}.event_queue_id\n                    WHERE       {$eqTable}.job_id = " . $this->id . "\n                        AND     {$edTable}.id IS null\n                        AND     {$ebTable}.id IS null\n                        AND    {$contactTable}.is_opt_out = 0";
     if ($mailing->sms_provider_id) {
         $query = "\n                    SELECT      {$eqTable}.id,\n                                {$phoneTable}.phone as phone,\n                                {$eqTable}.contact_id,\n                                {$eqTable}.hash,\n                                NULL as email\n                    FROM        {$eqTable}\n                    INNER JOIN  {$phoneTable}\n                            ON  {$eqTable}.phone_id = {$phoneTable}.id\n                    INNER JOIN  {$contactTable}\n                            ON  {$contactTable}.id = {$phoneTable}.contact_id\n                    LEFT JOIN   {$edTable}\n                            ON  {$eqTable}.id = {$edTable}.event_queue_id\n                    LEFT JOIN   {$ebTable}\n                            ON  {$eqTable}.id = {$ebTable}.event_queue_id\n                    WHERE       {$eqTable}.job_id = " . $this->id . "\n                        AND     {$edTable}.id IS null\n                        AND     {$ebTable}.id IS null\n                        AND    ( {$contactTable}.is_opt_out = 0\n                        OR       {$contactTable}.do_not_sms = 0 )";
     }
     $eq->query($query);
     $config = NULL;
     if ($config == NULL) {
         $config = CRM_Core_Config::singleton();
     }
     $job_date = CRM_Utils_Date::isoToMysql($this->scheduled_date);
     $fields = array();
     if (!empty($testParams)) {
         $mailing->subject = ts('[CiviMail Draft]') . ' ' . $mailing->subject;
     }
     CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
     // get and format attachments
     $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
     if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
         CRM_Core_Smarty::registerStringResource();
     }
     // CRM-12376
     // This handles the edge case scenario where all the mails
     // have been delivered in prior jobs
     $isDelivered = TRUE;
     // make sure that there's no more than $config->mailerBatchLimit mails processed in a run
     while ($eq->fetch()) {
         // if ( ( $mailsProcessed % 100 ) == 0 ) {
         // CRM_Utils_System::xMemory( "$mailsProcessed: " );
         // }
         if ($config->mailerBatchLimit > 0 && self::$mailsProcessed >= $config->mailerBatchLimit) {
             if (!empty($fields)) {
                 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
             }
             $eq->free();
             return FALSE;
         }
         self::$mailsProcessed++;
         $fields[] = array('id' => $eq->id, 'hash' => $eq->hash, 'contact_id' => $eq->contact_id, 'email' => $eq->email, 'phone' => $eq->phone);
         if (count($fields) == self::MAX_CONTACTS_TO_PROCESS) {
             $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
             if (!$isDelivered) {
                 $eq->free();
                 return $isDelivered;
             }
             $fields = array();
         }
     }
     $eq->free();
     if (!empty($fields)) {
         $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
     }
     return $isDelivered;
 }
Exemplo n.º 8
0
 /**
  * Get rows for the event browser
  *
  * @param int $mailing_id       ID of the mailing
  * @param int $job_id           optional ID of the job
  * @param boolean $is_distinct  Group by queue id?
  * @param int $offset           Offset
  * @param int $rowCount         Number of rows
  * @param array $sort           sort array
  * @return array                Result set
  * @access public
  * @static
  */
 function &getRows($mailing_id, $job_id = null, $is_distinct = false, $offset = null, $rowCount = null, $sort = null)
 {
     $dao =& new CRM_Core_Dao();
     $bounce = CRM_Mailing_Event_BAO_Bounce::getTableName();
     $bounceType = CRM_Mailing_DAO_BounceType::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $query = "\n            SELECT      {$contact}.display_name as display_name,\n                        {$contact}.id as contact_id,\n                        {$email}.email as email,\n                        {$bounce}.time_stamp as date,\n                        {$bounce}.bounce_reason as reason,\n                        {$bounceType}.name as bounce_type\n            FROM        {$contact}\n            INNER JOIN  {$queue}\n                    ON  {$queue}.contact_id = {$contact}.id\n            INNER JOIN  {$email}\n                    ON  {$queue}.email_id = {$email}.id\n            INNER JOIN  {$bounce}\n                    ON  {$bounce}.event_queue_id = {$queue}.id\n            LEFT JOIN   {$bounceType}\n                    ON  {$bounce}.bounce_type_id = {$bounceType}.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     $query .= " ORDER BY {$contact}.sort_name, {$bounce}.time_stamp ";
     if ($offset) {
         $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
     }
     $dao->query($query);
     $results = array();
     while ($dao->fetch()) {
         $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->contact_id}");
         $results[] = array('name' => "<a href=\"{$url}\">{$dao->display_name}</a>", 'email' => $dao->email, 'type' => empty($dao->bounce_type) ? ts('Unknown') : $dao->bounce_type, 'reason' => $dao->reason, 'date' => CRM_Utils_Date::customFormat($dao->date));
     }
     return $results;
 }
Exemplo n.º 9
0
 /**
  * returns all the rows in the given offset and rowCount
  *
  * @param enum   $action   the action being performed
  * @param int    $offset   the row number to start from
  * @param int    $rowCount the number of rows to return
  * @param string $sort     the sql string that describes the sort order
  * @param enum   $output   what should the result set include (web/email/csv)
  *
  * @return int   the total number of rows for this action
  */
 function &getRows($action, $offset, $rowCount, $sort, $output = NULL)
 {
     switch ($this->_event_type) {
         case 'queue':
             return CRM_Mailing_Event_BAO_Queue::getRows($this->_mailing_id, $this->_job_id, $offset, $rowCount, $sort);
             break;
         case 'delivered':
             return CRM_Mailing_Event_BAO_Delivered::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
             break;
         case 'opened':
             return CRM_Mailing_Event_BAO_Opened::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
             break;
         case 'bounce':
             return CRM_Mailing_Event_BAO_Bounce::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
             break;
         case 'forward':
             return CRM_Mailing_Event_BAO_Forward::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
         case 'reply':
             return CRM_Mailing_Event_BAO_Reply::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
             break;
         case 'unsubscribe':
             return CRM_Mailing_Event_BAO_Unsubscribe::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort, TRUE);
             break;
         case 'optout':
             return CRM_Mailing_Event_BAO_Unsubscribe::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort, FALSE);
             break;
         case 'click':
             return CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $this->_url_id, $offset, $rowCount, $sort);
             break;
         default:
             return NULL;
     }
 }
Exemplo n.º 10
0
 /**
  * Send the mailing
  *
  * @param object $mailer        A Mail object to send the messages
  * @return void
  * @access public
  */
 public function deliver(&$mailer, $testParams = null)
 {
     require_once 'CRM/Mailing/BAO/Mailing.php';
     $mailing =& new CRM_Mailing_BAO_Mailing();
     $mailing->id = $this->mailing_id;
     $mailing->find(true);
     $eq =& new CRM_Mailing_Event_BAO_Queue();
     $eqTable = CRM_Mailing_Event_BAO_Queue::getTableName();
     $emailTable = CRM_Core_BAO_Email::getTableName();
     $contactTable = CRM_Contact_BAO_Contact::getTableName();
     $edTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
     $ebTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
     $query = "  SELECT      {$eqTable}.id,\n                                {$emailTable}.email as email,\n                                {$eqTable}.contact_id,\n                                {$eqTable}.hash\n                    FROM        {$eqTable}\n                    INNER JOIN  {$emailTable}\n                            ON  {$eqTable}.email_id = {$emailTable}.id\n                    LEFT JOIN   {$edTable}\n                            ON  {$eqTable}.id = {$edTable}.event_queue_id\n                    LEFT JOIN   {$ebTable}\n                            ON  {$eqTable}.id = {$ebTable}.event_queue_id\n                    WHERE       {$eqTable}.job_id = " . $this->id . "\n                        AND     {$edTable}.id IS null\n                        AND     {$ebTable}.id IS null";
     $eq->query($query);
     static $config = null;
     $mailsProcessed = 0;
     if ($config == null) {
         $config =& CRM_Core_Config::singleton();
     }
     $job_date = CRM_Utils_Date::isoToMysql($this->scheduled_date);
     $fields = array();
     if (!empty($testParams)) {
         $mailing->from_name = ts('CiviCRM Test Mailer (%1)', array(1 => $mailing->from_name));
         $mailing->subject = ts('Test Mailing:') . ' ' . $mailing->subject;
     }
     CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
     // get and format attachments
     require_once 'CRM/Core/BAO/File.php';
     $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
     if (defined('CIVICRM_MAIL_SMARTY')) {
         require_once 'CRM/Core/Smarty/resources/String.php';
         civicrm_smarty_register_string_resource();
     }
     // make sure that there's no more than $config->mailerBatchLimit mails processed in a run
     while ($eq->fetch()) {
         // if ( ( $mailsProcessed % 100 ) == 0 ) {
         // CRM_Utils_System::xMemory( "$mailsProcessed: " );
         // }
         if ($config->mailerBatchLimit > 0 && $mailsProcessed >= $config->mailerBatchLimit) {
             $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
             return false;
         }
         $mailsProcessed++;
         $fields[] = array('id' => $eq->id, 'hash' => $eq->hash, 'contact_id' => $eq->contact_id, 'email' => $eq->email);
         if (count($fields) == self::MAX_CONTACTS_TO_PROCESS) {
             $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
             if (!$isDelivered) {
                 return $isDelivered;
             }
             $fields = array();
         }
     }
     $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
     return $isDelivered;
 }
Exemplo n.º 11
0
 /**
  * Generate a report.  Fetch event count information, mailing data, and job
  * status.
  *
  * @param int     $id          The mailing id to report
  * @param boolean $skipDetails whether return all detailed report
  * @return array        Associative array of reporting data
  * @access public
  * @static
  */
 public static function &report($id, $skipDetails = false)
 {
     $mailing_id = CRM_Utils_Type::escape($id, 'Integer');
     $mailing = new CRM_Mailing_BAO_Mailing();
     require_once 'CRM/Mailing/Event/BAO/Opened.php';
     require_once 'CRM/Mailing/Event/BAO/Reply.php';
     require_once 'CRM/Mailing/Event/BAO/Unsubscribe.php';
     require_once 'CRM/Mailing/Event/BAO/Forward.php';
     require_once 'CRM/Mailing/Event/BAO/TrackableURLOpen.php';
     require_once 'CRM/Mailing/BAO/Spool.php';
     $t = array('mailing' => self::getTableName(), 'mailing_group' => CRM_Mailing_DAO_Group::getTableName(), 'group' => CRM_Contact_BAO_Group::getTableName(), 'job' => CRM_Mailing_BAO_Job::getTableName(), 'queue' => CRM_Mailing_Event_BAO_Queue::getTableName(), 'delivered' => CRM_Mailing_Event_BAO_Delivered::getTableName(), 'opened' => CRM_Mailing_Event_BAO_Opened::getTableName(), 'reply' => CRM_Mailing_Event_BAO_Reply::getTableName(), 'unsubscribe' => CRM_Mailing_Event_BAO_Unsubscribe::getTableName(), 'bounce' => CRM_Mailing_Event_BAO_Bounce::getTableName(), 'forward' => CRM_Mailing_Event_BAO_Forward::getTableName(), 'url' => CRM_Mailing_BAO_TrackableURL::getTableName(), 'urlopen' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTableName(), 'component' => CRM_Mailing_BAO_Component::getTableName(), 'spool' => CRM_Mailing_BAO_Spool::getTableName());
     $report = array();
     /* Get the mailing info */
     $mailing->query("\n            SELECT          {$t['mailing']}.*\n            FROM            {$t['mailing']}\n            WHERE           {$t['mailing']}.id = {$mailing_id}");
     $mailing->fetch();
     $report['mailing'] = array();
     foreach (array_keys(self::fields()) as $field) {
         $report['mailing'][$field] = $mailing->{$field};
     }
     //mailing report is called by activity
     //we dont need all detail report
     if ($skipDetails) {
         return $report;
     }
     /* Get the component info */
     $query = array();
     $components = array('header' => ts('Header'), 'footer' => ts('Footer'), 'reply' => ts('Reply'), 'unsubscribe' => ts('Unsubscribe'), 'optout' => ts('Opt-Out'));
     foreach (array_keys($components) as $type) {
         $query[] = "SELECT          {$t['component']}.name as name,\n                                        '{$type}' as type,\n                                        {$t['component']}.id as id\n                        FROM            {$t['component']}\n                        INNER JOIN      {$t['mailing']}\n                                ON      {$t['mailing']}.{$type}_id =\n                                                {$t['component']}.id\n                        WHERE           {$t['mailing']}.id = {$mailing_id}";
     }
     $q = '(' . implode(') UNION (', $query) . ')';
     $mailing->query($q);
     $report['component'] = array();
     while ($mailing->fetch()) {
         $report['component'][] = array('type' => $components[$mailing->type], 'name' => $mailing->name, 'link' => CRM_Utils_System::url('civicrm/mailing/component', "reset=1&action=update&id={$mailing->id}"));
     }
     /* Get the recipient group info */
     $mailing->query("\n            SELECT          {$t['mailing_group']}.group_type as group_type,\n                            {$t['group']}.id as group_id,\n                            {$t['group']}.title as group_title,\n                            {$t['mailing']}.id as mailing_id,\n                            {$t['mailing']}.name as mailing_name\n            FROM            {$t['mailing_group']}\n            LEFT JOIN       {$t['group']}\n                    ON      {$t['mailing_group']}.entity_id = {$t['group']}.id\n                    AND     {$t['mailing_group']}.entity_table =\n                                                                '{$t['group']}'\n            LEFT JOIN       {$t['mailing']}\n                    ON      {$t['mailing_group']}.entity_id =\n                                                            {$t['mailing']}.id\n                    AND     {$t['mailing_group']}.entity_table =\n                                                            '{$t['mailing']}'\n\n            WHERE           {$t['mailing_group']}.mailing_id = {$mailing_id}\n            ");
     $report['group'] = array('include' => array(), 'exclude' => array());
     while ($mailing->fetch()) {
         $row = array();
         if (isset($mailing->group_id)) {
             $row['id'] = $mailing->group_id;
             $row['name'] = $mailing->group_title;
             $row['link'] = CRM_Utils_System::url('civicrm/group/search', "reset=1&force=1&context=smog&gid={$row['id']}");
         } else {
             $row['id'] = $mailing->mailing_id;
             $row['name'] = $mailing->mailing_name;
             $row['mailing'] = true;
             $row['link'] = CRM_Utils_System::url('civicrm/mailing/report', "mid={$row['id']}");
         }
         if ($mailing->group_type == 'Include') {
             $report['group']['include'][] = $row;
         } else {
             $report['group']['exclude'][] = $row;
         }
     }
     /* Get the event totals, grouped by job (retries) */
     $mailing->query("\n            SELECT          {$t['job']}.*,\n                            COUNT(DISTINCT {$t['queue']}.id) as queue,\n                            COUNT(DISTINCT {$t['delivered']}.id) as delivered,\n                            COUNT(DISTINCT {$t['reply']}.id) as reply,\n                            COUNT(DISTINCT {$t['forward']}.id) as forward,\n                            COUNT(DISTINCT {$t['bounce']}.id) as bounce,\n                            COUNT(DISTINCT {$t['urlopen']}.id) as url,\n                            COUNT(DISTINCT {$t['spool']}.id) as spool\n            FROM            {$t['job']}\n            LEFT JOIN       {$t['queue']}\n                    ON      {$t['queue']}.job_id = {$t['job']}.id\n            LEFT JOIN       {$t['reply']}\n                    ON      {$t['reply']}.event_queue_id = {$t['queue']}.id\n            LEFT JOIN       {$t['forward']}\n                    ON      {$t['forward']}.event_queue_id = {$t['queue']}.id\n            LEFT JOIN       {$t['bounce']}\n                    ON      {$t['bounce']}.event_queue_id = {$t['queue']}.id\n            LEFT JOIN       {$t['delivered']}\n                    ON      {$t['delivered']}.event_queue_id = {$t['queue']}.id\n                    AND     {$t['bounce']}.id IS null\n            LEFT JOIN       {$t['urlopen']}\n                    ON      {$t['urlopen']}.event_queue_id = {$t['queue']}.id\n            LEFT JOIN       {$t['spool']}\n                    ON      {$t['spool']}.job_id = {$t['job']}.id\n            WHERE           {$t['job']}.mailing_id = {$mailing_id}\n                    AND     {$t['job']}.is_test = 0\n            GROUP BY        {$t['job']}.id");
     $report['jobs'] = array();
     $report['event_totals'] = array();
     $elements = array('queue', 'delivered', 'url', 'forward', 'reply', 'unsubscribe', 'opened', 'bounce', 'spool');
     // initialize various counters
     foreach ($elements as $field) {
         $report['event_totals'][$field] = 0;
     }
     while ($mailing->fetch()) {
         $row = array();
         foreach ($elements as $field) {
             if (isset($mailing->{$field})) {
                 $row[$field] = $mailing->{$field};
                 $report['event_totals'][$field] += $mailing->{$field};
             }
         }
         // compute open total separately to discount duplicates
         // CRM-1258
         $row['opened'] = CRM_Mailing_Event_BAO_Opened::getTotalCount($mailing_id, $mailing->id, true);
         $report['event_totals']['opened'] += $row['opened'];
         // compute unsub total separately to discount duplicates
         // CRM-1783
         $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, true);
         $report['event_totals']['unsubscribe'] += $row['unsubscribe'];
         foreach (array_keys(CRM_Mailing_BAO_Job::fields()) as $field) {
             $row[$field] = $mailing->{$field};
         }
         if ($mailing->queue) {
             $row['delivered_rate'] = 100.0 * $mailing->delivered / $mailing->queue;
             $row['bounce_rate'] = 100.0 * $mailing->bounce / $mailing->queue;
             $row['unsubscribe_rate'] = 100.0 * $row['unsubscribe'] / $mailing->queue;
         } else {
             $row['delivered_rate'] = 0;
             $row['bounce_rate'] = 0;
             $row['unsubscribe_rate'] = 0;
         }
         $row['links'] = array('clicks' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=click&mid={$mailing_id}&jid={$mailing->id}"), 'queue' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=queue&mid={$mailing_id}&jid={$mailing->id}"), 'delivered' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=delivered&mid={$mailing_id}&jid={$mailing->id}"), 'bounce' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=bounce&mid={$mailing_id}&jid={$mailing->id}"), 'unsubscribe' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=unsubscribe&mid={$mailing_id}&jid={$mailing->id}"), 'forward' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=forward&mid={$mailing_id}&jid={$mailing->id}"), 'reply' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=reply&mid={$mailing_id}&jid={$mailing->id}"), 'opened' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=opened&mid={$mailing_id}&jid={$mailing->id}"));
         foreach (array('scheduled_date', 'start_date', 'end_date') as $key) {
             $row[$key] = CRM_Utils_Date::customFormat($row[$key]);
         }
         $report['jobs'][] = $row;
     }
     $report['event_totals']['queue'] = self::getRecipientsCount($mailing_id, false, $mailing_id);
     if (CRM_Utils_Array::value('queue', $report['event_totals'])) {
         $report['event_totals']['delivered_rate'] = 100.0 * $report['event_totals']['delivered'] / $report['event_totals']['queue'];
         $report['event_totals']['bounce_rate'] = 100.0 * $report['event_totals']['bounce'] / $report['event_totals']['queue'];
         $report['event_totals']['unsubscribe_rate'] = 100.0 * $report['event_totals']['unsubscribe'] / $report['event_totals']['queue'];
     } else {
         $report['event_totals']['delivered_rate'] = 0;
         $report['event_totals']['bounce_rate'] = 0;
         $report['event_totals']['unsubscribe_rate'] = 0;
     }
     /* Get the click-through totals, grouped by URL */
     $mailing->query("\n            SELECT      {$t['url']}.url,\n                        {$t['url']}.id,\n                        COUNT({$t['urlopen']}.id) as clicks,\n                        COUNT(DISTINCT {$t['queue']}.id) as unique_clicks\n            FROM        {$t['url']}\n            LEFT JOIN   {$t['urlopen']}\n                    ON  {$t['urlopen']}.trackable_url_id = {$t['url']}.id\n            LEFT JOIN  {$t['queue']}\n                    ON  {$t['urlopen']}.event_queue_id = {$t['queue']}.id\n            LEFT JOIN  {$t['job']}\n                    ON  {$t['queue']}.job_id = {$t['job']}.id\n            WHERE       {$t['url']}.mailing_id = {$mailing_id}\n                    AND {$t['job']}.is_test = 0\n            GROUP BY    {$t['url']}.id");
     $report['click_through'] = array();
     while ($mailing->fetch()) {
         $report['click_through'][] = array('url' => $mailing->url, 'link' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=click&mid={$mailing_id}&uid={$mailing->id}"), 'link_unique' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=click&mid={$mailing_id}&uid={$mailing->id}&distinct=1"), 'clicks' => $mailing->clicks, 'unique' => $mailing->unique_clicks, 'rate' => CRM_Utils_Array::value('delivered', $report['event_totals']) ? 100.0 * $mailing->unique_clicks / $report['event_totals']['delivered'] : 0);
     }
     $report['event_totals']['links'] = array('clicks' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=click&mid={$mailing_id}"), 'clicks_unique' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=click&mid={$mailing_id}&distinct=1"), 'queue' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=queue&mid={$mailing_id}"), 'delivered' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=delivered&mid={$mailing_id}"), 'bounce' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=bounce&mid={$mailing_id}"), 'unsubscribe' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=unsubscribe&mid={$mailing_id}"), 'forward' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=forward&mid={$mailing_id}"), 'reply' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=reply&mid={$mailing_id}"), 'opened' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=opened&mid={$mailing_id}"));
     return $report;
 }
Exemplo n.º 12
0
 /**
  * Delete email address records from a location
  *
  * @param int $locationId       Location ID to delete for
  * 
  * @return void
  * 
  * @access public
  * @static
  */
 function deleteLocation($locationId)
 {
     $dao =& new CRM_Core_DAO_Email();
     $dao->location_id = $locationId;
     $dao->find();
     require_once 'CRM/Mailing/Event/BAO/Queue.php';
     while ($dao->fetch()) {
         CRM_Mailing_Event_BAO_Queue::deleteEmail($dao->id);
     }
     $dao->reset();
     $dao->location_id = $locationId;
     $dao->delete();
 }
Exemplo n.º 13
0
 /**
  * Form rule to send out a test mailing.
  *
  * @param array $params     Array of the form values
  * @param array $files      Any files posted to the form
  * @param array $self       an current this object
  *
  * @return boolean          true on succesful SMTP handoff
  * @access public
  */
 static function &testMail($testParams, $files, $self)
 {
     $error = NULL;
     $urlString = 'civicrm/mailing/send';
     $urlParams = "_qf_Test_display=true&qfKey={$testParams['qfKey']}";
     $ssID = $self->get('ssID');
     if ($ssID && $self->_searchBasedMailing) {
         if ($self->_action == CRM_Core_Action::BASIC) {
             $fragment = 'search';
         } elseif ($self->_action == CRM_Core_Action::PROFILE) {
             $fragment = 'search/builder';
         } elseif ($self->_action == CRM_Core_Action::ADVANCED) {
             $fragment = 'search/advanced';
         } else {
             $fragment = 'search/custom';
         }
         $urlString = 'civicrm/contact/' . $fragment;
     }
     $emails = NULL;
     if (CRM_Utils_Array::value('sendtest', $testParams)) {
         if (!($testParams['test_group'] || $testParams['test_email'])) {
             CRM_Core_Session::setStatus(ts('Your did not provided any email address or selected any group. No test mail is sent.'));
             $error = TRUE;
         }
         if ($testParams['test_email']) {
             $emailAdd = explode(',', $testParams['test_email']);
             foreach ($emailAdd as $key => $value) {
                 $email = trim($value);
                 $testParams['emails'][] = $email;
                 $emails .= $emails ? ",'{$email}'" : "'{$email}'";
                 if (!CRM_Utils_Rule::email($email)) {
                     CRM_Core_Session::setStatus(ts('Please enter valid email addresses only.'));
                     $error = TRUE;
                 }
             }
         }
         if ($error) {
             $url = CRM_Utils_System::url($urlString, $urlParams);
             CRM_Utils_System::redirect($url);
             return $error;
         }
     }
     if (CRM_Utils_Array::value('_qf_Test_submit', $testParams)) {
         //when user perform mailing from search context
         //redirect it to search result CRM-3711.
         if ($ssID && $self->_searchBasedMailing) {
             $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             $status = ts("Your mailing has been saved. You can continue later by clicking the 'Continue' action to resume working on it.<br /> From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL));
             CRM_Core_Session::setStatus($status);
             //replace user context to search.
             $context = $self->get('context');
             if (!CRM_Contact_Form_Search::isSearchContext($context)) {
                 $context = 'search';
             }
             $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}&qfKey={$testParams['qfKey']}";
             $url = CRM_Utils_System::url($urlString, $urlParams);
             CRM_Utils_System::redirect($url);
         } else {
             $status = ts("Your mailing has been saved. Click the 'Continue' action to resume working on it.");
             CRM_Core_Session::setStatus($status);
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             CRM_Utils_System::redirect($url);
         }
     }
     if (CRM_Mailing_Info::workflowEnabled()) {
         if (!CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings')) {
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             CRM_Utils_System::redirect($url);
         }
     }
     if (CRM_Utils_Array::value('_qf_Import_refresh', $_POST) || CRM_Utils_Array::value('_qf_Test_next', $testParams) || !CRM_Utils_Array::value('sendtest', $testParams)) {
         $error = TRUE;
         return $error;
     }
     $job = new CRM_Mailing_BAO_Job();
     $job->mailing_id = $self->get('mailing_id');
     $job->is_test = TRUE;
     $job->save();
     $newEmails = NULL;
     $session = CRM_Core_Session::singleton();
     if (!empty($testParams['emails'])) {
         $query = "\n                      SELECT id, contact_id, email  \n                      FROM civicrm_email  \n                      WHERE civicrm_email.email IN ({$emails})";
         $dao = CRM_Core_DAO::executeQuery($query);
         $emailDetail = array();
         // fetch contact_id and email id for all existing emails
         while ($dao->fetch()) {
             $emailDetail[$dao->email] = array('contact_id' => $dao->contact_id, 'email_id' => $dao->id);
         }
         $dao->free();
         foreach ($testParams['emails'] as $key => $email) {
             $email = trim($email);
             $contactId = $emailId = NULL;
             if (array_key_exists($email, $emailDetail)) {
                 $emailId = $emailDetail[$email]['email_id'];
                 $contactId = $emailDetail[$email]['contact_id'];
             }
             if (!$contactId) {
                 //create new contact.
                 $params = array('contact_type' => 'Individual', 'email' => array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => 1)));
                 $contact = CRM_Contact_BAO_Contact::create($params);
                 $emailId = $contact->email[0]->id;
                 $contactId = $contact->id;
                 $contact->free();
             }
             $params = array('job_id' => $job->id, 'email_id' => $emailId, 'contact_id' => $contactId);
             CRM_Mailing_Event_BAO_Queue::create($params);
         }
     }
     $testParams['job_id'] = $job->id;
     $isComplete = FALSE;
     while (!$isComplete) {
         $isComplete = CRM_Mailing_BAO_Job::runJobs($testParams);
     }
     if (CRM_Utils_Array::value('sendtest', $testParams)) {
         $status = ts('Your test message has been sent.');
         if (CRM_Mailing_Info::workflowEnabled()) {
             if (CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings') || CRM_Core_Permission::check('access CiviMail')) {
                 $status .= ts(" Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
             }
         } else {
             $status .= ts(" Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
         }
         CRM_Core_Session::setStatus($status);
         $url = CRM_Utils_System::url($urlString, $urlParams);
         CRM_Utils_System::redirect($url);
     }
     $error = TRUE;
     return $error;
 }
Exemplo n.º 14
0
function mte_createQueue(&$mandrillHeader, $toEmail)
{
    $mail = new CRM_Mailing_DAO_Mailing();
    $mail->subject = "***All Transactional Emails***";
    $mail->url_tracking = TRUE;
    $mail->forward_replies = FALSE;
    $mail->auto_responder = FALSE;
    $mail->open_tracking = TRUE;
    if ($mail->find(TRUE)) {
        $emails = CRM_Mte_BAO_Mandrill::retrieveEmailContactId($toEmail);
        $jobCLassName = 'CRM_Mailing_DAO_MailingJob';
        if (version_compare('4.4alpha1', CRM_Core_Config::singleton()->civiVersion) > 0) {
            $jobCLassName = 'CRM_Mailing_DAO_Job';
        }
        $params = array('job_id' => CRM_Core_DAO::getFieldValue($jobCLassName, $mail->id, 'id', 'mailing_id'), 'contact_id' => $emails['email']['contact_id'], 'email_id' => $emails['email']['id']);
        $eventQueue = CRM_Mailing_Event_BAO_Queue::create($params);
        $mandrillHeader = implode(CRM_Core_Config::singleton()->verpSeparator, array($mandrillHeader, 'm', $params['job_id'], $eventQueue->id, $eventQueue->hash));
    }
}
Exemplo n.º 15
0
 /**
  * Send the mailing
  *
  * @param object $mailer        A Mail object to send the messages
  * @return void
  * @access public
  */
 function deliver(&$mailer)
 {
     require_once 'CRM/Mailing/BAO/Mailing.php';
     $mailing =& new CRM_Mailing_BAO_Mailing();
     $mailing->id = $this->mailing_id;
     $mailing->find(true);
     $eq =& new CRM_Mailing_Event_BAO_Queue();
     $eqTable = CRM_Mailing_Event_BAO_Queue::getTableName();
     $emailTable = CRM_Core_BAO_Email::getTableName();
     $contactTable = CRM_Contact_BAO_Contact::getTableName();
     $edTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
     $ebTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
     $query = "  SELECT      {$eqTable}.id,\n                                {$emailTable}.email as email,\n                                {$eqTable}.contact_id,\n                                {$eqTable}.hash\n                    FROM        {$eqTable}\n                    INNER JOIN  {$emailTable}\n                            ON  {$eqTable}.email_id = {$emailTable}.id\n                    LEFT JOIN   {$edTable}\n                            ON  {$eqTable}.id = {$edTable}.event_queue_id\n                    LEFT JOIN   {$ebTable}\n                            ON  {$eqTable}.id = {$ebTable}.event_queue_id\n                    WHERE       {$eqTable}.job_id = " . $this->id . "\n                        AND     {$edTable}.id IS null\n                        AND     {$ebTable}.id IS null";
     $eq->query($query);
     while ($eq->fetch()) {
         /* Compose the mailing */
         $recipient = null;
         $message = $mailing->compose($this->id, $eq->id, $eq->hash, $eq->contact_id, $eq->email, $recipient);
         /* Send the mailing */
         $body = $message->get();
         $headers = $message->headers();
         /* TODO: when we separate the content generator from the delivery
          * engine, maybe we should dump the messages into a table */
         PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Mailing_BAO_Mailing', 'catchSMTP'));
         $result = $mailer->send($recipient, $headers, $body);
         CRM_Core_Error::setCallback();
         $params = array('event_queue_id' => $eq->id, 'job_id' => $this->id, 'hash' => $eq->hash);
         if (is_a($result, PEAR_Error)) {
             /* Register the bounce event */
             require_once 'CRM/Mailing/BAO/BouncePattern.php';
             require_once 'CRM/Mailing/Event/BAO/Bounce.php';
             $params = array_merge($params, CRM_Mailing_BAO_BouncePattern::match($result->getMessage()));
             CRM_Mailing_Event_BAO_Bounce::create($params);
         } else {
             /* Register the delivery event */
             CRM_Mailing_Event_BAO_Delivered::create($params);
         }
     }
 }
 /**
  * @param $mailingId
  * @param $emails
  *
  * @return CRM_Mailing_BAO_MailingJob
  */
 protected static function sendTestEmailToIndividuals($mailingId, $emails)
 {
     $job = static::createTestMailingJob($mailingId);
     $emailArr = explode(',', $emails);
     array_walk($emailArr, function (&$email) {
         $email = trim($email);
     });
     $emailStr = implode(', ', array_map(function ($email) {
         return '\'' . $email . '\'';
     }, $emailArr));
     $query = "\n      SELECT e.id, e.contact_id, e.email\n      FROM civicrm_email e\n\n      INNER JOIN civicrm_contact c ON e.contact_id = c.id\n\n      WHERE e.email IN ({$emailStr})\n        AND e.on_hold = 0\n        AND c.is_opt_out = 0\n        AND c.do_not_email = 0\n        AND c.is_deceased = 0\n\n      GROUP BY e.id\n      ORDER BY e.is_bulkmail DESC, e.is_primary DESC\n    ";
     $dao = CRM_Core_DAO::executeQuery($query);
     $emailDetail = array();
     // fetch contact_id and email id for all existing emails
     while ($dao->fetch()) {
         $emailDetail[$dao->email] = array('contact_id' => $dao->contact_id, 'email_id' => $dao->id);
     }
     $dao->free();
     foreach ($emailArr as $email) {
         $email = trim($email);
         $contactId = $emailId = NULL;
         if (array_key_exists($email, $emailDetail)) {
             $emailId = $emailDetail[$email]['email_id'];
             $contactId = $emailDetail[$email]['contact_id'];
         }
         if (!$contactId) {
             //create new contact.
             $createParams = array('contact_type' => 'Individual', 'email' => array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => 1)));
             $contact = CRM_Contact_BAO_Contact::create($createParams);
             $emailId = $contact->email[0]->id;
             $contactId = $contact->id;
             $contact->free();
         }
         $queueParams = array('job_id' => $job->id, 'email_id' => $emailId, 'contact_id' => $contactId);
         CRM_Mailing_Event_BAO_Queue::create($queueParams);
     }
     static::runTestEmailJobs($job);
     return $job;
 }
Exemplo n.º 17
0
 /**
  * Given a queue event ID, find the corresponding email address.
  *
  * @param int $queue_id
  *   The queue event ID.
  *
  * @return string
  *   The email address
  */
 public static function getEmailAddress($queue_id)
 {
     $email = CRM_Core_BAO_Email::getTableName();
     $eq = self::getTableName();
     $query = "  SELECT      {$email}.email as email\n                    FROM        {$email}\n                    INNER JOIN  {$eq}\n                    ON          {$eq}.email_id = {$email}.id\n                    WHERE       {$eq}.id = " . CRM_Utils_Type::rule($queue_id, 'Integer');
     $q = new CRM_Mailing_Event_BAO_Queue();
     $q->query($query);
     if (!$q->fetch()) {
         return NULL;
     }
     return $q->email;
 }
Exemplo n.º 18
0
 /**
  * Generate a report.  Fetch event count information, mailing data, and job
  * status.
  *
  * @param int $id
  *   The mailing id to report.
  * @param bool $skipDetails
  *   Whether return all detailed report.
  *
  * @param bool $isSMS
  *
  * @return array
  *   Associative array of reporting data
  */
 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE)
 {
     $mailing_id = CRM_Utils_Type::escape($id, 'Integer');
     $mailing = new CRM_Mailing_BAO_Mailing();
     $t = array('mailing' => self::getTableName(), 'mailing_group' => CRM_Mailing_DAO_MailingGroup::getTableName(), 'group' => CRM_Contact_BAO_Group::getTableName(), 'job' => CRM_Mailing_BAO_MailingJob::getTableName(), 'queue' => CRM_Mailing_Event_BAO_Queue::getTableName(), 'delivered' => CRM_Mailing_Event_BAO_Delivered::getTableName(), 'opened' => CRM_Mailing_Event_BAO_Opened::getTableName(), 'reply' => CRM_Mailing_Event_BAO_Reply::getTableName(), 'unsubscribe' => CRM_Mailing_Event_BAO_Unsubscribe::getTableName(), 'bounce' => CRM_Mailing_Event_BAO_Bounce::getTableName(), 'forward' => CRM_Mailing_Event_BAO_Forward::getTableName(), 'url' => CRM_Mailing_BAO_TrackableURL::getTableName(), 'urlopen' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTableName(), 'component' => CRM_Mailing_BAO_Component::getTableName(), 'spool' => CRM_Mailing_BAO_Spool::getTableName());
     $report = array();
     $additionalWhereClause = " AND ";
     if (!$isSMS) {
         $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
     } else {
         $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
     }
     /* Get the mailing info */
     $mailing->query("\n            SELECT          {$t['mailing']}.*\n            FROM            {$t['mailing']}\n            WHERE           {$t['mailing']}.id = {$mailing_id} {$additionalWhereClause}");
     $mailing->fetch();
     $report['mailing'] = array();
     foreach (array_keys(self::fields()) as $field) {
         $report['mailing'][$field] = $mailing->{$field};
     }
     //get the campaign
     if ($campaignId = CRM_Utils_Array::value('campaign_id', $report['mailing'])) {
         $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
         $report['mailing']['campaign'] = $campaigns[$campaignId];
     }
     //mailing report is called by activity
     //we dont need all detail report
     if ($skipDetails) {
         return $report;
     }
     /* Get the component info */
     $query = array();
     $components = array('header' => ts('Header'), 'footer' => ts('Footer'), 'reply' => ts('Reply'), 'unsubscribe' => ts('Unsubscribe'), 'optout' => ts('Opt-Out'));
     foreach (array_keys($components) as $type) {
         $query[] = "SELECT          {$t['component']}.name as name,\n                                        '{$type}' as type,\n                                        {$t['component']}.id as id\n                        FROM            {$t['component']}\n                        INNER JOIN      {$t['mailing']}\n                                ON      {$t['mailing']}.{$type}_id =\n                                                {$t['component']}.id\n                        WHERE           {$t['mailing']}.id = {$mailing_id}";
     }
     $q = '(' . implode(') UNION (', $query) . ')';
     $mailing->query($q);
     $report['component'] = array();
     while ($mailing->fetch()) {
         $report['component'][] = array('type' => $components[$mailing->type], 'name' => $mailing->name, 'link' => CRM_Utils_System::url('civicrm/mailing/component', "reset=1&action=update&id={$mailing->id}"));
     }
     /* Get the recipient group info */
     $mailing->query("\n            SELECT          {$t['mailing_group']}.group_type as group_type,\n                            {$t['group']}.id as group_id,\n                            {$t['group']}.title as group_title,\n                            {$t['group']}.is_hidden as group_hidden,\n                            {$t['mailing']}.id as mailing_id,\n                            {$t['mailing']}.name as mailing_name\n            FROM            {$t['mailing_group']}\n            LEFT JOIN       {$t['group']}\n                    ON      {$t['mailing_group']}.entity_id = {$t['group']}.id\n                    AND     {$t['mailing_group']}.entity_table =\n                                                                '{$t['group']}'\n            LEFT JOIN       {$t['mailing']}\n                    ON      {$t['mailing_group']}.entity_id =\n                                                            {$t['mailing']}.id\n                    AND     {$t['mailing_group']}.entity_table =\n                                                            '{$t['mailing']}'\n\n            WHERE           {$t['mailing_group']}.mailing_id = {$mailing_id}\n            ");
     $report['group'] = array('include' => array(), 'exclude' => array(), 'base' => array());
     while ($mailing->fetch()) {
         $row = array();
         if (isset($mailing->group_id)) {
             $row['id'] = $mailing->group_id;
             $row['name'] = $mailing->group_title;
             $row['link'] = CRM_Utils_System::url('civicrm/group/search', "reset=1&force=1&context=smog&gid={$row['id']}");
         } else {
             $row['id'] = $mailing->mailing_id;
             $row['name'] = $mailing->mailing_name;
             $row['mailing'] = TRUE;
             $row['link'] = CRM_Utils_System::url('civicrm/mailing/report', "mid={$row['id']}");
         }
         /* Rename hidden groups */
         if ($mailing->group_hidden == 1) {
             $row['name'] = "Search Results";
         }
         if ($mailing->group_type == 'Include') {
             $report['group']['include'][] = $row;
         } elseif ($mailing->group_type == 'Base') {
             $report['group']['base'][] = $row;
         } else {
             $report['group']['exclude'][] = $row;
         }
     }
     /* Get the event totals, grouped by job (retries) */
     $mailing->query("\n            SELECT          {$t['job']}.*,\n                            COUNT(DISTINCT {$t['queue']}.id) as queue,\n                            COUNT(DISTINCT {$t['delivered']}.id) as delivered,\n                            COUNT(DISTINCT {$t['reply']}.id) as reply,\n                            COUNT(DISTINCT {$t['forward']}.id) as forward,\n                            COUNT(DISTINCT {$t['bounce']}.id) as bounce,\n                            COUNT(DISTINCT {$t['urlopen']}.id) as url,\n                            COUNT(DISTINCT {$t['spool']}.id) as spool\n            FROM            {$t['job']}\n            LEFT JOIN       {$t['queue']}\n                    ON      {$t['queue']}.job_id = {$t['job']}.id\n            LEFT JOIN       {$t['reply']}\n                    ON      {$t['reply']}.event_queue_id = {$t['queue']}.id\n            LEFT JOIN       {$t['forward']}\n                    ON      {$t['forward']}.event_queue_id = {$t['queue']}.id\n            LEFT JOIN       {$t['bounce']}\n                    ON      {$t['bounce']}.event_queue_id = {$t['queue']}.id\n            LEFT JOIN       {$t['delivered']}\n                    ON      {$t['delivered']}.event_queue_id = {$t['queue']}.id\n                    AND     {$t['bounce']}.id IS null\n            LEFT JOIN       {$t['urlopen']}\n                    ON      {$t['urlopen']}.event_queue_id = {$t['queue']}.id\n            LEFT JOIN       {$t['spool']}\n                    ON      {$t['spool']}.job_id = {$t['job']}.id\n            WHERE           {$t['job']}.mailing_id = {$mailing_id}\n                    AND     {$t['job']}.is_test = 0\n            GROUP BY        {$t['job']}.id");
     $report['jobs'] = array();
     $report['event_totals'] = array();
     $elements = array('queue', 'delivered', 'url', 'forward', 'reply', 'unsubscribe', 'optout', 'opened', 'bounce', 'spool');
     // initialize various counters
     foreach ($elements as $field) {
         $report['event_totals'][$field] = 0;
     }
     while ($mailing->fetch()) {
         $row = array();
         foreach ($elements as $field) {
             if (isset($mailing->{$field})) {
                 $row[$field] = $mailing->{$field};
                 $report['event_totals'][$field] += $mailing->{$field};
             }
         }
         // compute open total separately to discount duplicates
         // CRM-1258
         $row['opened'] = CRM_Mailing_Event_BAO_Opened::getTotalCount($mailing_id, $mailing->id, TRUE);
         $report['event_totals']['opened'] += $row['opened'];
         // compute unsub total separately to discount duplicates
         // CRM-1783
         $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, TRUE);
         $report['event_totals']['unsubscribe'] += $row['unsubscribe'];
         $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, FALSE);
         $report['event_totals']['optout'] += $row['optout'];
         foreach (array_keys(CRM_Mailing_BAO_MailingJob::fields()) as $field) {
             $row[$field] = $mailing->{$field};
         }
         if ($mailing->queue) {
             $row['delivered_rate'] = 100.0 * $mailing->delivered / $mailing->queue;
             $row['bounce_rate'] = 100.0 * $mailing->bounce / $mailing->queue;
             $row['unsubscribe_rate'] = 100.0 * $row['unsubscribe'] / $mailing->queue;
             $row['optout_rate'] = 100.0 * $row['optout'] / $mailing->queue;
         } else {
             $row['delivered_rate'] = 0;
             $row['bounce_rate'] = 0;
             $row['unsubscribe_rate'] = 0;
             $row['optout_rate'] = 0;
         }
         $row['links'] = array('clicks' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=click&mid={$mailing_id}&jid={$mailing->id}"), 'queue' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=queue&mid={$mailing_id}&jid={$mailing->id}"), 'delivered' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=delivered&mid={$mailing_id}&jid={$mailing->id}"), 'bounce' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=bounce&mid={$mailing_id}&jid={$mailing->id}"), 'unsubscribe' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=unsubscribe&mid={$mailing_id}&jid={$mailing->id}"), 'forward' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=forward&mid={$mailing_id}&jid={$mailing->id}"), 'reply' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=reply&mid={$mailing_id}&jid={$mailing->id}"), 'opened' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=opened&mid={$mailing_id}&jid={$mailing->id}"));
         foreach (array('scheduled_date', 'start_date', 'end_date') as $key) {
             $row[$key] = CRM_Utils_Date::customFormat($row[$key]);
         }
         $report['jobs'][] = $row;
     }
     $newTableSize = CRM_Mailing_BAO_Recipients::mailingSize($mailing_id);
     // we need to do this for backward compatibility, since old mailings did not
     // use the mailing_recipients table
     if ($newTableSize > 0) {
         $report['event_totals']['queue'] = $newTableSize;
     } else {
         $report['event_totals']['queue'] = self::getRecipientsCount($mailing_id, $mailing_id);
     }
     if (!empty($report['event_totals']['queue'])) {
         $report['event_totals']['delivered_rate'] = 100.0 * $report['event_totals']['delivered'] / $report['event_totals']['queue'];
         $report['event_totals']['bounce_rate'] = 100.0 * $report['event_totals']['bounce'] / $report['event_totals']['queue'];
         $report['event_totals']['unsubscribe_rate'] = 100.0 * $report['event_totals']['unsubscribe'] / $report['event_totals']['queue'];
         $report['event_totals']['optout_rate'] = 100.0 * $report['event_totals']['optout'] / $report['event_totals']['queue'];
     } else {
         $report['event_totals']['delivered_rate'] = 0;
         $report['event_totals']['bounce_rate'] = 0;
         $report['event_totals']['unsubscribe_rate'] = 0;
         $report['event_totals']['optout_rate'] = 0;
     }
     /* Get the click-through totals, grouped by URL */
     $mailing->query("\n            SELECT      {$t['url']}.url,\n                        {$t['url']}.id,\n                        COUNT({$t['urlopen']}.id) as clicks,\n                        COUNT(DISTINCT {$t['queue']}.id) as unique_clicks\n            FROM        {$t['url']}\n            LEFT JOIN   {$t['urlopen']}\n                    ON  {$t['urlopen']}.trackable_url_id = {$t['url']}.id\n            LEFT JOIN  {$t['queue']}\n                    ON  {$t['urlopen']}.event_queue_id = {$t['queue']}.id\n            LEFT JOIN  {$t['job']}\n                    ON  {$t['queue']}.job_id = {$t['job']}.id\n            WHERE       {$t['url']}.mailing_id = {$mailing_id}\n                    AND {$t['job']}.is_test = 0\n            GROUP BY    {$t['url']}.id");
     $report['click_through'] = array();
     while ($mailing->fetch()) {
         $report['click_through'][] = array('url' => $mailing->url, 'link' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=click&mid={$mailing_id}&uid={$mailing->id}"), 'link_unique' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=click&mid={$mailing_id}&uid={$mailing->id}&distinct=1"), 'clicks' => $mailing->clicks, 'unique' => $mailing->unique_clicks, 'rate' => CRM_Utils_Array::value('delivered', $report['event_totals']) ? 100.0 * $mailing->unique_clicks / $report['event_totals']['delivered'] : 0);
     }
     $report['event_totals']['links'] = array('clicks' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=click&mid={$mailing_id}"), 'clicks_unique' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=click&mid={$mailing_id}&distinct=1"), 'queue' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=queue&mid={$mailing_id}"), 'delivered' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=delivered&mid={$mailing_id}"), 'bounce' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=bounce&mid={$mailing_id}"), 'unsubscribe' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=unsubscribe&mid={$mailing_id}"), 'optout' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=optout&mid={$mailing_id}"), 'forward' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=forward&mid={$mailing_id}"), 'reply' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=reply&mid={$mailing_id}"), 'opened' => CRM_Utils_System::url('civicrm/mailing/report/event', "reset=1&event=opened&mid={$mailing_id}"));
     $actionLinks = array(CRM_Core_Action::VIEW => array('name' => ts('Report')));
     if (CRM_Core_Permission::check('view all contacts')) {
         $actionLinks[CRM_Core_Action::ADVANCED] = array('name' => ts('Advanced Search'), 'url' => 'civicrm/contact/search/advanced');
     }
     $action = array_sum(array_keys($actionLinks));
     $report['event_totals']['actionlinks'] = array();
     foreach (array('clicks', 'clicks_unique', 'queue', 'delivered', 'bounce', 'unsubscribe', 'forward', 'reply', 'opened', 'optout') as $key) {
         $url = 'mailing/detail';
         $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
         $searchFilter = "force=1&mailing_id=%%mid%%";
         switch ($key) {
             case 'delivered':
                 $reportFilter .= "&delivery_status_value=successful";
                 $searchFilter .= "&mailing_delivery_status=Y";
                 break;
             case 'bounce':
                 $url = "mailing/bounce";
                 $searchFilter .= "&mailing_delivery_status=N";
                 break;
             case 'forward':
                 $reportFilter .= "&is_forwarded_value=1";
                 $searchFilter .= "&mailing_forward=1";
                 break;
             case 'reply':
                 $reportFilter .= "&is_replied_value=1";
                 $searchFilter .= "&mailing_reply_status=Y";
                 break;
             case 'unsubscribe':
                 $reportFilter .= "&is_unsubscribed_value=1";
                 $searchFilter .= "&mailing_unsubscribe=1";
                 break;
             case 'optout':
                 $reportFilter .= "&is_optout_value=1";
                 $searchFilter .= "&mailing_optout=1";
                 break;
             case 'opened':
                 $url = "mailing/opened";
                 $searchFilter .= "&mailing_open_status=Y";
                 break;
             case 'clicks':
             case 'clicks_unique':
                 $url = "mailing/clicks";
                 $searchFilter .= "&mailing_click_status=Y";
                 break;
         }
         $actionLinks[CRM_Core_Action::VIEW]['url'] = CRM_Report_Utils_Report::getNextUrl($url, $reportFilter, FALSE, TRUE);
         if (array_key_exists(CRM_Core_Action::ADVANCED, $actionLinks)) {
             $actionLinks[CRM_Core_Action::ADVANCED]['qs'] = $searchFilter;
         }
         $report['event_totals']['actionlinks'][$key] = CRM_Core_Action::formLink($actionLinks, $action, array('mid' => $mailing_id), ts('more'), FALSE, 'mailing.report.action', 'Mailing', $mailing_id);
     }
     return $report;
 }
Exemplo n.º 19
0
 /**
  * Send a response email informing the contact of the groups to which he/she
  * has been resubscribed.
  *
  * @param string $queue_id
  *   The queue event ID.
  * @param array $groups
  *   List of group IDs.
  * @param bool $is_domain
  *   Is this domain-level?.
  * @param int $job
  *   The job ID.
  */
 public static function send_resub_response($queue_id, $groups, $is_domain = FALSE, $job)
 {
     // param is_domain is not supported as of now.
     $config = CRM_Core_Config::singleton();
     $domain = CRM_Core_BAO_Domain::getDomain();
     $jobTable = CRM_Mailing_BAO_MailingJob::getTableName();
     $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
     $contacts = CRM_Contact_DAO_Contact::getTableName();
     $email = CRM_Core_DAO_Email::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $dao = new CRM_Mailing_BAO_Mailing();
     $dao->query("   SELECT * FROM {$mailingTable}\n                        INNER JOIN {$jobTable} ON\n                            {$jobTable}.mailing_id = {$mailingTable}.id\n                        WHERE {$jobTable}.id = {$job}");
     $dao->fetch();
     $component = new CRM_Mailing_BAO_Component();
     $component->id = $dao->resubscribe_id;
     $component->find(TRUE);
     $html = $component->body_html;
     if ($component->body_text) {
         $text = $component->body_text;
     } else {
         $text = CRM_Utils_String::htmlToText($component->body_html);
     }
     $eq = new CRM_Core_DAO();
     $eq->query("SELECT     {$contacts}.preferred_mail_format as format,\n                    {$contacts}.id as contact_id,\n                    {$email}.email as email,\n                    {$queue}.hash as hash\n        FROM        {$contacts}\n        INNER JOIN  {$queue} ON {$queue}.contact_id = {$contacts}.id\n        INNER JOIN  {$email} ON {$queue}.email_id = {$email}.id\n        WHERE       {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer'));
     $eq->fetch();
     foreach ($groups as $key => $value) {
         if (!$value) {
             unset($groups[$key]);
         }
     }
     $message = new Mail_mime("\n");
     list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email);
     $bao = new CRM_Mailing_BAO_Mailing();
     $bao->body_text = $text;
     $bao->body_html = $html;
     $tokens = $bao->getTokens();
     if ($eq->format == 'HTML' || $eq->format == 'Both') {
         $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']);
         $html = CRM_Utils_Token::replaceResubscribeTokens($html, $domain, $groups, TRUE, $eq->contact_id, $eq->hash);
         $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, TRUE, $tokens['html']);
         $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, NULL, $tokens['html']);
         $message->setHTMLBody($html);
     }
     if (!$html || $eq->format == 'Text' || $eq->format == 'Both') {
         $text = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['text']);
         $text = CRM_Utils_Token::replaceResubscribeTokens($text, $domain, $groups, FALSE, $eq->contact_id, $eq->hash);
         $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, FALSE, $tokens['text']);
         $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, NULL, $tokens['text']);
         $message->setTxtBody($text);
     }
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}");
     CRM_Mailing_BAO_Mailing::addMessageIdHeader($headers, 'e', $job, $queue_id, $eq->hash);
     $b = CRM_Utils_Mail::setMimeParams($message);
     $h = $message->headers($headers);
     $mailer = \Civi::service('pear_mail');
     if (is_object($mailer)) {
         $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
         $mailer->send($eq->email, $h, $b);
         unset($errorScope);
     }
 }
Exemplo n.º 20
0
 /**
  * Get rows for the event browser
  *
  * @param int $mailing_id       ID of the mailing
  * @param int $job_id           optional ID of the job
  * @param boolean $is_distinct  Group by queue id?
  * @param int $offset           Offset
  * @param int $rowCount         Number of rows
  * @param array $sort           sort array
  * @return array                Result set
  * @access public
  * @static
  */
 public static function &getRows($mailing_id, $job_id = null, $is_distinct = false, $offset = null, $rowCount = null, $sort = null)
 {
     $dao =& new CRM_Core_Dao();
     $forward = self::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $query = "\n            SELECT      {$contact}.display_name as from_name,\n                        {$contact}.id as from_id,\n                        {$email}.email as from_email,\n                        dest_contact.id as dest_id,\n                        dest_email.email as dest_email,\n                        {$forward}.time_stamp as date\n            FROM        {$contact}\n            INNER JOIN  {$queue}\n                    ON  {$queue}.contact_id = {$contact}.id\n            INNER JOIN  {$email}\n                    ON  {$queue}.email_id = {$email}.id\n            INNER JOIN  {$forward}\n                    ON  {$forward}.event_queue_id = {$queue}.id\n            INNER JOIN  {$queue} as dest_queue\n                    ON  {$forward}.dest_queue_id = dest_queue.id\n            INNER JOIN  {$contact} as dest_contact\n                    ON  dest_queue.contact_id = dest_contact.id\n            INNER JOIN  {$email} as dest_email\n                    ON  dest_queue.email_id = dest_email.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n                    AND {$job}.is_test = 0\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     $query .= " ORDER BY {$contact}.sort_name, {$forward}.time_stamp DESC ";
     if ($offset || $rowCount) {
         //Added "||$rowCount" to avoid displaying all records on first page
         $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
     }
     $dao->query($query);
     $results = array();
     while ($dao->fetch()) {
         $from_url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->from_id}");
         $dest_url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->dest_id}");
         $results[] = array('from_name' => "<a href=\"{$from_url}\">{$dao->from_name}</a>", 'from_email' => $dao->from_email, 'dest_email' => "<a href=\"{$dest_url}\">{$dao->dest_email}</a>", 'date' => CRM_Utils_Date::customFormat($dao->date));
     }
     return $results;
 }
Exemplo n.º 21
0
 /**
  * returns all the rows in the given offset and rowCount
  *
  * @param enum   $action   the action being performed
  * @param int    $offset   the row number to start from
  * @param int    $rowCount the number of rows to return
  * @param string $sort     the sql string that describes the sort order
  * @param enum   $output   what should the result set include (web/email/csv)
  *
  * @return int   the total number of rows for this action
  */
 function &getRows($action, $offset, $rowCount, $sort, $output = null)
 {
     switch ($this->_event_type) {
         case 'queue':
             require_once 'CRM/Mailing/Event/BAO/Queue.php';
             return CRM_Mailing_Event_BAO_Queue::getRows($this->_mailing_id, $this->_job_id, $offset, $rowCount, $sort);
             break;
         case 'delivered':
             require_once 'CRM/Mailing/Event/BAO/Delivered.php';
             return CRM_Mailing_Event_BAO_Delivered::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
             break;
         case 'opened':
             require_once 'CRM/Mailing/Event/BAO/Opened.php';
             return CRM_Mailing_Event_BAO_Opened::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
             break;
         case 'bounce':
             require_once 'CRM/Mailing/Event/BAO/Bounce.php';
             return CRM_Mailing_Event_BAO_Bounce::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
             break;
         case 'forward':
             require_once 'CRM/Mailing/Event/BAO/Forward.php';
             return CRM_Mailing_Event_BAO_Forward::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
         case 'reply':
             require_once 'CRM/Mailing/Event/BAO/Reply.php';
             return CRM_Mailing_Event_BAO_Reply::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
             break;
         case 'unsubscribe':
             require_once 'CRM/Mailing/Event/BAO/Unsubscribe.php';
             return CRM_Mailing_Event_BAO_Unsubscribe::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $offset, $rowCount, $sort);
             break;
         case 'click':
             require_once 'CRM/Mailing/Event/BAO/TrackableURLOpen.php';
             return CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($this->_mailing_id, $this->_job_id, $this->_is_distinct, $this->_url_id, $offset, $rowCount, $sort);
             break;
         default:
             return null;
     }
 }
Exemplo n.º 22
0
 /**
  * Get rows for the event browser
  *
  * @param int $mailing_id       ID of the mailing
  * @param int $job_id           optional ID of the job
  * @param boolean $is_distinct  Group by queue id?
  * @param int $offset           Offset
  * @param int $rowCount         Number of rows
  * @param array $sort           sort array
  * @return array                Result set
  * @access public
  * @static
  */
 public static function &getRows($mailing_id, $job_id = null, $is_distinct = false, $offset = null, $rowCount = null, $sort = null)
 {
     $dao =& new CRM_Core_Dao();
     $unsub = self::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $query = "\n            SELECT      {$contact}.display_name as display_name,\n                        {$contact}.id as contact_id,\n                        {$email}.email as email,\n                        {$unsub}.time_stamp as date,\n                        {$unsub}.org_unsubscribe as org_unsubscribe\n            FROM        {$contact}\n            INNER JOIN  {$queue}\n                    ON  {$queue}.contact_id = {$contact}.id\n            INNER JOIN  {$email}\n                    ON  {$queue}.email_id = {$email}.id\n            INNER JOIN  {$unsub}\n                    ON  {$unsub}.event_queue_id = {$queue}.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n                    AND {$job}.is_test = 0\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     $query .= " ORDER BY {$contact}.sort_name, {$unsub}.time_stamp DESC ";
     if ($offset) {
         $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
     }
     $dao->query($query);
     $results = array();
     while ($dao->fetch()) {
         $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->contact_id}");
         $results[] = array('name' => "<a href=\"{$url}\">{$dao->display_name}</a>", 'email' => $dao->email, 'org' => $dao->org_unsubscribe ? ts('Yes') : ts('No'), 'date' => CRM_Utils_Date::customFormat($dao->date));
     }
     return $results;
 }
Exemplo n.º 23
0
 /**
  * Send a reponse email informing the contact of the groups to which he/she
  * has been resubscribed.
  *
  * @param string $queue_id      The queue event ID
  * @param array $groups         List of group IDs
  * @param bool $is_domain       Is this domain-level?
  * @param int $job              The job ID
  * @return void
  * @access public
  * @static
  */
 public static function send_resub_response($queue_id, $groups, $is_domain = false, $job)
 {
     // param is_domain is not supported as of now.
     $config = CRM_Core_Config::singleton();
     $domain =& CRM_Core_BAO_Domain::getDomain();
     $jobTable = CRM_Mailing_BAO_Job::getTableName();
     $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
     $contacts = CRM_Contact_DAO_Contact::getTableName();
     $email = CRM_Core_DAO_Email::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $dao = new CRM_Mailing_BAO_Mailing();
     $dao->query("   SELECT * FROM {$mailingTable} \n                        INNER JOIN {$jobTable} ON\n                            {$jobTable}.mailing_id = {$mailingTable}.id \n                        WHERE {$jobTable}.id = {$job}");
     $dao->fetch();
     $component = new CRM_Mailing_BAO_Component();
     $component->id = $dao->resubscribe_id;
     $component->find(true);
     $html = $component->body_html;
     if ($component->body_text) {
         $text = $component->body_text;
     } else {
         $text = CRM_Utils_String::htmlToText($component->body_html);
     }
     $eq = new CRM_Core_DAO();
     $eq->query("SELECT     {$contacts}.preferred_mail_format as format,\n                    {$contacts}.id as contact_id,\n                    {$email}.email as email,\n                    {$queue}.hash as hash\n        FROM        {$contacts}\n        INNER JOIN  {$queue} ON {$queue}.contact_id = {$contacts}.id\n        INNER JOIN  {$email} ON {$queue}.email_id = {$email}.id\n        WHERE       {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer'));
     $eq->fetch();
     foreach ($groups as $key => $value) {
         if (!$value) {
             unset($groups[$key]);
         }
     }
     $message = new Mail_mime("\n");
     list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email);
     $bao = new CRM_Mailing_BAO_Mailing();
     $bao->body_text = $text;
     $bao->body_html = $html;
     $tokens = $bao->getTokens();
     require_once 'CRM/Utils/Token.php';
     if ($eq->format == 'HTML' || $eq->format == 'Both') {
         $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']);
         $html = CRM_Utils_Token::replaceResubscribeTokens($html, $domain, $groups, true, $eq->contact_id, $eq->hash);
         $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, true, $tokens['html']);
         $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, null, $tokens['html']);
         $message->setHTMLBody($html);
     }
     if (!$html || $eq->format == 'Text' || $eq->format == 'Both') {
         $text = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['text']);
         $text = CRM_Utils_Token::replaceResubscribeTokens($text, $domain, $groups, false, $eq->contact_id, $eq->hash);
         $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, false, $tokens['text']);
         $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, null, $tokens['text']);
         $message->setTxtBody($text);
     }
     require_once 'CRM/Core/BAO/MailSettings.php';
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}");
     $b =& CRM_Utils_Mail::setMimeParams($message);
     $h =& $message->headers($headers);
     $mailer =& $config->getMailer();
     PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler'));
     if (is_object($mailer)) {
         $mailer->send($eq->email, $h, $b);
         CRM_Core_Error::setCallback();
     }
 }
Exemplo n.º 24
0
 /**
  * Form rule to send out a test mailing.
  *
  * @param aray $testParams
  * @param array $files
  *   Any files posted to the form.
  * @param array $self
  *   An current this object.
  *
  * @return bool
  *   true on successful SMTP handoff
  */
 public static function testMail($testParams, $files, $self)
 {
     $error = NULL;
     $urlString = 'civicrm/mailing/send';
     $urlParams = "_qf_Test_display=true&qfKey={$testParams['qfKey']}";
     $ssID = $self->get('ssID');
     if ($ssID && $self->_searchBasedMailing) {
         if ($self->_action == CRM_Core_Action::BASIC) {
             $fragment = 'search';
         } elseif ($self->_action == CRM_Core_Action::PROFILE) {
             $fragment = 'search/builder';
         } elseif ($self->_action == CRM_Core_Action::ADVANCED) {
             $fragment = 'search/advanced';
         } else {
             $fragment = 'search/custom';
         }
         $urlString = 'civicrm/contact/' . $fragment;
     }
     $emails = NULL;
     if (!empty($testParams['sendtest'])) {
         if (!($testParams['test_group'] || $testParams['test_email'])) {
             CRM_Core_Session::setStatus(ts('You did not provide an email address or select a group.'), ts('Test not sent.'), 'error');
             $error = TRUE;
         }
         if ($testParams['test_email']) {
             $emailAdd = explode(',', $testParams['test_email']);
             foreach ($emailAdd as $key => $value) {
                 $email = trim($value);
                 $testParams['emails'][] = $email;
                 $emails .= ($emails ? ',' : '') . "'" . CRM_Core_DAO::escapeString($email) . "'";
                 if (!CRM_Utils_Rule::email($email)) {
                     CRM_Core_Session::setStatus(ts('Please enter a valid email address.'), ts('Test not sent.'), 'error');
                     $error = TRUE;
                 }
             }
         }
         if ($error) {
             $url = CRM_Utils_System::url($urlString, $urlParams);
             CRM_Utils_System::redirect($url);
             return $error;
         }
     }
     if (!empty($testParams['_qf_Test_submit'])) {
         //when user perform mailing from search context
         //redirect it to search result CRM-3711.
         if ($ssID && $self->_searchBasedMailing) {
             $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             $status = ts("You can continue later by clicking the 'Continue' action to resume working on it.<br />From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL));
             //replace user context to search.
             $context = $self->get('context');
             if (!CRM_Contact_Form_Search::isSearchContext($context)) {
                 $context = 'search';
             }
             $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}&qfKey={$testParams['qfKey']}";
             $url = CRM_Utils_System::url($urlString, $urlParams);
         } else {
             $status = ts("Click the 'Continue' action to resume working on it.");
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
         }
         CRM_Core_Session::setStatus($status, ts('Mailing Saved'), 'success');
         CRM_Utils_System::redirect($url);
     }
     if (CRM_Mailing_Info::workflowEnabled()) {
         if (!CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings')) {
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             CRM_Utils_System::redirect($url);
         }
     }
     if (!empty($testParams['_qf_Test_next']) && $self->get('count') <= 0) {
         return array('_qf_default' => ts("You can not schedule or send this mailing because there are currently no recipients selected. Click 'Previous' to return to the Select Recipients step, OR click 'Save & Continue Later'."));
     }
     if (!empty($_POST['_qf_Import_refresh']) || !empty($testParams['_qf_Test_next']) || empty($testParams['sendtest'])) {
         $error = TRUE;
         return $error;
     }
     $job = new CRM_Mailing_BAO_MailingJob();
     $job->mailing_id = $self->get('mailing_id');
     $job->is_test = TRUE;
     $job->save();
     $newEmails = NULL;
     $session = CRM_Core_Session::singleton();
     if (!empty($testParams['emails'])) {
         $query = "\nSELECT     e.id, e.contact_id, e.email\nFROM       civicrm_email e\nINNER JOIN civicrm_contact c ON e.contact_id = c.id\nWHERE      e.email IN ({$emails})\nAND        e.on_hold = 0\nAND        c.is_opt_out = 0\nAND        c.do_not_email = 0\nAND        c.is_deleted = 0\nAND        c.is_deceased = 0\nGROUP BY   e.id\nORDER BY   e.is_bulkmail DESC, e.is_primary DESC\n";
         $dao = CRM_Core_DAO::executeQuery($query);
         $emailDetail = array();
         // fetch contact_id and email id for all existing emails
         while ($dao->fetch()) {
             $emailDetail[$dao->email] = array('contact_id' => $dao->contact_id, 'email_id' => $dao->id);
         }
         $dao->free();
         foreach ($testParams['emails'] as $key => $email) {
             // Email addresses are forced to lower case when saved, so ensure
             // we have the same case when comparing.
             $email = trim(strtolower($email));
             $contactId = $emailId = NULL;
             if (array_key_exists($email, $emailDetail)) {
                 $emailId = $emailDetail[$email]['email_id'];
                 $contactId = $emailDetail[$email]['contact_id'];
             }
             if (!$contactId) {
                 //create new contact.
                 $params = array('contact_type' => 'Individual', 'email' => array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => 1)));
                 $contact = CRM_Contact_BAO_Contact::create($params);
                 $emailId = $contact->email[0]->id;
                 $contactId = $contact->id;
                 $contact->free();
             }
             $params = array('job_id' => $job->id, 'email_id' => $emailId, 'contact_id' => $contactId);
             CRM_Mailing_Event_BAO_Queue::create($params);
         }
     }
     $testParams['job_id'] = $job->id;
     $isComplete = FALSE;
     while (!$isComplete) {
         $isComplete = CRM_Mailing_BAO_MailingJob::runJobs($testParams);
     }
     if (!empty($testParams['sendtest'])) {
         $status = NULL;
         if (CRM_Mailing_Info::workflowEnabled()) {
             if (CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings') || CRM_Core_Permission::check('access CiviMail')) {
                 $status = ts("Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
             }
         } else {
             $status = ts("Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
         }
         if ($status) {
             CRM_Core_Session::setStatus($status, ts('Test message sent'), 'success');
         }
         $url = CRM_Utils_System::url($urlString, $urlParams);
         CRM_Utils_System::redirect($url);
     }
     $error = TRUE;
     return $error;
 }
Exemplo n.º 25
0
 /**
  * Get rows for the event browser.
  *
  * @param int $mailing_id
  *   ID of the mailing.
  * @param int $job_id
  *   Optional ID of the job.
  * @param bool $is_distinct
  *   Group by queue id?.
  * @param int $offset
  *   Offset.
  * @param int $rowCount
  *   Number of rows.
  * @param array $sort
  *   Sort array.
  *
  * @param null $org_unsubscribe
  * @return array
  *   Result set
  */
 public static function &getRows($mailing_id, $job_id = NULL, $is_distinct = FALSE, $offset = NULL, $rowCount = NULL, $sort = NULL, $org_unsubscribe = NULL)
 {
     $dao = new CRM_Core_Dao();
     $unsub = self::$_tableName;
     $queueObject = new CRM_Mailing_Event_BAO_Queue();
     $queue = $queueObject->getTableName();
     $mailingObject = new CRM_Mailing_BAO_Mailing();
     $mailing = $mailingObject->getTableName();
     $jobObject = new CRM_Mailing_BAO_MailingJob();
     $job = $jobObject->getTableName();
     $contactObject = new CRM_Contact_BAO_Contact();
     $contact = $contactObject->getTableName();
     $emailObject = new CRM_Core_BAO_Email();
     $email = $emailObject->getTableName();
     $query = "\n            SELECT      {$contact}.display_name as display_name,\n                        {$contact}.id as contact_id,\n                        {$email}.email as email,\n                        {$unsub}.time_stamp as date,\n                        {$unsub}.org_unsubscribe as org_unsubscribe\n            FROM        {$contact}\n            INNER JOIN  {$queue}\n                    ON  {$queue}.contact_id = {$contact}.id\n            INNER JOIN  {$email}\n                    ON  {$queue}.email_id = {$email}.id\n            INNER JOIN  {$unsub}\n                    ON  {$unsub}.event_queue_id = {$queue}.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n                    AND {$job}.is_test = 0\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($org_unsubscribe !== NULL) {
         $query .= " AND {$unsub}.org_unsubscribe = " . ($org_unsubscribe ? 0 : 1);
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     $orderBy = "sort_name ASC, {$unsub}.time_stamp DESC";
     if ($sort) {
         if (is_string($sort)) {
             $sort = CRM_Utils_Type::escape($sort, 'String');
             $orderBy = $sort;
         } else {
             $orderBy = trim($sort->orderBy());
         }
     }
     $query .= " ORDER BY {$orderBy} ";
     if ($offset || $rowCount) {
         //Added "||$rowCount" to avoid displaying all records on first page
         $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
     }
     $dao->query($query);
     $results = array();
     while ($dao->fetch()) {
         $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->contact_id}");
         $results[] = array('name' => "<a href=\"{$url}\">{$dao->display_name}</a>", 'email' => $dao->email, 'unsubOrOptout' => ts('Yes'), 'date' => CRM_Utils_Date::customFormat($dao->date));
     }
     return $results;
 }
Exemplo n.º 26
0
 /**
  * Get rows for the event browser
  *
  * @param int $mailing_id       ID of the mailing
  * @param int $job_id           optional ID of the job
  * @param boolean $is_distinct  Group by queue id?
  * @param int $offset           Offset
  * @param int $rowCount         Number of rows
  * @param array $sort           sort array
  *
  * @return array                Result set
  * @access public
  * @static
  */
 public static function &getRows($mailing_id, $job_id = NULL, $is_distinct = FALSE, $offset = NULL, $rowCount = NULL, $sort = NULL)
 {
     $dao = new CRM_Core_Dao();
     $bounce = self::getTableName();
     $bounceType = CRM_Mailing_DAO_BounceType::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_MailingJob::getTableName();
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $query = "\n            SELECT      {$contact}.display_name as display_name,\n                        {$contact}.id as contact_id,\n                        {$email}.email as email,\n                        {$bounce}.time_stamp as date,\n                        {$bounce}.bounce_reason as reason,\n                        {$bounceType}.name as bounce_type\n            FROM        {$contact}\n            INNER JOIN  {$queue}\n                    ON  {$queue}.contact_id = {$contact}.id\n            INNER JOIN  {$email}\n                    ON  {$queue}.email_id = {$email}.id\n            INNER JOIN  {$bounce}\n                    ON  {$bounce}.event_queue_id = {$queue}.id\n            LEFT JOIN   {$bounceType}\n                    ON  {$bounce}.bounce_type_id = {$bounceType}.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n                    AND {$job}.is_test = 0\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     $orderBy = "sort_name ASC, {$bounce}.time_stamp DESC";
     if ($sort) {
         if (is_string($sort)) {
             $sort = CRM_Utils_Type::escape($sort, 'String');
             $orderBy = $sort;
         } else {
             $orderBy = trim($sort->orderBy());
         }
     }
     $query .= " ORDER BY {$orderBy} ";
     if ($offset || $rowCount) {
         //Added "||$rowCount" to avoid displaying all records on first page
         $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
     }
     $dao->query($query);
     $results = array();
     while ($dao->fetch()) {
         $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->contact_id}");
         $results[] = array('name' => "<a href=\"{$url}\">{$dao->display_name}</a>", 'email' => $dao->email, 'type' => empty($dao->bounce_type) ? ts('Unknown') : $dao->bounce_type, 'reason' => $dao->reason, 'date' => CRM_Utils_Date::customFormat($dao->date));
     }
     return $results;
 }
Exemplo n.º 27
0
 public static function processMandrillCalls($reponse)
 {
     $events = array('open', 'click', 'hard_bounce', 'soft_bounce', 'spam', 'reject');
     $bounceType = array();
     //MTE-17
     $config = CRM_Core_Config::singleton();
     if (property_exists($config, 'civiVersion')) {
         $civiVersion = $config->civiVersion;
     } else {
         $civiVersion = CRM_Core_BAO_Domain::version();
     }
     if (version_compare('4.4alpha1', $civiVersion) > 0) {
         $jobCLassName = 'CRM_Mailing_DAO_Job';
     } else {
         $jobCLassName = 'CRM_Mailing_DAO_MailingJob';
     }
     foreach ($reponse as $value) {
         //changes done to check if email exists in response array
         if (in_array($value['event'], $events) && CRM_Utils_Array::value('email', $value['msg'])) {
             $metaData = CRM_Utils_Array::value('metadata', $value['msg']) ? CRM_Utils_Array::value('CiviCRM_Mandrill_id', $value['msg']['metadata']) : NULL;
             $header = self::extractHeader($metaData);
             $mail = self::getMailing($header, $jobCLassName);
             $contacts = array();
             if ($mail->find(TRUE)) {
                 if ($value['event'] == 'click' && $mail->url_tracking === FALSE || $value['event'] == 'open' && $mail->open_tracking === FALSE) {
                     continue;
                 }
                 $emails = self::retrieveEmailContactId($value['msg']['email']);
                 if (!CRM_Utils_Array::value('contact_id', $emails['email'])) {
                     continue;
                 }
                 $value['mailing_id'] = $mail->id;
                 // IF no activity id in header then create new activity
                 if (empty($header[0])) {
                     self::createActivity($value, NULL, $header);
                 }
                 if (empty($header[2])) {
                     $params = array('job_id' => CRM_Core_DAO::getFieldValue($jobCLassName, $mail->id, 'id', 'mailing_id'), 'contact_id' => $emails['email']['contact_id'], 'email_id' => $emails['email']['id']);
                     $eventQueue = CRM_Mailing_Event_BAO_Queue::create($params);
                     $eventQueueID = $eventQueue->id;
                     $hash = $eventQueue->hash;
                     $jobId = $params['job_id'];
                 } else {
                     $eventQueueID = $header[3];
                     $hash = explode('@', $header[4]);
                     $hash = $hash[0];
                     $jobId = $header[2];
                 }
                 if ($eventQueueID) {
                     $mandrillActivtyParams = array('mailing_queue_id' => $eventQueueID, 'activity_id' => $header[0]);
                     CRM_Mte_BAO_MandrillActivity::create($mandrillActivtyParams);
                 }
                 $msgBody = '';
                 if (!empty($header[0])) {
                     $msgBody = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $header[0], 'details');
                 }
                 $value['mail_body'] = $msgBody;
                 $bType = ucfirst(preg_replace('/_\\w+/', '', $value['event']));
                 $assignedContacts = array();
                 switch ($value['event']) {
                     case 'open':
                         $oe = new CRM_Mailing_Event_BAO_Opened();
                         $oe->event_queue_id = $eventQueueID;
                         $oe->time_stamp = date('YmdHis', $value['ts']);
                         $oe->save();
                         break;
                     case 'click':
                         if (CRM_Utils_Array::value(1, $header) == 'b') {
                             break;
                         }
                         $tracker = new CRM_Mailing_BAO_TrackableURL();
                         $tracker->url = $value['url'];
                         $tracker->mailing_id = $mail->id;
                         if (!$tracker->find(TRUE)) {
                             $tracker->save();
                         }
                         $open = new CRM_Mailing_Event_BAO_TrackableURLOpen();
                         $open->event_queue_id = $eventQueueID;
                         $open->trackable_url_id = $tracker->id;
                         $open->time_stamp = date('YmdHis', $value['ts']);
                         $open->save();
                         break;
                     case 'hard_bounce':
                     case 'soft_bounce':
                     case 'spam':
                     case 'reject':
                         if (empty($bounceType)) {
                             CRM_Core_PseudoConstant::populate($bounceType, 'CRM_Mailing_DAO_BounceType', TRUE, 'id', NULL, NULL, NULL, 'name');
                         }
                         //Delete queue in delivered since this email is not successfull
                         $delivered = new CRM_Mailing_Event_BAO_Delivered();
                         $delivered->event_queue_id = $eventQueueID;
                         if ($delivered->find(TRUE)) {
                             $delivered->delete();
                         }
                         $bounceParams = array('time_stamp' => date('YmdHis', $value['ts']), 'event_queue_id' => $eventQueueID, 'bounce_type_id' => $bounceType["Mandrill {$bType}"], 'job_id' => $jobId, 'hash' => $hash);
                         $bounceParams['bounce_reason'] = CRM_Utils_Array::value('bounce_description', $value['msg']);
                         if (empty($bounceParams['bounce_reason'])) {
                             $bounceParams['bounce_reason'] = CRM_Core_DAO::getFieldValue('CRM_Mailing_DAO_BounceType', $bounceType["Mandrill {$bType}"], 'description');
                         }
                         CRM_Mailing_Event_BAO_Bounce::create($bounceParams);
                         if (substr($value['event'], -7) == '_bounce') {
                             $mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mandrill_smtp_settings');
                             if (CRM_Utils_Array::value('group_id', $mailingBackend)) {
                                 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
                                 $mailBody = ts('The following email failed to be delivered due to a') . " {$bType} Bounce :</br>\nTo: {$value['msg']['email']} </br>\nFrom: {$value['msg']['sender']} </br>\nSubject: {$value['msg']['subject']}</br>\nMessage Body: {$msgBody}";
                                 $mailParams = array('groupName' => 'Mandrill bounce notification', 'from' => '"' . $domainEmailName . '" <' . $domainEmailAddress . '>', 'subject' => ts('Mandrill Bounce Notification'), 'text' => $mailBody, 'html' => $mailBody);
                                 $query = "SELECT ce.email, cc.sort_name, cgc.contact_id FROM civicrm_contact cc\nINNER JOIN civicrm_group_contact cgc ON cgc.contact_id = cc.id\nINNER JOIN civicrm_email ce ON ce.contact_id = cc.id\nWHERE cc.is_deleted = 0 AND cc.is_deceased = 0 AND cgc.group_id = {$mailingBackend['group_id']} AND ce.is_primary = 1 AND ce.email <> %1";
                                 $queryParam = array(1 => array($value['msg']['email'], 'String'));
                                 $dao = CRM_Core_DAO::executeQuery($query, $queryParam);
                                 while ($dao->fetch()) {
                                     $mailParams['toName'] = $dao->sort_name;
                                     $mailParams['toEmail'] = $dao->email;
                                     CRM_Utils_Mail::send($mailParams);
                                     $value['assignee_contact_id'][] = $dao->contact_id;
                                 }
                             }
                         }
                         $bType = 'Bounce';
                         break;
                 }
                 // create activity for click and open event
                 if ($value['event'] == 'open' || $value['event'] == 'click' || $bType == 'Bounce') {
                     self::createActivity($value, $bType, $header);
                 }
             }
         }
     }
 }
Exemplo n.º 28
0
 /**
  * Run page.
  *
  * This includes assigning smarty variables and other page processing.
  *
  * @return string
  * @throws Exception
  */
 public function run()
 {
     $job_id = CRM_Utils_Request::retrieve('jid', 'Integer', CRM_Core_DAO::$_nullObject);
     $queue_id = CRM_Utils_Request::retrieve('qid', 'Integer', CRM_Core_DAO::$_nullObject);
     $hash = CRM_Utils_Request::retrieve('h', 'String', CRM_Core_DAO::$_nullObject);
     if (!$job_id || !$queue_id || !$hash) {
         CRM_Core_Error::fatal(ts("Missing input parameters"));
     }
     // verify that the three numbers above match
     $q = CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     if (!$q) {
         CRM_Core_Error::fatal(ts("There was an error in your request"));
     }
     $cancel = CRM_Utils_Request::retrieve("_qf_{$this->_type}_cancel", 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, $_REQUEST);
     if ($cancel) {
         $config = CRM_Core_Config::singleton();
         CRM_Utils_System::redirect($config->userFrameworkBaseURL);
     }
     $confirm = CRM_Utils_Request::retrieve('confirm', 'Boolean', CRM_Core_DAO::$_nullObject, FALSE, NULL, $_REQUEST);
     list($displayName, $email) = CRM_Mailing_Event_BAO_Queue::getContactInfo($queue_id);
     $this->assign('display_name', $displayName);
     $this->assign('email', $email);
     $this->assign('confirm', $confirm);
     $groups = CRM_Mailing_Event_BAO_Unsubscribe::unsub_from_mailing($job_id, $queue_id, $hash, TRUE);
     $this->assign('groups', $groups);
     $groupExist = NULL;
     foreach ($groups as $key => $value) {
         if ($value) {
             $groupExist = TRUE;
         }
     }
     $this->assign('groupExist', $groupExist);
     if ($confirm) {
         if ($this->_type == 'unsubscribe') {
             $groups = CRM_Mailing_Event_BAO_Unsubscribe::unsub_from_mailing($job_id, $queue_id, $hash);
             if (count($groups)) {
                 CRM_Mailing_Event_BAO_Unsubscribe::send_unsub_response($queue_id, $groups, FALSE, $job_id);
             } else {
                 // should we indicate an error, or just ignore?
             }
         } elseif ($this->_type == 'resubscribe') {
             $groups = CRM_Mailing_Event_BAO_Resubscribe::resub_to_mailing($job_id, $queue_id, $hash);
             if (count($groups)) {
                 CRM_Mailing_Event_BAO_Resubscribe::send_resub_response($queue_id, $groups, FALSE, $job_id);
             } else {
                 // should we indicate an error, or just ignore?
             }
         } else {
             if (CRM_Mailing_Event_BAO_Unsubscribe::unsub_from_domain($job_id, $queue_id, $hash)) {
                 CRM_Mailing_Event_BAO_Unsubscribe::send_unsub_response($queue_id, NULL, TRUE, $job_id);
             } else {
                 // should we indicate an error, or just ignore?
             }
         }
     } else {
         $confirmURL = CRM_Utils_System::url("civicrm/mailing/{$this->_type}", "reset=1&jid={$job_id}&qid={$queue_id}&h={$hash}&confirm=1");
         $this->assign('confirmURL', $confirmURL);
         // push context for further process CRM-4431
         $session = CRM_Core_Session::singleton();
         $session->pushUserContext($confirmURL);
     }
     return parent::run();
 }
Exemplo n.º 29
0
 /**
  * Helper function for Check contents in Activity.
  * @param $atype
  * @param $contactName
  *
  *  return string
  */
 public function _checkActivity($atype, $contactName, $subject, $withContact, $isHeader = TRUE, $mailingId = NULL)
 {
     $this->openCiviPage('activity/search', 'reset=1', '_qf_Search_refresh');
     $this->select('activity_type_id', "label={$atype}");
     $this->type('sort_name', $contactName);
     $this->clickLink('_qf_Search_refresh', 'Search');
     // View your Activity
     $this->clickLink("xpath=id('Search')/div[3]/div/div[2]/table/tbody/tr[2]/td[9]/span/a[text()='View']", "_qf_Activity_cancel", FALSE);
     $this->assertTrue($this->isTextPresent($atype));
     $expected = array(4 => $subject, 8 => 'Completed', 2 => $withContact, 10 => 'Urgent');
     foreach ($expected as $label => $value) {
         $this->verifyText("xpath=id('Activity')/div[2]/table[1]/tbody/tr[{$label}]/td[2]", preg_quote($value));
     }
     if (!$isHeader) {
         return FALSE;
     }
     $header = $this->urlArg('id', $this->getAttribute("xpath=id('Search')/div[3]/div/div[2]/table/tbody/tr[2]/td[9]/span/a[text()='View']@href"));
     if ($mailingId) {
         $cid = $this->urlArg('cid', $this->getAttribute("xpath=id('Search')/div[3]/div/div[2]/table/tbody/tr[2]/td[9]/span/a[text()='View']@href"));
         $queueId = CRM_Core_DAO::singleValueQuery("SELECT ce.id FROM `civicrm_mailing_event_queue` ce\nINNER JOIN civicrm_mailing_job mj ON mj.id = ce.job_id and ce.contact_id = {$cid} AND mj.mailing_id = {$mailingId}");
     } else {
         $queueId = CRM_Core_DAO::singleValueQuery('SELECT mailing_queue_id FROM civicrm_mandrill_activity WHERE activity_id = ' . $header);
     }
     if ($queueId) {
         $queue = new CRM_Mailing_Event_BAO_Queue();
         $queue->id = $queueId;
         if ($queue->find(TRUE)) {
             $header = implode(CRM_Core_Config::singleton()->verpSeparator, array($header, 'm', $queue->job_id, $queue->id, $queue->hash));
         }
     }
     return $header;
 }