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