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