Remove call to deprecated function
[civicrm-core.git] / CRM / Queue / Task.php
index b2d74b393ad71aa7773e6b84b9c680addef99297..da73d76379b6533e5d08913afd8fab9526fa286b 100644 (file)
@@ -41,16 +41,26 @@ class CRM_Queue_Task {
    */
   public $title;
 
+  /**
+   * @var array|null
+   * serializable
+   *
+   * If specified, it may include these keys:
+   *   - contactId: int|null
+   *   - domainId: int|null
+   */
+  public $runAs;
+
   /**
    * @param mixed $callback
    *   Serializable, a callable PHP item; must accept at least one argument
    *   (CRM_Queue_TaskContext).
    * @param array $arguments
    *   Serializable, extra arguments to pass to the callback (in order).
-   * @param string $title
+   * @param string|null $title
    *   A printable string which describes this task.
    */
-  public function __construct($callback, $arguments, $title = NULL) {
+  public function __construct($callback, array $arguments = [], ?string $title = NULL) {
     $this->callback = $callback;
     $this->arguments = $arguments;
     $this->title = $title;
@@ -59,24 +69,39 @@ class CRM_Queue_Task {
   /**
    * Perform the task.
    *
-   * @param array $taskCtx
-   *   Array with keys:
-   *   - log: object 'Log'
-   *
+   * @param \CRM_Queue_TaskContext $taskCtx
    * @throws Exception
-   * @return bool, TRUE if task completes successfully
+   * @return bool
+   *   TRUE if task completes successfully.
+   *   FALSE or exception if task fails.
    */
   public function run($taskCtx) {
     $args = $this->arguments;
     array_unshift($args, $taskCtx);
 
+    if ($this->runAs !== NULL) {
+      $equals = function($a, $b) {
+        return $a === $b || (is_numeric($a) && is_numeric($b) && $a == $b);
+      };
+      if (array_key_exists('contactId', $this->runAs) && !$equals(CRM_Core_Session::getLoggedInContactID(), $this->runAs['contactId'])) {
+        throw new Exception(sprintf('Cannot execute queue task. Unexpected contact "%s" for job "%s"', CRM_Core_Session::getLoggedInContactID(), $this->getSummary()));
+      }
+      if (array_key_exists('domainId', $this->runAs) && !$equals(CRM_Core_BAO_Domain::getDomain()->id, $this->runAs['domainId'])) {
+        throw new Exception(sprintf('Cannot execute queue task. Unexpected domain "%s" for job "%s"', CRM_Core_BAO_Domain::getDomain()->id, $this->getSummary()));
+      }
+    }
+
     if (is_callable($this->callback)) {
       $result = call_user_func_array($this->callback, $args);
       return $result;
     }
     else {
-      throw new Exception('Failed to call callback: ' . print_r($this->callback));
+      throw new Exception('Failed to call callback: ' . $this->getSummary());
     }
   }
 
+  private function getSummary(): string {
+    return json_encode(['title' => $this->title, 'runAs' => $this->runAs, 'callback' => $this->callback], JSON_UNESCAPED_SLASHES);
+  }
+
 }