Merge pull request #4913 from colemanw/INFRA-132
[civicrm-core.git] / CRM / Custom / Form / Group.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * form to process actions on the set aspect of Custom Data
38 */
39 class CRM_Custom_Form_Group extends CRM_Core_Form {
40
41 /**
42 * The set id saved to the session for an update
43 *
44 * @var int
45 */
46 protected $_id;
47
48 /**
49 * set is empty or not
50 *
51 * @var bool
52 */
53 protected $_isGroupEmpty = TRUE;
54
55 /**
56 * Array of existing subtypes set for a custom set
57 *
58 * @var array
59 */
60 protected $_subtypes = array();
61
62 /**
63 * Array of default params
64 *
65 * @var array
66 */
67 protected $_defaults = array();
68
69 /**
70 * Set variables up before form is built
71 *
72 * @param null
73 *
74 * @return void
75 */
76 public function preProcess() {
77 // current set id
78 $this->_id = $this->get('id');
79
80 if ($this->_id && $isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_id, 'is_reserved', 'id')) {
81 CRM_Core_Error::fatal("You cannot edit the settings of a reserved custom field-set.");
82 }
83 // setting title for html page
84 if ($this->_action == CRM_Core_Action::UPDATE) {
85 $title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
86 CRM_Utils_System::setTitle(ts('Edit %1', array(1 => $title)));
87 }
88 elseif ($this->_action == CRM_Core_Action::VIEW) {
89 $title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
90 CRM_Utils_System::setTitle(ts('Preview %1', array(1 => $title)));
91 }
92 else {
93 CRM_Utils_System::setTitle(ts('New Custom Field Set'));
94 }
95
96 if (isset($this->_id)) {
97 $params = array('id' => $this->_id);
98 CRM_Core_BAO_CustomGroup::retrieve($params, $this->_defaults);
99
100 $subExtends = CRM_Utils_Array::value('extends_entity_column_value', $this->_defaults);
101 if (!empty($subExtends)) {
102 $this->_subtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($subExtends, 1, -1));
103 }
104 }
105 }
106
107 /**
108 * Global form rule
109 *
110 * @param array $fields
111 * The input form values.
112 * @param array $files
113 * The uploaded files if any.
114 * @param $self
115 *
116 *
117 * @return bool|array
118 * true if no errors, else array of errors
119 */
120 public static function formRule($fields, $files, $self) {
121 $errors = array();
122
123 //validate group title as well as name.
124 $title = $fields['title'];
125 $name = CRM_Utils_String::munge($title, '_', 64);
126 $query = 'select count(*) from civicrm_custom_group where ( name like %1 OR title like %2 ) and id != %3';
127 $grpCnt = CRM_Core_DAO::singleValueQuery($query, array(
128 1 => array($name, 'String'),
129 2 => array($title, 'String'),
130 3 => array((int) $self->_id, 'Integer'),
131 ));
132 if ($grpCnt) {
133 $errors['title'] = ts('Custom group \'%1\' already exists in Database.', array(1 => $title));
134 }
135
136 if (!empty($fields['extends'][1])) {
137 if (in_array('', $fields['extends'][1]) && count($fields['extends'][1]) > 1) {
138 $errors['extends'] = ts("Cannot combine other option with 'Any'.");
139 }
140 }
141
142 if (empty($fields['extends'][0])) {
143 $errors['extends'] = ts("You need to select the type of record that this set of custom fields is applicable for.");
144 }
145
146 $extends = array('Activity', 'Relationship', 'Group', 'Contribution', 'Membership', 'Event', 'Participant');
147 if (in_array($fields['extends'][0], $extends) && $fields['style'] == 'Tab') {
148 $errors['style'] = ts("Display Style should be Inline for this Class");
149 $self->assign('showStyle', TRUE);
150 }
151
152 if (!empty($fields['is_multiple'])) {
153 $self->assign('showMultiple', TRUE);
154 }
155
156 if (empty($fields['is_multiple']) && $fields['style'] == 'Tab with table') {
157 $errors['style'] = ts("Display Style 'Tab with table' is only supported for multiple-record custom field sets.");
158 }
159
160 //checks the given custom set doesnot start with digit
161 $title = $fields['title'];
162 if (!empty($title)) {
163 // gives the ascii value
164 $asciiValue = ord($title{0});
165 if ($asciiValue >= 48 && $asciiValue <= 57) {
166 $errors['title'] = ts("Name cannot not start with a digit");
167 }
168 }
169
170 return empty($errors) ? TRUE : $errors;
171 }
172
173 /**
174 * add the rules (mainly global rules) for form.
175 * All local rules are added near the element
176 *
177 * @param null
178 *
179 * @return void
180 * @see valid_date
181 */
182 public function addRules() {
183 $this->addFormRule(array('CRM_Custom_Form_Group', 'formRule'), $this);
184 }
185
186 /**
187 * Build the form object
188 *
189 * @param null
190 *
191 * @return void
192 */
193 public function buildQuickForm() {
194 $this->applyFilter('__ALL__', 'trim');
195
196 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_CustomGroup');
197
198 //title
199 $this->add('text', 'title', ts('Set Name'), $attributes['title'], TRUE);
200
201 //Fix for code alignment, CRM-3058
202 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
203 $this->assign('contactTypes', json_encode($contactTypes));
204
205 $sel1 = array("" => "- select -") + CRM_Core_SelectValues::customGroupExtends();
206 $sel2 = array();
207 $activityType = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
208
209 $eventType = CRM_Core_OptionGroup::values('event_type');
210 $grantType = CRM_Core_OptionGroup::values('grant_type');
211 $campaignTypes = CRM_Campaign_PseudoConstant::campaignType();
212 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
213 $participantRole = CRM_Core_OptionGroup::values('participant_role');
214 $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
215 $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
216 $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household');
217
218 ksort($sel1);
219 asort($activityType);
220 asort($eventType);
221 asort($grantType);
222 asort($membershipType);
223 asort($participantRole);
224 $allRelationshipType = array();
225 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
226 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
227
228 //adding subtype specific relationships CRM-5256
229 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
230
231 foreach ($subTypes as $subType => $val) {
232 $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'],
233 FALSE, 'label', TRUE, $subType
234 );
235 $allRelationshipType = array_merge($allRelationshipType, $subTypeRelationshipTypes);
236 }
237
238 $sel2['Event'] = $eventType;
239 $sel2['Grant'] = $grantType;
240 $sel2['Activity'] = $activityType;
241 $sel2['Campaign'] = $campaignTypes;
242 $sel2['Membership'] = $membershipType;
243 $sel2['ParticipantRole'] = $participantRole;
244 $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
245 $sel2['ParticipantEventType'] = $eventType;
246 $sel2['Contribution'] = CRM_Contribute_PseudoConstant::financialType();
247 $sel2['Relationship'] = $allRelationshipType;
248
249 $sel2['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL);
250 $sel2['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL);
251 $sel2['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL);
252
253 CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($sel2);
254
255 foreach ($sel2 as $main => $sub) {
256 if (!empty($sel2[$main])) {
257 if ($main == 'Relationship') {
258 $relName = self::getFormattedList($sel2[$main]);
259 $sel2[$main] = array(
260 '' => ts("- Any -")
261 ) + $relName;
262 }
263 else {
264 $sel2[$main] = array(
265 '' => ts("- Any -")
266 ) + $sel2[$main];
267 }
268 }
269 }
270
271 $cSubTypes = CRM_Core_Component::contactSubTypes();
272
273 if (!empty($cSubTypes)) {
274 $contactSubTypes = array();
275 foreach ($cSubTypes as $key => $value) {
276 $contactSubTypes[$key] = $key;
277 }
278 $sel2['Contact'] = array(
279 "" => "-- Any --"
280 ) + $contactSubTypes;
281 }
282 else {
283 if (!isset($this->_id)) {
284 $formName = 'document.forms.' . $this->_name;
285
286 $js = "<script type='text/javascript'>\n";
287 $js .= "{$formName}['extends_1'].style.display = 'none';\n";
288 $js .= "</script>";
289 $this->assign('initHideBlocks', $js);
290 }
291 }
292
293 $sel = &$this->add('hierselect',
294 'extends',
295 ts('Used For'),
296 array(
297 'name' => 'extends[0]',
298 'style' => 'vertical-align: top;',
299 ),
300 TRUE
301 );
302 $sel->setOptions(array($sel1, $sel2));
303 if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
304 // make second selector a multi-select -
305 $sel->_elements[1]->setMultiple(TRUE);
306 $sel->_elements[1]->setSize(5);
307 }
308 if ($this->_action == CRM_Core_Action::UPDATE) {
309 $subName = CRM_Utils_Array::value('extends_entity_column_id', $this->_defaults);
310 if ($this->_defaults['extends'] == 'Participant') {
311 if ($subName == 1) {
312 $this->_defaults['extends'] = 'ParticipantRole';
313 }
314 elseif ($subName == 2) {
315 $this->_defaults['extends'] = 'ParticipantEventName';
316 }
317 elseif ($subName == 3) {
318 $this->_defaults['extends'] = 'ParticipantEventType';
319 }
320 }
321
322 //allow to edit settings if custom set is empty CRM-5258
323 $this->_isGroupEmpty = CRM_Core_BAO_CustomGroup::isGroupEmpty($this->_id);
324 if (!$this->_isGroupEmpty) {
325 if (!empty($this->_subtypes)) {
326 // we want to allow adding / updating subtypes for this case,
327 // and therefore freeze the first selector only.
328 $sel->_elements[0]->freeze();
329 }
330 else {
331 // freeze both the selectors
332 $sel->freeze();
333 }
334 }
335 $this->assign('isCustomGroupEmpty', $this->_isGroupEmpty);
336 $this->assign('gid', $this->_id);
337 }
338 $this->assign('defaultSubtypes', json_encode($this->_subtypes));
339
340 // help text
341 $this->addWysiwyg('help_pre', ts('Pre-form Help'), $attributes['help_pre']);
342 $this->addWysiwyg('help_post', ts('Post-form Help'), $attributes['help_post']);
343
344 // weight
345 $this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE);
346 $this->addRule('weight', ts('is a numeric field'), 'numeric');
347
348 // display style
349 $this->add('select', 'style', ts('Display Style'), CRM_Core_SelectValues::customGroupStyle());
350
351 // is this set collapsed or expanded ?
352 $this->addElement('checkbox', 'collapse_display', ts('Collapse this set on initial display'));
353
354 // is this set collapsed or expanded ? in advanced search
355 $this->addElement('checkbox', 'collapse_adv_display', ts('Collapse this set in Advanced Search'));
356
357 // is this set active ?
358 $this->addElement('checkbox', 'is_active', ts('Is this Custom Data Set active?'));
359
360 // does this set have multiple record?
361 $multiple = $this->addElement('checkbox', 'is_multiple',
362 ts('Does this Custom Field Set allow multiple records?'), NULL);
363
364 // $min_multiple = $this->add('text', 'min_multiple', ts('Minimum number of multiple records'), $attributes['min_multiple'] );
365 // $this->addRule('min_multiple', ts('is a numeric field') , 'numeric');
366
367 $max_multiple = $this->add('text', 'max_multiple', ts('Maximum number of multiple records'), $attributes['max_multiple']);
368 $this->addRule('max_multiple', ts('is a numeric field'), 'numeric');
369
370 //allow to edit settings if custom set is empty CRM-5258
371 $this->assign('isGroupEmpty', $this->_isGroupEmpty);
372 if (!$this->_isGroupEmpty) {
373 $multiple->freeze();
374 //$min_multiple->freeze();
375 $max_multiple->freeze();
376 }
377
378 $this->assign('showStyle', FALSE);
379 $this->assign('showMultiple', FALSE);
380 $buttons = array(
381 array(
382 'type' => 'next',
383 'name' => ts('Save'),
384 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
385 'isDefault' => TRUE,
386 ),
387 array(
388 'type' => 'cancel',
389 'name' => ts('Cancel'),
390 ),
391 );
392 if (!$this->_isGroupEmpty && !empty($this->_subtypes)) {
393 $buttons[0]['js'] = array('onclick' => "return warnDataLoss()");
394 }
395 $this->addButtons($buttons);
396
397 // views are implemented as frozen form
398 if ($this->_action & CRM_Core_Action::VIEW) {
399 $this->freeze();
400 $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"));
401 }
402 }
403
404 /**
405 * Set default values for the form. Note that in edit/view mode
406 * the default values are retrieved from the database
407 *
408 * @param null
409 *
410 * @return array
411 * array of default values
412 */
413 public function setDefaultValues() {
414 $defaults = &$this->_defaults;
415 $this->assign('showMaxMultiple', TRUE);
416 if ($this->_action == CRM_Core_Action::ADD) {
417 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_CustomGroup');
418
419 $defaults['is_multiple'] = $defaults['min_multiple'] = 0;
420 $defaults['is_active'] = $defaults['collapse_display'] = 1;
421 $defaults['style'] = 'Inline';
422 }
423 elseif (empty($defaults['max_multiple']) && !$this->_isGroupEmpty) {
424 $this->assign('showMaxMultiple', FALSE);
425 }
426
427 if (($this->_action & CRM_Core_Action::UPDATE) && !empty($defaults['is_multiple'])) {
428 $defaults['collapse_display'] = 0;
429 }
430
431 if (isset($defaults['extends'])) {
432 $extends = $defaults['extends'];
433 unset($defaults['extends']);
434
435 $defaults['extends'][0] = $extends;
436
437 if (!empty($this->_subtypes)) {
438 $defaults['extends'][1] = $this->_subtypes;
439 }
440 else {
441 $defaults['extends'][1] = array(0 => '');
442 }
443
444 if ($extends == 'Relationship' && !empty($this->_subtypes)) {
445 $relationshipDefaults = array();
446 foreach ($defaults['extends'][1] as $donCare => $rel_type_id) {
447 $relationshipDefaults[] = $rel_type_id;
448 }
449
450 $defaults['extends'][1] = $relationshipDefaults;
451 }
452 }
453
454 return $defaults;
455 }
456
457 /**
458 * Process the form
459 *
460 * @param null
461 *
462 * @return void
463 */
464 public function postProcess() {
465 // get the submitted form values.
466 $params = $this->controller->exportValues('Group');
467 $params['overrideFKConstraint'] = 0;
468 if ($this->_action & CRM_Core_Action::UPDATE) {
469 $params['id'] = $this->_id;
470 if ($this->_defaults['extends'][0] != $params['extends'][0]) {
471 $params['overrideFKConstraint'] = 1;
472 }
473
474 if (!empty($this->_subtypes)) {
475 $subtypesToBeRemoved = array_diff($this->_subtypes, array_intersect($this->_subtypes, $params['extends'][1]));
476 CRM_Contact_BAO_ContactType::deleteCustomRowsOfSubtype($this->_id, $subtypesToBeRemoved);
477 }
478 }
479 elseif ($this->_action & CRM_Core_Action::ADD) {
480 //new custom set , so lets set the created_id
481 $session = CRM_Core_Session::singleton();
482 $params['created_id'] = $session->get('userID');
483 $params['created_date'] = date('YmdHis');
484 }
485
486 $group = CRM_Core_BAO_CustomGroup::create($params);
487
488 // reset the cache
489 CRM_Core_BAO_Cache::deleteGroup('contact fields');
490
491 if ($this->_action & CRM_Core_Action::UPDATE) {
492 CRM_Core_Session::setStatus(ts('Your custom field set \'%1 \' has been saved.', array(1 => $group->title)), ts('Saved'), 'success');
493 }
494 else {
495 // Jump directly to adding a field if popups are disabled
496 $action = CRM_Core_Resources::singleton()->ajaxPopupsEnabled ? '' : '/add';
497 $url = CRM_Utils_System::url("civicrm/admin/custom/group/field$action", 'reset=1&new=1&gid=' . $group->id . '&action=' . ($action ? 'add' : 'browse'));
498 CRM_Core_Session::setStatus(ts("Your custom field set '%1' has been added. You can add custom fields now.",
499 array(1 => $group->title)
500 ), ts('Saved'), 'success');
501 $session = CRM_Core_Session::singleton();
502 $session->replaceUserContext($url);
503 }
504
505 // prompt Drupal Views users to update $db_prefix in settings.php, if necessary
506 global $db_prefix;
507 $config = CRM_Core_Config::singleton();
508 if (is_array($db_prefix) && $config->userSystem->is_drupal && module_exists('views')) {
509 // get table_name for each custom group
510 $tables = array();
511 $sql = "SELECT table_name FROM civicrm_custom_group WHERE is_active = 1";
512 $result = CRM_Core_DAO::executeQuery($sql);
513 while ($result->fetch()) {
514 $tables[$result->table_name] = $result->table_name;
515 }
516
517 // find out which tables are missing from the $db_prefix array
518 $missingTableNames = array_diff_key($tables, $db_prefix);
519
520 if (!empty($missingTableNames)) {
521 CRM_Core_Session::setStatus(ts("To ensure that all of your custom data groups are available to Views, you may need to add the following key(s) to the db_prefix array in your settings.php file: '%1'.",
522 array(1 => implode(', ', $missingTableNames))
523 ), ts('Note'), 'info');
524 }
525 }
526 }
527
528 /**
529 * Return a formatted list of relationship name.
530 *
531 * @param array $list
532 * Array of relationship name.
533 *
534 * @return array
535 * Array of relationship name.
536 */
537 public static function getFormattedList(&$list) {
538 $relName = array();
539
540 foreach ($list as $listItemKey => $itemValue) {
541 // Extract the relationship ID.
542 $key = substr($listItemKey, 0, strpos($listItemKey, '_'));
543 if (isset($list["{$key}_b_a"])) {
544 $relName["$key"] = $list["{$key}_a_b"];
545 // Are the two labels different?
546 if ($list["{$key}_a_b"] != $list["{$key}_b_a"]) {
547 $relName["$key"] = $list["{$key}_a_b"] . ' / ' . $list["{$key}_b_a"];
548 }
549 unset($list["{$key}_b_a"]);
550 unset($list["{$key}_a_b"]);
551 }
552 else {
553 // If no '_b_a' label exists save the '_a_b' one and unset it from the list
554 $relName["{$key}"] = $list["{$key}_a_b"];
555 unset($list["{$key}_a_b"]);
556 }
557 }
558 return $relName;
559 }
560 }