minor tidy ups
[civicrm-core.git] / CRM / Contact / BAO / Contact.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035 32 * $Id$
6a488035
TO
33 */
34class CRM_Contact_BAO_Contact extends CRM_Contact_DAO_Contact {
35
36 /**
37 * SQL function used to format the phone_numeric field via trigger.
38 * @see self::triggerInfo()
39 *
40 * Note that this is also used by the 4.3 upgrade script.
41 * @see CRM_Upgrade_Incremental_php_FourThree
42 */
43 const DROP_STRIP_FUNCTION_43 = "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
44 const CREATE_STRIP_FUNCTION_43 = "
45 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
46 RETURNS VARCHAR(255) CHARACTER SET utf8
47 DETERMINISTIC
48 NO SQL
49 BEGIN
50 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
51 DECLARE iterator INT DEFAULT 1;
52 WHILE iterator < (LENGTH(input) + 1) DO
53 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
54 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
55 END IF;
56 SET iterator = iterator + 1;
57 END WHILE;
58 RETURN output;
59 END";
60
61 /**
100fef9d 62 * The types of communication preferences
6a488035
TO
63 *
64 * @var array
65 */
22f80e87
EM
66 static $_commPrefs = array(
67 'do_not_phone',
68 'do_not_email',
69 'do_not_mail',
70 'do_not_sms',
71 'do_not_trade',
72 );
6a488035
TO
73
74 /**
100fef9d 75 * Types of greetings
6a488035
TO
76 *
77 * @var array
78 */
22f80e87
EM
79 static $_greetingTypes = array(
80 'addressee',
81 'email_greeting',
82 'postal_greeting',
83 );
6a488035
TO
84
85 /**
100fef9d 86 * Static field for all the contact information that we can potentially import
6a488035
TO
87 *
88 * @var array
6a488035
TO
89 */
90 static $_importableFields = array();
91
92 /**
100fef9d 93 * Static field for all the contact information that we can potentially export
6a488035
TO
94 *
95 * @var array
6a488035
TO
96 */
97 static $_exportableFields = NULL;
86538308
EM
98
99 /**
22f80e87 100 * Class constructor.
86538308 101 */
00be9182 102 public function __construct() {
6a488035
TO
103 parent::__construct();
104 }
105
106 /**
22f80e87 107 * Takes an associative array and creates a contact object.
6a488035 108 *
22f80e87 109 * The function extracts all the params it needs to initialize the create a
6a488035
TO
110 * contact object. the params array could contain additional unused name/value
111 * pairs
112 *
77c5b619 113 * @param array $params
22f80e87 114 * (reference) an assoc array of name/value pairs.
6a488035 115 *
22f80e87
EM
116 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
117 * Created or updated contact object or error object.
118 * (error objects are being phased out in favour of exceptions)
6a488035 119 */
00be9182 120 public static function add(&$params) {
6a488035
TO
121 $contact = new CRM_Contact_DAO_Contact();
122
123 if (empty($params)) {
124 return;
125 }
126
22f80e87 127 // Fix for validate contact sub type CRM-5143.
9bb77b8e
TO
128 if (isset($params['contact_sub_type'])) {
129 if (empty($params['contact_sub_type'])) {
6a488035
TO
130 $params['contact_sub_type'] = 'null';
131 }
132 else {
133 if (!CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'],
134 $params['contact_type'], TRUE
9bb77b8e
TO
135 )
136 ) {
6a488035
TO
137 // we'll need to fix tests to handle this
138 // CRM-7925
139 CRM_Core_Error::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
140 }
141 if (is_array($params['contact_sub_type'])) {
142 $params['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['contact_sub_type']) . CRM_Core_DAO::VALUE_SEPARATOR;
143 }
144 else {
145 $params['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . trim($params['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
146 }
147 }
148 }
149 else {
22f80e87
EM
150 // Reset the value.
151 // CRM-101XX.
6a488035
TO
152 $params['contact_sub_type'] = 'null';
153 }
154
22f80e87 155 // Fixed contact source.
6a488035
TO
156 if (isset($params['contact_source'])) {
157 $params['source'] = $params['contact_source'];
158 }
159
22f80e87 160 // Fix for preferred communication method.
6a488035
TO
161 $prefComm = CRM_Utils_Array::value('preferred_communication_method', $params);
162 if ($prefComm && is_array($prefComm)) {
163 unset($params['preferred_communication_method']);
164 $newPref = array();
165
166 foreach ($prefComm as $k => $v) {
167 if ($v) {
168 $newPref[$k] = $v;
169 }
170 }
171
172 $prefComm = $newPref;
173 if (is_array($prefComm) && !empty($prefComm)) {
174 $prefComm = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($prefComm)) . CRM_Core_DAO::VALUE_SEPARATOR;
175 $contact->preferred_communication_method = $prefComm;
176 }
177 else {
178 $contact->preferred_communication_method = '';
179 }
180 }
181
182 $allNull = $contact->copyValues($params);
183
184 $contact->id = CRM_Utils_Array::value('contact_id', $params);
185
186 if ($contact->contact_type == 'Individual') {
187 $allNull = FALSE;
188
22f80e87 189 // Format individual fields.
6a488035
TO
190 CRM_Contact_BAO_Individual::format($params, $contact);
191 }
192 elseif ($contact->contact_type == 'Household') {
193 if (isset($params['household_name'])) {
194 $allNull = FALSE;
195 $contact->display_name = $contact->sort_name = CRM_Utils_Array::value('household_name', $params, '');
196 }
197 }
198 elseif ($contact->contact_type == 'Organization') {
199 if (isset($params['organization_name'])) {
200 $allNull = FALSE;
201 $contact->display_name = $contact->sort_name = CRM_Utils_Array::value('organization_name', $params, '');
202 }
203 }
204
6a488035
TO
205 $privacy = CRM_Utils_Array::value('privacy', $params);
206 if ($privacy &&
207 is_array($privacy) &&
208 !empty($privacy)
209 ) {
210 $allNull = FALSE;
211 foreach (self::$_commPrefs as $name) {
212 $contact->$name = CRM_Utils_Array::value($name, $privacy, FALSE);
213 }
214 }
215
22f80e87
EM
216 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
217 // @todo - does this mean we can remove this block?
218 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
6a488035
TO
219 if ((!array_key_exists('hash', $contact) || !$contact->hash) && !$contact->id) {
220 $allNull = FALSE;
221 $contact->hash = md5(uniqid(rand(), TRUE));
222 }
223
224 // Even if we don't need $employerId, it's important to call getFieldValue() before
225 // the contact is saved because we want the existing value to be cached.
226 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
227 $employerId = empty($contact->id) ? NULL : CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contact->id, 'employer_id');
228
229 if (!$allNull) {
230 $contact->save();
231
232 CRM_Core_BAO_Log::register($contact->id,
233 'civicrm_contact',
234 $contact->id
235 );
236 }
237
fad0497c 238 if ($contact->contact_type == 'Individual' && (isset($params['current_employer']) || isset($params['employer_id']))) {
22f80e87 239 // Create current employer.
f06fc7d2 240 $newEmployer = !empty($params['employer_id']) ? $params['employer_id'] : CRM_Utils_Array::value('current_employer', $params);
241
242 $newContact = FALSE;
243 if (empty($params['contact_id'])) {
244 $newContact = TRUE;
6a488035 245 }
fad0497c 246 if ($newEmployer) {
6eae3162 247 CRM_Contact_BAO_Contact_Utils::createCurrentEmployerRelationship($contact->id, $newEmployer, $employerId, $newContact);
6a488035
TO
248 }
249 else {
6a488035
TO
250 if ($employerId) {
251 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($contact->id, $employerId);
252 }
253 }
254 }
255
22f80e87 256 // Update cached employer name.
6a488035
TO
257 if ($contact->contact_type == 'Organization') {
258 CRM_Contact_BAO_Contact_Utils::updateCurrentEmployer($contact->id);
259 }
260
261 return $contact;
262 }
263
264 /**
22f80e87
EM
265 * Create contact.
266 *
6a488035
TO
267 * takes an associative array and creates a contact object and all the associated
268 * derived objects (i.e. individual, location, email, phone etc)
269 *
270 * This function is invoked from within the web form layer and also from the api layer
271 *
77c5b619
TO
272 * @param array $params
273 * (reference ) an assoc array of name/value pairs.
274 * @param bool $fixAddress
275 * If we need to fix address.
276 * @param bool $invokeHooks
277 * If we need to invoke hooks.
6a488035 278 *
d9f93da9 279 * @param bool $skipDelete
22f80e87
EM
280 * Unclear parameter, passed to website create
281 *
282 * @todo explain this parameter
d9f93da9
EM
283 *
284 * @throws Exception
22f80e87
EM
285 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
286 * Created or updated contribution object. We are deprecating returning an error in
287 * favour of exceptions
6a488035 288 */
00be9182 289 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
9bb77b8e
TO
290 $contact = NULL;
291 if (empty($params['contact_type']) && empty($params['contact_id'])) {
292 return $contact;
293 }
6a488035 294
9bb77b8e
TO
295 $isEdit = TRUE;
296 if ($invokeHooks) {
297 if (!empty($params['contact_id'])) {
298 CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
299 }
300 else {
301 CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
302 $isEdit = FALSE;
6a488035 303 }
9bb77b8e 304 }
6a488035 305
9bb77b8e 306 $config = CRM_Core_Config::singleton();
6a488035 307
22f80e87 308 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
9bb77b8e
TO
309 if (empty($params['contact_id']) && empty($params['preferred_language'])) {
310 $params['preferred_language'] = $config->lcMessages;
311 }
6a488035 312
22f80e87 313 // CRM-9739: set greeting & addressee if unset and we’re creating a contact.
9bb77b8e
TO
314 if (empty($params['contact_id'])) {
315 foreach (self::$_greetingTypes as $greeting) {
316 if (empty($params[$greeting . '_id'])) {
22f80e87
EM
317 if ($defaultGreetingTypeId
318 = CRM_Contact_BAO_Contact_Utils::defaultGreeting($params['contact_type'], $greeting)
9bb77b8e
TO
319 ) {
320 $params[$greeting . '_id'] = $defaultGreetingTypeId;
6a488035
TO
321 }
322 }
323 }
9bb77b8e 324 }
6a488035 325
9bb77b8e 326 $transaction = new CRM_Core_Transaction();
6a488035 327
9bb77b8e
TO
328 $contact = self::add($params);
329 if (!$contact) {
22f80e87 330 // Not dying here is stupid, since we get into wierd situation and into a bug that
9bb77b8e
TO
331 // is impossible to figure out for the user or for us
332 // CRM-7925
333 CRM_Core_Error::fatal();
334 }
6a488035 335
9bb77b8e 336 $params['contact_id'] = $contact->id;
6a488035 337
9bb77b8e 338 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME, 'is_enabled')) {
22f80e87 339 // Enabling multisite causes the contact to be added to the domain group.
9bb77b8e
TO
340 $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
341 if (!empty($domainGroupID)) {
342 if (!empty($params['group']) && is_array($params['group'])) {
343 $params['group'][$domainGroupID] = 1;
6a488035 344 }
9bb77b8e
TO
345 else {
346 $params['group'] = array($domainGroupID => 1);
6a488035
TO
347 }
348 }
9bb77b8e 349 }
6a488035 350
9bb77b8e
TO
351 if (array_key_exists('group', $params)) {
352 $contactIds = array($params['contact_id']);
353 foreach ($params['group'] as $groupId => $flag) {
354 if ($flag == 1) {
355 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
356 }
357 elseif ($flag == -1) {
358 CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $groupId);
359 }
6a488035 360 }
9bb77b8e 361 }
6a488035 362
22f80e87 363 // Add location Block data.
9bb77b8e
TO
364 $blocks = CRM_Core_BAO_Location::create($params, $fixAddress);
365 foreach ($blocks as $name => $value) {
366 $contact->$name = $value;
367 }
6a488035 368
9bb77b8e
TO
369 //add website
370 CRM_Core_BAO_Website::create($params['website'], $contact->id, $skipDelete);
6a488035 371
9bb77b8e
TO
372 //get userID from session
373 $session = CRM_Core_Session::singleton();
374 $userID = $session->get('userID');
375 // add notes
376 if (!empty($params['note'])) {
377 if (is_array($params['note'])) {
378 foreach ($params['note'] as $note) {
6a488035
TO
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 }
387
388 $noteParams = array(
389 'entity_id' => $contact->id,
390 'entity_table' => 'civicrm_contact',
9bb77b8e
TO
391 'note' => $note['note'],
392 'subject' => CRM_Utils_Array::value('subject', $note),
6a488035
TO
393 'contact_id' => $contactId,
394 );
395 CRM_Core_BAO_Note::add($noteParams, CRM_Core_DAO::$_nullArray);
396 }
397 }
9bb77b8e
TO
398 else {
399 $contactId = $contact->id;
400 if (isset($note['contact_id'])) {
401 $contactId = $note['contact_id'];
402 }
403 //if logged in user, overwrite contactId
404 if ($userID) {
405 $contactId = $userID;
406 }
6a488035 407
9bb77b8e
TO
408 $noteParams = array(
409 'entity_id' => $contact->id,
410 'entity_table' => 'civicrm_contact',
411 'note' => $params['note'],
412 'subject' => CRM_Utils_Array::value('subject', $params),
413 'contact_id' => $contactId,
6a488035 414 );
9bb77b8e 415 CRM_Core_BAO_Note::add($noteParams, CRM_Core_DAO::$_nullArray);
6a488035 416 }
9bb77b8e 417 }
6a488035 418
9bb77b8e
TO
419 // update the UF user_unique_id if that has changed
420 CRM_Core_BAO_UFMatch::updateUFName($contact->id);
421
422 if (!empty($params['custom']) &&
423 is_array($params['custom'])
424 ) {
425 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contact', $contact->id);
426 }
427
428 // make a civicrm_subscription_history entry only on contact create (CRM-777)
429 if (empty($params['contact_id'])) {
430 $subscriptionParams = array(
431 'contact_id' => $contact->id,
432 'status' => 'Added',
433 'method' => 'Admin',
6a488035 434 );
9bb77b8e
TO
435 CRM_Contact_BAO_SubscriptionHistory::create($subscriptionParams);
436 }
6a488035 437
9bb77b8e 438 $transaction->commit();
6a488035 439
9bb77b8e
TO
440 // CRM-6367: fetch the right label for contact type’s display
441 $contact->contact_type_display = CRM_Core_DAO::getFieldValue(
442 'CRM_Contact_DAO_ContactType',
443 $contact->contact_type,
444 'label',
445 'name'
446 );
447
448 if (!$config->doNotResetCache) {
449 // Note: doNotResetCache flag is currently set by import contact process and merging,
450 // since resetting and
451 // rebuilding cache could be expensive (for many contacts). We might come out with better
452 // approach in future.
453 CRM_Contact_BAO_Contact_Utils::clearContactCaches($contact->id);
454 }
455
456 if ($invokeHooks) {
457 if ($isEdit) {
458 CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
459 }
460 else {
461 CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
6a488035 462 }
9bb77b8e 463 }
6a488035 464
9bb77b8e
TO
465 // process greetings CRM-4575, cache greetings
466 self::processGreetings($contact);
6a488035 467
9bb77b8e 468 return $contact;
6a488035
TO
469 }
470
471 /**
22f80e87 472 * Get the display name and image of a contact.
6a488035 473 *
77c5b619
TO
474 * @param int $id
475 * The contactId.
6a488035 476 *
22f80e87
EM
477 * @param bool $includeTypeInReturnParameters
478 * Should type be part of the returned array?
d9f93da9 479 *
a6c01b45
CW
480 * @return array
481 * the displayName and contactImage for this contact
6a488035 482 */
22f80e87 483 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
95fec3ce 484 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
250b3b1f 485 $sql = "
95fec3ce 486SELECT civicrm_contact.*,
6a488035
TO
487 civicrm_email.email as email
488FROM civicrm_contact
489LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
490 AND civicrm_email.is_primary = 1
491WHERE civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
492 $dao = new CRM_Core_DAO();
493 $dao->query($sql);
494 if ($dao->fetch()) {
495 $image = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
250b3b1f 496 $dao->contact_sub_type : $dao->contact_type, FALSE, $id
6a488035
TO
497 );
498 $imageUrl = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
250b3b1f 499 $dao->contact_sub_type : $dao->contact_type, TRUE, $id
6a488035
TO
500 );
501
502 // use email if display_name is empty
503 if (empty($dao->display_name)) {
250b3b1f 504 $displayName = $dao->email;
505 }
506 else {
507 $displayName = $dao->display_name;
508 }
509
510 CRM_Utils_Hook::alterDisplayName($displayName, $id, $dao);
95fec3ce 511
22f80e87 512 return $includeTypeInReturnParameters ? array(
967fddb5 513 $displayName,
250b3b1f 514 $image,
515 $dao->contact_type,
516 $dao->contact_sub_type,
517 $imageUrl,
967fddb5 518 ) : array($displayName, $image, $imageUrl);
6a488035
TO
519 }
520 return NULL;
521 }
522
688ad538 523 /**
22f80e87
EM
524 * Create last viewed link to recently updated contact.
525 *
77c5b619 526 * @param array $crudLinkSpec
55d2c6f1
EM
527 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
528 * - entity_table: string, eg "civicrm_contact"
529 * - entity_id: int
530 *
72b3a70c 531 * @return array|NULL
16b10e64
CW
532 * NULL if unavailable, or
533 * [path: string, query: string, title: string]
688ad538
TO
534 * @see CRM_Utils_System::createDefaultCrudLink
535 */
536 public function createDefaultCrudLink($crudLinkSpec) {
537 switch ($crudLinkSpec['action']) {
538 case CRM_Core_Action::VIEW:
5c9ff055 539
688ad538
TO
540 return array(
541 'title' => $this->display_name,
542 'path' => 'civicrm/contact/view',
543 'query' => array(
544 'reset' => 1,
545 'cid' => $this->id,
546 ),
547 );
ea100cb5 548
688ad538
TO
549 case CRM_Core_Action::UPDATE:
550 return array(
551 'title' => $this->display_name,
552 'path' => 'civicrm/contact/add',
553 'query' => array(
554 'reset' => 1,
555 'action' => 'update',
556 'cid' => $this->id,
557 ),
558 );
559 }
560 return NULL;
561 }
562
6a488035 563 /**
6a488035
TO
564 * Get the values for pseudoconstants for name->value and reverse.
565 *
77c5b619
TO
566 * @param array $defaults
567 * (reference) the default values, some of which need to be resolved.
568 * @param bool $reverse
569 * True if we want to resolve the values in the reverse direction (value -> name).
6a488035 570 */
00be9182 571 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
22f80e87 572 // Hack for birth_date.
a7488080 573 if (!empty($defaults['birth_date'])) {
6a488035
TO
574 if (is_array($defaults['birth_date'])) {
575 $defaults['birth_date'] = CRM_Utils_Date::format($defaults['birth_date'], '-');
576 }
577 }
578
e6c4755b
CW
579 CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
580 CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
26cf88b5 581 CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
aa62b355 582 CRM_Utils_Array::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
6a488035
TO
583
584 //lookup value of email/postal greeting, addressee, CRM-4575
585 foreach (self::$_greetingTypes as $greeting) {
9bb77b8e
TO
586 $filterCondition = array(
587 'contact_type' => CRM_Utils_Array::value('contact_type', $defaults),
6a488035
TO
588 'greeting_type' => $greeting,
589 );
590 CRM_Utils_Array::lookupValue($defaults, $greeting,
591 CRM_Core_PseudoConstant::greeting($filterCondition), $reverse
592 );
593 }
594
595 $blocks = array('address', 'im', 'phone');
596 foreach ($blocks as $name) {
597 if (!array_key_exists($name, $defaults) || !is_array($defaults[$name])) {
598 continue;
599 }
600 foreach ($defaults[$name] as $count => & $values) {
601
602 //get location type id.
b2b0530a 603 CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
6a488035
TO
604
605 if ($name == 'address') {
606 // FIXME: lookupValue doesn't work for vcard_name
a7488080 607 if (!empty($values['location_type_id'])) {
8f785c9e 608 $vcardNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
6a488035
TO
609 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
610 }
611
612 if (!CRM_Utils_Array::lookupValue($values,
613 'country',
614 CRM_Core_PseudoConstant::country(),
615 $reverse
616 ) &&
617 $reverse
618 ) {
619 CRM_Utils_Array::lookupValue($values,
620 'country',
621 CRM_Core_PseudoConstant::countryIsoCode(),
622 $reverse
623 );
624 }
625
626 // CRM-7597
627 // if we find a country id above, we need to restrict it to that country
628 // rather than the list of all countries
629
630 if (!empty($values['country_id'])) {
631 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($values['country_id']);
632 }
633 else {
634 $stateProvinceList = CRM_Core_PseudoConstant::stateProvince();
635 }
636 if (!CRM_Utils_Array::lookupValue($values,
637 'state_province',
638 $stateProvinceList,
639 $reverse
640 ) &&
641 $reverse
642 ) {
643
644 if (!empty($values['country_id'])) {
645 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($values['country_id'], 'abbreviation');
646 }
647 else {
648 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
649 }
650 CRM_Utils_Array::lookupValue($values,
651 'state_province',
652 $stateProvinceList,
653 $reverse
654 );
655 }
656
657 if (!empty($values['state_province_id'])) {
658 $countyList = CRM_Core_PseudoConstant::countyForState($values['state_province_id']);
659 }
660 else {
661 $countyList = CRM_Core_PseudoConstant::county();
662 }
663 CRM_Utils_Array::lookupValue($values,
664 'county',
665 $countyList,
666 $reverse
667 );
668 }
669
670 if ($name == 'im') {
671 CRM_Utils_Array::lookupValue($values,
672 'provider',
e7e657f0 673 CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
6a488035
TO
674 $reverse
675 );
676 }
677
678 if ($name == 'phone') {
679 CRM_Utils_Array::lookupValue($values,
680 'phone_type',
b4f964d9 681 CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
6a488035
TO
682 $reverse
683 );
684 }
685
22f80e87 686 // Kill the reference.
6a488035
TO
687 unset($values);
688 }
689 }
690 }
691
692 /**
0965e988 693 * Fetch object based on array of properties.
6a488035 694 *
77c5b619
TO
695 * @param array $params
696 * (reference ) an assoc array of name/value pairs.
697 * @param array $defaults
698 * (reference ) an assoc array to hold the name / value pairs.
6a488035 699 * in a hierarchical manner
77c5b619
TO
700 * @param bool $microformat
701 * For location in microformat.
6a488035 702 *
16b10e64 703 * @return CRM_Contact_BAO_Contact
6a488035 704 */
00be9182 705 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
6a488035
TO
706 if (array_key_exists('contact_id', $params)) {
707 $params['id'] = $params['contact_id'];
708 }
709 elseif (array_key_exists('id', $params)) {
710 $params['contact_id'] = $params['id'];
711 }
712
713 $contact = self::getValues($params, $defaults);
714
715 unset($params['id']);
716
717 //get the block information for this contact
718 $entityBlock = array('contact_id' => $params['contact_id']);
9bb77b8e
TO
719 $blocks = CRM_Core_BAO_Location::getValues($entityBlock, $microformat);
720 $defaults = array_merge($defaults, $blocks);
721 foreach ($blocks as $block => $value) {
722 $contact->$block = $value;
723 }
6a488035
TO
724
725 if (!isset($params['noNotes'])) {
726 $contact->notes = CRM_Core_BAO_Note::getValues($params, $defaults);
727 }
728
729 if (!isset($params['noRelationships'])) {
730 $contact->relationship = CRM_Contact_BAO_Relationship::getValues($params, $defaults);
731 }
732
733 if (!isset($params['noGroups'])) {
734 $contact->groupContact = CRM_Contact_BAO_GroupContact::getValues($params, $defaults);
735 }
736
737 if (!isset($params['noWebsite'])) {
738 $contact->website = CRM_Core_BAO_Website::getValues($params, $defaults);
739 }
740
741 return $contact;
742 }
743
744 /**
0965e988 745 * Get the display name of a contact.
6a488035 746 *
77c5b619
TO
747 * @param int $id
748 * Id of the contact.
6a488035 749 *
72b3a70c
CW
750 * @return null|string
751 * display name of the contact if found
6a488035 752 */
00be9182 753 public static function displayName($id) {
6a488035
TO
754 $displayName = NULL;
755 if ($id) {
756 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
757 }
758
759 return $displayName;
760 }
761
762 /**
55d2c6f1 763 * Delete a contact and all its associated records.
6a488035 764 *
77c5b619
TO
765 * @param int $id
766 * Id of the contact to delete.
767 * @param bool $restore
768 * Whether to actually restore, not delete.
769 * @param bool $skipUndelete
770 * Whether to force contact delete or not.
6a488035 771 *
55d2c6f1
EM
772 * @return bool
773 * Was contact deleted?
6a488035 774 */
00be9182 775 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) {
6a488035
TO
776
777 if (!$id) {
778 return FALSE;
779 }
780
781 // make sure we have edit permission for this contact
782 // before we delete
783 if (($skipUndelete && !CRM_Core_Permission::check('delete contacts')) ||
784 ($restore && !CRM_Core_Permission::check('access deleted contacts'))
785 ) {
786 return FALSE;
787 }
2efcf0c2 788
f182074e
PN
789 // CRM-12929
790 // Restrict contact to be delete if contact has financial trxns
791 $error = NULL;
792 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($id), $error)) {
793 return FALSE;
794 }
6a488035
TO
795
796 // make sure this contact_id does not have any membership types
797 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
798 $id,
799 'id',
800 'member_of_contact_id'
801 );
802 if ($membershipTypeID) {
803 return FALSE;
804 }
805
806 $contact = new CRM_Contact_DAO_Contact();
807 $contact->id = $id;
808 if (!$contact->find(TRUE)) {
809 return FALSE;
810 }
811
812 $contactType = $contact->contact_type;
813 $action = ($restore) ? 'restore' : 'delete';
814
815 CRM_Utils_Hook::pre($action, $contactType, $id, CRM_Core_DAO::$_nullArray);
816
817 if ($restore) {
818 self::contactTrashRestore($contact, TRUE);
819 CRM_Utils_Hook::post($action, $contactType, $contact->id, $contact);
820 return TRUE;
821 }
822
6a488035
TO
823 // currently we only clear employer cache.
824 // we are not deleting inherited membership if any.
825 if ($contact->contact_type == 'Organization') {
826 CRM_Contact_BAO_Contact_Utils::clearAllEmployee($id);
827 }
828
829 // start a new transaction
830 $transaction = new CRM_Core_Transaction();
831
832 if ($skipUndelete or !CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_undelete', NULL)) {
833
834 //delete billing address if exists.
835 CRM_Contribute_BAO_Contribution::deleteAddress(NULL, $id);
836
837 // delete the log entries since we dont have triggers enabled as yet
838 $logDAO = new CRM_Core_DAO_Log();
839 $logDAO->entity_table = 'civicrm_contact';
840 $logDAO->entity_id = $id;
841 $logDAO->delete();
1071730c 842
c3d24ba7
PN
843 // delete contact participants CRM-12155
844 CRM_Event_BAO_Participant::deleteContactParticipant($id);
6a488035 845
c3d24ba7
PN
846 // delete contact contributions CRM-12155
847 CRM_Contribute_BAO_Contribution::deleteContactContribution($id);
1071730c 848
6a488035
TO
849 // do activity cleanup, CRM-5604
850 CRM_Activity_BAO_Activity::cleanupActivity($id);
851
852 // delete all notes related to contact
853 CRM_Core_BAO_Note::cleanContactNotes($id);
854
55033e60
PJ
855 // delete cases related to contact
856 $contactCases = CRM_Case_BAO_Case::retrieveCaseIdsByContactId($id);
857 if (!empty($contactCases)) {
d3b60a94 858 foreach ($contactCases as $caseId) {
55033e60
PJ
859 //check if case is associate with other contact or not.
860 $caseContactId = CRM_Case_BAO_Case::getCaseClients($caseId);
d3b60a94 861 if (count($caseContactId) <= 1) {
55033e60
PJ
862 CRM_Case_BAO_Case::deleteCase($caseId);
863 }
864 }
865 }
866
6a488035
TO
867 $contact->delete();
868 }
869 else {
870 self::contactTrashRestore($contact);
871 }
872
873 //delete the contact id from recently view
874 CRM_Utils_Recent::delContact($id);
875
2c6bbd06
CW
876 // Update the group contact cache
877 if ($restore) {
878 CRM_Contact_BAO_GroupContactCache::remove();
879 }
880 else {
881 CRM_Contact_BAO_GroupContactCache::removeContact($id);
882 }
6a488035
TO
883
884 // delete any dupe cache entry
885 CRM_Core_BAO_PrevNextCache::deleteItem($id);
886
887 $transaction->commit();
888
889 CRM_Utils_Hook::post('delete', $contactType, $contact->id, $contact);
890
891 // also reset the DB_DO global array so we can reuse the memory
892 // http://issues.civicrm.org/jira/browse/CRM-4387
893 CRM_Core_DAO::freeResult();
894
895 return TRUE;
896 }
897
898 /**
55d2c6f1 899 * Delete the image of a contact.
6a488035 900 *
77c5b619
TO
901 * @param int $id
902 * Id of the contact.
6a488035 903 *
55d2c6f1
EM
904 * @return bool
905 * Was contact image deleted?
6a488035
TO
906 */
907 public static function deleteContactImage($id) {
908 if (!$id) {
909 return FALSE;
910 }
911 $query = "
912UPDATE civicrm_contact
913SET image_URL=NULL
914WHERE id={$id}; ";
915 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
916 return TRUE;
917 }
918
919 /**
0965e988
EM
920 * Return relative path.
921 *
6a488035
TO
922 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
923 *
77c5b619
TO
924 * @param string $absolutePath
925 * Absolute path.
6a488035 926 *
0965e988 927 * @return string
a6c01b45 928 * Relative url of uploaded image
6a488035
TO
929 */
930 public static function getRelativePath($absolutePath) {
931 $relativePath = NULL;
932 $config = CRM_Core_Config::singleton();
933 if ($config->userFramework == 'Joomla') {
934 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL));
935 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
936 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
937 }
938 elseif ($config->userSystem->is_drupal == '1') {
939 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
940 $rootPath = $config->userSystem->cmsRootPath();
941 $baseUrl = $config->userFrameworkBaseURL;
942
943 //format url for language negotiation, CRM-7135
944 $baseUrl = CRM_Utils_System::languageNegotiationURL($baseUrl, FALSE, TRUE);
945
946 $relativePath = str_replace("{$rootPath}/",
947 $baseUrl,
948 str_replace('\\', '/', $absolutePath)
949 );
9bb77b8e 950 }
4c9b6178 951 elseif ($config->userFramework == 'WordPress') {
9bb77b8e
TO
952 $userFrameworkBaseURL = trim(str_replace('/wp-admin/', '', $config->userFrameworkBaseURL));
953 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/wp-content/');
954 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
6a488035
TO
955 }
956
957 return $relativePath;
958 }
959
960 /**
0965e988 961 * Return proportional height and width of the image.
6a488035 962 *
df8d3074 963 * @param int $imageWidth
77c5b619 964 * Width of image.
6a488035 965 *
df8d3074 966 * @param int $imageHeight
77c5b619 967 * Height of image.
6a488035 968 *
0965e988
EM
969 * @return array
970 * Thumb dimension of image
6a488035
TO
971 */
972 public static function getThumbSize($imageWidth, $imageHeight) {
973 $thumbWidth = 100;
974 if ($imageWidth && $imageHeight) {
975 $imageRatio = $imageWidth / $imageHeight;
976 }
977 else {
978 $imageRatio = 1;
979 }
980 if ($imageRatio > 1) {
981 $imageThumbWidth = $thumbWidth;
982 $imageThumbHeight = round($thumbWidth / $imageRatio);
983 }
984 else {
985 $imageThumbHeight = $thumbWidth;
986 $imageThumbWidth = round($thumbWidth * $imageRatio);
987 }
988
989 return array($imageThumbWidth, $imageThumbHeight);
990 }
991
992 /**
0965e988 993 * Validate type of contact image.
6a488035 994 *
c490a46a 995 * @param array $params
d3e86119 996 * @param string $imageIndex
77c5b619 997 * Index of image field.
d3e86119 998 * @param string $statusMsg
77c5b619
TO
999 * Status message to be set after operation.
1000 * @param string $opType
1001 * Type of operation like fatal, bounce etc.
6a488035 1002 *
0965e988 1003 * @return bool
a6c01b45 1004 * true if valid image extension
6a488035 1005 */
9bb77b8e
TO
1006 public static function processImageParams(
1007 &$params,
6a488035 1008 $imageIndex = 'image_URL',
9bb77b8e
TO
1009 $statusMsg = NULL,
1010 $opType = 'status'
6a488035
TO
1011 ) {
1012 $mimeType = array(
1013 'image/jpeg',
1014 'image/jpg',
1015 'image/png',
1016 'image/bmp',
1017 'image/p-jpeg',
1018 'image/gif',
1019 'image/x-png',
1020 );
1021
1022 if (in_array($params[$imageIndex]['type'], $mimeType)) {
5da97e99 1023 $photo = basename($params[$imageIndex]['name']);
9bb77b8e 1024 $params[$imageIndex] = CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
6a488035
TO
1025 return TRUE;
1026 }
1027 else {
1028 unset($params[$imageIndex]);
1029 if (!$statusMsg) {
1030 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1031 }
1032 if ($opType == 'status') {
1033 CRM_Core_Session::setStatus($statusMsg, 'Sorry', 'error');
1034 }
1035 // FIXME: additional support for fatal, bounce etc could be added.
1036 return FALSE;
1037 }
1038 }
1039
1040 /**
0965e988 1041 * Extract contact id from url for deleting contact image.
6a488035
TO
1042 */
1043 public static function processImage() {
1044
1050d25c
CW
1045 $action = CRM_Utils_Request::retrieve('action', 'String');
1046 $cid = CRM_Utils_Request::retrieve('cid', 'Positive');
6a488035 1047 // retrieve contact id in case of Profile context
1050d25c 1048 $id = CRM_Utils_Request::retrieve('id', 'Positive');
6a488035
TO
1049 $cid = $cid ? $cid : $id;
1050 if ($action & CRM_Core_Action::DELETE) {
1050d25c 1051 if (CRM_Utils_Request::retrieve('confirmed', 'Boolean')) {
6a488035
TO
1052 CRM_Contact_BAO_Contact::deleteContactImage($cid);
1053 CRM_Core_Session::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1054 $session = CRM_Core_Session::singleton();
1055 $toUrl = $session->popUserContext();
1056 CRM_Utils_System::redirect($toUrl);
1057 }
1058 }
1059 }
1060
1061 /**
0965e988 1062 * Function to set is_delete true or restore deleted contact.
6a488035 1063 *
d3e86119
TO
1064 * @param int $contact
1065 * Contact DAO object.
1066 * @param bool $restore
1067 * True to set the is_delete = 1 else false to restore deleted contact,
6a488035 1068 * i.e. is_delete = 0
6a488035 1069 */
00be9182 1070 public static function contactTrashRestore($contact, $restore = FALSE) {
6a488035
TO
1071 $op = ($restore ? 'restore' : 'trash');
1072
1073 CRM_Utils_Hook::pre($op, $contact->contact_type, $contact->id, CRM_Core_DAO::$_nullArray);
1074
1075 $params = array(1 => array($contact->id, 'Integer'));
1076 $isDelete = ' is_deleted = 1 ';
1077 if ($restore) {
1078 $isDelete = ' is_deleted = 0 ';
1079 }
1080 else {
1081 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1082 CRM_Core_DAO::executeQuery($query, $params);
1083 }
1084
1085 $query = "UPDATE civicrm_contact SET {$isDelete} WHERE id = %1";
1086 CRM_Core_DAO::executeQuery($query, $params);
1087
1088 CRM_Utils_Hook::post($op, $contact->contact_type, $contact->id, $contact);
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 *
dd244018
EM
1110 * @param null $implodeDelimiter
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
1121 $subtype = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($subtype, CRM_Core_DAO::VALUE_SEPARATOR));
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) {
6a488035 1149 $contactTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($contact->contact_sub_type, CRM_Core_DAO::VALUE_SEPARATOR));
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 */
00be9182 1380 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
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,
b4a3b6b9 1473 CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord)
6a488035
TO
1474 );
1475 }
1476 else {
1477 foreach (array(
9bb77b8e
TO
1478 'Individual',
1479 'Household',
21dfd5f5 1480 'Organization',
9bb77b8e 1481 ) as $type) {
6a488035
TO
1482 $fields = array_merge($fields,
1483 CRM_Core_BAO_CustomField::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1484 );
1485 }
1486 }
1487
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.
6a488035 1627 $returnProperties['first_name'] =
9bb77b8e
TO
1628 $returnProperties['organization_name'] =
1629 $returnProperties['household_name'] =
1630 $returnProperties['contact_type'] =
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 }
1854
1855 if ($contactID) {
1856 $editHook = TRUE;
1857 CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params);
1858 }
1859 else {
1860 $editHook = FALSE;
1861 CRM_Utils_Hook::pre('create', 'Profile', NULL, $params);
1862 }
1863
1864 list($data, $contactDetails) = self::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1865
1866 // manage is_opt_out
1867 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
9bb77b8e
TO
1868 $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, FALSE);
1869 $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
6a488035
TO
1870 $data['is_opt_out'] = $isOptOut;
1871 // on change, create new civicrm_subscription_history entry
8cc574cf 1872 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
6a488035
TO
1873 $shParams = array(
1874 'contact_id' => $contactDetails['contact_id'],
1875 'status' => $isOptOut ? 'Removed' : 'Added',
1876 'method' => 'Web',
1877 );
1878 CRM_Contact_BAO_SubscriptionHistory::create($shParams);
1879 }
1880 }
1881
1882 $contact = self::create($data);
1883
1884 // contact is null if the profile does not have any contact fields
1885 if ($contact) {
1886 $contactID = $contact->id;
1887 }
1888
1889 if (empty($contactID)) {
1890 CRM_Core_Error::fatal('Cannot proceed without a valid contact id');
1891 }
1892
1893 // Process group and tag
a7488080 1894 if (!empty($fields['group'])) {
6a488035
TO
1895 $method = 'Admin';
1896 // this for sure means we are coming in via profile since i added it to fix
1897 // removing contacts from user groups -- lobo
1898 if ($visibility) {
1899 $method = 'Web';
1900 }
1901 CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method);
1902 }
1903
a7488080 1904 if (!empty($fields['tag'])) {
6a488035
TO
1905 CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $contactID);
1906 }
1907
1908 //to add profile in default group
1909 if (is_array($addToGroupID)) {
1910 $contactIds = array($contactID);
1911 foreach ($addToGroupID as $groupId) {
1912 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
1913 }
1914 }
1915 elseif ($addToGroupID) {
1916 $contactIds = array($contactID);
1917 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID);
1918 }
1919
1920 // reset the group contact cache for this group
1921 CRM_Contact_BAO_GroupContactCache::remove();
1922
1923 if ($editHook) {
1924 CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params);
1925 }
1926 else {
1927 CRM_Utils_Hook::post('create', 'Profile', $contactID, $params);
1928 }
1929 return $contactID;
1930 }
1931
86538308 1932 /**
57507ae6
EM
1933 * Format profile contact parameters.
1934 *
c490a46a 1935 * @param array $params
86538308 1936 * @param $fields
100fef9d
CW
1937 * @param int $contactID
1938 * @param int $ufGroupId
86538308
EM
1939 * @param null $ctype
1940 * @param bool $skipCustom
1941 *
1942 * @return array
1943 */
57507ae6 1944 public static function formatProfileContactParams(
6a488035
TO
1945 &$params,
1946 &$fields,
1947 $contactID = NULL,
1948 $ufGroupId = NULL,
1949 $ctype = NULL,
1950 $skipCustom = FALSE
1951 ) {
1952
1953 $data = $contactDetails = array();
1954
1955 // get the contact details (hier)
1956 if ($contactID) {
1957 list($details, $options) = self::getHierContactDetails($contactID, $fields);
1958
1959 $contactDetails = $details[$contactID];
1960 $data['contact_type'] = CRM_Utils_Array::value('contact_type', $contactDetails);
1961 $data['contact_sub_type'] = CRM_Utils_Array::value('contact_sub_type', $contactDetails);
1962 }
1963 else {
1964 //we should get contact type only if contact
1965 if ($ufGroupId) {
1966 $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId);
1967
1968 //special case to handle profile with only contact fields
1969 if ($data['contact_type'] == 'Contact') {
1970 $data['contact_type'] = 'Individual';
1971 }
1972 elseif (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) {
1973 $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']);
1974 }
1975 }
1976 elseif ($ctype) {
1977 $data['contact_type'] = $ctype;
1978 }
1979 else {
1980 $data['contact_type'] = 'Individual';
1981 }
1982 }
1983
1984 //fix contact sub type CRM-5125
1985 if (array_key_exists('contact_sub_type', $params) &&
1986 !empty($params['contact_sub_type'])
1987 ) {
9bb77b8e 1988 $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, (array) $params['contact_sub_type']) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
1989 }
1990 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1991 !empty($params['contact_sub_type_hidden'])
1992 ) {
1993 // if profile was used, and had any subtype, we obtain it from there
9bb77b8e 1994 $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, (array) $params['contact_sub_type_hidden']) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
1995 }
1996
1997 if ($ctype == 'Organization') {
1998 $data['organization_name'] = CRM_Utils_Array::value('organization_name', $contactDetails);
1999 }
2000 elseif ($ctype == 'Household') {
2001 $data['household_name'] = CRM_Utils_Array::value('household_name', $contactDetails);
2002 }
2003
2004 $locationType = array();
2005 $count = 1;
2006
2007 if ($contactID) {
2008 //add contact id
2009 $data['contact_id'] = $contactID;
2010 $primaryLocationType = self::getPrimaryLocationType($contactID);
2011 }
2012 else {
2013 $defaultLocation = CRM_Core_BAO_LocationType::getDefault();
2014 $defaultLocationId = $defaultLocation->id;
2015 }
2016
2017 // get the billing location type
180409a4 2018 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
6a488035
TO
2019 $billingLocationTypeId = array_search('Billing', $locationTypes);
2020
2021 $blocks = array('email', 'phone', 'im', 'openid');
2022
2023 $multiplFields = array('url');
2024 // prevent overwritten of formatted array, reset all block from
2025 // params if it is not in valid format (since import pass valid format)
2026 foreach ($blocks as $blk) {
2027 if (array_key_exists($blk, $params) &&
2028 !is_array($params[$blk])
2029 ) {
2030 unset($params[$blk]);
2031 }
2032 }
2033
2034 $primaryPhoneLoc = NULL;
ece0bc24 2035 $session = CRM_Core_Session::singleton();
6a488035
TO
2036 foreach ($params as $key => $value) {
2037 $fieldName = $locTypeId = $typeId = NULL;
2038 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3);
2039
2040 //store original location type id
2041 $actualLocTypeId = $locTypeId;
2042
2043 if ($locTypeId == 'Primary') {
2044 if ($contactID) {
9bb77b8e 2045 if (in_array($fieldName, $blocks)) {
6a488035
TO
2046 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, $fieldName);
2047 }
9bb77b8e 2048 else {
6a488035
TO
2049 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, 'address');
2050 }
2051 $primaryLocationType = $locTypeId;
2052 }
2053 else {
2054 $locTypeId = $defaultLocationId;
2055 }
2056 }
2057
2058 if (is_numeric($locTypeId) &&
2059 !in_array($fieldName, $multiplFields) &&
2060 substr($fieldName, 0, 7) != 'custom_'
2061 ) {
2062 $index = $locTypeId;
2063
2064 if (is_numeric($typeId)) {
2065 $index .= '-' . $typeId;
2066 }
2067 if (!in_array($index, $locationType)) {
2068 $locationType[$count] = $index;
2069 $count++;
2070 }
2071
2072 $loc = CRM_Utils_Array::key($index, $locationType);
2073
9bb77b8e 2074 $blockName = in_array($fieldName, $blocks) ? $fieldName : 'address';
6a488035
TO
2075
2076 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2077
2078 //set is_billing true, for location type "Billing"
2079 if ($locTypeId == $billingLocationTypeId) {
2080 $data[$blockName][$loc]['is_billing'] = 1;
2081 }
2082
2083 if ($contactID) {
2084 //get the primary location type
2085 if ($locTypeId == $primaryLocationType) {
2086 $data[$blockName][$loc]['is_primary'] = 1;
2087 }
2088 }
2089 elseif ($locTypeId == $defaultLocationId) {
2090 $data[$blockName][$loc]['is_primary'] = 1;
2091 }
2092
9bb77b8e 2093 if (in_array($fieldName, array('phone'))) {
6a488035
TO
2094 if ($typeId) {
2095 $data['phone'][$loc]['phone_type_id'] = $typeId;
2096 }
2097 else {
2098 $data['phone'][$loc]['phone_type_id'] = '';
2099 }
2100 $data['phone'][$loc]['phone'] = $value;
2101
2102 //special case to handle primary phone with different phone types
2103 // in this case we make first phone type as primary
2104 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2105 $primaryPhoneLoc = $loc;
2106 }
2107
2108 if ($loc != $primaryPhoneLoc) {
2109 unset($data['phone'][$loc]['is_primary']);
2110 }
2111 }
2112 elseif ($fieldName == 'phone_ext') {
2113 $data['phone'][$loc]['phone_ext'] = $value;
2114 }
2115 elseif ($fieldName == 'email') {
2116 $data['email'][$loc]['email'] = $value;
2117 }
2118 elseif ($fieldName == 'im') {
2119 if (isset($params[$key . '-provider_id'])) {
2120 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2121 }
2122 if (strpos($key, '-provider_id') !== FALSE) {
2123 $data['im'][$loc]['provider_id'] = $params[$key];
2124 }
2125 else {
2126 $data['im'][$loc]['name'] = $value;
2127 }
2128 }
2129 elseif ($fieldName == 'openid') {
2130 $data['openid'][$loc]['openid'] = $value;
2131 }
2132 else {
2133 if ($fieldName === 'state_province') {
2134 // CRM-3393
2135 if (is_numeric($value) && ((int ) $value) >= 1000) {
2136 $data['address'][$loc]['state_province_id'] = $value;
2137 }
2138 elseif (empty($value)) {
2139 $data['address'][$loc]['state_province_id'] = '';
2140 }
2141 else {
2142 $data['address'][$loc]['state_province'] = $value;
2143 }
2144 }
2145 elseif ($fieldName === 'country') {
2146 // CRM-3393
2147 if (is_numeric($value) && ((int ) $value) >= 1000
2148 ) {
2149 $data['address'][$loc]['country_id'] = $value;
2150 }
2151 elseif (empty($value)) {
2152 $data['address'][$loc]['country_id'] = '';
2153 }
2154 else {
2155 $data['address'][$loc]['country'] = $value;
2156 }
2157 }
2158 elseif ($fieldName === 'county') {
2159 $data['address'][$loc]['county_id'] = $value;
2160 }
2161 elseif ($fieldName == 'address_name') {
2162 $data['address'][$loc]['name'] = $value;
2163 }
2164 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2165 $data['address'][$loc][substr($fieldName, 8)] = $value;
2166 }
2167 else {
2168 $data['address'][$loc][$fieldName] = $value;
2169 }
2170 }
2171 }
2172 else {
2173 if (substr($key, 0, 4) === 'url-') {
2174 $websiteField = explode('-', $key);
887e764d
PN
2175 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2176 $data['website'][$websiteField[1]]['url'] = $value;
6a488035 2177 }
6a488035 2178 elseif (in_array($key, self::$_greetingTypes, TRUE)) {
41665e8f 2179 //save email/postal greeting and addressee values if any, CRM-4575
6a488035
TO
2180 $data[$key . '_id'] = $value;
2181 }
2182 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) {
2183 // for autocomplete transfer hidden value instead of label
2184 if ($params[$key] && isset($params[$key . '_id'])) {
2185 $value = $params[$key . '_id'];
2186 }
2187
2188 // we need to append time with date
2189 if ($params[$key] && isset($params[$key . '_time'])) {
2190 $value .= ' ' . $params[$key . '_time'];
2191 }
2192
ece0bc24
DS
2193 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2194 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 &&
9bb77b8e
TO
2195 ($value == '' || !isset($value))
2196 ) {
ece0bc24 2197 continue;
69739cb8 2198 }
ece0bc24 2199
6a488035 2200 $valueId = NULL;
a7488080 2201 if (!empty($params['customRecordValues'])) {
6a488035
TO
2202 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2203 foreach ($params['customRecordValues'] as $recId => $customFields) {
2204 if (is_array($customFields) && !empty($customFields)) {
2205 foreach ($customFields as $customFieldName) {
2206 if ($customFieldName == $key) {
2207 $valueId = $recId;
2208 break;
2209 }
2210 }
2211 }
2212 }
2213 }
2214 }
2215
2216 $type = $data['contact_type'];
a7488080 2217 if (!empty($data['contact_sub_type'])) {
6a488035
TO
2218 $type = $data['contact_sub_type'];
2219 $type = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($type, CRM_Core_DAO::VALUE_SEPARATOR));
2220 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2221 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2222 // as the results going to be same.
2223 $type = $type[0];
2224 }
2225
2226 CRM_Core_BAO_CustomField::formatCustomField($customFieldId,
2227 $data['custom'],
2228 $value,
2229 $type,
2230 $valueId,
2231 $contactID
2232 );
2233 }
2234 elseif ($key == 'edit') {
2235 continue;
2236 }
2237 else {
2238 if ($key == 'location') {
2239 foreach ($value as $locationTypeId => $field) {
2240 foreach ($field as $block => $val) {
2241 if ($block == 'address' && array_key_exists('address_name', $val)) {
2242 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2243 }
2244 }
2245 }
2246 }
9bb77b8e 2247 if ($key == 'phone' && isset($params['phone_ext'])) {
6a488035 2248 $data[$key] = $value;
9bb77b8e
TO
2249 foreach ($value as $cnt => $phoneBlock) {
2250 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
6a488035
TO
2251 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2252 }
2253 }
2254 }
4c9b6178 2255 elseif (in_array($key,
9bb77b8e
TO
2256 array(
2257 'nick_name',
69739cb8
EM
2258 'job_title',
2259 'middle_name',
2260 'birth_date',
4512fd44 2261 'gender_id',
69739cb8
EM
2262 'current_employer',
2263 'prefix_id',
21dfd5f5 2264 'suffix_id',
9bb77b8e 2265 )) &&
55ff2e3f 2266 ($value == '' || !isset($value)) &&
9bb77b8e
TO
2267 ($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0
2268 ) {
69739cb8 2269 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
55ff2e3f
DS
2270 // to avoid update with empty values
2271 continue;
69739cb8 2272 }
6a488035
TO
2273 else {
2274 $data[$key] = $value;
2275 }
2276 }
2277 }
2278 }
2279
2280 if (!isset($data['contact_type'])) {
2281 $data['contact_type'] = 'Individual';
2282 }
2283
2284 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2285 $privacy = CRM_Core_SelectValues::privacy();
2286 foreach ($privacy as $key => $value) {
2287 if (array_key_exists($key, $fields)) {
29748d00 2288 // do not reset values for existing contacts, if fields are added to a profile
6a488035
TO
2289 if (array_key_exists($key, $params)) {
2290 $data[$key] = $params[$key];
29748d00
C
2291 if (empty($params[$key])) {
2292 $data[$key] = 0;
2293 }
6a488035
TO
2294 }
2295 elseif (!$contactID) {
2296 $data[$key] = 0;
2297 }
2298 }
2299 }
2300
2301 return array($data, $contactDetails);
2302 }
2303
2304 /**
57507ae6
EM
2305 * Find the get contact details.
2306 *
2307 * This function does not respect ACLs for now, which might need to be rectified at some
2308 * stage based on how its used.
6a488035 2309 *
77c5b619
TO
2310 * @param string $mail
2311 * Primary email address of the contact.
2312 * @param string $ctype
2313 * Contact type.
6a488035 2314 *
a6c01b45
CW
2315 * @return object
2316 * $dao contact details
6a488035 2317 */
00be9182 2318 public static function &matchContactOnEmail($mail, $ctype = NULL) {
6a488035 2319 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
9bb77b8e
TO
2320 $mail = $strtolower(trim($mail));
2321 $query = "
6a488035
TO
2322SELECT civicrm_contact.id as contact_id,
2323 civicrm_contact.hash as hash,
2324 civicrm_contact.contact_type as contact_type,
2325 civicrm_contact.contact_sub_type as contact_sub_type
2326FROM civicrm_contact
2327INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2328
9bb77b8e 2329 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME, 'uniq_email_per_site')) {
6a488035
TO
2330 // try to find a match within a site (multisite).
2331 $groups = CRM_Core_BAO_Domain::getChildGroupIds();
2332 if (!empty($groups)) {
2333 $query .= "
2334INNER JOIN civicrm_group_contact gc ON
2335(civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2336 }
2337 }
2338
2339 $query .= "
2340WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2341 $p = array(1 => array($mail, 'String'));
2342
2343 if ($ctype) {
2344 $query .= " AND civicrm_contact.contact_type = %3";
2345 $p[3] = array($ctype, 'String');
2346 }
2347
2348 $query .= " ORDER BY civicrm_email.is_primary DESC";
2349
2350 $dao = CRM_Core_DAO::executeQuery($query, $p);
2351
2352 if ($dao->fetch()) {
2353 return $dao;
2354 }
2355 return CRM_Core_DAO::$_nullObject;
2356 }
2357
2358 /**
57507ae6 2359 * Find the contact details associated with an OpenID.
6a488035 2360 *
77c5b619
TO
2361 * @param string $openId
2362 * OpenId of the contact.
2363 * @param string $ctype
2364 * Contact type.
6a488035 2365 *
a6c01b45
CW
2366 * @return object
2367 * $dao contact details
6a488035 2368 */
00be9182 2369 public static function &matchContactOnOpenId($openId, $ctype = NULL) {
6a488035 2370 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
9bb77b8e
TO
2371 $openId = $strtolower(trim($openId));
2372 $query = "
6a488035
TO
2373SELECT civicrm_contact.id as contact_id,
2374 civicrm_contact.hash as hash,
2375 civicrm_contact.contact_type as contact_type,
2376 civicrm_contact.contact_sub_type as contact_sub_type
2377FROM civicrm_contact
2378INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2379WHERE civicrm_openid.openid = %1";
2380 $p = array(1 => array($openId, 'String'));
2381
2382 if ($ctype) {
2383 $query .= " AND civicrm_contact.contact_type = %3";
2384 $p[3] = array($ctype, 'String');
2385 }
2386
2387 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2388
2389 $dao = CRM_Core_DAO::executeQuery($query, $p);
2390
2391 if ($dao->fetch()) {
2392 return $dao;
2393 }
2394 return CRM_Core_DAO::$_nullObject;
2395 }
2396
2397 /**
57507ae6 2398 * Get primary email of the contact.
6a488035 2399 *
77c5b619
TO
2400 * @param int $contactID
2401 * Contact id.
6a488035 2402 *
a6c01b45 2403 * @return string
57507ae6 2404 * Email address if present else null
6a488035
TO
2405 */
2406 public static function getPrimaryEmail($contactID) {
2407 // fetch the primary email
2408 $query = "
2409 SELECT civicrm_email.email as email
2410 FROM civicrm_contact
2411LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2412 WHERE civicrm_email.is_primary = 1
2413 AND civicrm_contact.id = %1";
2414 $p = array(1 => array($contactID, 'Integer'));
2415 $dao = CRM_Core_DAO::executeQuery($query, $p);
2416
2417 $email = NULL;
2418 if ($dao->fetch()) {
2419 $email = $dao->email;
2420 }
2421 $dao->free();
2422 return $email;
2423 }
2424
2425 /**
57507ae6 2426 * Function to get primary OpenID of the contact.
6a488035 2427 *
77c5b619
TO
2428 * @param int $contactID
2429 * Contact id.
6a488035 2430 *
a6c01b45
CW
2431 * @return string
2432 * >openid OpenID if present else null
6a488035
TO
2433 */
2434 public static function getPrimaryOpenId($contactID) {
2435 // fetch the primary OpenID
2436 $query = "
2437SELECT civicrm_openid.openid as openid
2438FROM civicrm_contact
2439LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2440WHERE civicrm_contact.id = %1
2441AND civicrm_openid.is_primary = 1";
2442 $p = array(1 => array($contactID, 'Integer'));
2443 $dao = CRM_Core_DAO::executeQuery($query, $p);
2444
2445 $openId = NULL;
2446 if ($dao->fetch()) {
2447 $openId = $dao->openid;
2448 }
2449 $dao->free();
2450 return $openId;
2451 }
2452
2453 /**
57507ae6 2454 * Fetch the object and store the values in the values array.
6a488035 2455 *
77c5b619
TO
2456 * @param array $params
2457 * Input parameters to find object.
2458 * @param array $values
2459 * Output values of the object.
6a488035 2460 *
57507ae6
EM
2461 * @return CRM_Contact_BAO_Contact|null
2462 * The found object or null
6a488035
TO
2463 */
2464 public static function getValues(&$params, &$values) {
2465 $contact = new CRM_Contact_BAO_Contact();
2466
2467 $contact->copyValues($params);
2468
2469 if ($contact->find(TRUE)) {
2470
2471 CRM_Core_DAO::storeValues($contact, $values);
2472
2473 $privacy = array();
2474 foreach (self::$_commPrefs as $name) {
2475 if (isset($contact->$name)) {
2476 $privacy[$name] = $contact->$name;
2477 }
2478 }
2479
2480 if (!empty($privacy)) {
2481 $values['privacy'] = $privacy;
2482 }
2483
2484 // communication Prefferance
2485 $preffComm = $comm = array();
2486 $comm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2487 $contact->preferred_communication_method
2488 );
2489 foreach ($comm as $value) {
2490 $preffComm[$value] = 1;
2491 }
2492 $temp = array('preferred_communication_method' => $contact->preferred_communication_method);
2493
2494 $names = array(
9bb77b8e
TO
2495 'preferred_communication_method' => array(
2496 'newName' => 'preferred_communication_method_display',
6a488035 2497 'groupName' => 'preferred_communication_method',
21dfd5f5 2498 ),
9bb77b8e 2499 );
6a488035
TO
2500
2501 CRM_Core_OptionGroup::lookupValues($temp, $names, FALSE);
2502
2503 $values['preferred_communication_method'] = $preffComm;
2504 $values['preferred_communication_method_display'] = CRM_Utils_Array::value('preferred_communication_method_display', $temp);
2505
77d0b1f8 2506 $preferredMailingFormat = CRM_Core_SelectValues::pmf();
2507 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format];
6a488035
TO
2508
2509 // get preferred languages
2510 if (!empty($contact->preferred_language)) {
a8c23526 2511 $values['preferred_language'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language);
6a488035
TO
2512 }
2513
2514 // Calculating Year difference
2515 if ($contact->birth_date) {
2516 $birthDate = CRM_Utils_Date::customFormat($contact->birth_date, '%Y%m%d');
2517 if ($birthDate < date('Ymd')) {
9bb77b8e 2518 $age = CRM_Utils_Date::calculateAge($birthDate);
6a488035
TO
2519 $values['age']['y'] = CRM_Utils_Array::value('years', $age);
2520 $values['age']['m'] = CRM_Utils_Array::value('months', $age);
2521 }
2522
2523 list($values['birth_date']) = CRM_Utils_Date::setDateDefaults($contact->birth_date, 'birth');
2524 $values['birth_date_display'] = $contact->birth_date;
2525 }
2526
2527 if ($contact->deceased_date) {
2528 list($values['deceased_date']) = CRM_Utils_Date::setDateDefaults($contact->deceased_date, 'birth');
2529 $values['deceased_date_display'] = $contact->deceased_date;
2530 }
2531
2532 $contact->contact_id = $contact->id;
2533
2534 return $contact;
2535 }
2536 return NULL;
2537 }
2538
2539 /**
db7de9c1 2540 * Given the component name and returns the count of participation of contact.
6a488035 2541 *
77c5b619
TO
2542 * @param string $component
2543 * Input component name.
2544 * @param int $contactId
2545 * Input contact id.
2546 * @param string $tableName
2547 * Optional tableName if component is custom group.
6a488035 2548 *
72b3a70c
CW
2549 * @return int
2550 * total number in database
6a488035 2551 */
00be9182 2552 public static function getCountComponent($component, $contactId, $tableName = NULL) {
6a488035
TO
2553 $object = NULL;
2554 switch ($component) {
2555 case 'tag':
2556 return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE);
2557
2558 case 'rel':
2559 return CRM_Contact_BAO_Relationship::getRelationship($contactId,
2560 CRM_Contact_BAO_Relationship::CURRENT,
2561 0, 1
2562 );
2563
2564 case 'group':
2565 return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE);
2566
2567 case 'log':
2568 if (CRM_Core_BAO_Log::useLoggingReport()) {
2569 return FALSE;
2570 }
2571 return CRM_Core_BAO_Log::getContactLogCount($contactId);
2572
2573 case 'note':
2574 return CRM_Core_BAO_Note::getContactNoteCount($contactId);
2575
2576 case 'contribution':
2577 return CRM_Contribute_BAO_Contribution::contributionCount($contactId);
2578
2579 case 'membership':
2580 return CRM_Member_BAO_Membership::getContactMembershipCount($contactId, TRUE);
2581
2582 case 'participant':
2583 return CRM_Event_BAO_Participant::getContactParticipantCount($contactId);
2584
2585 case 'pledge':
2586 return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId);
2587
2588 case 'case':
2589 return CRM_Case_BAO_Case::caseCount($contactId);
2590
2591 case 'grant':
2592 return CRM_Grant_BAO_Grant::getContactGrantCount($contactId);
2593
2594 case 'activity':
2595 $input = array(
2596 'contact_id' => $contactId,
2597 'admin' => FALSE,
2598 'caseId' => NULL,
2599 'context' => 'activity',
2600 );
2601 return CRM_Activity_BAO_Activity::getActivitiesCount($input);
2602
36bb946c 2603 case 'mailing':
7c006637 2604 $params = array('contact_id' => $contactId);
553f116a 2605 return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
36bb946c 2606
6a488035
TO
2607 default:
2608 $custom = explode('_', $component);
2609 if ($custom['0'] = 'custom') {
2610 if (!$tableName) {
2611 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2612 }
2613 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2614 return CRM_Core_DAO::singleValueQuery($queryString);
2615 }
2616 }
2617 }
2618
2619 /**
100fef9d 2620 * Process greetings and cache
6a488035 2621 *
77c5b619
TO
2622 * @param object $contact
2623 * Contact object after save.
2624 * @param bool $useDefaults
2625 * Use default greeting values.
6a488035 2626 */
00be9182 2627 public static function processGreetings(&$contact, $useDefaults = FALSE) {
6a488035
TO
2628 if ($useDefaults) {
2629 //retrieve default greetings
2630 $defaultGreetings = CRM_Core_PseudoConstant::greetingDefaults();
2631 $contactDefaults = $defaultGreetings[$contact->contact_type];
2632 }
2633
2634 // note that contact object not always has required greeting related
2635 // fields that are required to calculate greeting and
2636 // also other fields used in tokens etc,
2637 // hence we need to retrieve it again.
9bb77b8e 2638 if ($contact->_query !== FALSE) {
1a902da0
BS
2639 $contact->find(TRUE);
2640 }
6a488035
TO
2641
2642 // store object values to an array
2643 $contactDetails = array();
2644 CRM_Core_DAO::storeValues($contact, $contactDetails);
2645 $contactDetails = array(array($contact->id => $contactDetails));
2646
2647 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2648 $updateQueryString = array();
2649
2650 //cache email and postal greeting to greeting display
2651 if ($contact->email_greeting_custom != 'null' && $contact->email_greeting_custom) {
2652 $emailGreetingString = $contact->email_greeting_custom;
2653 }
2654 elseif ($contact->email_greeting_id != 'null' && $contact->email_greeting_id) {
2655 // the filter value for Individual contact type is set to 1
2656 $filter = array(
2657 'contact_type' => $contact->contact_type,
2658 'greeting_type' => 'email_greeting',
2659 );
2660
9bb77b8e 2661 $emailGreeting = CRM_Core_PseudoConstant::greeting($filter);
6a488035
TO
2662 $emailGreetingString = $emailGreeting[$contact->email_greeting_id];
2663 $updateQueryString[] = " email_greeting_custom = NULL ";
2664 }
2665 else {
2666 if ($useDefaults) {
2667 reset($contactDefaults['email_greeting']);
9bb77b8e 2668 $emailGreetingID = key($contactDefaults['email_greeting']);
6a488035
TO
2669 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2670 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2671 $updateQueryString[] = " email_greeting_custom = NULL ";
2672 }
2673 elseif ($contact->email_greeting_custom) {
2674 $updateQueryString[] = " email_greeting_display = NULL ";
2675 }
2676 }
2677
2678 if ($emailGreetingString) {
73d64eb6 2679 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($emailGreetingString,
6a488035
TO
2680 $contactDetails,
2681 $contact->id,
2682 'CRM_Contact_BAO_Contact'
2683 );
2684 $emailGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($emailGreetingString));
2685 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2686 }
2687
2688 //postal greetings
2689 if ($contact->postal_greeting_custom != 'null' && $contact->postal_greeting_custom) {
2690 $postalGreetingString = $contact->postal_greeting_custom;
2691 }
2692 elseif ($contact->postal_greeting_id != 'null' && $contact->postal_greeting_id) {
2693 $filter = array(
2694 'contact_type' => $contact->contact_type,
2695 'greeting_type' => 'postal_greeting',
2696 );
2697 $postalGreeting = CRM_Core_PseudoConstant::greeting($filter);
2698 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id];
2699 $updateQueryString[] = " postal_greeting_custom = NULL ";
2700 }
2701 else {
2702 if ($useDefaults) {
2703 reset($contactDefaults['postal_greeting']);
2704 $postalGreetingID = key($contactDefaults['postal_greeting']);
2705 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2706 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2707 $updateQueryString[] = " postal_greeting_custom = NULL ";
2708 }
2709 elseif ($contact->postal_greeting_custom) {
2710 $updateQueryString[] = " postal_greeting_display = NULL ";
2711 }
2712 }
2713
2714 if ($postalGreetingString) {
73d64eb6 2715 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($postalGreetingString,
6a488035
TO
2716 $contactDetails,
2717 $contact->id,
2718 'CRM_Contact_BAO_Contact'
2719 );
2720 $postalGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($postalGreetingString));
2721 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2722 }
2723
2724 // addressee
2725 if ($contact->addressee_custom != 'null' && $contact->addressee_custom) {
2726 $addresseeString = $contact->addressee_custom;
2727 }
2728 elseif ($contact->addressee_id != 'null' && $contact->addressee_id) {
2729 $filter = array(
2730 'contact_type' => $contact->contact_type,
2731 'greeting_type' => 'addressee',
2732 );
2733
9bb77b8e
TO
2734 $addressee = CRM_Core_PseudoConstant::greeting($filter);
2735 $addresseeString = $addressee[$contact->addressee_id];
6a488035
TO
2736 $updateQueryString[] = " addressee_custom = NULL ";
2737 }
2738 else {
2739 if ($useDefaults) {
2740 reset($contactDefaults['addressee']);
9bb77b8e
TO
2741 $addresseeID = key($contactDefaults['addressee']);
2742 $addresseeString = $contactDefaults['addressee'][$addresseeID];
6a488035
TO
2743 $updateQueryString[] = " addressee_id = $addresseeID ";
2744 $updateQueryString[] = " addressee_custom = NULL ";
2745 }
2746 elseif ($contact->addressee_custom) {
2747 $updateQueryString[] = " addressee_display = NULL ";
2748 }
2749 }
2750
2751 if ($addresseeString) {
73d64eb6 2752 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($addresseeString,
6a488035
TO
2753 $contactDetails,
2754 $contact->id,
2755 'CRM_Contact_BAO_Contact'
2756 );
2757 $addresseeString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($addresseeString));
2758 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2759 }
2760
2761 if (!empty($updateQueryString)) {
2762 $updateQueryString = implode(',', $updateQueryString);
2763 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2764 CRM_Core_DAO::executeQuery($queryString);
2765 }
2766 }
2767
2768 /**
100fef9d 2769 * Retrieve loc block ids w/ given condition.
6a488035 2770 *
77c5b619
TO
2771 * @param int $contactId
2772 * Contact id.
2773 * @param array $criteria
2774 * Key => value pair which should be.
6a488035 2775 * fulfill by return record ids.
77c5b619
TO
2776 * @param string $condOperator
2777 * Operator use for grouping multiple conditions.
6a488035 2778 *
a6c01b45
CW
2779 * @return array
2780 * loc block ids which fulfill condition.
6a488035 2781 */
00be9182 2782 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
6a488035
TO
2783 $locBlockIds = array();
2784 if (!$contactId) {
2785 return $locBlockIds;
2786 }
2787
46a4f1e9 2788 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
6a488035 2789 $name = strtolower($block);
46a4f1e9
CW
2790 $className = "CRM_Core_DAO_$block";
2791 $blockDAO = new $className();
6a488035
TO
2792
2793 // build the condition.
2794 if (is_array($criteria)) {
46a4f1e9 2795 $fields = $blockDAO->fields();
6a488035
TO
2796 $conditions = array();
2797 foreach ($criteria as $field => $value) {
2798 if (array_key_exists($field, $fields)) {
2799 $cond = "( $field = $value )";
2800 // value might be zero or null.
2801 if (!$value || strtolower($value) == 'null') {
2802 $cond = "( $field = 0 OR $field IS NULL )";
2803 }
2804 $conditions[] = $cond;
2805 }
2806 }
2807 if (!empty($conditions)) {
2808 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2809 }
2810 }
2811
2812 $blockDAO->contact_id = $contactId;
2813 $blockDAO->find();
2814 while ($blockDAO->fetch()) {
2815 $locBlockIds[$name][] = $blockDAO->id;
2816 }
2817 $blockDAO->free();
2818 }
2819
2820 return $locBlockIds;
2821 }
2822
2823 /**
100fef9d 2824 * Build context menu items.
6a488035 2825 *
100fef9d 2826 * @param int $contactId
77b97be7 2827 *
a6c01b45 2828 * @return array
16b10e64 2829 * Array of context menu for logged in user.
6a488035 2830 */
00be9182 2831 public static function contextMenu($contactId = NULL) {
6a488035 2832 $menu = array(
8e4ec1f5
CW
2833 'view' => array(
2834 'title' => ts('View Contact'),
6a488035
TO
2835 'weight' => 0,
2836 'ref' => 'view-contact',
8e4ec1f5 2837 'class' => 'no-popup',
6a488035
TO
2838 'key' => 'view',
2839 'permissions' => array('view all contacts'),
2840 ),
8e4ec1f5
CW
2841 'add' => array(
2842 'title' => ts('Edit Contact'),
6a488035
TO
2843 'weight' => 0,
2844 'ref' => 'edit-contact',
8e4ec1f5 2845 'class' => 'no-popup',
6a488035
TO
2846 'key' => 'add',
2847 'permissions' => array('edit all contacts'),
2848 ),
8e4ec1f5
CW
2849 'delete' => array(
2850 'title' => ts('Delete Contact'),
6a488035
TO
2851 'weight' => 0,
2852 'ref' => 'delete-contact',
2853 'key' => 'delete',
2854 'permissions' => array('access deleted contacts', 'delete contacts'),
2855 ),
8e4ec1f5
CW
2856 'contribution' => array(
2857 'title' => ts('Add Contribution'),
6a488035
TO
2858 'weight' => 5,
2859 'ref' => 'new-contribution',
8e4ec1f5
CW
2860 'key' => 'contribution',
2861 'tab' => 'contribute',
6a488035
TO
2862 'component' => 'CiviContribute',
2863 'href' => CRM_Utils_System::url('civicrm/contact/view/contribution',
2864 'reset=1&action=add&context=contribution'
2865 ),
2866 'permissions' => array(
2867 'access CiviContribute',
2868 'edit contributions',
2869 ),
2870 ),
8e4ec1f5
CW
2871 'participant' => array(
2872 'title' => ts('Register for Event'),
6a488035
TO
2873 'weight' => 10,
2874 'ref' => 'new-participant',
2875 'key' => 'participant',
8e4ec1f5 2876 'tab' => 'participant',
6a488035
TO
2877 'component' => 'CiviEvent',
2878 'href' => CRM_Utils_System::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2879 'permissions' => array(
2880 'access CiviEvent',
2881 'edit event participants',
2882 ),
2883 ),
8e4ec1f5
CW
2884 'activity' => array(
2885 'title' => ts('Record Activity'),
6a488035
TO
2886 'weight' => 35,
2887 'ref' => 'new-activity',
2888 'key' => 'activity',
2889 'permissions' => array('edit all contacts'),
2890 ),
8e4ec1f5
CW
2891 'pledge' => array(
2892 'title' => ts('Add Pledge'),
6a488035
TO
2893 'weight' => 15,
2894 'ref' => 'new-pledge',
2895 'key' => 'pledge',
8e4ec1f5 2896 'tab' => 'pledge',
6a488035
TO
2897 'href' => CRM_Utils_System::url('civicrm/contact/view/pledge',
2898 'reset=1&action=add&context=pledge'
2899 ),
2900 'component' => 'CiviPledge',
2901 'permissions' => array(
2902 'access CiviPledge',
2903 'edit pledges',
2904 ),
2905 ),
8e4ec1f5
CW
2906 'membership' => array(
2907 'title' => ts('Add Membership'),
6a488035
TO
2908 'weight' => 20,
2909 'ref' => 'new-membership',
8e4ec1f5
CW
2910 'key' => 'membership',
2911 'tab' => 'member',
6a488035
TO
2912 'component' => 'CiviMember',
2913 'href' => CRM_Utils_System::url('civicrm/contact/view/membership',
2914 'reset=1&action=add&context=membership'
2915 ),
2916 'permissions' => array(
2917 'access CiviMember',
2918 'edit memberships',
2919 ),
2920 ),
8e4ec1f5
CW
2921 'case' => array(
2922 'title' => ts('Add Case'),
6a488035
TO
2923 'weight' => 25,
2924 'ref' => 'new-case',
2925 'key' => 'case',
8e4ec1f5 2926 'tab' => 'case',
6a488035
TO
2927 'component' => 'CiviCase',
2928 'href' => CRM_Utils_System::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2929 'permissions' => array('add cases'),
2930 ),
8e4ec1f5
CW
2931 'grant' => array(
2932 'title' => ts('Add Grant'),
6a488035
TO
2933 'weight' => 26,
2934 'ref' => 'new-grant',
2935 'key' => 'grant',
8e4ec1f5 2936 'tab' => 'grant',
6a488035
TO
2937 'component' => 'CiviGrant',
2938 'href' => CRM_Utils_System::url('civicrm/contact/view/grant',
2939 'reset=1&action=add&context=grant'
2940 ),
2941 'permissions' => array('edit grants'),
2942 ),
8e4ec1f5
CW
2943 'rel' => array(
2944 'title' => ts('Add Relationship'),
6a488035
TO
2945 'weight' => 30,
2946 'ref' => 'new-relationship',
2947 'key' => 'rel',
8e4ec1f5 2948 'tab' => 'rel',
6a488035
TO
2949 'href' => CRM_Utils_System::url('civicrm/contact/view/rel',
2950 'reset=1&action=add'
2951 ),
2952 'permissions' => array('edit all contacts'),
2953 ),
8e4ec1f5
CW
2954 'note' => array(
2955 'title' => ts('Add Note'),
6a488035
TO
2956 'weight' => 40,
2957 'ref' => 'new-note',
2958 'key' => 'note',
8e4ec1f5 2959 'tab' => 'note',
77042884 2960 'class' => 'medium-popup',
6a488035
TO
2961 'href' => CRM_Utils_System::url('civicrm/contact/view/note',
2962 'reset=1&action=add'
2963 ),
2964 'permissions' => array('edit all contacts'),
2965 ),
8e4ec1f5
CW
2966 'email' => array(
2967 'title' => ts('Send an Email'),
6a488035
TO
2968 'weight' => 45,
2969 'ref' => 'new-email',
2970 'key' => 'email',
2971 'permissions' => array('view all contacts'),
2972 ),
8e4ec1f5
CW
2973 'group' => array(
2974 'title' => ts('Add to Group'),
6a488035
TO
2975 'weight' => 50,
2976 'ref' => 'group-add-contact',
2977 'key' => 'group',
8e4ec1f5 2978 'tab' => 'group',
6a488035
TO
2979 'permissions' => array('edit groups'),
2980 ),
8e4ec1f5
CW
2981 'tag' => array(
2982 'title' => ts('Tag Contact'),
6a488035
TO
2983 'weight' => 55,
2984 'ref' => 'tag-contact',
2985 'key' => 'tag',
8e4ec1f5 2986 'tab' => 'tag',
6a488035
TO
2987 'permissions' => array('edit all contacts'),
2988 ),
2989 );
2990
2991 CRM_Utils_Hook::summaryActions($menu, $contactId);
2992 //1. check for component is active.
2993 //2. check for user permissions.
2994 //3. check for acls.
2995 //3. edit and view contact are directly accessible to user.
2996
2997 $aclPermissionedTasks = array(
9bb77b8e
TO
2998 'view-contact',
2999 'edit-contact',
3000 'new-activity',
3001 'new-email',
3002 'group-add-contact',
3003 'tag-contact',
3004 'delete-contact',
6a488035
TO
3005 );
3006 $corePermission = CRM_Core_Permission::getPermission();
3007
3008 $config = CRM_Core_Config::singleton();
3009
3010 $contextMenu = array();
3011 foreach ($menu as $key => $values) {
3012 $componentName = CRM_Utils_Array::value('component', $values);
3013
3014 // if component action - make sure component is enable.
3015 if ($componentName && !in_array($componentName, $config->enableComponents)) {
3016 continue;
3017 }
3018
3019 // make sure user has all required permissions.
3020 $hasAllPermissions = FALSE;
3021
3022 $permissions = CRM_Utils_Array::value('permissions', $values);
3023 if (!is_array($permissions) || empty($permissions)) {
3024 $hasAllPermissions = TRUE;
3025 }
3026
3027 // iterate for required permissions in given permissions array.
3028 if (!$hasAllPermissions) {
3029 $hasPermissions = 0;
3030 foreach ($permissions as $permission) {
3031 if (CRM_Core_Permission::check($permission)) {
3032 $hasPermissions++;
3033 }
3034 }
3035
3036 if (count($permissions) == $hasPermissions) {
3037 $hasAllPermissions = TRUE;
3038 }
3039
3040 // if still user does not have required permissions, check acl.
3041 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
3042 if (in_array($values['ref'], $aclPermissionedTasks) &&
3043 $corePermission == CRM_Core_Permission::EDIT
3044 ) {
3045 $hasAllPermissions = TRUE;
3046 }
3047 elseif (in_array($values['ref'], array(
21dfd5f5 3048 'new-email',
9bb77b8e 3049 ))) {
6a488035
TO
3050 // grant permissions for these tasks.
3051 $hasAllPermissions = TRUE;
3052 }
3053 }
3054 }
3055
3056 // user does not have necessary permissions.
3057 if (!$hasAllPermissions) {
3058 continue;
3059 }
3060
3061 // build directly accessible action menu.
3062 if (in_array($values['ref'], array(
9bb77b8e 3063 'view-contact',
21dfd5f5 3064 'edit-contact',
9bb77b8e 3065 ))) {
6a488035
TO
3066 $contextMenu['primaryActions'][$key] = array(
3067 'title' => $values['title'],
3068 'ref' => $values['ref'],
8e4ec1f5 3069 'class' => CRM_Utils_Array::value('class', $values),
6a488035
TO
3070 'key' => $values['key'],
3071 );
3072 continue;
3073 }
3074
3075 // finally get menu item for -more- action widget.
3076 $contextMenu['moreActions'][$values['weight']] = array(
3077 'title' => $values['title'],
3078 'ref' => $values['ref'],
3079 'href' => CRM_Utils_Array::value('href', $values),
8e4ec1f5
CW
3080 'tab' => CRM_Utils_Array::value('tab', $values),
3081 'class' => CRM_Utils_Array::value('class', $values),
6a488035
TO
3082 'key' => $values['key'],
3083 );
3084 }
3085
3086 ksort($contextMenu['moreActions']);
3087
3088 return $contextMenu;
3089 }
3090
3091 /**
100fef9d 3092 * Retrieve display name of contact that address is shared
6a488035
TO
3093 * based on $masterAddressId or $contactId .
3094 *
77c5b619
TO
3095 * @param int $masterAddressId
3096 * Master id.
3097 * @param int $contactId
3098 * Contact id.
6a488035 3099 *
72b3a70c
CW
3100 * @return string|null
3101 * the found display name or null.
6a488035 3102 */
00be9182 3103 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
6a488035
TO
3104 $masterDisplayName = NULL;
3105 $sql = NULL;
3106 if (!$masterAddressId && !$contactId) {
3107 return $masterDisplayName;
3108 }
3109
3110 if ($masterAddressId) {
3111 $sql = "
3112 SELECT display_name from civicrm_contact
3113LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3114 WHERE civicrm_address.id = " . $masterAddressId;
3115 }
3116 elseif ($contactId) {
3117 $sql = "
3118 SELECT display_name from civicrm_contact cc, civicrm_address add1
3119LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3120 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3121 }
3122
3123 $masterDisplayName = CRM_Core_DAO::singleValueQuery($sql);
3124 return $masterDisplayName;
3125 }
3126
3127 /**
3128 * Get the creation/modification times for a contact
3129 *
100fef9d 3130 * @param int $contactId
77b97be7 3131 *
6a488035 3132 * @return array('created_date' => $, 'modified_date' => $)
77b97be7 3133 */
00be9182 3134 public static function getTimestamps($contactId) {
6a488035
TO
3135 $timestamps = CRM_Core_DAO::executeQuery(
3136 'SELECT created_date, modified_date
3137 FROM civicrm_contact
3138 WHERE id = %1',
3139 array(
3140 1 => array($contactId, 'Integer'),
3141 )
3142 );
3143 if ($timestamps->fetch()) {
3144 return array(
3145 'created_date' => $timestamps->created_date,
3146 'modified_date' => $timestamps->modified_date,
3147 );
3148 }
3149 else {
3150 return NULL;
3151 }
3152 }
3153
0590c631
DK
3154 /**
3155 * Generate triggers to update the timestamp on the corresponding civicrm_contact row,
3156 * on insert/update/delete to a table that extends civicrm_contact.
3157 * Don't regenerate triggers for all such tables if only asked for one table.
3158 *
3159 * @param array $info
3160 * Reference to the array where generated trigger information is being stored
3161 * @param string|null $reqTableName
3162 * Name of the table for which triggers are being generated, or NULL if all tables
3163 * @param array $relatedTableNames
3164 * Array of all core or all custom table names extending civicrm_contact
3165 * @param string $contactRefColumn
3166 * 'contact_id' if processing core tables, 'entity_id' if processing custom tables
0590c631
DK
3167 *
3168 * @link https://issues.civicrm.org/jira/browse/CRM-15602
3169 * @see triggerInfo
0590c631 3170 */
00be9182 3171 public static function generateTimestampTriggers(&$info, $reqTableName, $relatedTableNames, $contactRefColumn) {
0590c631
DK
3172 // Safety
3173 $contactRefColumn = CRM_Core_DAO::escapeString($contactRefColumn);
3174 // If specific related table requested, just process that one
3175 if (in_array($reqTableName, $relatedTableNames)) {
3176 $relatedTableNames = array($reqTableName);
3177 }
3178
3179 // If no specific table requested (include all related tables),
3180 // or a specific related table requested (as matched above)
3181 if (empty($reqTableName) || in_array($reqTableName, $relatedTableNames)) {
3182 $info[] = array(
3183 'table' => $relatedTableNames,
3184 'when' => 'AFTER',
3185 'event' => array('INSERT', 'UPDATE'),
3186 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.$contactRefColumn;\n",
3187 );
3188 $info[] = array(
3189 'table' => $relatedTableNames,
3190 'when' => 'AFTER',
3191 'event' => array('DELETE'),
3192 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.$contactRefColumn;\n",
3193 );
3194 }
3195 }
3196
6a488035 3197 /**
db7de9c1 3198 * Get a list of triggers for the contact table.
6a488035
TO
3199 *
3200 * @see hook_civicrm_triggerInfo
3201 * @see CRM_Core_DAO::triggerRebuild
3202 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3203 */
00be9182 3204 public static function triggerInfo(&$info, $tableName = NULL) {
6a488035
TO
3205 //during upgrade, first check for valid version and then create triggers
3206 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3207 if (CRM_Core_Config::isUpgradeMode()) {
3208 $currentVer = CRM_Core_BAO_Domain::version(TRUE);
3209 //if current version is less than 4.3.alpha1 dont create below triggers
3210 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3211 return;
3212 }
3213 }
3214
0590c631 3215 // Update timestamp for civicrm_contact itself
6a488035
TO
3216 if ($tableName == NULL || $tableName == self::getTableName()) {
3217 $info[] = array(
3218 'table' => array(self::getTableName()),
3219 'when' => 'BEFORE',
3220 'event' => array('INSERT'),
3221 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3222 );
3223 }
3224
3225 // Update timestamp when modifying closely related core tables
3226 $relatedTables = array(
3227 'civicrm_address',
3228 'civicrm_email',
3229 'civicrm_im',
3230 'civicrm_phone',
3231 'civicrm_website',
3232 );
0590c631 3233 self::generateTimestampTriggers($info, $tableName, $relatedTables, 'contact_id');
6a488035
TO
3234
3235 // Update timestamp when modifying related custom-data tables
3236 $customGroupTables = array();
3237 $customGroupDAO = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
3238 $customGroupDAO->is_multiple = 0;
3239 $customGroupDAO->find();
3240 while ($customGroupDAO->fetch()) {
3241 $customGroupTables[] = $customGroupDAO->table_name;
3242 }
3243 if (!empty($customGroupTables)) {
0590c631 3244 self::generateTimestampTriggers($info, $tableName, $customGroupTables, 'entity_id');
6a488035
TO
3245 }
3246
3247 // Update phone table to populate phone_numeric field
3248 if (!$tableName || $tableName == 'civicrm_phone') {
3249 // Define stored sql function needed for phones
3250 CRM_Core_DAO::executeQuery(self::DROP_STRIP_FUNCTION_43);
3251 CRM_Core_DAO::executeQuery(self::CREATE_STRIP_FUNCTION_43);
3252 $info[] = array(
3253 'table' => array('civicrm_phone'),
3254 'when' => 'BEFORE',
3255 'event' => array('INSERT', 'UPDATE'),
3256 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3257 );
3258 }
3259 }
3260
3261 /**
db7de9c1 3262 * Check if contact is being used in civicrm_domain based on $contactId.
6a488035 3263 *
77c5b619
TO
3264 * @param int $contactId
3265 * Contact id.
6a488035 3266 *
a6c01b45
CW
3267 * @return bool
3268 * true if present else false.
6a488035 3269 */
00be9182 3270 public static function checkDomainContact($contactId) {
db7de9c1 3271 if (!$contactId) {
6a488035 3272 return FALSE;
db7de9c1 3273 }
9bb77b8e 3274 $domainId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
6a488035
TO
3275
3276 if ($domainId) {
3277 return TRUE;
9bb77b8e
TO
3278 }
3279 else {
6a488035
TO
3280 return FALSE;
3281 }
3282 }
12445e1c 3283
dc86f881
CW
3284 /**
3285 * Get options for a given contact field.
db7de9c1 3286 *
dc86f881
CW
3287 * @see CRM_Core_DAO::buildOptions
3288 *
3289 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3290 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3291 *
77c5b619
TO
3292 * @param string $fieldName
3293 * @param string $context
63e9c3fd 3294 * @see CRM_Core_DAO::buildOptionsContext
77c5b619 3295 * @param array $props
16b10e64 3296 * whatever is known about this dao object.
77b97be7
EM
3297 *
3298 * @return Array|bool
dc86f881
CW
3299 */
3300 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3301 $params = array();
3302 // Special logic for fields whose options depend on context or properties
3303 switch ($fieldName) {
3304 case 'contact_sub_type':
3305 if (!empty($props['contact_type'])) {
3306 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3307 }
3308 break;
ea100cb5 3309
bee6039a
CW
3310 case 'contact_type':
3311 if ($context == 'search') {
76773c5a
CW
3312 // CRM-15495 - EntityRef filters and basic search forms expect this format
3313 // FIXME: Search builder does not
bee6039a
CW
3314 return CRM_Contact_BAO_ContactType::getSelectElements();
3315 }
3316 break;
dc86f881 3317 }
786ad6e1 3318 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
dc86f881 3319 }
1071730c 3320
12445e1c 3321 /**
db7de9c1
EM
3322 * Delete a contact-related object that has an 'is_primary' field.
3323 *
12445e1c
CW
3324 * Ensures that is_primary gets assigned to another object if available
3325 * Also calls pre/post hooks
3326 *
db7de9c1
EM
3327 * @var object $type
3328 * @var int $id
77b97be7 3329 * @return bool
12445e1c
CW
3330 */
3331 public static function deleteObjectWithPrimary($type, $id) {
3332 if (!$id || !is_numeric($id)) {
a65e2e55 3333 return FALSE;
12445e1c
CW
3334 }
3335 $daoName = "CRM_Core_DAO_$type";
3336 $obj = new $daoName();
3337 $obj->id = $id;
3338 $obj->find();
3339 if ($obj->fetch()) {
3340 CRM_Utils_Hook::pre('delete', $type, $id, CRM_Core_DAO::$_nullArray);
3341 $contactId = $obj->contact_id;
3342 $obj->delete();
3343 }
3344 else {
a65e2e55 3345 return FALSE;
12445e1c 3346 }
50fa40e8
CW
3347 // is_primary is only relavent if this field belongs to a contact
3348 if ($contactId) {
3349 $dao = new $daoName();
3350 $dao->contact_id = $contactId;
3351 $dao->is_primary = 1;
3352 // Pick another record to be primary (if one isn't already)
3353 if (!$dao->find(TRUE)) {
3354 $dao->is_primary = 0;
3355 $dao->find();
3356 if ($dao->fetch()) {
3357 $dao->is_primary = 1;
3358 $dao->save();
3359 }
3360 }
3361 $dao->free();
12445e1c 3362 }
12445e1c
CW
3363 CRM_Utils_Hook::post('delete', $type, $id, $obj);
3364 $obj->free();
a65e2e55 3365 return TRUE;
12445e1c 3366 }
6a488035 3367}