Cleanup variables in event/contribution register forms
[civicrm-core.git] / CRM / Admin / Form / Job.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Class for configuring jobs.
20 */
21 class CRM_Admin_Form_Job extends CRM_Admin_Form {
22 public $_id = NULL;
23
24 public function preProcess() {
25
26 parent::preProcess();
27
28 CRM_Utils_System::setTitle(ts('Manage - Scheduled Jobs'));
29
30 if ($this->_id) {
31 $refreshURL = CRM_Utils_System::url('civicrm/admin/job',
32 "reset=1&action=update&id={$this->_id}",
33 FALSE, NULL, FALSE
34 );
35 }
36 else {
37 $refreshURL = CRM_Utils_System::url('civicrm/admin/job',
38 "reset=1&action=add",
39 FALSE, NULL, FALSE
40 );
41 }
42
43 $this->assign('refreshURL', $refreshURL);
44 }
45
46 /**
47 * Build the form object.
48 *
49 * @param bool $check
50 */
51 public function buildQuickForm($check = FALSE) {
52 parent::buildQuickForm();
53
54 if ($this->_action & CRM_Core_Action::DELETE) {
55 return;
56 }
57
58 if ($this->_action & CRM_Core_Action::VIEW) {
59 $this->assign('jobName', self::getJobName($this->_id));
60 $this->addButtons([
61 [
62 'type' => 'submit',
63 'name' => ts('Execute'),
64 'isDefault' => TRUE,
65 ],
66 [
67 'type' => 'cancel',
68 'name' => ts('Cancel'),
69 ],
70 ]);
71 return;
72 }
73
74 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Job');
75
76 $this->add('text', 'name', ts('Name'),
77 $attributes['name'], TRUE
78 );
79
80 $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', [
81 'CRM_Core_DAO_Job',
82 $this->_id,
83 ]);
84
85 $this->add('text', 'description', ts('Description'),
86 $attributes['description']
87 );
88
89 $this->add('text', 'api_entity', ts('API Call Entity'),
90 $attributes['api_entity'], TRUE
91 );
92
93 $this->add('text', 'api_action', ts('API Call Action'),
94 $attributes['api_action'], TRUE
95 );
96
97 $this->add('select', 'run_frequency', ts('Run frequency'), CRM_Core_SelectValues::getJobFrequency());
98
99 // CRM-17686
100 $this->add('datepicker', 'scheduled_run_date', ts('Scheduled Run Date'), NULL, FALSE, ['minDate' => time()]);
101
102 $this->add('textarea', 'parameters', ts('Command parameters'),
103 "cols=50 rows=6"
104 );
105
106 // is this job active ?
107 $this->add('checkbox', 'is_active', ts('Is this Scheduled Job active?'));
108
109 $this->addFormRule(['CRM_Admin_Form_Job', 'formRule']);
110 }
111
112 /**
113 * @param $fields
114 *
115 * @return array|bool
116 * @throws API_Exception
117 */
118 public static function formRule($fields) {
119
120 $errors = [];
121
122 require_once 'api/api.php';
123
124 /** @var \Civi\API\Kernel $apiKernel */
125 $apiKernel = \Civi::service('civi_api_kernel');
126 $apiRequest = \Civi\API\Request::create($fields['api_entity'], $fields['api_action'], ['version' => 3]);
127 try {
128 $apiKernel->resolve($apiRequest);
129 }
130 catch (\Civi\API\Exception\NotImplementedException $e) {
131 $errors['api_action'] = ts('Given API command is not defined.');
132 }
133
134 if (!empty($errors)) {
135 return $errors;
136 }
137
138 return empty($errors) ? TRUE : $errors;
139 }
140
141 /**
142 * @return array
143 */
144 public function setDefaultValues() {
145 $defaults = [];
146
147 if (!$this->_id) {
148 $defaults['is_active'] = $defaults['is_default'] = 1;
149 return $defaults;
150 }
151 $domainID = CRM_Core_Config::domainID();
152
153 $dao = new CRM_Core_DAO_Job();
154 $dao->id = $this->_id;
155 $dao->domain_id = $domainID;
156 if (!$dao->find(TRUE)) {
157 return $defaults;
158 }
159
160 CRM_Core_DAO::storeValues($dao, $defaults);
161
162 // CRM-17686
163 if (!empty($dao->scheduled_run_date)) {
164 $ts = strtotime($dao->scheduled_run_date);
165 $defaults['scheduled_run_date'] = date("Y-m-d H:i:s", $ts);
166 }
167
168 // CRM-10708
169 // job entity thats shipped with core is all lower case.
170 // this makes sure camel casing is followed for proper working of default population.
171 if (!empty($defaults['api_entity'])) {
172 $defaults['api_entity'] = ucfirst($defaults['api_entity']);
173 }
174
175 return $defaults;
176 }
177
178 /**
179 * Process the form submission.
180 */
181 public function postProcess() {
182
183 CRM_Utils_System::flushCache();
184
185 if ($this->_action & CRM_Core_Action::DELETE) {
186 CRM_Core_BAO_Job::del($this->_id);
187 CRM_Core_Session::setStatus("", ts('Scheduled Job Deleted.'), "success");
188 return;
189 }
190
191 // using View action for Execute. Doh.
192 if ($this->_action & CRM_Core_Action::VIEW) {
193 $jm = new CRM_Core_JobManager();
194 $jm->executeJobById($this->_id);
195 $jobName = self::getJobName($this->_id);
196 CRM_Core_Session::setStatus(ts('%1 Scheduled Job has been executed. See the log for details.', [1 => $jobName]), ts("Executed"), "success");
197 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/job', 'reset=1'));
198 return;
199 }
200
201 $values = $this->controller->exportValues($this->_name);
202 $domainID = CRM_Core_Config::domainID();
203
204 $dao = new CRM_Core_DAO_Job();
205
206 $dao->id = $this->_id;
207 $dao->domain_id = $domainID;
208 $dao->run_frequency = $values['run_frequency'];
209 $dao->parameters = $values['parameters'];
210 $dao->name = $values['name'];
211 $dao->api_entity = $values['api_entity'];
212 $dao->api_action = $values['api_action'];
213 $dao->description = $values['description'];
214 $dao->is_active = CRM_Utils_Array::value('is_active', $values, 0);
215
216 // CRM-17686
217 $ts = strtotime($values['scheduled_run_date']);
218 // if a date/time is supplied and not in the past, then set the next scheduled run...
219 if ($ts > time()) {
220 $dao->scheduled_run_date = CRM_Utils_Date::currentDBDate($ts);
221 // warn about monthly/quarterly scheduling, if applicable
222 if (($dao->run_frequency == 'Monthly') || ($dao->run_frequency == 'Quarter')) {
223 $info = getdate($ts);
224 if ($info['mday'] > 28) {
225 CRM_Core_Session::setStatus(
226 ts('Relative month values are calculated based on the length of month(s) that they pass through.
227 The result will land on the same day of the month except for days 29-31 when the target month contains fewer days than the previous month.
228 For example, if a job is scheduled to run on August 31st, the following invocation will occur on October 1st, and then the 1st of every month thereafter.
229 To avoid this issue, please schedule Monthly and Quarterly jobs to run within the first 28 days of the month.'),
230 ts('Warning'), 'info', ['expires' => 0]);
231 }
232 }
233 }
234 // ...otherwise, if this isn't a new scheduled job, clear the next scheduled run
235 elseif ($dao->id) {
236 $job = new CRM_Core_ScheduledJob(['id' => $dao->id]);
237 $job->clearScheduledRunDate();
238 }
239
240 $dao->save();
241
242 // CRM-11143 - Give warning message if update_greetings is Enabled (is_active) since it generally should not be run automatically via execute action or runjobs url.
243 if ($values['api_action'] == 'update_greeting' && CRM_Utils_Array::value('is_active', $values) == 1) {
244 $docLink = CRM_Utils_System::docURL2("user/initial-set-up/scheduled-jobs/#job_update_greeting");
245 $msg = ts('The update greeting job can be very resource intensive and is typically not necessary to run on a regular basis. If you do choose to enable the job, we recommend you do not run it with the force=1 option, which would rebuild greetings on all records. Leaving that option absent, or setting it to force=0, will only rebuild greetings for contacts that do not currently have a value stored. %1', [1 => $docLink]);
246 CRM_Core_Session::setStatus($msg, ts('Warning: Update Greeting job enabled'), 'alert');
247 }
248
249 }
250
251 /**
252 * Get the API action aka Job Name for this scheduled job
253 * @param int $id - Id of the stored Job
254 *
255 * @return string
256 */
257 private static function getJobName($id) {
258 $entity = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Job', $id, 'api_entity');
259 $action = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Job', $id, 'api_action');
260 $name = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Job', $id, 'name');
261 return $name . ' (' . $entity . '.' . $action . ')';
262 }
263
264 }