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