Merge pull request #7687 from JMAConsulting/CRM-16259-2
[civicrm-core.git] / CRM / Contact / Form / Contact.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
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
315 //build contact subtype form element, CRM-6864
316 $buildContactSubType = TRUE;
317 if ($this->_contactSubType && ($this->_action & CRM_Core_Action::ADD)) {
318 $buildContactSubType = FALSE;
319 }
320 $this->assign('buildContactSubType', $buildContactSubType);
321
322 // get the location blocks.
323 $this->_blocks = $this->get('blocks');
324 if (CRM_Utils_System::isNull($this->_blocks)) {
325 $this->_blocks = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
326 'contact_edit_options', TRUE, NULL,
327 FALSE, 'name', TRUE, 'AND v.filter = 1'
328 );
329 $this->set('blocks', $this->_blocks);
330 }
331 $this->assign('blocks', $this->_blocks);
332
333 // this is needed for custom data.
334 $this->assign('entityID', $this->_contactId);
335
336 // also keep the convention.
337 $this->assign('contactId', $this->_contactId);
338
339 // location blocks.
340 CRM_Contact_Form_Location::preProcess($this);
341
342 // retain the multiple count custom fields value
a7488080 343 if (!empty($_POST['hidden_custom'])) {
6a488035
TO
344 $customGroupCount = CRM_Utils_Array::value('hidden_custom_group_count', $_POST);
345
481a74f4 346 if ($contactSubType = CRM_Utils_Array::value('contact_sub_type', $_POST)) {
6a488035
TO
347 $paramSubType = implode(',', $contactSubType);
348 }
349
350 $this->_getCachedTree = FALSE;
351 unset($customGroupCount[0]);
352 foreach ($customGroupCount as $groupID => $groupCount) {
353 if ($groupCount > 1) {
354 $this->set('groupID', $groupID);
355 //loop the group
356 for ($i = 0; $i <= $groupCount; $i++) {
357 CRM_Custom_Form_CustomData::preProcess($this, NULL, $contactSubType,
358 $i, $this->_contactType
359 );
360 CRM_Contact_Form_Edit_CustomData::buildQuickForm($this);
361 }
362 }
363 }
364
365 //reset all the ajax stuff, for normal processing
366 if (isset($this->_groupTree)) {
367 $this->_groupTree = NULL;
368 }
369 $this->set('groupID', NULL);
370 $this->_getCachedTree = TRUE;
371 }
372
373 // execute preProcess dynamically by js else execute normal preProcess
374 if (array_key_exists('CustomData', $this->_editOptions)) {
375 //assign a parameter to pass for sub type multivalue
376 //custom field to load
377 if ($this->_contactSubType || isset($paramSubType)) {
378 $paramSubType = (isset($paramSubType)) ? $paramSubType :
481a74f4 379 str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ',', trim($this->_contactSubType, CRM_Core_DAO::VALUE_SEPARATOR));
6a488035
TO
380
381 $this->assign('paramSubType', $paramSubType);
382 }
383
384 if (CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject)) {
385 CRM_Contact_Form_Edit_CustomData::preProcess($this);
386 }
387 else {
388 $contactSubType = $this->_contactSubType;
389 // need contact sub type to build related grouptree array during post process
a7488080 390 if (!empty($_POST['contact_sub_type'])) {
6a488035
TO
391 $contactSubType = $_POST['contact_sub_type'];
392 }
393 //only custom data has preprocess hence directly call it
394 CRM_Custom_Form_CustomData::preProcess($this, NULL, $contactSubType,
395 1, $this->_contactType, $this->_contactId
396 );
397 $this->assign('customValueCount', $this->_customValueCount);
398 }
399 }
400 }
401
402 /**
c037736a 403 * Set default values for the form.
6a488035 404 *
c037736a 405 * Note that in edit/view mode the default values are retrieved from the database
6a488035 406 */
00be9182 407 public function setDefaultValues() {
6a488035 408 $defaults = $this->_values;
6a488035
TO
409
410 if ($this->_action & CRM_Core_Action::ADD) {
411 if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
412 // set group and tag defaults if any
413 if ($this->_gid) {
c18f95b7 414 $defaults['group'][] = $this->_gid;
6a488035
TO
415 }
416 if ($this->_tid) {
417 $defaults['tag'][$this->_tid] = 1;
418 }
419 }
420 if ($this->_contactSubType) {
421 $defaults['contact_sub_type'] = $this->_contactSubType;
422 }
423 }
424 else {
6a488035
TO
425 foreach ($defaults['email'] as $dontCare => & $val) {
426 if (isset($val['signature_text'])) {
427 $val['signature_text_hidden'] = $val['signature_text'];
428 }
429 if (isset($val['signature_html'])) {
430 $val['signature_html_hidden'] = $val['signature_html'];
431 }
432 }
433
a7488080 434 if (!empty($defaults['contact_sub_type'])) {
6a488035
TO
435 $defaults['contact_sub_type'] = $this->_oldSubtypes;
436 }
437 }
6a488035
TO
438 // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
439 foreach ($this->_editOptions as $name => $label) {
150f50c1
CW
440 if (!in_array($name, array('Address', 'Notes'))) {
441 $className = 'CRM_Contact_Form_Edit_' . $name;
442 $className::setDefaultValues($this, $defaults);
6a488035
TO
443 }
444 }
445
446 //set address block defaults
481a74f4 447 CRM_Contact_Form_Edit_Address::setDefaultValues($defaults, $this);
6a488035 448
a7488080 449 if (!empty($defaults['image_URL'])) {
77d45291 450 list($imageWidth, $imageHeight) = getimagesize(CRM_Utils_String::unstupifyUrl($defaults['image_URL']));
6a488035
TO
451 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
452 $this->assign('imageWidth', $imageWidth);
453 $this->assign('imageHeight', $imageHeight);
454 $this->assign('imageThumbWidth', $imageThumbWidth);
455 $this->assign('imageThumbHeight', $imageThumbHeight);
456 $this->assign('imageURL', $defaults['image_URL']);
457 }
458
459 //set location type and country to default for each block
460 $this->blockSetDefaults($defaults);
461
462 $this->_preEditValues = $defaults;
463 return $defaults;
464 }
465
466 /**
ea3ddccf 467 * Do the set default related to location type id, primary location, default country.
468 *
469 * @param array $defaults
6a488035 470 */
00be9182 471 public function blockSetDefaults(&$defaults) {
b2b0530a 472 $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int');
6a488035
TO
473 sort($locationTypeKeys);
474
475 // get the default location type
476 $locationType = CRM_Core_BAO_LocationType::getDefault();
477
478 // unset primary location type
479 $primaryLocationTypeIdKey = CRM_Utils_Array::key($locationType->id, $locationTypeKeys);
480 unset($locationTypeKeys[$primaryLocationTypeIdKey]);
481
482 // reset the array sequence
483 $locationTypeKeys = array_values($locationTypeKeys);
484
485 // get default phone and im provider id.
486 $defPhoneTypeId = key(CRM_Core_OptionGroup::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1'));
487 $defIMProviderId = key(CRM_Core_OptionGroup::values('instant_messenger_service',
353ffa53
TO
488 FALSE, FALSE, FALSE, ' AND is_default = 1'
489 ));
1d477756
PN
490 $defWebsiteTypeId = key(CRM_Core_OptionGroup::values('website_type',
491 FALSE, FALSE, FALSE, ' AND is_default = 1'
492 ));
6a488035
TO
493
494 $allBlocks = $this->_blocks;
495 if (array_key_exists('Address', $this->_editOptions)) {
496 $allBlocks['Address'] = $this->_editOptions['Address'];
497 }
498
499 $config = CRM_Core_Config::singleton();
500 foreach ($allBlocks as $blockName => $label) {
501 $name = strtolower($blockName);
502 $hasPrimary = $updateMode = FALSE;
503
504 // user is in update mode.
505 if (array_key_exists($name, $defaults) &&
506 !CRM_Utils_System::isNull($defaults[$name])
507 ) {
508 $updateMode = TRUE;
509 }
510
511 for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++) {
512 // make we require one primary block, CRM-5505
c600b8ac 513 if ($updateMode && !$hasPrimary) {
514 $hasPrimary = CRM_Utils_Array::value(
515 'is_primary',
516 CRM_Utils_Array::value($instance, $defaults[$name])
517 );
6a488035
TO
518 continue;
519 }
520
521 //set location to primary for first one.
522 if ($instance == 1) {
523 $hasPrimary = TRUE;
524 $defaults[$name][$instance]['is_primary'] = TRUE;
525 $defaults[$name][$instance]['location_type_id'] = $locationType->id;
526 }
527 else {
528 $locTypeId = isset($locationTypeKeys[$instance - 1]) ? $locationTypeKeys[$instance - 1] : $locationType->id;
529 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
530 }
531
532 //set default country
533 if ($name == 'address' && $config->defaultContactCountry) {
534 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry;
535 }
536
537 //set default state/province
538 if ($name == 'address' && $config->defaultContactStateProvince) {
539 $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince;
540 }
541
542 //set default phone type.
543 if ($name == 'phone' && $defPhoneTypeId) {
544 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
545 }
1d477756
PN
546 //set default website type.
547 if ($name == 'website' && $defWebsiteTypeId) {
548 $defaults[$name][$instance]['website_type_id'] = $defWebsiteTypeId;
549 }
6a488035
TO
550
551 //set default im provider.
552 if ($name == 'im' && $defIMProviderId) {
553 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
554 }
555 }
556
557 if (!$hasPrimary) {
558 $defaults[$name][1]['is_primary'] = TRUE;
559 }
560 }
6a488035
TO
561 }
562
563 /**
dc195289 564 * add the rules (mainly global rules) for form.
6a488035
TO
565 * All local rules are added near the element
566 *
6a488035
TO
567 * @see valid_date
568 */
00be9182 569 public function addRules() {
6a488035
TO
570 // skip adding formRules when custom data is build
571 if ($this->_addBlockName || ($this->_action & CRM_Core_Action::DELETE)) {
572 return;
573 }
574
575 $this->addFormRule(array('CRM_Contact_Form_Edit_' . $this->_contactType, 'formRule'), $this->_contactId);
576
577 // Call Locking check if editing existing contact
578 if ($this->_contactId) {
579 $this->addFormRule(array('CRM_Contact_Form_Edit_Lock', 'formRule'), $this->_contactId);
580 }
581
582 if (array_key_exists('Address', $this->_editOptions)) {
ac79e2f5 583 $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'), $this);
6a488035
TO
584 }
585
586 if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
587 $this->addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this);
588 }
589 }
590
591 /**
fe482240 592 * Global validation rules for the form.
6a488035 593 *
77c5b619
TO
594 * @param array $fields
595 * Posted values of the form.
596 * @param array $errors
597 * List of errors to be posted back to the form.
598 * @param int $contactId
599 * Contact id if doing update.
6a488035 600 *
a6c01b45
CW
601 * @return bool
602 * email/openId
6a488035 603 */
00be9182 604 public static function formRule($fields, &$errors, $contactId = NULL) {
6a488035
TO
605 $config = CRM_Core_Config::singleton();
606
607 // validations.
608 //1. for each block only single value can be marked as is_primary = true.
609 //2. location type id should be present if block data present.
610 //3. check open id across db and other each block for duplicate.
611 //4. at least one location should be primary.
612 //5. also get primaryID from email or open id block.
613
614 // take the location blocks.
615 $blocks = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
616 'contact_edit_options', TRUE, NULL,
617 FALSE, 'name', TRUE, 'AND v.filter = 1'
618 );
619
620 $otherEditOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
621 'contact_edit_options', TRUE, NULL,
622 FALSE, 'name', TRUE, 'AND v.filter = 0'
623 );
624 //get address block inside.
625 if (array_key_exists('Address', $otherEditOptions)) {
626 $blocks['Address'] = $otherEditOptions['Address'];
627 }
628
629 $openIds = array();
630 $primaryID = FALSE;
631 foreach ($blocks as $name => $label) {
632 $hasData = $hasPrimary = array();
633 $name = strtolower($name);
a7488080 634 if (!empty($fields[$name]) && is_array($fields[$name])) {
6a488035
TO
635 foreach ($fields[$name] as $instance => $blockValues) {
636 $dataExists = self::blockDataExists($blockValues);
637
638 if (!$dataExists && $name == 'address') {
639 $dataExists = CRM_Utils_Array::value('use_shared_address', $fields['address'][$instance]);
640 }
641
642 if ($dataExists) {
643 // skip remaining checks for website
644 if ($name == 'website') {
645 continue;
646 }
647
648 $hasData[] = $instance;
a7488080 649 if (!empty($blockValues['is_primary'])) {
6a488035
TO
650 $hasPrimary[] = $instance;
651 if (!$primaryID &&
652 in_array($name, array(
353ffa53 653 'email',
af9b09df 654 'openid',
353ffa53
TO
655 )) && !empty($blockValues[$name])
656 ) {
6a488035
TO
657 $primaryID = $blockValues[$name];
658 }
659 }
660
a7488080 661 if (empty($blockValues['location_type_id'])) {
6a488035
TO
662 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', array(1 => $label));
663 }
664 }
665
8cc574cf 666 if ($name == 'openid' && !empty($blockValues[$name])) {
353ffa53 667 $oid = new CRM_Core_DAO_OpenID();
6a488035 668 $oid->openid = $openIds[$instance] = CRM_Utils_Array::value($name, $blockValues);
353ffa53 669 $cid = isset($contactId) ? $contactId : 0;
6a488035
TO
670 if ($oid->find(TRUE) && ($oid->contact_id != $cid)) {
671 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID']));
672 }
673 }
674 }
675
676 if (empty($hasPrimary) && !empty($hasData)) {
677 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label));
678 }
679
680 if (count($hasPrimary) > 1) {
681 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
682 array(1 => $label)
683 );
684 }
685 }
686 }
687
688 //do validations for all opend ids they should be distinct.
689 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
690 foreach ($openIds as $instance => $value) {
691 if (!array_key_exists($instance, array_unique($openIds))) {
692 $errors["openid[$instance][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID']));
693 }
694 }
695 }
696
697 // street number should be digit + suffix, CRM-5450
698 $parseStreetAddress = CRM_Utils_Array::value('street_address_parsing',
699 CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
700 'address_options'
701 )
702 );
703 if ($parseStreetAddress) {
704 if (isset($fields['address']) &&
705 is_array($fields['address'])
706 ) {
707 $invalidStreetNumbers = array();
708 foreach ($fields['address'] as $cnt => $address) {
709 if ($streetNumber = CRM_Utils_Array::value('street_number', $address)) {
710 $parsedAddress = CRM_Core_BAO_Address::parseStreetAddress($address['street_number']);
a7488080 711 if (empty($parsedAddress['street_number'])) {
6a488035
TO
712 $invalidStreetNumbers[] = $cnt;
713 }
714 }
715 }
716
717 if (!empty($invalidStreetNumbers)) {
718 $first = $invalidStreetNumbers[0];
353ffa53
TO
719 foreach ($invalidStreetNumbers as & $num) {
720 $num = CRM_Contact_Form_Contact::ordinalNumber($num);
721 }
6a488035
TO
722 $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)));
723 }
724 }
725 }
726
727 return $primaryID;
728 }
729
730 /**
fe482240 731 * Build the form object.
6a488035
TO
732 */
733 public function buildQuickForm() {
734 //load form for child blocks
735 if ($this->_addBlockName) {
150f50c1
CW
736 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName;
737 return $className::buildQuickForm($this);
6a488035
TO
738 }
739
740 if ($this->_action == CRM_Core_Action::UPDATE) {
e8fb9449 741 $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.'));
6a488035 742 $deleteURL = array(
af9b09df
TO
743 CRM_Core_Action::DELETE => array(
744 'name' => ts('Delete Contact Image'),
745 'url' => 'civicrm/contact/image',
746 'qs' => 'reset=1&cid=%%id%%&action=delete',
e8fb9449 747 'extra' => 'onclick = "' . htmlspecialchars("if (confirm($deleteExtra)) this.href+='&confirmed=1'; else return false;") . '"',
af9b09df 748 ),
6a488035
TO
749 );
750 $deleteURL = CRM_Core_Action::formLink($deleteURL,
751 CRM_Core_Action::DELETE,
752 array(
753 'id' => $this->_contactId,
87dab4a4
AH
754 ),
755 ts('more'),
756 FALSE,
757 'contact.image.delete',
758 'Contact',
759 $this->_contactId
6a488035
TO
760 );
761 $this->assign('deleteURL', $deleteURL);
762 }
763
764 //build contact type specific fields
150f50c1
CW
765 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType;
766 $className::buildQuickForm($this);
6a488035
TO
767
768 // build Custom data if Custom data present in edit option
769 $buildCustomData = 'noCustomDataPresent';
770 if (array_key_exists('CustomData', $this->_editOptions)) {
771 $buildCustomData = "customDataPresent";
772 }
773
774 // subtype is a common field. lets keep it here
ab345ca5 775 $subtypes = CRM_Contact_BAO_Contact::buildOptions('contact_sub_type', 'create', array('contact_type' => $this->_contactType));
6a488035 776 if (!empty($subtypes)) {
33fa033c
TM
777 $this->addField('contact_sub_type', array(
778 'label' => ts('Contact Type'),
779 'options' => $subtypes,
780 'class' => $buildCustomData,
781 'multiple' => 'multiple',
599ae208
CW
782 'option_url' => NULL,
783 ));
6a488035
TO
784 }
785
786 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
787 foreach ($this->_editOptions as $name => $label) {
788 if ($name == 'Address') {
789 $this->_blocks['Address'] = $this->_editOptions['Address'];
790 continue;
791 }
c18f95b7
PJ
792 if ($name == 'TagsAndGroups') {
793 continue;
794 }
150f50c1
CW
795 $className = 'CRM_Contact_Form_Edit_' . $name;
796 $className::buildQuickForm($this);
6a488035
TO
797 }
798
c18f95b7
PJ
799 // build tags and groups
800 CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups::ALL,
ab345ca5 801 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'select');
c18f95b7 802
6a488035
TO
803 // build location blocks.
804 CRM_Contact_Form_Edit_Lock::buildQuickForm($this);
805 CRM_Contact_Form_Location::buildQuickForm($this);
806
807 // add attachment
51479855 808 $this->addField('image_URL', array('maxlength' => '60', 'label' => ts('Browse/Upload Image')));
6a488035
TO
809
810 // add the dedupe button
811 $this->addElement('submit',
812 $this->_dedupeButtonName,
813 ts('Check for Matching Contact(s)')
814 );
815 $this->addElement('submit',
816 $this->_duplicateButtonName,
817 ts('Save Matching Contact')
818 );
819 $this->addElement('submit',
820 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
821 ts('Save With Duplicate Household')
822 );
823
824 $buttons = array(
825 array(
826 'type' => 'upload',
827 'name' => ts('Save'),
828 'subName' => 'view',
829 'isDefault' => TRUE,
830 ),
1870cae9
CW
831 );
832 if (CRM_Core_Permission::check('add contacts')) {
833 $buttons[] = array(
6a488035
TO
834 'type' => 'upload',
835 'name' => ts('Save and New'),
836 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
837 'subName' => 'new',
1870cae9
CW
838 );
839 }
840 $buttons[] = array(
841 'type' => 'cancel',
842 'name' => ts('Cancel'),
6a488035
TO
843 );
844
a7488080 845 if (!empty($this->_values['contact_sub_type'])) {
6a488035
TO
846 $this->_oldSubtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
847 trim($this->_values['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR)
848 );
849 }
850 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes));
851
852 $this->addButtons($buttons);
853 }
854
855 /**
856 * Form submission of new/edit contact is processed.
6a488035
TO
857 */
858 public function postProcess() {
859 // check if dedupe button, if so return.
860 $buttonName = $this->controller->getButtonName();
861 if ($buttonName == $this->_dedupeButtonName) {
862 return;
863 }
864
865 //get the submitted values in an array
866 $params = $this->controller->exportValues($this->_name);
867
c18f95b7 868 $group = CRM_Utils_Array::value('group', $params);
7e6c32e8 869 if (!empty($group) && is_array($group)) {
c18f95b7
PJ
870 unset($params['group']);
871 foreach ($group as $key => $value) {
872 $params['group'][$value] = 1;
873 }
874 }
875
481a74f4 876 CRM_Contact_BAO_Contact_Optimizer::edit($params, $this->_preEditValues);
6a488035 877
a7488080 878 if (!empty($params['image_URL'])) {
6a488035
TO
879 CRM_Contact_BAO_Contact::processImageParams($params);
880 }
881
8cc574cf 882 if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
6a488035
TO
883 $params['current_employer'] = $params['current_employer_id'];
884 }
885
886 // don't carry current_employer_id field,
887 // since we don't want to directly update DAO object without
888 // handling related business logic ( eg related membership )
889 if (isset($params['current_employer_id'])) {
890 unset($params['current_employer_id']);
891 }
892
893 $params['contact_type'] = $this->_contactType;
894 if (empty($params['contact_sub_type']) && $this->_isContactSubType) {
895 $params['contact_sub_type'] = array($this->_contactSubType);
896 }
897
898 if ($this->_contactId) {
899 $params['contact_id'] = $this->_contactId;
900 }
901
902 //make deceased date null when is_deceased = false
8cc574cf 903 if ($this->_contactType == 'Individual' && !empty($this->_editOptions['Demographics']) && empty($params['is_deceased'])) {
6a488035
TO
904 $params['is_deceased'] = FALSE;
905 $params['deceased_date'] = NULL;
906 }
907
908 if (isset($params['contact_id'])) {
909 // process membership status for deceased contact
6ea503d4
TO
910 $deceasedParams = array(
911 'contact_id' => CRM_Utils_Array::value('contact_id', $params),
6a488035
TO
912 'is_deceased' => CRM_Utils_Array::value('is_deceased', $params, FALSE),
913 'deceased_date' => CRM_Utils_Array::value('deceased_date', $params, NULL),
914 );
915 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
916 }
917
918 // action is taken depending upon the mode
919 if ($this->_action & CRM_Core_Action::UPDATE) {
920 CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
921 }
922 else {
923 CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
924 }
925
926 $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], FALSE, TRUE);
927
928 //CRM-5143
929 //if subtype is set, send subtype as extend to validate subtype customfield
930 $customFieldExtends = (CRM_Utils_Array::value('contact_sub_type', $params)) ? $params['contact_sub_type'] : $params['contact_type'];
931
932 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
6a488035
TO
933 $this->_contactId,
934 $customFieldExtends,
935 TRUE
936 );
937 if ($this->_contactId && !empty($this->_oldSubtypes)) {
938 CRM_Contact_BAO_ContactType::deleteCustomSetForSubtypeMigration($this->_contactId,
939 $params['contact_type'],
940 $this->_oldSubtypes,
941 $params['contact_sub_type']
942 );
943 }
944
945 if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
946 // this is a chekbox, so mark false if we dont get a POST value
947 $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
948 }
949
950 // process shared contact address.
951 CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']);
952
7e6c32e8 953 if (!array_key_exists('TagsAndGroups', $this->_editOptions) && !empty($params['group'])) {
6a488035
TO
954 unset($params['group']);
955 }
956
7e6c32e8 957 if (!empty($params['contact_id']) && ($this->_action & CRM_Core_Action::UPDATE) && !empty($params['group'])) {
6a488035 958 // figure out which all groups are intended to be removed
c18f95b7
PJ
959 $contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
960 if (is_array($contactGroupList)) {
961 foreach ($contactGroupList as $key) {
8cc574cf 962 if ((!array_key_exists($key['group_id'], $params['group']) || $params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
c18f95b7 963 $params['group'][$key['group_id']] = -1;
6a488035
TO
964 }
965 }
966 }
967 }
968
969 // parse street address, CRM-5450
970 $parseStatusMsg = NULL;
971 if ($this->_parseStreetAddress) {
972 $parseResult = self::parseAddress($params);
973 $parseStatusMsg = self::parseAddressStatusMsg($parseResult);
974 }
975
139a60f3 976 $blocks = array('email', 'phone', 'im', 'openid', 'address', 'website');
85c882c5 977 foreach ($blocks as $block) {
a3b489b9 978 if (!empty($this->_preEditValues[$block]) && is_array($this->_preEditValues[$block])) {
979 foreach ($this->_preEditValues[$block] as $count => $value) {
980 if (!empty($value['id'])) {
981 $params[$block][$count]['id'] = $value['id'];
982 $params[$block]['isIdSet'] = TRUE;
983 }
85c882c5 984 }
985 }
986 }
987
6a488035
TO
988 // Allow un-setting of location info, CRM-5969
989 $params['updateBlankLocInfo'] = TRUE;
990
991 $contact = CRM_Contact_BAO_Contact::create($params, TRUE, FALSE, TRUE);
992
993 // status message
994 if ($this->_contactId) {
995 $message = ts('%1 has been updated.', array(1 => $contact->display_name));
996 }
997 else {
998 $message = ts('%1 has been created.', array(1 => $contact->display_name));
999 }
1000
1001 // set the contact ID
1002 $this->_contactId = $contact->id;
1003
1004 if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
1005 //add contact to tags
1006 CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1007
1008 //save free tags
1009 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1010 CRM_Core_Form_Tag::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1011 }
1012 }
1013
1014 if (!empty($parseStatusMsg)) {
1015 $message .= "<br />$parseStatusMsg";
1016 }
1017 if (!empty($updateMembershipMsg)) {
1018 $message .= "<br />$updateMembershipMsg";
1019 }
1020
1021 $session = CRM_Core_Session::singleton();
1022 $session->setStatus($message, ts('Contact Saved'), 'success');
1023
1024 // add the recently viewed contact
1025 $recentOther = array();
1026 if (($session->get('userID') == $contact->id) ||
1027 CRM_Contact_BAO_Contact_Permission::allow($contact->id, CRM_Core_Permission::EDIT)
1028 ) {
1029 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id);
1030 }
1031
1032 if (($session->get('userID') != $this->_contactId) && CRM_Core_Permission::check('delete contacts')) {
1033 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id);
1034 }
1035
1036 CRM_Utils_Recent::add($contact->display_name,
1037 CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id),
1038 $contact->id,
1039 $this->_contactType,
1040 $contact->id,
1041 $contact->display_name,
1042 $recentOther
1043 );
1044
1045 // here we replace the user context with the url to view this contact
1046 $buttonName = $this->controller->getButtonName();
1047 if ($buttonName == $this->getButtonName('upload', 'new')) {
69dde52d 1048 $contactSubTypes = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_contactSubType));
6a488035 1049 $resetStr = "reset=1&ct={$contact->contact_type}";
69dde52d 1050 $resetStr .= (count($contactSubTypes) == 1) ? "&cst=" . array_pop($contactSubTypes) : '';
6a488035
TO
1051 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr));
1052 }
1053 else {
1054 $context = CRM_Utils_Request::retrieve('context', 'String', $this);
1055 $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
1056 //validate the qfKey
1057 $urlParams = 'reset=1&cid=' . $contact->id;
1058 if ($context) {
1059 $urlParams .= "&context=$context";
1060 }
1061 if (CRM_Utils_Rule::qfKey($qfKey)) {
1062 $urlParams .= "&key=$qfKey";
1063 }
1064
1065 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams));
1066 }
1067
1068 // now invoke the post hook
1069 if ($this->_action & CRM_Core_Action::UPDATE) {
1070 CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
1071 }
1072 else {
1073 CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
1074 }
1075 }
1076
1077 /**
fe482240 1078 * Is there any real significant data in the hierarchical location array.
6a488035 1079 *
77c5b619
TO
1080 * @param array $fields
1081 * The hierarchical value representation of this location.
6a488035 1082 *
5c766a0b 1083 * @return bool
a6c01b45 1084 * true if data exists, false otherwise
6a488035 1085 */
00be9182 1086 public static function blockDataExists(&$fields) {
6a488035
TO
1087 if (!is_array($fields)) {
1088 return FALSE;
1089 }
1090
353ffa53
TO
1091 static $skipFields = array(
1092 'location_type_id',
1093 'is_primary',
1094 'phone_type_id',
1095 'provider_id',
1096 'country_id',
1097 'website_type_id',
af9b09df 1098 'master_id',
353ffa53 1099 );
6a488035
TO
1100 foreach ($fields as $name => $value) {
1101 $skipField = FALSE;
1102 foreach ($skipFields as $skip) {
1103 if (strpos("[$skip]", $name) !== FALSE) {
1104 if ($name == 'phone') {
1105 continue;
1106 }
1107 $skipField = TRUE;
1108 break;
1109 }
1110 }
1111 if ($skipField) {
1112 continue;
1113 }
1114 if (is_array($value)) {
1115 if (self::blockDataExists($value)) {
1116 return TRUE;
1117 }
1118 }
1119 else {
1120 if (!empty($value)) {
1121 return TRUE;
1122 }
1123 }
1124 }
1125
1126 return FALSE;
1127 }
1128
1129 /**
fe482240 1130 * That checks for duplicate contacts.
6a488035 1131 *
77c5b619
TO
1132 * @param array $fields
1133 * Fields array which are submitted.
fd31fa4c 1134 * @param $errors
77c5b619
TO
1135 * @param int $contactID
1136 * Contact id.
1137 * @param string $contactType
1138 * Contact type.
6a488035 1139 */
00be9182 1140 public static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
6a488035 1141 // if this is a forced save, ignore find duplicate rule
a7488080 1142 if (empty($fields['_qf_Contact_upload_duplicate'])) {
6a488035
TO
1143
1144 $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, $contactType);
1145 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, 'Supervised', array($contactID));
1146 if ($ids) {
1147
1148 $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1149
1150 $duplicateContactsLinks = '<div class="matching-contacts-found">';
353ffa53
TO
1151 $duplicateContactsLinks .= ts('One matching contact was found. ', array(
1152 'count' => count($contactLinks['rows']),
af9b09df 1153 'plural' => '%count matching contacts were found.<br />',
353ffa53 1154 ));
6a488035 1155 if ($contactLinks['msg'] == 'view') {
353ffa53
TO
1156 $duplicateContactsLinks .= ts('You can View the existing contact', array(
1157 'count' => count($contactLinks['rows']),
af9b09df 1158 'plural' => 'You can View the existing contacts',
353ffa53 1159 ));
6a488035
TO
1160 }
1161 else {
353ffa53
TO
1162 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array(
1163 'count' => count($contactLinks['rows']),
af9b09df 1164 'plural' => 'You can View or Edit the existing contacts',
353ffa53 1165 ));
6a488035
TO
1166 }
1167 if ($contactLinks['msg'] == 'merge') {
1168 // We should also get a merge link if this is for an existing contact
1169 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1170 }
1171 $duplicateContactsLinks .= '.';
1172 $duplicateContactsLinks .= '</div>';
1173 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1174 $row = '';
1175 for ($i = 0; $i < count($contactLinks['rows']); $i++) {
1176 $row .= ' <tr> ';
1177 $row .= ' <td class="matching-contacts-name"> ';
1178 $row .= $contactLinks['rows'][$i]['display_name'];
1179 $row .= ' </td>';
1180 $row .= ' <td class="matching-contacts-email"> ';
1181 $row .= $contactLinks['rows'][$i]['primary_email'];
1182 $row .= ' </td>';
1183 $row .= ' <td class="action-items"> ';
1184 $row .= $contactLinks['rows'][$i]['view'];
1185 $row .= $contactLinks['rows'][$i]['edit'];
1186 $row .= CRM_Utils_Array::value('merge', $contactLinks['rows'][$i]);
1187 $row .= ' </td>';
1188 $row .= ' </tr> ';
1189 }
1190
1191 $duplicateContactsLinks .= $row . '</table>';
1192 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1193
1194 $errors['_qf_default'] = $duplicateContactsLinks;
1195
6a488035
TO
1196 // let smarty know that there are duplicates
1197 $template = CRM_Core_Smarty::singleton();
1198 $template->assign('isDuplicate', 1);
1199 }
a7488080 1200 elseif (!empty($fields['_qf_Contact_refresh_dedupe'])) {
6a488035
TO
1201 // add a session message for no matching contacts
1202 CRM_Core_Session::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1203 }
1204 }
1205 }
1206
86538308 1207 /**
fe482240 1208 * Use the form name to create the tpl file name.
86538308
EM
1209 *
1210 * @return string
86538308 1211 */
00be9182 1212 public function getTemplateFileName() {
6a488035
TO
1213 if ($this->_contactSubType) {
1214 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1215 $template = CRM_Core_Form::getTemplate();
1216 if ($template->template_exists($templateFile)) {
1217 return $templateFile;
1218 }
1219 }
1220 return parent::getTemplateFileName();
1221 }
1222
1223 /**
1224 * Parse all address blocks present in given params
77b97be7
EM
1225 * and return parse result for all address blocks,
1226 * This function either parse street address in to child
1227 * elements or build street address from child elements.
1228 *
5a4f6742
CW
1229 * @param array $params
1230 * of key value consist of address blocks.
77b97be7 1231 *
a6c01b45 1232 * @return array
b44e3f84 1233 * as array of success/fails for each address block
77b97be7 1234 */
00be9182 1235 public function parseAddress(&$params) {
6a488035
TO
1236 $parseSuccess = $parsedFields = array();
1237 if (!is_array($params['address']) ||
1238 CRM_Utils_System::isNull($params['address'])
1239 ) {
1240 return $parseSuccess;
1241 }
1242
1243 foreach ($params['address'] as $instance => & $address) {
1244 $buildStreetAddress = FALSE;
1245 $parseFieldName = 'street_address';
1246 foreach (array(
353ffa53
TO
1247 'street_number',
1248 'street_name',
af9b09df 1249 'street_unit',
353ffa53 1250 ) as $fld) {
a7488080 1251 if (!empty($address[$fld])) {
6a488035
TO
1252 $parseFieldName = 'street_number';
1253 $buildStreetAddress = TRUE;
1254 break;
1255 }
1256 }
1257
1258 // main parse string.
1259 $parseString = CRM_Utils_Array::value($parseFieldName, $address);
1260
1261 // parse address field.
1262 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($parseString);
1263
1264 if ($buildStreetAddress) {
1265 //hack to ignore spaces between number and suffix.
1266 //here user gives input as street_number so it has to
1267 //be street_number and street_number_suffix, but
1268 //due to spaces though preg detect string as street_name
1269 //consider it as 'street_number_suffix'.
1270 $suffix = $parsedFields['street_number_suffix'];
1271 if (!$suffix) {
1272 $suffix = $parsedFields['street_name'];
1273 }
1274 $address['street_number_suffix'] = $suffix;
1275 $address['street_number'] = $parsedFields['street_number'];
1276
1277 $streetAddress = NULL;
1278 foreach (array(
353ffa53
TO
1279 'street_number',
1280 'street_number_suffix',
1281 'street_name',
af9b09df 1282 'street_unit',
353ffa53 1283 ) as $fld) {
6a488035 1284 if (in_array($fld, array(
353ffa53 1285 'street_name',
af9b09df 1286 'street_unit',
353ffa53 1287 ))) {
6a488035
TO
1288 $streetAddress .= ' ';
1289 }
1290 $streetAddress .= CRM_Utils_Array::value($fld, $address);
1291 }
1292 $address['street_address'] = trim($streetAddress);
1293 $parseSuccess[$instance] = TRUE;
1294 }
1295 else {
1296 $success = TRUE;
1297 // consider address is automatically parseable,
1298 // when we should found street_number and street_name
8cc574cf 1299 if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
6a488035
TO
1300 $success = FALSE;
1301 }
1302
1303 // check for original street address string.
1304 if (empty($parseString)) {
1305 $success = TRUE;
1306 }
1307
1308 $parseSuccess[$instance] = $success;
1309
1310 // we do not reset element values, but keep what we've parsed
1311 // in case of partial matches: CRM-8378
1312
1313 // merge parse address in to main address block.
1314 $address = array_merge($address, $parsedFields);
1315 }
1316 }
1317
1318 return $parseSuccess;
1319 }
1320
1321 /**
100fef9d 1322 * Check parse result and if some address block fails then this
6a488035
TO
1323 * function return the status message for all address blocks.
1324 *
5a4f6742 1325 * @param array $parseResult
77c5b619 1326 * An array of address blk instance and its status.
6a488035 1327 *
72b3a70c
CW
1328 * @return null|string
1329 * $statusMsg string status message for all address blocks.
6a488035 1330 */
00be9182 1331 public static function parseAddressStatusMsg($parseResult) {
6a488035
TO
1332 $statusMsg = NULL;
1333 if (!is_array($parseResult) || empty($parseResult)) {
1334 return $statusMsg;
1335 }
1336
1337 $parseFails = array();
1338 foreach ($parseResult as $instance => $success) {
1339 if (!$success) {
1340 $parseFails[] = self::ordinalNumber($instance);
1341 }
1342 }
1343
1344 if (!empty($parseFails)) {
1345 $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.",
1346 array(1 => implode(', ', $parseFails))
1347 );
1348 }
1349
1350 return $statusMsg;
1351 }
1352
1353 /**
1354 * Convert normal number to ordinal number format.
1355 * like 1 => 1st, 2 => 2nd and so on...
1356 *
5a4f6742
CW
1357 * @param int $number
1358 * number to convert in to ordinal number.
6a488035 1359 *
72b3a70c
CW
1360 * @return string
1361 * ordinal number for given number.
6a488035 1362 */
00be9182 1363 public static function ordinalNumber($number) {
6a488035
TO
1364 if (empty($number)) {
1365 return NULL;
1366 }
1367
1368 $str = 'th';
1369 switch (floor($number / 10) % 10) {
1370 case 1:
1371 default:
1372 switch ($number % 10) {
1373 case 1:
1374 $str = 'st';
1375 break;
1376
1377 case 2:
1378 $str = 'nd';
1379 break;
1380
1381 case 3:
1382 $str = 'rd';
1383 break;
1384 }
1385 }
1386
1387 return "$number$str";
1388 }
1389
1390 /**
fe482240 1391 * Update membership status to deceased.
6a488035
TO
1392 * function return the status message for updated membership.
1393 *
5a4f6742
CW
1394 * @param array $deceasedParams
1395 * having contact id and deceased value.
6a488035 1396 *
72b3a70c
CW
1397 * @return null|string
1398 * $updateMembershipMsg string status message for updated membership.
6a488035 1399 */
00be9182 1400 public function updateMembershipStatus($deceasedParams) {
6a488035 1401 $updateMembershipMsg = NULL;
353ffa53
TO
1402 $contactId = CRM_Utils_Array::value('contact_id', $deceasedParams);
1403 $deceasedDate = CRM_Utils_Array::value('deceased_date', $deceasedParams);
6a488035
TO
1404
1405 // process to set membership status to deceased for both active/inactive membership
1406 if ($contactId &&
353ffa53
TO
1407 $this->_contactType == 'Individual' && !empty($deceasedParams['is_deceased'])
1408 ) {
6a488035
TO
1409
1410 $session = CRM_Core_Session::singleton();
1411 $userId = $session->get('userID');
1412 if (!$userId) {
1413 $userId = $contactId;
1414 }
1415
6a488035
TO
1416 // get deceased status id
1417 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
1418 $deceasedStatusId = array_search('Deceased', $allStatus);
1419 if (!$deceasedStatusId) {
1420 return $updateMembershipMsg;
1421 }
1422
1423 $today = time();
1424 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1425 return $updateMembershipMsg;
1426 }
1427
1428 // get non deceased membership
1429 $dao = new CRM_Member_DAO_Membership();
1430 $dao->contact_id = $contactId;
1431 $dao->whereAdd("status_id != $deceasedStatusId");
1432 $dao->find();
1433 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
353ffa53 1434 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
6a488035
TO
1435 $memCount = 0;
1436 while ($dao->fetch()) {
1437 // update status to deceased (for both active/inactive membership )
1438 CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $dao->id,
1439 'status_id', $deceasedStatusId
1440 );
1441
1442 // add membership log
1443 $membershipLog = array(
1444 'membership_id' => $dao->id,
1445 'status_id' => $deceasedStatusId,
1446 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1447 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1448 'modified_id' => $userId,
1449 'modified_date' => date('Ymd'),
1450 'membership_type_id' => $dao->membership_type_id,
1451 'max_related' => $dao->max_related,
1452 );
1453
6a488035
TO
1454 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1455
1456 //create activity when membership status is changed
1457 $activityParam = array(
1458 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1459 'source_contact_id' => $userId,
1460 'target_contact_id' => $dao->contact_id,
1461 'source_record_id' => $dao->id,
1462 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1463 'status_id' => 2,
1464 'version' => 3,
1465 'priority_id' => 2,
1466 'activity_date_time' => date('Y-m-d H:i:s'),
1467 'is_auto' => 0,
1468 'is_current_revision' => 1,
1469 'is_deleted' => 0,
1470 );
1471 $activityResult = civicrm_api('activity', 'create', $activityParam);
1472
1473 $memCount++;
1474 }
1475
1476 // set status msg
1477 if ($memCount) {
1478 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1479 array(1 => $memCount)
1480 );
1481 }
1482 }
1483
1484 return $updateMembershipMsg;
1485 }
96025800 1486
6a488035 1487}