Merge pull request #11300 from eileenmcnaughton/towards1
[civicrm-core.git] / CRM / Contact / BAO / Contact.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33class 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 /**
fe482240 61 * The types of communication preferences.
6a488035
TO
62 *
63 * @var array
64 */
22f80e87
EM
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 );
6a488035
TO
72
73 /**
fe482240 74 * Types of greetings.
6a488035
TO
75 *
76 * @var array
77 */
22f80e87
EM
78 static $_greetingTypes = array(
79 'addressee',
80 'email_greeting',
81 'postal_greeting',
82 );
6a488035
TO
83
84 /**
fe482240 85 * Static field for all the contact information that we can potentially import.
6a488035
TO
86 *
87 * @var array
6a488035
TO
88 */
89 static $_importableFields = array();
90
91 /**
fe482240 92 * Static field for all the contact information that we can potentially export.
6a488035
TO
93 *
94 * @var array
6a488035
TO
95 */
96 static $_exportableFields = NULL;
86538308
EM
97
98 /**
22f80e87 99 * Class constructor.
86538308 100 */
00be9182 101 public function __construct() {
6a488035
TO
102 parent::__construct();
103 }
104
105 /**
22f80e87 106 * Takes an associative array and creates a contact object.
6a488035 107 *
22f80e87 108 * The function extracts all the params it needs to initialize the create a
6a488035
TO
109 * contact object. the params array could contain additional unused name/value
110 * pairs
111 *
77c5b619 112 * @param array $params
22f80e87 113 * (reference) an assoc array of name/value pairs.
6a488035 114 *
a1a2a83d 115 * @return CRM_Contact_BAO_Contact|CRM_Core_Error|NULL
22f80e87
EM
116 * Created or updated contact object or error object.
117 * (error objects are being phased out in favour of exceptions)
6a488035 118 */
00be9182 119 public static function add(&$params) {
6a488035
TO
120 $contact = new CRM_Contact_DAO_Contact();
121
122 if (empty($params)) {
a1a2a83d 123 return NULL;
6a488035
TO
124 }
125
22f80e87 126 // Fix for validate contact sub type CRM-5143.
9bb77b8e
TO
127 if (isset($params['contact_sub_type'])) {
128 if (empty($params['contact_sub_type'])) {
6a488035
TO
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
9bb77b8e
TO
134 )
135 ) {
6a488035
TO
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 }
f2181617 140 $params['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
6a488035
TO
141 }
142 }
143 else {
22f80e87
EM
144 // Reset the value.
145 // CRM-101XX.
6a488035
TO
146 $params['contact_sub_type'] = 'null';
147 }
148
22f80e87 149 // Fixed contact source.
6a488035
TO
150 if (isset($params['contact_source'])) {
151 $params['source'] = $params['contact_source'];
152 }
153
37f7ae88 154 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
155 CRM_Utils_Array::formatArrayKeys($params['preferred_communication_method']);
156 $contact->preferred_communication_method = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
6a488035 157 unset($params['preferred_communication_method']);
6a488035
TO
158 }
159
160 $allNull = $contact->copyValues($params);
161
162 $contact->id = CRM_Utils_Array::value('contact_id', $params);
163
164 if ($contact->contact_type == 'Individual') {
165 $allNull = FALSE;
166
22f80e87 167 // Format individual fields.
6a488035
TO
168 CRM_Contact_BAO_Individual::format($params, $contact);
169 }
170 elseif ($contact->contact_type == 'Household') {
171 if (isset($params['household_name'])) {
172 $allNull = FALSE;
173 $contact->display_name = $contact->sort_name = CRM_Utils_Array::value('household_name', $params, '');
174 }
175 }
176 elseif ($contact->contact_type == 'Organization') {
177 if (isset($params['organization_name'])) {
178 $allNull = FALSE;
179 $contact->display_name = $contact->sort_name = CRM_Utils_Array::value('organization_name', $params, '');
180 }
181 }
3628dc86 182 if (strlen($contact->display_name) > 128) {
183 $contact->display_name = substr($contact->display_name, 0, 128);
184 }
185 if (strlen($contact->sort_name) > 128) {
186 $contact->sort_name = substr($contact->sort_name, 0, 128);
187 }
6a488035 188
6a488035
TO
189 $privacy = CRM_Utils_Array::value('privacy', $params);
190 if ($privacy &&
191 is_array($privacy) &&
192 !empty($privacy)
193 ) {
194 $allNull = FALSE;
195 foreach (self::$_commPrefs as $name) {
196 $contact->$name = CRM_Utils_Array::value($name, $privacy, FALSE);
197 }
198 }
199
22f80e87
EM
200 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
201 // @todo - does this mean we can remove this block?
202 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
6a488035
TO
203 if ((!array_key_exists('hash', $contact) || !$contact->hash) && !$contact->id) {
204 $allNull = FALSE;
205 $contact->hash = md5(uniqid(rand(), TRUE));
206 }
207
208 // Even if we don't need $employerId, it's important to call getFieldValue() before
209 // the contact is saved because we want the existing value to be cached.
210 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
211 $employerId = empty($contact->id) ? NULL : CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contact->id, 'employer_id');
212
213 if (!$allNull) {
214 $contact->save();
215
216 CRM_Core_BAO_Log::register($contact->id,
217 'civicrm_contact',
218 $contact->id
219 );
220 }
221
fad0497c 222 if ($contact->contact_type == 'Individual' && (isset($params['current_employer']) || isset($params['employer_id']))) {
22f80e87 223 // Create current employer.
f06fc7d2 224 $newEmployer = !empty($params['employer_id']) ? $params['employer_id'] : CRM_Utils_Array::value('current_employer', $params);
225
226 $newContact = FALSE;
227 if (empty($params['contact_id'])) {
228 $newContact = TRUE;
6a488035 229 }
fad0497c 230 if ($newEmployer) {
6eae3162 231 CRM_Contact_BAO_Contact_Utils::createCurrentEmployerRelationship($contact->id, $newEmployer, $employerId, $newContact);
6a488035
TO
232 }
233 else {
6a488035
TO
234 if ($employerId) {
235 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($contact->id, $employerId);
236 }
237 }
238 }
239
22f80e87 240 // Update cached employer name.
6a488035
TO
241 if ($contact->contact_type == 'Organization') {
242 CRM_Contact_BAO_Contact_Utils::updateCurrentEmployer($contact->id);
243 }
244
245 return $contact;
246 }
247
248 /**
22f80e87
EM
249 * Create contact.
250 *
6a488035
TO
251 * takes an associative array and creates a contact object and all the associated
252 * derived objects (i.e. individual, location, email, phone etc)
253 *
254 * This function is invoked from within the web form layer and also from the api layer
255 *
77c5b619
TO
256 * @param array $params
257 * (reference ) an assoc array of name/value pairs.
258 * @param bool $fixAddress
259 * If we need to fix address.
260 * @param bool $invokeHooks
261 * If we need to invoke hooks.
6a488035 262 *
60fd90d8
DG
263 * @param bool $skipDelete
264 * Unclear parameter, passed to website create
265 *
22f80e87 266 * @todo explain this parameter
d9f93da9
EM
267 *
268 * @throws Exception
22f80e87
EM
269 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
270 * Created or updated contribution object. We are deprecating returning an error in
271 * favour of exceptions
6a488035 272 */
60fd90d8 273 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
9bb77b8e
TO
274 $contact = NULL;
275 if (empty($params['contact_type']) && empty($params['contact_id'])) {
276 return $contact;
277 }
6a488035 278
9bb77b8e
TO
279 $isEdit = TRUE;
280 if ($invokeHooks) {
281 if (!empty($params['contact_id'])) {
282 CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
283 }
284 else {
285 CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
286 $isEdit = FALSE;
6a488035 287 }
9bb77b8e 288 }
6a488035 289
9bb77b8e 290 $config = CRM_Core_Config::singleton();
6a488035 291
22f80e87 292 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
9bb77b8e 293 if (empty($params['contact_id'])) {
9747df8a 294 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
295 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n::getContactDefaultLanguage()) != FALSE) {
296 $params['preferred_language'] = $language;
297 }
298
299 // CRM-9739: set greeting & addressee if unset and we’re creating a contact.
9bb77b8e
TO
300 foreach (self::$_greetingTypes as $greeting) {
301 if (empty($params[$greeting . '_id'])) {
22f80e87
EM
302 if ($defaultGreetingTypeId
303 = CRM_Contact_BAO_Contact_Utils::defaultGreeting($params['contact_type'], $greeting)
9bb77b8e
TO
304 ) {
305 $params[$greeting . '_id'] = $defaultGreetingTypeId;
6a488035
TO
306 }
307 }
308 }
054bda37
VV
309
310 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
311 if (empty($params['communication_style_id'])) {
d8ccde47
VV
312 $defaultCommunicationStyleId = CRM_Core_OptionGroup::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
313 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
054bda37 314 }
9bb77b8e 315 }
6a488035 316
9bb77b8e 317 $transaction = new CRM_Core_Transaction();
6a488035 318
9bb77b8e
TO
319 $contact = self::add($params);
320 if (!$contact) {
b44e3f84 321 // Not dying here is stupid, since we get into weird situation and into a bug that
9bb77b8e
TO
322 // is impossible to figure out for the user or for us
323 // CRM-7925
324 CRM_Core_Error::fatal();
325 }
6a488035 326
9bb77b8e 327 $params['contact_id'] = $contact->id;
6a488035 328
aaffa79f 329 if (Civi::settings()->get('is_enabled')) {
22f80e87 330 // Enabling multisite causes the contact to be added to the domain group.
9bb77b8e
TO
331 $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
332 if (!empty($domainGroupID)) {
333 if (!empty($params['group']) && is_array($params['group'])) {
334 $params['group'][$domainGroupID] = 1;
6a488035 335 }
9bb77b8e
TO
336 else {
337 $params['group'] = array($domainGroupID => 1);
6a488035
TO
338 }
339 }
9bb77b8e 340 }
6a488035 341
9bb77b8e
TO
342 if (array_key_exists('group', $params)) {
343 $contactIds = array($params['contact_id']);
344 foreach ($params['group'] as $groupId => $flag) {
345 if ($flag == 1) {
346 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
347 }
348 elseif ($flag == -1) {
349 CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $groupId);
350 }
6a488035 351 }
9bb77b8e 352 }
6a488035 353
22f80e87 354 // Add location Block data.
9bb77b8e
TO
355 $blocks = CRM_Core_BAO_Location::create($params, $fixAddress);
356 foreach ($blocks as $name => $value) {
357 $contact->$name = $value;
358 }
139a60f3 359 if (!empty($params['updateBlankLocInfo'])) {
360 $skipDelete = TRUE;
361 }
6a488035 362
60fd90d8
DG
363 //add website
364 CRM_Core_BAO_Website::create($params['website'], $contact->id, $skipDelete);
6a488035 365
ec52a65a 366 $userID = CRM_Core_Session::singleton()->get('userID');
9bb77b8e
TO
367 // add notes
368 if (!empty($params['note'])) {
369 if (is_array($params['note'])) {
370 foreach ($params['note'] as $note) {
6a488035
TO
371 $contactId = $contact->id;
372 if (isset($note['contact_id'])) {
373 $contactId = $note['contact_id'];
374 }
375 //if logged in user, overwrite contactId
376 if ($userID) {
377 $contactId = $userID;
378 }
379
380 $noteParams = array(
381 'entity_id' => $contact->id,
382 'entity_table' => 'civicrm_contact',
9bb77b8e
TO
383 'note' => $note['note'],
384 'subject' => CRM_Utils_Array::value('subject', $note),
6a488035
TO
385 'contact_id' => $contactId,
386 );
387 CRM_Core_BAO_Note::add($noteParams, CRM_Core_DAO::$_nullArray);
388 }
389 }
9bb77b8e
TO
390 else {
391 $contactId = $contact->id;
392 if (isset($note['contact_id'])) {
393 $contactId = $note['contact_id'];
394 }
395 //if logged in user, overwrite contactId
396 if ($userID) {
397 $contactId = $userID;
398 }
6a488035 399
9bb77b8e
TO
400 $noteParams = array(
401 'entity_id' => $contact->id,
402 'entity_table' => 'civicrm_contact',
403 'note' => $params['note'],
404 'subject' => CRM_Utils_Array::value('subject', $params),
405 'contact_id' => $contactId,
6a488035 406 );
9bb77b8e 407 CRM_Core_BAO_Note::add($noteParams, CRM_Core_DAO::$_nullArray);
6a488035 408 }
9bb77b8e 409 }
6a488035 410
9bb77b8e
TO
411 // update the UF user_unique_id if that has changed
412 CRM_Core_BAO_UFMatch::updateUFName($contact->id);
413
414 if (!empty($params['custom']) &&
415 is_array($params['custom'])
416 ) {
417 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contact', $contact->id);
418 }
419
420 // make a civicrm_subscription_history entry only on contact create (CRM-777)
421 if (empty($params['contact_id'])) {
422 $subscriptionParams = array(
423 'contact_id' => $contact->id,
424 'status' => 'Added',
425 'method' => 'Admin',
6a488035 426 );
9bb77b8e
TO
427 CRM_Contact_BAO_SubscriptionHistory::create($subscriptionParams);
428 }
6a488035 429
9bb77b8e 430 $transaction->commit();
6a488035 431
9bb77b8e
TO
432 // CRM-6367: fetch the right label for contact type’s display
433 $contact->contact_type_display = CRM_Core_DAO::getFieldValue(
434 'CRM_Contact_DAO_ContactType',
435 $contact->contact_type,
436 'label',
437 'name'
438 );
439
0626851e 440 CRM_Contact_BAO_Contact_Utils::clearContactCaches();
9bb77b8e
TO
441
442 if ($invokeHooks) {
443 if ($isEdit) {
444 CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
445 }
446 else {
447 CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
6a488035 448 }
9bb77b8e 449 }
6a488035 450
9bb77b8e
TO
451 // process greetings CRM-4575, cache greetings
452 self::processGreetings($contact);
6a488035 453
9bb77b8e 454 return $contact;
6a488035
TO
455 }
456
457 /**
22f80e87 458 * Get the display name and image of a contact.
6a488035 459 *
77c5b619
TO
460 * @param int $id
461 * The contactId.
6a488035 462 *
22f80e87
EM
463 * @param bool $includeTypeInReturnParameters
464 * Should type be part of the returned array?
d9f93da9 465 *
a6c01b45
CW
466 * @return array
467 * the displayName and contactImage for this contact
6a488035 468 */
22f80e87 469 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
95fec3ce 470 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
250b3b1f 471 $sql = "
95fec3ce 472SELECT civicrm_contact.*,
6a488035
TO
473 civicrm_email.email as email
474FROM civicrm_contact
475LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
476 AND civicrm_email.is_primary = 1
477WHERE civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
478 $dao = new CRM_Core_DAO();
479 $dao->query($sql);
480 if ($dao->fetch()) {
481 $image = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
250b3b1f 482 $dao->contact_sub_type : $dao->contact_type, FALSE, $id
6a488035
TO
483 );
484 $imageUrl = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
250b3b1f 485 $dao->contact_sub_type : $dao->contact_type, TRUE, $id
6a488035
TO
486 );
487
488 // use email if display_name is empty
489 if (empty($dao->display_name)) {
250b3b1f 490 $displayName = $dao->email;
491 }
492 else {
493 $displayName = $dao->display_name;
494 }
495
496 CRM_Utils_Hook::alterDisplayName($displayName, $id, $dao);
95fec3ce 497
22f80e87 498 return $includeTypeInReturnParameters ? array(
967fddb5 499 $displayName,
250b3b1f 500 $image,
501 $dao->contact_type,
502 $dao->contact_sub_type,
503 $imageUrl,
967fddb5 504 ) : array($displayName, $image, $imageUrl);
6a488035
TO
505 }
506 return NULL;
507 }
508
870156d6 509 /**
510 * Add billing fields to the params if appropriate.
511 *
512 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
513 * don't then we should set the name fields to the filling fields AND add the preserveDBName
514 * parameter (which will tell the BAO only to set those fields if none already exist.
515 *
516 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
517 * matching is best done by hipsters.
518 *
519 * @param array $params
520 */
521 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
afa4787b 522 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
870156d6 523 foreach ($nameFields as $field) {
524 if (!empty($params[$field])) {
525 return;
526 }
527 }
528 // There are only 3 - we can iterate through them twice :-)
529 foreach ($nameFields as $field) {
530 if (!empty($params['billing_' . $field])) {
531 $params[$field] = $params['billing_' . $field];
532 }
533 $params['preserveDBName'] = TRUE;
534 }
535
536 }
537
688ad538 538 /**
22f80e87
EM
539 * Create last viewed link to recently updated contact.
540 *
77c5b619 541 * @param array $crudLinkSpec
55d2c6f1
EM
542 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
543 * - entity_table: string, eg "civicrm_contact"
544 * - entity_id: int
545 *
72b3a70c 546 * @return array|NULL
16b10e64
CW
547 * NULL if unavailable, or
548 * [path: string, query: string, title: string]
688ad538
TO
549 * @see CRM_Utils_System::createDefaultCrudLink
550 */
551 public function createDefaultCrudLink($crudLinkSpec) {
552 switch ($crudLinkSpec['action']) {
553 case CRM_Core_Action::VIEW:
6c552737 554 $result = array(
688ad538
TO
555 'title' => $this->display_name,
556 'path' => 'civicrm/contact/view',
557 'query' => array(
558 'reset' => 1,
559 'cid' => $this->id,
560 ),
561 );
6c552737 562 return $result;
ea100cb5 563
688ad538 564 case CRM_Core_Action::UPDATE:
6c552737 565 $result = array(
688ad538
TO
566 'title' => $this->display_name,
567 'path' => 'civicrm/contact/add',
568 'query' => array(
569 'reset' => 1,
570 'action' => 'update',
571 'cid' => $this->id,
572 ),
573 );
6c552737 574 return $result;
688ad538
TO
575 }
576 return NULL;
577 }
578
6a488035 579 /**
6a488035
TO
580 * Get the values for pseudoconstants for name->value and reverse.
581 *
77c5b619
TO
582 * @param array $defaults
583 * (reference) the default values, some of which need to be resolved.
584 * @param bool $reverse
585 * True if we want to resolve the values in the reverse direction (value -> name).
6a488035 586 */
00be9182 587 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
22f80e87 588 // Hack for birth_date.
a7488080 589 if (!empty($defaults['birth_date'])) {
6a488035
TO
590 if (is_array($defaults['birth_date'])) {
591 $defaults['birth_date'] = CRM_Utils_Date::format($defaults['birth_date'], '-');
592 }
593 }
594
e6c4755b
CW
595 CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
596 CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
26cf88b5 597 CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
aa62b355 598 CRM_Utils_Array::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
6a488035
TO
599
600 //lookup value of email/postal greeting, addressee, CRM-4575
601 foreach (self::$_greetingTypes as $greeting) {
9bb77b8e
TO
602 $filterCondition = array(
603 'contact_type' => CRM_Utils_Array::value('contact_type', $defaults),
6a488035
TO
604 'greeting_type' => $greeting,
605 );
606 CRM_Utils_Array::lookupValue($defaults, $greeting,
607 CRM_Core_PseudoConstant::greeting($filterCondition), $reverse
608 );
609 }
610
611 $blocks = array('address', 'im', 'phone');
612 foreach ($blocks as $name) {
613 if (!array_key_exists($name, $defaults) || !is_array($defaults[$name])) {
614 continue;
615 }
616 foreach ($defaults[$name] as $count => & $values) {
617
618 //get location type id.
b2b0530a 619 CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
6a488035
TO
620
621 if ($name == 'address') {
622 // FIXME: lookupValue doesn't work for vcard_name
a7488080 623 if (!empty($values['location_type_id'])) {
8f785c9e 624 $vcardNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
6a488035
TO
625 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
626 }
627
628 if (!CRM_Utils_Array::lookupValue($values,
629 'country',
630 CRM_Core_PseudoConstant::country(),
631 $reverse
632 ) &&
633 $reverse
634 ) {
635 CRM_Utils_Array::lookupValue($values,
636 'country',
637 CRM_Core_PseudoConstant::countryIsoCode(),
638 $reverse
639 );
640 }
641
642 // CRM-7597
643 // if we find a country id above, we need to restrict it to that country
644 // rather than the list of all countries
645
646 if (!empty($values['country_id'])) {
647 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($values['country_id']);
648 }
649 else {
650 $stateProvinceList = CRM_Core_PseudoConstant::stateProvince();
651 }
652 if (!CRM_Utils_Array::lookupValue($values,
653 'state_province',
654 $stateProvinceList,
655 $reverse
656 ) &&
657 $reverse
658 ) {
659
660 if (!empty($values['country_id'])) {
661 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($values['country_id'], 'abbreviation');
662 }
663 else {
664 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
665 }
666 CRM_Utils_Array::lookupValue($values,
667 'state_province',
668 $stateProvinceList,
669 $reverse
670 );
671 }
672
673 if (!empty($values['state_province_id'])) {
674 $countyList = CRM_Core_PseudoConstant::countyForState($values['state_province_id']);
675 }
676 else {
677 $countyList = CRM_Core_PseudoConstant::county();
678 }
679 CRM_Utils_Array::lookupValue($values,
680 'county',
681 $countyList,
682 $reverse
683 );
684 }
685
686 if ($name == 'im') {
687 CRM_Utils_Array::lookupValue($values,
688 'provider',
e7e657f0 689 CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
6a488035
TO
690 $reverse
691 );
692 }
693
694 if ($name == 'phone') {
695 CRM_Utils_Array::lookupValue($values,
696 'phone_type',
b4f964d9 697 CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
6a488035
TO
698 $reverse
699 );
700 }
701
22f80e87 702 // Kill the reference.
6a488035
TO
703 unset($values);
704 }
705 }
706 }
707
708 /**
0965e988 709 * Fetch object based on array of properties.
6a488035 710 *
77c5b619
TO
711 * @param array $params
712 * (reference ) an assoc array of name/value pairs.
713 * @param array $defaults
714 * (reference ) an assoc array to hold the name / value pairs.
6a488035 715 * in a hierarchical manner
77c5b619
TO
716 * @param bool $microformat
717 * For location in microformat.
6a488035 718 *
16b10e64 719 * @return CRM_Contact_BAO_Contact
6a488035 720 */
00be9182 721 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
6a488035
TO
722 if (array_key_exists('contact_id', $params)) {
723 $params['id'] = $params['contact_id'];
724 }
725 elseif (array_key_exists('id', $params)) {
726 $params['contact_id'] = $params['id'];
727 }
728
729 $contact = self::getValues($params, $defaults);
730
731 unset($params['id']);
732
733 //get the block information for this contact
734 $entityBlock = array('contact_id' => $params['contact_id']);
9bb77b8e
TO
735 $blocks = CRM_Core_BAO_Location::getValues($entityBlock, $microformat);
736 $defaults = array_merge($defaults, $blocks);
737 foreach ($blocks as $block => $value) {
738 $contact->$block = $value;
739 }
6a488035
TO
740
741 if (!isset($params['noNotes'])) {
742 $contact->notes = CRM_Core_BAO_Note::getValues($params, $defaults);
743 }
744
745 if (!isset($params['noRelationships'])) {
746 $contact->relationship = CRM_Contact_BAO_Relationship::getValues($params, $defaults);
747 }
748
749 if (!isset($params['noGroups'])) {
750 $contact->groupContact = CRM_Contact_BAO_GroupContact::getValues($params, $defaults);
751 }
752
753 if (!isset($params['noWebsite'])) {
754 $contact->website = CRM_Core_BAO_Website::getValues($params, $defaults);
755 }
756
757 return $contact;
758 }
759
760 /**
0965e988 761 * Get the display name of a contact.
6a488035 762 *
77c5b619
TO
763 * @param int $id
764 * Id of the contact.
6a488035 765 *
72b3a70c
CW
766 * @return null|string
767 * display name of the contact if found
6a488035 768 */
00be9182 769 public static function displayName($id) {
6a488035
TO
770 $displayName = NULL;
771 if ($id) {
772 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
773 }
774
775 return $displayName;
776 }
777
778 /**
55d2c6f1 779 * Delete a contact and all its associated records.
6a488035 780 *
77c5b619
TO
781 * @param int $id
782 * Id of the contact to delete.
783 * @param bool $restore
784 * Whether to actually restore, not delete.
785 * @param bool $skipUndelete
786 * Whether to force contact delete or not.
dbb0d30b 787 * @param bool $checkPermissions
6a488035 788 *
55d2c6f1
EM
789 * @return bool
790 * Was contact deleted?
6a488035 791 */
fa6448fa 792 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
6a488035
TO
793
794 if (!$id) {
795 return FALSE;
796 }
b0033001 797 // If trash is disabled in system settings then we always skip
89595c92 798 if (!Civi::settings()->get('contact_undelete')) {
b0033001
CW
799 $skipUndelete = TRUE;
800 }
6a488035
TO
801
802 // make sure we have edit permission for this contact
803 // before we delete
fa6448fa
EM
804 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission::check('delete contacts')) ||
805 ($restore && !CRM_Core_Permission::check('access deleted contacts')))
6a488035
TO
806 ) {
807 return FALSE;
808 }
2efcf0c2 809
f182074e
PN
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 }
6a488035
TO
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;
6a488035 834 // currently we only clear employer cache.
690c56c3 835 // we are now deleting inherited membership if any.
6a488035 836 if ($contact->contact_type == 'Organization') {
690c56c3 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 }
6a488035
TO
844 CRM_Contact_BAO_Contact_Utils::clearAllEmployee($id);
845 }
846
690c56c3 847 if ($restore) {
848 return self::contactTrashRestore($contact, TRUE);
849 }
850
6a488035
TO
851 // start a new transaction
852 $transaction = new CRM_Core_Transaction();
853
b0033001
CW
854 if ($skipUndelete) {
855 CRM_Utils_Hook::pre('delete', $contactType, $id, CRM_Core_DAO::$_nullArray);
6a488035
TO
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();
1071730c 865
c3d24ba7
PN
866 // delete contact participants CRM-12155
867 CRM_Event_BAO_Participant::deleteContactParticipant($id);
6a488035 868
c3d24ba7
PN
869 // delete contact contributions CRM-12155
870 CRM_Contribute_BAO_Contribution::deleteContactContribution($id);
1071730c 871
6a488035
TO
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
55033e60
PJ
878 // delete cases related to contact
879 $contactCases = CRM_Case_BAO_Case::retrieveCaseIdsByContactId($id);
880 if (!empty($contactCases)) {
d3b60a94 881 foreach ($contactCases as $caseId) {
55033e60
PJ
882 //check if case is associate with other contact or not.
883 $caseContactId = CRM_Case_BAO_Case::getCaseClients($caseId);
d3b60a94 884 if (count($caseContactId) <= 1) {
55033e60
PJ
885 CRM_Case_BAO_Case::deleteCase($caseId);
886 }
887 }
888 }
889
6a488035
TO
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);
ae44c3b9 898 self::updateContactCache($id, empty($restore));
6a488035
TO
899
900 // delete any dupe cache entry
901 CRM_Core_BAO_PrevNextCache::deleteItem($id);
902
903 $transaction->commit();
904
b0033001
CW
905 if ($skipUndelete) {
906 CRM_Utils_Hook::post('delete', $contactType, $contact->id, $contact);
907 }
6a488035
TO
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
ae44c3b9 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 {
2b68a50c 938 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
ae44c3b9 939 }
940 }
941
6a488035 942 /**
55d2c6f1 943 * Delete the image of a contact.
6a488035 944 *
77c5b619
TO
945 * @param int $id
946 * Id of the contact.
6a488035 947 *
55d2c6f1
EM
948 * @return bool
949 * Was contact image deleted?
6a488035
TO
950 */
951 public static function deleteContactImage($id) {
952 if (!$id) {
953 return FALSE;
954 }
955 $query = "
956UPDATE civicrm_contact
957SET image_URL=NULL
958WHERE id={$id}; ";
33621c4f 959 CRM_Core_DAO::executeQuery($query);
6a488035
TO
960 return TRUE;
961 }
962
6a488035 963 /**
0965e988 964 * Return proportional height and width of the image.
6a488035 965 *
df8d3074 966 * @param int $imageWidth
77c5b619 967 * Width of image.
6a488035 968 *
df8d3074 969 * @param int $imageHeight
77c5b619 970 * Height of image.
6a488035 971 *
0965e988
EM
972 * @return array
973 * Thumb dimension of image
6a488035
TO
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 /**
0965e988 996 * Validate type of contact image.
6a488035 997 *
c490a46a 998 * @param array $params
d3e86119 999 * @param string $imageIndex
77c5b619 1000 * Index of image field.
d3e86119 1001 * @param string $statusMsg
77c5b619
TO
1002 * Status message to be set after operation.
1003 * @param string $opType
1004 * Type of operation like fatal, bounce etc.
6a488035 1005 *
0965e988 1006 * @return bool
a6c01b45 1007 * true if valid image extension
6a488035 1008 */
9bb77b8e
TO
1009 public static function processImageParams(
1010 &$params,
6a488035 1011 $imageIndex = 'image_URL',
9bb77b8e
TO
1012 $statusMsg = NULL,
1013 $opType = 'status'
6a488035
TO
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)) {
5da97e99 1026 $photo = basename($params[$imageIndex]['name']);
9bb77b8e 1027 $params[$imageIndex] = CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
6a488035
TO
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 /**
0965e988 1044 * Extract contact id from url for deleting contact image.
6a488035
TO
1045 */
1046 public static function processImage() {
1047
1050d25c
CW
1048 $action = CRM_Utils_Request::retrieve('action', 'String');
1049 $cid = CRM_Utils_Request::retrieve('cid', 'Positive');
6a488035 1050 // retrieve contact id in case of Profile context
1050d25c 1051 $id = CRM_Utils_Request::retrieve('id', 'Positive');
6a488035
TO
1052 $cid = $cid ? $cid : $id;
1053 if ($action & CRM_Core_Action::DELETE) {
1050d25c 1054 if (CRM_Utils_Request::retrieve('confirmed', 'Boolean')) {
6a488035
TO
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 /**
0965e988 1065 * Function to set is_delete true or restore deleted contact.
6a488035 1066 *
b0033001 1067 * @param CRM_Contact_DAO_Contact $contact
d3e86119
TO
1068 * Contact DAO object.
1069 * @param bool $restore
1070 * True to set the is_delete = 1 else false to restore deleted contact,
b0033001
CW
1071 * i.e. is_delete = 0
1072 *
1073 * @return bool
6a488035 1074 */
00be9182 1075 public static function contactTrashRestore($contact, $restore = FALSE) {
b0033001
CW
1076 $updateParams = array(
1077 'id' => $contact->id,
1078 'is_deleted' => $restore ? 0 : 1,
1079 );
6a488035 1080
b0033001 1081 CRM_Utils_Hook::pre('update', $contact->contact_type, $contact->id, $updateParams);
6a488035
TO
1082
1083 $params = array(1 => array($contact->id, 'Integer'));
b0033001 1084 if (!$restore) {
6a488035
TO
1085 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1086 CRM_Core_DAO::executeQuery($query, $params);
1087 }
1088
b0033001
CW
1089 $contact->copyValues($updateParams);
1090 $contact->save();
1091
1092 CRM_Utils_Hook::post('update', $contact->contact_type, $contact->id, $contact);
6a488035 1093
b0033001 1094 return TRUE;
6a488035
TO
1095 }
1096
1097 /**
1098 * Get contact type for a contact.
1099 *
77c5b619
TO
1100 * @param int $id
1101 * Id of the contact whose contact type is needed.
6a488035 1102 *
a6c01b45
CW
1103 * @return string
1104 * contact_type if $id found else null ""
6a488035
TO
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 *
77c5b619
TO
1113 * @param int $id
1114 * Id of the contact whose contact sub type is needed.
6a488035 1115 *
364c80f1 1116 * @param string $implodeDelimiter
dd244018 1117 *
a6c01b45
CW
1118 * @return string
1119 * contact_sub_type if $id found else null ""
6a488035
TO
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
f2181617 1127 $subtype = CRM_Utils_Array::explodePadded($subtype);
6a488035
TO
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 *
77c5b619
TO
1138 * @param int $id
1139 * Id of the contact whose contact sub/contact type is needed.
6a488035
TO
1140 *
1141 * @return array
6a488035
TO
1142 */
1143 public static function getContactTypes($id) {
9bb77b8e 1144 $params = array('id' => $id);
6a488035
TO
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();
0965e988 1154 if ($contact->contact_sub_type) {
f2181617 1155 $contactTypes = CRM_Utils_Array::explodePadded($contact->contact_sub_type);
0965e988 1156 }
6a488035
TO
1157 array_unshift($contactTypes, $contact->contact_type);
1158
1159 return $contactTypes;
1160 }
1161 else {
1162 CRM_Core_Error::fatal();
1163 }
1164 }
1165
1166 /**
0965e988 1167 * Combine all the importable fields from the lower levels object.
6a488035
TO
1168 *
1169 * The ordering is important, since currently we do not have a weight
1071730c 1170 * scheme. Adding weight is super important
6a488035 1171 *
dd244018 1172 * @param int|string $contactType contact Type
77c5b619
TO
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).
6a488035 1181 *
dd244018
EM
1182 * @param bool $withMultiCustomFields
1183 *
a6c01b45
CW
1184 * @return array
1185 * array of importable Fields
6a488035 1186 */
5c9ff055 1187 public static function importableFields(
9bb77b8e
TO
1188 $contactType = 'Individual',
1189 $status = FALSE,
1190 $showAll = FALSE,
1191 $isProfile = FALSE,
6a488035
TO
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(
9bb77b8e
TO
1217 'Individual',
1218 'Household',
1219 'Organization',
21dfd5f5 1220 'All',
9bb77b8e 1221 ))) {
6a488035
TO
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
1071730c
DL
1247 $fields = array_merge($fields, CRM_Contact_DAO_Contact::import());
1248 $fields = array_merge($fields, CRM_Core_DAO_Note::import());
6a488035
TO
1249
1250 //website fields
1251 $fields = array_merge($fields, CRM_Core_DAO_Website::import());
887e764d 1252 $fields['url']['hasWebsiteType'] = TRUE;
6a488035
TO
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(
8c77c68b
KJ
1267 'Individual' => array(
1268 'household_name',
1269 'legal_name',
1270 'sic_code',
21dfd5f5 1271 'organization_name',
8c77c68b 1272 ),
6a488035 1273 'Household' => array(
8c77c68b
KJ
1274 'first_name',
1275 'middle_name',
1276 'last_name',
e171748b 1277 'formal_title',
8c77c68b 1278 'job_title',
04ffef8d
CW
1279 'gender_id',
1280 'prefix_id',
1281 'suffix_id',
8c77c68b
KJ
1282 'birth_date',
1283 'organization_name',
1284 'legal_name',
1285 'legal_identifier',
1286 'sic_code',
1287 'home_URL',
1288 'is_deceased',
6a488035
TO
1289 'deceased_date',
1290 ),
1291 'Organization' => array(
8c77c68b
KJ
1292 'first_name',
1293 'middle_name',
1294 'last_name',
e171748b 1295 'formal_title',
8c77c68b 1296 'job_title',
04ffef8d
CW
1297 'gender_id',
1298 'prefix_id',
1299 'suffix_id',
8c77c68b
KJ
1300 'birth_date',
1301 'household_name',
1302 'is_deceased',
1303 'deceased_date',
6a488035
TO
1304 ),
1305 );
1306 foreach ($commonValues[$contactType] as $value) {
1307 unset($fields[$value]);
1308 }
1309 }
1310 else {
9bb77b8e 1311 foreach (array('Individual', 'Household', 'Organization') as $type) {
6a488035
TO
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) {
8c77c68b
KJ
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 ),
d4dcd180 1338 'communication_style_id' => array(
1339 'title' => ts('Communication Style'),
1340 'name' => 'communication_style_id',
1341 ),
8c77c68b 1342 ));
6a488035
TO
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 /**
0965e988 1369 * Combine all the exportable fields from the lower levels object.
6a488035 1370 *
0965e988 1371 * Currently we are using importable fields as exportable fields
6a488035 1372 *
8232cf2d 1373 * @param int|string $contactType contact Type
77c5b619
TO
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?.
6a488035 1380 *
8232cf2d
E
1381 * @param bool $withMultiRecord
1382 *
a6c01b45
CW
1383 * @return array
1384 * array of exportable Fields
6a488035 1385 */
5837835b 1386 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
6a488035
TO
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';
bb341097
EM
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();
6a488035
TO
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) {
6a488035
TO
1409 $fields = CRM_Contact_DAO_Contact::export();
1410
5c9ff055
EM
1411 // The fields are meant for contact types.
1412 if (in_array($contactType, array(
1413 'Individual',
1414 'Household',
1415 'Organization',
1416 'All',
1417 )
1418 )) {
6a488035
TO
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 ),
9bb77b8e 1428 ));
6a488035
TO
1429
1430 $locationType = array(
8c77c68b
KJ
1431 'location_type' => array(
1432 'name' => 'location_type',
6a488035
TO
1433 'where' => 'civicrm_location_type.name',
1434 'title' => ts('Location Type'),
21dfd5f5 1435 ),
9bb77b8e 1436 );
6a488035
TO
1437
1438 $IMProvider = array(
8c77c68b
KJ
1439 'im_provider' => array(
1440 'name' => 'im_provider',
6a488035
TO
1441 'where' => 'civicrm_im.provider_id',
1442 'title' => ts('IM Provider'),
21dfd5f5 1443 ),
9bb77b8e 1444 );
6a488035
TO
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
6a488035
TO
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,
5837835b 1479 CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
6a488035
TO
1480 );
1481 }
1482 else {
1483 foreach (array(
9bb77b8e
TO
1484 'Individual',
1485 'Household',
21dfd5f5 1486 'Organization',
9bb77b8e 1487 ) as $type) {
6a488035 1488 $fields = array_merge($fields,
5837835b 1489 CRM_Core_BAO_CustomField::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
6a488035
TO
1490 );
1491 }
1492 }
48ef7bf8 1493 $fields['current_employer_id']['title'] = ts('Current Employer ID');
6a488035
TO
1494 //fix for CRM-791
1495 if ($export) {
8c77c68b
KJ
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 ));
6a488035
TO
1510 }
1511 else {
8c77c68b
KJ
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 ));
6a488035
TO
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(
8c77c68b
KJ
1537 'Individual' => array(
1538 'household_name',
1539 'legal_name',
1540 'sic_code',
1541 'organization_name',
1542 'email_greeting_custom',
1543 'postal_greeting_custom',
6a488035
TO
1544 'addressee_custom',
1545 ),
1546 'Household' => array(
8c77c68b
KJ
1547 'first_name',
1548 'middle_name',
1549 'last_name',
e171748b 1550 'formal_title',
8c77c68b 1551 'job_title',
04ffef8d
CW
1552 'gender_id',
1553 'prefix_id',
1554 'suffix_id',
8c77c68b
KJ
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',
21dfd5f5 1568 'suffix_id',
6a488035
TO
1569 ),
1570 'Organization' => array(
8c77c68b
KJ
1571 'first_name',
1572 'middle_name',
1573 'last_name',
e171748b 1574 'formal_title',
8c77c68b 1575 'job_title',
04ffef8d
CW
1576 'gender_id',
1577 'prefix_id',
1578 'suffix_id',
8c77c68b
KJ
1579 'birth_date',
1580 'household_name',
6a488035 1581 'email_greeting_custom',
8c77c68b
KJ
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',
6a488035
TO
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 /**
0965e988 1615 * Get the all contact details (Hierarchical).
6a488035 1616 *
77c5b619
TO
1617 * @param int $contactId
1618 * Contact id.
1619 * @param array $fields
1620 * Fields array.
6a488035 1621 *
0965e988
EM
1622 * @return array
1623 * Contact details
6a488035 1624 */
00be9182 1625 public static function getHierContactDetails($contactId, &$fields) {
6a488035
TO
1626 $params = array(array('contact_id', '=', $contactId, 0, 0));
1627 $options = array();
1628
1629 $returnProperties = self::makeHierReturnProperties($fields, $contactId);
1630
5c9ff055
EM
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.
6c552737
TO
1633 $returnProperties['first_name'] = 1;
1634 $returnProperties['organization_name'] = 1;
1635 $returnProperties['household_name'] = 1;
1636 $returnProperties['contact_type'] = 1;
9bb77b8e 1637 $returnProperties['contact_sub_type'] = 1;
6a488035
TO
1638 return list($query, $options) = CRM_Contact_BAO_Query::apiQuery($params, $returnProperties, $options);
1639 }
1640
1641 /**
db7de9c1
EM
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.
6a488035 1645 *
8232cf2d 1646 * @param $fields
77c5b619
TO
1647 * @param int $contactId
1648 * Contact id.
6a488035 1649 *
a6c01b45 1650 * @return array
db7de9c1 1651 * A hierarchical property tree if appropriate
6a488035 1652 */
00be9182 1653 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
b2b0530a 1654 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
1655
1656 $returnProperties = array();
1657
9bb77b8e 1658 $multipleFields = array('website' => 'url');
6a488035
TO
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
a7488080 1674 if (empty($returnProperties['location'])) {
6a488035
TO
1675 $returnProperties['location'] = array();
1676 }
a7488080 1677 if (empty($returnProperties['location'][$locationTypeName])) {
6a488035
TO
1678 $returnProperties['location'][$locationTypeName] = array();
1679 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1680 }
1681 if (in_array($fieldName, array(
9bb77b8e
TO
1682 'phone',
1683 'im',
1684 'email',
1685 'openid',
21dfd5f5 1686 'phone_ext',
9bb77b8e 1687 ))) {
6a488035
TO
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 /**
57507ae6 1715 * Return the primary location type of a contact.
6a488035
TO
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 *
100fef9d 1721 * @param int $contactId
8232cf2d
E
1722 * @param bool $skipDefaultPriamry
1723 * @param null $block
1724 *
a6c01b45
CW
1725 * @return int
1726 * $locationType location_type_id
6a488035 1727 */
00be9182 1728 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
9bb77b8e 1729 if ($block) {
6a488035 1730 $entityBlock = array('contact_id' => $contactId);
9bb77b8e
TO
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);
6a488035
TO
1735 }
1736 }
1737 }
1738 else {
1739 $query = "
1740SELECT
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
1750FROM 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)
1756WHERE 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 /**
57507ae6 1783 * Get the display name, primary email and location type of a contact.
6a488035 1784 *
77c5b619
TO
1785 * @param int $id
1786 * Id of the contact.
6a488035 1787 *
a6c01b45 1788 * @return array
16b10e64 1789 * Array of display_name, email if found, do_not_email or (null,null,null)
6a488035 1790 */
00be9182 1791 public static function getContactDetails($id) {
6a488035
TO
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 = "
1798SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1799FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1800WHERE civicrm_contact.id = %1
1801ORDER 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 }
9bb77b8e 1817 $email = $dao->email;
6a488035 1818 $doNotEmail = $dao->do_not_email ? TRUE : FALSE;
9bb77b8e 1819 $onHold = $dao->on_hold ? TRUE : FALSE;
6a488035
TO
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 /**
100fef9d 1827 * Add/edit/register contacts through profile.
6a488035 1828 *
77c5b619
TO
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).
57507ae6 1839 * @param string $ctype
77c5b619
TO
1840 * @param bool $visibility
1841 * Basically lets us know where this request is coming from.
6a488035
TO
1842 * if via a profile from web, we restrict what groups are changed
1843 *
a6c01b45
CW
1844 * @return int
1845 * contact id created/edited
6a488035 1846 */
57507ae6 1847 public static function createProfileContact(
6a488035
TO
1848 &$params,
1849 &$fields,
1850 $contactID = NULL,
1851 $addToGroupID = NULL,
1852 $ufGroupId = NULL,
9bb77b8e
TO
1853 $ctype = NULL,
1854 $visibility = FALSE
6a488035
TO
1855 ) {
1856 // add ufGroupID to params array ( CRM-2012 )
1857 if ($ufGroupId) {
1858 $params['uf_group_id'] = $ufGroupId;
1859 }
870156d6 1860 self::addBillingNameFieldsIfOtherwiseNotSet($params);
6a488035 1861
85c882c5 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
6a488035
TO
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)) {
9bb77b8e
TO
1883 $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, FALSE);
1884 $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
6a488035
TO
1885 $data['is_opt_out'] = $isOptOut;
1886 // on change, create new civicrm_subscription_history entry
8cc574cf 1887 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
6a488035
TO
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
a7488080 1909 if (!empty($fields['group'])) {
6a488035
TO
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
a7488080 1919 if (!empty($fields['tag'])) {
6a488035
TO
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
2b68a50c 1935 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
6a488035
TO
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
86538308 1946 /**
57507ae6
EM
1947 * Format profile contact parameters.
1948 *
c490a46a 1949 * @param array $params
86538308 1950 * @param $fields
100fef9d
CW
1951 * @param int $contactID
1952 * @param int $ufGroupId
86538308
EM
1953 * @param null $ctype
1954 * @param bool $skipCustom
1955 *
1956 * @return array
1957 */
57507ae6 1958 public static function formatProfileContactParams(
6a488035
TO
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 ) {
f2181617 2002 $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
6a488035
TO
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
aa7a7a14 2008 //CRM-13596 - add to existing contact types, rather than overwriting
f2181617 2009 $data_contact_sub_type_arr = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
aa7a7a14 2010 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
dbc839f9 2011 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2012 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR);
2013 $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . $data['contact_sub_type'] . CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
aa7a7a14 2014 }
6a488035
TO
2015 }
2016
2017 if ($ctype == 'Organization') {
2018 $data['organization_name'] = CRM_Utils_Array::value('organization_name', $contactDetails);
2019 }
2020 elseif ($ctype == 'Household') {
2021 $data['household_name'] = CRM_Utils_Array::value('household_name', $contactDetails);
2022 }
2023
2024 $locationType = array();
2025 $count = 1;
2026
2027 if ($contactID) {
2028 //add contact id
2029 $data['contact_id'] = $contactID;
2030 $primaryLocationType = self::getPrimaryLocationType($contactID);
2031 }
2032 else {
2033 $defaultLocation = CRM_Core_BAO_LocationType::getDefault();
2034 $defaultLocationId = $defaultLocation->id;
2035 }
2036
b576d770 2037 $billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling();
6a488035
TO
2038
2039 $blocks = array('email', 'phone', 'im', 'openid');
2040
2041 $multiplFields = array('url');
2042 // prevent overwritten of formatted array, reset all block from
2043 // params if it is not in valid format (since import pass valid format)
2044 foreach ($blocks as $blk) {
2045 if (array_key_exists($blk, $params) &&
2046 !is_array($params[$blk])
2047 ) {
2048 unset($params[$blk]);
2049 }
2050 }
2051
2052 $primaryPhoneLoc = NULL;
ece0bc24 2053 $session = CRM_Core_Session::singleton();
6a488035 2054 foreach ($params as $key => $value) {
6a488035
TO
2055 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3);
2056
6a488035
TO
2057 if ($locTypeId == 'Primary') {
2058 if ($contactID) {
9bb77b8e 2059 if (in_array($fieldName, $blocks)) {
6a488035
TO
2060 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, $fieldName);
2061 }
9bb77b8e 2062 else {
6a488035
TO
2063 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, 'address');
2064 }
2065 $primaryLocationType = $locTypeId;
2066 }
2067 else {
2068 $locTypeId = $defaultLocationId;
2069 }
2070 }
2071
2072 if (is_numeric($locTypeId) &&
2073 !in_array($fieldName, $multiplFields) &&
2074 substr($fieldName, 0, 7) != 'custom_'
2075 ) {
2076 $index = $locTypeId;
2077
2078 if (is_numeric($typeId)) {
2079 $index .= '-' . $typeId;
2080 }
2081 if (!in_array($index, $locationType)) {
2082 $locationType[$count] = $index;
2083 $count++;
2084 }
2085
2086 $loc = CRM_Utils_Array::key($index, $locationType);
2087
9bb77b8e 2088 $blockName = in_array($fieldName, $blocks) ? $fieldName : 'address';
6a488035
TO
2089
2090 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2091
2092 //set is_billing true, for location type "Billing"
2093 if ($locTypeId == $billingLocationTypeId) {
2094 $data[$blockName][$loc]['is_billing'] = 1;
2095 }
2096
2097 if ($contactID) {
2098 //get the primary location type
2099 if ($locTypeId == $primaryLocationType) {
2100 $data[$blockName][$loc]['is_primary'] = 1;
2101 }
2102 }
2103 elseif ($locTypeId == $defaultLocationId) {
2104 $data[$blockName][$loc]['is_primary'] = 1;
2105 }
2106
9bb77b8e 2107 if (in_array($fieldName, array('phone'))) {
6a488035
TO
2108 if ($typeId) {
2109 $data['phone'][$loc]['phone_type_id'] = $typeId;
2110 }
2111 else {
2112 $data['phone'][$loc]['phone_type_id'] = '';
2113 }
2114 $data['phone'][$loc]['phone'] = $value;
2115
2116 //special case to handle primary phone with different phone types
2117 // in this case we make first phone type as primary
2118 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2119 $primaryPhoneLoc = $loc;
2120 }
2121
2122 if ($loc != $primaryPhoneLoc) {
2123 unset($data['phone'][$loc]['is_primary']);
2124 }
2125 }
2126 elseif ($fieldName == 'phone_ext') {
2127 $data['phone'][$loc]['phone_ext'] = $value;
2128 }
2129 elseif ($fieldName == 'email') {
2130 $data['email'][$loc]['email'] = $value;
0c043d46 2131 if (empty($contactID)) {
2132 $data['email'][$loc]['is_primary'] = 1;
2133 }
6a488035
TO
2134 }
2135 elseif ($fieldName == 'im') {
2136 if (isset($params[$key . '-provider_id'])) {
2137 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2138 }
2139 if (strpos($key, '-provider_id') !== FALSE) {
2140 $data['im'][$loc]['provider_id'] = $params[$key];
2141 }
2142 else {
2143 $data['im'][$loc]['name'] = $value;
2144 }
2145 }
2146 elseif ($fieldName == 'openid') {
2147 $data['openid'][$loc]['openid'] = $value;
2148 }
2149 else {
2150 if ($fieldName === 'state_province') {
2151 // CRM-3393
2152 if (is_numeric($value) && ((int ) $value) >= 1000) {
2153 $data['address'][$loc]['state_province_id'] = $value;
2154 }
2155 elseif (empty($value)) {
2156 $data['address'][$loc]['state_province_id'] = '';
2157 }
2158 else {
2159 $data['address'][$loc]['state_province'] = $value;
2160 }
2161 }
2162 elseif ($fieldName === 'country') {
2163 // CRM-3393
2164 if (is_numeric($value) && ((int ) $value) >= 1000
2165 ) {
2166 $data['address'][$loc]['country_id'] = $value;
2167 }
2168 elseif (empty($value)) {
2169 $data['address'][$loc]['country_id'] = '';
2170 }
2171 else {
2172 $data['address'][$loc]['country'] = $value;
2173 }
2174 }
2175 elseif ($fieldName === 'county') {
2176 $data['address'][$loc]['county_id'] = $value;
2177 }
2178 elseif ($fieldName == 'address_name') {
2179 $data['address'][$loc]['name'] = $value;
2180 }
2181 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2182 $data['address'][$loc][substr($fieldName, 8)] = $value;
2183 }
2184 else {
2185 $data['address'][$loc][$fieldName] = $value;
2186 }
2187 }
2188 }
2189 else {
2190 if (substr($key, 0, 4) === 'url-') {
2191 $websiteField = explode('-', $key);
887e764d
PN
2192 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2193 $data['website'][$websiteField[1]]['url'] = $value;
6a488035 2194 }
6a488035 2195 elseif (in_array($key, self::$_greetingTypes, TRUE)) {
41665e8f 2196 //save email/postal greeting and addressee values if any, CRM-4575
6a488035
TO
2197 $data[$key . '_id'] = $value;
2198 }
2199 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) {
2200 // for autocomplete transfer hidden value instead of label
2201 if ($params[$key] && isset($params[$key . '_id'])) {
2202 $value = $params[$key . '_id'];
2203 }
2204
2205 // we need to append time with date
2206 if ($params[$key] && isset($params[$key . '_time'])) {
2207 $value .= ' ' . $params[$key . '_time'];
2208 }
2209
ece0bc24
DS
2210 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2211 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 &&
9bb77b8e
TO
2212 ($value == '' || !isset($value))
2213 ) {
ece0bc24 2214 continue;
69739cb8 2215 }
ece0bc24 2216
6a488035 2217 $valueId = NULL;
a7488080 2218 if (!empty($params['customRecordValues'])) {
6a488035
TO
2219 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2220 foreach ($params['customRecordValues'] as $recId => $customFields) {
2221 if (is_array($customFields) && !empty($customFields)) {
2222 foreach ($customFields as $customFieldName) {
2223 if ($customFieldName == $key) {
2224 $valueId = $recId;
2225 break;
2226 }
2227 }
2228 }
2229 }
2230 }
2231 }
2232
aa7a7a14
AW
2233 //CRM-13596 - check for contact_sub_type_hidden first
2234 if (array_key_exists('contact_sub_type_hidden', $params)) {
2235 $type = $params['contact_sub_type_hidden'];
9c302451 2236 }
aa7a7a14
AW
2237 else {
2238 $type = $data['contact_type'];
2239 if (!empty($data['contact_sub_type'])) {
77896892 2240 $type = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
aa7a7a14 2241 }
6a488035
TO
2242 }
2243
2244 CRM_Core_BAO_CustomField::formatCustomField($customFieldId,
2245 $data['custom'],
2246 $value,
2247 $type,
2248 $valueId,
c8f7094b 2249 $contactID,
2250 FALSE,
2251 FALSE
6a488035
TO
2252 );
2253 }
2254 elseif ($key == 'edit') {
2255 continue;
2256 }
2257 else {
2258 if ($key == 'location') {
2259 foreach ($value as $locationTypeId => $field) {
2260 foreach ($field as $block => $val) {
2261 if ($block == 'address' && array_key_exists('address_name', $val)) {
2262 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2263 }
2264 }
2265 }
2266 }
9bb77b8e 2267 if ($key == 'phone' && isset($params['phone_ext'])) {
6a488035 2268 $data[$key] = $value;
9bb77b8e
TO
2269 foreach ($value as $cnt => $phoneBlock) {
2270 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
6a488035
TO
2271 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2272 }
2273 }
2274 }
4c9b6178 2275 elseif (in_array($key,
9bb77b8e
TO
2276 array(
2277 'nick_name',
69739cb8
EM
2278 'job_title',
2279 'middle_name',
2280 'birth_date',
4512fd44 2281 'gender_id',
69739cb8
EM
2282 'current_employer',
2283 'prefix_id',
21dfd5f5 2284 'suffix_id',
9bb77b8e 2285 )) &&
55ff2e3f 2286 ($value == '' || !isset($value)) &&
bc1e91c8 2287 ($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 ||
2288 ($key == 'current_employer' && empty($params['current_employer']))) {
69739cb8 2289 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
55ff2e3f
DS
2290 // to avoid update with empty values
2291 continue;
69739cb8 2292 }
6a488035
TO
2293 else {
2294 $data[$key] = $value;
2295 }
2296 }
2297 }
2298 }
2299
2300 if (!isset($data['contact_type'])) {
2301 $data['contact_type'] = 'Individual';
2302 }
2303
2304 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2305 $privacy = CRM_Core_SelectValues::privacy();
2306 foreach ($privacy as $key => $value) {
2307 if (array_key_exists($key, $fields)) {
29748d00 2308 // do not reset values for existing contacts, if fields are added to a profile
6a488035
TO
2309 if (array_key_exists($key, $params)) {
2310 $data[$key] = $params[$key];
29748d00
C
2311 if (empty($params[$key])) {
2312 $data[$key] = 0;
2313 }
6a488035
TO
2314 }
2315 elseif (!$contactID) {
2316 $data[$key] = 0;
2317 }
2318 }
2319 }
2320
2321 return array($data, $contactDetails);
2322 }
2323
2324 /**
57507ae6
EM
2325 * Find the get contact details.
2326 *
2327 * This function does not respect ACLs for now, which might need to be rectified at some
2328 * stage based on how its used.
6a488035 2329 *
77c5b619
TO
2330 * @param string $mail
2331 * Primary email address of the contact.
2332 * @param string $ctype
2333 * Contact type.
6a488035 2334 *
1273d77c 2335 * @return object|null
a6c01b45 2336 * $dao contact details
6a488035 2337 */
1273d77c 2338 public static function matchContactOnEmail($mail, $ctype = NULL) {
6a488035 2339 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
9bb77b8e
TO
2340 $mail = $strtolower(trim($mail));
2341 $query = "
6a488035
TO
2342SELECT civicrm_contact.id as contact_id,
2343 civicrm_contact.hash as hash,
2344 civicrm_contact.contact_type as contact_type,
2345 civicrm_contact.contact_sub_type as contact_sub_type
2346FROM civicrm_contact
2347INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2348
aaffa79f 2349 if (Civi::settings()->get('uniq_email_per_site')) {
6a488035
TO
2350 // try to find a match within a site (multisite).
2351 $groups = CRM_Core_BAO_Domain::getChildGroupIds();
2352 if (!empty($groups)) {
2353 $query .= "
2354INNER JOIN civicrm_group_contact gc ON
2355(civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2356 }
2357 }
2358
2359 $query .= "
2360WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2361 $p = array(1 => array($mail, 'String'));
2362
2363 if ($ctype) {
2364 $query .= " AND civicrm_contact.contact_type = %3";
2365 $p[3] = array($ctype, 'String');
2366 }
2367
2368 $query .= " ORDER BY civicrm_email.is_primary DESC";
2369
2370 $dao = CRM_Core_DAO::executeQuery($query, $p);
2371
2372 if ($dao->fetch()) {
2373 return $dao;
2374 }
1273d77c 2375 return NULL;
6a488035
TO
2376 }
2377
2378 /**
57507ae6 2379 * Find the contact details associated with an OpenID.
6a488035 2380 *
77c5b619
TO
2381 * @param string $openId
2382 * OpenId of the contact.
2383 * @param string $ctype
2384 * Contact type.
6a488035 2385 *
1273d77c 2386 * @return object|null
a6c01b45 2387 * $dao contact details
6a488035 2388 */
1273d77c 2389 public static function matchContactOnOpenId($openId, $ctype = NULL) {
6a488035 2390 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
9bb77b8e
TO
2391 $openId = $strtolower(trim($openId));
2392 $query = "
6a488035
TO
2393SELECT civicrm_contact.id as contact_id,
2394 civicrm_contact.hash as hash,
2395 civicrm_contact.contact_type as contact_type,
2396 civicrm_contact.contact_sub_type as contact_sub_type
2397FROM civicrm_contact
2398INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2399WHERE civicrm_openid.openid = %1";
2400 $p = array(1 => array($openId, 'String'));
2401
2402 if ($ctype) {
2403 $query .= " AND civicrm_contact.contact_type = %3";
2404 $p[3] = array($ctype, 'String');
2405 }
2406
2407 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2408
2409 $dao = CRM_Core_DAO::executeQuery($query, $p);
2410
2411 if ($dao->fetch()) {
2412 return $dao;
2413 }
1273d77c 2414 return NULL;
6a488035
TO
2415 }
2416
2417 /**
57507ae6 2418 * Get primary email of the contact.
6a488035 2419 *
77c5b619
TO
2420 * @param int $contactID
2421 * Contact id.
6a488035 2422 *
a6c01b45 2423 * @return string
57507ae6 2424 * Email address if present else null
6a488035
TO
2425 */
2426 public static function getPrimaryEmail($contactID) {
2427 // fetch the primary email
2428 $query = "
2429 SELECT civicrm_email.email as email
2430 FROM civicrm_contact
2431LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2432 WHERE civicrm_email.is_primary = 1
2433 AND civicrm_contact.id = %1";
2434 $p = array(1 => array($contactID, 'Integer'));
2435 $dao = CRM_Core_DAO::executeQuery($query, $p);
2436
2437 $email = NULL;
2438 if ($dao->fetch()) {
2439 $email = $dao->email;
2440 }
2441 $dao->free();
2442 return $email;
2443 }
2444
2445 /**
57507ae6 2446 * Function to get primary OpenID of the contact.
6a488035 2447 *
77c5b619
TO
2448 * @param int $contactID
2449 * Contact id.
6a488035 2450 *
a6c01b45
CW
2451 * @return string
2452 * >openid OpenID if present else null
6a488035
TO
2453 */
2454 public static function getPrimaryOpenId($contactID) {
2455 // fetch the primary OpenID
2456 $query = "
2457SELECT civicrm_openid.openid as openid
2458FROM civicrm_contact
2459LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2460WHERE civicrm_contact.id = %1
2461AND civicrm_openid.is_primary = 1";
2462 $p = array(1 => array($contactID, 'Integer'));
2463 $dao = CRM_Core_DAO::executeQuery($query, $p);
2464
2465 $openId = NULL;
2466 if ($dao->fetch()) {
2467 $openId = $dao->openid;
2468 }
2469 $dao->free();
2470 return $openId;
2471 }
2472
2473 /**
57507ae6 2474 * Fetch the object and store the values in the values array.
6a488035 2475 *
77c5b619
TO
2476 * @param array $params
2477 * Input parameters to find object.
2478 * @param array $values
2479 * Output values of the object.
6a488035 2480 *
57507ae6
EM
2481 * @return CRM_Contact_BAO_Contact|null
2482 * The found object or null
6a488035
TO
2483 */
2484 public static function getValues(&$params, &$values) {
2485 $contact = new CRM_Contact_BAO_Contact();
2486
2487 $contact->copyValues($params);
2488
2489 if ($contact->find(TRUE)) {
2490
2491 CRM_Core_DAO::storeValues($contact, $values);
2492
2493 $privacy = array();
2494 foreach (self::$_commPrefs as $name) {
2495 if (isset($contact->$name)) {
2496 $privacy[$name] = $contact->$name;
2497 }
2498 }
2499
2500 if (!empty($privacy)) {
2501 $values['privacy'] = $privacy;
2502 }
2503
2504 // communication Prefferance
2505 $preffComm = $comm = array();
2506 $comm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2507 $contact->preferred_communication_method
2508 );
2509 foreach ($comm as $value) {
2510 $preffComm[$value] = 1;
2511 }
2512 $temp = array('preferred_communication_method' => $contact->preferred_communication_method);
2513
2514 $names = array(
9bb77b8e
TO
2515 'preferred_communication_method' => array(
2516 'newName' => 'preferred_communication_method_display',
6a488035 2517 'groupName' => 'preferred_communication_method',
21dfd5f5 2518 ),
9bb77b8e 2519 );
6a488035 2520
ed0ca248 2521 // @todo This can be figured out from metadata & we can avoid the uncached query.
6a488035
TO
2522 CRM_Core_OptionGroup::lookupValues($temp, $names, FALSE);
2523
2524 $values['preferred_communication_method'] = $preffComm;
2525 $values['preferred_communication_method_display'] = CRM_Utils_Array::value('preferred_communication_method_display', $temp);
2526
cd223eef 2527 if ($contact->preferred_mail_format) {
2528 $preferredMailingFormat = CRM_Core_SelectValues::pmf();
2529 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format];
2530 }
6a488035
TO
2531
2532 // get preferred languages
2533 if (!empty($contact->preferred_language)) {
a8c23526 2534 $values['preferred_language'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language);
6a488035
TO
2535 }
2536
2537 // Calculating Year difference
2538 if ($contact->birth_date) {
2539 $birthDate = CRM_Utils_Date::customFormat($contact->birth_date, '%Y%m%d');
2540 if ($birthDate < date('Ymd')) {
9bb77b8e 2541 $age = CRM_Utils_Date::calculateAge($birthDate);
6a488035
TO
2542 $values['age']['y'] = CRM_Utils_Array::value('years', $age);
2543 $values['age']['m'] = CRM_Utils_Array::value('months', $age);
2544 }
6a488035
TO
2545 }
2546
2547 $contact->contact_id = $contact->id;
2548
2549 return $contact;
2550 }
2551 return NULL;
2552 }
2553
2554 /**
db7de9c1 2555 * Given the component name and returns the count of participation of contact.
6a488035 2556 *
77c5b619
TO
2557 * @param string $component
2558 * Input component name.
2559 * @param int $contactId
2560 * Input contact id.
2561 * @param string $tableName
2562 * Optional tableName if component is custom group.
6a488035 2563 *
72b3a70c
CW
2564 * @return int
2565 * total number in database
6a488035 2566 */
00be9182 2567 public static function getCountComponent($component, $contactId, $tableName = NULL) {
6a488035
TO
2568 $object = NULL;
2569 switch ($component) {
2570 case 'tag':
2571 return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE);
2572
2573 case 'rel':
6c552737 2574 $result = CRM_Contact_BAO_Relationship::getRelationship($contactId,
468da094 2575 CRM_Contact_BAO_Relationship::CURRENT,
b7d19957 2576 0, 1, 0,
a93664c8 2577 NULL, NULL,
2578 TRUE
6a488035 2579 );
b7d19957 2580 return $result;
6a488035
TO
2581
2582 case 'group':
468da094 2583
6a488035
TO
2584 return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE);
2585
2586 case 'log':
2587 if (CRM_Core_BAO_Log::useLoggingReport()) {
2588 return FALSE;
2589 }
2590 return CRM_Core_BAO_Log::getContactLogCount($contactId);
2591
2592 case 'note':
2593 return CRM_Core_BAO_Note::getContactNoteCount($contactId);
2594
2595 case 'contribution':
2596 return CRM_Contribute_BAO_Contribution::contributionCount($contactId);
2597
2598 case 'membership':
2599 return CRM_Member_BAO_Membership::getContactMembershipCount($contactId, TRUE);
2600
2601 case 'participant':
2602 return CRM_Event_BAO_Participant::getContactParticipantCount($contactId);
2603
2604 case 'pledge':
2605 return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId);
2606
2607 case 'case':
2608 return CRM_Case_BAO_Case::caseCount($contactId);
2609
2610 case 'grant':
2611 return CRM_Grant_BAO_Grant::getContactGrantCount($contactId);
2612
2613 case 'activity':
2614 $input = array(
2615 'contact_id' => $contactId,
2616 'admin' => FALSE,
2617 'caseId' => NULL,
2618 'context' => 'activity',
2619 );
6ab43e1b 2620 return CRM_Activity_BAO_Activity::deprecatedGetActivitiesCount($input);
6a488035 2621
36bb946c 2622 case 'mailing':
7c006637 2623 $params = array('contact_id' => $contactId);
553f116a 2624 return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
36bb946c 2625
6a488035
TO
2626 default:
2627 $custom = explode('_', $component);
2628 if ($custom['0'] = 'custom') {
2629 if (!$tableName) {
2630 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2631 }
2632 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2633 return CRM_Core_DAO::singleValueQuery($queryString);
2634 }
2635 }
2636 }
2637
2638 /**
567b2076 2639 * Process greetings and cache.
6a488035 2640 *
77c5b619
TO
2641 * @param object $contact
2642 * Contact object after save.
2643 * @param bool $useDefaults
2644 * Use default greeting values.
6a488035 2645 */
00be9182 2646 public static function processGreetings(&$contact, $useDefaults = FALSE) {
6a488035
TO
2647 if ($useDefaults) {
2648 //retrieve default greetings
2649 $defaultGreetings = CRM_Core_PseudoConstant::greetingDefaults();
2650 $contactDefaults = $defaultGreetings[$contact->contact_type];
2651 }
2652
663cc0b4
J
2653 // The contact object has not always required the
2654 // fields that are required to calculate greetings
2655 // so we need to retrieve it again.
9bb77b8e 2656 if ($contact->_query !== FALSE) {
1a902da0
BS
2657 $contact->find(TRUE);
2658 }
6a488035
TO
2659
2660 // store object values to an array
2661 $contactDetails = array();
2662 CRM_Core_DAO::storeValues($contact, $contactDetails);
2663 $contactDetails = array(array($contact->id => $contactDetails));
2664
2665 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2666 $updateQueryString = array();
2667
2668 //cache email and postal greeting to greeting display
2669 if ($contact->email_greeting_custom != 'null' && $contact->email_greeting_custom) {
2670 $emailGreetingString = $contact->email_greeting_custom;
2671 }
2672 elseif ($contact->email_greeting_id != 'null' && $contact->email_greeting_id) {
2673 // the filter value for Individual contact type is set to 1
2674 $filter = array(
2675 'contact_type' => $contact->contact_type,
2676 'greeting_type' => 'email_greeting',
2677 );
2678
9bb77b8e 2679 $emailGreeting = CRM_Core_PseudoConstant::greeting($filter);
6a488035
TO
2680 $emailGreetingString = $emailGreeting[$contact->email_greeting_id];
2681 $updateQueryString[] = " email_greeting_custom = NULL ";
2682 }
2683 else {
2684 if ($useDefaults) {
2685 reset($contactDefaults['email_greeting']);
9bb77b8e 2686 $emailGreetingID = key($contactDefaults['email_greeting']);
6a488035
TO
2687 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2688 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2689 $updateQueryString[] = " email_greeting_custom = NULL ";
2690 }
2691 elseif ($contact->email_greeting_custom) {
2692 $updateQueryString[] = " email_greeting_display = NULL ";
2693 }
2694 }
2695
2696 if ($emailGreetingString) {
73d64eb6 2697 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($emailGreetingString,
6a488035
TO
2698 $contactDetails,
2699 $contact->id,
2700 'CRM_Contact_BAO_Contact'
2701 );
2702 $emailGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($emailGreetingString));
2703 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2704 }
2705
2706 //postal greetings
2707 if ($contact->postal_greeting_custom != 'null' && $contact->postal_greeting_custom) {
2708 $postalGreetingString = $contact->postal_greeting_custom;
2709 }
2710 elseif ($contact->postal_greeting_id != 'null' && $contact->postal_greeting_id) {
2711 $filter = array(
2712 'contact_type' => $contact->contact_type,
2713 'greeting_type' => 'postal_greeting',
2714 );
2715 $postalGreeting = CRM_Core_PseudoConstant::greeting($filter);
2716 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id];
2717 $updateQueryString[] = " postal_greeting_custom = NULL ";
2718 }
2719 else {
2720 if ($useDefaults) {
2721 reset($contactDefaults['postal_greeting']);
2722 $postalGreetingID = key($contactDefaults['postal_greeting']);
2723 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2724 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2725 $updateQueryString[] = " postal_greeting_custom = NULL ";
2726 }
2727 elseif ($contact->postal_greeting_custom) {
2728 $updateQueryString[] = " postal_greeting_display = NULL ";
2729 }
2730 }
2731
2732 if ($postalGreetingString) {
73d64eb6 2733 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($postalGreetingString,
6a488035
TO
2734 $contactDetails,
2735 $contact->id,
2736 'CRM_Contact_BAO_Contact'
2737 );
2738 $postalGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($postalGreetingString));
2739 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2740 }
2741
2742 // addressee
2743 if ($contact->addressee_custom != 'null' && $contact->addressee_custom) {
2744 $addresseeString = $contact->addressee_custom;
2745 }
2746 elseif ($contact->addressee_id != 'null' && $contact->addressee_id) {
2747 $filter = array(
2748 'contact_type' => $contact->contact_type,
2749 'greeting_type' => 'addressee',
2750 );
2751
9bb77b8e
TO
2752 $addressee = CRM_Core_PseudoConstant::greeting($filter);
2753 $addresseeString = $addressee[$contact->addressee_id];
6a488035
TO
2754 $updateQueryString[] = " addressee_custom = NULL ";
2755 }
2756 else {
2757 if ($useDefaults) {
2758 reset($contactDefaults['addressee']);
9bb77b8e
TO
2759 $addresseeID = key($contactDefaults['addressee']);
2760 $addresseeString = $contactDefaults['addressee'][$addresseeID];
6a488035
TO
2761 $updateQueryString[] = " addressee_id = $addresseeID ";
2762 $updateQueryString[] = " addressee_custom = NULL ";
2763 }
2764 elseif ($contact->addressee_custom) {
2765 $updateQueryString[] = " addressee_display = NULL ";
2766 }
2767 }
2768
2769 if ($addresseeString) {
73d64eb6 2770 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($addresseeString,
6a488035
TO
2771 $contactDetails,
2772 $contact->id,
2773 'CRM_Contact_BAO_Contact'
2774 );
2775 $addresseeString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($addresseeString));
2776 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2777 }
2778
2779 if (!empty($updateQueryString)) {
2780 $updateQueryString = implode(',', $updateQueryString);
2781 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2782 CRM_Core_DAO::executeQuery($queryString);
2783 }
2784 }
2785
2786 /**
100fef9d 2787 * Retrieve loc block ids w/ given condition.
6a488035 2788 *
77c5b619
TO
2789 * @param int $contactId
2790 * Contact id.
2791 * @param array $criteria
2792 * Key => value pair which should be.
6a488035 2793 * fulfill by return record ids.
77c5b619
TO
2794 * @param string $condOperator
2795 * Operator use for grouping multiple conditions.
6a488035 2796 *
a6c01b45
CW
2797 * @return array
2798 * loc block ids which fulfill condition.
6a488035 2799 */
00be9182 2800 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
6a488035
TO
2801 $locBlockIds = array();
2802 if (!$contactId) {
2803 return $locBlockIds;
2804 }
2805
46a4f1e9 2806 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
6a488035 2807 $name = strtolower($block);
46a4f1e9
CW
2808 $className = "CRM_Core_DAO_$block";
2809 $blockDAO = new $className();
6a488035
TO
2810
2811 // build the condition.
2812 if (is_array($criteria)) {
46a4f1e9 2813 $fields = $blockDAO->fields();
6a488035
TO
2814 $conditions = array();
2815 foreach ($criteria as $field => $value) {
2816 if (array_key_exists($field, $fields)) {
2817 $cond = "( $field = $value )";
2818 // value might be zero or null.
2819 if (!$value || strtolower($value) == 'null') {
2820 $cond = "( $field = 0 OR $field IS NULL )";
2821 }
2822 $conditions[] = $cond;
2823 }
2824 }
2825 if (!empty($conditions)) {
2826 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2827 }
2828 }
2829
2830 $blockDAO->contact_id = $contactId;
2831 $blockDAO->find();
2832 while ($blockDAO->fetch()) {
2833 $locBlockIds[$name][] = $blockDAO->id;
2834 }
2835 $blockDAO->free();
2836 }
2837
2838 return $locBlockIds;
2839 }
2840
2841 /**
100fef9d 2842 * Build context menu items.
6a488035 2843 *
100fef9d 2844 * @param int $contactId
77b97be7 2845 *
a6c01b45 2846 * @return array
16b10e64 2847 * Array of context menu for logged in user.
6a488035 2848 */
00be9182 2849 public static function contextMenu($contactId = NULL) {
6a488035 2850 $menu = array(
9309f5c6
E
2851 'view' => array(
2852 'title' => ts('View Contact'),
2853 'weight' => 0,
2854 'ref' => 'view-contact',
2855 'class' => 'no-popup',
2856 'key' => 'view',
2857 'permissions' => array('view all contacts'),
2858 ),
2859 'add' => array(
2860 'title' => ts('Edit Contact'),
2861 'weight' => 0,
2862 'ref' => 'edit-contact',
2863 'class' => 'no-popup',
2864 'key' => 'add',
2865 'permissions' => array('edit all contacts'),
2866 ),
2867 'delete' => array(
2868 'title' => ts('Delete Contact'),
2869 'weight' => 0,
2870 'ref' => 'delete-contact',
2871 'key' => 'delete',
2872 'permissions' => array('access deleted contacts', 'delete contacts'),
2873 ),
2874 'contribution' => array(
2875 'title' => ts('Add Contribution'),
2876 'weight' => 5,
2877 'ref' => 'new-contribution',
2878 'key' => 'contribution',
2879 'tab' => 'contribute',
2880 'component' => 'CiviContribute',
2881 'href' => CRM_Utils_System::url('civicrm/contact/view/contribution',
2882 'reset=1&action=add&context=contribution'
6a488035 2883 ),
9309f5c6
E
2884 'permissions' => array(
2885 'access CiviContribute',
2886 'edit contributions',
6a488035 2887 ),
9309f5c6
E
2888 ),
2889 'participant' => array(
2890 'title' => ts('Register for Event'),
2891 'weight' => 10,
2892 'ref' => 'new-participant',
2893 'key' => 'participant',
2894 'tab' => 'participant',
2895 'component' => 'CiviEvent',
2896 'href' => CRM_Utils_System::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2897 'permissions' => array(
2898 'access CiviEvent',
2899 'edit event participants',
6a488035 2900 ),
9309f5c6
E
2901 ),
2902 'activity' => array(
2903 'title' => ts('Record Activity'),
2904 'weight' => 35,
2905 'ref' => 'new-activity',
2906 'key' => 'activity',
2907 'permissions' => array('edit all contacts'),
2908 ),
2909 'pledge' => array(
2910 'title' => ts('Add Pledge'),
2911 'weight' => 15,
2912 'ref' => 'new-pledge',
2913 'key' => 'pledge',
2914 'tab' => 'pledge',
2915 'href' => CRM_Utils_System::url('civicrm/contact/view/pledge',
2916 'reset=1&action=add&context=pledge'
6a488035 2917 ),
9309f5c6
E
2918 'component' => 'CiviPledge',
2919 'permissions' => array(
2920 'access CiviPledge',
2921 'edit pledges',
1fb73100 2922 ),
9309f5c6
E
2923 ),
2924 'membership' => array(
2925 'title' => ts('Add Membership'),
2926 'weight' => 20,
2927 'ref' => 'new-membership',
2928 'key' => 'membership',
2929 'tab' => 'member',
2930 'component' => 'CiviMember',
2931 'href' => CRM_Utils_System::url('civicrm/contact/view/membership',
2932 'reset=1&action=add&context=membership'
1fb73100 2933 ),
9309f5c6
E
2934 'permissions' => array(
2935 'access CiviMember',
2936 'edit memberships',
1fb73100 2937 ),
9309f5c6
E
2938 ),
2939 'case' => array(
2940 'title' => ts('Add Case'),
2941 'weight' => 25,
2942 'ref' => 'new-case',
2943 'key' => 'case',
2944 'tab' => 'case',
2945 'component' => 'CiviCase',
2946 'href' => CRM_Utils_System::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2947 'permissions' => array('add cases'),
2948 ),
2949 'grant' => array(
2950 'title' => ts('Add Grant'),
2951 'weight' => 26,
2952 'ref' => 'new-grant',
2953 'key' => 'grant',
2954 'tab' => 'grant',
2955 'component' => 'CiviGrant',
2956 'href' => CRM_Utils_System::url('civicrm/contact/view/grant',
2957 'reset=1&action=add&context=grant'
1fb73100 2958 ),
9309f5c6
E
2959 'permissions' => array('edit grants'),
2960 ),
2961 'rel' => array(
2962 'title' => ts('Add Relationship'),
2963 'weight' => 30,
2964 'ref' => 'new-relationship',
2965 'key' => 'rel',
2966 'tab' => 'rel',
2967 'href' => CRM_Utils_System::url('civicrm/contact/view/rel',
2968 'reset=1&action=add'
1fb73100 2969 ),
9309f5c6
E
2970 'permissions' => array('edit all contacts'),
2971 ),
2972 'note' => array(
2973 'title' => ts('Add Note'),
2974 'weight' => 40,
2975 'ref' => 'new-note',
2976 'key' => 'note',
2977 'tab' => 'note',
2978 'class' => 'medium-popup',
2979 'href' => CRM_Utils_System::url('civicrm/contact/view/note',
2980 'reset=1&action=add'
6a488035 2981 ),
9309f5c6 2982 'permissions' => array('edit all contacts'),
6a488035 2983 ),
9309f5c6
E
2984 'email' => array(
2985 'title' => ts('Send an Email'),
2986 'weight' => 45,
2987 'ref' => 'new-email',
2988 'key' => 'email',
2989 'permissions' => array('view all contacts'),
2990 ),
2991 'group' => array(
2992 'title' => ts('Add to Group'),
2993 'weight' => 50,
2994 'ref' => 'group-add-contact',
2995 'key' => 'group',
2996 'tab' => 'group',
2997 'permissions' => array('edit groups'),
2998 ),
2999 'tag' => array(
3000 'title' => ts('Tag Contact'),
3001 'weight' => 55,
3002 'ref' => 'tag-contact',
3003 'key' => 'tag',
3004 'tab' => 'tag',
3005 'permissions' => array('edit all contacts'),
3006 ),
3007 );
3008
3009 $menu['otherActions'] = array(
3010 'print' => array(
3011 'title' => ts('Print Summary'),
3012 'description' => ts('Printer-friendly view of this page.'),
3013 'weight' => 5,
3014 'ref' => 'crm-contact-print',
3015 'key' => 'print',
3016 'tab' => 'print',
3017 'href' => CRM_Utils_System::url('civicrm/contact/view/print',
3018 "reset=1&print=1"
1fb73100 3019 ),
9309f5c6
E
3020 'class' => 'print',
3021 'icon' => 'crm-i fa-print',
3022 ),
3023 'vcard' => array(
3024 'title' => ts('vCard'),
3025 'description' => ts('vCard record for this contact.'),
3026 'weight' => 10,
3027 'ref' => 'crm-contact-vcard',
3028 'key' => 'vcard',
3029 'tab' => 'vcard',
3030 'href' => CRM_Utils_System::url('civicrm/contact/view/vcard',
3031 "reset=1"
1fb73100 3032 ),
9309f5c6
E
3033 'class' => 'vcard',
3034 'icon' => 'crm-i fa-list-alt',
6a488035
TO
3035 ),
3036 );
3037
9309f5c6 3038 if (CRM_Core_Permission::check('access Contact Dashboard')) {
1fb73100
E
3039 $menu['otherActions']['dashboard'] = array(
3040 'title' => ts('Contact Dashboard'),
3041 'description' => ts('Contact Dashboard'),
3042 'weight' => 15,
3043 'ref' => 'crm-contact-dashboard',
3044 'key' => 'dashboard',
3045 'tab' => 'dashboard',
3046 'class' => 'dashboard',
9309f5c6
E
3047 // NOTE: As an alternative you can also build url on CMS specific way
3048 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3049 'href' => CRM_Utils_System::url('civicrm/user', "reset=1&id={$contactId}"),
1fb73100
E
3050 'icon' => 'crm-i fa-tachometer',
3051 );
3052 }
3053
9309f5c6
E
3054 $uid = CRM_Core_BAO_UFMatch::getUFId($contactId);
3055 if ($uid) {
1fb73100
E
3056 $menu['otherActions']['user-record'] = array(
3057 'title' => ts('User Record'),
3058 'description' => ts('User Record'),
3059 'weight' => 20,
3060 'ref' => 'crm-contact-user-record',
3061 'key' => 'user-record',
3062 'tab' => 'user-record',
3063 'class' => 'user-record',
9309f5c6 3064 'href' => CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId),
1fb73100
E
3065 'icon' => 'crm-i fa-user',
3066 );
3067 }
9309f5c6 3068 elseif (CRM_Core_Config::singleton()->userSystem->checkPermissionAddUser()) {
1fb73100
E
3069 $menu['otherActions']['user-add'] = array(
3070 'title' => ts('Create User Record'),
3071 'description' => ts('Create User Record'),
3072 'weight' => 25,
3073 'ref' => 'crm-contact-user-add',
3074 'key' => 'user-add',
3075 'tab' => 'user-add',
3076 'class' => 'user-add',
9309f5c6 3077 'href' => CRM_Utils_System::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
1fb73100
E
3078 'icon' => 'crm-i fa-user-plus',
3079 );
3080 }
3081
6a488035
TO
3082 CRM_Utils_Hook::summaryActions($menu, $contactId);
3083 //1. check for component is active.
3084 //2. check for user permissions.
3085 //3. check for acls.
3086 //3. edit and view contact are directly accessible to user.
3087
3088 $aclPermissionedTasks = array(
9bb77b8e
TO
3089 'view-contact',
3090 'edit-contact',
3091 'new-activity',
3092 'new-email',
3093 'group-add-contact',
3094 'tag-contact',
3095 'delete-contact',
6a488035
TO
3096 );
3097 $corePermission = CRM_Core_Permission::getPermission();
3098
6a488035 3099 $contextMenu = array();
9309f5c6
E
3100 foreach ($menu as $key => $values) {
3101 if ($key != 'otherActions') {
6a488035 3102
1fb73100 3103 // user does not have necessary permissions.
9309f5c6 3104 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
1fb73100
E
3105 continue;
3106 }
1fb73100
E
3107 // build directly accessible action menu.
3108 if (in_array($values['ref'], array(
3109 'view-contact',
3110 'edit-contact',
3111 ))) {
3112 $contextMenu['primaryActions'][$key] = array(
3113 'title' => $values['title'],
3114 'ref' => $values['ref'],
3115 'class' => CRM_Utils_Array::value('class', $values),
3116 'key' => $values['key'],
3117 );
3118 continue;
3119 }
3120
3121 // finally get menu item for -more- action widget.
9309f5c6 3122 $contextMenu['moreActions'][$values['weight']] = array(
6a488035
TO
3123 'title' => $values['title'],
3124 'ref' => $values['ref'],
1fb73100
E
3125 'href' => CRM_Utils_Array::value('href', $values),
3126 'tab' => CRM_Utils_Array::value('tab', $values),
8e4ec1f5 3127 'class' => CRM_Utils_Array::value('class', $values),
6a488035
TO
3128 'key' => $values['key'],
3129 );
6a488035 3130 }
9309f5c6
E
3131 else {
3132 foreach ($values as $value) {
3133 // user does not have necessary permissions.
3134 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3135 continue;
3136 }
3137
3138 // finally get menu item for -more- action widget.
3139 $contextMenu['otherActions'][$value['weight']] = array(
3140 'title' => $value['title'],
3141 'ref' => $value['ref'],
3142 'href' => CRM_Utils_Array::value('href', $value),
3143 'tab' => CRM_Utils_Array::value('tab', $value),
3144 'class' => CRM_Utils_Array::value('class', $value),
3145 'icon' => CRM_Utils_Array::value('icon', $value),
3146 'key' => $value['key'],
3147 );
3148 }
3149 }
6a488035
TO
3150 }
3151
3152 ksort($contextMenu['moreActions']);
1fb73100 3153 ksort($contextMenu['otherActions']);
6a488035
TO
3154
3155 return $contextMenu;
3156 }
3157
9309f5c6
E
3158 /**
3159 * Check if user has permissions to access items in action menu.
3160 *
3161 * @param array $aclPermissionedTasks
3162 * Array containing ACL related tasks.
3163 * @param string $corePermission
3164 * The permission of the user (edit or view or null).
3165 * @param array $menuOptions
3166 * Array containing params of the menu (title, href, etc).
3167 *
3168 * @return bool
3169 * TRUE if user has all permissions, FALSE if otherwise.
3170 */
3171 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3172 $componentName = CRM_Utils_Array::value('component', $menuOptions);
3173
3174 // if component action - make sure component is enable.
3175 if ($componentName && !in_array($componentName, CRM_Core_Config::singleton()->enableComponents)) {
3176 return FALSE;
3177 }
3178
3179 // make sure user has all required permissions.
3180 $hasAllPermissions = FALSE;
3181
3182 $permissions = CRM_Utils_Array::value('permissions', $menuOptions);
3183 if (!is_array($permissions) || empty($permissions)) {
3184 $hasAllPermissions = TRUE;
3185 }
3186
3187 // iterate for required permissions in given permissions array.
3188 if (!$hasAllPermissions) {
3189 $hasPermissions = 0;
3190 foreach ($permissions as $permission) {
3191 if (CRM_Core_Permission::check($permission)) {
3192 $hasPermissions++;
3193 }
3194 }
3195
3196 if (count($permissions) == $hasPermissions) {
3197 $hasAllPermissions = TRUE;
3198 }
3199
3200 // if still user does not have required permissions, check acl.
3201 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
c2463857 3202 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
9309f5c6
E
3203 $corePermission == CRM_Core_Permission::EDIT
3204 ) {
3205 $hasAllPermissions = TRUE;
3206 }
3207 elseif (in_array($menuOptions['ref'], array(
3208 'new-email',
3209 ))) {
3210 // grant permissions for these tasks.
3211 $hasAllPermissions = TRUE;
3212 }
3213 }
3214 }
3215
3216 return $hasAllPermissions;
3217 }
3218
6a488035 3219 /**
567b2076
EM
3220 * Retrieve display name of contact that address is shared.
3221 *
3222 * This is based on $masterAddressId or $contactId .
6a488035 3223 *
77c5b619
TO
3224 * @param int $masterAddressId
3225 * Master id.
3226 * @param int $contactId
3227 * Contact id.
6a488035 3228 *
72b3a70c
CW
3229 * @return string|null
3230 * the found display name or null.
6a488035 3231 */
00be9182 3232 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
6a488035
TO
3233 $masterDisplayName = NULL;
3234 $sql = NULL;
3235 if (!$masterAddressId && !$contactId) {
3236 return $masterDisplayName;
3237 }
3238
3239 if ($masterAddressId) {
3240 $sql = "
3241 SELECT display_name from civicrm_contact
3242LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3243 WHERE civicrm_address.id = " . $masterAddressId;
3244 }
3245 elseif ($contactId) {
3246 $sql = "
3247 SELECT display_name from civicrm_contact cc, civicrm_address add1
3248LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3249 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3250 }
3251
3252 $masterDisplayName = CRM_Core_DAO::singleValueQuery($sql);
3253 return $masterDisplayName;
3254 }
3255
3256 /**
567b2076 3257 * Get the creation/modification times for a contact.
6a488035 3258 *
100fef9d 3259 * @param int $contactId
77b97be7 3260 *
567b2076 3261 * @return array
5c766a0b 3262 * Dates - ('created_date' => $, 'modified_date' => $)
77b97be7 3263 */
00be9182 3264 public static function getTimestamps($contactId) {
6a488035
TO
3265 $timestamps = CRM_Core_DAO::executeQuery(
3266 'SELECT created_date, modified_date
3267 FROM civicrm_contact
3268 WHERE id = %1',
3269 array(
3270 1 => array($contactId, 'Integer'),
3271 )
3272 );
3273 if ($timestamps->fetch()) {
3274 return array(
3275 'created_date' => $timestamps->created_date,
3276 'modified_date' => $timestamps->modified_date,
3277 );
3278 }
3279 else {
3280 return NULL;
3281 }
3282 }
3283
3284 /**
db7de9c1 3285 * Get a list of triggers for the contact table.
6a488035
TO
3286 *
3287 * @see hook_civicrm_triggerInfo
3288 * @see CRM_Core_DAO::triggerRebuild
3289 * @see http://issues.civicrm.org/jira/browse/CRM-10554
2e2605fe
EM
3290 *
3291 * @param $info
3292 * @param null $tableName
6a488035 3293 */
00be9182 3294 public static function triggerInfo(&$info, $tableName = NULL) {
6a488035
TO
3295 //during upgrade, first check for valid version and then create triggers
3296 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3297 if (CRM_Core_Config::isUpgradeMode()) {
3298 $currentVer = CRM_Core_BAO_Domain::version(TRUE);
3299 //if current version is less than 4.3.alpha1 dont create below triggers
3300 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3301 return;
3302 }
3303 }
3304
6050e9ad
TO
3305 // Modifications to these records should update the contact timestamps.
3306 \Civi\Core\SqlTrigger\TimestampTriggers::create('civicrm_contact', 'Contact')
3307 ->setRelations(array(
3308 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3309 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3310 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3311 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3312 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3313 )
3314 )
3315 ->alterTriggerInfo($info, $tableName);
6a488035
TO
3316
3317 // Update phone table to populate phone_numeric field
3318 if (!$tableName || $tableName == 'civicrm_phone') {
3319 // Define stored sql function needed for phones
1b31daf6 3320 $sqlTriggers = Civi::service('sql_triggers');
3321 $sqlTriggers->enqueueQuery(self::DROP_STRIP_FUNCTION_43);
3322 $sqlTriggers->enqueueQuery(self::CREATE_STRIP_FUNCTION_43);
6a488035
TO
3323 $info[] = array(
3324 'table' => array('civicrm_phone'),
3325 'when' => 'BEFORE',
3326 'event' => array('INSERT', 'UPDATE'),
3327 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3328 );
3329 }
3330 }
3331
3332 /**
db7de9c1 3333 * Check if contact is being used in civicrm_domain based on $contactId.
6a488035 3334 *
77c5b619
TO
3335 * @param int $contactId
3336 * Contact id.
6a488035 3337 *
a6c01b45
CW
3338 * @return bool
3339 * true if present else false.
6a488035 3340 */
00be9182 3341 public static function checkDomainContact($contactId) {
db7de9c1 3342 if (!$contactId) {
6a488035 3343 return FALSE;
db7de9c1 3344 }
9bb77b8e 3345 $domainId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
6a488035
TO
3346
3347 if ($domainId) {
3348 return TRUE;
9bb77b8e
TO
3349 }
3350 else {
6a488035
TO
3351 return FALSE;
3352 }
3353 }
12445e1c 3354
dc86f881
CW
3355 /**
3356 * Get options for a given contact field.
db7de9c1 3357 *
dc86f881
CW
3358 * @see CRM_Core_DAO::buildOptions
3359 *
3360 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3361 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3362 *
77c5b619
TO
3363 * @param string $fieldName
3364 * @param string $context
63e9c3fd 3365 * @see CRM_Core_DAO::buildOptionsContext
77c5b619 3366 * @param array $props
16b10e64 3367 * whatever is known about this dao object.
77b97be7 3368 *
5c766a0b 3369 * @return array|bool
dc86f881
CW
3370 */
3371 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3372 $params = array();
3373 // Special logic for fields whose options depend on context or properties
3374 switch ($fieldName) {
3375 case 'contact_sub_type':
3376 if (!empty($props['contact_type'])) {
3377 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3378 }
3379 break;
ea100cb5 3380
bee6039a
CW
3381 case 'contact_type':
3382 if ($context == 'search') {
76773c5a
CW
3383 // CRM-15495 - EntityRef filters and basic search forms expect this format
3384 // FIXME: Search builder does not
bee6039a
CW
3385 return CRM_Contact_BAO_ContactType::getSelectElements();
3386 }
3387 break;
985f4890
CW
3388
3389 // The contact api supports some related entities so we'll honor that by fetching their options
3390 case 'group_id':
3391 case 'group':
3392 return CRM_Contact_BAO_GroupContact::buildOptions('group_id', $context, $props);
3393
3394 case 'tag_id':
3395 case 'tag':
3396 $props['entity_table'] = 'civicrm_contact';
3397 return CRM_Core_BAO_EntityTag::buildOptions('tag_id', $context, $props);
3398
3493947a 3399 case 'state_province_id':
d0bfb983 3400 case 'state_province':
3401 case 'state_province_name':
3493947a 3402 case 'country_id':
d0bfb983 3403 case 'country':
3493947a 3404 case 'county_id':
3405 case 'worldregion':
3406 case 'worldregion_id':
3407 return CRM_Core_BAO_Address::buildOptions($fieldName, 'get', $props);
3408
dc86f881 3409 }
786ad6e1 3410 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
dc86f881 3411 }
1071730c 3412
12445e1c 3413 /**
db7de9c1
EM
3414 * Delete a contact-related object that has an 'is_primary' field.
3415 *
12445e1c
CW
3416 * Ensures that is_primary gets assigned to another object if available
3417 * Also calls pre/post hooks
3418 *
f47539f6 3419 * @param string $type
3420 * @param int $id
77b97be7 3421 * @return bool
12445e1c
CW
3422 */
3423 public static function deleteObjectWithPrimary($type, $id) {
3424 if (!$id || !is_numeric($id)) {
a65e2e55 3425 return FALSE;
12445e1c
CW
3426 }
3427 $daoName = "CRM_Core_DAO_$type";
3428 $obj = new $daoName();
3429 $obj->id = $id;
3430 $obj->find();
3431 if ($obj->fetch()) {
3432 CRM_Utils_Hook::pre('delete', $type, $id, CRM_Core_DAO::$_nullArray);
3433 $contactId = $obj->contact_id;
3434 $obj->delete();
3435 }
3436 else {
a65e2e55 3437 return FALSE;
12445e1c 3438 }
50fa40e8
CW
3439 // is_primary is only relavent if this field belongs to a contact
3440 if ($contactId) {
3441 $dao = new $daoName();
3442 $dao->contact_id = $contactId;
3443 $dao->is_primary = 1;
3444 // Pick another record to be primary (if one isn't already)
3445 if (!$dao->find(TRUE)) {
3446 $dao->is_primary = 0;
3447 $dao->find();
3448 if ($dao->fetch()) {
3449 $dao->is_primary = 1;
3450 $dao->save();
3451 }
3452 }
3453 $dao->free();
12445e1c 3454 }
12445e1c
CW
3455 CRM_Utils_Hook::post('delete', $type, $id, $obj);
3456 $obj->free();
a65e2e55 3457 return TRUE;
12445e1c 3458 }
96025800 3459
d343069c
CW
3460 /**
3461 * @inheritDoc
3462 */
20e41014 3463 public function addSelectWhereClause() {
0b80f0b4
CW
3464 // We always return an array with these keys, even if they are empty,
3465 // because this tells the query builder that we have considered these fields for acls
032346cc 3466 $clauses = array(
0b80f0b4
CW
3467 'id' => (array) CRM_Contact_BAO_Contact_Permission::cacheSubquery(),
3468 'is_deleted' => CRM_Core_Permission::check('access deleted contacts') ? array() : array('!= 1'),
b53bcc5d 3469 );
032346cc
CW
3470 CRM_Utils_Hook::selectWhereClause($this, $clauses);
3471 return $clauses;
d343069c
CW
3472 }
3473
fedc3428 3474 /**
3475 * Get any existing duplicate contacts based on the input parameters.
3476 *
3477 * @param array $input
3478 * Input parameters to be matched.
3479 * @param string $contactType
3480 * @param string $rule
3481 * - Supervised
3482 * - Unsupervised
3483 * @param $excludedContactIDs
3484 * An array of ids not to be included in the results.
3485 * @param bool $checkPermissions
3486 * @param int $ruleGroupID
3487 * ID of the rule group to be used if an override is desirable.
3488 *
3489 * @return array
3490 */
3491 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3492 $dedupeParams = CRM_Dedupe_Finder::formatParams($input, $contactType);
3493 $dedupeParams['check_permission'] = $checkPermissions;
3494 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3495 return $ids;
3496 }
3497
3498 /**
3499 * Get the first duplicate contacts based on the input parameters.
3500 *
3501 * @param array $input
3502 * Input parameters to be matched.
3503 * @param string $contactType
3504 * @param string $rule
3505 * - Supervised
3506 * - Unsupervised
3507 * @param $excludedContactIDs
3508 * An array of ids not to be included in the results.
3509 * @param bool $checkPermissions
3510 * @param int $ruleGroupID
3511 * ID of the rule group to be used if an override is desirable.
3512 *
3513 * @return int|NULL
3514 */
3515 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3516 $ids = self::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID);
3517 if (empty($ids)) {
3518 return NULL;
3519 }
3520 return $ids[0];
3521 }
3522
6ebecfea 3523 /**
3524 * Check if a field is associated with an entity that has a location type.
3525 *
3526 * (ie. is an address, phone, email etc field).
3527 *
3528 * @param string $fieldTitle
3529 * Title of the field (not the name - create a new function for that if required).
3530 *
3531 * @return bool
3532 */
3533 public static function isFieldHasLocationType($fieldTitle) {
3534 foreach (CRM_Contact_BAO_Contact::importableFields() as $key => $field) {
3535 if ($field['title'] === $fieldTitle) {
3536 return CRM_Utils_Array::value('hasLocationType', $field);
3537 }
3538 }
3539 return FALSE;
3540 }
3541
6a488035 3542}