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