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