CRM-13746 - Enable delete hooks for Mailings
[civicrm-core.git] / CRM / Mailing / BAO / Mailing.php
index 5b07950c813a702e25f47b0d52117d15e3ca2007..f66947bc1fc5b3b3e6673400893399433bca812b 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 4.3                                                |
+ | CiviCRM version 4.4                                                |
  +--------------------------------------------------------------------+
  | Copyright CiviCRM LLC (c) 2004-2013                                |
  +--------------------------------------------------------------------+
@@ -111,7 +111,7 @@ class CRM_Mailing_BAO_Mailing extends CRM_Mailing_DAO_Mailing {
     $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
 
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
-    $job     = CRM_Mailing_BAO_Job::getTableName();
+    $job     = CRM_Mailing_BAO_MailingJob::getTableName();
     $mg      = CRM_Mailing_DAO_MailingGroup::getTableName();
     $eq      = CRM_Mailing_Event_DAO_Queue::getTableName();
     $ed      = CRM_Mailing_Event_DAO_Delivered::getTableName();
@@ -467,6 +467,9 @@ AND    $mg.mailing_id = {$mailing_id}
     $aclWhere = $aclWhere ? "WHERE {$aclWhere}" : '';
     $limitString = NULL;
     if ($limit && $offset !== NULL) {
+      $offset = CRM_Utils_Type::escape($offset, 'Int');
+      $limit = CRM_Utils_Type::escape($limit, 'Int');
+
       $limitString = "LIMIT $offset, $limit";
     }
 
@@ -519,7 +522,7 @@ ORDER BY   i.contact_id, i.{$tempColumn}
   private function _getMailingGroupIds($type = 'Include') {
     $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
     $group = CRM_Contact_DAO_Group::getTableName();
-    if (!isset($thi->sid)) {
+    if (!isset($this->id)) {
       // we're just testing tokens, so return any group
       $query = "SELECT   id AS entity_id
                       FROM     $group
@@ -1187,9 +1190,7 @@ ORDER BY   civicrm_email.is_bulkmail DESC
       )) {
       $textBody = join('', $text);
       if ($useSmarty) {
-        $smarty->security = TRUE;
-        $textBody         = $smarty->fetch("string:$textBody");
-        $smarty->security = FALSE;
+        $textBody = $smarty->fetch("string:$textBody");
       }
       $mailParams['text'] = $textBody;
     }
@@ -1199,9 +1200,7 @@ ORDER BY   civicrm_email.is_bulkmail DESC
         ))) {
       $htmlBody = join('', $html);
       if ($useSmarty) {
-        $smarty->security = TRUE;
-        $htmlBody         = $smarty->fetch("string:$htmlBody");
-        $smarty->security = FALSE;
+        $htmlBody = $smarty->fetch("string:$htmlBody");
       }
       $mailParams['html'] = $htmlBody;
     }
@@ -1603,7 +1602,7 @@ ORDER BY   civicrm_email.is_bulkmail DESC
      * CRM_Mailing_Form_Schedule::postProcess() or via API.
      */
     if (isset($params['approval_status_id']) && $params['approval_status_id']) {
-      $job = new CRM_Mailing_BAO_Job();
+      $job = new CRM_Mailing_BAO_MailingJob();
       $job->mailing_id = $mailing->id;
       $job->status = 'Scheduled';
       $job->is_test = 0;
@@ -1636,7 +1635,7 @@ ORDER BY   civicrm_email.is_bulkmail DESC
       'mailing' => self::getTableName(),
       'mailing_group' => CRM_Mailing_DAO_MailingGroup::getTableName(),
       'group' => CRM_Contact_BAO_Group::getTableName(),
-      'job' => CRM_Mailing_BAO_Job::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(),
@@ -1848,7 +1847,7 @@ ORDER BY   civicrm_email.is_bulkmail DESC
       $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_Job::fields()) as $field) {
+      foreach (array_keys(CRM_Mailing_BAO_MailingJob::fields()) as $field) {
         $row[$field] = $mailing->$field;
       }
 
@@ -2162,11 +2161,10 @@ ORDER BY   civicrm_email.is_bulkmail DESC
     $groups = CRM_Core_PseudoConstant::group(NULL, FALSE);
     if (!empty($groups)) {
       $groupIDs = implode(',', array_keys($groups));
-      $selectClause = ($count) ? 'COUNT( DISTINCT m.id) as count' : 'DISTINCT( m.id ) as id';
 
       // get all the mailings that are in this subset of groups
       $query = "
-SELECT    $selectClause
+SELECT    DISTINCT( m.id ) as id
   FROM    civicrm_mailing m
 LEFT JOIN civicrm_mailing_group g ON g.mailing_id   = m.id
  WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
@@ -2195,7 +2193,7 @@ LEFT JOIN civicrm_mailing_group g ON g.mailing_id   = m.id
    */
   public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
     $mailing = self::getTableName();
-    $job     = CRM_Mailing_BAO_Job::getTableName();
+    $job     = CRM_Mailing_BAO_MailingJob::getTableName();
     $group   = CRM_Mailing_DAO_MailingGroup::getTableName();
     $session = CRM_Core_Session::singleton();
 
@@ -2237,6 +2235,9 @@ LEFT JOIN civicrm_mailing_group g ON g.mailing_id   = m.id
     }
 
     if ($rowCount) {
+      $offset = CRM_Utils_Type::escape($offset, 'Int');
+      $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
+
       $query .= " LIMIT $offset, $rowCount ";
     }
 
@@ -2297,6 +2298,8 @@ LEFT JOIN civicrm_mailing_group g ON g.mailing_id   = m.id
       CRM_Core_Error::fatal();
     }
 
+    CRM_Utils_Hook::pre('delete', 'Mailing', $id, CRM_Core_DAO::$_nullArray);
+
     // delete all file attachments
     CRM_Core_BAO_File::deleteEntityFile('civicrm_mailing',
       $id
@@ -2307,6 +2310,8 @@ LEFT JOIN civicrm_mailing_group g ON g.mailing_id   = m.id
     $dao->delete();
 
     CRM_Core_Session::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
+
+    CRM_Utils_Hook::post('delete', 'Mailing', $id, $dao);
   }
 
   /**
@@ -2324,7 +2329,7 @@ LEFT JOIN civicrm_mailing_group g ON g.mailing_id   = m.id
       CRM_Core_Error::fatal();
     }
 
-    $dao = new CRM_Mailing_BAO_Job();
+    $dao = new CRM_Mailing_BAO_MailingJob();
     $dao->id = $id;
     $dao->delete();
   }
@@ -2419,7 +2424,7 @@ LEFT JOIN civicrm_mailing_group g ON g.mailing_id   = m.id
     );
 
 
-    $form->_templates = CRM_Core_BAO_MessageTemplates::getMessageTemplates(FALSE);
+    $form->_templates = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE);
     if (!empty($form->_templates)) {
       $form->assign('templates', TRUE);
       $form->add('select', 'template', ts('Use Template'),
@@ -2473,11 +2478,15 @@ LEFT JOIN civicrm_mailing_group g ON g.mailing_id   = m.id
     if (CRM_Utils_System::getClassName($form) == 'CRM_Mailing_Form_Upload') {
       $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens);
     }
-
+    //@todo move this fn onto the form
     if (CRM_Utils_System::getClassName($form) == 'CRM_Contribute_Form_Task_PDFLetter') {
       $tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens);
     }
 
+    if(method_exists($form, 'listTokens')) {
+      $tokens = array_merge($form->listTokens(), $tokens);
+    }
+
     //sorted in ascending order tokens by ignoring word case
     natcasesort($tokens);
 
@@ -2492,7 +2501,7 @@ LEFT JOIN civicrm_mailing_group g ON g.mailing_id   = m.id
       )
     );
 
-    $form->_templates = CRM_Core_BAO_MessageTemplates::getMessageTemplates(FALSE);
+    $form->_templates = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE);
     if (!empty($form->_templates)) {
       $form->assign('templates', TRUE);
       $form->add('select', 'template', ts('Select Template'),
@@ -2637,7 +2646,7 @@ WHERE  civicrm_mailing_job.id = %1
  //   CRM_Core_Error::debug_log_message("Beginning processQueue run: {$config->mailerJobsMax}, {$config->mailerJobSize}");
 
     if ($mode == NULL && CRM_Core_BAO_MailSettings::defaultDomain() == "EXAMPLE.ORG") {
-      CRM_Core_Error::fatal(ts('The <a href="%1">default mailbox</a> has not been configured. You will find <a href="%2">more info in the online user and administrator guide</a>', array(1 => CRM_Utils_System::url('civicrm/admin/mailSettings', 'reset=1'), 2 => "http://book.civicrm.org/user/initial-set-up/email-system-configuration")));
+      CRM_Core_Error::fatal(ts('The <a href="%1">default mailbox</a> has not been configured. You will find <a href="%2">more info in the online user and administrator guide</a>', array(1 => CRM_Utils_System::url('civicrm/admin/mailSettings', 'reset=1'), 2 => "http://book.civicrm.org/user/advanced-configuration/email-system-configuration/")));
     }
 
     // check if we are enforcing number of parallel cron jobs
@@ -2671,9 +2680,9 @@ WHERE  civicrm_mailing_job.id = %1
     // load bootstrap to call hooks
 
     // Split up the parent jobs into multiple child jobs
-    CRM_Mailing_BAO_Job::runJobs_pre($config->mailerJobSize, $mode);
-    CRM_Mailing_BAO_Job::runJobs(NULL, $mode);
-    CRM_Mailing_BAO_Job::runJobs_post($mode);
+    CRM_Mailing_BAO_MailingJob::runJobs_pre($config->mailerJobSize, $mode);
+    CRM_Mailing_BAO_MailingJob::runJobs(NULL, $mode);
+    CRM_Mailing_BAO_MailingJob::runJobs_post($mode);
 
     // lets release the global cron lock if we do have one
     if ($gotCronLock) {
@@ -2684,7 +2693,7 @@ WHERE  civicrm_mailing_job.id = %1
     return TRUE;
   }
 
-  private function addMultipleEmails($mailingID) {
+  private static function addMultipleEmails($mailingID) {
     $sql = "
 INSERT INTO civicrm_mailing_recipients
     (mailing_id, email_id, contact_id)
@@ -2761,6 +2770,12 @@ AND        m.id = %1
     // add total
     $params['total'] = CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
 
+    //CRM-12814
+    if (!empty($mailings)) {
+      $openCounts = CRM_Mailing_Event_BAO_Opened::getMailingTotalCount(array_keys($mailings));
+      $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen::getMailingTotalCount(array_keys($mailings));
+    }
+
     // format params and add links
     $contactMailings = array();
     foreach ($mailings as $mailingId => $values) {
@@ -2768,25 +2783,21 @@ AND        m.id = %1
       $contactMailings[$mailingId]['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
       $contactMailings[$mailingId]['recipients'] = CRM_Utils_System::href(ts('(recipients)'), 'civicrm/mailing/report/event',
         "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
+
       $contactMailings[$mailingId]['mailing_creator'] = CRM_Utils_System::href(
-          $values['creator_name'],
-          'civicrm/contact/view',
-          "reset=1&cid={$values['creator_id']}");
-
-      $contactMailings[$mailingId]['openstats'] = "Opens: ".
-        count(CRM_Mailing_Event_BAO_Opened::getRows(
-            $values['mailing_id'], NULL, FALSE, NULL, NULL, NULL, $values['creator_id']
-          )
-        )."<br />Clicks:" .
-        count(CRM_Mailing_Event_BAO_TrackableURLOpen::getRows(
-          $values['mailing_id'], NULL, FALSE, NULL, NULL, NULL, NULL, $values['creator_id']
-        ) );
+        $values['creator_name'],
+        'civicrm/contact/view',
+        "reset=1&cid={$values['creator_id']}");
+
+      //CRM-12814
+      $contactMailings[$mailingId]['openstats'] = ts('Opens') . ': ' . $openCounts[$values['mailing_id']] .
+        '<br />' . ts('Clicks') . ': ' . $clickCounts[$values['mailing_id']];
 
       $actionLinks = array(
         CRM_Core_Action::VIEW => array(
-          'name'  => ts('View'),
-          'url'   => 'civicrm/mailing/view',
-          'qs'    => "reset=1&id={$values['mailing_id']}",
+          'name' => ts('View'),
+          'url' => 'civicrm/mailing/view',
+          'qs' => "reset=1&id={$values['mailing_id']}",
           'title' => ts('View Mailing'),
           'class' => 'crm-mailing-view',
         ),
@@ -2836,9 +2847,7 @@ AND        m.id = %1
    */
   static public function getContactMailingsCount(&$params) {
     $params['version'] = 3;
-
-    $result = civicrm_api('MailingContact', 'getcount', $params);
-    return $result['values']['count'];
+    return civicrm_api('MailingContact', 'getcount', $params);
   }
 }