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