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