Only add in the additional metadata if we are also adding them to the form
[civicrm-core.git] / CRM / Core / JobManager.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 * This interface defines methods that need to be implemented
14 * by every scheduled job (cron task) in CiviCRM.
15 *
16 * @package CRM
ca5cec67 17 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
18 */
19class CRM_Core_JobManager {
20
21 /**
e97c66ff 22 * Jobs.
23 *
24 * Format is ($id => CRM_Core_ScheduledJob).
25 *
26 * @var array
6a488035 27 */
518fa0ee 28 public $jobs = NULL;
6a488035
TO
29
30 /**
31 * @var CRM_Core_ScheduledJob
32 */
518fa0ee 33 public $currentJob = NULL;
6a488035 34
518fa0ee 35 public $singleRunParams = [];
6a488035 36
518fa0ee 37 public $_source = NULL;
6a488035 38
d424ffde 39 /**
d09edf64 40 * Class constructor.
6a488035
TO
41 */
42 public function __construct() {
43 $config = CRM_Core_Config::singleton();
44 $config->fatalErrorHandler = 'CRM_Core_JobManager_scheduledJobFatalErrorHandler';
45
46 $this->jobs = $this->_getJobs();
47 }
48
a0ee3941
EM
49 /**
50 * @param bool $auth
51 */
6a488035
TO
52 public function execute($auth = TRUE) {
53
54 $this->logEntry('Starting scheduled jobs execution');
55
56 if ($auth && !CRM_Utils_System::authenticateKey(TRUE)) {
57 $this->logEntry('Could not authenticate the site key.');
58 }
59 require_once 'api/api.php';
60
61 // it's not asynchronous at this stage
62 CRM_Utils_Hook::cron($this);
63 foreach ($this->jobs as $job) {
64 if ($job->is_active) {
65 if ($job->needsRunning()) {
66 $this->executeJob($job);
67 }
68 }
69 }
70 $this->logEntry('Finishing scheduled jobs execution.');
aa96ce62
AH
71
72 // Set last cron date for the status check
be2fb01f 73 $statusPref = [
aa96ce62
AH
74 'name' => 'checkLastCron',
75 'check_info' => gmdate('U'),
be2fb01f 76 ];
aa96ce62 77 CRM_Core_BAO_StatusPreference::create($statusPref);
6a488035
TO
78 }
79
d424ffde 80 /**
d09edf64 81 * Class destructor.
6a488035 82 */
6ea503d4
TO
83 public function __destruct() {
84 }
6a488035 85
a0ee3941
EM
86 /**
87 * @param $entity
88 * @param $action
89 */
6a488035
TO
90 public function executeJobByAction($entity, $action) {
91 $job = $this->_getJob(NULL, $entity, $action);
92 $this->executeJob($job);
93 }
94
a0ee3941 95 /**
100fef9d 96 * @param int $id
a0ee3941 97 */
6a488035
TO
98 public function executeJobById($id) {
99 $job = $this->_getJob($id);
100 $this->executeJob($job);
101 }
102
103 /**
104 * @param CRM_Core_ScheduledJob $job
105 */
106 public function executeJob($job) {
107 $this->currentJob = $job;
f008885c
E
108
109 // CRM-18231 check if non-production environment.
110 try {
111 CRM_Core_BAO_Setting::isAPIJobAllowedToRun($job->apiParams);
112 }
113 catch (Exception $e) {
114 $this->logEntry('Error while executing ' . $job->name . ': ' . $e->getMessage());
115 $this->currentJob = FALSE;
116 return FALSE;
117 }
118
6a488035
TO
119 $this->logEntry('Starting execution of ' . $job->name);
120 $job->saveLastRun();
121
122 $singleRunParamsKey = strtolower($job->api_entity . '_' . $job->api_action);
123
124 if (array_key_exists($singleRunParamsKey, $this->singleRunParams)) {
125 $params = $this->singleRunParams[$singleRunParamsKey];
126 }
127 else {
128 $params = $job->apiParams;
129 }
130
912d0751 131 CRM_Utils_Hook::preJob($job, $params);
6a488035
TO
132 try {
133 $result = civicrm_api($job->api_entity, $job->api_action, $params);
134 }
353ffa53 135 catch (Exception$e) {
6a488035 136 $this->logEntry('Error while executing ' . $job->name . ': ' . $e->getMessage());
912d0751 137 $result = $e;
6a488035 138 }
912d0751 139 CRM_Utils_Hook::postJob($job, $params, $result);
6a488035
TO
140 $this->logEntry('Finished execution of ' . $job->name . ' with result: ' . $this->_apiResultToMessage($result));
141 $this->currentJob = FALSE;
288e5f75
JP
142
143 //Disable outBound option after executing the job.
144 $environment = CRM_Core_Config::environment(NULL, TRUE);
145 if ($environment != 'Production' && !empty($job->apiParams['runInNonProductionEnvironment'])) {
be2fb01f 146 Civi::settings()->set('mailing_backend', ['outBound_option' => CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED]);
288e5f75 147 }
6a488035
TO
148 }
149
d424ffde 150 /**
6a488035
TO
151 * Retrieves the list of jobs from the database,
152 * populates class param.
cbb7c7e0 153 *
a6c01b45
CW
154 * @return array
155 * ($id => CRM_Core_ScheduledJob)
6a488035
TO
156 */
157 private function _getJobs() {
be2fb01f 158 $jobs = [];
6a488035
TO
159 $dao = new CRM_Core_DAO_Job();
160 $dao->orderBy('name');
2f7a6dd7 161 $dao->domain_id = CRM_Core_Config::domainID();
6a488035
TO
162 $dao->find();
163 while ($dao->fetch()) {
be2fb01f 164 $temp = [];
6a488035
TO
165 CRM_Core_DAO::storeValues($dao, $temp);
166 $jobs[$dao->id] = new CRM_Core_ScheduledJob($temp);
167 }
168 return $jobs;
169 }
170
d424ffde 171 /**
d09edf64 172 * Retrieves specific job from the database by id.
6a488035 173 * and creates ScheduledJob object.
cbb7c7e0 174 *
100fef9d 175 * @param int $id
a0ee3941
EM
176 * @param null $entity
177 * @param null $action
178 *
179 * @return CRM_Core_ScheduledJob
180 * @throws Exception
181 */
6a488035
TO
182 private function _getJob($id = NULL, $entity = NULL, $action = NULL) {
183 if (is_null($id) && is_null($action)) {
184 CRM_Core_Error::fatal('You need to provide either id or name to use this method');
185 }
353ffa53
TO
186 $dao = new CRM_Core_DAO_Job();
187 $dao->id = $id;
6a488035
TO
188 $dao->api_entity = $entity;
189 $dao->api_action = $action;
190 $dao->find();
191 while ($dao->fetch()) {
192 CRM_Core_DAO::storeValues($dao, $temp);
193 $job = new CRM_Core_ScheduledJob($temp);
194 }
195 return $job;
196 }
197
a0ee3941
EM
198 /**
199 * @param $entity
200 * @param $job
c490a46a 201 * @param array $params
a0ee3941
EM
202 * @param null $source
203 */
6a488035
TO
204 public function setSingleRunParams($entity, $job, $params, $source = NULL) {
205 $this->_source = $source;
206 $key = strtolower($entity . '_' . $job);
207 $this->singleRunParams[$key] = $params;
208 $this->singleRunParams[$key]['version'] = 3;
209 }
cbb7c7e0 210
d424ffde
CW
211 /**
212 * @param string $message
6a488035
TO
213 */
214 public function logEntry($message) {
215 $domainID = CRM_Core_Config::domainID();
216 $dao = new CRM_Core_DAO_JobLog();
217
218 $dao->domain_id = $domainID;
11945183 219
220 /*
221 * The description is a summary of the message.
222 * HTML tags are stripped from the message.
223 * The description is limited to 240 characters
224 * and has an ellipsis added if it is truncated.
225 */
226 $maxDescription = 240;
227 $ellipsis = " (...)";
228 $description = strip_tags($message);
229 if (strlen($description) > $maxDescription) {
230 $description = substr($description, 0, $maxDescription - strlen($ellipsis)) . $ellipsis;
6a488035 231 }
11945183 232 $dao->description = $description;
233
6a488035 234 if ($this->currentJob) {
353ffa53
TO
235 $dao->job_id = $this->currentJob->id;
236 $dao->name = $this->currentJob->name;
fe901a30 237 $dao->command = ts("Entity:") . " " . $this->currentJob->api_entity . " " . ts("Action:") . " " . $this->currentJob->api_action;
353ffa53 238 $data = "";
6a488035
TO
239 if (!empty($this->currentJob->parameters)) {
240 $data .= "\n\nParameters raw (from db settings): \n" . $this->currentJob->parameters;
241 }
242 $singleRunParamsKey = strtolower($this->currentJob->api_entity . '_' . $this->currentJob->api_action);
243 if (array_key_exists($singleRunParamsKey, $this->singleRunParams)) {
244 $data .= "\n\nParameters raw (" . $this->_source . "): \n" . serialize($this->singleRunParams[$singleRunParamsKey]);
245 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->singleRunParams[$singleRunParamsKey]);
246 }
247 else {
248 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->currentJob->apiParams);
249 }
250
251 $data .= "\n\nFull message: \n" . $message;
252
253 $dao->data = $data;
254 }
255 $dao->save();
256 }
257
a0ee3941
EM
258 /**
259 * @param $apiResult
260 *
261 * @return string
262 */
6a488035
TO
263 private function _apiResultToMessage($apiResult) {
264 $status = $apiResult['is_error'] ? ts('Failure') : ts('Success');
353ffa53
TO
265 $msg = CRM_Utils_Array::value('error_message', $apiResult, 'empty error_message!');
266 $vals = CRM_Utils_Array::value('values', $apiResult, 'empty values!');
6a488035
TO
267 if (is_array($msg)) {
268 $msg = serialize($msg);
269 }
270 if (is_array($vals)) {
271 $vals = serialize($vals);
272 }
273 $message = $apiResult['is_error'] ? ', Error message: ' . $msg : " (" . $vals . ")";
274 return $status . $message;
275 }
96025800 276
6a488035
TO
277}
278
a0ee3941
EM
279/**
280 * @param $message
281 *
282 * @throws Exception
283 */
6a488035
TO
284function CRM_Core_JobManager_scheduledJobFatalErrorHandler($message) {
285 throw new Exception("{$message['message']}: {$message['code']}");
286}