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