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