3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * This interface defines methods that need to be implemented
30 * by every scheduled job (cron task) in CiviCRM.
33 * @copyright CiviCRM LLC (c) 2004-2019
35 class CRM_Core_JobManager
{
38 * @var array ($id => CRM_Core_ScheduledJob)
43 * @var CRM_Core_ScheduledJob
45 public $currentJob = NULL;
47 public $singleRunParams = [];
49 public $_source = NULL;
54 public function __construct() {
55 $config = CRM_Core_Config
::singleton();
56 $config->fatalErrorHandler
= 'CRM_Core_JobManager_scheduledJobFatalErrorHandler';
58 $this->jobs
= $this->_getJobs();
64 public function execute($auth = TRUE) {
66 $this->logEntry('Starting scheduled jobs execution');
68 if ($auth && !CRM_Utils_System
::authenticateKey(TRUE)) {
69 $this->logEntry('Could not authenticate the site key.');
71 require_once 'api/api.php';
73 // it's not asynchronous at this stage
74 CRM_Utils_Hook
::cron($this);
75 foreach ($this->jobs
as $job) {
76 if ($job->is_active
) {
77 if ($job->needsRunning()) {
78 $this->executeJob($job);
82 $this->logEntry('Finishing scheduled jobs execution.');
84 // Set last cron date for the status check
86 'name' => 'checkLastCron',
87 'check_info' => gmdate('U'),
89 CRM_Core_BAO_StatusPreference
::create($statusPref);
95 public function __destruct() {
102 public function executeJobByAction($entity, $action) {
103 $job = $this->_getJob(NULL, $entity, $action);
104 $this->executeJob($job);
110 public function executeJobById($id) {
111 $job = $this->_getJob($id);
112 $this->executeJob($job);
116 * @param CRM_Core_ScheduledJob $job
118 public function executeJob($job) {
119 $this->currentJob
= $job;
121 // CRM-18231 check if non-production environment.
123 CRM_Core_BAO_Setting
::isAPIJobAllowedToRun($job->apiParams
);
125 catch (Exception
$e) {
126 $this->logEntry('Error while executing ' . $job->name
. ': ' . $e->getMessage());
127 $this->currentJob
= FALSE;
131 $this->logEntry('Starting execution of ' . $job->name
);
134 $singleRunParamsKey = strtolower($job->api_entity
. '_' . $job->api_action
);
136 if (array_key_exists($singleRunParamsKey, $this->singleRunParams
)) {
137 $params = $this->singleRunParams
[$singleRunParamsKey];
140 $params = $job->apiParams
;
143 CRM_Utils_Hook
::preJob($job, $params);
145 $result = civicrm_api($job->api_entity
, $job->api_action
, $params);
147 catch (Exception
$e) {
148 $this->logEntry('Error while executing ' . $job->name
. ': ' . $e->getMessage());
151 CRM_Utils_Hook
::postJob($job, $params, $result);
152 $this->logEntry('Finished execution of ' . $job->name
. ' with result: ' . $this->_apiResultToMessage($result));
153 $this->currentJob
= FALSE;
155 //Disable outBound option after executing the job.
156 $environment = CRM_Core_Config
::environment(NULL, TRUE);
157 if ($environment != 'Production' && !empty($job->apiParams
['runInNonProductionEnvironment'])) {
158 Civi
::settings()->set('mailing_backend', ['outBound_option' => CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
]);
163 * Retrieves the list of jobs from the database,
164 * populates class param.
167 * ($id => CRM_Core_ScheduledJob)
169 private function _getJobs() {
171 $dao = new CRM_Core_DAO_Job();
172 $dao->orderBy('name');
173 $dao->domain_id
= CRM_Core_Config
::domainID();
175 while ($dao->fetch()) {
177 CRM_Core_DAO
::storeValues($dao, $temp);
178 $jobs[$dao->id
] = new CRM_Core_ScheduledJob($temp);
184 * Retrieves specific job from the database by id.
185 * and creates ScheduledJob object.
188 * @param null $entity
189 * @param null $action
191 * @return CRM_Core_ScheduledJob
194 private function _getJob($id = NULL, $entity = NULL, $action = NULL) {
195 if (is_null($id) && is_null($action)) {
196 CRM_Core_Error
::fatal('You need to provide either id or name to use this method');
198 $dao = new CRM_Core_DAO_Job();
200 $dao->api_entity
= $entity;
201 $dao->api_action
= $action;
203 while ($dao->fetch()) {
204 CRM_Core_DAO
::storeValues($dao, $temp);
205 $job = new CRM_Core_ScheduledJob($temp);
213 * @param array $params
214 * @param null $source
216 public function setSingleRunParams($entity, $job, $params, $source = NULL) {
217 $this->_source
= $source;
218 $key = strtolower($entity . '_' . $job);
219 $this->singleRunParams
[$key] = $params;
220 $this->singleRunParams
[$key]['version'] = 3;
224 * @param string $message
226 public function logEntry($message) {
227 $domainID = CRM_Core_Config
::domainID();
228 $dao = new CRM_Core_DAO_JobLog();
230 $dao->domain_id
= $domainID;
233 * The description is a summary of the message.
234 * HTML tags are stripped from the message.
235 * The description is limited to 240 characters
236 * and has an ellipsis added if it is truncated.
238 $maxDescription = 240;
239 $ellipsis = " (...)";
240 $description = strip_tags($message);
241 if (strlen($description) > $maxDescription) {
242 $description = substr($description, 0, $maxDescription - strlen($ellipsis)) . $ellipsis;
244 $dao->description
= $description;
246 if ($this->currentJob
) {
247 $dao->job_id
= $this->currentJob
->id
;
248 $dao->name
= $this->currentJob
->name
;
249 $dao->command
= ts("Entity:") . " " . $this->currentJob
->api_entity
. " " . ts("Action:") . " " . $this->currentJob
->api_action
;
251 if (!empty($this->currentJob
->parameters
)) {
252 $data .= "\n\nParameters raw (from db settings): \n" . $this->currentJob
->parameters
;
254 $singleRunParamsKey = strtolower($this->currentJob
->api_entity
. '_' . $this->currentJob
->api_action
);
255 if (array_key_exists($singleRunParamsKey, $this->singleRunParams
)) {
256 $data .= "\n\nParameters raw (" . $this->_source
. "): \n" . serialize($this->singleRunParams
[$singleRunParamsKey]);
257 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->singleRunParams
[$singleRunParamsKey]);
260 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->currentJob
->apiParams
);
263 $data .= "\n\nFull message: \n" . $message;
275 private function _apiResultToMessage($apiResult) {
276 $status = $apiResult['is_error'] ?
ts('Failure') : ts('Success');
277 $msg = CRM_Utils_Array
::value('error_message', $apiResult, 'empty error_message!');
278 $vals = CRM_Utils_Array
::value('values', $apiResult, 'empty values!');
279 if (is_array($msg)) {
280 $msg = serialize($msg);
282 if (is_array($vals)) {
283 $vals = serialize($vals);
285 $message = $apiResult['is_error'] ?
', Error message: ' . $msg : " (" . $vals . ")";
286 return $status . $message;
296 function CRM_Core_JobManager_scheduledJobFatalErrorHandler($message) {
297 throw new Exception("{$message['message']}: {$message['code']}");