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

Last change on this file since 644 was 635, checked in by anonymous, 6 years ago

Minor tweaks

File size: 8.7 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
48    /**
49     * Constructor. Finds the current sort by and order.
50     *
51     * @param string $default_sort   If not found elsewhere, this will be the
52     *                               current sort by.
53     * @param string $default_order  If not found elsewhere, this will be the
54     *                               current order.
55     */
56    public function __construct($default_sort = '', $default_order = '')
57    {
58        $app =& App::getInstance();
59
60        // Setup the HTML for printing ASC/DESC paths.
61        // This should be converted to CSS someday.
62        $images_path = $app->getParam('images_path') ? $app->getParam('images_path') : '/admin/_widgets';
63        $this->asc_widget = sprintf('<img src="%s/sort_ascending.gif" alt="%s" width="11" height="7" border="0" />', $images_path, _("Ascending"));
64        $this->desc_widget = sprintf('<img src="%s/sort_descending.gif" alt="%s" width="11" height="7" border="0" />', $images_path, _("Descending"));
65
66        // Setup prefs object.
67        $this->prefs = new Prefs($_SERVER['PHP_SELF']);
68        $this->prefs->setParam(array('persistent' => false));
69
70        // Setup defaults.
71        $this->setDefault($default_sort, $default_order);
72        $this->default_sort = $default_sort;
73        $this->default_order = $default_order;
74    }
75
76    /**
77     * Build an array of valid sort SQL for each DB column. This SQL is reference
78     * by the name and 'asc' or 'desc'.
79     *
80     * @param string $name      Reference name for the column this SQL sorts on.
81     * @param string $asc_sql   The sort SQL if $this->order is ascending.
82     * @param string $desc_sql  The sort SQL if $this->order is descending.
83     */
84    public function setColumn($name, $asc_sql, $desc_sql)
85    {
86        $this->_columns[$name] = array(
87            'asc'  => $asc_sql,
88            'desc' => $desc_sql
89        );
90    }
91
92    /**
93     * Set sort and order values. This is how you set new sort values after
94     * already declaring a SortOrder object, but expect values to come from
95     * getFormData.
96     *
97     * @param string $default_sort   If not found elsewhere, this will be the
98     *                               current sort by.
99     * @param string $default_order  If not found elsewhere, this will be the
100     *                               current order.
101     */
102    public function setDefault($default_sort = '', $default_order = '')
103    {
104        // Which column to sort by?
105        // (1) By GET or POST specification, if available.
106        // (2) By saved preference, if available.
107        // (3) By default (provided at class instantiation).
108        $new_sort_by = getFormData('sort');
109        if (!empty($new_sort_by)) {
110            $this->sort_by = $new_sort_by;
111            $this->prefs->set('sort_by', $this->sort_by);
112        } else if ($this->prefs->exists('sort_by')) {
113            $this->sort_by = $this->prefs->get('sort_by');
114        } else {
115            $this->sort_by = $default_sort;
116        }
117
118        // Which sort order to use?
119        // (1) By GET or POST specification, if available.
120        // (2) By saved preference, if available.
121        // (3) By default (provided at class instantiation).
122        $new_order = getFormData('order');
123        if (!empty($new_order)) {
124            $this->order = $new_order;
125            $this->prefs->set('sort_order', $this->order);
126        } else if ($this->prefs->exists('sort_order')) {
127            $this->order = $this->prefs->get('sort_order');
128        } else {
129            $this->order = $default_order;
130        }
131    }
132
133
134    /**
135     * Forcibly set sort and order values. This is how you set new sort values after
136     * already declaring a SortOrder object. This will ignore getFormData values.
137     *
138     * @param string $sort           The sort by name.
139     * @param string $order          The order direction (ASC,
140     *                               for example, for an alphabetical sort)
141     */
142    public function set($sort=null, $order=null, $save_value=true)
143    {
144        // Set new sort value.
145        if (isset($sort)) {
146            $this->sort_by = $sort;
147            if ($save_value) {
148                $this->prefs->set('sort_by', $this->sort_by);
149            }
150        }
151
152        // Set new order value.
153        if (isset($order)) {
154            $this->order = $order;
155            if ($save_value) {
156                $this->prefs->set('sort_order', $this->order);
157            }
158        }
159    }
160
161    /**
162     * Get the current sort and order values.
163     *
164     * @return array    Array with keys: sort and order. These can be fed back into the SortOrder::set() method or defaults.
165     */
166    public function get()
167    {
168        return array(
169            'sort' => $this->prefs->get('sort_by'),
170            'order' => $this->prefs->get('sort_order'),
171        );
172    }
173
174    /**
175     * Returns the SQL code to sort by set column and set order.
176     */
177    public function getSortOrderSQL()
178    {
179        $app =& App::getInstance();
180        $db =& DB::getInstance();
181
182        if (!isset($this->_columns[mb_strtolower($this->sort_by)])) {
183            $this->sort_by = $this->default_sort;
184            $this->order = $this->default_order;
185        }
186        if (!isset($this->_columns[mb_strtolower($this->sort_by)][mb_strtolower($this->order)])) {
187            $this->order = 'ASC';
188        }
189
190        if (!empty($this->_columns[mb_strtolower($this->sort_by)][mb_strtolower($this->order)])) {
191            return sprintf(' ORDER BY %s ', $this->_columns[mb_strtolower($this->sort_by)][mb_strtolower($this->order)]);
192        } else {
193            $app->logMsg(sprintf('Could not find SQL to sort by %s %s.', $this->sort_by, $this->order), LOG_WARNING, __FILE__, __LINE__);
194            return '';
195        }
196    }
197
198
199    /**
200     * Prints a link for a column header with URL sort determining logic.
201     * Column must be defined first using setColumn().
202     *
203     * @param string $col            The database column to sort by.
204     * @param string $col_name       The human-readable title of the column.
205     * @param string $default_order  The default order for this column (ASC,
206     *                               for example, for an alphabetical sort)
207     */
208    public function printSortHeader($col, $col_name, $default_order='ASC')
209    {
210        $app =& App::getInstance();
211
212        if (isset($this->_columns[$col])) {
213            if ($this->sort_by == $col) {
214                if (mb_strtolower($this->order) == 'desc') {
215                    ?><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?sort=' . $col . '&order=ASC'); ?>" title="<?php echo _("Change to ascending sort order"); ?>" class="sc-sort sc-desc"><?php echo $this->desc_widget; ?></a><?php echo $col_name; ?><?php
216                } else {
217                    ?><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?sort=' . $col . '&order=DESC'); ?>" title="<?php echo _("Change to descending sort order"); ?>" class="sc-sort sc-asc"><?php echo $this->asc_widget; ?></a><?php echo $col_name; ?><?php
218                }
219            } else {
220                ?><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?sort=' . $col . '&order=' . $default_order); ?>" title="<?php echo sprintf(_("Sort by %s"), $col_name); ?>" class="sc-sort"><?php echo $col_name; ?></a><?php
221            }
222        } else {
223            echo $col_name;
224        }
225    }
226
227}
228
Note: See TracBrowser for help on using the repository browser.