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