Merge pull request #2390 from dlobo/CRM-14085
[civicrm-core.git] / CRM / Contact / Form / Contact.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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 * This class generates form components generic to all the contact types.
38 *
39 * It delegates the work to lower level subclasses and integrates the changes
40 * back in. It also uses a lot of functionality with the CRM API's, so any change
41 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
42 *
43 */
44 class CRM_Contact_Form_Contact extends CRM_Core_Form {
45
46 /**
47 * The contact type of the form
48 *
49 * @var string
50 */
51 public $_contactType;
52
53 /**
54 * The contact type of the form
55 *
56 * @var string
57 */
58 public $_contactSubType;
59
60 /**
61 * The contact id, used when editing the form
62 *
63 * @var int
64 */
65 public $_contactId;
66
67 /**
68 * the default group id passed in via the url
69 *
70 * @var int
71 */
72 public $_gid;
73
74 /**
75 * the default tag id passed in via the url
76 *
77 * @var int
78 */
79 public $_tid;
80
81 /**
82 * name of de-dupe button
83 *
84 * @var string
85 * @access protected
86 */
87 protected $_dedupeButtonName;
88
89 /**
90 * name of optional save duplicate button
91 *
92 * @var string
93 * @access protected
94 */
95 protected $_duplicateButtonName;
96
97 protected $_editOptions = array();
98
99 protected $_oldSubtypes = array();
100
101 public $_blocks;
102
103 public $_values = array();
104
105 public $_action;
106
107 public $_customValueCount;
108 /**
109 * The array of greetings with option group and filed names
110 *
111 * @var array
112 */
113 public $_greetings;
114
115 /**
116 * Do we want to parse street address.
117 */
118 public $_parseStreetAddress;
119
120 /**
121 * check contact has a subtype or not
122 */
123 public $_isContactSubType;
124
125 /**
126 * Lets keep a cache of all the values that we retrieved.
127 * THis is an attempt to avoid the number of update statements
128 * during the write phase
129 */
130 public $_preEditValues;
131
132 /**
133 * build all the data structures needed to build the form
134 *
135 * @return void
136 * @access public
137 */
138 function preProcess() {
139 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
140
141 $this->_dedupeButtonName = $this->getButtonName('refresh', 'dedupe');
142 $this->_duplicateButtonName = $this->getButtonName('upload', 'duplicate');
143
144 $session = CRM_Core_Session::singleton();
145 if ($this->_action == CRM_Core_Action::ADD) {
146 // check for add contacts permissions
147 if (!CRM_Core_Permission::check('add contacts')) {
148 CRM_Utils_System::permissionDenied();
149 CRM_Utils_System::civiExit();
150 }
151 $this->_contactType = CRM_Utils_Request::retrieve('ct', 'String',
152 $this, TRUE, NULL, 'REQUEST'
153 );
154 if (!in_array($this->_contactType,
155 array('Individual', 'Household', 'Organization')
156 )) {
157 CRM_Core_Error::statusBounce(ts('Could not get a contact id and/or contact type'));
158 }
159
160 $this->_isContactSubType = FALSE;
161 if ($this->_contactSubType = CRM_Utils_Request::retrieve('cst', 'String', $this)) {
162 $this->_isContactSubType = TRUE;
163 }
164
165 if (
166 $this->_contactSubType &&
167 !(CRM_Contact_BAO_ContactType::isExtendsContactType($this->_contactSubType, $this->_contactType, TRUE))) {
168 CRM_Core_Error::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", array(1 => $this->_contactType)));
169 }
170
171 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Integer',
172 CRM_Core_DAO::$_nullObject,
173 FALSE, NULL, 'GET'
174 );
175 $this->_tid = CRM_Utils_Request::retrieve('tid', 'Integer',
176 CRM_Core_DAO::$_nullObject,
177 FALSE, NULL, 'GET'
178 );
179 $typeLabel = CRM_Contact_BAO_ContactType::contactTypePairs(TRUE, $this->_contactSubType ?
180 $this->_contactSubType : $this->_contactType
181 );
182 $typeLabel = implode(' / ', $typeLabel);
183
184 CRM_Utils_System::setTitle(ts('New %1', array(1 => $typeLabel)));
185 $session->pushUserContext(CRM_Utils_System::url('civicrm/dashboard', 'reset=1'));
186 $this->_contactId = NULL;
187 }
188 else {
189 //update mode
190 if (!$this->_contactId) {
191 $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
192 }
193
194 if ($this->_contactId) {
195 $defaults = array();
196 $params = array('id' => $this->_contactId);
197 $returnProperities = array('id', 'contact_type', 'contact_sub_type', 'modified_date');
198 CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact', $params, $defaults, $returnProperities);
199
200 if (!CRM_Utils_Array::value('id', $defaults)) {
201 CRM_Core_Error::statusBounce(ts('A Contact with that ID does not exist: %1', array(1 => $this->_contactId)));
202 }
203
204 $this->_contactType = CRM_Utils_Array::value('contact_type', $defaults);
205 $this->_contactSubType = CRM_Utils_Array::value('contact_sub_type', $defaults);
206
207 // check for permissions
208 $session = CRM_Core_Session::singleton();
209 if (!CRM_Contact_BAO_Contact_Permission::allow($this->_contactId, CRM_Core_Permission::EDIT)) {
210 CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
211 }
212
213 $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId);
214 $displayName = ts('Edit %1', array(1 => $displayName));
215
216 // Check if this is default domain contact CRM-10482
217 if (CRM_Contact_BAO_Contact::checkDomainContact($this->_contactId)) {
218 $displayName .= ' (' . ts('default organization') . ')';
219 }
220
221 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
222 CRM_Utils_System::setTitle($displayName);
223 $context = CRM_Utils_Request::retrieve('context', 'String', $this);
224 $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
225
226 $urlParams = 'reset=1&cid=' . $this->_contactId;
227 if ($context) {
228 $urlParams .= "&context=$context";
229 }
230
231 if (CRM_Utils_Rule::qfKey($qfKey)) {
232
233 $urlParams .= "&key=$qfKey";
234
235 }
236 $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams));
237
238 $values = $this->get('values');
239 // get contact values.
240 if (!empty($values)) {
241 $this->_values = $values;
242 }
243 else {
244 $params = array(
245 'id' => $this->_contactId,
246 'contact_id' => $this->_contactId,
247 'noRelationships' => TRUE,
248 'noNotes' => TRUE,
249 'noGroups' => TRUE,
250 );
251
252 $contact = CRM_Contact_BAO_Contact::retrieve($params, $this->_values, TRUE);
253 $this->set('values', $this->_values);
254 }
255 }
256 else {
257 CRM_Core_Error::statusBounce(ts('Could not get a contact_id and/or contact_type'));
258 }
259 }
260
261 // parse street address, CRM-5450
262 $this->_parseStreetAddress = $this->get('parseStreetAddress');
263 if (!isset($this->_parseStreetAddress)) {
264 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
265 'address_options'
266 );
267 $this->_parseStreetAddress = FALSE;
268 if (CRM_Utils_Array::value('street_address', $addressOptions) &&
269 CRM_Utils_Array::value('street_address_parsing', $addressOptions)
270 ) {
271 $this->_parseStreetAddress = TRUE;
272 }
273 $this->set('parseStreetAddress', $this->_parseStreetAddress);
274 }
275 $this->assign('parseStreetAddress', $this->_parseStreetAddress);
276
277 $this->_editOptions = $this->get('contactEditOptions');
278 if (CRM_Utils_System::isNull($this->_editOptions)) {
279 $this->_editOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
280 'contact_edit_options', TRUE, NULL,
281 FALSE, 'name', TRUE, 'AND v.filter = 0'
282 );
283 $this->set('contactEditOptions', $this->_editOptions);
284 }
285
286 // build demographics only for Individual contact type
287 if ($this->_contactType != 'Individual' &&
288 array_key_exists('Demographics', $this->_editOptions)
289 ) {
290 unset($this->_editOptions['Demographics']);
291 }
292
293 // in update mode don't show notes
294 if ($this->_contactId && array_key_exists('Notes', $this->_editOptions)) {
295 unset($this->_editOptions['Notes']);
296 }
297
298 $this->assign('editOptions', $this->_editOptions);
299 $this->assign('contactType', $this->_contactType);
300 $this->assign('contactSubType', $this->_contactSubType);
301
302 //build contact subtype form element, CRM-6864
303 $buildContactSubType = TRUE;
304 if ($this->_contactSubType && ($this->_action & CRM_Core_Action::ADD)) {
305 $buildContactSubType = FALSE;
306 }
307 $this->assign('buildContactSubType', $buildContactSubType);
308
309 // get the location blocks.
310 $this->_blocks = $this->get('blocks');
311 if (CRM_Utils_System::isNull($this->_blocks)) {
312 $this->_blocks = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
313 'contact_edit_options', TRUE, NULL,
314 FALSE, 'name', TRUE, 'AND v.filter = 1'
315 );
316 $this->set('blocks', $this->_blocks);
317 }
318 $this->assign('blocks', $this->_blocks);
319
320 // this is needed for custom data.
321 $this->assign('entityID', $this->_contactId);
322
323 // also keep the convention.
324 $this->assign('contactId', $this->_contactId);
325
326 // location blocks.
327 CRM_Contact_Form_Location::preProcess($this);
328
329 // retain the multiple count custom fields value
330 if(CRM_Utils_Array::value('hidden_custom', $_POST)) {
331 $customGroupCount = CRM_Utils_Array::value('hidden_custom_group_count', $_POST);
332
333 if ($contactSubType = CRM_Utils_Array::value( 'contact_sub_type', $_POST)) {
334 $paramSubType = implode(',', $contactSubType);
335 }
336
337 $this->_getCachedTree = FALSE;
338 unset($customGroupCount[0]);
339 foreach ($customGroupCount as $groupID => $groupCount) {
340 if ($groupCount > 1) {
341 $this->set('groupID', $groupID);
342 //loop the group
343 for ($i = 0; $i <= $groupCount; $i++) {
344 CRM_Custom_Form_CustomData::preProcess($this, NULL, $contactSubType,
345 $i, $this->_contactType
346 );
347 CRM_Contact_Form_Edit_CustomData::buildQuickForm($this);
348 }
349 }
350 }
351
352 //reset all the ajax stuff, for normal processing
353 if (isset($this->_groupTree)) {
354 $this->_groupTree = NULL;
355 }
356 $this->set('groupID', NULL);
357 $this->_getCachedTree = TRUE;
358 }
359
360 // execute preProcess dynamically by js else execute normal preProcess
361 if (array_key_exists('CustomData', $this->_editOptions)) {
362 //assign a parameter to pass for sub type multivalue
363 //custom field to load
364 if ($this->_contactSubType || isset($paramSubType)) {
365 $paramSubType = (isset($paramSubType)) ? $paramSubType :
366 str_replace( CRM_Core_DAO::VALUE_SEPARATOR, ',', trim($this->_contactSubType, CRM_Core_DAO::VALUE_SEPARATOR));
367
368 $this->assign('paramSubType', $paramSubType);
369 }
370
371 if (CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject)) {
372 CRM_Contact_Form_Edit_CustomData::preProcess($this);
373 }
374 else {
375 $contactSubType = $this->_contactSubType;
376 // need contact sub type to build related grouptree array during post process
377 if (CRM_Utils_Array::value('contact_sub_type', $_POST)) {
378 $contactSubType = $_POST['contact_sub_type'];
379 }
380 //only custom data has preprocess hence directly call it
381 CRM_Custom_Form_CustomData::preProcess($this, NULL, $contactSubType,
382 1, $this->_contactType, $this->_contactId
383 );
384 $this->assign('customValueCount', $this->_customValueCount);
385 }
386 }
387 }
388
389 /**
390 * This function sets the default values for the form. Note that in edit/view mode
391 * the default values are retrieved from the database
392 *
393 * @access public
394 *
395 * @return void
396 */
397 function setDefaultValues() {
398 $defaults = $this->_values;
399 $params = array();
400
401 if ($this->_action & CRM_Core_Action::ADD) {
402 if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
403 // set group and tag defaults if any
404 if ($this->_gid) {
405 $defaults['group'][] = $this->_gid;
406 }
407 if ($this->_tid) {
408 $defaults['tag'][$this->_tid] = 1;
409 }
410 }
411 if ($this->_contactSubType) {
412 $defaults['contact_sub_type'] = $this->_contactSubType;
413 }
414 }
415 else {
416 $currentEmployer = CRM_Contact_BAO_Relationship::getCurrentEmployer(array($this->_contactId));
417 $defaults['current_employer_id'] = CRM_Utils_Array::value('org_id', $currentEmployer[$this->_contactId]);
418
419 foreach ($defaults['email'] as $dontCare => & $val) {
420 if (isset($val['signature_text'])) {
421 $val['signature_text_hidden'] = $val['signature_text'];
422 }
423 if (isset($val['signature_html'])) {
424 $val['signature_html_hidden'] = $val['signature_html'];
425 }
426 }
427
428 if (CRM_Utils_Array::value('contact_sub_type', $defaults)) {
429 $defaults['contact_sub_type'] = $this->_oldSubtypes;
430 }
431 }
432 $this->assign('currentEmployer', CRM_Utils_Array::value('current_employer_id', $defaults));
433
434 // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
435 foreach ($this->_editOptions as $name => $label) {
436 if (!in_array($name, array('Address', 'Notes'))) {
437 $className = 'CRM_Contact_Form_Edit_' . $name;
438 $className::setDefaultValues($this, $defaults);
439 }
440 }
441
442 //set address block defaults
443 CRM_Contact_Form_Edit_Address::setDefaultValues( $defaults, $this );
444
445 if (CRM_Utils_Array::value('image_URL', $defaults)) {
446 list($imageWidth, $imageHeight) = getimagesize($defaults['image_URL']);
447 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
448 $this->assign('imageWidth', $imageWidth);
449 $this->assign('imageHeight', $imageHeight);
450 $this->assign('imageThumbWidth', $imageThumbWidth);
451 $this->assign('imageThumbHeight', $imageThumbHeight);
452 $this->assign('imageURL', $defaults['image_URL']);
453 }
454
455 //set location type and country to default for each block
456 $this->blockSetDefaults($defaults);
457
458 $this->_preEditValues = $defaults;
459 return $defaults;
460 }
461
462 /**
463 * do the set default related to location type id,
464 * primary location, default country
465 *
466 */
467 function blockSetDefaults(&$defaults) {
468 $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int');
469 sort($locationTypeKeys);
470
471 // get the default location type
472 $locationType = CRM_Core_BAO_LocationType::getDefault();
473
474 // unset primary location type
475 $primaryLocationTypeIdKey = CRM_Utils_Array::key($locationType->id, $locationTypeKeys);
476 unset($locationTypeKeys[$primaryLocationTypeIdKey]);
477
478 // reset the array sequence
479 $locationTypeKeys = array_values($locationTypeKeys);
480
481 // get default phone and im provider id.
482 $defPhoneTypeId = key(CRM_Core_OptionGroup::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1'));
483 $defIMProviderId = key(CRM_Core_OptionGroup::values('instant_messenger_service',
484 FALSE, FALSE, FALSE, ' AND is_default = 1'
485 ));
486
487 $allBlocks = $this->_blocks;
488 if (array_key_exists('Address', $this->_editOptions)) {
489 $allBlocks['Address'] = $this->_editOptions['Address'];
490 }
491
492 $config = CRM_Core_Config::singleton();
493 foreach ($allBlocks as $blockName => $label) {
494 $name = strtolower($blockName);
495 $hasPrimary = $updateMode = FALSE;
496
497 // user is in update mode.
498 if (array_key_exists($name, $defaults) &&
499 !CRM_Utils_System::isNull($defaults[$name])
500 ) {
501 $updateMode = TRUE;
502 }
503
504 for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++) {
505 // make we require one primary block, CRM-5505
506 if ($updateMode) {
507 if (!$hasPrimary) {
508 $hasPrimary =
509 CRM_Utils_Array::value(
510 'is_primary',
511 CRM_Utils_Array::value($instance, $defaults[$name])
512 );
513 }
514 continue;
515 }
516
517 //set location to primary for first one.
518 if ($instance == 1) {
519 $hasPrimary = TRUE;
520 $defaults[$name][$instance]['is_primary'] = TRUE;
521 $defaults[$name][$instance]['location_type_id'] = $locationType->id;
522 }
523 else {
524 $locTypeId = isset($locationTypeKeys[$instance - 1]) ? $locationTypeKeys[$instance - 1] : $locationType->id;
525 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
526 }
527
528 //set default country
529 if ($name == 'address' && $config->defaultContactCountry) {
530 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry;
531 }
532
533 //set default state/province
534 if ($name == 'address' && $config->defaultContactStateProvince) {
535 $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince;
536 }
537
538 //set default phone type.
539 if ($name == 'phone' && $defPhoneTypeId) {
540 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
541 }
542
543 //set default im provider.
544 if ($name == 'im' && $defIMProviderId) {
545 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
546 }
547 }
548
549 if (!$hasPrimary) {
550 $defaults[$name][1]['is_primary'] = TRUE;
551 }
552 }
553
554 // set defaults for country-state widget
555 if (CRM_Utils_Array::value('address', $defaults) && is_array($defaults['address'])) {
556 foreach ($defaults['address'] as $blockId => $values) {
557 CRM_Contact_Form_Edit_Address::fixStateSelect($this,
558 "address[$blockId][country_id]",
559 "address[$blockId][state_province_id]",
560 "address[$blockId][county_id]",
561 CRM_Utils_Array::value('country_id',
562 $values, $config->defaultContactCountry
563 ),
564 CRM_Utils_Array::value('state_province_id',
565 $values, $config->defaultContactStateProvince
566 )
567 );
568 }
569 }
570 }
571
572 /**
573 * This function is used to add the rules (mainly global rules) for form.
574 * All local rules are added near the element
575 *
576 * @return void
577 * @access public
578 * @see valid_date
579 */
580 function addRules() {
581 // skip adding formRules when custom data is build
582 if ($this->_addBlockName || ($this->_action & CRM_Core_Action::DELETE)) {
583 return;
584 }
585
586 $this->addFormRule(array('CRM_Contact_Form_Edit_' . $this->_contactType, 'formRule'), $this->_contactId);
587
588 // Call Locking check if editing existing contact
589 if ($this->_contactId) {
590 $this->addFormRule(array('CRM_Contact_Form_Edit_Lock', 'formRule'), $this->_contactId);
591 }
592
593 if (array_key_exists('Address', $this->_editOptions)) {
594 $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'), $this);
595 }
596
597 if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
598 $this->addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this);
599 }
600 }
601
602 /**
603 * global validation rules for the form
604 *
605 * @param array $fields posted values of the form
606 * @param array $errors list of errors to be posted back to the form
607 * @param int $contactId contact id if doing update.
608 *
609 * @return $primaryID email/openId
610 * @static
611 * @access public
612 */
613 static function formRule($fields, &$errors, $contactId = NULL) {
614 $config = CRM_Core_Config::singleton();
615
616 // validations.
617 //1. for each block only single value can be marked as is_primary = true.
618 //2. location type id should be present if block data present.
619 //3. check open id across db and other each block for duplicate.
620 //4. at least one location should be primary.
621 //5. also get primaryID from email or open id block.
622
623 // take the location blocks.
624 $blocks = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
625 'contact_edit_options', TRUE, NULL,
626 FALSE, 'name', TRUE, 'AND v.filter = 1'
627 );
628
629 $otherEditOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
630 'contact_edit_options', TRUE, NULL,
631 FALSE, 'name', TRUE, 'AND v.filter = 0'
632 );
633 //get address block inside.
634 if (array_key_exists('Address', $otherEditOptions)) {
635 $blocks['Address'] = $otherEditOptions['Address'];
636 }
637
638 $openIds = array();
639 $primaryID = FALSE;
640 foreach ($blocks as $name => $label) {
641 $hasData = $hasPrimary = array();
642 $name = strtolower($name);
643 if (CRM_Utils_Array::value($name, $fields) && is_array($fields[$name])) {
644 foreach ($fields[$name] as $instance => $blockValues) {
645 $dataExists = self::blockDataExists($blockValues);
646
647 if (!$dataExists && $name == 'address') {
648 $dataExists = CRM_Utils_Array::value('use_shared_address', $fields['address'][$instance]);
649 }
650
651 if ($dataExists) {
652 // skip remaining checks for website
653 if ($name == 'website') {
654 continue;
655 }
656
657 $hasData[] = $instance;
658 if (CRM_Utils_Array::value('is_primary', $blockValues)) {
659 $hasPrimary[] = $instance;
660 if (!$primaryID &&
661 in_array($name, array(
662 'email', 'openid')) &&
663 CRM_Utils_Array::value($name, $blockValues)
664 ) {
665 $primaryID = $blockValues[$name];
666 }
667 }
668
669 if (!CRM_Utils_Array::value('location_type_id', $blockValues)) {
670 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', array(1 => $label));
671 }
672 }
673
674 if ($name == 'openid' && CRM_Utils_Array::value($name, $blockValues)) {
675 $oid = new CRM_Core_DAO_OpenID();
676 $oid->openid = $openIds[$instance] = CRM_Utils_Array::value($name, $blockValues);
677 $cid = isset($contactId) ? $contactId : 0;
678 if ($oid->find(TRUE) && ($oid->contact_id != $cid)) {
679 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID']));
680 }
681 }
682 }
683
684 if (empty($hasPrimary) && !empty($hasData)) {
685 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label));
686 }
687
688 if (count($hasPrimary) > 1) {
689 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
690 array(1 => $label)
691 );
692 }
693 }
694 }
695
696 //do validations for all opend ids they should be distinct.
697 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
698 foreach ($openIds as $instance => $value) {
699 if (!array_key_exists($instance, array_unique($openIds))) {
700 $errors["openid[$instance][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID']));
701 }
702 }
703 }
704
705 // street number should be digit + suffix, CRM-5450
706 $parseStreetAddress = CRM_Utils_Array::value('street_address_parsing',
707 CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
708 'address_options'
709 )
710 );
711 if ($parseStreetAddress) {
712 if (isset($fields['address']) &&
713 is_array($fields['address'])
714 ) {
715 $invalidStreetNumbers = array();
716 foreach ($fields['address'] as $cnt => $address) {
717 if ($streetNumber = CRM_Utils_Array::value('street_number', $address)) {
718 $parsedAddress = CRM_Core_BAO_Address::parseStreetAddress($address['street_number']);
719 if (!CRM_Utils_Array::value('street_number', $parsedAddress)) {
720 $invalidStreetNumbers[] = $cnt;
721 }
722 }
723 }
724
725 if (!empty($invalidStreetNumbers)) {
726 $first = $invalidStreetNumbers[0];
727 foreach ($invalidStreetNumbers as & $num) $num = CRM_Contact_Form_Contact::ordinalNumber($num);
728 $errors["address[$first][street_number]"] = ts('The street number you entered for the %1 address block(s) is not in an expected format. Street numbers may include numeric digit(s) followed by other characters. You can still enter the complete street address (unparsed) by clicking "Edit Complete Street Address".', array(1 => implode(', ', $invalidStreetNumbers)));
729 }
730 }
731 }
732
733 return $primaryID;
734 }
735
736 /**
737 * Function to actually build the form
738 *
739 * @return void
740 * @access public
741 */
742 public function buildQuickForm() {
743 //load form for child blocks
744 if ($this->_addBlockName) {
745 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName;
746 return $className::buildQuickForm($this);
747 }
748
749 if ($this->_action == CRM_Core_Action::UPDATE) {
750 $deleteExtra = ts('Are you sure you want to delete contact image.');
751 $deleteURL = array(
752 CRM_Core_Action::DELETE =>
753 array(
754 'name' => ts('Delete Contact Image'),
755 'url' => 'civicrm/contact/image',
756 'qs' => 'reset=1&cid=%%id%%&action=delete',
757 'extra' =>
758 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&amp;confirmed=1\'; else return false;"',
759 ),
760 );
761 $deleteURL = CRM_Core_Action::formLink($deleteURL,
762 CRM_Core_Action::DELETE,
763 array(
764 'id' => $this->_contactId,
765 ),
766 ts('more'),
767 FALSE,
768 'contact.image.delete',
769 'Contact',
770 $this->_contactId
771 );
772 $this->assign('deleteURL', $deleteURL);
773 }
774
775 //build contact type specific fields
776 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType;
777 $className::buildQuickForm($this);
778
779 // build Custom data if Custom data present in edit option
780 $buildCustomData = 'noCustomDataPresent';
781 if (array_key_exists('CustomData', $this->_editOptions)) {
782 $buildCustomData = "customDataPresent";
783 }
784
785 // subtype is a common field. lets keep it here
786 $subtypes = CRM_Contact_BAO_ContactType::subTypePairs($this->_contactType);
787 if (!empty($subtypes)) {
788 $sel = $this->add('select', 'contact_sub_type', ts('Contact Type'),
789 $subtypes, FALSE,
790 array(
791 'id' => 'contact_sub_type',
792 'multiple' => 'multiple',
793 'title' => '- ' . ts('select') . ' -',
794 'class' => $buildCustomData,
795 )
796 );
797 }
798
799 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
800 foreach ($this->_editOptions as $name => $label) {
801 if ($name == 'Address') {
802 $this->_blocks['Address'] = $this->_editOptions['Address'];
803 continue;
804 }
805 if ($name == 'TagsAndGroups') {
806 continue;
807 }
808 $className = 'CRM_Contact_Form_Edit_' . $name;
809 $className::buildQuickForm($this);
810 }
811
812 // build tags and groups
813 CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups::ALL,
814 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'crmasmSelect');
815
816 // build location blocks.
817 CRM_Contact_Form_Edit_Lock::buildQuickForm($this);
818 CRM_Contact_Form_Location::buildQuickForm($this);
819
820 // add attachment
821 $this->addElement('file', 'image_URL', ts('Browse/Upload Image'), 'size=30 maxlength=60');
822 $this->addUploadElement('image_URL');
823
824 // add the dedupe button
825 $this->addElement('submit',
826 $this->_dedupeButtonName,
827 ts('Check for Matching Contact(s)')
828 );
829 $this->addElement('submit',
830 $this->_duplicateButtonName,
831 ts('Save Matching Contact')
832 );
833 $this->addElement('submit',
834 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
835 ts('Save With Duplicate Household')
836 );
837
838 $buttons = array(
839 array(
840 'type' => 'upload',
841 'name' => ts('Save'),
842 'subName' => 'view',
843 'isDefault' => TRUE,
844 ),
845 array(
846 'type' => 'upload',
847 'name' => ts('Save and New'),
848 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
849 'subName' => 'new',
850 ),
851 array(
852 'type' => 'cancel',
853 'name' => ts('Cancel'),
854 ),
855 );
856
857 if (CRM_Utils_Array::value('contact_sub_type', $this->_values)) {
858 $this->_oldSubtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
859 trim($this->_values['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR)
860 );
861 }
862 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes));
863
864 $this->addButtons($buttons);
865 }
866
867 /**
868 * Form submission of new/edit contact is processed.
869 *
870 * @access public
871 *
872 * @return void
873 */
874 public function postProcess() {
875 // check if dedupe button, if so return.
876 $buttonName = $this->controller->getButtonName();
877 if ($buttonName == $this->_dedupeButtonName) {
878 return;
879 }
880
881 //get the submitted values in an array
882 $params = $this->controller->exportValues($this->_name);
883
884 $group = CRM_Utils_Array::value('group', $params);
885 if ($group && is_array($group)) {
886 unset($params['group']);
887 foreach ($group as $key => $value) {
888 $params['group'][$value] = 1;
889 }
890 }
891
892 CRM_Contact_BAO_Contact_Optimizer::edit( $params, $this->_preEditValues );
893
894 if (CRM_Utils_Array::value('image_URL', $params)) {
895 CRM_Contact_BAO_Contact::processImageParams($params);
896 }
897
898 if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params))
899 && CRM_Utils_Array::value('current_employer', $params)
900 ) {
901 $params['current_employer'] = $params['current_employer_id'];
902 }
903
904 // don't carry current_employer_id field,
905 // since we don't want to directly update DAO object without
906 // handling related business logic ( eg related membership )
907 if (isset($params['current_employer_id'])) {
908 unset($params['current_employer_id']);
909 }
910
911 $params['contact_type'] = $this->_contactType;
912 if (empty($params['contact_sub_type']) && $this->_isContactSubType) {
913 $params['contact_sub_type'] = array($this->_contactSubType);
914 }
915
916 if ($this->_contactId) {
917 $params['contact_id'] = $this->_contactId;
918 }
919
920 //make deceased date null when is_deceased = false
921 if ($this->_contactType == 'Individual' &&
922 CRM_Utils_Array::value('Demographics', $this->_editOptions) &&
923 !CRM_Utils_Array::value('is_deceased', $params)
924 ) {
925 $params['is_deceased'] = FALSE;
926 $params['deceased_date'] = NULL;
927 }
928
929 if (isset($params['contact_id'])) {
930 // process membership status for deceased contact
931 $deceasedParams = array('contact_id' => CRM_Utils_Array::value('contact_id', $params),
932 'is_deceased' => CRM_Utils_Array::value('is_deceased', $params, FALSE),
933 'deceased_date' => CRM_Utils_Array::value('deceased_date', $params, NULL),
934 );
935 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
936 }
937
938 // action is taken depending upon the mode
939 if ($this->_action & CRM_Core_Action::UPDATE) {
940 CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
941 }
942 else {
943 CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
944 }
945
946 $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], FALSE, TRUE);
947
948 //CRM-5143
949 //if subtype is set, send subtype as extend to validate subtype customfield
950 $customFieldExtends = (CRM_Utils_Array::value('contact_sub_type', $params)) ? $params['contact_sub_type'] : $params['contact_type'];
951
952 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
953 $customFields,
954 $this->_contactId,
955 $customFieldExtends,
956 TRUE
957 );
958 if ($this->_contactId && !empty($this->_oldSubtypes)) {
959 CRM_Contact_BAO_ContactType::deleteCustomSetForSubtypeMigration($this->_contactId,
960 $params['contact_type'],
961 $this->_oldSubtypes,
962 $params['contact_sub_type']
963 );
964 }
965
966 if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
967 // this is a chekbox, so mark false if we dont get a POST value
968 $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
969 }
970
971 // process shared contact address.
972 CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']);
973
974 if (!array_key_exists('TagsAndGroups', $this->_editOptions)) {
975 unset($params['group']);
976 }
977
978 if (CRM_Utils_Array::value('contact_id', $params) && ($this->_action & CRM_Core_Action::UPDATE)) {
979 // figure out which all groups are intended to be removed
980 $contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
981 if (is_array($contactGroupList)) {
982 foreach ($contactGroupList as $key) {
983 if ((!array_key_exists($key['group_id'], $params['group']) || $params['group'][$key['group_id']] != 1)
984 && !CRM_Utils_Array::value('is_hidden', $key)
985 ) {
986 $params['group'][$key['group_id']] = -1;
987 }
988 }
989 }
990 }
991
992 // parse street address, CRM-5450
993 $parseStatusMsg = NULL;
994 if ($this->_parseStreetAddress) {
995 $parseResult = self::parseAddress($params);
996 $parseStatusMsg = self::parseAddressStatusMsg($parseResult);
997 }
998
999 // Allow un-setting of location info, CRM-5969
1000 $params['updateBlankLocInfo'] = TRUE;
1001
1002 $contact = CRM_Contact_BAO_Contact::create($params, TRUE, FALSE, TRUE);
1003
1004 // status message
1005 if ($this->_contactId) {
1006 $message = ts('%1 has been updated.', array(1 => $contact->display_name));
1007 }
1008 else {
1009 $message = ts('%1 has been created.', array(1 => $contact->display_name));
1010 }
1011
1012 // set the contact ID
1013 $this->_contactId = $contact->id;
1014
1015 if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
1016 //add contact to tags
1017 CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1018
1019 //save free tags
1020 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1021 CRM_Core_Form_Tag::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1022 }
1023 }
1024
1025 if (!empty($parseStatusMsg)) {
1026 $message .= "<br />$parseStatusMsg";
1027 }
1028 if (!empty($updateMembershipMsg)) {
1029 $message .= "<br />$updateMembershipMsg";
1030 }
1031
1032 $session = CRM_Core_Session::singleton();
1033 $session->setStatus($message, ts('Contact Saved'), 'success');
1034
1035 // add the recently viewed contact
1036 $recentOther = array();
1037 if (($session->get('userID') == $contact->id) ||
1038 CRM_Contact_BAO_Contact_Permission::allow($contact->id, CRM_Core_Permission::EDIT)
1039 ) {
1040 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id);
1041 }
1042
1043 if (($session->get('userID') != $this->_contactId) && CRM_Core_Permission::check('delete contacts')) {
1044 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id);
1045 }
1046
1047 CRM_Utils_Recent::add($contact->display_name,
1048 CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id),
1049 $contact->id,
1050 $this->_contactType,
1051 $contact->id,
1052 $contact->display_name,
1053 $recentOther
1054 );
1055
1056 // here we replace the user context with the url to view this contact
1057 $buttonName = $this->controller->getButtonName();
1058 if ($buttonName == $this->getButtonName('upload', 'new')) {
1059 $resetStr = "reset=1&ct={$contact->contact_type}";
1060 $resetStr .= $this->_contactSubType ? "&cst={$this->_contactSubType}" : '';
1061 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr));
1062 }
1063 else {
1064 $context = CRM_Utils_Request::retrieve('context', 'String', $this);
1065 $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
1066 //validate the qfKey
1067 $urlParams = 'reset=1&cid=' . $contact->id;
1068 if ($context) {
1069 $urlParams .= "&context=$context";
1070 }
1071 if (CRM_Utils_Rule::qfKey($qfKey)) {
1072 $urlParams .= "&key=$qfKey";
1073 }
1074
1075 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams));
1076 }
1077
1078 // now invoke the post hook
1079 if ($this->_action & CRM_Core_Action::UPDATE) {
1080 CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
1081 }
1082 else {
1083 CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
1084 }
1085 }
1086
1087 /**
1088 * is there any real significant data in the hierarchical location array
1089 *
1090 * @param array $fields the hierarchical value representation of this location
1091 *
1092 * @return boolean true if data exists, false otherwise
1093 * @static
1094 * @access public
1095 */
1096 static function blockDataExists(&$fields) {
1097 if (!is_array($fields)) {
1098 return FALSE;
1099 }
1100
1101 static $skipFields = array('location_type_id', 'is_primary', 'phone_type_id', 'provider_id', 'country_id', 'website_type_id', 'master_id');
1102 foreach ($fields as $name => $value) {
1103 $skipField = FALSE;
1104 foreach ($skipFields as $skip) {
1105 if (strpos("[$skip]", $name) !== FALSE) {
1106 if ($name == 'phone') {
1107 continue;
1108 }
1109 $skipField = TRUE;
1110 break;
1111 }
1112 }
1113 if ($skipField) {
1114 continue;
1115 }
1116 if (is_array($value)) {
1117 if (self::blockDataExists($value)) {
1118 return TRUE;
1119 }
1120 }
1121 else {
1122 if (!empty($value)) {
1123 return TRUE;
1124 }
1125 }
1126 }
1127
1128 return FALSE;
1129 }
1130
1131 /**
1132 * Function to that checks for duplicate contacts
1133 *
1134 * @param array $fields fields array which are submitted
1135 * @param array $error error message array
1136 * @param int $contactID contact id
1137 * @param string $contactType contact type
1138 */
1139 static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
1140 // if this is a forced save, ignore find duplicate rule
1141 if (!CRM_Utils_Array::value('_qf_Contact_upload_duplicate', $fields)) {
1142
1143 $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, $contactType);
1144 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, 'Supervised', array($contactID));
1145 if ($ids) {
1146
1147 $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1148
1149 $duplicateContactsLinks = '<div class="matching-contacts-found">';
1150 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
1151 if ($contactLinks['msg'] == 'view') {
1152 $duplicateContactsLinks .= ts('You can View the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts'));
1153 }
1154 else {
1155 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts'));
1156 }
1157 if ($contactLinks['msg'] == 'merge') {
1158 // We should also get a merge link if this is for an existing contact
1159 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1160 }
1161 $duplicateContactsLinks .= '.';
1162 $duplicateContactsLinks .= '</div>';
1163 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1164 $row = '';
1165 for ($i = 0; $i < count($contactLinks['rows']); $i++) {
1166 $row .= ' <tr> ';
1167 $row .= ' <td class="matching-contacts-name"> ';
1168 $row .= $contactLinks['rows'][$i]['display_name'];
1169 $row .= ' </td>';
1170 $row .= ' <td class="matching-contacts-email"> ';
1171 $row .= $contactLinks['rows'][$i]['primary_email'];
1172 $row .= ' </td>';
1173 $row .= ' <td class="action-items"> ';
1174 $row .= $contactLinks['rows'][$i]['view'];
1175 $row .= $contactLinks['rows'][$i]['edit'];
1176 $row .= CRM_Utils_Array::value('merge', $contactLinks['rows'][$i]);
1177 $row .= ' </td>';
1178 $row .= ' </tr> ';
1179 }
1180
1181 $duplicateContactsLinks .= $row . '</table>';
1182 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1183
1184 $errors['_qf_default'] = $duplicateContactsLinks;
1185
1186
1187
1188 // let smarty know that there are duplicates
1189 $template = CRM_Core_Smarty::singleton();
1190 $template->assign('isDuplicate', 1);
1191 }
1192 elseif (CRM_Utils_Array::value('_qf_Contact_refresh_dedupe', $fields)) {
1193 // add a session message for no matching contacts
1194 CRM_Core_Session::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1195 }
1196 }
1197 }
1198
1199 function getTemplateFileName() {
1200 if ($this->_contactSubType) {
1201 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1202 $template = CRM_Core_Form::getTemplate();
1203 if ($template->template_exists($templateFile)) {
1204 return $templateFile;
1205 }
1206 }
1207 return parent::getTemplateFileName();
1208 }
1209
1210 /**
1211 * Parse all address blocks present in given params
1212 * and return parse result for all address blocks,
1213 * This function either parse street address in to child
1214 * elements or build street address from child elements.
1215 *
1216 * @params $params an array of key value consist of address blocks.
1217 *
1218 * @return $parseSuccess as array of sucess/fails for each address block
1219 * @static
1220 */
1221 function parseAddress(&$params) {
1222 $parseSuccess = $parsedFields = array();
1223 if (!is_array($params['address']) ||
1224 CRM_Utils_System::isNull($params['address'])
1225 ) {
1226 return $parseSuccess;
1227 }
1228
1229 foreach ($params['address'] as $instance => & $address) {
1230 $buildStreetAddress = FALSE;
1231 $parseFieldName = 'street_address';
1232 foreach (array(
1233 'street_number', 'street_name', 'street_unit') as $fld) {
1234 if (CRM_Utils_Array::value($fld, $address)) {
1235 $parseFieldName = 'street_number';
1236 $buildStreetAddress = TRUE;
1237 break;
1238 }
1239 }
1240
1241 // main parse string.
1242 $parseString = CRM_Utils_Array::value($parseFieldName, $address);
1243
1244 // parse address field.
1245 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($parseString);
1246
1247 if ($buildStreetAddress) {
1248 //hack to ignore spaces between number and suffix.
1249 //here user gives input as street_number so it has to
1250 //be street_number and street_number_suffix, but
1251 //due to spaces though preg detect string as street_name
1252 //consider it as 'street_number_suffix'.
1253 $suffix = $parsedFields['street_number_suffix'];
1254 if (!$suffix) {
1255 $suffix = $parsedFields['street_name'];
1256 }
1257 $address['street_number_suffix'] = $suffix;
1258 $address['street_number'] = $parsedFields['street_number'];
1259
1260 $streetAddress = NULL;
1261 foreach (array(
1262 'street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) {
1263 if (in_array($fld, array(
1264 'street_name', 'street_unit'))) {
1265 $streetAddress .= ' ';
1266 }
1267 $streetAddress .= CRM_Utils_Array::value($fld, $address);
1268 }
1269 $address['street_address'] = trim($streetAddress);
1270 $parseSuccess[$instance] = TRUE;
1271 }
1272 else {
1273 $success = TRUE;
1274 // consider address is automatically parseable,
1275 // when we should found street_number and street_name
1276 if (!CRM_Utils_Array::value('street_name', $parsedFields) ||
1277 !CRM_Utils_Array::value('street_number', $parsedFields)
1278 ) {
1279 $success = FALSE;
1280 }
1281
1282 // check for original street address string.
1283 if (empty($parseString)) {
1284 $success = TRUE;
1285 }
1286
1287 $parseSuccess[$instance] = $success;
1288
1289 // we do not reset element values, but keep what we've parsed
1290 // in case of partial matches: CRM-8378
1291
1292 // merge parse address in to main address block.
1293 $address = array_merge($address, $parsedFields);
1294 }
1295 }
1296
1297 return $parseSuccess;
1298 }
1299
1300 /**
1301 * check parse result and if some address block fails then this
1302 * function return the status message for all address blocks.
1303 *
1304 * @param $parseResult an array of address blk instance and its status.
1305 *
1306 * @return $statusMsg string status message for all address blocks.
1307 * @static
1308 */
1309 static function parseAddressStatusMsg($parseResult) {
1310 $statusMsg = NULL;
1311 if (!is_array($parseResult) || empty($parseResult)) {
1312 return $statusMsg;
1313 }
1314
1315 $parseFails = array();
1316 foreach ($parseResult as $instance => $success) {
1317 if (!$success) {
1318 $parseFails[] = self::ordinalNumber($instance);
1319 }
1320 }
1321
1322 if (!empty($parseFails)) {
1323 $statusMsg = ts("Complete street address(es) have been saved. However we were unable to split the address in the %1 address block(s) into address elements (street number, street name, street unit) due to an unrecognized address format. You can set the address elements manually by clicking 'Edit Address Elements' next to the Street Address field while in edit mode.",
1324 array(1 => implode(', ', $parseFails))
1325 );
1326 }
1327
1328 return $statusMsg;
1329 }
1330
1331 /**
1332 * Convert normal number to ordinal number format.
1333 * like 1 => 1st, 2 => 2nd and so on...
1334 *
1335 * @param $number int number to convert in to ordinal number.
1336 *
1337 * @return ordinal number for given number.
1338 * @static
1339 */
1340 static function ordinalNumber($number) {
1341 if (empty($number)) {
1342 return NULL;
1343 }
1344
1345 $str = 'th';
1346 switch (floor($number / 10) % 10) {
1347 case 1:
1348 default:
1349 switch ($number % 10) {
1350 case 1:
1351 $str = 'st';
1352 break;
1353
1354 case 2:
1355 $str = 'nd';
1356 break;
1357
1358 case 3:
1359 $str = 'rd';
1360 break;
1361 }
1362 }
1363
1364 return "$number$str";
1365 }
1366
1367 /**
1368 * Update membership status to deceased
1369 * function return the status message for updated membership.
1370 *
1371 * @param $deceasedParams array having contact id and deceased value.
1372 *
1373 * @return $updateMembershipMsg string status message for updated membership.
1374 */
1375 function updateMembershipStatus($deceasedParams) {
1376 $updateMembershipMsg = NULL;
1377 $contactId = CRM_Utils_Array::value('contact_id', $deceasedParams);
1378 $deceasedDate = CRM_Utils_Array::value('deceased_date', $deceasedParams);
1379
1380 // process to set membership status to deceased for both active/inactive membership
1381 if ($contactId &&
1382 $this->_contactType == 'Individual' &&
1383 CRM_Utils_Array::value('is_deceased', $deceasedParams)
1384 ) {
1385
1386 $session = CRM_Core_Session::singleton();
1387 $userId = $session->get('userID');
1388 if (!$userId) {
1389 $userId = $contactId;
1390 }
1391
1392
1393 // get deceased status id
1394 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
1395 $deceasedStatusId = array_search('Deceased', $allStatus);
1396 if (!$deceasedStatusId) {
1397 return $updateMembershipMsg;
1398 }
1399
1400 $today = time();
1401 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1402 return $updateMembershipMsg;
1403 }
1404
1405 // get non deceased membership
1406 $dao = new CRM_Member_DAO_Membership();
1407 $dao->contact_id = $contactId;
1408 $dao->whereAdd("status_id != $deceasedStatusId");
1409 $dao->find();
1410 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
1411 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
1412 $memCount = 0;
1413 while ($dao->fetch()) {
1414 // update status to deceased (for both active/inactive membership )
1415 CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $dao->id,
1416 'status_id', $deceasedStatusId
1417 );
1418
1419 // add membership log
1420 $membershipLog = array(
1421 'membership_id' => $dao->id,
1422 'status_id' => $deceasedStatusId,
1423 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1424 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1425 'modified_id' => $userId,
1426 'modified_date' => date('Ymd'),
1427 'membership_type_id' => $dao->membership_type_id,
1428 'max_related' => $dao->max_related,
1429 );
1430
1431
1432 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1433
1434 //create activity when membership status is changed
1435 $activityParam = array(
1436 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1437 'source_contact_id' => $userId,
1438 'target_contact_id' => $dao->contact_id,
1439 'source_record_id' => $dao->id,
1440 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1441 'status_id' => 2,
1442 'version' => 3,
1443 'priority_id' => 2,
1444 'activity_date_time' => date('Y-m-d H:i:s'),
1445 'is_auto' => 0,
1446 'is_current_revision' => 1,
1447 'is_deleted' => 0,
1448 );
1449 $activityResult = civicrm_api('activity', 'create', $activityParam);
1450
1451 $memCount++;
1452 }
1453
1454 // set status msg
1455 if ($memCount) {
1456 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1457 array(1 => $memCount)
1458 );
1459 }
1460 }
1461
1462 return $updateMembershipMsg;
1463 }
1464 }
1465