Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-02-03-14-48-25
[civicrm-core.git] / CRM / Contact / Selector.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * This class is used to retrieve and display a range of
38 * contacts that match the given criteria (specifically for
39 * results of advanced search options.
40 *
41 */
42 class CRM_Contact_Selector extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
43
44 /**
45 * This defines two actions- View and Edit.
46 *
47 * @var array
48 * @static
49 */
50 static $_links = NULL;
51
52 /**
53 * we use desc to remind us what that column is, name is used in the tpl
54 *
55 * @var array
56 * @static
57 */
58 static $_columnHeaders;
59
60 /**
61 * Properties of contact we're interested in displaying
62 * @var array
63 * @static
64 */
65 static $_properties = array(
66 'contact_id', 'contact_type', 'contact_sub_type',
67 'sort_name', 'street_address',
68 'city', 'state_province', 'postal_code', 'country',
69 'geo_code_1', 'geo_code_2', 'is_deceased',
70 'email', 'on_hold', 'phone', 'status',
71 'do_not_email', 'do_not_phone', 'do_not_mail',
72 );
73
74 /**
75 * formValues is the array returned by exportValues called on
76 * the HTML_QuickForm_Controller for that page.
77 *
78 * @var array
79 * @access protected
80 */
81 public $_formValues;
82
83 /**
84 * The contextMenu
85 *
86 * @var array
87 * @access protected
88 */
89 protected $_contextMenu;
90
91 /**
92 * params is the array in a value used by the search query creator
93 *
94 * @var array
95 * @access protected
96 */
97 public $_params;
98
99 /**
100 * The return properties used for search
101 *
102 * @var array
103 * @access protected
104 */
105 protected $_returnProperties;
106
107 /**
108 * represent the type of selector
109 *
110 * @var int
111 * @access protected
112 */
113 protected $_action;
114
115 protected $_searchContext;
116
117 protected $_query;
118
119 /**
120 * group id
121 *
122 * @var int
123 */
124 protected $_ufGroupID;
125
126 /**
127 * the public visible fields to be shown to the user
128 *
129 * @var array
130 * @access protected
131 */
132 protected $_fields;
133
134 /**
135 * Class constructor
136 *
137 * @param array $formValues array of form values imported
138 * @param array $params array of parameters for query
139 * @param int $action - action of search basic or advanced.
140 *
141 * @return CRM_Contact_Selector
142 * @access public
143 */
144 function __construct(
145 $customSearchClass,
146 $formValues = NULL,
147 $params = NULL,
148 $returnProperties = NULL,
149 $action = CRM_Core_Action::NONE,
150 $includeContactIds = FALSE,
151 $searchDescendentGroups = TRUE,
152 $searchContext = 'search',
153 $contextMenu = NULL
154 ) {
155 //don't build query constructor, if form is not submitted
156 $force = CRM_Utils_Request::retrieve('force', 'Boolean', CRM_Core_DAO::$_nullObject);
157 if (empty($formValues) && !$force) {
158 return;
159 }
160
161 // submitted form values
162 $this->_formValues = &$formValues;
163 $this->_params = &$params;
164 $this->_returnProperties = &$returnProperties;
165 $this->_contextMenu = &$contextMenu;
166 $this->_context = $searchContext;
167
168 // type of selector
169 $this->_action = $action;
170
171 $this->_searchContext = $searchContext;
172
173 $this->_ufGroupID = CRM_Utils_Array::value('uf_group_id', $this->_formValues);
174
175 if ($this->_ufGroupID) {
176 $this->_fields = CRM_Core_BAO_UFGroup::getListingFields(CRM_Core_Action::VIEW,
177 CRM_Core_BAO_UFGroup::PUBLIC_VISIBILITY |
178 CRM_Core_BAO_UFGroup::LISTINGS_VISIBILITY,
179 FALSE, $this->_ufGroupID
180 );
181 self::$_columnHeaders = NULL;
182
183 $this->_customFields = CRM_Core_BAO_CustomField::getFieldsForImport('Individual');
184
185 $this->_returnProperties = CRM_Contact_BAO_Contact::makeHierReturnProperties($this->_fields);
186 $this->_returnProperties['contact_type'] = 1;
187 $this->_returnProperties['contact_sub_type'] = 1;
188 $this->_returnProperties['sort_name'] = 1;
189 }
190
191 $displayRelationshipType = CRM_Utils_Array::value('display_relationship_type', $this->_formValues);
192 $operator = CRM_Utils_Array::value('operator', $this->_formValues, 'AND');
193
194 // rectify params to what proximity search expects if there is a value for prox_distance
195 // CRM-7021
196 if (!empty($this->_params)) {
197 CRM_Contact_BAO_ProximityQuery::fixInputParams($this->_params);
198 }
199
200 $this->_query = new CRM_Contact_BAO_Query(
201 $this->_params,
202 $this->_returnProperties,
203 NULL,
204 $includeContactIds,
205 FALSE,
206 CRM_Contact_BAO_Query::MODE_CONTACTS,
207 FALSE,
208 $searchDescendentGroups,
209 FALSE,
210 $displayRelationshipType,
211 $operator
212 );
213
214 $this->_options = &$this->_query->_options;
215 }
216 //end of constructor
217
218 /**
219 * This method returns the links that are given for each search row.
220 * currently the links added for each row are
221 *
222 * - View
223 * - Edit
224 *
225 * @return array
226 * @access public
227 *
228 */
229 static function &links() {
230 list($context, $contextMenu, $key) = func_get_args();
231 $extraParams = ($key) ? "&key={$key}" : NULL;
232 $searchContext = ($context) ? "&context=$context" : NULL;
233
234 if (!(self::$_links)) {
235 self::$_links = array(
236 CRM_Core_Action::VIEW => array(
237 'name' => ts('View'),
238 'url' => 'civicrm/contact/view',
239 'class' => 'no-popup',
240 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
241 'title' => ts('View Contact Details'),
242 'ref' => 'view-contact',
243 ),
244 CRM_Core_Action::UPDATE => array(
245 'name' => ts('Edit'),
246 'url' => 'civicrm/contact/add',
247 'class' => 'no-popup',
248 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
249 'title' => ts('Edit Contact Details'),
250 'ref' => 'edit-contact',
251 ),
252 );
253
254 $config = CRM_Core_Config::singleton();
255 if ($config->mapAPIKey && $config->mapProvider) {
256 self::$_links[CRM_Core_Action::MAP] = array(
257 'name' => ts('Map'),
258 'url' => 'civicrm/contact/map',
259 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
260 'title' => ts('Map Contact'),
261 );
262 }
263
264 // Adding Context Menu Links in more action
265 if ($contextMenu) {
266 $counter = 7000;
267 foreach ($contextMenu as $key => $value) {
268 $contextVal = '&context=' . $value['key'];
269 if ($value['key'] == 'delete') {
270 $contextVal = $searchContext;
271 }
272 $url = "civicrm/contact/view/{$value['key']}";
273 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
274 if ($value['key'] == 'activity') {
275 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
276 }
277 elseif ($value['key'] == 'email') {
278 $url = "civicrm/contact/view/activity";
279 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
280 }
281
282 self::$_links[$counter++] = array(
283 'name' => $value['title'],
284 'url' => $url,
285 'qs' => $qs,
286 'title' => $value['title'],
287 'ref' => $value['ref'],
288 'class' => CRM_Utils_Array::value('class', $value),
289 );
290 }
291 }
292 }
293 return self::$_links;
294 }
295 //end of function
296
297 /**
298 * getter for array of the parameters required for creating pager.
299 *
300 * @param
301 * @access public
302 */
303 function getPagerParams($action, &$params) {
304 $params['status'] = ts('Contact %%StatusMessage%%');
305 $params['csvString'] = NULL;
306 $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
307
308 $params['buttonTop'] = 'PagerTopButton';
309 $params['buttonBottom'] = 'PagerBottomButton';
310 }
311 //end of function
312
313 function &getColHeads($action = NULL, $output = NULL) {
314 $colHeads = self::_getColumnHeaders();
315 $colHeads[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
316 return $colHeads;
317 }
318
319 /**
320 * returns the column headers as an array of tuples:
321 * (name, sortName (key to the sort array))
322 *
323 * @param string $action the action being performed
324 * @param enum $output what should the result set include (web/email/csv)
325 *
326 * @return array the column headers that need to be displayed
327 * @access public
328 */
329 function &getColumnHeaders($action = NULL, $output = NULL) {
330 $headers = NULL;
331
332 // unset return property elements that we don't care
333 if (!empty($this->_returnProperties)) {
334 $doNotCareElements = array(
335 'contact_type',
336 'contact_sub_type',
337 'sort_name',
338 );
339 foreach ( $doNotCareElements as $value) {
340 unset($this->_returnProperties[$value]);
341 }
342 }
343
344 if ($output == CRM_Core_Selector_Controller::EXPORT) {
345 $csvHeaders = array(ts('Contact Id'), ts('Contact Type'));
346 foreach ($this->getColHeads($action, $output) as $column) {
347 if (array_key_exists('name', $column)) {
348 $csvHeaders[] = $column['name'];
349 }
350 }
351 $headers = $csvHeaders;
352 }
353 elseif ($output == CRM_Core_Selector_Controller::SCREEN) {
354 $csvHeaders = array(ts('Name'));
355 foreach ($this->getColHeads($action, $output) as $key => $column) {
356 if (array_key_exists('name', $column) &&
357 $column['name'] &&
358 $column['name'] != ts('Name')
359 ) {
360 $csvHeaders[$key] = $column['name'];
361 }
362 }
363 $headers = $csvHeaders;
364 }
365 elseif ($this->_ufGroupID) {
366 // we dont use the cached value of column headers
367 // since it potentially changed because of the profile selected
368 static $skipFields = array('group', 'tag');
369 $direction = CRM_Utils_Sort::ASCENDING;
370 $empty = TRUE;
371 if (!self::$_columnHeaders) {
372 self::$_columnHeaders = array(array('name' => ''),
373 array(
374 'name' => ts('Name'),
375 'sort' => 'sort_name',
376 'direction' => CRM_Utils_Sort::ASCENDING,
377 ),
378 );
379
380 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
381
382 foreach ($this->_fields as $name => $field) {
383 if (!empty($field['in_selector']) &&
384 !in_array($name, $skipFields)
385 ) {
386 if (strpos($name, '-') !== FALSE) {
387 list($fieldName, $lType, $type) = CRM_Utils_System::explode('-', $name, 3);
388
389 if ($lType == 'Primary') {
390 $locationTypeName = 1;
391 }
392 else {
393 $locationTypeName = $locationTypes[$lType];
394 }
395
396 if (in_array($fieldName, array(
397 'phone', 'im', 'email'))) {
398 if ($type) {
399 $name = "`$locationTypeName-$fieldName-$type`";
400 }
401 else {
402 $name = "`$locationTypeName-$fieldName`";
403 }
404 }
405 else {
406 $name = "`$locationTypeName-$fieldName`";
407 }
408 }
409 //to handle sort key for Internal contactId.CRM-2289
410 if ($name == 'id') {
411 $name = 'contact_id';
412 }
413
414 self::$_columnHeaders[] = array(
415 'name' => $field['title'],
416 'sort' => $name,
417 'direction' => $direction,
418 );
419 $direction = CRM_Utils_Sort::DONTCARE;
420 $empty = FALSE;
421 }
422 }
423
424 // if we dont have any valid columns, dont add the implicit ones
425 // this allows the template to check on emptiness of column headers
426 if ($empty) {
427 self::$_columnHeaders = array();
428 }
429 else {
430 self::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
431 }
432 }
433 $headers = self::$_columnHeaders;
434 }
435 elseif (!empty($this->_returnProperties)) {
436 self::$_columnHeaders = array(array('name' => ''),
437 array(
438 'name' => ts('Name'),
439 'sort' => 'sort_name',
440 'direction' => CRM_Utils_Sort::ASCENDING,
441 ),
442 );
443 $properties = self::makeProperties($this->_returnProperties);
444
445 foreach ($properties as $prop) {
446 if (strpos($prop, '-')) {
447 list($loc, $fld, $phoneType) = CRM_Utils_System::explode('-', $prop, 3);
448 $title = $this->_query->_fields[$fld]['title'];
449 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
450 $title .= "-{$phoneType}";
451 }
452 $title .= " ($loc)";
453 }
454 elseif (isset($this->_query->_fields[$prop]) && isset($this->_query->_fields[$prop]['title'])) {
455 $title = $this->_query->_fields[$prop]['title'];
456 }
457 else {
458 $title = '';
459 }
460
461 self::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
462 }
463 self::$_columnHeaders[] = array('name' => ts('Actions'));
464 $headers = self::$_columnHeaders;
465 }
466 else {
467 $headers = $this->getColHeads($action, $output);
468 }
469
470 return $headers;
471 }
472
473 /**
474 * Returns total number of rows for the query.
475 *
476 * @param
477 *
478 * @return int Total number of rows
479 * @access public
480 */
481 function getTotalCount($action) {
482 // Use count from cache during paging/sorting
483 if (!empty($_GET['crmPID']) || !empty($_GET['crmSID'])) {
484 $count = CRM_Core_BAO_Cache::getItem('Search Results Count', $this->_key);
485 }
486 if (empty($count)) {
487 $count = $this->_query->searchQuery(0, 0, NULL, TRUE);
488 CRM_Core_BAO_Cache::setItem($count, 'Search Results Count', $this->_key);
489 }
490 return $count;
491 }
492
493 /**
494 * returns all the rows in the given offset and rowCount
495 *
496 * @param enum $action the action being performed
497 * @param int $offset the row number to start from
498 * @param int $rowCount the number of rows to return
499 * @param string $sort the sql string that describes the sort order
500 * @param enum $output what should the result set include (web/email/csv)
501 *
502 * @return int the total number of rows for this action
503 */
504 function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
505 $config = CRM_Core_Config::singleton();
506
507 if (($output == CRM_Core_Selector_Controller::EXPORT ||
508 $output == CRM_Core_Selector_Controller::SCREEN
509 ) &&
510 $this->_formValues['radio_ts'] == 'ts_sel'
511 ) {
512 $includeContactIds = TRUE;
513 }
514 else {
515 $includeContactIds = FALSE;
516 }
517
518 // note the formvalues were given by CRM_Contact_Form_Search to us
519 // and contain the search criteria (parameters)
520 // note that the default action is basic
521 if ($rowCount) {
522 $cacheKey = $this->buildPrevNextCache($sort);
523 $result = $this->_query->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds);
524
525 // CRM-13996: result is empty when selector columns are sorted. hence we need to run the query again
526 if ( $result->N == 0) {
527 $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
528 }
529 }
530 else {
531 $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
532 }
533
534 // process the result of the query
535 $rows = array();
536 $permissions = array(CRM_Core_Permission::getPermission());
537 if (CRM_Core_Permission::check('delete contacts')) {
538 $permissions[] = CRM_Core_Permission::DELETE;
539 }
540 $mask = CRM_Core_Action::mask($permissions);
541
542 // mask value to hide map link if there are not lat/long
543 $mapMask = $mask & 4095;
544
545 if ($this->_searchContext == 'smog') {
546 $gc = CRM_Core_SelectValues::groupContactStatus();
547 }
548
549 if ($this->_ufGroupID) {
550 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
551
552 $names = array();
553 static $skipFields = array('group', 'tag');
554 foreach ($this->_fields as $key => $field) {
555 if (!empty($field['in_selector']) &&
556 !in_array($key, $skipFields)
557 ) {
558 if (strpos($key, '-') !== FALSE) {
559 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $key, 3);
560
561 if ($id == 'Primary') {
562 $locationTypeName = 1;
563 }
564 else {
565 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
566 if (!$locationTypeName) {
567 continue;
568 }
569 }
570
571 $locationTypeName = str_replace(' ', '_', $locationTypeName);
572 if (in_array($fieldName, array(
573 'phone', 'im', 'email'))) {
574 if ($type) {
575 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
576 }
577 else {
578 $names[] = "{$locationTypeName}-{$fieldName}";
579 }
580 }
581 else {
582 $names[] = "{$locationTypeName}-{$fieldName}";
583 }
584 }
585 else {
586 $names[] = $field['name'];
587 }
588 }
589 }
590
591 $names[] = "status";
592 }
593 elseif (!empty($this->_returnProperties)) {
594 $names = self::makeProperties($this->_returnProperties);
595 }
596 else {
597 $names = self::$_properties;
598 }
599
600 $multipleSelectFields = array('preferred_communication_method' => 1);
601
602 $links = self::links($this->_context, $this->_contextMenu, $this->_key);
603
604 //check explicitly added contact to a Smart Group.
605 $groupID = CRM_Utils_Array::key('1', $this->_formValues['group']);
606
607 $pseudoconstants = array();
608 // for CRM-3157 purposes
609 if (in_array('world_region', $names)) {
610 $pseudoconstants['world_region'] = array(
611 'dbName' => 'world_region_id',
612 'values' => CRM_Core_PseudoConstant::worldRegion()
613 );
614 }
615
616 $seenIDs = array();
617 while ($result->fetch()) {
618 $row = array();
619 $this->_query->convertToPseudoNames($result);
620
621 // the columns we are interested in
622 foreach ($names as $property) {
623 if ($property == 'status') {
624 continue;
625 }
626 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($property)) {
627 $row[$property] = CRM_Core_BAO_CustomField::getDisplayValue(
628 $result->$property,
629 $cfID,
630 $this->_options,
631 $result->contact_id
632 );
633 }
634 elseif (
635 $multipleSelectFields &&
636 array_key_exists($property, $multipleSelectFields)
637 ) {
638 $key = $property;
639 $paramsNew = array($key => $result->$property);
640 $name = array($key => array('newName' => $key, 'groupName' => $key));
641
642 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
643 $row[$key] = $paramsNew[$key];
644 }
645 elseif (strpos($property, '-im')) {
646 $row[$property] = $result->$property;
647 if (!empty($result->$property)) {
648 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
649 $providerId = $property . "-provider_id";
650 $providerName = $imProviders[$result->$providerId];
651 $row[$property] = $result->$property . " ({$providerName})";
652 }
653 }
654 elseif (in_array($property, array(
655 'addressee', 'email_greeting', 'postal_greeting'))) {
656 $greeting = $property . '_display';
657 $row[$property] = $result->$greeting;
658 }
659 elseif ($property == 'state_province') {
660 $row[$property] = $result->state_province_name;
661 }
662 elseif (isset($pseudoconstants[$property])) {
663 $row[$property] = CRM_Utils_Array::value(
664 $result->{$pseudoconstants[$property]['dbName']},
665 $pseudoconstants[$property]['values']
666 );
667 }
668 elseif (strpos($property, '-url') !== FALSE) {
669 $websiteUrl = '';
670 $websiteKey = 'website-1';
671 $propertyArray = explode('-', $property);
672 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
673 if (!empty($result->$websiteFld)) {
674 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
675 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
676 $websiteValue = $result->$websiteFld;
677 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
678 }
679 $row[$property] = $websiteUrl;
680 }
681 else {
682 $row[$property] = isset($result->$property) ? $result->$property : NULL;
683 }
684 }
685
686 if (!empty($result->postal_code_suffix)) {
687 $row['postal_code'] .= "-" . $result->postal_code_suffix;
688 }
689
690 if ($output != CRM_Core_Selector_Controller::EXPORT &&
691 $this->_searchContext == 'smog'
692 ) {
693 if (empty($result->status) &&
694 $groupID
695 ) {
696 $contactID = $result->contact_id;
697 if ($contactID) {
698 $gcParams = array(
699 'contact_id' => $contactID,
700 'group_id' => $groupID,
701 );
702
703 $gcDefaults = array();
704 CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
705
706 if (empty($gcDefaults)) {
707 $row['status'] = ts('Smart');
708 }
709 else {
710 $row['status'] = $gc[$gcDefaults['status']];
711 }
712 }
713 else {
714 $row['status'] = NULL;
715 }
716 }
717 else {
718 $row['status'] = $gc[$result->status];
719 }
720 }
721
722 if ($output != CRM_Core_Selector_Controller::EXPORT) {
723 $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contact_id;
724
725 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
726 ) {
727 $links = array(
728 array(
729 'name' => ts('View'),
730 'url' => 'civicrm/contact/view',
731 'qs' => 'reset=1&cid=%%id%%',
732 'class' => 'no-popup',
733 'title' => ts('View Contact Details'),
734 ),
735 array(
736 'name' => ts('Restore'),
737 'url' => 'civicrm/contact/view/delete',
738 'qs' => 'reset=1&cid=%%id%%&restore=1',
739 'title' => ts('Restore Contact'),
740 ),
741 );
742 if (CRM_Core_Permission::check('delete contacts')) {
743 $links[] = array(
744 'name' => ts('Delete Permanently'),
745 'url' => 'civicrm/contact/view/delete',
746 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
747 'title' => ts('Permanently Delete Contact'),
748 );
749 }
750 $row['action'] = CRM_Core_Action::formLink(
751 $links,
752 NULL,
753 array('id' => $result->contact_id),
754 ts('more'),
755 FALSE,
756 'contact.selector.row',
757 'Contact',
758 $result->contact_id
759 );
760 }
761 elseif ((is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) ||
762 ($config->mapGeoCoding && !empty($row['city']) &&
763 CRM_Utils_Array::value('state_province', $row)
764 )
765 ) {
766 $row['action'] = CRM_Core_Action::formLink(
767 $links,
768 $mask,
769 array('id' => $result->contact_id),
770 ts('more'),
771 FALSE,
772 'contact.selector.row',
773 'Contact',
774 $result->contact_id
775 );
776 }
777 else {
778 $row['action'] = CRM_Core_Action::formLink(
779 $links,
780 $mapMask,
781 array('id' => $result->contact_id),
782 ts('more'),
783 FALSE,
784 'contact.selector.row',
785 'Contact',
786 $result->contact_id
787 );
788 }
789
790 // allow components to add more actions
791 CRM_Core_Component::searchAction($row, $result->contact_id);
792
793 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ?
794 $result->contact_sub_type : $result->contact_type,
795 FALSE,
796 $result->contact_id
797 );
798
799 $row['contact_type_orig'] = $result->contact_sub_type ? $result->contact_sub_type : $result->contact_type;
800 $row['contact_sub_type'] = $result->contact_sub_type ?
801 CRM_Contact_BAO_ContactType::contactTypePairs(FALSE, $result->contact_sub_type, ', ') : $result->contact_sub_type;
802 $row['contact_id'] = $result->contact_id;
803 $row['sort_name'] = $result->sort_name;
804 if (array_key_exists('id', $row)) {
805 $row['id'] = $result->contact_id;
806 }
807 }
808
809 // Dedupe contacts
810 if (in_array($row['contact_id'], $seenIDs) === FALSE) {
811 $seenIDs[] = $row['contact_id'];
812 $rows[] = $row;
813 }
814 }
815
816 return $rows;
817 }
818
819 function buildPrevNextCache($sort) {
820 $cacheKey = 'civicrm search ' . $this->_key;
821
822 // Get current page requested
823 $pageNum = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
824 // When starting from scratch, clear any old cache
825 if (!$pageNum) {
826 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKey, 'civicrm_contact');
827 $pageNum = 1;
828 }
829
830 $pageSize = CRM_Utils_Request::retrieve('crmRowCount', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, 50);
831 $firstRecord = ($pageNum - 1) * $pageSize;
832
833 //for alphabetic pagination selection save
834 $sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter', 'String', CRM_Core_DAO::$_nullObject);
835
836 //for text field pagination selection save
837 $countRow = CRM_Core_BAO_PrevNextCache::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
838
839 // $sortByCharacter triggers a refresh in the prevNext cache
840 if ($sortByCharacter && $sortByCharacter != 'all') {
841 $cacheKey .= "_alphabet";
842 $this->fillupPrevNextCache($sort, $cacheKey);
843 }
844 elseif ($firstRecord >= $countRow) {
845 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, $firstRecord + 500);
846 }
847 return $cacheKey;
848 }
849
850 function addActions(&$rows) {
851 $config = CRM_Core_Config::singleton();
852
853 $permissions = array(CRM_Core_Permission::getPermission());
854 if (CRM_Core_Permission::check('delete contacts')) {
855 $permissions[] = CRM_Core_Permission::DELETE;
856 }
857 $mask = CRM_Core_Action::mask($permissions);
858 // mask value to hide map link if there are not lat/long
859 $mapMask = $mask & 4095;
860
861 // mask value to hide map link if there are not lat/long
862 $mapMask = $mask & 4095;
863
864 $links = self::links($this->_context, $this->_contextMenu, $this->_key);
865
866
867 foreach ($rows as $id => & $row) {
868 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
869 ) {
870 $links = array(
871 array(
872 'name' => ts('View'),
873 'url' => 'civicrm/contact/view',
874 'qs' => 'reset=1&cid=%%id%%',
875 'title' => ts('View Contact Details'),
876 ),
877 array(
878 'name' => ts('Restore'),
879 'url' => 'civicrm/contact/view/delete',
880 'qs' => 'reset=1&cid=%%id%%&restore=1',
881 'title' => ts('Restore Contact'),
882 ),
883 );
884 if (CRM_Core_Permission::check('delete contacts')) {
885 $links[] = array(
886 'name' => ts('Delete Permanently'),
887 'url' => 'civicrm/contact/view/delete',
888 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
889 'title' => ts('Permanently Delete Contact'),
890 );
891 }
892 $row['action'] = CRM_Core_Action::formLink(
893 $links,
894 null,
895 array('id' => $row['contact_id']),
896 ts('more'),
897 FALSE,
898 'contact.selector.actions',
899 'Contact',
900 $row['contact_id']
901 );
902 }
903 elseif ((is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) ||
904 ($config->mapGeoCoding && !empty($row['city']) &&
905 CRM_Utils_Array::value('state_province', $row)
906 )
907 ) {
908 $row['action'] = CRM_Core_Action::formLink(
909 $links,
910 $mask,
911 array('id' => $row['contact_id']),
912 ts('more'),
913 FALSE,
914 'contact.selector.actions',
915 'Contact',
916 $row['contact_id']
917 );
918 }
919 else {
920 $row['action'] = CRM_Core_Action::formLink(
921 $links,
922 $mapMask,
923 array('id' => $row['contact_id']),
924 ts('more'),
925 FALSE,
926 'contact.selector.actions',
927 'Contact',
928 $row['contact_id']
929 );
930 }
931
932 // allow components to add more actions
933 CRM_Core_Component::searchAction($row, $row['contact_id']);
934
935 if (!empty($row['contact_type_orig'])) {
936 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($row['contact_type_orig'],
937 FALSE, $row['contact_id']);
938 }
939 }
940 }
941
942 function removeActions(&$rows) {
943 foreach ($rows as $rid => & $rValue) {
944 unset($rValue['contact_type']);
945 unset($rValue['action']);
946 }
947 }
948
949 /**
950 * @param object $sort
951 * @param string $cacheKey
952 * @param int $start
953 * @param int $end
954 */
955 function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) {
956
957 // For custom searches, use the contactIDs method
958 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
959 $sql = $this->_search->contactIDs($start, $end, $sort, TRUE);
960 $replaceSQL = "SELECT contact_a.id as contact_id";
961 }
962 // For core searches use the searchQuery method
963 else {
964 $sql = $this->_query->searchQuery(
965 $start, $end, $sort,
966 FALSE, FALSE,
967 FALSE, TRUE, TRUE, NULL
968 );
969 $replaceSQL = "SELECT contact_a.id as id";
970 }
971
972 // CRM-9096
973 // due to limitations in our search query writer, the above query does not work
974 // in cases where the query is being sorted on a non-contact table
975 // this results in a fatal error :(
976 // see below for the gross hack of trapping the error and not filling
977 // the prev next cache in this situation
978 // the other alternative of running the FULL query will just be incredibly inefficient
979 // and slow things down way too much on large data sets / complex queries
980
981 $insertSQL = "
982 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
983 SELECT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
984 ";
985
986 $sql = str_replace($replaceSQL, $insertSQL, $sql);
987
988 CRM_Core_Error::ignoreException();
989 $result = CRM_Core_DAO::executeQuery($sql);
990 CRM_Core_Error::setCallback();
991
992 if (is_a($result, 'DB_Error')) {
993 // oops the above query failed, so lets just ignore it
994 // and return
995 // we print a sorry cant figure it out on view page
996 return;
997 }
998
999 // also record an entry in the cache key table, so we can delete it periodically
1000 CRM_Core_BAO_Cache::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1001 }
1002
1003 /**
1004 * Given the current formValues, gets the query in local
1005 * language
1006 *
1007 * @param array(
1008 reference) $formValues submitted formValues
1009 *
1010 * @return array $qill which contains an array of strings
1011 * @access public
1012 */
1013
1014 // the current internationalisation is bad, but should more or less work
1015 // for most of "European" languages
1016 public function getQILL() {
1017 return $this->_query->qill();
1018 }
1019
1020 /**
1021 * name of export file.
1022 *
1023 * @param string $output type of output
1024 *
1025 * @return string name of the file
1026 */
1027 function getExportFileName($output = 'csv') {
1028 return ts('CiviCRM Contact Search');
1029 }
1030
1031 /**
1032 * get colunmn headers for search selector
1033 *
1034 *
1035 * @return array $_columnHeaders
1036 * @access private
1037 */
1038 private static function &_getColumnHeaders() {
1039 if (!isset(self::$_columnHeaders)) {
1040 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1041 'address_options', TRUE, NULL, TRUE
1042 );
1043
1044 self::$_columnHeaders = array(
1045 'contact_type' => array('desc' => ts('Contact Type')),
1046 'sort_name' => array(
1047 'name' => ts('Name'),
1048 'sort' => 'sort_name',
1049 'direction' => CRM_Utils_Sort::ASCENDING,
1050 ),
1051 );
1052
1053 $defaultAddress = array(
1054 'street_address' => array('name' => ts('Address')),
1055 'city' => array(
1056 'name' => ts('City'),
1057 'sort' => 'city',
1058 'direction' => CRM_Utils_Sort::DONTCARE,
1059 ),
1060 'state_province' => array(
1061 'name' => ts('State'),
1062 'sort' => 'state_province',
1063 'direction' => CRM_Utils_Sort::DONTCARE,
1064 ),
1065 'postal_code' => array(
1066 'name' => ts('Postal'),
1067 'sort' => 'postal_code',
1068 'direction' => CRM_Utils_Sort::DONTCARE,
1069 ),
1070 'country' => array(
1071 'name' => ts('Country'),
1072 'sort' => 'country',
1073 'direction' => CRM_Utils_Sort::DONTCARE,
1074 ),
1075 );
1076
1077 foreach ($defaultAddress as $columnName => $column) {
1078 if (!empty($addressOptions[$columnName])) {
1079 self::$_columnHeaders[$columnName] = $column;
1080 }
1081 }
1082
1083 self::$_columnHeaders['email'] = array(
1084 'name' => ts('Email'),
1085 'sort' => 'email',
1086 'direction' => CRM_Utils_Sort::DONTCARE,
1087 );
1088
1089 self::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1090 }
1091 return self::$_columnHeaders;
1092 }
1093
1094 function &getQuery() {
1095 return $this->_query;
1096 }
1097
1098 function alphabetQuery() {
1099 return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1100 }
1101
1102 function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1103 $sortOrder = &$this->getSortOrder($this->_action);
1104 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1105
1106 // rectify params to what proximity search expects if there is a value for prox_distance
1107 // CRM-7021 CRM-7905
1108 if (!empty($params)) {
1109 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
1110 }
1111
1112 if (!$displayRelationshipType) {
1113 $query = new CRM_Contact_BAO_Query($params,
1114 $this->_returnProperties,
1115 NULL, FALSE, FALSE, 1,
1116 FALSE, TRUE, TRUE, NULL,
1117 $queryOperator
1118 );
1119 }
1120 else {
1121 $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties,
1122 NULL, FALSE, FALSE, 1,
1123 FALSE, TRUE, TRUE, $displayRelationshipType,
1124 $queryOperator
1125 );
1126 }
1127 $value = $query->searchQuery(0, 0, $sort,
1128 FALSE, FALSE, FALSE,
1129 FALSE, FALSE
1130 );
1131 return $value;
1132 }
1133
1134 function &makeProperties(&$returnProperties) {
1135 $properties = array();
1136 foreach ($returnProperties as $name => $value) {
1137 if ($name != 'location') {
1138 // special handling for group and tag
1139 if (in_array($name, array('group', 'tag'))) {
1140 $name = "{$name}s";
1141 }
1142
1143 // special handling for notes
1144 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1145 $name = "notes";
1146 }
1147
1148 $properties[] = $name;
1149 }
1150 else {
1151 // extract all the location stuff
1152 foreach ($value as $n => $v) {
1153 foreach ($v as $n1 => $v1) {
1154 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1155 $properties[] = "{$n}-{$n1}";
1156 }
1157 }
1158 }
1159 }
1160 }
1161 return $properties;
1162 }
1163 }
1164 //end of class
1165