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