Merge commit '013198e90942d' into 4.5-missing-prs
[civicrm-core.git] / CRM / Core / JobManager.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 33 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
34 * $Id$
35 *
36 */
37class CRM_Core_JobManager {
38
39 /**
40 * @var array ($id => CRM_Core_ScheduledJob)
41 */
42 var $jobs = NULL;
43
44 /**
45 * @var CRM_Core_ScheduledJob
46 */
47 var $currentJob = NULL;
48
49 var $singleRunParams = array();
50
51 var $_source = NULL;
52
53
54 /*
55 * Class constructor
cbb7c7e0 56 *
6a488035
TO
57 * @param void
58 * @access public
cbb7c7e0 59 *
6a488035 60 */
a0ee3941
EM
61 /**
62 *
63 */
6a488035
TO
64 public function __construct() {
65 $config = CRM_Core_Config::singleton();
66 $config->fatalErrorHandler = 'CRM_Core_JobManager_scheduledJobFatalErrorHandler';
67
68 $this->jobs = $this->_getJobs();
69 }
70
71 /*
cbb7c7e0 72 *
6a488035
TO
73 * @param void
74 * @access private
cbb7c7e0 75 *
6a488035 76 */
a0ee3941
EM
77 /**
78 * @param bool $auth
79 */
6a488035
TO
80 public function execute($auth = TRUE) {
81
82 $this->logEntry('Starting scheduled jobs execution');
83
84 if ($auth && !CRM_Utils_System::authenticateKey(TRUE)) {
85 $this->logEntry('Could not authenticate the site key.');
86 }
87 require_once 'api/api.php';
88
89 // it's not asynchronous at this stage
90 CRM_Utils_Hook::cron($this);
91 foreach ($this->jobs as $job) {
92 if ($job->is_active) {
93 if ($job->needsRunning()) {
94 $this->executeJob($job);
95 }
96 }
97 }
98 $this->logEntry('Finishing scheduled jobs execution.');
99 }
100
101 /*
102 * Class destructor
cbb7c7e0 103 *
6a488035
TO
104 * @param void
105 * @access public
cbb7c7e0 106 *
6a488035
TO
107 */
108 public function __destruct() {}
109
a0ee3941
EM
110 /**
111 * @param $entity
112 * @param $action
113 */
6a488035
TO
114 public function executeJobByAction($entity, $action) {
115 $job = $this->_getJob(NULL, $entity, $action);
116 $this->executeJob($job);
117 }
118
a0ee3941
EM
119 /**
120 * @param $id
121 */
6a488035
TO
122 public function executeJobById($id) {
123 $job = $this->_getJob($id);
124 $this->executeJob($job);
125 }
126
127 /**
128 * @param CRM_Core_ScheduledJob $job
129 */
130 public function executeJob($job) {
131 $this->currentJob = $job;
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 try {
145 $result = civicrm_api($job->api_entity, $job->api_action, $params);
146 }
147 catch(Exception$e) {
148 $this->logEntry('Error while executing ' . $job->name . ': ' . $e->getMessage());
149 }
150 $this->logEntry('Finished execution of ' . $job->name . ' with result: ' . $this->_apiResultToMessage($result));
151 $this->currentJob = FALSE;
152 }
153
154 /*
155 * Retrieves the list of jobs from the database,
156 * populates class param.
cbb7c7e0 157 *
6a488035
TO
158 * @param void
159 * @return array ($id => CRM_Core_ScheduledJob)
160 * @access private
cbb7c7e0 161 *
6a488035 162 */
a0ee3941
EM
163 /**
164 * @return array
165 */
6a488035
TO
166 private function _getJobs() {
167 $jobs = array();
168 $dao = new CRM_Core_DAO_Job();
169 $dao->orderBy('name');
2f7a6dd7 170 $dao->domain_id = CRM_Core_Config::domainID();
6a488035
TO
171 $dao->find();
172 while ($dao->fetch()) {
173 $temp = array();
174 CRM_Core_DAO::storeValues($dao, $temp);
175 $jobs[$dao->id] = new CRM_Core_ScheduledJob($temp);
176 }
177 return $jobs;
178 }
179
180 /*
181 * Retrieves specific job from the database by id
182 * and creates ScheduledJob object.
cbb7c7e0 183 *
6a488035
TO
184 * @param void
185 * @access private
cbb7c7e0 186 *
6a488035 187 */
a0ee3941
EM
188 /**
189 * @param null $id
190 * @param null $entity
191 * @param null $action
192 *
193 * @return CRM_Core_ScheduledJob
194 * @throws Exception
195 */
6a488035
TO
196 private function _getJob($id = NULL, $entity = NULL, $action = NULL) {
197 if (is_null($id) && is_null($action)) {
198 CRM_Core_Error::fatal('You need to provide either id or name to use this method');
199 }
200 $dao = new CRM_Core_DAO_Job();
201 $dao->id = $id;
202 $dao->api_entity = $entity;
203 $dao->api_action = $action;
204 $dao->find();
205 while ($dao->fetch()) {
206 CRM_Core_DAO::storeValues($dao, $temp);
207 $job = new CRM_Core_ScheduledJob($temp);
208 }
209 return $job;
210 }
211
a0ee3941
EM
212 /**
213 * @param $entity
214 * @param $job
215 * @param $params
216 * @param null $source
217 */
6a488035
TO
218 public function setSingleRunParams($entity, $job, $params, $source = NULL) {
219 $this->_source = $source;
220 $key = strtolower($entity . '_' . $job);
221 $this->singleRunParams[$key] = $params;
222 $this->singleRunParams[$key]['version'] = 3;
223 }
cbb7c7e0 224
6a488035
TO
225 /*
226 *
227 * @return array|null collection of permissions, null if none
228 * @access public
229 *
230 */
a0ee3941
EM
231 /**
232 * @param $message
233 */
6a488035
TO
234 public function logEntry($message) {
235 $domainID = CRM_Core_Config::domainID();
236 $dao = new CRM_Core_DAO_JobLog();
237
238 $dao->domain_id = $domainID;
239 $dao->description = substr($message, 0, 235);
240 if (strlen($message) > 235) {
241 $dao->description .= " (...)";
242 }
243 if ($this->currentJob) {
244 $dao->job_id = $this->currentJob->id;
245 $dao->name = $this->currentJob->name;
246 $dao->command = ts("Entity:") . " " + $this->currentJob->api_entity + " " . ts("Action:") . " " + $this->currentJob->api_action;
247 $data = "";
248 if (!empty($this->currentJob->parameters)) {
249 $data .= "\n\nParameters raw (from db settings): \n" . $this->currentJob->parameters;
250 }
251 $singleRunParamsKey = strtolower($this->currentJob->api_entity . '_' . $this->currentJob->api_action);
252 if (array_key_exists($singleRunParamsKey, $this->singleRunParams)) {
253 $data .= "\n\nParameters raw (" . $this->_source . "): \n" . serialize($this->singleRunParams[$singleRunParamsKey]);
254 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->singleRunParams[$singleRunParamsKey]);
255 }
256 else {
257 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->currentJob->apiParams);
258 }
259
260 $data .= "\n\nFull message: \n" . $message;
261
262 $dao->data = $data;
263 }
264 $dao->save();
265 }
266
a0ee3941
EM
267 /**
268 * @param $apiResult
269 *
270 * @return string
271 */
6a488035
TO
272 private function _apiResultToMessage($apiResult) {
273 $status = $apiResult['is_error'] ? ts('Failure') : ts('Success');
274 $msg = CRM_Utils_Array::value('error_message', $apiResult, 'empty error_message!');
275 $vals = CRM_Utils_Array::value('values', $apiResult, 'empty values!');
276 if (is_array($msg)) {
277 $msg = serialize($msg);
278 }
279 if (is_array($vals)) {
280 $vals = serialize($vals);
281 }
282 $message = $apiResult['is_error'] ? ', Error message: ' . $msg : " (" . $vals . ")";
283 return $status . $message;
284 }
285}
286
a0ee3941
EM
287/**
288 * @param $message
289 *
290 * @throws Exception
291 */
6a488035
TO
292function CRM_Core_JobManager_scheduledJobFatalErrorHandler($message) {
293 throw new Exception("{$message['message']}: {$message['code']}");
294}
295