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