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