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