source: trunk/lib/SortOrder.inc.php @ 717

Last change on this file since 717 was 717, checked in by anonymous, 4 years ago

Strip tags from sort header title attributes

File size: 9.8 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * SortOrder.inc.php
25 *
26 * SortOrder can determine how to sort results of a database query for display
27 * on a listing. It can print column headers that will be links to
28 * automatically change the sort and order.
29 *
30 * @requires    This class requires Prefs.inc.php
31 *
32 * @author  Quinn Comendant <quinn@strangecode.com>
33 * @version 1.6.2
34 */
35require_once dirname(__FILE__) . '/Prefs.inc.php';
36
37class SortOrder
38{
39
40    protected $_columns;
41    public $sort_by;
42    public $order;
43    public $asc_widget;
44    public $desc_widget;
45    public $default_sort;
46    public $default_order;
47    public $base_url;
48
49    /**
50     * Constructor. Finds the current sort by and order.
51     *
52     * @param string $default_sort   If not found elsewhere, this will be the
53     *                               current sort by.
54     * @param string $default_order  If not found elsewhere, this will be the
55     *                               current order.
56     */
57    public function __construct($default_sort = '', $default_order = '')
58    {
59        $app =& App::getInstance();
60
61        // Setup the HTML for printing ASC/DESC paths.
62        // This should be converted to CSS someday.
63        $images_path = $app->getParam('images_path') ? $app->getParam('images_path') : '/admin/_widgets';
64        $this->asc_widget = sprintf('<img src="%s/sort_ascending.gif" alt="%s" width="11" height="7" border="0" />', $images_path, _("Ascending"));
65        $this->desc_widget = sprintf('<img src="%s/sort_descending.gif" alt="%s" width="11" height="7" border="0" />', $images_path, _("Descending"));
66
67        // Setup prefs object.
68        $this->prefs = new Prefs($_SERVER['PHP_SELF']);
69        $this->prefs->setParam(array('persistent' => false));
70
71        // Setup defaults.
72        $this->setDefault($default_sort, $default_order);
73        $this->default_sort = $default_sort;
74        $this->default_order = $default_order;
75
76        // The base URL of sort header links.
77        $this->base_url = $_SERVER['PHP_SELF'];
78    }
79
80    /**
81     * Build an array of valid sort SQL for each DB column. This SQL is reference
82     * by the name and 'asc' or 'desc'.
83     *
84     * @param string $name      Reference name for the column this SQL sorts on.
85     * @param string $asc_sql   The sort SQL if $this->order is ascending.
86     * @param string $desc_sql  The sort SQL if $this->order is descending.
87     */
88    public function setColumn($name, $asc_sql, $desc_sql)
89    {
90        $this->_columns[$name] = array(
91            'asc'  => $asc_sql,
92            'desc' => $desc_sql
93        );
94    }
95
96    /**
97     * Set sort and order values. This is how you set new sort values after
98     * already declaring a SortOrder object, but expect values to come from
99     * getFormData.
100     *
101     * @param string $default_sort   If not found elsewhere, this will be the
102     *                               current sort by.
103     * @param string $default_order  If not found elsewhere, this will be the
104     *                               current order.
105     */
106    public function setDefault($default_sort = '', $default_order = '')
107    {
108        // Which column to sort by?
109        // (1) By GET or POST specification, if available.
110        // (2) By saved preference, if available.
111        // (3) By default (provided at class instantiation).
112        $new_sort_by = getFormData('sort');
113        if (!empty($new_sort_by)) {
114            $this->sort_by = $new_sort_by;
115            $this->prefs->set('sort_by', $this->sort_by);
116        } else if ($this->prefs->exists('sort_by')) {
117            $this->sort_by = $this->prefs->get('sort_by');
118        } else {
119            $this->sort_by = $default_sort;
120        }
121
122        // Which sort order to use?
123        // (1) By GET or POST specification, if available.
124        // (2) By saved preference, if available.
125        // (3) By default (provided at class instantiation).
126        $new_order = getFormData('order');
127        if (!empty($new_order)) {
128            $this->order = $new_order;
129            $this->prefs->set('sort_order', $this->order);
130        } else if ($this->prefs->exists('sort_order')) {
131            $this->order = $this->prefs->get('sort_order');
132        } else {
133            $this->order = $default_order;
134        }
135    }
136
137
138    /**
139     * Forcibly set sort and order values. This is how you set new sort values after
140     * already declaring a SortOrder object. This will ignore getFormData values.
141     *
142     * @param string $sort           The sort by name.
143     * @param string $order          The order direction (ASC,
144     *                               for example, for an alphabetical sort)
145     */
146    public function set($sort=null, $order=null, $save_value=true)
147    {
148        // Set new sort value.
149        if (isset($sort)) {
150            $this->sort_by = $sort;
151            if ($save_value) {
152                $this->prefs->set('sort_by', $this->sort_by);
153            }
154        }
155
156        // Set new order value.
157        if (isset($order)) {
158            $this->order = $order;
159            if ($save_value) {
160                $this->prefs->set('sort_order', $this->order);
161            }
162        }
163    }
164
165    /**
166     * Get the current sort and order values.
167     *
168     * @return array    Array with keys: sort and order. These can be fed back into the SortOrder::set() method or defaults.
169     */
170    public function get()
171    {
172        return array(
173            'sort' => $this->prefs->get('sort_by'),
174            'order' => $this->prefs->get('sort_order'),
175        );
176    }
177
178    /**
179     * Returns the SQL code to sort by set column and set order.
180     */
181    public function getSortOrderSQL()
182    {
183        $app =& App::getInstance();
184        $db =& DB::getInstance();
185
186        if (!isset($this->_columns[mb_strtolower($this->sort_by)])) {
187            $this->sort_by = $this->default_sort;
188            $this->order = $this->default_order;
189        }
190        if (!isset($this->_columns[mb_strtolower($this->sort_by)][mb_strtolower($this->order)])) {
191            $this->order = 'ASC';
192        }
193
194        if (!empty($this->_columns[mb_strtolower($this->sort_by)][mb_strtolower($this->order)])) {
195            return sprintf(' ORDER BY %s ', $this->_columns[mb_strtolower($this->sort_by)][mb_strtolower($this->order)]);
196        } else {
197            $app->logMsg(sprintf('Could not find SQL to sort by %s %s.', $this->sort_by, $this->order), LOG_WARNING, __FILE__, __LINE__);
198            return '';
199        }
200    }
201
202
203    /**
204     * Prints a link for a column header with URL sort determining logic.
205     * Column must be defined first using setColumn().
206     *
207     * @param string $col            The database column to sort by.
208     * @param string $col_name       The human-readable title of the column.
209     * @param string $default_order  The default order for this column (ASC,
210     *                               for example, for an alphabetical sort)
211     */
212    public function printSortHeader($col, $col_name, $default_order='ASC')
213    {
214        $app =& App::getInstance();
215
216        if (isset($this->_columns[$col])) {
217            if ($this->sort_by == $col) {
218                if (mb_strtolower($this->order) == 'desc') {
219                    ?><a href="<?php echo $app->oHREF($this->base_url . '?sort=' . $col . '&order=ASC'); ?>" data-tooltip title="<?php echo _("Change to ascending sort order"); ?>" class="sc-sort sc-desc"><?php echo $this->desc_widget; ?></a><?php echo $col_name; ?><?php
220                } else {
221                    ?><a href="<?php echo $app->oHREF($this->base_url . '?sort=' . $col . '&order=DESC'); ?>" data-tooltip title="<?php echo _("Change to descending sort order"); ?>" class="sc-sort sc-asc"><?php echo $this->asc_widget; ?></a><?php echo $col_name; ?><?php
222                }
223            } else {
224                ?><a href="<?php echo $app->oHREF($this->base_url . '?sort=' . $col . '&order=' . $default_order); ?>" data-tooltip title="<?php echo sprintf(_("Sort by %s"), strip_tags($col_name)); ?>" class="sc-sort"><?php echo $col_name; ?></a><?php
225            }
226        } else {
227            echo $col_name;
228        }
229    }
230
231    /*
232    * Print a select menu of sort options.
233    *
234    * @access   public
235    * @param    array   $cols   Array of column keys (printed in <option value="
">) and names (human-readable)
236    * @return
237    * @author   Quinn Comendant <quinn@strangecode.com>
238    * @since    18 May 2019 15:27:21
239    */
240    public function printSortSelectMenu($cols)
241    {
242        $app =& App::getInstance();
243
244        ?><select name="sort" id="sort"><?php
245        foreach ($cols as $col => $col_name) {
246            if (!isset($this->_columns[$col])) {
247                $app->logMsg(sprintf('Sort select option %s is not setup via setColumn', $col), LOG_NOTICE, __FILE__, __LINE__);
248            }
249            printf('<option value="%s"%s>%s</option>',
250                $col,
251                ($this->sort_by == $col ? ' selected="selected"' : ''),
252                strip_tags($col_name)
253            );
254        }
255        ?></select><?php
256    }
257
258}
259
Note: See TracBrowser for help on using the repository browser.