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