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