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