INFRA-132 - Remove extra newlines from the bottom of docblocks
[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 * @param $entity
105 * @param $action
106 */
107 public function executeJobByAction($entity, $action) {
108 $job = $this->_getJob(NULL, $entity, $action);
109 $this->executeJob($job);
110 }
111
112 /**
113 * @param int $id
114 */
115 public function executeJobById($id) {
116 $job = $this->_getJob($id);
117 $this->executeJob($job);
118 }
119
120 /**
121 * @param CRM_Core_ScheduledJob $job
122 */
123 public function executeJob($job) {
124 $this->currentJob = $job;
125 $this->logEntry('Starting execution of ' . $job->name);
126 $job->saveLastRun();
127
128 $singleRunParamsKey = strtolower($job->api_entity . '_' . $job->api_action);
129
130 if (array_key_exists($singleRunParamsKey, $this->singleRunParams)) {
131 $params = $this->singleRunParams[$singleRunParamsKey];
132 }
133 else {
134 $params = $job->apiParams;
135 }
136
137 try {
138 $result = civicrm_api($job->api_entity, $job->api_action, $params);
139 }
140 catch(Exception$e) {
141 $this->logEntry('Error while executing ' . $job->name . ': ' . $e->getMessage());
142 }
143 $this->logEntry('Finished execution of ' . $job->name . ' with result: ' . $this->_apiResultToMessage($result));
144 $this->currentJob = FALSE;
145 }
146
147 /*
148 * Retrieves the list of jobs from the database,
149 * populates class param.
150 *
151 * @param void
152 * @return array
153 * ($id => CRM_Core_ScheduledJob)
154 */
155 /**
156 * @return array
157 */
158 private function _getJobs() {
159 $jobs = array();
160 $dao = new CRM_Core_DAO_Job();
161 $dao->orderBy('name');
162 $dao->domain_id = CRM_Core_Config::domainID();
163 $dao->find();
164 while ($dao->fetch()) {
165 $temp = array();
166 CRM_Core_DAO::storeValues($dao, $temp);
167 $jobs[$dao->id] = new CRM_Core_ScheduledJob($temp);
168 }
169 return $jobs;
170 }
171
172 /*
173 * Retrieves specific job from the database by id
174 * and creates ScheduledJob object.
175 *
176 * @param void
177 */
178 /**
179 * @param int $id
180 * @param null $entity
181 * @param null $action
182 *
183 * @return CRM_Core_ScheduledJob
184 * @throws Exception
185 */
186 private function _getJob($id = NULL, $entity = NULL, $action = NULL) {
187 if (is_null($id) && is_null($action)) {
188 CRM_Core_Error::fatal('You need to provide either id or name to use this method');
189 }
190 $dao = new CRM_Core_DAO_Job();
191 $dao->id = $id;
192 $dao->api_entity = $entity;
193 $dao->api_action = $action;
194 $dao->find();
195 while ($dao->fetch()) {
196 CRM_Core_DAO::storeValues($dao, $temp);
197 $job = new CRM_Core_ScheduledJob($temp);
198 }
199 return $job;
200 }
201
202 /**
203 * @param $entity
204 * @param $job
205 * @param array $params
206 * @param null $source
207 */
208 public function setSingleRunParams($entity, $job, $params, $source = NULL) {
209 $this->_source = $source;
210 $key = strtolower($entity . '_' . $job);
211 $this->singleRunParams[$key] = $params;
212 $this->singleRunParams[$key]['version'] = 3;
213 }
214
215 /*
216 *
217 * @return array|null collection of permissions, null if none
218 */
219 /**
220 * @param $message
221 */
222 public function logEntry($message) {
223 $domainID = CRM_Core_Config::domainID();
224 $dao = new CRM_Core_DAO_JobLog();
225
226 $dao->domain_id = $domainID;
227 $dao->description = substr($message, 0, 235);
228 if (strlen($message) > 235) {
229 $dao->description .= " (...)";
230 }
231 if ($this->currentJob) {
232 $dao->job_id = $this->currentJob->id;
233 $dao->name = $this->currentJob->name;
234 $dao->command = ts("Entity:") . " " . $this->currentJob->api_entity . " " . ts("Action:") . " " . $this->currentJob->api_action;
235 $data = "";
236 if (!empty($this->currentJob->parameters)) {
237 $data .= "\n\nParameters raw (from db settings): \n" . $this->currentJob->parameters;
238 }
239 $singleRunParamsKey = strtolower($this->currentJob->api_entity . '_' . $this->currentJob->api_action);
240 if (array_key_exists($singleRunParamsKey, $this->singleRunParams)) {
241 $data .= "\n\nParameters raw (" . $this->_source . "): \n" . serialize($this->singleRunParams[$singleRunParamsKey]);
242 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->singleRunParams[$singleRunParamsKey]);
243 }
244 else {
245 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->currentJob->apiParams);
246 }
247
248 $data .= "\n\nFull message: \n" . $message;
249
250 $dao->data = $data;
251 }
252 $dao->save();
253 }
254
255 /**
256 * @param $apiResult
257 *
258 * @return string
259 */
260 private function _apiResultToMessage($apiResult) {
261 $status = $apiResult['is_error'] ? ts('Failure') : ts('Success');
262 $msg = CRM_Utils_Array::value('error_message', $apiResult, 'empty error_message!');
263 $vals = CRM_Utils_Array::value('values', $apiResult, 'empty values!');
264 if (is_array($msg)) {
265 $msg = serialize($msg);
266 }
267 if (is_array($vals)) {
268 $vals = serialize($vals);
269 }
270 $message = $apiResult['is_error'] ? ', Error message: ' . $msg : " (" . $vals . ")";
271 return $status . $message;
272 }
273 }
274
275 /**
276 * @param $message
277 *
278 * @throws Exception
279 */
280 function CRM_Core_JobManager_scheduledJobFatalErrorHandler($message) {
281 throw new Exception("{$message['message']}: {$message['code']}");
282 }