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