Merge pull request #4575 from jitendrapurohit/CRM-15552
[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 'communication_style_id' => array(
1316 'title' => ts('Communication Style'),
1317 'name' => 'communication_style_id',
1318 ),
1319 ));
1320 }
1321
1322 //Sorting fields in alphabetical order(CRM-1507)
1323 $fields = CRM_Utils_Array::crmArraySortByField($fields, 'title');
1324
1325 CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
1326 }
1327
1328 self::$_importableFields[$cacheKeyString] = $fields;
1329
1330 if (!$isProfile) {
1331 if (!$status) {
1332 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1333 self::$_importableFields[$cacheKeyString]
1334 );
1335 }
1336 else {
1337 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1338 self::$_importableFields[$cacheKeyString]
1339 );
1340 }
1341 }
1342 return $fields;
1343 }
1344
1345 /**
1346 * combine all the exportable fields from the lower levels object
1347 *
1348 * currentlty we are using importable fields as exportable fields
1349 *
1350 * @param int|string $contactType contact Type
1351 * @param boolean $status true while exporting primary contacts
1352 * @param boolean $export true when used during export
1353 * @param boolean $search true when used during search, might conflict with export param?
1354 *
1355 * @param bool $withMultiRecord
1356 *
1357 * @return array array of exportable Fields
1358 * @access public
1359 * @static
1360 */
1361 static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1362 if (empty($contactType)) {
1363 $contactType = 'All';
1364 }
1365
1366 $cacheKeyString = "exportableFields $contactType";
1367 $cacheKeyString .= $export ? '_1' : '_0';
1368 $cacheKeyString .= $status ? '_1' : '_0';
1369 $cacheKeyString .= $search ? '_1' : '_0';
1370 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1371 //calculates custom fields takes into account the logged in user & caches that for all users
1372 //as an interim fix we will cache the fields by contact
1373 $cacheKeyString .= '_' . CRM_Core_Session::getLoggedInContactID();
1374
1375 if (!self::$_exportableFields || !CRM_Utils_Array::value($cacheKeyString, self::$_exportableFields)) {
1376 if (!self::$_exportableFields) {
1377 self::$_exportableFields = array();
1378 }
1379
1380 // check if we can retrieve from database cache
1381 $fields = CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
1382
1383 if (!$fields) {
1384 $fields = CRM_Contact_DAO_Contact::export();
1385
1386 // the fields are meant for contact types
1387 if (
1388 in_array(
1389 $contactType,
1390 array('Individual', 'Household', 'Organization', 'All')
1391 )
1392 ) {
1393 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
1394 }
1395 // add current employer for individuals
1396 $fields = array_merge($fields, array(
1397 'current_employer' =>
1398 array(
1399 'name' => 'organization_name',
1400 'title' => ts('Current Employer'),
1401 ),
1402 ));
1403
1404 $locationType = array(
1405 'location_type' => array(
1406 'name' => 'location_type',
1407 'where' => 'civicrm_location_type.name',
1408 'title' => ts('Location Type'),
1409 ));
1410
1411 $IMProvider = array(
1412 'im_provider' => array(
1413 'name' => 'im_provider',
1414 'where' => 'civicrm_im.provider_id',
1415 'title' => ts('IM Provider'),
1416 ));
1417
1418 $locationFields = array_merge($locationType,
1419 CRM_Core_DAO_Address::export(),
1420 CRM_Core_DAO_Phone::export(),
1421 CRM_Core_DAO_Email::export(),
1422 $IMProvider,
1423 CRM_Core_DAO_IM::export(TRUE),
1424 CRM_Core_DAO_OpenID::export()
1425 );
1426
1427 $locationFields = array_merge($locationFields,
1428 CRM_Core_BAO_CustomField::getFieldsForImport('Address')
1429 );
1430
1431 foreach ($locationFields as $key => $field) {
1432 $locationFields[$key]['hasLocationType'] = TRUE;
1433 }
1434
1435 $fields = array_merge($fields, $locationFields);
1436
1437 //add world region
1438 $fields = array_merge($fields,
1439 CRM_Core_DAO_Worldregion::export()
1440 );
1441
1442
1443 $fields = array_merge($fields,
1444 CRM_Contact_DAO_Contact::export()
1445 );
1446
1447 //website fields
1448 $fields = array_merge($fields, CRM_Core_DAO_Website::export());
1449
1450 if ($contactType != 'All') {
1451 $fields = array_merge($fields,
1452 CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord)
1453 );
1454 }
1455 else {
1456 foreach (array(
1457 'Individual', 'Household', 'Organization') as $type) {
1458 $fields = array_merge($fields,
1459 CRM_Core_BAO_CustomField::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1460 );
1461 }
1462 }
1463
1464 //fix for CRM-791
1465 if ($export) {
1466 $fields = array_merge($fields, array(
1467 'groups' => array(
1468 'title' => ts('Group(s)'),
1469 'name' => 'groups',
1470 ),
1471 'tags' => array(
1472 'title' => ts('Tag(s)'),
1473 'name' => 'tags',
1474 ),
1475 'notes' => array(
1476 'title' => ts('Note(s)'),
1477 'name' => 'notes',
1478 ),
1479 ));
1480 }
1481 else {
1482 $fields = array_merge($fields, array(
1483 'group' => array(
1484 'title' => ts('Group(s)'),
1485 'name' => 'group',
1486 ),
1487 'tag' => array(
1488 'title' => ts('Tag(s)'),
1489 'name' => 'tag',
1490 ),
1491 'note' => array(
1492 'title' => ts('Note(s)'),
1493 'name' => 'note',
1494 ),
1495 ));
1496 }
1497
1498 //Sorting fields in alphabetical order(CRM-1507)
1499 foreach ($fields as $k => $v) {
1500 $sortArray[$k] = CRM_Utils_Array::value('title', $v);
1501 }
1502
1503 $fields = array_merge($sortArray, $fields);
1504 //unset the field which are not related to their contact type.
1505 if ($contactType != 'All') {
1506 $commonValues = array(
1507 'Individual' => array(
1508 'household_name',
1509 'legal_name',
1510 'sic_code',
1511 'organization_name',
1512 'email_greeting_custom',
1513 'postal_greeting_custom',
1514 'addressee_custom',
1515 ),
1516 'Household' => array(
1517 'first_name',
1518 'middle_name',
1519 'last_name',
1520 'formal_title',
1521 'job_title',
1522 'gender_id',
1523 'prefix_id',
1524 'suffix_id',
1525 'birth_date',
1526 'organization_name',
1527 'legal_name',
1528 'legal_identifier',
1529 'sic_code',
1530 'home_URL',
1531 'is_deceased',
1532 'deceased_date',
1533 'current_employer',
1534 'email_greeting_custom',
1535 'postal_greeting_custom',
1536 'addressee_custom',
1537 'prefix_id',
1538 'suffix_id'
1539 ),
1540 'Organization' => array(
1541 'first_name',
1542 'middle_name',
1543 'last_name',
1544 'formal_title',
1545 'job_title',
1546 'gender_id',
1547 'prefix_id',
1548 'suffix_id',
1549 'birth_date',
1550 'household_name',
1551 'email_greeting_custom',
1552 'postal_greeting_custom',
1553 'prefix_id',
1554 'suffix_id',
1555 'gender_id',
1556 'addressee_custom',
1557 'is_deceased',
1558 'deceased_date',
1559 'current_employer',
1560 ),
1561 );
1562 foreach ($commonValues[$contactType] as $value) {
1563 unset($fields[$value]);
1564 }
1565 }
1566
1567 CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
1568 }
1569 self::$_exportableFields[$cacheKeyString] = $fields;
1570 }
1571
1572 if (!$status) {
1573 $fields = self::$_exportableFields[$cacheKeyString];
1574 }
1575 else {
1576 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1577 self::$_exportableFields[$cacheKeyString]
1578 );
1579 }
1580
1581 return $fields;
1582 }
1583
1584 /**
1585 * Function to get the all contact details(Hierarchical)
1586 *
1587 * @param int $contactId contact id
1588 * @param array $fields fields array
1589 *
1590 * @return $values array contains the contact details
1591 * @static
1592 * @access public
1593 */
1594 static function getHierContactDetails($contactId, &$fields) {
1595 $params = array(array('contact_id', '=', $contactId, 0, 0));
1596 $options = array();
1597
1598 $returnProperties = self::makeHierReturnProperties($fields, $contactId);
1599
1600 // we dont know the contents of return properties, but we need the lower level ids of the contact
1601 // so add a few fields
1602 $returnProperties['first_name'] =
1603 $returnProperties['organization_name'] =
1604 $returnProperties['household_name'] =
1605 $returnProperties['contact_type'] =
1606 $returnProperties['contact_sub_type'] = 1;
1607 return list($query, $options) = CRM_Contact_BAO_Query::apiQuery($params, $returnProperties, $options);
1608 }
1609
1610 /**
1611 * given a set of flat profile style field names, create a hierarchy
1612 * for query to use and crete the right sql
1613 *
1614 * @param $fields
1615 * @param int $contactId contact id
1616 *
1617 * @internal param array $properties a flat return properties name value array
1618 * @return array a hierarchical property tree if appropriate
1619 * @access public
1620 * @static
1621 */
1622 static function &makeHierReturnProperties($fields, $contactId = NULL) {
1623 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
1624
1625 $returnProperties = array();
1626
1627 $multipleFields = array('website' => 'url');
1628 foreach ($fields as $name => $dontCare) {
1629 if (strpos($name, '-') !== FALSE) {
1630 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3);
1631
1632 if (!in_array($fieldName, $multipleFields)) {
1633 if ($id == 'Primary') {
1634 $locationTypeName = 1;
1635 }
1636 else {
1637 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
1638 if (!$locationTypeName) {
1639 continue;
1640 }
1641 }
1642
1643 if (empty($returnProperties['location'])) {
1644 $returnProperties['location'] = array();
1645 }
1646 if (empty($returnProperties['location'][$locationTypeName])) {
1647 $returnProperties['location'][$locationTypeName] = array();
1648 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1649 }
1650 if (in_array($fieldName, array(
1651 'phone', 'im', 'email', 'openid', 'phone_ext'))) {
1652 if ($type) {
1653 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1654 }
1655 else {
1656 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1657 }
1658 }
1659 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1660 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1661 }
1662 else {
1663 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1664 }
1665 }
1666 else {
1667 $returnProperties['website'][$id][$fieldName] = 1;
1668 }
1669 }
1670 else {
1671 $returnProperties[$name] = 1;
1672 }
1673 }
1674
1675 return $returnProperties;
1676 }
1677
1678 /**
1679 * Function to return the primary location type of a contact
1680 *
1681 * $params int $contactId contact_id
1682 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1683 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1684 *
1685 * @param $contactId
1686 * @param bool $skipDefaultPriamry
1687 * @param null $block
1688 *
1689 * @return int $locationType location_type_id
1690 * @access public
1691 * @static
1692 */
1693 static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1694 if($block){
1695 $entityBlock = array('contact_id' => $contactId);
1696 $blocks = CRM_Core_BAO_Location::getValues($entityBlock);
1697 foreach($blocks[$block] as $key => $value){
1698 if (!empty($value['is_primary'])){
1699 $locationType = CRM_Utils_Array::value('location_type_id',$value);
1700 }
1701 }
1702 }
1703 else {
1704 $query = "
1705 SELECT
1706 IF ( civicrm_email.location_type_id IS NULL,
1707 IF ( civicrm_address.location_type_id IS NULL,
1708 IF ( civicrm_phone.location_type_id IS NULL,
1709 IF ( civicrm_im.location_type_id IS NULL,
1710 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1711 ,civicrm_im.location_type_id)
1712 ,civicrm_phone.location_type_id)
1713 ,civicrm_address.location_type_id)
1714 ,civicrm_email.location_type_id) as locationType
1715 FROM civicrm_contact
1716 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1717 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1718 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1719 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1720 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1721 WHERE civicrm_contact.id = %1 ";
1722
1723 $params = array(1 => array($contactId, 'Integer'));
1724
1725 $dao = CRM_Core_DAO::executeQuery($query, $params);
1726
1727 $locationType = NULL;
1728 if ($dao->fetch()) {
1729 $locationType = $dao->locationType;
1730 }
1731 }
1732 if (isset($locationType)) {
1733 return $locationType;
1734 }
1735 elseif ($skipDefaultPriamry) {
1736 // if there is no primary contact location then return null
1737 return NULL;
1738 }
1739 else {
1740 // if there is no primart contact location, then return default
1741 // location type of the system
1742 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
1743 return $defaultLocationType->id;
1744 }
1745 }
1746
1747 /**
1748 * function to get the display name, primary email and location type of a contact
1749 *
1750 * @param int $id id of the contact
1751 *
1752 * @return array of display_name, email if found, do_not_email or (null,null,null)
1753 * @static
1754 * @access public
1755 */
1756 static function getContactDetails($id) {
1757 // check if the contact type
1758 $contactType = self::getContactType($id);
1759
1760 $nameFields = ($contactType == 'Individual') ? "civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1761
1762 $sql = "
1763 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1764 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1765 WHERE civicrm_contact.id = %1
1766 ORDER BY civicrm_email.is_primary DESC";
1767 $params = array(1 => array($id, 'Integer'));
1768 $dao = CRM_Core_DAO::executeQuery($sql, $params);
1769
1770 if ($dao->fetch()) {
1771 if ($contactType == 'Individual') {
1772 if ($dao->first_name || $dao->last_name) {
1773 $name = "{$dao->first_name} {$dao->last_name}";
1774 }
1775 else {
1776 $name = $dao->display_name;
1777 }
1778 }
1779 else {
1780 $name = $dao->display_name;
1781 }
1782 $email = $dao->email;
1783 $doNotEmail = $dao->do_not_email ? TRUE : FALSE;
1784 $onHold = $dao->on_hold ? TRUE : FALSE;
1785 $isDeceased = $dao->is_deceased ? TRUE : FALSE;
1786 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1787 }
1788 return array(NULL, NULL, NULL, NULL, NULL);
1789 }
1790
1791 /**
1792 * function to add/edit/register contacts through profile.
1793 *
1794 * @params array $params Array of profile fields to be edited/added.
1795 * @params int $contactID contact_id of the contact to be edited/added.
1796 * @params array $fields array of fields from UFGroup
1797 * @params int $addToGroupID specifies the default group to which contact is added.
1798 * @params int $ufGroupId uf group id (profile id)
1799 * @param $params
1800 * @param $fields
1801 * @param null $contactID
1802 * @param null $addToGroupID
1803 * @param null $ufGroupId
1804 * @param string $ctype contact type
1805 * @param boolean $visibility basically lets us know where this request is coming from
1806 * if via a profile from web, we restrict what groups are changed
1807 *
1808 * @return int contact id created/edited
1809 * @static
1810 * @access public
1811 */
1812 static function createProfileContact(
1813 &$params,
1814 &$fields,
1815 $contactID = NULL,
1816 $addToGroupID = NULL,
1817 $ufGroupId = NULL,
1818 $ctype = NULL,
1819 $visibility = FALSE
1820 ) {
1821 // add ufGroupID to params array ( CRM-2012 )
1822 if ($ufGroupId) {
1823 $params['uf_group_id'] = $ufGroupId;
1824 }
1825
1826 if ($contactID) {
1827 $editHook = TRUE;
1828 CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params);
1829 }
1830 else {
1831 $editHook = FALSE;
1832 CRM_Utils_Hook::pre('create', 'Profile', NULL, $params);
1833 }
1834
1835 list($data, $contactDetails) = self::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1836
1837 // manage is_opt_out
1838 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1839 $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, FALSE);
1840 $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
1841 $data['is_opt_out'] = $isOptOut;
1842 // on change, create new civicrm_subscription_history entry
1843 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1844 $shParams = array(
1845 'contact_id' => $contactDetails['contact_id'],
1846 'status' => $isOptOut ? 'Removed' : 'Added',
1847 'method' => 'Web',
1848 );
1849 CRM_Contact_BAO_SubscriptionHistory::create($shParams);
1850 }
1851 }
1852
1853 $contact = self::create($data);
1854
1855 // contact is null if the profile does not have any contact fields
1856 if ($contact) {
1857 $contactID = $contact->id;
1858 }
1859
1860 if (empty($contactID)) {
1861 CRM_Core_Error::fatal('Cannot proceed without a valid contact id');
1862 }
1863
1864 // Process group and tag
1865 if (!empty($fields['group'])) {
1866 $method = 'Admin';
1867 // this for sure means we are coming in via profile since i added it to fix
1868 // removing contacts from user groups -- lobo
1869 if ($visibility) {
1870 $method = 'Web';
1871 }
1872 CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method);
1873 }
1874
1875 if (!empty($fields['tag'])) {
1876 CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $contactID);
1877 }
1878
1879 //to add profile in default group
1880 if (is_array($addToGroupID)) {
1881 $contactIds = array($contactID);
1882 foreach ($addToGroupID as $groupId) {
1883 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
1884 }
1885 }
1886 elseif ($addToGroupID) {
1887 $contactIds = array($contactID);
1888 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID);
1889 }
1890
1891 // reset the group contact cache for this group
1892 CRM_Contact_BAO_GroupContactCache::remove();
1893
1894 if ($editHook) {
1895 CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params);
1896 }
1897 else {
1898 CRM_Utils_Hook::post('create', 'Profile', $contactID, $params);
1899 }
1900 return $contactID;
1901 }
1902
1903 /**
1904 * @param $params
1905 * @param $fields
1906 * @param null $contactID
1907 * @param null $ufGroupId
1908 * @param null $ctype
1909 * @param bool $skipCustom
1910 *
1911 * @return array
1912 */
1913 static function formatProfileContactParams(
1914 &$params,
1915 &$fields,
1916 $contactID = NULL,
1917 $ufGroupId = NULL,
1918 $ctype = NULL,
1919 $skipCustom = FALSE
1920 ) {
1921
1922 $data = $contactDetails = array();
1923
1924 // get the contact details (hier)
1925 if ($contactID) {
1926 list($details, $options) = self::getHierContactDetails($contactID, $fields);
1927
1928 $contactDetails = $details[$contactID];
1929 $data['contact_type'] = CRM_Utils_Array::value('contact_type', $contactDetails);
1930 $data['contact_sub_type'] = CRM_Utils_Array::value('contact_sub_type', $contactDetails);
1931 }
1932 else {
1933 //we should get contact type only if contact
1934 if ($ufGroupId) {
1935 $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId);
1936
1937 //special case to handle profile with only contact fields
1938 if ($data['contact_type'] == 'Contact') {
1939 $data['contact_type'] = 'Individual';
1940 }
1941 elseif (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) {
1942 $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']);
1943 }
1944 }
1945 elseif ($ctype) {
1946 $data['contact_type'] = $ctype;
1947 }
1948 else {
1949 $data['contact_type'] = 'Individual';
1950 }
1951 }
1952
1953 //fix contact sub type CRM-5125
1954 if (array_key_exists('contact_sub_type', $params) &&
1955 !empty($params['contact_sub_type'])
1956 ) {
1957 $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;
1958 }
1959 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1960 !empty($params['contact_sub_type_hidden'])
1961 ) {
1962 // if profile was used, and had any subtype, we obtain it from there
1963 $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;
1964 }
1965
1966 if ($ctype == 'Organization') {
1967 $data['organization_name'] = CRM_Utils_Array::value('organization_name', $contactDetails);
1968 }
1969 elseif ($ctype == 'Household') {
1970 $data['household_name'] = CRM_Utils_Array::value('household_name', $contactDetails);
1971 }
1972
1973 $locationType = array();
1974 $count = 1;
1975
1976 if ($contactID) {
1977 //add contact id
1978 $data['contact_id'] = $contactID;
1979 $primaryLocationType = self::getPrimaryLocationType($contactID);
1980 }
1981 else {
1982 $defaultLocation = CRM_Core_BAO_LocationType::getDefault();
1983 $defaultLocationId = $defaultLocation->id;
1984 }
1985
1986 // get the billing location type
1987 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1988 $billingLocationTypeId = array_search('Billing', $locationTypes);
1989
1990 $blocks = array('email', 'phone', 'im', 'openid');
1991
1992 $multiplFields = array('url');
1993 // prevent overwritten of formatted array, reset all block from
1994 // params if it is not in valid format (since import pass valid format)
1995 foreach ($blocks as $blk) {
1996 if (array_key_exists($blk, $params) &&
1997 !is_array($params[$blk])
1998 ) {
1999 unset($params[$blk]);
2000 }
2001 }
2002
2003 $primaryPhoneLoc = NULL;
2004 $session = CRM_Core_Session::singleton();
2005 foreach ($params as $key => $value) {
2006 $fieldName = $locTypeId = $typeId = NULL;
2007 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3);
2008
2009 //store original location type id
2010 $actualLocTypeId = $locTypeId;
2011
2012 if ($locTypeId == 'Primary') {
2013 if ($contactID) {
2014 if(in_array( $fieldName, $blocks)){
2015 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, $fieldName);
2016 }
2017 else{
2018 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, 'address');
2019 }
2020 $primaryLocationType = $locTypeId;
2021 }
2022 else {
2023 $locTypeId = $defaultLocationId;
2024 }
2025 }
2026
2027 if (is_numeric($locTypeId) &&
2028 !in_array($fieldName, $multiplFields) &&
2029 substr($fieldName, 0, 7) != 'custom_'
2030 ) {
2031 $index = $locTypeId;
2032
2033 if (is_numeric($typeId)) {
2034 $index .= '-' . $typeId;
2035 }
2036 if (!in_array($index, $locationType)) {
2037 $locationType[$count] = $index;
2038 $count++;
2039 }
2040
2041 $loc = CRM_Utils_Array::key($index, $locationType);
2042
2043 $blockName = in_array( $fieldName, $blocks) ? $fieldName : 'address';
2044
2045 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2046
2047 //set is_billing true, for location type "Billing"
2048 if ($locTypeId == $billingLocationTypeId) {
2049 $data[$blockName][$loc]['is_billing'] = 1;
2050 }
2051
2052 if ($contactID) {
2053 //get the primary location type
2054 if ($locTypeId == $primaryLocationType) {
2055 $data[$blockName][$loc]['is_primary'] = 1;
2056 }
2057 }
2058 elseif ($locTypeId == $defaultLocationId) {
2059 $data[$blockName][$loc]['is_primary'] = 1;
2060 }
2061
2062 if ( in_array($fieldName, array('phone'))) {
2063 if ($typeId) {
2064 $data['phone'][$loc]['phone_type_id'] = $typeId;
2065 }
2066 else {
2067 $data['phone'][$loc]['phone_type_id'] = '';
2068 }
2069 $data['phone'][$loc]['phone'] = $value;
2070
2071 //special case to handle primary phone with different phone types
2072 // in this case we make first phone type as primary
2073 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2074 $primaryPhoneLoc = $loc;
2075 }
2076
2077 if ($loc != $primaryPhoneLoc) {
2078 unset($data['phone'][$loc]['is_primary']);
2079 }
2080 }
2081 elseif ($fieldName == 'phone_ext') {
2082 $data['phone'][$loc]['phone_ext'] = $value;
2083 }
2084 elseif ($fieldName == 'email') {
2085 $data['email'][$loc]['email'] = $value;
2086 }
2087 elseif ($fieldName == 'im') {
2088 if (isset($params[$key . '-provider_id'])) {
2089 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2090 }
2091 if (strpos($key, '-provider_id') !== FALSE) {
2092 $data['im'][$loc]['provider_id'] = $params[$key];
2093 }
2094 else {
2095 $data['im'][$loc]['name'] = $value;
2096 }
2097 }
2098 elseif ($fieldName == 'openid') {
2099 $data['openid'][$loc]['openid'] = $value;
2100 }
2101 else {
2102 if ($fieldName === 'state_province') {
2103 // CRM-3393
2104 if (is_numeric($value) && ((int ) $value) >= 1000) {
2105 $data['address'][$loc]['state_province_id'] = $value;
2106 }
2107 elseif (empty($value)) {
2108 $data['address'][$loc]['state_province_id'] = '';
2109 }
2110 else {
2111 $data['address'][$loc]['state_province'] = $value;
2112 }
2113 }
2114 elseif ($fieldName === 'country') {
2115 // CRM-3393
2116 if (is_numeric($value) && ((int ) $value) >= 1000
2117 ) {
2118 $data['address'][$loc]['country_id'] = $value;
2119 }
2120 elseif (empty($value)) {
2121 $data['address'][$loc]['country_id'] = '';
2122 }
2123 else {
2124 $data['address'][$loc]['country'] = $value;
2125 }
2126 }
2127 elseif ($fieldName === 'county') {
2128 $data['address'][$loc]['county_id'] = $value;
2129 }
2130 elseif ($fieldName == 'address_name') {
2131 $data['address'][$loc]['name'] = $value;
2132 }
2133 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2134 $data['address'][$loc][substr($fieldName, 8)] = $value;
2135 }
2136 else {
2137 $data['address'][$loc][$fieldName] = $value;
2138 }
2139 }
2140 }
2141 else {
2142 if (substr($key, 0, 4) === 'url-') {
2143 $websiteField = explode('-', $key);
2144 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2145 $data['website'][$websiteField[1]]['url'] = $value;
2146 }
2147 elseif (in_array($key, self::$_greetingTypes, TRUE)) {
2148 //save email/postal greeting and addressee values if any, CRM-4575
2149 $data[$key . '_id'] = $value;
2150 }
2151 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) {
2152 // for autocomplete transfer hidden value instead of label
2153 if ($params[$key] && isset($params[$key . '_id'])) {
2154 $value = $params[$key . '_id'];
2155 }
2156
2157 // we need to append time with date
2158 if ($params[$key] && isset($params[$key . '_time'])) {
2159 $value .= ' ' . $params[$key . '_time'];
2160 }
2161
2162 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2163 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 &&
2164 ($value == '' || !isset($value))) {
2165 continue;
2166 }
2167
2168 $valueId = NULL;
2169 if (!empty($params['customRecordValues'])) {
2170 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2171 foreach ($params['customRecordValues'] as $recId => $customFields) {
2172 if (is_array($customFields) && !empty($customFields)) {
2173 foreach ($customFields as $customFieldName) {
2174 if ($customFieldName == $key) {
2175 $valueId = $recId;
2176 break;
2177 }
2178 }
2179 }
2180 }
2181 }
2182 }
2183
2184 $type = $data['contact_type'];
2185 if (!empty($data['contact_sub_type'])) {
2186 $type = $data['contact_sub_type'];
2187 $type = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($type, CRM_Core_DAO::VALUE_SEPARATOR));
2188 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2189 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2190 // as the results going to be same.
2191 $type = $type[0];
2192 }
2193
2194 CRM_Core_BAO_CustomField::formatCustomField($customFieldId,
2195 $data['custom'],
2196 $value,
2197 $type,
2198 $valueId,
2199 $contactID
2200 );
2201 }
2202 elseif ($key == 'edit') {
2203 continue;
2204 }
2205 else {
2206 if ($key == 'location') {
2207 foreach ($value as $locationTypeId => $field) {
2208 foreach ($field as $block => $val) {
2209 if ($block == 'address' && array_key_exists('address_name', $val)) {
2210 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2211 }
2212 }
2213 }
2214 }
2215 if($key == 'phone' && isset($params['phone_ext'])){
2216 $data[$key] = $value;
2217 foreach($value as $cnt => $phoneBlock){
2218 if($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']){
2219 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2220 }
2221 }
2222 }
2223 else if (in_array($key,
2224 array('nick_name',
2225 'job_title',
2226 'middle_name',
2227 'birth_date',
2228 'gender_id',
2229 'current_employer',
2230 'prefix_id',
2231 'suffix_id')) &&
2232 ($value == '' || !isset($value)) &&
2233 ($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0) {
2234 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2235 // to avoid update with empty values
2236 continue;
2237 }
2238 else {
2239 $data[$key] = $value;
2240 }
2241 }
2242 }
2243 }
2244
2245 if (!isset($data['contact_type'])) {
2246 $data['contact_type'] = 'Individual';
2247 }
2248
2249 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2250 $privacy = CRM_Core_SelectValues::privacy();
2251 foreach ($privacy as $key => $value) {
2252 if (array_key_exists($key, $fields)) {
2253 // do not reset values for existing contacts, if fields are added to a profile
2254 if (array_key_exists($key, $params)) {
2255 $data[$key] = $params[$key];
2256 if (empty($params[$key])) {
2257 $data[$key] = 0;
2258 }
2259 }
2260 elseif (!$contactID) {
2261 $data[$key] = 0;
2262 }
2263 }
2264 }
2265
2266 return array($data, $contactDetails);
2267 }
2268
2269 /**
2270 * Function to find the get contact details
2271 * does not respect ACLs for now, which might need to be rectified at some
2272 * stage based on how its used
2273 *
2274 * @param string $mail primary email address of the contact
2275 * @param string $ctype contact type
2276 *
2277 * @return object $dao contact details
2278 * @static
2279 */
2280 static function &matchContactOnEmail($mail, $ctype = NULL) {
2281 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2282 $mail = $strtolower(trim($mail));
2283 $query = "
2284 SELECT civicrm_contact.id as contact_id,
2285 civicrm_contact.hash as hash,
2286 civicrm_contact.contact_type as contact_type,
2287 civicrm_contact.contact_sub_type as contact_sub_type
2288 FROM civicrm_contact
2289 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2290
2291
2292 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
2293 'uniq_email_per_site'
2294 )) {
2295 // try to find a match within a site (multisite).
2296 $groups = CRM_Core_BAO_Domain::getChildGroupIds();
2297 if (!empty($groups)) {
2298 $query .= "
2299 INNER JOIN civicrm_group_contact gc ON
2300 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2301 }
2302 }
2303
2304 $query .= "
2305 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2306 $p = array(1 => array($mail, 'String'));
2307
2308 if ($ctype) {
2309 $query .= " AND civicrm_contact.contact_type = %3";
2310 $p[3] = array($ctype, 'String');
2311 }
2312
2313 $query .= " ORDER BY civicrm_email.is_primary DESC";
2314
2315 $dao = CRM_Core_DAO::executeQuery($query, $p);
2316
2317 if ($dao->fetch()) {
2318 return $dao;
2319 }
2320 return CRM_Core_DAO::$_nullObject;
2321 }
2322
2323 /**
2324 * Function to find the contact details associated with an OpenID
2325 *
2326 * @param string $openId openId of the contact
2327 * @param string $ctype contact type
2328 *
2329 * @return object $dao contact details
2330 * @static
2331 */
2332 static function &matchContactOnOpenId($openId, $ctype = NULL) {
2333 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2334 $openId = $strtolower(trim($openId));
2335 $query = "
2336 SELECT civicrm_contact.id as contact_id,
2337 civicrm_contact.hash as hash,
2338 civicrm_contact.contact_type as contact_type,
2339 civicrm_contact.contact_sub_type as contact_sub_type
2340 FROM civicrm_contact
2341 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2342 WHERE civicrm_openid.openid = %1";
2343 $p = array(1 => array($openId, 'String'));
2344
2345 if ($ctype) {
2346 $query .= " AND civicrm_contact.contact_type = %3";
2347 $p[3] = array($ctype, 'String');
2348 }
2349
2350 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2351
2352 $dao = CRM_Core_DAO::executeQuery($query, $p);
2353
2354 if ($dao->fetch()) {
2355 return $dao;
2356 }
2357 return CRM_Core_DAO::$_nullObject;
2358 }
2359
2360 /**
2361 * Funtion to get primary email of the contact
2362 *
2363 * @param int $contactID contact id
2364 *
2365 * @return string $dao->email email address if present else null
2366 * @static
2367 * @access public
2368 */
2369 public static function getPrimaryEmail($contactID) {
2370 // fetch the primary email
2371 $query = "
2372 SELECT civicrm_email.email as email
2373 FROM civicrm_contact
2374 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2375 WHERE civicrm_email.is_primary = 1
2376 AND civicrm_contact.id = %1";
2377 $p = array(1 => array($contactID, 'Integer'));
2378 $dao = CRM_Core_DAO::executeQuery($query, $p);
2379
2380 $email = NULL;
2381 if ($dao->fetch()) {
2382 $email = $dao->email;
2383 }
2384 $dao->free();
2385 return $email;
2386 }
2387
2388 /**
2389 * Funtion to get primary OpenID of the contact
2390 *
2391 * @param int $contactID contact id
2392 *
2393 * @return string $dao->openid OpenID if present else null
2394 * @static
2395 * @access public
2396 */
2397 public static function getPrimaryOpenId($contactID) {
2398 // fetch the primary OpenID
2399 $query = "
2400 SELECT civicrm_openid.openid as openid
2401 FROM civicrm_contact
2402 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2403 WHERE civicrm_contact.id = %1
2404 AND civicrm_openid.is_primary = 1";
2405 $p = array(1 => array($contactID, 'Integer'));
2406 $dao = CRM_Core_DAO::executeQuery($query, $p);
2407
2408 $openId = NULL;
2409 if ($dao->fetch()) {
2410 $openId = $dao->openid;
2411 }
2412 $dao->free();
2413 return $openId;
2414 }
2415
2416 /**
2417 * Given the list of params in the params array, fetch the object
2418 * and store the values in the values array
2419 *
2420 * @param array $params input parameters to find object
2421 * @param array $values output values of the object
2422 *
2423 * @return CRM_Contact_BAO_Contact|null the found object or null
2424 * @access public
2425 * @static
2426 */
2427 public static function getValues(&$params, &$values) {
2428 $contact = new CRM_Contact_BAO_Contact();
2429
2430 $contact->copyValues($params);
2431
2432 if ($contact->find(TRUE)) {
2433
2434 CRM_Core_DAO::storeValues($contact, $values);
2435
2436 $privacy = array();
2437 foreach (self::$_commPrefs as $name) {
2438 if (isset($contact->$name)) {
2439 $privacy[$name] = $contact->$name;
2440 }
2441 }
2442
2443 if (!empty($privacy)) {
2444 $values['privacy'] = $privacy;
2445 }
2446
2447 // communication Prefferance
2448 $preffComm = $comm = array();
2449 $comm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2450 $contact->preferred_communication_method
2451 );
2452 foreach ($comm as $value) {
2453 $preffComm[$value] = 1;
2454 }
2455 $temp = array('preferred_communication_method' => $contact->preferred_communication_method);
2456
2457 $names = array(
2458 'preferred_communication_method' => array('newName' => 'preferred_communication_method_display',
2459 'groupName' => 'preferred_communication_method',
2460 ));
2461
2462 CRM_Core_OptionGroup::lookupValues($temp, $names, FALSE);
2463
2464 $values['preferred_communication_method'] = $preffComm;
2465 $values['preferred_communication_method_display'] = CRM_Utils_Array::value('preferred_communication_method_display', $temp);
2466
2467 $preferredMailingFormat = CRM_Core_SelectValues::pmf();
2468 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format];
2469
2470 // get preferred languages
2471 if (!empty($contact->preferred_language)) {
2472 $values['preferred_language'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language);
2473 }
2474
2475 // Calculating Year difference
2476 if ($contact->birth_date) {
2477 $birthDate = CRM_Utils_Date::customFormat($contact->birth_date, '%Y%m%d');
2478 if ($birthDate < date('Ymd')) {
2479 $age = CRM_Utils_Date::calculateAge($birthDate);
2480 $values['age']['y'] = CRM_Utils_Array::value('years', $age);
2481 $values['age']['m'] = CRM_Utils_Array::value('months', $age);
2482 }
2483
2484 list($values['birth_date']) = CRM_Utils_Date::setDateDefaults($contact->birth_date, 'birth');
2485 $values['birth_date_display'] = $contact->birth_date;
2486 }
2487
2488 if ($contact->deceased_date) {
2489 list($values['deceased_date']) = CRM_Utils_Date::setDateDefaults($contact->deceased_date, 'birth');
2490 $values['deceased_date_display'] = $contact->deceased_date;
2491 }
2492
2493 $contact->contact_id = $contact->id;
2494
2495 return $contact;
2496 }
2497 return NULL;
2498 }
2499
2500 /**
2501 * Given the component name and returns
2502 * the count of participation of contact
2503 *
2504 * @param string $component input component name
2505 * @param integer $contactId input contact id
2506 * @param string $tableName optional tableName if component is custom group
2507 *
2508 * @return total number of count of occurence in database
2509 * @access public
2510 * @static
2511 */
2512 static function getCountComponent($component, $contactId, $tableName = NULL) {
2513 $object = NULL;
2514 switch ($component) {
2515 case 'tag':
2516 return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE);
2517
2518 case 'rel':
2519 return CRM_Contact_BAO_Relationship::getRelationship($contactId,
2520 CRM_Contact_BAO_Relationship::CURRENT,
2521 0, 1
2522 );
2523
2524 case 'group':
2525 return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE);
2526
2527 case 'log':
2528 if (CRM_Core_BAO_Log::useLoggingReport()) {
2529 return FALSE;
2530 }
2531 return CRM_Core_BAO_Log::getContactLogCount($contactId);
2532
2533 case 'note':
2534 return CRM_Core_BAO_Note::getContactNoteCount($contactId);
2535
2536 case 'contribution':
2537 return CRM_Contribute_BAO_Contribution::contributionCount($contactId);
2538
2539 case 'membership':
2540 return CRM_Member_BAO_Membership::getContactMembershipCount($contactId, TRUE);
2541
2542 case 'participant':
2543 return CRM_Event_BAO_Participant::getContactParticipantCount($contactId);
2544
2545 case 'pledge':
2546 return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId);
2547
2548 case 'case':
2549 return CRM_Case_BAO_Case::caseCount($contactId);
2550
2551 case 'grant':
2552 return CRM_Grant_BAO_Grant::getContactGrantCount($contactId);
2553
2554 case 'activity':
2555 $input = array(
2556 'contact_id' => $contactId,
2557 'admin' => FALSE,
2558 'caseId' => NULL,
2559 'context' => 'activity',
2560 );
2561 return CRM_Activity_BAO_Activity::getActivitiesCount($input);
2562
2563 case 'mailing':
2564 $params = array('contact_id' => $contactId);
2565 return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
2566
2567 default:
2568 $custom = explode('_', $component);
2569 if ($custom['0'] = 'custom') {
2570 if (!$tableName) {
2571 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2572 }
2573 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2574 return CRM_Core_DAO::singleValueQuery($queryString);
2575 }
2576 }
2577 }
2578
2579 /**
2580 * Function to process greetings and cache
2581 *
2582 * @param object $contact contact object after save
2583 * @param boolean $useDefaults use default greeting values
2584 *
2585 * @return void
2586 * @access public
2587 * @static
2588 */
2589 static function processGreetings(&$contact, $useDefaults = FALSE) {
2590 if ($useDefaults) {
2591 //retrieve default greetings
2592 $defaultGreetings = CRM_Core_PseudoConstant::greetingDefaults();
2593 $contactDefaults = $defaultGreetings[$contact->contact_type];
2594 }
2595
2596 // note that contact object not always has required greeting related
2597 // fields that are required to calculate greeting and
2598 // also other fields used in tokens etc,
2599 // hence we need to retrieve it again.
2600 if ( $contact->_query !== FALSE ) {
2601 $contact->find(TRUE);
2602 }
2603
2604 // store object values to an array
2605 $contactDetails = array();
2606 CRM_Core_DAO::storeValues($contact, $contactDetails);
2607 $contactDetails = array(array($contact->id => $contactDetails));
2608
2609 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2610 $updateQueryString = array();
2611
2612 //cache email and postal greeting to greeting display
2613 if ($contact->email_greeting_custom != 'null' && $contact->email_greeting_custom) {
2614 $emailGreetingString = $contact->email_greeting_custom;
2615 }
2616 elseif ($contact->email_greeting_id != 'null' && $contact->email_greeting_id) {
2617 // the filter value for Individual contact type is set to 1
2618 $filter = array(
2619 'contact_type' => $contact->contact_type,
2620 'greeting_type' => 'email_greeting',
2621 );
2622
2623 $emailGreeting = CRM_Core_PseudoConstant::greeting($filter);
2624 $emailGreetingString = $emailGreeting[$contact->email_greeting_id];
2625 $updateQueryString[] = " email_greeting_custom = NULL ";
2626 }
2627 else {
2628 if ($useDefaults) {
2629 reset($contactDefaults['email_greeting']);
2630 $emailGreetingID = key($contactDefaults['email_greeting']);
2631 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2632 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2633 $updateQueryString[] = " email_greeting_custom = NULL ";
2634 }
2635 elseif ($contact->email_greeting_custom) {
2636 $updateQueryString[] = " email_greeting_display = NULL ";
2637 }
2638 }
2639
2640 if ($emailGreetingString) {
2641 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($emailGreetingString,
2642 $contactDetails,
2643 $contact->id,
2644 'CRM_Contact_BAO_Contact'
2645 );
2646 $emailGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($emailGreetingString));
2647 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2648 }
2649
2650 //postal greetings
2651 if ($contact->postal_greeting_custom != 'null' && $contact->postal_greeting_custom) {
2652 $postalGreetingString = $contact->postal_greeting_custom;
2653 }
2654 elseif ($contact->postal_greeting_id != 'null' && $contact->postal_greeting_id) {
2655 $filter = array(
2656 'contact_type' => $contact->contact_type,
2657 'greeting_type' => 'postal_greeting',
2658 );
2659 $postalGreeting = CRM_Core_PseudoConstant::greeting($filter);
2660 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id];
2661 $updateQueryString[] = " postal_greeting_custom = NULL ";
2662 }
2663 else {
2664 if ($useDefaults) {
2665 reset($contactDefaults['postal_greeting']);
2666 $postalGreetingID = key($contactDefaults['postal_greeting']);
2667 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2668 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2669 $updateQueryString[] = " postal_greeting_custom = NULL ";
2670 }
2671 elseif ($contact->postal_greeting_custom) {
2672 $updateQueryString[] = " postal_greeting_display = NULL ";
2673 }
2674 }
2675
2676 if ($postalGreetingString) {
2677 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($postalGreetingString,
2678 $contactDetails,
2679 $contact->id,
2680 'CRM_Contact_BAO_Contact'
2681 );
2682 $postalGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($postalGreetingString));
2683 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2684 }
2685
2686 // addressee
2687 if ($contact->addressee_custom != 'null' && $contact->addressee_custom) {
2688 $addresseeString = $contact->addressee_custom;
2689 }
2690 elseif ($contact->addressee_id != 'null' && $contact->addressee_id) {
2691 $filter = array(
2692 'contact_type' => $contact->contact_type,
2693 'greeting_type' => 'addressee',
2694 );
2695
2696 $addressee = CRM_Core_PseudoConstant::greeting($filter);
2697 $addresseeString = $addressee[$contact->addressee_id];
2698 $updateQueryString[] = " addressee_custom = NULL ";
2699 }
2700 else {
2701 if ($useDefaults) {
2702 reset($contactDefaults['addressee']);
2703 $addresseeID = key($contactDefaults['addressee']);
2704 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2705 $updateQueryString[] = " addressee_id = $addresseeID ";
2706 $updateQueryString[] = " addressee_custom = NULL ";
2707 }
2708 elseif ($contact->addressee_custom) {
2709 $updateQueryString[] = " addressee_display = NULL ";
2710 }
2711 }
2712
2713 if ($addresseeString) {
2714 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($addresseeString,
2715 $contactDetails,
2716 $contact->id,
2717 'CRM_Contact_BAO_Contact'
2718 );
2719 $addresseeString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($addresseeString));
2720 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2721 }
2722
2723 if (!empty($updateQueryString)) {
2724 $updateQueryString = implode(',', $updateQueryString);
2725 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2726 CRM_Core_DAO::executeQuery($queryString);
2727 }
2728 }
2729
2730 /**
2731 * Function to retrieve loc block ids w/ given condition.
2732 *
2733 * @param int $contactId contact id.
2734 * @param array $criteria key => value pair which should be
2735 * fulfill by return record ids.
2736 * @param string $condOperator operator use for grouping multiple conditions.
2737 *
2738 * @return array $locBlockIds loc block ids which fulfill condition.
2739 * @static
2740 */
2741 static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2742 $locBlockIds = array();
2743 if (!$contactId) {
2744 return $locBlockIds;
2745 }
2746
2747 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2748 $name = strtolower($block);
2749 $className = "CRM_Core_DAO_$block";
2750 $blockDAO = new $className();
2751
2752 // build the condition.
2753 if (is_array($criteria)) {
2754 $fields = $blockDAO->fields();
2755 $conditions = array();
2756 foreach ($criteria as $field => $value) {
2757 if (array_key_exists($field, $fields)) {
2758 $cond = "( $field = $value )";
2759 // value might be zero or null.
2760 if (!$value || strtolower($value) == 'null') {
2761 $cond = "( $field = 0 OR $field IS NULL )";
2762 }
2763 $conditions[] = $cond;
2764 }
2765 }
2766 if (!empty($conditions)) {
2767 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2768 }
2769 }
2770
2771 $blockDAO->contact_id = $contactId;
2772 $blockDAO->find();
2773 while ($blockDAO->fetch()) {
2774 $locBlockIds[$name][] = $blockDAO->id;
2775 }
2776 $blockDAO->free();
2777 }
2778
2779 return $locBlockIds;
2780 }
2781
2782 /**
2783 * Function to build context menu items.
2784 *
2785 * @param null $contactId
2786 *
2787 * @return array of context menu for logged in user.
2788 * @static
2789 */
2790 static function contextMenu($contactId = NULL) {
2791 $menu = array(
2792 'view' => array(
2793 'title' => ts('View Contact'),
2794 'weight' => 0,
2795 'ref' => 'view-contact',
2796 'class' => 'no-popup',
2797 'key' => 'view',
2798 'permissions' => array('view all contacts'),
2799 ),
2800 'add' => array(
2801 'title' => ts('Edit Contact'),
2802 'weight' => 0,
2803 'ref' => 'edit-contact',
2804 'class' => 'no-popup',
2805 'key' => 'add',
2806 'permissions' => array('edit all contacts'),
2807 ),
2808 'delete' => array(
2809 'title' => ts('Delete Contact'),
2810 'weight' => 0,
2811 'ref' => 'delete-contact',
2812 'key' => 'delete',
2813 'permissions' => array('access deleted contacts', 'delete contacts'),
2814 ),
2815 'contribution' => array(
2816 'title' => ts('Add Contribution'),
2817 'weight' => 5,
2818 'ref' => 'new-contribution',
2819 'key' => 'contribution',
2820 'tab' => 'contribute',
2821 'component' => 'CiviContribute',
2822 'href' => CRM_Utils_System::url('civicrm/contact/view/contribution',
2823 'reset=1&action=add&context=contribution'
2824 ),
2825 'permissions' => array(
2826 'access CiviContribute',
2827 'edit contributions',
2828 ),
2829 ),
2830 'participant' => array(
2831 'title' => ts('Register for Event'),
2832 'weight' => 10,
2833 'ref' => 'new-participant',
2834 'key' => 'participant',
2835 'tab' => 'participant',
2836 'component' => 'CiviEvent',
2837 'href' => CRM_Utils_System::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2838 'permissions' => array(
2839 'access CiviEvent',
2840 'edit event participants',
2841 ),
2842 ),
2843 'activity' => array(
2844 'title' => ts('Record Activity'),
2845 'weight' => 35,
2846 'ref' => 'new-activity',
2847 'key' => 'activity',
2848 'permissions' => array('edit all contacts'),
2849 ),
2850 'pledge' => array(
2851 'title' => ts('Add Pledge'),
2852 'weight' => 15,
2853 'ref' => 'new-pledge',
2854 'key' => 'pledge',
2855 'tab' => 'pledge',
2856 'href' => CRM_Utils_System::url('civicrm/contact/view/pledge',
2857 'reset=1&action=add&context=pledge'
2858 ),
2859 'component' => 'CiviPledge',
2860 'permissions' => array(
2861 'access CiviPledge',
2862 'edit pledges',
2863 ),
2864 ),
2865 'membership' => array(
2866 'title' => ts('Add Membership'),
2867 'weight' => 20,
2868 'ref' => 'new-membership',
2869 'key' => 'membership',
2870 'tab' => 'member',
2871 'component' => 'CiviMember',
2872 'href' => CRM_Utils_System::url('civicrm/contact/view/membership',
2873 'reset=1&action=add&context=membership'
2874 ),
2875 'permissions' => array(
2876 'access CiviMember',
2877 'edit memberships',
2878 ),
2879 ),
2880 'case' => array(
2881 'title' => ts('Add Case'),
2882 'weight' => 25,
2883 'ref' => 'new-case',
2884 'key' => 'case',
2885 'tab' => 'case',
2886 'component' => 'CiviCase',
2887 'href' => CRM_Utils_System::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2888 'permissions' => array('add cases'),
2889 ),
2890 'grant' => array(
2891 'title' => ts('Add Grant'),
2892 'weight' => 26,
2893 'ref' => 'new-grant',
2894 'key' => 'grant',
2895 'tab' => 'grant',
2896 'component' => 'CiviGrant',
2897 'href' => CRM_Utils_System::url('civicrm/contact/view/grant',
2898 'reset=1&action=add&context=grant'
2899 ),
2900 'permissions' => array('edit grants'),
2901 ),
2902 'rel' => array(
2903 'title' => ts('Add Relationship'),
2904 'weight' => 30,
2905 'ref' => 'new-relationship',
2906 'key' => 'rel',
2907 'tab' => 'rel',
2908 'href' => CRM_Utils_System::url('civicrm/contact/view/rel',
2909 'reset=1&action=add'
2910 ),
2911 'permissions' => array('edit all contacts'),
2912 ),
2913 'note' => array(
2914 'title' => ts('Add Note'),
2915 'weight' => 40,
2916 'ref' => 'new-note',
2917 'key' => 'note',
2918 'tab' => 'note',
2919 'class' => 'medium-popup',
2920 'href' => CRM_Utils_System::url('civicrm/contact/view/note',
2921 'reset=1&action=add'
2922 ),
2923 'permissions' => array('edit all contacts'),
2924 ),
2925 'email' => array(
2926 'title' => ts('Send an Email'),
2927 'weight' => 45,
2928 'ref' => 'new-email',
2929 'key' => 'email',
2930 'permissions' => array('view all contacts'),
2931 ),
2932 'group' => array(
2933 'title' => ts('Add to Group'),
2934 'weight' => 50,
2935 'ref' => 'group-add-contact',
2936 'key' => 'group',
2937 'tab' => 'group',
2938 'permissions' => array('edit groups'),
2939 ),
2940 'tag' => array(
2941 'title' => ts('Tag Contact'),
2942 'weight' => 55,
2943 'ref' => 'tag-contact',
2944 'key' => 'tag',
2945 'tab' => 'tag',
2946 'permissions' => array('edit all contacts'),
2947 ),
2948 );
2949
2950 CRM_Utils_Hook::summaryActions($menu, $contactId);
2951 //1. check for component is active.
2952 //2. check for user permissions.
2953 //3. check for acls.
2954 //3. edit and view contact are directly accessible to user.
2955
2956 $aclPermissionedTasks = array(
2957 'view-contact', 'edit-contact', 'new-activity',
2958 'new-email', 'group-add-contact', 'tag-contact', 'delete-contact',
2959 );
2960 $corePermission = CRM_Core_Permission::getPermission();
2961
2962 $config = CRM_Core_Config::singleton();
2963
2964 $contextMenu = array();
2965 foreach ($menu as $key => $values) {
2966 $componentName = CRM_Utils_Array::value('component', $values);
2967
2968 // if component action - make sure component is enable.
2969 if ($componentName && !in_array($componentName, $config->enableComponents)) {
2970 continue;
2971 }
2972
2973 // make sure user has all required permissions.
2974 $hasAllPermissions = FALSE;
2975
2976 $permissions = CRM_Utils_Array::value('permissions', $values);
2977 if (!is_array($permissions) || empty($permissions)) {
2978 $hasAllPermissions = TRUE;
2979 }
2980
2981 // iterate for required permissions in given permissions array.
2982 if (!$hasAllPermissions) {
2983 $hasPermissions = 0;
2984 foreach ($permissions as $permission) {
2985 if (CRM_Core_Permission::check($permission)) {
2986 $hasPermissions++;
2987 }
2988 }
2989
2990 if (count($permissions) == $hasPermissions) {
2991 $hasAllPermissions = TRUE;
2992 }
2993
2994 // if still user does not have required permissions, check acl.
2995 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
2996 if (in_array($values['ref'], $aclPermissionedTasks) &&
2997 $corePermission == CRM_Core_Permission::EDIT
2998 ) {
2999 $hasAllPermissions = TRUE;
3000 }
3001 elseif (in_array($values['ref'], array(
3002 'new-email'))) {
3003 // grant permissions for these tasks.
3004 $hasAllPermissions = TRUE;
3005 }
3006 }
3007 }
3008
3009 // user does not have necessary permissions.
3010 if (!$hasAllPermissions) {
3011 continue;
3012 }
3013
3014 // build directly accessible action menu.
3015 if (in_array($values['ref'], array(
3016 'view-contact', 'edit-contact'))) {
3017 $contextMenu['primaryActions'][$key] = array(
3018 'title' => $values['title'],
3019 'ref' => $values['ref'],
3020 'class' => CRM_Utils_Array::value('class', $values),
3021 'key' => $values['key'],
3022 );
3023 continue;
3024 }
3025
3026 // finally get menu item for -more- action widget.
3027 $contextMenu['moreActions'][$values['weight']] = array(
3028 'title' => $values['title'],
3029 'ref' => $values['ref'],
3030 'href' => CRM_Utils_Array::value('href', $values),
3031 'tab' => CRM_Utils_Array::value('tab', $values),
3032 'class' => CRM_Utils_Array::value('class', $values),
3033 'key' => $values['key'],
3034 );
3035 }
3036
3037 ksort($contextMenu['moreActions']);
3038
3039 return $contextMenu;
3040 }
3041
3042 /**
3043 * Function to retrieve display name of contact that address is shared
3044 * based on $masterAddressId or $contactId .
3045 *
3046 * @param int $masterAddressId master id.
3047 * @param int $contactId contact id.
3048 *
3049 * @return display name |null the found display name or null.
3050 * @access public
3051 * @static
3052 */
3053 static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3054 $masterDisplayName = NULL;
3055 $sql = NULL;
3056 if (!$masterAddressId && !$contactId) {
3057 return $masterDisplayName;
3058 }
3059
3060 if ($masterAddressId) {
3061 $sql = "
3062 SELECT display_name from civicrm_contact
3063 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3064 WHERE civicrm_address.id = " . $masterAddressId;
3065 }
3066 elseif ($contactId) {
3067 $sql = "
3068 SELECT display_name from civicrm_contact cc, civicrm_address add1
3069 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3070 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3071 }
3072
3073 $masterDisplayName = CRM_Core_DAO::singleValueQuery($sql);
3074 return $masterDisplayName;
3075 }
3076
3077 /**
3078 * Get the creation/modification times for a contact
3079 *
3080 * @param $contactId
3081 *
3082 * @return array('created_date' => $, 'modified_date' => $)
3083 */
3084 static function getTimestamps($contactId) {
3085 $timestamps = CRM_Core_DAO::executeQuery(
3086 'SELECT created_date, modified_date
3087 FROM civicrm_contact
3088 WHERE id = %1',
3089 array(
3090 1 => array($contactId, 'Integer'),
3091 )
3092 );
3093 if ($timestamps->fetch()) {
3094 return array(
3095 'created_date' => $timestamps->created_date,
3096 'modified_date' => $timestamps->modified_date,
3097 );
3098 }
3099 else {
3100 return NULL;
3101 }
3102 }
3103
3104 /**
3105 * Get a list of triggers for the contact table
3106 *
3107 * @see hook_civicrm_triggerInfo
3108 * @see CRM_Core_DAO::triggerRebuild
3109 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3110 */
3111 static function triggerInfo(&$info, $tableName = NULL) {
3112 //during upgrade, first check for valid version and then create triggers
3113 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3114 if (CRM_Core_Config::isUpgradeMode()) {
3115 $currentVer = CRM_Core_BAO_Domain::version(TRUE);
3116 //if current version is less than 4.3.alpha1 dont create below triggers
3117 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3118 return;
3119 }
3120 }
3121
3122 if ($tableName == NULL || $tableName == self::getTableName()) {
3123 $info[] = array(
3124 'table' => array(self::getTableName()),
3125 'when' => 'BEFORE',
3126 'event' => array('INSERT'),
3127 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3128 );
3129 }
3130
3131 // Update timestamp when modifying closely related core tables
3132 $relatedTables = array(
3133 'civicrm_address',
3134 'civicrm_email',
3135 'civicrm_im',
3136 'civicrm_phone',
3137 'civicrm_website',
3138 );
3139 $info[] = array(
3140 'table' => $relatedTables,
3141 'when' => 'AFTER',
3142 'event' => array('INSERT', 'UPDATE'),
3143 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.contact_id;\n",
3144 );
3145 $info[] = array(
3146 'table' => $relatedTables,
3147 'when' => 'AFTER',
3148 'event' => array('DELETE'),
3149 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.contact_id;\n",
3150 );
3151
3152 // Update timestamp when modifying related custom-data tables
3153 $customGroupTables = array();
3154 $customGroupDAO = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
3155 $customGroupDAO->is_multiple = 0;
3156 $customGroupDAO->find();
3157 while ($customGroupDAO->fetch()) {
3158 $customGroupTables[] = $customGroupDAO->table_name;
3159 }
3160 if (!empty($customGroupTables)) {
3161 $info[] = array(
3162 'table' => $customGroupTables,
3163 'when' => 'AFTER',
3164 'event' => array('INSERT', 'UPDATE'),
3165 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.entity_id;\n",
3166 );
3167 $info[] = array(
3168 'table' => $customGroupTables,
3169 'when' => 'AFTER',
3170 'event' => array('DELETE'),
3171 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.entity_id;\n",
3172 );
3173 }
3174
3175 // Update phone table to populate phone_numeric field
3176 if (!$tableName || $tableName == 'civicrm_phone') {
3177 // Define stored sql function needed for phones
3178 CRM_Core_DAO::executeQuery(self::DROP_STRIP_FUNCTION_43);
3179 CRM_Core_DAO::executeQuery(self::CREATE_STRIP_FUNCTION_43);
3180 $info[] = array(
3181 'table' => array('civicrm_phone'),
3182 'when' => 'BEFORE',
3183 'event' => array('INSERT', 'UPDATE'),
3184 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3185 );
3186 }
3187 }
3188
3189 /**
3190 * Function to check if contact is being used in civicrm_domain
3191 * based on $contactId
3192 *
3193 * @param int $contactId contact id.
3194 *
3195 * @return bool true if present else false.
3196 * @access public
3197 * @static
3198 */
3199 static function checkDomainContact($contactId) {
3200 if (!$contactId)
3201 return FALSE;
3202 $domainId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3203
3204 if ($domainId) {
3205 return TRUE;
3206 } else {
3207 return FALSE;
3208 }
3209 }
3210
3211 /**
3212 * Get options for a given contact field.
3213 * @see CRM_Core_DAO::buildOptions
3214 *
3215 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3216 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3217 *
3218 * @param String $fieldName
3219 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3220 * @param Array $props : whatever is known about this dao object
3221 *
3222 * @return Array|bool
3223 */
3224 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3225 $params = array();
3226 // Special logic for fields whose options depend on context or properties
3227 switch ($fieldName) {
3228 case 'contact_sub_type':
3229 if (!empty($props['contact_type'])) {
3230 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3231 }
3232 break;
3233 }
3234 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
3235 }
3236
3237 /**
3238 * Delete a contact-related object that has an 'is_primary' field
3239 * Ensures that is_primary gets assigned to another object if available
3240 * Also calls pre/post hooks
3241 *
3242 * @var $type : object type
3243 * @var $id : object id
3244 * @return bool
3245 */
3246 public static function deleteObjectWithPrimary($type, $id) {
3247 if (!$id || !is_numeric($id)) {
3248 return FALSE;
3249 }
3250 $daoName = "CRM_Core_DAO_$type";
3251 $obj = new $daoName();
3252 $obj->id = $id;
3253 $obj->find();
3254 if ($obj->fetch()) {
3255 CRM_Utils_Hook::pre('delete', $type, $id, CRM_Core_DAO::$_nullArray);
3256 $contactId = $obj->contact_id;
3257 $obj->delete();
3258 }
3259 else {
3260 return FALSE;
3261 }
3262 // is_primary is only relavent if this field belongs to a contact
3263 if ($contactId) {
3264 $dao = new $daoName();
3265 $dao->contact_id = $contactId;
3266 $dao->is_primary = 1;
3267 // Pick another record to be primary (if one isn't already)
3268 if (!$dao->find(TRUE)) {
3269 $dao->is_primary = 0;
3270 $dao->find();
3271 if ($dao->fetch()) {
3272 $dao->is_primary = 1;
3273 $dao->save();
3274 }
3275 }
3276 $dao->free();
3277 }
3278 CRM_Utils_Hook::post('delete', $type, $id, $obj);
3279 $obj->free();
3280 return TRUE;
3281 }
3282 }