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