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
{
40 * Format is ($id => CRM_Core_ScheduledJob).
47 * @var CRM_Core_ScheduledJob
49 public $currentJob = NULL;
51 public $singleRunParams = [];
53 public $_source = NULL;
58 public function __construct() {
59 $config = CRM_Core_Config
::singleton();
60 $config->fatalErrorHandler
= 'CRM_Core_JobManager_scheduledJobFatalErrorHandler';
62 $this->jobs
= $this->_getJobs();
68 public function execute($auth = TRUE) {
70 $this->logEntry('Starting scheduled jobs execution');
72 if ($auth && !CRM_Utils_System
::authenticateKey(TRUE)) {
73 $this->logEntry('Could not authenticate the site key.');
75 require_once 'api/api.php';
77 // it's not asynchronous at this stage
78 CRM_Utils_Hook
::cron($this);
79 foreach ($this->jobs
as $job) {
80 if ($job->is_active
) {
81 if ($job->needsRunning()) {
82 $this->executeJob($job);
86 $this->logEntry('Finishing scheduled jobs execution.');
88 // Set last cron date for the status check
90 'name' => 'checkLastCron',
91 'check_info' => gmdate('U'),
93 CRM_Core_BAO_StatusPreference
::create($statusPref);
99 public function __destruct() {
106 public function executeJobByAction($entity, $action) {
107 $job = $this->_getJob(NULL, $entity, $action);
108 $this->executeJob($job);
114 public function executeJobById($id) {
115 $job = $this->_getJob($id);
116 $this->executeJob($job);
120 * @param CRM_Core_ScheduledJob $job
122 public function executeJob($job) {
123 $this->currentJob
= $job;
125 // CRM-18231 check if non-production environment.
127 CRM_Core_BAO_Setting
::isAPIJobAllowedToRun($job->apiParams
);
129 catch (Exception
$e) {
130 $this->logEntry('Error while executing ' . $job->name
. ': ' . $e->getMessage());
131 $this->currentJob
= FALSE;
135 $this->logEntry('Starting execution of ' . $job->name
);
138 $singleRunParamsKey = strtolower($job->api_entity
. '_' . $job->api_action
);
140 if (array_key_exists($singleRunParamsKey, $this->singleRunParams
)) {
141 $params = $this->singleRunParams
[$singleRunParamsKey];
144 $params = $job->apiParams
;
147 CRM_Utils_Hook
::preJob($job, $params);
149 $result = civicrm_api($job->api_entity
, $job->api_action
, $params);
151 catch (Exception
$e) {
152 $this->logEntry('Error while executing ' . $job->name
. ': ' . $e->getMessage());
155 CRM_Utils_Hook
::postJob($job, $params, $result);
156 $this->logEntry('Finished execution of ' . $job->name
. ' with result: ' . $this->_apiResultToMessage($result));
157 $this->currentJob
= FALSE;
159 //Disable outBound option after executing the job.
160 $environment = CRM_Core_Config
::environment(NULL, TRUE);
161 if ($environment != 'Production' && !empty($job->apiParams
['runInNonProductionEnvironment'])) {
162 Civi
::settings()->set('mailing_backend', ['outBound_option' => CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
]);
167 * Retrieves the list of jobs from the database,
168 * populates class param.
171 * ($id => CRM_Core_ScheduledJob)
173 private function _getJobs() {
175 $dao = new CRM_Core_DAO_Job();
176 $dao->orderBy('name');
177 $dao->domain_id
= CRM_Core_Config
::domainID();
179 while ($dao->fetch()) {
181 CRM_Core_DAO
::storeValues($dao, $temp);
182 $jobs[$dao->id
] = new CRM_Core_ScheduledJob($temp);
188 * Retrieves specific job from the database by id.
189 * and creates ScheduledJob object.
192 * @param null $entity
193 * @param null $action
195 * @return CRM_Core_ScheduledJob
198 private function _getJob($id = NULL, $entity = NULL, $action = NULL) {
199 if (is_null($id) && is_null($action)) {
200 CRM_Core_Error
::fatal('You need to provide either id or name to use this method');
202 $dao = new CRM_Core_DAO_Job();
204 $dao->api_entity
= $entity;
205 $dao->api_action
= $action;
207 while ($dao->fetch()) {
208 CRM_Core_DAO
::storeValues($dao, $temp);
209 $job = new CRM_Core_ScheduledJob($temp);
217 * @param array $params
218 * @param null $source
220 public function setSingleRunParams($entity, $job, $params, $source = NULL) {
221 $this->_source
= $source;
222 $key = strtolower($entity . '_' . $job);
223 $this->singleRunParams
[$key] = $params;
224 $this->singleRunParams
[$key]['version'] = 3;
228 * @param string $message
230 public function logEntry($message) {
231 $domainID = CRM_Core_Config
::domainID();
232 $dao = new CRM_Core_DAO_JobLog();
234 $dao->domain_id
= $domainID;
237 * The description is a summary of the message.
238 * HTML tags are stripped from the message.
239 * The description is limited to 240 characters
240 * and has an ellipsis added if it is truncated.
242 $maxDescription = 240;
243 $ellipsis = " (...)";
244 $description = strip_tags($message);
245 if (strlen($description) > $maxDescription) {
246 $description = substr($description, 0, $maxDescription - strlen($ellipsis)) . $ellipsis;
248 $dao->description
= $description;
250 if ($this->currentJob
) {
251 $dao->job_id
= $this->currentJob
->id
;
252 $dao->name
= $this->currentJob
->name
;
253 $dao->command
= ts("Entity:") . " " . $this->currentJob
->api_entity
. " " . ts("Action:") . " " . $this->currentJob
->api_action
;
255 if (!empty($this->currentJob
->parameters
)) {
256 $data .= "\n\nParameters raw (from db settings): \n" . $this->currentJob
->parameters
;
258 $singleRunParamsKey = strtolower($this->currentJob
->api_entity
. '_' . $this->currentJob
->api_action
);
259 if (array_key_exists($singleRunParamsKey, $this->singleRunParams
)) {
260 $data .= "\n\nParameters raw (" . $this->_source
. "): \n" . serialize($this->singleRunParams
[$singleRunParamsKey]);
261 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->singleRunParams
[$singleRunParamsKey]);
264 $data .= "\n\nParameters parsed (and passed to API method): \n" . serialize($this->currentJob
->apiParams
);
267 $data .= "\n\nFull message: \n" . $message;
279 private function _apiResultToMessage($apiResult) {
280 $status = $apiResult['is_error'] ?
ts('Failure') : ts('Success');
281 $msg = CRM_Utils_Array
::value('error_message', $apiResult, 'empty error_message!');
282 $vals = CRM_Utils_Array
::value('values', $apiResult, 'empty values!');
283 if (is_array($msg)) {
284 $msg = serialize($msg);
286 if (is_array($vals)) {
287 $vals = serialize($vals);
289 $message = $apiResult['is_error'] ?
', Error message: ' . $msg : " (" . $vals . ")";
290 return $status . $message;
300 function CRM_Core_JobManager_scheduledJobFatalErrorHandler($message) {
301 throw new Exception("{$message['message']}: {$message['code']}");