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