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