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