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