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