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