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