Merge pull request #14250 from totten/master-select-null
[civicrm-core.git] / CRM / Core / BAO / ActionSchedule.php
index fe30d41619a2dbc400cee9693fb354925896f7cb..abc90a1cfb313222848d392c32c88a5292adce07 100644 (file)
@@ -58,9 +58,9 @@ class CRM_Core_BAO_ActionSchedule extends CRM_Core_DAO_ActionSchedule {
       return $_action_mapping;
     }
     elseif (isset($filters['id'])) {
-      return array(
+      return [
         $filters['id'] => $_action_mapping[$filters['id']],
-      );
+      ];
     }
     else {
       throw new CRM_Core_Exception("getMappings() called with unsupported filter: " . implode(', ', array_keys($filters)));
@@ -84,11 +84,11 @@ class CRM_Core_BAO_ActionSchedule extends CRM_Core_DAO_ActionSchedule {
    * @throws CRM_Core_Exception
    */
   public static function getAllEntityValueLabels() {
-    $entityValueLabels = array();
+    $entityValueLabels = [];
     foreach (CRM_Core_BAO_ActionSchedule::getMappings() as $mapping) {
       /** @var \Civi\ActionSchedule\Mapping $mapping */
       $entityValueLabels[$mapping->getId()] = $mapping->getValueLabels();
-      $valueLabel = array('- ' . strtolower($mapping->getValueHeader()) . ' -');
+      $valueLabel = ['- ' . strtolower($mapping->getValueHeader()) . ' -'];
       $entityValueLabels[$mapping->getId()] = $valueLabel + $entityValueLabels[$mapping->getId()];
     }
     return $entityValueLabels;
@@ -102,10 +102,10 @@ class CRM_Core_BAO_ActionSchedule extends CRM_Core_DAO_ActionSchedule {
    */
   public static function getAllEntityStatusLabels() {
     $entityValueLabels = self::getAllEntityValueLabels();
-    $entityStatusLabels = array();
+    $entityStatusLabels = [];
     foreach (CRM_Core_BAO_ActionSchedule::getMappings() as $mapping) {
       /** @var \Civi\ActionSchedule\Mapping $mapping */
-      $statusLabel = array('- ' . strtolower($mapping->getStatusHeader()) . ' -');
+      $statusLabel = ['- ' . strtolower($mapping->getStatusHeader()) . ' -'];
       $entityStatusLabels[$mapping->getId()] = $entityValueLabels[$mapping->getId()];
       foreach ($entityStatusLabels[$mapping->getId()] as $kkey => & $vval) {
         $vval = $statusLabel + $mapping->getStatusLabels($kkey);
@@ -120,13 +120,14 @@ class CRM_Core_BAO_ActionSchedule extends CRM_Core_DAO_ActionSchedule {
    * @param bool $namesOnly
    *   Return simple list of names.
    *
-   * @param \Civi\ActionSchedule\Mapping|NULL $filterMapping
+   * @param \Civi\ActionSchedule\Mapping|null $filterMapping
    *   Filter by the schedule's mapping type.
    * @param int $filterValue
    *   Filter by the schedule's entity_value.
    *
    * @return array
    *   (reference)   reminder list
+   * @throws \CRM_Core_Exception
    */
   public static function &getList($namesOnly = FALSE, $filterMapping = NULL, $filterValue = NULL) {
     $query = "
@@ -146,21 +147,21 @@ SELECT
 
 FROM civicrm_action_schedule cas
 ";
-    $queryParams = array();
+    $queryParams = [];
     $where = " WHERE 1 ";
     if ($filterMapping and $filterValue) {
       $where .= " AND cas.entity_value = %1 AND cas.mapping_id = %2";
-      $queryParams[1] = array($filterValue, 'Integer');
-      $queryParams[2] = array($filterMapping->getId(), 'String');
+      $queryParams[1] = [$filterValue, 'Integer'];
+      $queryParams[2] = [$filterMapping->getId(), 'String'];
     }
     $where .= " AND cas.used_for IS NULL";
     $query .= $where;
     $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
     while ($dao->fetch()) {
       /** @var Civi\ActionSchedule\Mapping $filterMapping */
-      $filterMapping = CRM_Utils_Array::first(self::getMappings(array(
+      $filterMapping = CRM_Utils_Array::first(self::getMappings([
         'id' => $dao->mapping_id,
-      )));
+      ]));
       $list[$dao->id]['id'] = $dao->id;
       $list[$dao->id]['title'] = $dao->title;
       $list[$dao->id]['start_action_offset'] = $dao->start_action_offset;
@@ -194,7 +195,7 @@ FROM civicrm_action_schedule cas
    *
    * @return CRM_Core_DAO_ActionSchedule
    */
-  public static function add(&$params, $ids = array()) {
+  public static function add(&$params, $ids = []) {
     $actionSchedule = new CRM_Core_DAO_ActionSchedule();
     $actionSchedule->copyValues($params);
 
@@ -273,9 +274,9 @@ FROM civicrm_action_schedule cas
    * @throws CRM_Core_Exception
    */
   public static function sendMailings($mappingID, $now) {
-    $mapping = CRM_Utils_Array::first(self::getMappings(array(
+    $mapping = CRM_Utils_Array::first(self::getMappings([
       'id' => $mappingID,
-    )));
+    ]));
 
     $actionSchedule = new CRM_Core_DAO_ActionSchedule();
     $actionSchedule->mapping_id = $mappingID;
@@ -285,7 +286,7 @@ FROM civicrm_action_schedule cas
     while ($actionSchedule->fetch()) {
       $query = CRM_Core_BAO_ActionSchedule::prepareMailingQuery($mapping, $actionSchedule);
       $dao = CRM_Core_DAO::executeQuery($query,
-        array(1 => array($actionSchedule->id, 'Integer'))
+        [1 => [$actionSchedule->id, 'Integer']]
       );
 
       $multilingual = CRM_Core_I18n::isMultilingual();
@@ -296,7 +297,7 @@ FROM civicrm_action_schedule cas
           CRM_Core_BAO_ActionSchedule::setCommunicationLanguage($actionSchedule->communication_language, $preferred_language);
         }
 
-        $errors = array();
+        $errors = [];
         try {
           $tokenProcessor = self::createTokenProcessor($actionSchedule, $mapping);
           $tokenProcessor->addRow()
@@ -322,16 +323,15 @@ FROM civicrm_action_schedule cas
         }
 
         // update action log record
-        $logParams = array(
+        $logParams = [
           'id' => $dao->reminderID,
           'is_error' => !empty($errors),
           'message' => empty($errors) ? "null" : implode(' ', $errors),
           'action_date_time' => $now,
-        );
+        ];
         CRM_Core_BAO_ActionLog::create($logParams);
       }
 
-      $dao->free();
     }
   }
 
@@ -342,7 +342,7 @@ FROM civicrm_action_schedule cas
    *
    * @throws API_Exception
    */
-  public static function buildRecipientContacts($mappingID, $now, $params = array()) {
+  public static function buildRecipientContacts($mappingID, $now, $params = []) {
     $actionSchedule = new CRM_Core_DAO_ActionSchedule();
     $actionSchedule->mapping_id = $mappingID;
     $actionSchedule->is_active = 1;
@@ -353,9 +353,9 @@ FROM civicrm_action_schedule cas
 
     while ($actionSchedule->fetch()) {
       /** @var \Civi\ActionSchedule\Mapping $mapping */
-      $mapping = CRM_Utils_Array::first(self::getMappings(array(
+      $mapping = CRM_Utils_Array::first(self::getMappings([
         'id' => $mappingID,
-      )));
+      ]));
       $builder = new \Civi\ActionSchedule\RecipientBuilder($now, $actionSchedule, $mapping);
       $builder->build();
     }
@@ -367,7 +367,7 @@ FROM civicrm_action_schedule cas
    *
    * @return array
    */
-  public static function processQueue($now = NULL, $params = array()) {
+  public static function processQueue($now = NULL, $params = []) {
     $now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
 
     $mappings = CRM_Core_BAO_ActionSchedule::getMappings();
@@ -376,10 +376,10 @@ FROM civicrm_action_schedule cas
       CRM_Core_BAO_ActionSchedule::sendMailings($mappingID, $now);
     }
 
-    $result = array(
+    $result = [
       'is_error' => 0,
       'messages' => ts('Sent all scheduled reminders successfully'),
-    );
+    ];
     return $result;
   }
 
@@ -394,10 +394,10 @@ FROM civicrm_action_schedule cas
                         WHERE  mapping_id = %1 AND
                                entity_value = %2";
 
-    $params = array(
-      1 => array($mappingID, 'String'),
-      2 => array($id, 'Integer'),
-    );
+    $params = [
+      1 => [$mappingID, 'String'],
+      2 => [$id, 'Integer'],
+    ];
     return CRM_Core_DAO::singleValueQuery($queryString, $params);
   }
 
@@ -409,13 +409,13 @@ FROM civicrm_action_schedule cas
    */
   public static function getRecipientListing($mappingID, $recipientType) {
     if (!$mappingID) {
-      return array();
+      return [];
     }
 
     /** @var \Civi\ActionSchedule\Mapping $mapping */
-    $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+    $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
       'id' => $mappingID,
-    )));
+    ]));
     return $mapping->getRecipientListing($recipientType);
   }
 
@@ -458,7 +458,7 @@ FROM civicrm_action_schedule cas
    * @param Civi\ActionSchedule\Mapping $mapping
    * @param int $contactID
    * @param int $entityID
-   * @param int|NULL $caseID
+   * @param int|null $caseID
    * @throws CRM_Core_Exception
    */
   protected static function createMailingActivity($tokenRow, $mapping, $contactID, $entityID, $caseID) {
@@ -475,7 +475,7 @@ FROM civicrm_action_schedule cas
         = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Reminder Sent');
     }
 
-    $activityParams = array(
+    $activityParams = [
       'subject' => $tokenRow->render('subject'),
       'details' => $tokenRow->render('body_html'),
       'source_contact_id' => $session->get('userID') ? $session->get('userID') : $contactID,
@@ -486,13 +486,13 @@ FROM civicrm_action_schedule cas
       'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
       'activity_type_id' => $activityTypeID,
       'source_record_id' => $entityID,
-    );
+    ];
     // @todo use api, remove all the above wrangling
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
 
     //file reminder on case if source activity is a case activity
     if (!empty($caseID)) {
-      $caseActivityParams = array();
+      $caseActivityParams = [];
       $caseActivityParams['case_id'] = $caseID;
       $caseActivityParams['activity_id'] = $activity->id;
       CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
@@ -511,13 +511,13 @@ FROM civicrm_action_schedule cas
       ->select("e.id as entityID, e.*")
       ->where("reminder.action_schedule_id = #casActionScheduleId")
       ->where("reminder.action_date_time IS NULL")
-      ->param(array(
+      ->param([
         'casActionScheduleId' => $actionSchedule->id,
         'casMailingJoinType' => ($actionSchedule->limit_to == 0) ? 'LEFT JOIN' : 'INNER JOIN',
         'casMappingId' => $mapping->getId(),
         'casMappingEntity' => $mapping->getEntity(),
         'casEntityJoinExpr' => 'e.id = reminder.entity_id',
-      ));
+      ]);
 
     if ($actionSchedule->limit_to == 0) {
       $select->where("e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact'");
@@ -543,7 +543,13 @@ FROM civicrm_action_schedule cas
   protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
     $toPhoneNumber = self::pickSmsPhoneNumber($toContactID);
     if (!$toPhoneNumber) {
-      return array("sms_phone_missing" => "Couldn't find recipient's phone number.");
+      return ["sms_phone_missing" => "Couldn't find recipient's phone number."];
+    }
+
+    // dev/core#369 If an SMS provider is deleted then the relevant row in the action_schedule_table is set to NULL
+    // So we need to exclude them.
+    if (CRM_Utils_System::isNull($schedule->sms_provider_id)) {
+      return ["sms_provider_missing" => "SMS reminder cannot be sent because the SMS provider has been deleted."];
     }
 
     $messageSubject = $tokenRow->render('subject');
@@ -551,20 +557,20 @@ FROM civicrm_action_schedule cas
 
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID') ? $session->get('userID') : $tokenRow->context['contactId'];
-    $smsParams = array(
+    $smsParams = [
       'To' => $toPhoneNumber,
       'provider_id' => $schedule->sms_provider_id,
       'activity_subject' => $messageSubject,
-    );
+    ];
     $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
-    $activityParams = array(
+    $activityParams = [
       'source_contact_id' => $userID,
       'activity_type_id' => $activityTypeID,
       'activity_date_time' => date('YmdHis'),
       'subject' => $messageSubject,
       'details' => $sms_body_text,
       'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
-    );
+    ];
 
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
 
@@ -575,7 +581,7 @@ FROM civicrm_action_schedule cas
       $userID
     );
 
-    return array();
+    return [];
   }
 
   /**
@@ -603,7 +609,7 @@ FROM civicrm_action_schedule cas
   protected static function sendReminderEmail($tokenRow, $schedule, $toContactID) {
     $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($toContactID);
     if (!$toEmail) {
-      return array("email_missing" => "Couldn't find recipient's email address.");
+      return ["email_missing" => "Couldn't find recipient's email address."];
     }
 
     $body_text = $tokenRow->render('body_text');
@@ -613,7 +619,7 @@ FROM civicrm_action_schedule cas
     }
 
     // set up the parameters for CRM_Utils_Mail::send
-    $mailParams = array(
+    $mailParams = [
       'groupName' => 'Scheduled Reminder Sender',
       'from' => self::pickFromEmail($schedule),
       'toName' => $tokenRow->context['contact']['display_name'],
@@ -621,7 +627,7 @@ FROM civicrm_action_schedule cas
       'subject' => $tokenRow->render('subject'),
       'entity' => 'action_schedule',
       'entity_id' => $schedule->id,
-    );
+    ];
 
     if (!$body_html || $tokenRow->context['contact']['preferred_mail_format'] == 'Text' ||
       $tokenRow->context['contact']['preferred_mail_format'] == 'Both'
@@ -637,10 +643,10 @@ FROM civicrm_action_schedule cas
     }
     $result = CRM_Utils_Mail::send($mailParams);
     if (!$result || is_a($result, 'PEAR_Error')) {
-      return array('email_fail' => 'Failed to send message');
+      return ['email_fail' => 'Failed to send message'];
     }
 
-    return array();
+    return [];
   }
 
   /**
@@ -649,12 +655,12 @@ FROM civicrm_action_schedule cas
    * @return \Civi\Token\TokenProcessor
    */
   protected static function createTokenProcessor($schedule, $mapping) {
-    $tp = new \Civi\Token\TokenProcessor(\Civi\Core\Container::singleton()->get('dispatcher'), array(
+    $tp = new \Civi\Token\TokenProcessor(\Civi\Core\Container::singleton()->get('dispatcher'), [
       'controller' => __CLASS__,
       'actionSchedule' => $schedule,
       'actionMapping' => $mapping,
       'smarty' => TRUE,
-    ));
+    ]);
     $tp->addMessage('body_text', $schedule->body_text, 'text/plain');
     $tp->addMessage('body_html', $schedule->body_html, 'text/html');
     $tp->addMessage('sms_body_text', $schedule->sms_body_text, 'text/plain');
@@ -670,11 +676,11 @@ FROM civicrm_action_schedule cas
    * @return NULL|string
    */
   protected static function pickSmsPhoneNumber($smsToContactId) {
-    $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($smsToContactId, FALSE, 'Mobile', array(
+    $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($smsToContactId, FALSE, 'Mobile', [
       'is_deceased' => 0,
       'is_deleted' => 0,
       'do_not_sms' => 0,
-    ));
+    ]);
     //to get primary mobile ph,if not get a first mobile phONE
     if (!empty($toPhoneNumbers)) {
       $toPhoneNumberDetails = reset($toPhoneNumbers);
@@ -691,10 +697,10 @@ FROM civicrm_action_schedule cas
    *   array(mixed $value => string $label).
    */
   public static function getAdditionalRecipients() {
-    return array(
+    return [
       'manual' => ts('Choose Recipient(s)'),
       'group' => ts('Select Group'),
-    );
+    ];
   }
 
 }