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