Merge remote-tracking branch 'upstream/4.3' into 4.3-master-2013-09-25-01-46-57
[civicrm-core.git] / CRM / Core / JobManager.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 * @access public
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 * @access private
72 *
73 */
74 public function execute($auth = TRUE) {
75
76 $this->logEntry('Starting scheduled jobs execution');
77
78 if ($auth && !CRM_Utils_System::authenticateKey(TRUE)) {
79 $this->logEntry('Could not authenticate the site key.');
80 }
81 require_once 'api/api.php';
82
83 // it's not asynchronous at this stage
84 CRM_Utils_Hook::cron($this);
85 foreach ($this->jobs as $job) {
86 if ($job->is_active) {
87 if ($job->needsRunning()) {
88 $this->executeJob($job);
89 }
90 }
91 }
92 $this->logEntry('Finishing scheduled jobs execution.');
93 }
94
95 /*
96 * Class destructor
97 *
98 * @param void
99 * @access public
100 *
101 */
102 public function __destruct() {}
103
104 public function executeJobByAction($entity, $action) {
105 $job = $this->_getJob(NULL, $entity, $action);
106 $this->executeJob($job);
107 }
108
109 public function executeJobById($id) {
110 $job = $this->_getJob($id);
111 $this->executeJob($job);
112 }
113
114 /**
115 * @param CRM_Core_ScheduledJob $job
116 */
117 public function executeJob($job) {
118 $this->currentJob = $job;
119 $this->logEntry('Starting execution of ' . $job->name);
120 $job->saveLastRun();
121
122 $singleRunParamsKey = strtolower($job->api_entity . '_' . $job->api_action);
123
124 if (array_key_exists($singleRunParamsKey, $this->singleRunParams)) {
125 $params = $this->singleRunParams[$singleRunParamsKey];
126 }
127 else {
128 $params = $job->apiParams;
129 }
130
131 try {
132 $result = civicrm_api($job->api_entity, $job->api_action, $params);
133 }
134 catch(Exception$e) {
135 $this->logEntry('Error while executing ' . $job->name . ': ' . $e->getMessage());
136 }
137 $this->logEntry('Finished execution of ' . $job->name . ' with result: ' . $this->_apiResultToMessage($result));
138 $this->currentJob = FALSE;
139 }
140
141 /*
142 * Retrieves the list of jobs from the database,
143 * populates class param.
144 *
145 * @param void
146 * @return array ($id => CRM_Core_ScheduledJob)
147 * @access private
148 *
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 void
169 * @access private
170 *
171 */
172 private function _getJob($id = NULL, $entity = NULL, $action = NULL) {
173 if (is_null($id) && is_null($action)) {
174 CRM_Core_Error::fatal('You need to provide either id or name to use this method');
175 }
176 $dao = new CRM_Core_DAO_Job();
177 $dao->id = $id;
178 $dao->api_entity = $entity;
179 $dao->api_action = $action;
180 $dao->find();
181 while ($dao->fetch()) {
182 CRM_Core_DAO::storeValues($dao, $temp);
183 $job = new CRM_Core_ScheduledJob($temp);
184 }
185 return $job;
186 }
187
188 public function setSingleRunParams($entity, $job, $params, $source = NULL) {
189 $this->_source = $source;
190 $key = strtolower($entity . '_' . $job);
191 $this->singleRunParams[$key] = $params;
192 $this->singleRunParams[$key]['version'] = 3;
193 }
194
195 /*
196 *
197 * @return array|null collection of permissions, null if none
198 * @access public
199 *
200 */
201 public function logEntry($message) {
202 $domainID = CRM_Core_Config::domainID();
203 $dao = new CRM_Core_DAO_JobLog();
204
205 $dao->domain_id = $domainID;
206 $dao->description = substr($message, 0, 235);
207 if (strlen($message) > 235) {
208 $dao->description .= " (...)";
209 }
210 if ($this->currentJob) {
211 $dao->job_id = $this->currentJob->id;
212 $dao->name = $this->currentJob->name;
213 $dao->command = ts("Entity:") . " " + $this->currentJob->api_entity + " " . ts("Action:") . " " + $this->currentJob->api_action;
214 $data = "";
215 if (!empty($this->currentJob->parameters)) {
216 $data .= "\n\nParameters raw (from db settings): \n" . $this->currentJob->parameters;
217 }
218 $singleRunParamsKey = strtolower($this->currentJob->api_entity . '_' . $this->currentJob->api_action);
219 if (array_key_exists($singleRunParamsKey, $this->singleRunParams)) {
220 $data .= "\n\nParameters raw (" . $this->_source . "): \n" . serialize($this->singleRunParams[$singleRunParamsKey]);
221 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->singleRunParams[$singleRunParamsKey]);
222 }
223 else {
224 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->currentJob->apiParams);
225 }
226
227 $data .= "\n\nFull message: \n" . $message;
228
229 $dao->data = $data;
230 }
231 $dao->save();
232 }
233
234 private function _apiResultToMessage($apiResult) {
235 $status = $apiResult['is_error'] ? ts('Failure') : ts('Success');
236 $msg = CRM_Utils_Array::value('error_message', $apiResult, 'empty error_message!');
237 $vals = CRM_Utils_Array::value('values', $apiResult, 'empty values!');
238 if (is_array($msg)) {
239 $msg = serialize($msg);
240 }
241 if (is_array($vals)) {
242 $vals = serialize($vals);
243 }
244 $message = $apiResult['is_error'] ? ', Error message: ' . $msg : " (" . $vals . ")";
245 return $status . $message;
246 }
247 }
248
249 function CRM_Core_JobManager_scheduledJobFatalErrorHandler($message) {
250 throw new Exception("{$message['message']}: {$message['code']}");
251 }
252