Merge pull request #1014 from colemanw/importParser
[civicrm-core.git] / CRM / Custom / Form / Group.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 * @access protected
46 */
47 protected $_id;
48
49 /**
50 * set is empty or not
51 *
52 * @var bool
53 * @access protected
54 */
55 protected $_isGroupEmpty = TRUE;
56
57 /**
58 * array of existing subtypes set for a custom set
59 *
60 * @var array
61 * @access protected
62 */
63 protected $_subtypes = array();
64
65 /**
66 * array of default params
67 *
68 * @var array
69 * @access protected
70 */
71 protected $_defaults = array();
72
73 /**
74 * Function to set variables up before form is built
75 *
76 * @param null
77 *
78 * @return void
79 * @access public
80 */
81 public function preProcess() {
82 // current set id
83 $this->_id = $this->get('id');
84
85 if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_id, 'is_reserved', 'id')) {
86 CRM_Core_Error::fatal("You cannot edit the settings of a reserved custom field-set.");
87 }
88 // setting title for html page
89 if ($this->_action == CRM_Core_Action::UPDATE) {
90 $title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
91 CRM_Utils_System::setTitle(ts('Edit %1', array(1 => $title)));
92 }
93 elseif ($this->_action == CRM_Core_Action::VIEW) {
94 $title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
95 CRM_Utils_System::setTitle(ts('Preview %1', array(1 => $title)));
96 }
97 else {
98 CRM_Utils_System::setTitle(ts('New Custom Field Set'));
99 }
100
101 if (isset($this->_id)) {
102 $params = array('id' => $this->_id);
103 CRM_Core_BAO_CustomGroup::retrieve($params, $this->_defaults);
104
105 $subExtends = CRM_Utils_Array::value('extends_entity_column_value', $this->_defaults);
106 if (!empty($subExtends)) {
107 $this->_subtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($subExtends, 1, -1));
108 }
109 }
110 }
111
112 /**
113 * global form rule
114 *
115 * @param array $fields the input form values
116 * @param array $files the uploaded files if any
117 * @param array $options additional user data
118 *
119 * @return true if no errors, else array of errors
120 * @access public
121 * @static
122 */
123 static function formRule($fields, $files, $self) {
124 $errors = array();
125
126 //validate group title as well as name.
127 $title = $fields['title'];
128 $name = CRM_Utils_String::munge($title, '_', 64);
129 $query = 'select count(*) from civicrm_custom_group where ( name like %1 OR title like %2 ) and id != %3';
130 $grpCnt = CRM_Core_DAO::singleValueQuery($query, array(1 => array($name, 'String'),
131 2 => array($title, 'String'),
132 3 => array((int)$self->_id, 'Integer'),
133 ));
134 if ($grpCnt) {
135 $errors['title'] = ts('Custom group \'%1\' already exists in Database.', array(1 => $title));
136 }
137
138 if (CRM_Utils_Array::value(1, $fields['extends'])) {
139 if (in_array('', $fields['extends'][1]) && count($fields['extends'][1]) > 1) {
140 $errors['extends'] = ts("Cannot combine other option with 'Any'.");
141 }
142 }
143
144 if (empty($fields['extends'][0])) {
145 $errors['extends'] = ts("You need to select the type of record that this set of custom fields is applicable for.");
146 }
147
148 $extends = array('Activity', 'Relationship', 'Group', 'Contribution', 'Membership', 'Event', 'Participant');
149 if (in_array($fields['extends'][0], $extends) && $fields['style'] == 'Tab') {
150 $errors['style'] = ts("Display Style should be Inline for this Class");
151 $self->assign('showStyle', TRUE);
152 }
153
154 if (CRM_Utils_Array::value('is_multiple', $fields)) {
155 $self->assign('showMultiple', TRUE);
156 }
157
158 //checks the given custom set doesnot start with digit
159 $title = $fields['title'];
160 if (!empty($title)) {
161 // gives the ascii value
162 $asciiValue = ord($title{0});
163 if ($asciiValue >= 48 && $asciiValue <= 57) {
164 $errors['title'] = ts("Set's Name should not start with digit");
165 }
166 }
167
168 return empty($errors) ? TRUE : $errors;
169 }
170
171 /**
172 * This function is used to add the rules (mainly global rules) for form.
173 * All local rules are added near the element
174 *
175 * @param null
176 *
177 * @return void
178 * @access public
179 * @see valid_date
180 */
181 function addRules() {
182 $this->addFormRule(array('CRM_Custom_Form_Group', 'formRule'), $this);
183 }
184
185 /**
186 * Function to actually build the form
187 *
188 * @param null
189 *
190 * @return void
191 * @access public
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 -")) + $relName;
261 }
262 else {
263 $sel2[$main] = array(
264 '' => ts("- Any -")) + $sel2[$main];
265 }
266 }
267 }
268
269 $cSubTypes = CRM_Core_Component::contactSubTypes();
270
271 if (!empty($cSubTypes)) {
272 $contactSubTypes = array();
273 foreach ($cSubTypes as $key => $value) {
274 $contactSubTypes[$key] = $key;
275 }
276 $sel2['Contact'] = array(
277 "" => "-- Any --") + $contactSubTypes;
278 }
279 else {
280 if (!isset($this->_id)) {
281 $formName = 'document.forms.' . $this->_name;
282
283 $js = "<script type='text/javascript'>\n";
284 $js .= "{$formName}['extends_1'].style.display = 'none';\n";
285 $js .= "</script>";
286 $this->assign('initHideBlocks', $js);
287 }
288 }
289
290 $sel = &$this->add('hierselect',
291 'extends',
292 ts('Used For'),
293 array(
294 'onClick' => 'showHideStyle();',
295 'name' => 'extends[0]',
296 'style' => 'vertical-align: top;',
297 ),
298 TRUE
299 );
300 $sel->setOptions(array($sel1, $sel2));
301 if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
302 // make second selector a multi-select -
303 $sel->_elements[1]->setMultiple(TRUE);
304 $sel->_elements[1]->setSize(5);
305 }
306 if ($this->_action == CRM_Core_Action::UPDATE) {
307 $subName = CRM_Utils_Array::value('extends_entity_column_id', $this->_defaults);
308 if ($this->_defaults['extends'] == 'Participant') {
309 if ($subName == 1) {
310 $this->_defaults['extends'] = 'ParticipantRole';
311 }
312 elseif ($subName == 2) {
313 $this->_defaults['extends'] = 'ParticipantEventName';
314 }
315 elseif ($subName == 3) {
316 $this->_defaults['extends'] = 'ParticipantEventType';
317 }
318 }
319
320 //allow to edit settings if custom set is empty CRM-5258
321 $this->_isGroupEmpty = CRM_Core_BAO_CustomGroup::isGroupEmpty($this->_id);
322 if (!$this->_isGroupEmpty) {
323 if (!empty($this->_subtypes)) {
324 // we want to allow adding / updating subtypes for this case,
325 // and therefore freeze the first selector only.
326 $sel->_elements[0]->freeze();
327 }
328 else {
329 // freeze both the selectors
330 $sel->freeze();
331 }
332 }
333 $this->assign('isCustomGroupEmpty', $this->_isGroupEmpty);
334 $this->assign('gid', $this->_id);
335 }
336 $this->assign('defaultSubtypes', json_encode($this->_subtypes));
337
338 // help text
339 $this->addWysiwyg('help_pre', ts('Pre-form Help'), $attributes['help_pre']);
340 $this->addWysiwyg('help_post', ts('Post-form Help'), $attributes['help_post']);
341
342 // weight
343 $this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE);
344 $this->addRule('weight', ts('is a numeric field'), 'numeric');
345
346 // display style
347 $this->add('select', 'style', ts('Display Style'), CRM_Core_SelectValues::customGroupStyle());
348
349 // is this set collapsed or expanded ?
350 $this->addElement('checkbox', 'collapse_display', ts('Collapse this set on initial display'));
351
352 // is this set collapsed or expanded ? in advanced search
353 $this->addElement('checkbox', 'collapse_adv_display', ts('Collapse this set in Advanced Search'));
354
355 // is this set active ?
356 $this->addElement('checkbox', 'is_active', ts('Is this Custom Data Set active?'));
357
358 // does this set have multiple record?
359 $multiple = $this->addElement('checkbox',
360 'is_multiple',
361 ts('Does this Custom Field Set allow multiple records?'),
362 NULL,
363 array('onclick' => "showRange();")
364 );
365
366 // $min_multiple = $this->add('text', 'min_multiple', ts('Minimum number of multiple records'), $attributes['min_multiple'] );
367 // $this->addRule('min_multiple', ts('is a numeric field') , 'numeric');
368
369 $max_multiple = $this->add('text', 'max_multiple', ts('Maximum number of multiple records'), $attributes['max_multiple']);
370 $this->addRule('max_multiple', ts('is a numeric field'), 'numeric');
371
372 //allow to edit settings if custom set is empty CRM-5258
373 $this->assign('isGroupEmpty', $this->_isGroupEmpty);
374 if (!$this->_isGroupEmpty) {
375 $multiple->freeze();
376 //$min_multiple->freeze();
377 $max_multiple->freeze();
378 }
379
380 $this->assign('showStyle', FALSE);
381 $this->assign('showMultiple', FALSE);
382 $buttons = array(
383 array(
384 'type' => 'next',
385 'name' => ts('Save'),
386 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
387 'isDefault' => TRUE,
388 ),
389 array(
390 'type' => 'cancel',
391 'name' => ts('Cancel'),
392 ),
393 );
394 if (!$this->_isGroupEmpty && !empty($this->_subtypes)) {
395 $buttons[0]['js'] = array('onclick' => "return warnDataLoss()");
396 }
397 $this->addButtons($buttons);
398
399 // views are implemented as frozen form
400 if ($this->_action & CRM_Core_Action::VIEW) {
401 $this->freeze();
402 $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"));
403 }
404 }
405
406 /**
407 * This function sets the default values for the form. Note that in edit/view mode
408 * the default values are retrieved from the database
409 *
410 * @param null
411 *
412 * @return array array of default values
413 * @access public
414 */
415 function setDefaultValues() {
416 $defaults = &$this->_defaults;
417 $this->assign('showMaxMultiple', TRUE);
418 if ($this->_action == CRM_Core_Action::ADD) {
419 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_CustomGroup');
420
421 $defaults['is_multiple'] = $defaults['min_multiple'] = 0;
422 $defaults['is_active'] = $defaults['collapse_display'] = 1;
423 $defaults['style'] = 'Inline';
424 }
425 elseif (!CRM_Utils_Array::value('max_multiple', $defaults) && !$this->_isGroupEmpty) {
426 $this->assign('showMaxMultiple', FALSE);
427 }
428
429 if (isset($defaults['extends'])) {
430 $extends = $defaults['extends'];
431 unset($defaults['extends']);
432
433 $defaults['extends'][0] = $extends;
434
435 if (!empty($this->_subtypes)) {
436 $defaults['extends'][1] = $this->_subtypes;
437 }
438 else {
439 $defaults['extends'][1] = array(0 => '');
440 }
441
442
443 $subName = CRM_Utils_Array::value('extends_entity_column_id', $defaults);
444
445 if ($extends == 'Relationship' && !empty($this->_subtypes)) {
446 $relationshipDefaults = array();
447 foreach ($defaults['extends'][1] as $donCare => $rel_type_id) {
448 $relationshipDefaults[] = $rel_type_id;
449 }
450
451 $defaults['extends'][1] = $relationshipDefaults;
452 }
453 }
454
455 return $defaults;
456 }
457
458 /**
459 * Process the form
460 *
461 * @param null
462 *
463 * @return void
464 * @access public
465 */
466 public function postProcess() {
467 // get the submitted form values.
468 $params = $this->controller->exportValues('Group');
469 $params['overrideFKConstraint'] = 0;
470 if ($this->_action & CRM_Core_Action::UPDATE) {
471 $params['id'] = $this->_id;
472 if ($this->_defaults['extends'][0] != $params['extends'][0]) {
473 $params['overrideFKConstraint'] = 1;
474 }
475
476 if (!empty($this->_subtypes)) {
477 $subtypesToBeRemoved = array_diff($this->_subtypes, array_intersect($this->_subtypes, $params['extends'][1]));
478 CRM_Contact_BAO_ContactType::deleteCustomRowsOfSubtype($this->_id, $subtypesToBeRemoved);
479 }
480 }
481 elseif ($this->_action & CRM_Core_Action::ADD) {
482 //new custom set , so lets set the created_id
483 $session = CRM_Core_Session::singleton();
484 $params['created_id'] = $session->get('userID');
485 $params['created_date'] = date('YmdHis');
486 }
487
488 $group = CRM_Core_BAO_CustomGroup::create($params);
489
490 // reset the cache
491 CRM_Core_BAO_Cache::deleteGroup('contact fields');
492
493 if ($this->_action & CRM_Core_Action::UPDATE) {
494 CRM_Core_Session::setStatus(ts('Your custom field set \'%1 \' has been saved.', array(1 => $group->title)), ts('Saved'), 'success');
495 }
496 else {
497 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field/add', 'reset=1&action=add&gid=' . $group->id);
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 * Function to return a formatted list of relationship name.
530 * @param $list array array of relationship name.
531 * @static
532 * return array array of relationship name.
533 */
534 static function getFormattedList(&$list) {
535 $relName = array();
536
537 foreach ($list as $k => $v) {
538 $key = substr($k, 0, strpos($k, '_'));
539 if (isset($list["{$key}_b_a"])) {
540 if ($list["{$key}_a_b"] != $list["{$key}_b_a"]) {
541 $relName["$key"] = $list["{$key}_a_b"] . ' / ' . $list["{$key}_b_a"];
542 }
543 unset($list["{$key}_b_a"]);
544 }
545 else {
546 $relName["{$key}"] = $list["{$key}_a_b"];
547 }
548 }
549 return $relName;
550 }
551 }
552