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