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