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