Merge pull request #9596 from eileenmcnaughton/performance
[civicrm-core.git] / CRM / Contact / BAO / Contact.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2017
32 */
33 class CRM_Contact_BAO_Contact extends CRM_Contact_DAO_Contact {
34
35 /**
36 * SQL function used to format the phone_numeric field via trigger.
37 * @see self::triggerInfo()
38 *
39 * Note that this is also used by the 4.3 upgrade script.
40 * @see CRM_Upgrade_Incremental_php_FourThree
41 */
42 const DROP_STRIP_FUNCTION_43 = "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
43 const CREATE_STRIP_FUNCTION_43 = "
44 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
45 RETURNS VARCHAR(255) CHARACTER SET utf8
46 DETERMINISTIC
47 NO SQL
48 BEGIN
49 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
50 DECLARE iterator INT DEFAULT 1;
51 WHILE iterator < (LENGTH(input) + 1) DO
52 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
53 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
54 END IF;
55 SET iterator = iterator + 1;
56 END WHILE;
57 RETURN output;
58 END";
59
60 /**
61 * The types of communication preferences.
62 *
63 * @var array
64 */
65 static $_commPrefs = array(
66 'do_not_phone',
67 'do_not_email',
68 'do_not_mail',
69 'do_not_sms',
70 'do_not_trade',
71 );
72
73 /**
74 * Types of greetings.
75 *
76 * @var array
77 */
78 static $_greetingTypes = array(
79 'addressee',
80 'email_greeting',
81 'postal_greeting',
82 );
83
84 /**
85 * Static field for all the contact information that we can potentially import.
86 *
87 * @var array
88 */
89 static $_importableFields = array();
90
91 /**
92 * Static field for all the contact information that we can potentially export.
93 *
94 * @var array
95 */
96 static $_exportableFields = NULL;
97
98 /**
99 * Class constructor.
100 */
101 public function __construct() {
102 parent::__construct();
103 }
104
105 /**
106 * Takes an associative array and creates a contact object.
107 *
108 * The function extracts all the params it needs to initialize the create a
109 * contact object. the params array could contain additional unused name/value
110 * pairs
111 *
112 * @param array $params
113 * (reference) an assoc array of name/value pairs.
114 *
115 * @return CRM_Contact_BAO_Contact|CRM_Core_Error|NULL
116 * Created or updated contact object or error object.
117 * (error objects are being phased out in favour of exceptions)
118 */
119 public static function add(&$params) {
120 $contact = new CRM_Contact_DAO_Contact();
121
122 if (empty($params)) {
123 return NULL;
124 }
125
126 // Fix for validate contact sub type CRM-5143.
127 if (isset($params['contact_sub_type'])) {
128 if (empty($params['contact_sub_type'])) {
129 $params['contact_sub_type'] = 'null';
130 }
131 else {
132 if (!CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'],
133 $params['contact_type'], TRUE
134 )
135 ) {
136 // we'll need to fix tests to handle this
137 // CRM-7925
138 CRM_Core_Error::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
139 }
140 $params['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
141 }
142 }
143 else {
144 // Reset the value.
145 // CRM-101XX.
146 $params['contact_sub_type'] = 'null';
147 }
148
149 // Fixed contact source.
150 if (isset($params['contact_source'])) {
151 $params['source'] = $params['contact_source'];
152 }
153
154 // Fix for preferred communication method.
155 $prefComm = CRM_Utils_Array::value('preferred_communication_method', $params, '');
156 if ($prefComm && is_array($prefComm)) {
157 unset($params['preferred_communication_method']);
158
159 CRM_Utils_Array::formatArrayKeys($prefComm);
160 $prefComm = CRM_Utils_Array::implodePadded($prefComm);
161 }
162
163 $contact->preferred_communication_method = $prefComm;
164
165 $allNull = $contact->copyValues($params);
166
167 $contact->id = CRM_Utils_Array::value('contact_id', $params);
168
169 if ($contact->contact_type == 'Individual') {
170 $allNull = FALSE;
171
172 // Format individual fields.
173 CRM_Contact_BAO_Individual::format($params, $contact);
174 }
175 elseif ($contact->contact_type == 'Household') {
176 if (isset($params['household_name'])) {
177 $allNull = FALSE;
178 $contact->display_name = $contact->sort_name = CRM_Utils_Array::value('household_name', $params, '');
179 }
180 }
181 elseif ($contact->contact_type == 'Organization') {
182 if (isset($params['organization_name'])) {
183 $allNull = FALSE;
184 $contact->display_name = $contact->sort_name = CRM_Utils_Array::value('organization_name', $params, '');
185 }
186 }
187
188 $privacy = CRM_Utils_Array::value('privacy', $params);
189 if ($privacy &&
190 is_array($privacy) &&
191 !empty($privacy)
192 ) {
193 $allNull = FALSE;
194 foreach (self::$_commPrefs as $name) {
195 $contact->$name = CRM_Utils_Array::value($name, $privacy, FALSE);
196 }
197 }
198
199 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
200 // @todo - does this mean we can remove this block?
201 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
202 if ((!array_key_exists('hash', $contact) || !$contact->hash) && !$contact->id) {
203 $allNull = FALSE;
204 $contact->hash = md5(uniqid(rand(), TRUE));
205 }
206
207 // Even if we don't need $employerId, it's important to call getFieldValue() before
208 // the contact is saved because we want the existing value to be cached.
209 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
210 $employerId = empty($contact->id) ? NULL : CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contact->id, 'employer_id');
211
212 if (!$allNull) {
213 $contact->save();
214
215 CRM_Core_BAO_Log::register($contact->id,
216 'civicrm_contact',
217 $contact->id
218 );
219 }
220
221 if ($contact->contact_type == 'Individual' && (isset($params['current_employer']) || isset($params['employer_id']))) {
222 // Create current employer.
223 $newEmployer = !empty($params['employer_id']) ? $params['employer_id'] : CRM_Utils_Array::value('current_employer', $params);
224
225 $newContact = FALSE;
226 if (empty($params['contact_id'])) {
227 $newContact = TRUE;
228 }
229 if ($newEmployer) {
230 CRM_Contact_BAO_Contact_Utils::createCurrentEmployerRelationship($contact->id, $newEmployer, $employerId, $newContact);
231 }
232 else {
233 if ($employerId) {
234 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($contact->id, $employerId);
235 }
236 }
237 }
238
239 // Update cached employer name.
240 if ($contact->contact_type == 'Organization') {
241 CRM_Contact_BAO_Contact_Utils::updateCurrentEmployer($contact->id);
242 }
243
244 return $contact;
245 }
246
247 /**
248 * Create contact.
249 *
250 * takes an associative array and creates a contact object and all the associated
251 * derived objects (i.e. individual, location, email, phone etc)
252 *
253 * This function is invoked from within the web form layer and also from the api layer
254 *
255 * @param array $params
256 * (reference ) an assoc array of name/value pairs.
257 * @param bool $fixAddress
258 * If we need to fix address.
259 * @param bool $invokeHooks
260 * If we need to invoke hooks.
261 *
262 * @param bool $skipDelete
263 * Unclear parameter, passed to website create
264 *
265 * @todo explain this parameter
266 *
267 * @throws Exception
268 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
269 * Created or updated contribution object. We are deprecating returning an error in
270 * favour of exceptions
271 */
272 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
273 $contact = NULL;
274 if (empty($params['contact_type']) && empty($params['contact_id'])) {
275 return $contact;
276 }
277
278 $isEdit = TRUE;
279 if ($invokeHooks) {
280 if (!empty($params['contact_id'])) {
281 CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
282 }
283 else {
284 CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
285 $isEdit = FALSE;
286 }
287 }
288
289 $config = CRM_Core_Config::singleton();
290
291 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
292 if (empty($params['contact_id'])) {
293 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
294 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n::getContactDefaultLanguage()) != FALSE) {
295 $params['preferred_language'] = $language;
296 }
297
298 // CRM-9739: set greeting & addressee if unset and we’re creating a contact.
299 foreach (self::$_greetingTypes as $greeting) {
300 if (empty($params[$greeting . '_id'])) {
301 if ($defaultGreetingTypeId
302 = CRM_Contact_BAO_Contact_Utils::defaultGreeting($params['contact_type'], $greeting)
303 ) {
304 $params[$greeting . '_id'] = $defaultGreetingTypeId;
305 }
306 }
307 }
308 }
309
310 $transaction = new CRM_Core_Transaction();
311
312 $contact = self::add($params);
313 if (!$contact) {
314 // Not dying here is stupid, since we get into weird situation and into a bug that
315 // is impossible to figure out for the user or for us
316 // CRM-7925
317 CRM_Core_Error::fatal();
318 }
319
320 $params['contact_id'] = $contact->id;
321
322 if (Civi::settings()->get('is_enabled')) {
323 // Enabling multisite causes the contact to be added to the domain group.
324 $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
325 if (!empty($domainGroupID)) {
326 if (!empty($params['group']) && is_array($params['group'])) {
327 $params['group'][$domainGroupID] = 1;
328 }
329 else {
330 $params['group'] = array($domainGroupID => 1);
331 }
332 }
333 }
334
335 if (array_key_exists('group', $params)) {
336 $contactIds = array($params['contact_id']);
337 foreach ($params['group'] as $groupId => $flag) {
338 if ($flag == 1) {
339 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
340 }
341 elseif ($flag == -1) {
342 CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $groupId);
343 }
344 }
345 }
346
347 // Add location Block data.
348 $blocks = CRM_Core_BAO_Location::create($params, $fixAddress);
349 foreach ($blocks as $name => $value) {
350 $contact->$name = $value;
351 }
352 if (!empty($params['updateBlankLocInfo'])) {
353 $skipDelete = TRUE;
354 }
355
356 //add website
357 CRM_Core_BAO_Website::create($params['website'], $contact->id, $skipDelete);
358
359 //get userID from session
360 $session = CRM_Core_Session::singleton();
361 $userID = $session->get('userID');
362 // add notes
363 if (!empty($params['note'])) {
364 if (is_array($params['note'])) {
365 foreach ($params['note'] as $note) {
366 $contactId = $contact->id;
367 if (isset($note['contact_id'])) {
368 $contactId = $note['contact_id'];
369 }
370 //if logged in user, overwrite contactId
371 if ($userID) {
372 $contactId = $userID;
373 }
374
375 $noteParams = array(
376 'entity_id' => $contact->id,
377 'entity_table' => 'civicrm_contact',
378 'note' => $note['note'],
379 'subject' => CRM_Utils_Array::value('subject', $note),
380 'contact_id' => $contactId,
381 );
382 CRM_Core_BAO_Note::add($noteParams, CRM_Core_DAO::$_nullArray);
383 }
384 }
385 else {
386 $contactId = $contact->id;
387 if (isset($note['contact_id'])) {
388 $contactId = $note['contact_id'];
389 }
390 //if logged in user, overwrite contactId
391 if ($userID) {
392 $contactId = $userID;
393 }
394
395 $noteParams = array(
396 'entity_id' => $contact->id,
397 'entity_table' => 'civicrm_contact',
398 'note' => $params['note'],
399 'subject' => CRM_Utils_Array::value('subject', $params),
400 'contact_id' => $contactId,
401 );
402 CRM_Core_BAO_Note::add($noteParams, CRM_Core_DAO::$_nullArray);
403 }
404 }
405
406 // update the UF user_unique_id if that has changed
407 CRM_Core_BAO_UFMatch::updateUFName($contact->id);
408
409 if (!empty($params['custom']) &&
410 is_array($params['custom'])
411 ) {
412 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contact', $contact->id);
413 }
414
415 // make a civicrm_subscription_history entry only on contact create (CRM-777)
416 if (empty($params['contact_id'])) {
417 $subscriptionParams = array(
418 'contact_id' => $contact->id,
419 'status' => 'Added',
420 'method' => 'Admin',
421 );
422 CRM_Contact_BAO_SubscriptionHistory::create($subscriptionParams);
423 }
424
425 $transaction->commit();
426
427 // CRM-6367: fetch the right label for contact type’s display
428 $contact->contact_type_display = CRM_Core_DAO::getFieldValue(
429 'CRM_Contact_DAO_ContactType',
430 $contact->contact_type,
431 'label',
432 'name'
433 );
434
435 if (!$config->doNotResetCache) {
436 // Note: doNotResetCache flag is currently set by import contact process and merging,
437 // since resetting and
438 // rebuilding cache could be expensive (for many contacts). We might come out with better
439 // approach in future.
440 CRM_Contact_BAO_Contact_Utils::clearContactCaches($contact->id);
441 }
442
443 if ($invokeHooks) {
444 if ($isEdit) {
445 CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
446 }
447 else {
448 CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
449 }
450 }
451
452 // process greetings CRM-4575, cache greetings
453 self::processGreetings($contact);
454
455 return $contact;
456 }
457
458 /**
459 * Get the display name and image of a contact.
460 *
461 * @param int $id
462 * The contactId.
463 *
464 * @param bool $includeTypeInReturnParameters
465 * Should type be part of the returned array?
466 *
467 * @return array
468 * the displayName and contactImage for this contact
469 */
470 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
471 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
472 $sql = "
473 SELECT civicrm_contact.*,
474 civicrm_email.email as email
475 FROM civicrm_contact
476 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
477 AND civicrm_email.is_primary = 1
478 WHERE civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
479 $dao = new CRM_Core_DAO();
480 $dao->query($sql);
481 if ($dao->fetch()) {
482 $image = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
483 $dao->contact_sub_type : $dao->contact_type, FALSE, $id
484 );
485 $imageUrl = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
486 $dao->contact_sub_type : $dao->contact_type, TRUE, $id
487 );
488
489 // use email if display_name is empty
490 if (empty($dao->display_name)) {
491 $displayName = $dao->email;
492 }
493 else {
494 $displayName = $dao->display_name;
495 }
496
497 CRM_Utils_Hook::alterDisplayName($displayName, $id, $dao);
498
499 return $includeTypeInReturnParameters ? array(
500 $displayName,
501 $image,
502 $dao->contact_type,
503 $dao->contact_sub_type,
504 $imageUrl,
505 ) : array($displayName, $image, $imageUrl);
506 }
507 return NULL;
508 }
509
510 /**
511 * Add billing fields to the params if appropriate.
512 *
513 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
514 * don't then we should set the name fields to the filling fields AND add the preserveDBName
515 * parameter (which will tell the BAO only to set those fields if none already exist.
516 *
517 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
518 * matching is best done by hipsters.
519 *
520 * @param array $params
521 */
522 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
523 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
524 foreach ($nameFields as $field) {
525 if (!empty($params[$field])) {
526 return;
527 }
528 }
529 // There are only 3 - we can iterate through them twice :-)
530 foreach ($nameFields as $field) {
531 if (!empty($params['billing_' . $field])) {
532 $params[$field] = $params['billing_' . $field];
533 }
534 $params['preserveDBName'] = TRUE;
535 }
536
537 }
538
539 /**
540 * Create last viewed link to recently updated contact.
541 *
542 * @param array $crudLinkSpec
543 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
544 * - entity_table: string, eg "civicrm_contact"
545 * - entity_id: int
546 *
547 * @return array|NULL
548 * NULL if unavailable, or
549 * [path: string, query: string, title: string]
550 * @see CRM_Utils_System::createDefaultCrudLink
551 */
552 public function createDefaultCrudLink($crudLinkSpec) {
553 switch ($crudLinkSpec['action']) {
554 case CRM_Core_Action::VIEW:
555 $result = array(
556 'title' => $this->display_name,
557 'path' => 'civicrm/contact/view',
558 'query' => array(
559 'reset' => 1,
560 'cid' => $this->id,
561 ),
562 );
563 return $result;
564
565 case CRM_Core_Action::UPDATE:
566 $result = array(
567 'title' => $this->display_name,
568 'path' => 'civicrm/contact/add',
569 'query' => array(
570 'reset' => 1,
571 'action' => 'update',
572 'cid' => $this->id,
573 ),
574 );
575 return $result;
576 }
577 return NULL;
578 }
579
580 /**
581 * Get the values for pseudoconstants for name->value and reverse.
582 *
583 * @param array $defaults
584 * (reference) the default values, some of which need to be resolved.
585 * @param bool $reverse
586 * True if we want to resolve the values in the reverse direction (value -> name).
587 */
588 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
589 // Hack for birth_date.
590 if (!empty($defaults['birth_date'])) {
591 if (is_array($defaults['birth_date'])) {
592 $defaults['birth_date'] = CRM_Utils_Date::format($defaults['birth_date'], '-');
593 }
594 }
595
596 CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
597 CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
598 CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
599 CRM_Utils_Array::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
600
601 //lookup value of email/postal greeting, addressee, CRM-4575
602 foreach (self::$_greetingTypes as $greeting) {
603 $filterCondition = array(
604 'contact_type' => CRM_Utils_Array::value('contact_type', $defaults),
605 'greeting_type' => $greeting,
606 );
607 CRM_Utils_Array::lookupValue($defaults, $greeting,
608 CRM_Core_PseudoConstant::greeting($filterCondition), $reverse
609 );
610 }
611
612 $blocks = array('address', 'im', 'phone');
613 foreach ($blocks as $name) {
614 if (!array_key_exists($name, $defaults) || !is_array($defaults[$name])) {
615 continue;
616 }
617 foreach ($defaults[$name] as $count => & $values) {
618
619 //get location type id.
620 CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
621
622 if ($name == 'address') {
623 // FIXME: lookupValue doesn't work for vcard_name
624 if (!empty($values['location_type_id'])) {
625 $vcardNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
626 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
627 }
628
629 if (!CRM_Utils_Array::lookupValue($values,
630 'country',
631 CRM_Core_PseudoConstant::country(),
632 $reverse
633 ) &&
634 $reverse
635 ) {
636 CRM_Utils_Array::lookupValue($values,
637 'country',
638 CRM_Core_PseudoConstant::countryIsoCode(),
639 $reverse
640 );
641 }
642
643 // CRM-7597
644 // if we find a country id above, we need to restrict it to that country
645 // rather than the list of all countries
646
647 if (!empty($values['country_id'])) {
648 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($values['country_id']);
649 }
650 else {
651 $stateProvinceList = CRM_Core_PseudoConstant::stateProvince();
652 }
653 if (!CRM_Utils_Array::lookupValue($values,
654 'state_province',
655 $stateProvinceList,
656 $reverse
657 ) &&
658 $reverse
659 ) {
660
661 if (!empty($values['country_id'])) {
662 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($values['country_id'], 'abbreviation');
663 }
664 else {
665 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
666 }
667 CRM_Utils_Array::lookupValue($values,
668 'state_province',
669 $stateProvinceList,
670 $reverse
671 );
672 }
673
674 if (!empty($values['state_province_id'])) {
675 $countyList = CRM_Core_PseudoConstant::countyForState($values['state_province_id']);
676 }
677 else {
678 $countyList = CRM_Core_PseudoConstant::county();
679 }
680 CRM_Utils_Array::lookupValue($values,
681 'county',
682 $countyList,
683 $reverse
684 );
685 }
686
687 if ($name == 'im') {
688 CRM_Utils_Array::lookupValue($values,
689 'provider',
690 CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
691 $reverse
692 );
693 }
694
695 if ($name == 'phone') {
696 CRM_Utils_Array::lookupValue($values,
697 'phone_type',
698 CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
699 $reverse
700 );
701 }
702
703 // Kill the reference.
704 unset($values);
705 }
706 }
707 }
708
709 /**
710 * Fetch object based on array of properties.
711 *
712 * @param array $params
713 * (reference ) an assoc array of name/value pairs.
714 * @param array $defaults
715 * (reference ) an assoc array to hold the name / value pairs.
716 * in a hierarchical manner
717 * @param bool $microformat
718 * For location in microformat.
719 *
720 * @return CRM_Contact_BAO_Contact
721 */
722 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
723 if (array_key_exists('contact_id', $params)) {
724 $params['id'] = $params['contact_id'];
725 }
726 elseif (array_key_exists('id', $params)) {
727 $params['contact_id'] = $params['id'];
728 }
729
730 $contact = self::getValues($params, $defaults);
731
732 unset($params['id']);
733
734 //get the block information for this contact
735 $entityBlock = array('contact_id' => $params['contact_id']);
736 $blocks = CRM_Core_BAO_Location::getValues($entityBlock, $microformat);
737 $defaults = array_merge($defaults, $blocks);
738 foreach ($blocks as $block => $value) {
739 $contact->$block = $value;
740 }
741
742 if (!isset($params['noNotes'])) {
743 $contact->notes = CRM_Core_BAO_Note::getValues($params, $defaults);
744 }
745
746 if (!isset($params['noRelationships'])) {
747 $contact->relationship = CRM_Contact_BAO_Relationship::getValues($params, $defaults);
748 }
749
750 if (!isset($params['noGroups'])) {
751 $contact->groupContact = CRM_Contact_BAO_GroupContact::getValues($params, $defaults);
752 }
753
754 if (!isset($params['noWebsite'])) {
755 $contact->website = CRM_Core_BAO_Website::getValues($params, $defaults);
756 }
757
758 return $contact;
759 }
760
761 /**
762 * Get the display name of a contact.
763 *
764 * @param int $id
765 * Id of the contact.
766 *
767 * @return null|string
768 * display name of the contact if found
769 */
770 public static function displayName($id) {
771 $displayName = NULL;
772 if ($id) {
773 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
774 }
775
776 return $displayName;
777 }
778
779 /**
780 * Delete a contact and all its associated records.
781 *
782 * @param int $id
783 * Id of the contact to delete.
784 * @param bool $restore
785 * Whether to actually restore, not delete.
786 * @param bool $skipUndelete
787 * Whether to force contact delete or not.
788 *
789 * @return bool
790 * Was contact deleted?
791 */
792 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
793
794 if (!$id) {
795 return FALSE;
796 }
797 // If trash is disabled in system settings then we always skip
798 if (!Civi::settings()->get('contact_undelete')) {
799 $skipUndelete = TRUE;
800 }
801
802 // make sure we have edit permission for this contact
803 // before we delete
804 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission::check('delete contacts')) ||
805 ($restore && !CRM_Core_Permission::check('access deleted contacts')))
806 ) {
807 return FALSE;
808 }
809
810 // CRM-12929
811 // Restrict contact to be delete if contact has financial trxns
812 $error = NULL;
813 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($id), $error)) {
814 return FALSE;
815 }
816
817 // make sure this contact_id does not have any membership types
818 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
819 $id,
820 'id',
821 'member_of_contact_id'
822 );
823 if ($membershipTypeID) {
824 return FALSE;
825 }
826
827 $contact = new CRM_Contact_DAO_Contact();
828 $contact->id = $id;
829 if (!$contact->find(TRUE)) {
830 return FALSE;
831 }
832
833 $contactType = $contact->contact_type;
834 // currently we only clear employer cache.
835 // we are now deleting inherited membership if any.
836 if ($contact->contact_type == 'Organization') {
837 $action = $restore ? CRM_Core_Action::ENABLE : CRM_Core_Action::DISABLE;
838 $relationshipDtls = CRM_Contact_BAO_Relationship::getRelationship($id);
839 if (!empty($relationshipDtls)) {
840 foreach ($relationshipDtls as $rId => $details) {
841 CRM_Contact_BAO_Relationship::disableEnableRelationship($rId, $action);
842 }
843 }
844 CRM_Contact_BAO_Contact_Utils::clearAllEmployee($id);
845 }
846
847 if ($restore) {
848 return self::contactTrashRestore($contact, TRUE);
849 }
850
851 // start a new transaction
852 $transaction = new CRM_Core_Transaction();
853
854 if ($skipUndelete) {
855 CRM_Utils_Hook::pre('delete', $contactType, $id, CRM_Core_DAO::$_nullArray);
856
857 //delete billing address if exists.
858 CRM_Contribute_BAO_Contribution::deleteAddress(NULL, $id);
859
860 // delete the log entries since we dont have triggers enabled as yet
861 $logDAO = new CRM_Core_DAO_Log();
862 $logDAO->entity_table = 'civicrm_contact';
863 $logDAO->entity_id = $id;
864 $logDAO->delete();
865
866 // delete contact participants CRM-12155
867 CRM_Event_BAO_Participant::deleteContactParticipant($id);
868
869 // delete contact contributions CRM-12155
870 CRM_Contribute_BAO_Contribution::deleteContactContribution($id);
871
872 // do activity cleanup, CRM-5604
873 CRM_Activity_BAO_Activity::cleanupActivity($id);
874
875 // delete all notes related to contact
876 CRM_Core_BAO_Note::cleanContactNotes($id);
877
878 // delete cases related to contact
879 $contactCases = CRM_Case_BAO_Case::retrieveCaseIdsByContactId($id);
880 if (!empty($contactCases)) {
881 foreach ($contactCases as $caseId) {
882 //check if case is associate with other contact or not.
883 $caseContactId = CRM_Case_BAO_Case::getCaseClients($caseId);
884 if (count($caseContactId) <= 1) {
885 CRM_Case_BAO_Case::deleteCase($caseId);
886 }
887 }
888 }
889
890 $contact->delete();
891 }
892 else {
893 self::contactTrashRestore($contact);
894 }
895
896 //delete the contact id from recently view
897 CRM_Utils_Recent::delContact($id);
898 self::updateContactCache($id, empty($restore));
899
900 // delete any dupe cache entry
901 CRM_Core_BAO_PrevNextCache::deleteItem($id);
902
903 $transaction->commit();
904
905 if ($skipUndelete) {
906 CRM_Utils_Hook::post('delete', $contactType, $contact->id, $contact);
907 }
908
909 // also reset the DB_DO global array so we can reuse the memory
910 // http://issues.civicrm.org/jira/browse/CRM-4387
911 CRM_Core_DAO::freeResult();
912
913 return TRUE;
914 }
915
916 /**
917 * Action to update any caches relating to a recently update contact.
918 *
919 * I was going to call this from delete as well as from create to ensure the delete is being
920 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
921 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
922 * where the call involved a subquery that was locking the table.
923 *
924 * @param int $contactID
925 * @param bool $isTrashed
926 */
927 public static function updateContactCache($contactID, $isTrashed = FALSE) {
928
929 if ($isTrashed) {
930 CRM_Contact_BAO_GroupContactCache::removeContact($contactID);
931 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
932 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
933 // but this should not cause any change as long as contacts are not being trashed outside the
934 // main functions for that.
935 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
936 }
937 else {
938 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
939 }
940 }
941
942 /**
943 * Delete the image of a contact.
944 *
945 * @param int $id
946 * Id of the contact.
947 *
948 * @return bool
949 * Was contact image deleted?
950 */
951 public static function deleteContactImage($id) {
952 if (!$id) {
953 return FALSE;
954 }
955 $query = "
956 UPDATE civicrm_contact
957 SET image_URL=NULL
958 WHERE id={$id}; ";
959 CRM_Core_DAO::executeQuery($query);
960 return TRUE;
961 }
962
963 /**
964 * Return proportional height and width of the image.
965 *
966 * @param int $imageWidth
967 * Width of image.
968 *
969 * @param int $imageHeight
970 * Height of image.
971 *
972 * @return array
973 * Thumb dimension of image
974 */
975 public static function getThumbSize($imageWidth, $imageHeight) {
976 $thumbWidth = 100;
977 if ($imageWidth && $imageHeight) {
978 $imageRatio = $imageWidth / $imageHeight;
979 }
980 else {
981 $imageRatio = 1;
982 }
983 if ($imageRatio > 1) {
984 $imageThumbWidth = $thumbWidth;
985 $imageThumbHeight = round($thumbWidth / $imageRatio);
986 }
987 else {
988 $imageThumbHeight = $thumbWidth;
989 $imageThumbWidth = round($thumbWidth * $imageRatio);
990 }
991
992 return array($imageThumbWidth, $imageThumbHeight);
993 }
994
995 /**
996 * Validate type of contact image.
997 *
998 * @param array $params
999 * @param string $imageIndex
1000 * Index of image field.
1001 * @param string $statusMsg
1002 * Status message to be set after operation.
1003 * @param string $opType
1004 * Type of operation like fatal, bounce etc.
1005 *
1006 * @return bool
1007 * true if valid image extension
1008 */
1009 public static function processImageParams(
1010 &$params,
1011 $imageIndex = 'image_URL',
1012 $statusMsg = NULL,
1013 $opType = 'status'
1014 ) {
1015 $mimeType = array(
1016 'image/jpeg',
1017 'image/jpg',
1018 'image/png',
1019 'image/bmp',
1020 'image/p-jpeg',
1021 'image/gif',
1022 'image/x-png',
1023 );
1024
1025 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1026 $photo = basename($params[$imageIndex]['name']);
1027 $params[$imageIndex] = CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1028 return TRUE;
1029 }
1030 else {
1031 unset($params[$imageIndex]);
1032 if (!$statusMsg) {
1033 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1034 }
1035 if ($opType == 'status') {
1036 CRM_Core_Session::setStatus($statusMsg, 'Sorry', 'error');
1037 }
1038 // FIXME: additional support for fatal, bounce etc could be added.
1039 return FALSE;
1040 }
1041 }
1042
1043 /**
1044 * Extract contact id from url for deleting contact image.
1045 */
1046 public static function processImage() {
1047
1048 $action = CRM_Utils_Request::retrieve('action', 'String');
1049 $cid = CRM_Utils_Request::retrieve('cid', 'Positive');
1050 // retrieve contact id in case of Profile context
1051 $id = CRM_Utils_Request::retrieve('id', 'Positive');
1052 $cid = $cid ? $cid : $id;
1053 if ($action & CRM_Core_Action::DELETE) {
1054 if (CRM_Utils_Request::retrieve('confirmed', 'Boolean')) {
1055 CRM_Contact_BAO_Contact::deleteContactImage($cid);
1056 CRM_Core_Session::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1057 $session = CRM_Core_Session::singleton();
1058 $toUrl = $session->popUserContext();
1059 CRM_Utils_System::redirect($toUrl);
1060 }
1061 }
1062 }
1063
1064 /**
1065 * Function to set is_delete true or restore deleted contact.
1066 *
1067 * @param CRM_Contact_DAO_Contact $contact
1068 * Contact DAO object.
1069 * @param bool $restore
1070 * True to set the is_delete = 1 else false to restore deleted contact,
1071 * i.e. is_delete = 0
1072 *
1073 * @return bool
1074 */
1075 public static function contactTrashRestore($contact, $restore = FALSE) {
1076 $updateParams = array(
1077 'id' => $contact->id,
1078 'is_deleted' => $restore ? 0 : 1,
1079 );
1080
1081 CRM_Utils_Hook::pre('update', $contact->contact_type, $contact->id, $updateParams);
1082
1083 $params = array(1 => array($contact->id, 'Integer'));
1084 if (!$restore) {
1085 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1086 CRM_Core_DAO::executeQuery($query, $params);
1087 }
1088
1089 $contact->copyValues($updateParams);
1090 $contact->save();
1091
1092 CRM_Utils_Hook::post('update', $contact->contact_type, $contact->id, $contact);
1093
1094 return TRUE;
1095 }
1096
1097 /**
1098 * Get contact type for a contact.
1099 *
1100 * @param int $id
1101 * Id of the contact whose contact type is needed.
1102 *
1103 * @return string
1104 * contact_type if $id found else null ""
1105 */
1106 public static function getContactType($id) {
1107 return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1108 }
1109
1110 /**
1111 * Get contact sub type for a contact.
1112 *
1113 * @param int $id
1114 * Id of the contact whose contact sub type is needed.
1115 *
1116 * @param string $implodeDelimiter
1117 *
1118 * @return string
1119 * contact_sub_type if $id found else null ""
1120 */
1121 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1122 $subtype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1123 if (!$subtype) {
1124 return $implodeDelimiter ? NULL : array();
1125 }
1126
1127 $subtype = CRM_Utils_Array::explodePadded($subtype);
1128
1129 if ($implodeDelimiter) {
1130 $subtype = implode($implodeDelimiter, $subtype);
1131 }
1132 return $subtype;
1133 }
1134
1135 /**
1136 * Get pair of contact-type and sub-type for a contact.
1137 *
1138 * @param int $id
1139 * Id of the contact whose contact sub/contact type is needed.
1140 *
1141 * @return array
1142 */
1143 public static function getContactTypes($id) {
1144 $params = array('id' => $id);
1145 $details = array();
1146 $contact = CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact',
1147 $params,
1148 $details,
1149 array('contact_type', 'contact_sub_type')
1150 );
1151
1152 if ($contact) {
1153 $contactTypes = array();
1154 if ($contact->contact_sub_type) {
1155 $contactTypes = CRM_Utils_Array::explodePadded($contact->contact_sub_type);
1156 }
1157 array_unshift($contactTypes, $contact->contact_type);
1158
1159 return $contactTypes;
1160 }
1161 else {
1162 CRM_Core_Error::fatal();
1163 }
1164 }
1165
1166 /**
1167 * Combine all the importable fields from the lower levels object.
1168 *
1169 * The ordering is important, since currently we do not have a weight
1170 * scheme. Adding weight is super important
1171 *
1172 * @param int|string $contactType contact Type
1173 * @param bool $status
1174 * Status is used to manipulate first title.
1175 * @param bool $showAll
1176 * If true returns all fields (includes disabled fields).
1177 * @param bool $isProfile
1178 * If its profile mode.
1179 * @param bool $checkPermission
1180 * If false, do not include permissioning clause (for custom data).
1181 *
1182 * @param bool $withMultiCustomFields
1183 *
1184 * @return array
1185 * array of importable Fields
1186 */
1187 public static function importableFields(
1188 $contactType = 'Individual',
1189 $status = FALSE,
1190 $showAll = FALSE,
1191 $isProfile = FALSE,
1192 $checkPermission = TRUE,
1193 $withMultiCustomFields = FALSE
1194 ) {
1195 if (empty($contactType)) {
1196 $contactType = 'All';
1197 }
1198
1199 $cacheKeyString = "importableFields $contactType";
1200 $cacheKeyString .= $status ? '_1' : '_0';
1201 $cacheKeyString .= $showAll ? '_1' : '_0';
1202 $cacheKeyString .= $isProfile ? '_1' : '_0';
1203 $cacheKeyString .= $checkPermission ? '_1' : '_0';
1204
1205 $fields = CRM_Utils_Array::value($cacheKeyString, self::$_importableFields);
1206
1207 if (!$fields) {
1208 // check if we can retrieve from database cache
1209 $fields = CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
1210 }
1211
1212 if (!$fields) {
1213 $fields = CRM_Contact_DAO_Contact::import();
1214
1215 // get the fields thar are meant for contact types
1216 if (in_array($contactType, array(
1217 'Individual',
1218 'Household',
1219 'Organization',
1220 'All',
1221 ))) {
1222 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
1223 }
1224
1225 $locationFields = array_merge(CRM_Core_DAO_Address::import(),
1226 CRM_Core_DAO_Phone::import(),
1227 CRM_Core_DAO_Email::import(),
1228 CRM_Core_DAO_IM::import(TRUE),
1229 CRM_Core_DAO_OpenID::import()
1230 );
1231
1232 $locationFields = array_merge($locationFields,
1233 CRM_Core_BAO_CustomField::getFieldsForImport('Address',
1234 FALSE,
1235 FALSE,
1236 FALSE,
1237 FALSE
1238 )
1239 );
1240
1241 foreach ($locationFields as $key => $field) {
1242 $locationFields[$key]['hasLocationType'] = TRUE;
1243 }
1244
1245 $fields = array_merge($fields, $locationFields);
1246
1247 $fields = array_merge($fields, CRM_Contact_DAO_Contact::import());
1248 $fields = array_merge($fields, CRM_Core_DAO_Note::import());
1249
1250 //website fields
1251 $fields = array_merge($fields, CRM_Core_DAO_Website::import());
1252 $fields['url']['hasWebsiteType'] = TRUE;
1253
1254 if ($contactType != 'All') {
1255 $fields = array_merge($fields,
1256 CRM_Core_BAO_CustomField::getFieldsForImport($contactType,
1257 $showAll,
1258 TRUE,
1259 FALSE,
1260 FALSE,
1261 $withMultiCustomFields
1262 )
1263 );
1264 //unset the fields, which are not related to their
1265 //contact type.
1266 $commonValues = array(
1267 'Individual' => array(
1268 'household_name',
1269 'legal_name',
1270 'sic_code',
1271 'organization_name',
1272 ),
1273 'Household' => array(
1274 'first_name',
1275 'middle_name',
1276 'last_name',
1277 'formal_title',
1278 'job_title',
1279 'gender_id',
1280 'prefix_id',
1281 'suffix_id',
1282 'birth_date',
1283 'organization_name',
1284 'legal_name',
1285 'legal_identifier',
1286 'sic_code',
1287 'home_URL',
1288 'is_deceased',
1289 'deceased_date',
1290 ),
1291 'Organization' => array(
1292 'first_name',
1293 'middle_name',
1294 'last_name',
1295 'formal_title',
1296 'job_title',
1297 'gender_id',
1298 'prefix_id',
1299 'suffix_id',
1300 'birth_date',
1301 'household_name',
1302 'is_deceased',
1303 'deceased_date',
1304 ),
1305 );
1306 foreach ($commonValues[$contactType] as $value) {
1307 unset($fields[$value]);
1308 }
1309 }
1310 else {
1311 foreach (array('Individual', 'Household', 'Organization') as $type) {
1312 $fields = array_merge($fields,
1313 CRM_Core_BAO_CustomField::getFieldsForImport($type,
1314 $showAll,
1315 FALSE,
1316 FALSE,
1317 FALSE,
1318 $withMultiCustomFields
1319 )
1320 );
1321 }
1322 }
1323
1324 if ($isProfile) {
1325 $fields = array_merge($fields, array(
1326 'group' => array(
1327 'title' => ts('Group(s)'),
1328 'name' => 'group',
1329 ),
1330 'tag' => array(
1331 'title' => ts('Tag(s)'),
1332 'name' => 'tag',
1333 ),
1334 'note' => array(
1335 'title' => ts('Note(s)'),
1336 'name' => 'note',
1337 ),
1338 'communication_style_id' => array(
1339 'title' => ts('Communication Style'),
1340 'name' => 'communication_style_id',
1341 ),
1342 ));
1343 }
1344
1345 //Sorting fields in alphabetical order(CRM-1507)
1346 $fields = CRM_Utils_Array::crmArraySortByField($fields, 'title');
1347
1348 CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
1349 }
1350
1351 self::$_importableFields[$cacheKeyString] = $fields;
1352
1353 if (!$isProfile) {
1354 if (!$status) {
1355 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1356 self::$_importableFields[$cacheKeyString]
1357 );
1358 }
1359 else {
1360 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1361 self::$_importableFields[$cacheKeyString]
1362 );
1363 }
1364 }
1365 return $fields;
1366 }
1367
1368 /**
1369 * Combine all the exportable fields from the lower levels object.
1370 *
1371 * Currently we are using importable fields as exportable fields
1372 *
1373 * @param int|string $contactType contact Type
1374 * @param bool $status
1375 * True while exporting primary contacts.
1376 * @param bool $export
1377 * True when used during export.
1378 * @param bool $search
1379 * True when used during search, might conflict with export param?.
1380 *
1381 * @param bool $withMultiRecord
1382 *
1383 * @return array
1384 * array of exportable Fields
1385 */
1386 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1387 if (empty($contactType)) {
1388 $contactType = 'All';
1389 }
1390
1391 $cacheKeyString = "exportableFields $contactType";
1392 $cacheKeyString .= $export ? '_1' : '_0';
1393 $cacheKeyString .= $status ? '_1' : '_0';
1394 $cacheKeyString .= $search ? '_1' : '_0';
1395 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1396 //calculates custom fields takes into account the logged in user & caches that for all users
1397 //as an interim fix we will cache the fields by contact
1398 $cacheKeyString .= '_' . CRM_Core_Session::getLoggedInContactID();
1399
1400 if (!self::$_exportableFields || !CRM_Utils_Array::value($cacheKeyString, self::$_exportableFields)) {
1401 if (!self::$_exportableFields) {
1402 self::$_exportableFields = array();
1403 }
1404
1405 // check if we can retrieve from database cache
1406 $fields = CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
1407
1408 if (!$fields) {
1409 $fields = CRM_Contact_DAO_Contact::export();
1410
1411 // The fields are meant for contact types.
1412 if (in_array($contactType, array(
1413 'Individual',
1414 'Household',
1415 'Organization',
1416 'All',
1417 )
1418 )) {
1419 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
1420 }
1421 // add current employer for individuals
1422 $fields = array_merge($fields, array(
1423 'current_employer' =>
1424 array(
1425 'name' => 'organization_name',
1426 'title' => ts('Current Employer'),
1427 ),
1428 ));
1429
1430 $locationType = array(
1431 'location_type' => array(
1432 'name' => 'location_type',
1433 'where' => 'civicrm_location_type.name',
1434 'title' => ts('Location Type'),
1435 ),
1436 );
1437
1438 $IMProvider = array(
1439 'im_provider' => array(
1440 'name' => 'im_provider',
1441 'where' => 'civicrm_im.provider_id',
1442 'title' => ts('IM Provider'),
1443 ),
1444 );
1445
1446 $locationFields = array_merge($locationType,
1447 CRM_Core_DAO_Address::export(),
1448 CRM_Core_DAO_Phone::export(),
1449 CRM_Core_DAO_Email::export(),
1450 $IMProvider,
1451 CRM_Core_DAO_IM::export(TRUE),
1452 CRM_Core_DAO_OpenID::export()
1453 );
1454
1455 $locationFields = array_merge($locationFields,
1456 CRM_Core_BAO_CustomField::getFieldsForImport('Address')
1457 );
1458
1459 foreach ($locationFields as $key => $field) {
1460 $locationFields[$key]['hasLocationType'] = TRUE;
1461 }
1462
1463 $fields = array_merge($fields, $locationFields);
1464
1465 //add world region
1466 $fields = array_merge($fields,
1467 CRM_Core_DAO_Worldregion::export()
1468 );
1469
1470 $fields = array_merge($fields,
1471 CRM_Contact_DAO_Contact::export()
1472 );
1473
1474 //website fields
1475 $fields = array_merge($fields, CRM_Core_DAO_Website::export());
1476
1477 if ($contactType != 'All') {
1478 $fields = array_merge($fields,
1479 CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1480 );
1481 }
1482 else {
1483 foreach (array(
1484 'Individual',
1485 'Household',
1486 'Organization',
1487 ) as $type) {
1488 $fields = array_merge($fields,
1489 CRM_Core_BAO_CustomField::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1490 );
1491 }
1492 }
1493 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1494 //fix for CRM-791
1495 if ($export) {
1496 $fields = array_merge($fields, array(
1497 'groups' => array(
1498 'title' => ts('Group(s)'),
1499 'name' => 'groups',
1500 ),
1501 'tags' => array(
1502 'title' => ts('Tag(s)'),
1503 'name' => 'tags',
1504 ),
1505 'notes' => array(
1506 'title' => ts('Note(s)'),
1507 'name' => 'notes',
1508 ),
1509 ));
1510 }
1511 else {
1512 $fields = array_merge($fields, array(
1513 'group' => array(
1514 'title' => ts('Group(s)'),
1515 'name' => 'group',
1516 ),
1517 'tag' => array(
1518 'title' => ts('Tag(s)'),
1519 'name' => 'tag',
1520 ),
1521 'note' => array(
1522 'title' => ts('Note(s)'),
1523 'name' => 'note',
1524 ),
1525 ));
1526 }
1527
1528 //Sorting fields in alphabetical order(CRM-1507)
1529 foreach ($fields as $k => $v) {
1530 $sortArray[$k] = CRM_Utils_Array::value('title', $v);
1531 }
1532
1533 $fields = array_merge($sortArray, $fields);
1534 //unset the field which are not related to their contact type.
1535 if ($contactType != 'All') {
1536 $commonValues = array(
1537 'Individual' => array(
1538 'household_name',
1539 'legal_name',
1540 'sic_code',
1541 'organization_name',
1542 'email_greeting_custom',
1543 'postal_greeting_custom',
1544 'addressee_custom',
1545 ),
1546 'Household' => array(
1547 'first_name',
1548 'middle_name',
1549 'last_name',
1550 'formal_title',
1551 'job_title',
1552 'gender_id',
1553 'prefix_id',
1554 'suffix_id',
1555 'birth_date',
1556 'organization_name',
1557 'legal_name',
1558 'legal_identifier',
1559 'sic_code',
1560 'home_URL',
1561 'is_deceased',
1562 'deceased_date',
1563 'current_employer',
1564 'email_greeting_custom',
1565 'postal_greeting_custom',
1566 'addressee_custom',
1567 'prefix_id',
1568 'suffix_id',
1569 ),
1570 'Organization' => array(
1571 'first_name',
1572 'middle_name',
1573 'last_name',
1574 'formal_title',
1575 'job_title',
1576 'gender_id',
1577 'prefix_id',
1578 'suffix_id',
1579 'birth_date',
1580 'household_name',
1581 'email_greeting_custom',
1582 'postal_greeting_custom',
1583 'prefix_id',
1584 'suffix_id',
1585 'gender_id',
1586 'addressee_custom',
1587 'is_deceased',
1588 'deceased_date',
1589 'current_employer',
1590 ),
1591 );
1592 foreach ($commonValues[$contactType] as $value) {
1593 unset($fields[$value]);
1594 }
1595 }
1596
1597 CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
1598 }
1599 self::$_exportableFields[$cacheKeyString] = $fields;
1600 }
1601
1602 if (!$status) {
1603 $fields = self::$_exportableFields[$cacheKeyString];
1604 }
1605 else {
1606 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1607 self::$_exportableFields[$cacheKeyString]
1608 );
1609 }
1610
1611 return $fields;
1612 }
1613
1614 /**
1615 * Get the all contact details (Hierarchical).
1616 *
1617 * @param int $contactId
1618 * Contact id.
1619 * @param array $fields
1620 * Fields array.
1621 *
1622 * @return array
1623 * Contact details
1624 */
1625 public static function getHierContactDetails($contactId, &$fields) {
1626 $params = array(array('contact_id', '=', $contactId, 0, 0));
1627 $options = array();
1628
1629 $returnProperties = self::makeHierReturnProperties($fields, $contactId);
1630
1631 // We don't know the contents of return properties, but we need the lower
1632 // level ids of the contact so add a few fields.
1633 $returnProperties['first_name'] = 1;
1634 $returnProperties['organization_name'] = 1;
1635 $returnProperties['household_name'] = 1;
1636 $returnProperties['contact_type'] = 1;
1637 $returnProperties['contact_sub_type'] = 1;
1638 return list($query, $options) = CRM_Contact_BAO_Query::apiQuery($params, $returnProperties, $options);
1639 }
1640
1641 /**
1642 * Given a set of flat profile style field names, create a hierarchy.
1643 *
1644 * This is for the query to use, create the right sql.
1645 *
1646 * @param $fields
1647 * @param int $contactId
1648 * Contact id.
1649 *
1650 * @return array
1651 * A hierarchical property tree if appropriate
1652 */
1653 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1654 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
1655
1656 $returnProperties = array();
1657
1658 $multipleFields = array('website' => 'url');
1659 foreach ($fields as $name => $dontCare) {
1660 if (strpos($name, '-') !== FALSE) {
1661 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3);
1662
1663 if (!in_array($fieldName, $multipleFields)) {
1664 if ($id == 'Primary') {
1665 $locationTypeName = 1;
1666 }
1667 else {
1668 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
1669 if (!$locationTypeName) {
1670 continue;
1671 }
1672 }
1673
1674 if (empty($returnProperties['location'])) {
1675 $returnProperties['location'] = array();
1676 }
1677 if (empty($returnProperties['location'][$locationTypeName])) {
1678 $returnProperties['location'][$locationTypeName] = array();
1679 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1680 }
1681 if (in_array($fieldName, array(
1682 'phone',
1683 'im',
1684 'email',
1685 'openid',
1686 'phone_ext',
1687 ))) {
1688 if ($type) {
1689 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1690 }
1691 else {
1692 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1693 }
1694 }
1695 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1696 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1697 }
1698 else {
1699 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1700 }
1701 }
1702 else {
1703 $returnProperties['website'][$id][$fieldName] = 1;
1704 }
1705 }
1706 else {
1707 $returnProperties[$name] = 1;
1708 }
1709 }
1710
1711 return $returnProperties;
1712 }
1713
1714 /**
1715 * Return the primary location type of a contact.
1716 *
1717 * $params int $contactId contact_id
1718 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1719 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1720 *
1721 * @param int $contactId
1722 * @param bool $skipDefaultPriamry
1723 * @param null $block
1724 *
1725 * @return int
1726 * $locationType location_type_id
1727 */
1728 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1729 if ($block) {
1730 $entityBlock = array('contact_id' => $contactId);
1731 $blocks = CRM_Core_BAO_Location::getValues($entityBlock);
1732 foreach ($blocks[$block] as $key => $value) {
1733 if (!empty($value['is_primary'])) {
1734 $locationType = CRM_Utils_Array::value('location_type_id', $value);
1735 }
1736 }
1737 }
1738 else {
1739 $query = "
1740 SELECT
1741 IF ( civicrm_email.location_type_id IS NULL,
1742 IF ( civicrm_address.location_type_id IS NULL,
1743 IF ( civicrm_phone.location_type_id IS NULL,
1744 IF ( civicrm_im.location_type_id IS NULL,
1745 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1746 ,civicrm_im.location_type_id)
1747 ,civicrm_phone.location_type_id)
1748 ,civicrm_address.location_type_id)
1749 ,civicrm_email.location_type_id) as locationType
1750 FROM civicrm_contact
1751 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1752 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1753 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1754 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1755 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1756 WHERE civicrm_contact.id = %1 ";
1757
1758 $params = array(1 => array($contactId, 'Integer'));
1759
1760 $dao = CRM_Core_DAO::executeQuery($query, $params);
1761
1762 $locationType = NULL;
1763 if ($dao->fetch()) {
1764 $locationType = $dao->locationType;
1765 }
1766 }
1767 if (isset($locationType)) {
1768 return $locationType;
1769 }
1770 elseif ($skipDefaultPriamry) {
1771 // if there is no primary contact location then return null
1772 return NULL;
1773 }
1774 else {
1775 // if there is no primart contact location, then return default
1776 // location type of the system
1777 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
1778 return $defaultLocationType->id;
1779 }
1780 }
1781
1782 /**
1783 * Get the display name, primary email and location type of a contact.
1784 *
1785 * @param int $id
1786 * Id of the contact.
1787 *
1788 * @return array
1789 * Array of display_name, email if found, do_not_email or (null,null,null)
1790 */
1791 public static function getContactDetails($id) {
1792 // check if the contact type
1793 $contactType = self::getContactType($id);
1794
1795 $nameFields = ($contactType == 'Individual') ? "civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1796
1797 $sql = "
1798 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1799 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1800 WHERE civicrm_contact.id = %1
1801 ORDER BY civicrm_email.is_primary DESC";
1802 $params = array(1 => array($id, 'Integer'));
1803 $dao = CRM_Core_DAO::executeQuery($sql, $params);
1804
1805 if ($dao->fetch()) {
1806 if ($contactType == 'Individual') {
1807 if ($dao->first_name || $dao->last_name) {
1808 $name = "{$dao->first_name} {$dao->last_name}";
1809 }
1810 else {
1811 $name = $dao->display_name;
1812 }
1813 }
1814 else {
1815 $name = $dao->display_name;
1816 }
1817 $email = $dao->email;
1818 $doNotEmail = $dao->do_not_email ? TRUE : FALSE;
1819 $onHold = $dao->on_hold ? TRUE : FALSE;
1820 $isDeceased = $dao->is_deceased ? TRUE : FALSE;
1821 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1822 }
1823 return array(NULL, NULL, NULL, NULL, NULL);
1824 }
1825
1826 /**
1827 * Add/edit/register contacts through profile.
1828 *
1829 * @param array $params
1830 * Array of profile fields to be edited/added.
1831 * @param array $fields
1832 * Array of fields from UFGroup.
1833 * @param int $contactID
1834 * Id of the contact to be edited/added.
1835 * @param int $addToGroupID
1836 * Specifies the default group to which contact is added.
1837 * @param int $ufGroupId
1838 * Uf group id (profile id).
1839 * @param string $ctype
1840 * @param bool $visibility
1841 * Basically lets us know where this request is coming from.
1842 * if via a profile from web, we restrict what groups are changed
1843 *
1844 * @return int
1845 * contact id created/edited
1846 */
1847 public static function createProfileContact(
1848 &$params,
1849 &$fields,
1850 $contactID = NULL,
1851 $addToGroupID = NULL,
1852 $ufGroupId = NULL,
1853 $ctype = NULL,
1854 $visibility = FALSE
1855 ) {
1856 // add ufGroupID to params array ( CRM-2012 )
1857 if ($ufGroupId) {
1858 $params['uf_group_id'] = $ufGroupId;
1859 }
1860 self::addBillingNameFieldsIfOtherwiseNotSet($params);
1861
1862 // If a user has logged in, or accessed via a checksum
1863 // Then deliberately 'blanking' a value in the profile should remove it from their record
1864 $session = CRM_Core_Session::singleton();
1865 $params['updateBlankLocInfo'] = TRUE;
1866 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0) {
1867 $params['updateBlankLocInfo'] = FALSE;
1868 }
1869
1870 if ($contactID) {
1871 $editHook = TRUE;
1872 CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params);
1873 }
1874 else {
1875 $editHook = FALSE;
1876 CRM_Utils_Hook::pre('create', 'Profile', NULL, $params);
1877 }
1878
1879 list($data, $contactDetails) = self::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1880
1881 // manage is_opt_out
1882 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1883 $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, FALSE);
1884 $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
1885 $data['is_opt_out'] = $isOptOut;
1886 // on change, create new civicrm_subscription_history entry
1887 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1888 $shParams = array(
1889 'contact_id' => $contactDetails['contact_id'],
1890 'status' => $isOptOut ? 'Removed' : 'Added',
1891 'method' => 'Web',
1892 );
1893 CRM_Contact_BAO_SubscriptionHistory::create($shParams);
1894 }
1895 }
1896
1897 $contact = self::create($data);
1898
1899 // contact is null if the profile does not have any contact fields
1900 if ($contact) {
1901 $contactID = $contact->id;
1902 }
1903
1904 if (empty($contactID)) {
1905 CRM_Core_Error::fatal('Cannot proceed without a valid contact id');
1906 }
1907
1908 // Process group and tag
1909 if (!empty($fields['group'])) {
1910 $method = 'Admin';
1911 // this for sure means we are coming in via profile since i added it to fix
1912 // removing contacts from user groups -- lobo
1913 if ($visibility) {
1914 $method = 'Web';
1915 }
1916 CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method);
1917 }
1918
1919 if (!empty($fields['tag'])) {
1920 CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $contactID);
1921 }
1922
1923 //to add profile in default group
1924 if (is_array($addToGroupID)) {
1925 $contactIds = array($contactID);
1926 foreach ($addToGroupID as $groupId) {
1927 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
1928 }
1929 }
1930 elseif ($addToGroupID) {
1931 $contactIds = array($contactID);
1932 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID);
1933 }
1934
1935 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
1936
1937 if ($editHook) {
1938 CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params);
1939 }
1940 else {
1941 CRM_Utils_Hook::post('create', 'Profile', $contactID, $params);
1942 }
1943 return $contactID;
1944 }
1945
1946 /**
1947 * Format profile contact parameters.
1948 *
1949 * @param array $params
1950 * @param $fields
1951 * @param int $contactID
1952 * @param int $ufGroupId
1953 * @param null $ctype
1954 * @param bool $skipCustom
1955 *
1956 * @return array
1957 */
1958 public static function formatProfileContactParams(
1959 &$params,
1960 &$fields,
1961 $contactID = NULL,
1962 $ufGroupId = NULL,
1963 $ctype = NULL,
1964 $skipCustom = FALSE
1965 ) {
1966
1967 $data = $contactDetails = array();
1968
1969 // get the contact details (hier)
1970 if ($contactID) {
1971 list($details, $options) = self::getHierContactDetails($contactID, $fields);
1972
1973 $contactDetails = $details[$contactID];
1974 $data['contact_type'] = CRM_Utils_Array::value('contact_type', $contactDetails);
1975 $data['contact_sub_type'] = CRM_Utils_Array::value('contact_sub_type', $contactDetails);
1976 }
1977 else {
1978 //we should get contact type only if contact
1979 if ($ufGroupId) {
1980 $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId);
1981
1982 //special case to handle profile with only contact fields
1983 if ($data['contact_type'] == 'Contact') {
1984 $data['contact_type'] = 'Individual';
1985 }
1986 elseif (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) {
1987 $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']);
1988 }
1989 }
1990 elseif ($ctype) {
1991 $data['contact_type'] = $ctype;
1992 }
1993 else {
1994 $data['contact_type'] = 'Individual';
1995 }
1996 }
1997
1998 //fix contact sub type CRM-5125
1999 if (array_key_exists('contact_sub_type', $params) &&
2000 !empty($params['contact_sub_type'])
2001 ) {
2002 $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
2003 }
2004 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2005 !empty($params['contact_sub_type_hidden'])
2006 ) {
2007 // if profile was used, and had any subtype, we obtain it from there
2008 //CRM-13596 - add to existing contact types, rather than overwriting
2009 $data_contact_sub_type_arr = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
2010 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2011 $data['contact_sub_type'] .= CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
2012 }
2013 }
2014
2015 if ($ctype == 'Organization') {
2016 $data['organization_name'] = CRM_Utils_Array::value('organization_name', $contactDetails);
2017 }
2018 elseif ($ctype == 'Household') {
2019 $data['household_name'] = CRM_Utils_Array::value('household_name', $contactDetails);
2020 }
2021
2022 $locationType = array();
2023 $count = 1;
2024
2025 if ($contactID) {
2026 //add contact id
2027 $data['contact_id'] = $contactID;
2028 $primaryLocationType = self::getPrimaryLocationType($contactID);
2029 }
2030 else {
2031 $defaultLocation = CRM_Core_BAO_LocationType::getDefault();
2032 $defaultLocationId = $defaultLocation->id;
2033 }
2034
2035 $billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling();
2036
2037 $blocks = array('email', 'phone', 'im', 'openid');
2038
2039 $multiplFields = array('url');
2040 // prevent overwritten of formatted array, reset all block from
2041 // params if it is not in valid format (since import pass valid format)
2042 foreach ($blocks as $blk) {
2043 if (array_key_exists($blk, $params) &&
2044 !is_array($params[$blk])
2045 ) {
2046 unset($params[$blk]);
2047 }
2048 }
2049
2050 $primaryPhoneLoc = NULL;
2051 $session = CRM_Core_Session::singleton();
2052 foreach ($params as $key => $value) {
2053 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3);
2054
2055 if ($locTypeId == 'Primary') {
2056 if ($contactID) {
2057 if (in_array($fieldName, $blocks)) {
2058 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, $fieldName);
2059 }
2060 else {
2061 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, 'address');
2062 }
2063 $primaryLocationType = $locTypeId;
2064 }
2065 else {
2066 $locTypeId = $defaultLocationId;
2067 }
2068 }
2069
2070 if (is_numeric($locTypeId) &&
2071 !in_array($fieldName, $multiplFields) &&
2072 substr($fieldName, 0, 7) != 'custom_'
2073 ) {
2074 $index = $locTypeId;
2075
2076 if (is_numeric($typeId)) {
2077 $index .= '-' . $typeId;
2078 }
2079 if (!in_array($index, $locationType)) {
2080 $locationType[$count] = $index;
2081 $count++;
2082 }
2083
2084 $loc = CRM_Utils_Array::key($index, $locationType);
2085
2086 $blockName = in_array($fieldName, $blocks) ? $fieldName : 'address';
2087
2088 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2089
2090 //set is_billing true, for location type "Billing"
2091 if ($locTypeId == $billingLocationTypeId) {
2092 $data[$blockName][$loc]['is_billing'] = 1;
2093 }
2094
2095 if ($contactID) {
2096 //get the primary location type
2097 if ($locTypeId == $primaryLocationType) {
2098 $data[$blockName][$loc]['is_primary'] = 1;
2099 }
2100 }
2101 elseif ($locTypeId == $defaultLocationId) {
2102 $data[$blockName][$loc]['is_primary'] = 1;
2103 }
2104
2105 if (in_array($fieldName, array('phone'))) {
2106 if ($typeId) {
2107 $data['phone'][$loc]['phone_type_id'] = $typeId;
2108 }
2109 else {
2110 $data['phone'][$loc]['phone_type_id'] = '';
2111 }
2112 $data['phone'][$loc]['phone'] = $value;
2113
2114 //special case to handle primary phone with different phone types
2115 // in this case we make first phone type as primary
2116 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2117 $primaryPhoneLoc = $loc;
2118 }
2119
2120 if ($loc != $primaryPhoneLoc) {
2121 unset($data['phone'][$loc]['is_primary']);
2122 }
2123 }
2124 elseif ($fieldName == 'phone_ext') {
2125 $data['phone'][$loc]['phone_ext'] = $value;
2126 }
2127 elseif ($fieldName == 'email') {
2128 $data['email'][$loc]['email'] = $value;
2129 if (empty($contactID)) {
2130 $data['email'][$loc]['is_primary'] = 1;
2131 }
2132 }
2133 elseif ($fieldName == 'im') {
2134 if (isset($params[$key . '-provider_id'])) {
2135 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2136 }
2137 if (strpos($key, '-provider_id') !== FALSE) {
2138 $data['im'][$loc]['provider_id'] = $params[$key];
2139 }
2140 else {
2141 $data['im'][$loc]['name'] = $value;
2142 }
2143 }
2144 elseif ($fieldName == 'openid') {
2145 $data['openid'][$loc]['openid'] = $value;
2146 }
2147 else {
2148 if ($fieldName === 'state_province') {
2149 // CRM-3393
2150 if (is_numeric($value) && ((int ) $value) >= 1000) {
2151 $data['address'][$loc]['state_province_id'] = $value;
2152 }
2153 elseif (empty($value)) {
2154 $data['address'][$loc]['state_province_id'] = '';
2155 }
2156 else {
2157 $data['address'][$loc]['state_province'] = $value;
2158 }
2159 }
2160 elseif ($fieldName === 'country') {
2161 // CRM-3393
2162 if (is_numeric($value) && ((int ) $value) >= 1000
2163 ) {
2164 $data['address'][$loc]['country_id'] = $value;
2165 }
2166 elseif (empty($value)) {
2167 $data['address'][$loc]['country_id'] = '';
2168 }
2169 else {
2170 $data['address'][$loc]['country'] = $value;
2171 }
2172 }
2173 elseif ($fieldName === 'county') {
2174 $data['address'][$loc]['county_id'] = $value;
2175 }
2176 elseif ($fieldName == 'address_name') {
2177 $data['address'][$loc]['name'] = $value;
2178 }
2179 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2180 $data['address'][$loc][substr($fieldName, 8)] = $value;
2181 }
2182 else {
2183 $data['address'][$loc][$fieldName] = $value;
2184 }
2185 }
2186 }
2187 else {
2188 if (substr($key, 0, 4) === 'url-') {
2189 $websiteField = explode('-', $key);
2190 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2191 $data['website'][$websiteField[1]]['url'] = $value;
2192 }
2193 elseif (in_array($key, self::$_greetingTypes, TRUE)) {
2194 //save email/postal greeting and addressee values if any, CRM-4575
2195 $data[$key . '_id'] = $value;
2196 }
2197 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) {
2198 // for autocomplete transfer hidden value instead of label
2199 if ($params[$key] && isset($params[$key . '_id'])) {
2200 $value = $params[$key . '_id'];
2201 }
2202
2203 // we need to append time with date
2204 if ($params[$key] && isset($params[$key . '_time'])) {
2205 $value .= ' ' . $params[$key . '_time'];
2206 }
2207
2208 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2209 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 &&
2210 ($value == '' || !isset($value))
2211 ) {
2212 continue;
2213 }
2214
2215 $valueId = NULL;
2216 if (!empty($params['customRecordValues'])) {
2217 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2218 foreach ($params['customRecordValues'] as $recId => $customFields) {
2219 if (is_array($customFields) && !empty($customFields)) {
2220 foreach ($customFields as $customFieldName) {
2221 if ($customFieldName == $key) {
2222 $valueId = $recId;
2223 break;
2224 }
2225 }
2226 }
2227 }
2228 }
2229 }
2230
2231 //CRM-13596 - check for contact_sub_type_hidden first
2232 if (array_key_exists('contact_sub_type_hidden', $params)) {
2233 $type = $params['contact_sub_type_hidden'];
2234 }
2235 else {
2236 $type = $data['contact_type'];
2237 if (!empty($data['contact_sub_type'])) {
2238 $type = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
2239 }
2240 }
2241
2242 CRM_Core_BAO_CustomField::formatCustomField($customFieldId,
2243 $data['custom'],
2244 $value,
2245 $type,
2246 $valueId,
2247 $contactID,
2248 FALSE,
2249 FALSE
2250 );
2251 }
2252 elseif ($key == 'edit') {
2253 continue;
2254 }
2255 else {
2256 if ($key == 'location') {
2257 foreach ($value as $locationTypeId => $field) {
2258 foreach ($field as $block => $val) {
2259 if ($block == 'address' && array_key_exists('address_name', $val)) {
2260 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2261 }
2262 }
2263 }
2264 }
2265 if ($key == 'phone' && isset($params['phone_ext'])) {
2266 $data[$key] = $value;
2267 foreach ($value as $cnt => $phoneBlock) {
2268 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2269 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2270 }
2271 }
2272 }
2273 elseif (in_array($key,
2274 array(
2275 'nick_name',
2276 'job_title',
2277 'middle_name',
2278 'birth_date',
2279 'gender_id',
2280 'current_employer',
2281 'prefix_id',
2282 'suffix_id',
2283 )) &&
2284 ($value == '' || !isset($value)) &&
2285 ($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 ||
2286 ($key == 'current_employer' && empty($params['current_employer']))) {
2287 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2288 // to avoid update with empty values
2289 continue;
2290 }
2291 else {
2292 $data[$key] = $value;
2293 }
2294 }
2295 }
2296 }
2297
2298 if (!isset($data['contact_type'])) {
2299 $data['contact_type'] = 'Individual';
2300 }
2301
2302 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2303 $privacy = CRM_Core_SelectValues::privacy();
2304 foreach ($privacy as $key => $value) {
2305 if (array_key_exists($key, $fields)) {
2306 // do not reset values for existing contacts, if fields are added to a profile
2307 if (array_key_exists($key, $params)) {
2308 $data[$key] = $params[$key];
2309 if (empty($params[$key])) {
2310 $data[$key] = 0;
2311 }
2312 }
2313 elseif (!$contactID) {
2314 $data[$key] = 0;
2315 }
2316 }
2317 }
2318
2319 return array($data, $contactDetails);
2320 }
2321
2322 /**
2323 * Find the get contact details.
2324 *
2325 * This function does not respect ACLs for now, which might need to be rectified at some
2326 * stage based on how its used.
2327 *
2328 * @param string $mail
2329 * Primary email address of the contact.
2330 * @param string $ctype
2331 * Contact type.
2332 *
2333 * @return object|null
2334 * $dao contact details
2335 */
2336 public static function matchContactOnEmail($mail, $ctype = NULL) {
2337 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2338 $mail = $strtolower(trim($mail));
2339 $query = "
2340 SELECT civicrm_contact.id as contact_id,
2341 civicrm_contact.hash as hash,
2342 civicrm_contact.contact_type as contact_type,
2343 civicrm_contact.contact_sub_type as contact_sub_type
2344 FROM civicrm_contact
2345 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2346
2347 if (Civi::settings()->get('uniq_email_per_site')) {
2348 // try to find a match within a site (multisite).
2349 $groups = CRM_Core_BAO_Domain::getChildGroupIds();
2350 if (!empty($groups)) {
2351 $query .= "
2352 INNER JOIN civicrm_group_contact gc ON
2353 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2354 }
2355 }
2356
2357 $query .= "
2358 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2359 $p = array(1 => array($mail, 'String'));
2360
2361 if ($ctype) {
2362 $query .= " AND civicrm_contact.contact_type = %3";
2363 $p[3] = array($ctype, 'String');
2364 }
2365
2366 $query .= " ORDER BY civicrm_email.is_primary DESC";
2367
2368 $dao = CRM_Core_DAO::executeQuery($query, $p);
2369
2370 if ($dao->fetch()) {
2371 return $dao;
2372 }
2373 return NULL;
2374 }
2375
2376 /**
2377 * Find the contact details associated with an OpenID.
2378 *
2379 * @param string $openId
2380 * OpenId of the contact.
2381 * @param string $ctype
2382 * Contact type.
2383 *
2384 * @return object|null
2385 * $dao contact details
2386 */
2387 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2388 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2389 $openId = $strtolower(trim($openId));
2390 $query = "
2391 SELECT civicrm_contact.id as contact_id,
2392 civicrm_contact.hash as hash,
2393 civicrm_contact.contact_type as contact_type,
2394 civicrm_contact.contact_sub_type as contact_sub_type
2395 FROM civicrm_contact
2396 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2397 WHERE civicrm_openid.openid = %1";
2398 $p = array(1 => array($openId, 'String'));
2399
2400 if ($ctype) {
2401 $query .= " AND civicrm_contact.contact_type = %3";
2402 $p[3] = array($ctype, 'String');
2403 }
2404
2405 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2406
2407 $dao = CRM_Core_DAO::executeQuery($query, $p);
2408
2409 if ($dao->fetch()) {
2410 return $dao;
2411 }
2412 return NULL;
2413 }
2414
2415 /**
2416 * Get primary email of the contact.
2417 *
2418 * @param int $contactID
2419 * Contact id.
2420 *
2421 * @return string
2422 * Email address if present else null
2423 */
2424 public static function getPrimaryEmail($contactID) {
2425 // fetch the primary email
2426 $query = "
2427 SELECT civicrm_email.email as email
2428 FROM civicrm_contact
2429 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2430 WHERE civicrm_email.is_primary = 1
2431 AND civicrm_contact.id = %1";
2432 $p = array(1 => array($contactID, 'Integer'));
2433 $dao = CRM_Core_DAO::executeQuery($query, $p);
2434
2435 $email = NULL;
2436 if ($dao->fetch()) {
2437 $email = $dao->email;
2438 }
2439 $dao->free();
2440 return $email;
2441 }
2442
2443 /**
2444 * Function to get primary OpenID of the contact.
2445 *
2446 * @param int $contactID
2447 * Contact id.
2448 *
2449 * @return string
2450 * >openid OpenID if present else null
2451 */
2452 public static function getPrimaryOpenId($contactID) {
2453 // fetch the primary OpenID
2454 $query = "
2455 SELECT civicrm_openid.openid as openid
2456 FROM civicrm_contact
2457 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2458 WHERE civicrm_contact.id = %1
2459 AND civicrm_openid.is_primary = 1";
2460 $p = array(1 => array($contactID, 'Integer'));
2461 $dao = CRM_Core_DAO::executeQuery($query, $p);
2462
2463 $openId = NULL;
2464 if ($dao->fetch()) {
2465 $openId = $dao->openid;
2466 }
2467 $dao->free();
2468 return $openId;
2469 }
2470
2471 /**
2472 * Fetch the object and store the values in the values array.
2473 *
2474 * @param array $params
2475 * Input parameters to find object.
2476 * @param array $values
2477 * Output values of the object.
2478 *
2479 * @return CRM_Contact_BAO_Contact|null
2480 * The found object or null
2481 */
2482 public static function getValues(&$params, &$values) {
2483 $contact = new CRM_Contact_BAO_Contact();
2484
2485 $contact->copyValues($params);
2486
2487 if ($contact->find(TRUE)) {
2488
2489 CRM_Core_DAO::storeValues($contact, $values);
2490
2491 $privacy = array();
2492 foreach (self::$_commPrefs as $name) {
2493 if (isset($contact->$name)) {
2494 $privacy[$name] = $contact->$name;
2495 }
2496 }
2497
2498 if (!empty($privacy)) {
2499 $values['privacy'] = $privacy;
2500 }
2501
2502 // communication Prefferance
2503 $preffComm = $comm = array();
2504 $comm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2505 $contact->preferred_communication_method
2506 );
2507 foreach ($comm as $value) {
2508 $preffComm[$value] = 1;
2509 }
2510 $temp = array('preferred_communication_method' => $contact->preferred_communication_method);
2511
2512 $names = array(
2513 'preferred_communication_method' => array(
2514 'newName' => 'preferred_communication_method_display',
2515 'groupName' => 'preferred_communication_method',
2516 ),
2517 );
2518
2519 CRM_Core_OptionGroup::lookupValues($temp, $names, FALSE);
2520
2521 $values['preferred_communication_method'] = $preffComm;
2522 $values['preferred_communication_method_display'] = CRM_Utils_Array::value('preferred_communication_method_display', $temp);
2523
2524 if ($contact->preferred_mail_format) {
2525 $preferredMailingFormat = CRM_Core_SelectValues::pmf();
2526 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format];
2527 }
2528
2529 // get preferred languages
2530 if (!empty($contact->preferred_language)) {
2531 $values['preferred_language'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language);
2532 }
2533
2534 // Calculating Year difference
2535 if ($contact->birth_date) {
2536 $birthDate = CRM_Utils_Date::customFormat($contact->birth_date, '%Y%m%d');
2537 if ($birthDate < date('Ymd')) {
2538 $age = CRM_Utils_Date::calculateAge($birthDate);
2539 $values['age']['y'] = CRM_Utils_Array::value('years', $age);
2540 $values['age']['m'] = CRM_Utils_Array::value('months', $age);
2541 }
2542
2543 list($values['birth_date']) = CRM_Utils_Date::setDateDefaults($contact->birth_date, 'birth');
2544 $values['birth_date_display'] = $contact->birth_date;
2545 }
2546
2547 if ($contact->deceased_date) {
2548 list($values['deceased_date']) = CRM_Utils_Date::setDateDefaults($contact->deceased_date, 'birth');
2549 $values['deceased_date_display'] = $contact->deceased_date;
2550 }
2551
2552 $contact->contact_id = $contact->id;
2553
2554 return $contact;
2555 }
2556 return NULL;
2557 }
2558
2559 /**
2560 * Given the component name and returns the count of participation of contact.
2561 *
2562 * @param string $component
2563 * Input component name.
2564 * @param int $contactId
2565 * Input contact id.
2566 * @param string $tableName
2567 * Optional tableName if component is custom group.
2568 *
2569 * @return int
2570 * total number in database
2571 */
2572 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2573 $object = NULL;
2574 switch ($component) {
2575 case 'tag':
2576 return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE);
2577
2578 case 'rel':
2579 $result = CRM_Contact_BAO_Relationship::getRelationship($contactId,
2580 CRM_Contact_BAO_Relationship::CURRENT,
2581 0, 0, 0,
2582 NULL, NULL,
2583 TRUE
2584 );
2585 return count($result);
2586
2587 case 'group':
2588
2589 return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE);
2590
2591 case 'log':
2592 if (CRM_Core_BAO_Log::useLoggingReport()) {
2593 return FALSE;
2594 }
2595 return CRM_Core_BAO_Log::getContactLogCount($contactId);
2596
2597 case 'note':
2598 return CRM_Core_BAO_Note::getContactNoteCount($contactId);
2599
2600 case 'contribution':
2601 return CRM_Contribute_BAO_Contribution::contributionCount($contactId);
2602
2603 case 'membership':
2604 return CRM_Member_BAO_Membership::getContactMembershipCount($contactId, TRUE);
2605
2606 case 'participant':
2607 return CRM_Event_BAO_Participant::getContactParticipantCount($contactId);
2608
2609 case 'pledge':
2610 return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId);
2611
2612 case 'case':
2613 return CRM_Case_BAO_Case::caseCount($contactId);
2614
2615 case 'grant':
2616 return CRM_Grant_BAO_Grant::getContactGrantCount($contactId);
2617
2618 case 'activity':
2619 $input = array(
2620 'contact_id' => $contactId,
2621 'admin' => FALSE,
2622 'caseId' => NULL,
2623 'context' => 'activity',
2624 );
2625 return CRM_Activity_BAO_Activity::getActivitiesCount($input);
2626
2627 case 'mailing':
2628 $params = array('contact_id' => $contactId);
2629 return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
2630
2631 default:
2632 $custom = explode('_', $component);
2633 if ($custom['0'] = 'custom') {
2634 if (!$tableName) {
2635 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2636 }
2637 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2638 return CRM_Core_DAO::singleValueQuery($queryString);
2639 }
2640 }
2641 }
2642
2643 /**
2644 * Process greetings and cache.
2645 *
2646 * @param object $contact
2647 * Contact object after save.
2648 * @param bool $useDefaults
2649 * Use default greeting values.
2650 */
2651 public static function processGreetings(&$contact, $useDefaults = FALSE) {
2652 if ($useDefaults) {
2653 //retrieve default greetings
2654 $defaultGreetings = CRM_Core_PseudoConstant::greetingDefaults();
2655 $contactDefaults = $defaultGreetings[$contact->contact_type];
2656 }
2657
2658 // note that contact object not always has required greeting related
2659 // fields that are required to calculate greeting and
2660 // also other fields used in tokens etc,
2661 // hence we need to retrieve it again.
2662 if ($contact->_query !== FALSE) {
2663 $contact->find(TRUE);
2664 }
2665
2666 // store object values to an array
2667 $contactDetails = array();
2668 CRM_Core_DAO::storeValues($contact, $contactDetails);
2669 $contactDetails = array(array($contact->id => $contactDetails));
2670
2671 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2672 $updateQueryString = array();
2673
2674 //cache email and postal greeting to greeting display
2675 if ($contact->email_greeting_custom != 'null' && $contact->email_greeting_custom) {
2676 $emailGreetingString = $contact->email_greeting_custom;
2677 }
2678 elseif ($contact->email_greeting_id != 'null' && $contact->email_greeting_id) {
2679 // the filter value for Individual contact type is set to 1
2680 $filter = array(
2681 'contact_type' => $contact->contact_type,
2682 'greeting_type' => 'email_greeting',
2683 );
2684
2685 $emailGreeting = CRM_Core_PseudoConstant::greeting($filter);
2686 $emailGreetingString = $emailGreeting[$contact->email_greeting_id];
2687 $updateQueryString[] = " email_greeting_custom = NULL ";
2688 }
2689 else {
2690 if ($useDefaults) {
2691 reset($contactDefaults['email_greeting']);
2692 $emailGreetingID = key($contactDefaults['email_greeting']);
2693 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2694 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2695 $updateQueryString[] = " email_greeting_custom = NULL ";
2696 }
2697 elseif ($contact->email_greeting_custom) {
2698 $updateQueryString[] = " email_greeting_display = NULL ";
2699 }
2700 }
2701
2702 if ($emailGreetingString) {
2703 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($emailGreetingString,
2704 $contactDetails,
2705 $contact->id,
2706 'CRM_Contact_BAO_Contact'
2707 );
2708 $emailGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($emailGreetingString));
2709 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2710 }
2711
2712 //postal greetings
2713 if ($contact->postal_greeting_custom != 'null' && $contact->postal_greeting_custom) {
2714 $postalGreetingString = $contact->postal_greeting_custom;
2715 }
2716 elseif ($contact->postal_greeting_id != 'null' && $contact->postal_greeting_id) {
2717 $filter = array(
2718 'contact_type' => $contact->contact_type,
2719 'greeting_type' => 'postal_greeting',
2720 );
2721 $postalGreeting = CRM_Core_PseudoConstant::greeting($filter);
2722 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id];
2723 $updateQueryString[] = " postal_greeting_custom = NULL ";
2724 }
2725 else {
2726 if ($useDefaults) {
2727 reset($contactDefaults['postal_greeting']);
2728 $postalGreetingID = key($contactDefaults['postal_greeting']);
2729 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2730 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2731 $updateQueryString[] = " postal_greeting_custom = NULL ";
2732 }
2733 elseif ($contact->postal_greeting_custom) {
2734 $updateQueryString[] = " postal_greeting_display = NULL ";
2735 }
2736 }
2737
2738 if ($postalGreetingString) {
2739 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($postalGreetingString,
2740 $contactDetails,
2741 $contact->id,
2742 'CRM_Contact_BAO_Contact'
2743 );
2744 $postalGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($postalGreetingString));
2745 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2746 }
2747
2748 // addressee
2749 if ($contact->addressee_custom != 'null' && $contact->addressee_custom) {
2750 $addresseeString = $contact->addressee_custom;
2751 }
2752 elseif ($contact->addressee_id != 'null' && $contact->addressee_id) {
2753 $filter = array(
2754 'contact_type' => $contact->contact_type,
2755 'greeting_type' => 'addressee',
2756 );
2757
2758 $addressee = CRM_Core_PseudoConstant::greeting($filter);
2759 $addresseeString = $addressee[$contact->addressee_id];
2760 $updateQueryString[] = " addressee_custom = NULL ";
2761 }
2762 else {
2763 if ($useDefaults) {
2764 reset($contactDefaults['addressee']);
2765 $addresseeID = key($contactDefaults['addressee']);
2766 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2767 $updateQueryString[] = " addressee_id = $addresseeID ";
2768 $updateQueryString[] = " addressee_custom = NULL ";
2769 }
2770 elseif ($contact->addressee_custom) {
2771 $updateQueryString[] = " addressee_display = NULL ";
2772 }
2773 }
2774
2775 if ($addresseeString) {
2776 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($addresseeString,
2777 $contactDetails,
2778 $contact->id,
2779 'CRM_Contact_BAO_Contact'
2780 );
2781 $addresseeString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($addresseeString));
2782 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2783 }
2784
2785 if (!empty($updateQueryString)) {
2786 $updateQueryString = implode(',', $updateQueryString);
2787 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2788 CRM_Core_DAO::executeQuery($queryString);
2789 }
2790 }
2791
2792 /**
2793 * Retrieve loc block ids w/ given condition.
2794 *
2795 * @param int $contactId
2796 * Contact id.
2797 * @param array $criteria
2798 * Key => value pair which should be.
2799 * fulfill by return record ids.
2800 * @param string $condOperator
2801 * Operator use for grouping multiple conditions.
2802 *
2803 * @return array
2804 * loc block ids which fulfill condition.
2805 */
2806 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2807 $locBlockIds = array();
2808 if (!$contactId) {
2809 return $locBlockIds;
2810 }
2811
2812 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2813 $name = strtolower($block);
2814 $className = "CRM_Core_DAO_$block";
2815 $blockDAO = new $className();
2816
2817 // build the condition.
2818 if (is_array($criteria)) {
2819 $fields = $blockDAO->fields();
2820 $conditions = array();
2821 foreach ($criteria as $field => $value) {
2822 if (array_key_exists($field, $fields)) {
2823 $cond = "( $field = $value )";
2824 // value might be zero or null.
2825 if (!$value || strtolower($value) == 'null') {
2826 $cond = "( $field = 0 OR $field IS NULL )";
2827 }
2828 $conditions[] = $cond;
2829 }
2830 }
2831 if (!empty($conditions)) {
2832 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2833 }
2834 }
2835
2836 $blockDAO->contact_id = $contactId;
2837 $blockDAO->find();
2838 while ($blockDAO->fetch()) {
2839 $locBlockIds[$name][] = $blockDAO->id;
2840 }
2841 $blockDAO->free();
2842 }
2843
2844 return $locBlockIds;
2845 }
2846
2847 /**
2848 * Build context menu items.
2849 *
2850 * @param int $contactId
2851 *
2852 * @return array
2853 * Array of context menu for logged in user.
2854 */
2855 public static function contextMenu($contactId = NULL) {
2856 $menu = array(
2857 'view' => array(
2858 'title' => ts('View Contact'),
2859 'weight' => 0,
2860 'ref' => 'view-contact',
2861 'class' => 'no-popup',
2862 'key' => 'view',
2863 'permissions' => array('view all contacts'),
2864 ),
2865 'add' => array(
2866 'title' => ts('Edit Contact'),
2867 'weight' => 0,
2868 'ref' => 'edit-contact',
2869 'class' => 'no-popup',
2870 'key' => 'add',
2871 'permissions' => array('edit all contacts'),
2872 ),
2873 'delete' => array(
2874 'title' => ts('Delete Contact'),
2875 'weight' => 0,
2876 'ref' => 'delete-contact',
2877 'key' => 'delete',
2878 'permissions' => array('access deleted contacts', 'delete contacts'),
2879 ),
2880 'contribution' => array(
2881 'title' => ts('Add Contribution'),
2882 'weight' => 5,
2883 'ref' => 'new-contribution',
2884 'key' => 'contribution',
2885 'tab' => 'contribute',
2886 'component' => 'CiviContribute',
2887 'href' => CRM_Utils_System::url('civicrm/contact/view/contribution',
2888 'reset=1&action=add&context=contribution'
2889 ),
2890 'permissions' => array(
2891 'access CiviContribute',
2892 'edit contributions',
2893 ),
2894 ),
2895 'participant' => array(
2896 'title' => ts('Register for Event'),
2897 'weight' => 10,
2898 'ref' => 'new-participant',
2899 'key' => 'participant',
2900 'tab' => 'participant',
2901 'component' => 'CiviEvent',
2902 'href' => CRM_Utils_System::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2903 'permissions' => array(
2904 'access CiviEvent',
2905 'edit event participants',
2906 ),
2907 ),
2908 'activity' => array(
2909 'title' => ts('Record Activity'),
2910 'weight' => 35,
2911 'ref' => 'new-activity',
2912 'key' => 'activity',
2913 'permissions' => array('edit all contacts'),
2914 ),
2915 'pledge' => array(
2916 'title' => ts('Add Pledge'),
2917 'weight' => 15,
2918 'ref' => 'new-pledge',
2919 'key' => 'pledge',
2920 'tab' => 'pledge',
2921 'href' => CRM_Utils_System::url('civicrm/contact/view/pledge',
2922 'reset=1&action=add&context=pledge'
2923 ),
2924 'component' => 'CiviPledge',
2925 'permissions' => array(
2926 'access CiviPledge',
2927 'edit pledges',
2928 ),
2929 ),
2930 'membership' => array(
2931 'title' => ts('Add Membership'),
2932 'weight' => 20,
2933 'ref' => 'new-membership',
2934 'key' => 'membership',
2935 'tab' => 'member',
2936 'component' => 'CiviMember',
2937 'href' => CRM_Utils_System::url('civicrm/contact/view/membership',
2938 'reset=1&action=add&context=membership'
2939 ),
2940 'permissions' => array(
2941 'access CiviMember',
2942 'edit memberships',
2943 ),
2944 ),
2945 'case' => array(
2946 'title' => ts('Add Case'),
2947 'weight' => 25,
2948 'ref' => 'new-case',
2949 'key' => 'case',
2950 'tab' => 'case',
2951 'component' => 'CiviCase',
2952 'href' => CRM_Utils_System::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2953 'permissions' => array('add cases'),
2954 ),
2955 'grant' => array(
2956 'title' => ts('Add Grant'),
2957 'weight' => 26,
2958 'ref' => 'new-grant',
2959 'key' => 'grant',
2960 'tab' => 'grant',
2961 'component' => 'CiviGrant',
2962 'href' => CRM_Utils_System::url('civicrm/contact/view/grant',
2963 'reset=1&action=add&context=grant'
2964 ),
2965 'permissions' => array('edit grants'),
2966 ),
2967 'rel' => array(
2968 'title' => ts('Add Relationship'),
2969 'weight' => 30,
2970 'ref' => 'new-relationship',
2971 'key' => 'rel',
2972 'tab' => 'rel',
2973 'href' => CRM_Utils_System::url('civicrm/contact/view/rel',
2974 'reset=1&action=add'
2975 ),
2976 'permissions' => array('edit all contacts'),
2977 ),
2978 'note' => array(
2979 'title' => ts('Add Note'),
2980 'weight' => 40,
2981 'ref' => 'new-note',
2982 'key' => 'note',
2983 'tab' => 'note',
2984 'class' => 'medium-popup',
2985 'href' => CRM_Utils_System::url('civicrm/contact/view/note',
2986 'reset=1&action=add'
2987 ),
2988 'permissions' => array('edit all contacts'),
2989 ),
2990 'email' => array(
2991 'title' => ts('Send an Email'),
2992 'weight' => 45,
2993 'ref' => 'new-email',
2994 'key' => 'email',
2995 'permissions' => array('view all contacts'),
2996 ),
2997 'group' => array(
2998 'title' => ts('Add to Group'),
2999 'weight' => 50,
3000 'ref' => 'group-add-contact',
3001 'key' => 'group',
3002 'tab' => 'group',
3003 'permissions' => array('edit groups'),
3004 ),
3005 'tag' => array(
3006 'title' => ts('Tag Contact'),
3007 'weight' => 55,
3008 'ref' => 'tag-contact',
3009 'key' => 'tag',
3010 'tab' => 'tag',
3011 'permissions' => array('edit all contacts'),
3012 ),
3013 );
3014
3015 CRM_Utils_Hook::summaryActions($menu, $contactId);
3016 //1. check for component is active.
3017 //2. check for user permissions.
3018 //3. check for acls.
3019 //3. edit and view contact are directly accessible to user.
3020
3021 $aclPermissionedTasks = array(
3022 'view-contact',
3023 'edit-contact',
3024 'new-activity',
3025 'new-email',
3026 'group-add-contact',
3027 'tag-contact',
3028 'delete-contact',
3029 );
3030 $corePermission = CRM_Core_Permission::getPermission();
3031
3032 $config = CRM_Core_Config::singleton();
3033
3034 $contextMenu = array();
3035 foreach ($menu as $key => $values) {
3036 $componentName = CRM_Utils_Array::value('component', $values);
3037
3038 // if component action - make sure component is enable.
3039 if ($componentName && !in_array($componentName, $config->enableComponents)) {
3040 continue;
3041 }
3042
3043 // make sure user has all required permissions.
3044 $hasAllPermissions = FALSE;
3045
3046 $permissions = CRM_Utils_Array::value('permissions', $values);
3047 if (!is_array($permissions) || empty($permissions)) {
3048 $hasAllPermissions = TRUE;
3049 }
3050
3051 // iterate for required permissions in given permissions array.
3052 if (!$hasAllPermissions) {
3053 $hasPermissions = 0;
3054 foreach ($permissions as $permission) {
3055 if (CRM_Core_Permission::check($permission)) {
3056 $hasPermissions++;
3057 }
3058 }
3059
3060 if (count($permissions) == $hasPermissions) {
3061 $hasAllPermissions = TRUE;
3062 }
3063
3064 // if still user does not have required permissions, check acl.
3065 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
3066 if (in_array($values['ref'], $aclPermissionedTasks) &&
3067 $corePermission == CRM_Core_Permission::EDIT
3068 ) {
3069 $hasAllPermissions = TRUE;
3070 }
3071 elseif (in_array($values['ref'], array(
3072 'new-email',
3073 ))) {
3074 // grant permissions for these tasks.
3075 $hasAllPermissions = TRUE;
3076 }
3077 }
3078 }
3079
3080 // user does not have necessary permissions.
3081 if (!$hasAllPermissions) {
3082 continue;
3083 }
3084
3085 // build directly accessible action menu.
3086 if (in_array($values['ref'], array(
3087 'view-contact',
3088 'edit-contact',
3089 ))) {
3090 $contextMenu['primaryActions'][$key] = array(
3091 'title' => $values['title'],
3092 'ref' => $values['ref'],
3093 'class' => CRM_Utils_Array::value('class', $values),
3094 'key' => $values['key'],
3095 );
3096 continue;
3097 }
3098
3099 // finally get menu item for -more- action widget.
3100 $contextMenu['moreActions'][$values['weight']] = array(
3101 'title' => $values['title'],
3102 'ref' => $values['ref'],
3103 'href' => CRM_Utils_Array::value('href', $values),
3104 'tab' => CRM_Utils_Array::value('tab', $values),
3105 'class' => CRM_Utils_Array::value('class', $values),
3106 'key' => $values['key'],
3107 );
3108 }
3109
3110 ksort($contextMenu['moreActions']);
3111
3112 return $contextMenu;
3113 }
3114
3115 /**
3116 * Retrieve display name of contact that address is shared.
3117 *
3118 * This is based on $masterAddressId or $contactId .
3119 *
3120 * @param int $masterAddressId
3121 * Master id.
3122 * @param int $contactId
3123 * Contact id.
3124 *
3125 * @return string|null
3126 * the found display name or null.
3127 */
3128 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3129 $masterDisplayName = NULL;
3130 $sql = NULL;
3131 if (!$masterAddressId && !$contactId) {
3132 return $masterDisplayName;
3133 }
3134
3135 if ($masterAddressId) {
3136 $sql = "
3137 SELECT display_name from civicrm_contact
3138 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3139 WHERE civicrm_address.id = " . $masterAddressId;
3140 }
3141 elseif ($contactId) {
3142 $sql = "
3143 SELECT display_name from civicrm_contact cc, civicrm_address add1
3144 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3145 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3146 }
3147
3148 $masterDisplayName = CRM_Core_DAO::singleValueQuery($sql);
3149 return $masterDisplayName;
3150 }
3151
3152 /**
3153 * Get the creation/modification times for a contact.
3154 *
3155 * @param int $contactId
3156 *
3157 * @return array
3158 * Dates - ('created_date' => $, 'modified_date' => $)
3159 */
3160 public static function getTimestamps($contactId) {
3161 $timestamps = CRM_Core_DAO::executeQuery(
3162 'SELECT created_date, modified_date
3163 FROM civicrm_contact
3164 WHERE id = %1',
3165 array(
3166 1 => array($contactId, 'Integer'),
3167 )
3168 );
3169 if ($timestamps->fetch()) {
3170 return array(
3171 'created_date' => $timestamps->created_date,
3172 'modified_date' => $timestamps->modified_date,
3173 );
3174 }
3175 else {
3176 return NULL;
3177 }
3178 }
3179
3180 /**
3181 * Generate triggers to update the timestamp.
3182 *
3183 * The corresponding civicrm_contact row is updated on insert/update/delete
3184 * to a table that extends civicrm_contact.
3185 * Don't regenerate triggers for all such tables if only asked for one table.
3186 *
3187 * @param array $info
3188 * Reference to the array where generated trigger information is being stored
3189 * @param string|null $reqTableName
3190 * Name of the table for which triggers are being generated, or NULL if all tables
3191 * @param array $relatedTableNames
3192 * Array of all core or all custom table names extending civicrm_contact
3193 * @param string $contactRefColumn
3194 * 'contact_id' if processing core tables, 'entity_id' if processing custom tables
3195 *
3196 * @link https://issues.civicrm.org/jira/browse/CRM-15602
3197 * @see triggerInfo
3198 */
3199 public static function generateTimestampTriggers(&$info, $reqTableName, $relatedTableNames, $contactRefColumn) {
3200 // Safety
3201 $contactRefColumn = CRM_Core_DAO::escapeString($contactRefColumn);
3202 // If specific related table requested, just process that one
3203 if (in_array($reqTableName, $relatedTableNames)) {
3204 $relatedTableNames = array($reqTableName);
3205 }
3206
3207 // If no specific table requested (include all related tables),
3208 // or a specific related table requested (as matched above)
3209 if (empty($reqTableName) || in_array($reqTableName, $relatedTableNames)) {
3210 $info[] = array(
3211 'table' => $relatedTableNames,
3212 'when' => 'AFTER',
3213 'event' => array('INSERT', 'UPDATE'),
3214 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.$contactRefColumn;\n",
3215 );
3216 $info[] = array(
3217 'table' => $relatedTableNames,
3218 'when' => 'AFTER',
3219 'event' => array('DELETE'),
3220 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.$contactRefColumn;\n",
3221 );
3222 }
3223 }
3224
3225 /**
3226 * Get a list of triggers for the contact table.
3227 *
3228 * @see hook_civicrm_triggerInfo
3229 * @see CRM_Core_DAO::triggerRebuild
3230 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3231 *
3232 * @param $info
3233 * @param null $tableName
3234 */
3235 public static function triggerInfo(&$info, $tableName = NULL) {
3236 //during upgrade, first check for valid version and then create triggers
3237 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3238 if (CRM_Core_Config::isUpgradeMode()) {
3239 $currentVer = CRM_Core_BAO_Domain::version(TRUE);
3240 //if current version is less than 4.3.alpha1 dont create below triggers
3241 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3242 return;
3243 }
3244 }
3245
3246 // Update timestamp for civicrm_contact itself
3247 if ($tableName == NULL || $tableName == self::getTableName()) {
3248 $info[] = array(
3249 'table' => array(self::getTableName()),
3250 'when' => 'BEFORE',
3251 'event' => array('INSERT'),
3252 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3253 );
3254 }
3255
3256 // Update timestamp when modifying closely related core tables
3257 $relatedTables = array(
3258 'civicrm_address',
3259 'civicrm_email',
3260 'civicrm_im',
3261 'civicrm_phone',
3262 'civicrm_website',
3263 );
3264 self::generateTimestampTriggers($info, $tableName, $relatedTables, 'contact_id');
3265
3266 // Update timestamp when modifying related custom-data tables
3267 $customGroupTables = array();
3268 $customGroupDAO = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
3269 $customGroupDAO->is_multiple = 0;
3270 $customGroupDAO->find();
3271 while ($customGroupDAO->fetch()) {
3272 $customGroupTables[] = $customGroupDAO->table_name;
3273 }
3274 if (!empty($customGroupTables)) {
3275 self::generateTimestampTriggers($info, $tableName, $customGroupTables, 'entity_id');
3276 }
3277
3278 // Update phone table to populate phone_numeric field
3279 if (!$tableName || $tableName == 'civicrm_phone') {
3280 // Define stored sql function needed for phones
3281 $sqlTriggers = Civi::service('sql_triggers');
3282 $sqlTriggers->enqueueQuery(self::DROP_STRIP_FUNCTION_43);
3283 $sqlTriggers->enqueueQuery(self::CREATE_STRIP_FUNCTION_43);
3284 $info[] = array(
3285 'table' => array('civicrm_phone'),
3286 'when' => 'BEFORE',
3287 'event' => array('INSERT', 'UPDATE'),
3288 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3289 );
3290 }
3291 }
3292
3293 /**
3294 * Check if contact is being used in civicrm_domain based on $contactId.
3295 *
3296 * @param int $contactId
3297 * Contact id.
3298 *
3299 * @return bool
3300 * true if present else false.
3301 */
3302 public static function checkDomainContact($contactId) {
3303 if (!$contactId) {
3304 return FALSE;
3305 }
3306 $domainId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3307
3308 if ($domainId) {
3309 return TRUE;
3310 }
3311 else {
3312 return FALSE;
3313 }
3314 }
3315
3316 /**
3317 * Get options for a given contact field.
3318 *
3319 * @see CRM_Core_DAO::buildOptions
3320 *
3321 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3322 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3323 *
3324 * @param string $fieldName
3325 * @param string $context
3326 * @see CRM_Core_DAO::buildOptionsContext
3327 * @param array $props
3328 * whatever is known about this dao object.
3329 *
3330 * @return array|bool
3331 */
3332 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3333 $params = array();
3334 // Special logic for fields whose options depend on context or properties
3335 switch ($fieldName) {
3336 case 'contact_sub_type':
3337 if (!empty($props['contact_type'])) {
3338 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3339 }
3340 break;
3341
3342 case 'contact_type':
3343 if ($context == 'search') {
3344 // CRM-15495 - EntityRef filters and basic search forms expect this format
3345 // FIXME: Search builder does not
3346 return CRM_Contact_BAO_ContactType::getSelectElements();
3347 }
3348 break;
3349
3350 // The contact api supports some related entities so we'll honor that by fetching their options
3351 case 'group_id':
3352 case 'group':
3353 return CRM_Contact_BAO_GroupContact::buildOptions('group_id', $context, $props);
3354
3355 case 'tag_id':
3356 case 'tag':
3357 $props['entity_table'] = 'civicrm_contact';
3358 return CRM_Core_BAO_EntityTag::buildOptions('tag_id', $context, $props);
3359
3360 case 'state_province_id':
3361 case 'state_province':
3362 case 'state_province_name':
3363 case 'country_id':
3364 case 'country':
3365 case 'county_id':
3366 case 'worldregion':
3367 case 'worldregion_id':
3368 return CRM_Core_BAO_Address::buildOptions($fieldName, 'get', $props);
3369
3370 }
3371 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
3372 }
3373
3374 /**
3375 * Delete a contact-related object that has an 'is_primary' field.
3376 *
3377 * Ensures that is_primary gets assigned to another object if available
3378 * Also calls pre/post hooks
3379 *
3380 * @var object $type
3381 * @var int $id
3382 * @return bool
3383 */
3384 public static function deleteObjectWithPrimary($type, $id) {
3385 if (!$id || !is_numeric($id)) {
3386 return FALSE;
3387 }
3388 $daoName = "CRM_Core_DAO_$type";
3389 $obj = new $daoName();
3390 $obj->id = $id;
3391 $obj->find();
3392 if ($obj->fetch()) {
3393 CRM_Utils_Hook::pre('delete', $type, $id, CRM_Core_DAO::$_nullArray);
3394 $contactId = $obj->contact_id;
3395 $obj->delete();
3396 }
3397 else {
3398 return FALSE;
3399 }
3400 // is_primary is only relavent if this field belongs to a contact
3401 if ($contactId) {
3402 $dao = new $daoName();
3403 $dao->contact_id = $contactId;
3404 $dao->is_primary = 1;
3405 // Pick another record to be primary (if one isn't already)
3406 if (!$dao->find(TRUE)) {
3407 $dao->is_primary = 0;
3408 $dao->find();
3409 if ($dao->fetch()) {
3410 $dao->is_primary = 1;
3411 $dao->save();
3412 }
3413 }
3414 $dao->free();
3415 }
3416 CRM_Utils_Hook::post('delete', $type, $id, $obj);
3417 $obj->free();
3418 return TRUE;
3419 }
3420
3421 /**
3422 * @inheritDoc
3423 */
3424 public function addSelectWhereClause() {
3425 // We always return an array with these keys, even if they are empty,
3426 // because this tells the query builder that we have considered these fields for acls
3427 $clauses = array(
3428 'id' => (array) CRM_Contact_BAO_Contact_Permission::cacheSubquery(),
3429 'is_deleted' => CRM_Core_Permission::check('access deleted contacts') ? array() : array('!= 1'),
3430 );
3431 CRM_Utils_Hook::selectWhereClause($this, $clauses);
3432 return $clauses;
3433 }
3434
3435 }