3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * This interface defines methods that need to be implemented
14 * by every scheduled job (cron task) in CiviCRM.
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 class CRM_Core_JobManager
{
24 * Format is ($id => CRM_Core_ScheduledJob).
31 * @var CRM_Core_ScheduledJob
33 public $currentJob = NULL;
35 public $singleRunParams = [];
37 public $_source = NULL;
42 public function __construct() {
43 $this->jobs
= $this->_getJobs();
49 public function execute($auth = TRUE) {
51 $this->logEntry('Starting scheduled jobs execution');
53 if ($auth && !CRM_Utils_System
::authenticateKey(TRUE)) {
54 $this->logEntry('Could not authenticate the site key.');
56 require_once 'api/api.php';
58 // it's not asynchronous at this stage
59 CRM_Utils_Hook
::cron($this);
60 foreach ($this->jobs
as $job) {
61 if ($job->is_active
) {
62 if ($job->needsRunning()) {
63 $this->executeJob($job);
67 $this->logEntry('Finishing scheduled jobs execution.');
69 // Set last cron date for the status check
71 'name' => 'checkLastCron',
72 'check_info' => gmdate('U'),
75 CRM_Core_BAO_StatusPreference
::create($statusPref);
81 public function __destruct() {
88 public function executeJobByAction($entity, $action) {
89 $job = $this->_getJob(NULL, $entity, $action);
90 $this->executeJob($job);
96 public function executeJobById($id) {
97 $job = $this->_getJob($id);
98 $this->executeJob($job);
102 * @param CRM_Core_ScheduledJob $job
104 public function executeJob($job) {
105 $this->currentJob
= $job;
107 // CRM-18231 check if non-production environment.
109 CRM_Core_BAO_Setting
::isAPIJobAllowedToRun($job->apiParams
);
111 catch (Exception
$e) {
112 $this->logEntry('Error while executing ' . $job->name
. ': ' . $e->getMessage());
113 $this->currentJob
= FALSE;
117 $this->logEntry('Starting execution of ' . $job->name
);
120 $singleRunParamsKey = strtolower($job->api_entity
. '_' . $job->api_action
);
122 if (array_key_exists($singleRunParamsKey, $this->singleRunParams
)) {
123 $params = $this->singleRunParams
[$singleRunParamsKey];
126 $params = $job->apiParams
;
129 CRM_Utils_Hook
::preJob($job, $params);
131 $result = civicrm_api($job->api_entity
, $job->api_action
, $params);
133 catch (Exception
$e) {
134 $this->logEntry('Error while executing ' . $job->name
. ': ' . $e->getMessage());
137 CRM_Utils_Hook
::postJob($job, $params, $result);
138 $this->logEntry('Finished execution of ' . $job->name
. ' with result: ' . $this->_apiResultToMessage($result));
139 $this->currentJob
= FALSE;
141 //Disable outBound option after executing the job.
142 $environment = CRM_Core_Config
::environment(NULL, TRUE);
143 if ($environment != 'Production' && !empty($job->apiParams
['runInNonProductionEnvironment'])) {
144 Civi
::settings()->set('mailing_backend', ['outBound_option' => CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
]);
149 * Retrieves the list of jobs from the database,
150 * populates class param.
153 * ($id => CRM_Core_ScheduledJob)
155 private function _getJobs(): array {
157 $dao = new CRM_Core_DAO_Job();
158 $dao->orderBy('name');
159 $dao->domain_id
= CRM_Core_Config
::domainID();
161 while ($dao->fetch()) {
162 $temp = ['class' => NULL, 'parameters' => NULL, 'last_run' => NULL];
163 CRM_Core_DAO
::storeValues($dao, $temp);
164 $jobs[$dao->id
] = new CRM_Core_ScheduledJob($temp);
170 * Retrieves specific job from the database by id.
171 * and creates ScheduledJob object.
174 * @param null $entity
175 * @param null $action
177 * @return CRM_Core_ScheduledJob
180 private function _getJob($id = NULL, $entity = NULL, $action = NULL) {
181 if (is_null($id) && is_null($action)) {
182 throw new CRM_Core_Exception('You need to provide either id or name to use this method');
184 $dao = new CRM_Core_DAO_Job();
186 $dao->api_entity
= $entity;
187 $dao->api_action
= $action;
189 while ($dao->fetch()) {
190 CRM_Core_DAO
::storeValues($dao, $temp);
191 $job = new CRM_Core_ScheduledJob($temp);
199 * @param array $params
200 * @param null $source
202 public function setSingleRunParams($entity, $job, $params, $source = NULL) {
203 $this->_source
= $source;
204 $key = strtolower($entity . '_' . $job);
205 $this->singleRunParams
[$key] = $params;
206 $this->singleRunParams
[$key]['version'] = 3;
210 * @param string $message
212 public function logEntry($message) {
213 $domainID = CRM_Core_Config
::domainID();
214 $dao = new CRM_Core_DAO_JobLog();
216 $dao->domain_id
= $domainID;
219 * The description is a summary of the message.
220 * HTML tags are stripped from the message.
221 * The description is limited to 240 characters
222 * and has an ellipsis added if it is truncated.
224 $maxDescription = 240;
225 $ellipsis = " (...)";
226 $description = strip_tags($message);
227 if (strlen($description) > $maxDescription) {
228 $description = substr($description, 0, $maxDescription - strlen($ellipsis)) . $ellipsis;
230 $dao->description
= $description;
232 if ($this->currentJob
) {
233 $dao->job_id
= $this->currentJob
->id
;
234 $dao->name
= $this->currentJob
->name
;
235 $dao->command
= ts("Entity:") . " " . $this->currentJob
->api_entity
. " " . ts("Action:") . " " . $this->currentJob
->api_action
;
237 if (!empty($this->currentJob
->parameters
)) {
238 $data .= "\n\nParameters raw (from db settings): \n" . $this->currentJob
->parameters
;
240 $singleRunParamsKey = strtolower($this->currentJob
->api_entity
. '_' . $this->currentJob
->api_action
);
241 if (array_key_exists($singleRunParamsKey, $this->singleRunParams
)) {
242 $data .= "\n\nParameters raw (" . $this->_source
. "): \n" . serialize($this->singleRunParams
[$singleRunParamsKey]);
243 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->singleRunParams
[$singleRunParamsKey]);
246 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->currentJob
->apiParams
);
249 $data .= "\n\nFull message: \n" . $message;
261 private function _apiResultToMessage($apiResult) {
262 $status = $apiResult['is_error'] ?
ts('Failure') : ts('Success');
263 $msg = CRM_Utils_Array
::value('error_message', $apiResult, 'empty error_message!');
264 $vals = CRM_Utils_Array
::value('values', $apiResult, 'empty values!');
265 if (is_array($msg)) {
266 $msg = serialize($msg);
268 if (is_array($vals)) {
269 $vals = serialize($vals);
271 $message = $apiResult['is_error'] ?
', Error message: ' . $msg : " (" . $vals . ")";
272 return $status . $message;