(NFC) Update coding style in PCP, Pledge, Profile, Queue, Report folders
[civicrm-core.git] / CRM / Report / Form / Instance.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 * Class CRM_Report_Form_Instance
30 */
31 class CRM_Report_Form_Instance {
32
33 /**
34 * Build form.
35 *
36 * @param CRM_Core_Form $form
37 */
38 public static function buildForm(&$form) {
39 // We should not build form elements in dashlet mode.
40 if ($form->_section) {
41 return;
42 }
43
44 // Check role based permission.
45 $instanceID = $form->getVar('_id');
46 if ($instanceID && !CRM_Report_Utils_Report::isInstanceGroupRoleAllowed($instanceID)) {
47 $url = CRM_Utils_System::url('civicrm/report/list', 'reset=1');
48 CRM_Core_Error::statusBounce(ts('You do not have permission to access this report.'),
49 $url
50 );
51 }
52
53 $attributes = CRM_Core_DAO::getAttribute('CRM_Report_DAO_ReportInstance');
54
55 $form->add('text',
56 'title',
57 ts('Report Title'),
58 $attributes['title']
59 );
60
61 $form->add('text',
62 'description',
63 ts('Report Description'),
64 $attributes['description']
65 );
66
67 $form->add('text',
68 'email_subject',
69 ts('Subject'),
70 $attributes['email_subject']
71 );
72
73 $form->add('text',
74 'email_to',
75 ts('To'),
76 $attributes['email_to']
77 );
78
79 $form->add('text',
80 'email_cc',
81 ts('CC'),
82 $attributes['email_subject']
83 );
84
85 $form->add('number',
86 'row_count',
87 ts('Limit Dashboard Results'),
88 ['class' => 'four', 'min' => 1]
89 );
90
91 $form->add('textarea',
92 'report_header',
93 ts('Report Header'),
94 $attributes['header']
95 );
96
97 $form->add('textarea',
98 'report_footer',
99 ts('Report Footer'),
100 $attributes['footer']
101 );
102
103 $form->addElement('checkbox', 'is_navigation', ts('Include Report in Navigation Menu?'), NULL,
104 ['onclick' => "return showHideByValue('is_navigation','','navigation_menu','table-row','radio',false);"]
105 );
106
107 $form->addElement('select', 'view_mode', ts('Configure link to...'), [
108 'view' => ts('View Results'),
109 'criteria' => ts('Show Criteria'),
110 ]);
111
112 $form->addElement('checkbox', 'addToDashboard', ts('Available for Dashboard?'));
113 $form->add('number', 'cache_minutes', ts('Cache dashlet for'), ['class' => 'four', 'min' => 1]);
114 $form->addElement('checkbox', 'add_to_my_reports', ts('Add to My Reports?'), NULL);
115
116 $form->addElement('checkbox', 'is_reserved', ts('Reserved Report?'));
117 if (!CRM_Core_Permission::check('administer reserved reports')) {
118 $form->freeze('is_reserved');
119 }
120
121 $config = CRM_Core_Config::singleton();
122 if ($config->userFramework != 'Joomla' ||
123 $config->userFramework != 'WordPress'
124 ) {
125 $form->addElement('select',
126 'permission',
127 ts('Permission'),
128 ['0' => ts('Everyone (includes anonymous)')] + CRM_Core_Permission::basicPermissions()
129 );
130
131 // prepare user_roles to save as names not as ids
132 if (function_exists('user_roles')) {
133 $user_roles_array = user_roles();
134 foreach ($user_roles_array as $key => $value) {
135 $user_roles[$value] = $value;
136 }
137 $grouprole = &$form->addElement('advmultiselect',
138 'grouprole',
139 ts('ACL Group/Role'),
140 $user_roles,
141 [
142 'size' => 5,
143 'style' => 'width:240px',
144 'class' => 'advmultiselect',
145 ]
146 );
147 $grouprole->setButtonAttributes('add', ['value' => ts('Add >>')]);
148 $grouprole->setButtonAttributes('remove', ['value' => ts('<< Remove')]);
149 }
150 }
151
152 // navigation field
153 $parentMenu = CRM_Core_BAO_Navigation::getNavigationList();
154
155 $form->add('select', 'parent_id', ts('Parent Menu'), ['' => ts('- select -')] + $parentMenu);
156
157 // For now we only providing drilldown for one primary detail report only. In future this could be multiple reports
158 foreach ($form->_drilldownReport as $reportUrl => $drillLabel) {
159 $instanceList = CRM_Report_Utils_Report::getInstanceList($reportUrl);
160 if (count($instanceList) > 1) {
161 $form->add('select', 'drilldown_id', $drillLabel, ['' => ts('- select -')] + $instanceList);
162 }
163 break;
164 }
165
166 $form->addButtons([
167 [
168 'type' => 'submit',
169 'name' => ts('Save Report'),
170 'isDefault' => TRUE,
171 ],
172 [
173 'type' => 'cancel',
174 'name' => ts('Cancel'),
175 ],
176 ]);
177
178 $form->addFormRule(['CRM_Report_Form_Instance', 'formRule'], $form);
179 }
180
181 /**
182 * Add form rules.
183 *
184 * @param array $fields
185 * @param array $errors
186 * @param CRM_Report_Form_Instance $self
187 *
188 * @return array|bool
189 */
190 public static function formRule($fields, $errors, $self) {
191 // Validate both the "next" and "save" buttons for creating/updating a report.
192 $nextButton = $self->controller->getButtonName();
193 $saveButton = str_replace('_next', '_save', $nextButton);
194 $clickedButton = $self->getVar('_instanceButtonName');
195
196 $errors = [];
197 if ($clickedButton == $nextButton || $clickedButton == $saveButton) {
198 if (empty($fields['title'])) {
199 $errors['title'] = ts('Title is a required field.');
200 $self->assign('instanceFormError', TRUE);
201 }
202 }
203
204 return empty($errors) ? TRUE : $errors;
205 }
206
207 /**
208 * Set default values.
209 *
210 * @param CRM_Core_Form $form
211 * @param array $defaults
212 */
213 public static function setDefaultValues(&$form, &$defaults) {
214 // we should not build form elements in dashlet mode.
215 if ($form->_section) {
216 return;
217 }
218
219 $instanceID = $form->getVar('_id');
220 $navigationDefaults = [];
221
222 if (!isset($defaults['permission'])) {
223 $defaults['permission'] = 'access CiviReport';
224 }
225
226 $userFrameworkResourceURL = CRM_Core_Config::singleton()->userFrameworkResourceURL;
227
228 // Add a special region for the default HTML header of printed reports. It
229 // won't affect reports with customized headers, just ones with the default.
230 $printHeaderRegion = CRM_Core_Region::instance('default-report-header', FALSE);
231 $htmlHeader = ($printHeaderRegion) ? $printHeaderRegion->render('', FALSE) : '';
232
233 $defaults['report_header'] = $report_header = "<html>
234 <head>
235 <title>CiviCRM Report</title>
236 <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
237 <style type=\"text/css\">@import url({$userFrameworkResourceURL}css/print.css);</style>
238 {$htmlHeader}
239 </head>
240 <body><div id=\"crm-container\">";
241
242 $defaults['report_footer'] = $report_footer = "<p><img src=\"{$userFrameworkResourceURL}i/powered_by.png\" /></p></div></body>
243 </html>
244 ";
245
246 // CRM-17225 view_mode currently supports 'view' or 'criteria'.
247 // Prior to 4.7 'view' meant reset=1 in the url & if not set
248 // then show criteria.
249 // From 4.7 we will pro-actively set 'force=1' but still respect the old behaviour.
250 // we may look to add pdf, print_view, csv & various charts as these could simply
251 // be added to the url allowing us to conceptualise 'view right now' vs saved view
252 // & using a multiselect (option value?) could help here.
253 // Note that accessing reports without reset=1 in the url turns out to be
254 // dangerous as it seems to carry actions like 'delete' from one report to another.
255 $defaults['view_mode'] = 'view';
256 $output = CRM_Utils_Request::retrieve('output', 'String');
257 if ($output == 'criteria') {
258 $defaults['view_mode'] = 'criteria';
259 }
260
261 if (empty($defaults['cache_minutes'])) {
262 $defaults['cache_minutes'] = '60';
263 }
264
265 if ($instanceID) {
266 // this is already retrieved via Form.php
267 $defaults['description'] = CRM_Utils_Array::value('description', $defaults);
268 if (!empty($defaults['header'])) {
269 $defaults['report_header'] = $defaults['header'];
270 }
271 if (!empty($defaults['footer'])) {
272 $defaults['report_footer'] = $defaults['footer'];
273 }
274
275 // CRM-17310 private reports option.
276 $defaults['add_to_my_reports'] = 0;
277 if (CRM_Utils_Array::value('owner_id', $defaults) != NULL) {
278 $defaults['add_to_my_reports'] = 1;
279 }
280
281 if (!empty($defaults['navigation_id'])) {
282 // Get the default navigation parent id.
283 $params = ['id' => $defaults['navigation_id']];
284 CRM_Core_BAO_Navigation::retrieve($params, $navigationDefaults);
285 $defaults['is_navigation'] = 1;
286 $defaults['parent_id'] = CRM_Utils_Array::value('parent_id', $navigationDefaults);
287 if (!empty($navigationDefaults['is_active'])) {
288 $form->assign('is_navigation', TRUE);
289 }
290 // A saved view mode will over-ride any url assumptions.
291 if (strpos($navigationDefaults['url'], 'output=criteria')) {
292 $defaults['view_mode'] = 'criteria';
293 }
294
295 if (!empty($navigationDefaults['id'])) {
296 $form->_navigation['id'] = $navigationDefaults['id'];
297 $form->_navigation['parent_id'] = !empty($navigationDefaults['parent_id']) ?
298 $navigationDefaults['parent_id'] : NULL;
299 }
300 }
301
302 if (!empty($defaults['grouprole'])) {
303 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['grouprole']) as $value) {
304 $groupRoles[] = $value;
305 }
306 $defaults['grouprole'] = $groupRoles;
307 }
308 }
309 elseif (property_exists($form, '_description')) {
310 $defaults['description'] = $form->_description;
311 }
312 }
313
314 /**
315 * Post process function.
316 *
317 * @param CRM_Core_Form $form
318 * @param bool $redirect
319 */
320 public static function postProcess(&$form, $redirect = TRUE) {
321 $params = $form->getVar('_params');
322 $instanceID = $form->getVar('_id');
323
324 if ($isNew = $form->getVar('_createNew')) {
325 // set the report_id since base template is going to be same, and we going to unset $instanceID
326 // which will make it difficult later on, to compute report_id
327 $params['report_id'] = CRM_Report_Utils_Report::getValueFromUrl($instanceID);
328 // Unset $instanceID so a new copy would be created.
329 $instanceID = NULL;
330 }
331 $params['instance_id'] = $instanceID;
332 if (!empty($params['is_navigation'])) {
333 $params['navigation'] = $form->_navigation;
334 }
335 elseif ($instanceID) {
336 // Delete navigation if exists.
337 $navId = CRM_Core_DAO::getFieldValue('CRM_Report_DAO_ReportInstance', $instanceID, 'navigation_id', 'id');
338 if ($navId) {
339 CRM_Core_BAO_Navigation::processDelete($navId);
340 CRM_Core_BAO_Navigation::resetNavigation();
341 }
342 }
343
344 // make a copy of params
345 $formValues = $params;
346
347 // unset params from $formValues that doesn't match with DB columns of instance tables, and also not required in form-values for sure
348 $unsetFields = [
349 'title',
350 'to_emails',
351 'cc_emails',
352 'header',
353 'footer',
354 'qfKey',
355 'id',
356 '_qf_default',
357 'report_header',
358 'report_footer',
359 'grouprole',
360 'task',
361 ];
362 foreach ($unsetFields as $field) {
363 unset($formValues[$field]);
364 }
365 $view_mode = $formValues['view_mode'];
366
367 // CRM-17310 my reports functionality - we should set owner if the checkbox is 1,
368 // it seems to be not set at all if unchecked.
369 if (!empty($formValues['add_to_my_reports'])) {
370 $params['owner_id'] = CRM_Core_Session::getLoggedInContactID();
371 }
372 else {
373 $params['owner_id'] = 'null';
374 }
375 unset($formValues['add_to_my_reports']);
376
377 // pass form_values as string
378 $params['form_values'] = serialize($formValues);
379
380 $instance = CRM_Report_BAO_ReportInstance::create($params);
381 $form->set('id', $instance->id);
382
383 if ($instanceID && !$isNew) {
384 // updating existing instance
385 $statusMsg = ts('"%1" report has been updated.', [1 => $instance->title]);
386 }
387 elseif ($form->getVar('_id') && $isNew) {
388 $statusMsg = ts('Your report has been successfully copied as "%1". You are currently viewing the new copy.', [1 => $instance->title]);
389 }
390 else {
391 $statusMsg = ts('"%1" report has been successfully created. You are currently viewing the new report instance.', [1 => $instance->title]);
392 }
393 CRM_Core_Session::setStatus($statusMsg);
394
395 if ($redirect) {
396 $urlParams = ['reset' => 1];
397 if ($view_mode == 'view') {
398 $urlParams['force'] = 1;
399 }
400 else {
401 $urlParams['output'] = 'criteria';
402 }
403 CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/report/instance/{$instance->id}", $urlParams));
404 }
405 }
406
407 }