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