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