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