1<?php
2/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
4/**
5 * Contains the Pager_HtmlWidgets class
6 *
7 * PHP versions 4 and 5
8 *
9 * LICENSE: Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote products
17 *    derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
20 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
23 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 *
30 * @category  HTML
31 * @package   Pager
32 * @author    Lorenzo Alberton <l.alberton@quipo.it>
33 * @copyright 2003-2007 Lorenzo Alberton
34 * @license   http://www.debian.org/misc/bsd.license  BSD License (3 Clause)
35 * @version   CVS: $Id$
36 * @link      http://pear.php.net/package/Pager
37 */
38
39/**
40 * Pager_HtmlWidgets
41 *
42 * @category  HTML
43 * @package   Pager
44 * @author    Lorenzo Alberton <l.alberton@quipo.it>
45 * @copyright 2003-2007 Lorenzo Alberton
46 * @license   http://www.debian.org/misc/bsd.license  BSD License (3 Clause)
47 * @link      http://pear.php.net/package/Pager
48 */
49class Pager_HtmlWidgets
50{
51    var $pager = null;
52
53    // {{{ constructor
54
55    /**
56     * Constructor
57     *
58     * @param object &$pager Pager instance
59     */
60    function __construct(&$pager)
61    {
62        $this->pager =& $pager;
63    }
64
65    /**
66     * Constructor for PHP4 compatibility
67     *
68     * @param object &$pager Pager instance
69     *
70     * @see http://cweiske.de/tagebuch/php4-constructors-php7.htm
71     */
72    public function Pager_HtmlWidgets(&$pager)
73    {
74        self::__construct($pager);
75    }
76
77    // }}}
78    // {{{ getPerPageSelectBox()
79
80    /**
81     * Returns a string with a XHTML SELECT menu,
82     * useful for letting the user choose how many items per page should be
83     * displayed. If parameter useSessions is TRUE, this value is stored in
84     * a session var. The string isn't echoed right now so you can use it
85     * with template engines.
86     *
87     * @param integer $start       starting value for the select menu
88     * @param integer $end         ending value for the select menu
89     * @param integer $step        step between values in the select menu
90     * @param boolean $showAllData If true, perPage is set equal to totalItems.
91     * @param array   $extraParams (or string $optionText for BC reasons)
92     *                - 'optionText': text to show in each option.
93     *                  Use '%d' where you want to see the number of pages selected.
94     *                - 'attributes': (html attributes) Tag attributes or
95     *                  HTML attributes (id="foo" pairs), will be inserted in the
96     *                  <select> tag
97     *                - 'checkMaxLimit': if true, Pager checks if $end is bigger
98     *                  than $totalItems, and doesn't show the extra select options
99     *                - 'autoSubmit': if TRUE, add some js code
100     *                  to submit the form on the onChange event
101     *
102     * @return string xhtml select box
103     * @access public
104     */
105    function getPerPageSelectBox($start=5, $end=30, $step=5, $showAllData=false, $extraParams=array())
106    {
107        // FIXME: needs POST support
108        $optionText = '%d';
109        $attributes = '';
110        $checkMaxLimit = false;
111        if (is_string($extraParams)) {
112            //old behavior, BC maintained
113            $optionText = $extraParams;
114        } else {
115            if (array_key_exists('optionText', $extraParams)) {
116                $optionText = $extraParams['optionText'];
117            }
118            if (array_key_exists('attributes', $extraParams)) {
119                $attributes = $extraParams['attributes'];
120            }
121            if (array_key_exists('checkMaxLimit', $extraParams)) {
122                $checkMaxLimit = $extraParams['checkMaxLimit'];
123            }
124        }
125
126        if (!strstr($optionText, '%d')) {
127            return $this->pager->raiseError(
128                $this->pager->errorMessage(ERROR_PAGER_INVALID_PLACEHOLDER),
129                ERROR_PAGER_INVALID_PLACEHOLDER
130            );
131        }
132        $start = (int)$start;
133        $end   = (int)$end;
134        $step  = (int)$step;
135        if (!empty($_SESSION[$this->pager->_sessionVar])) {
136            $selected = (int)$_SESSION[$this->pager->_sessionVar];
137        } else {
138            $selected = $this->pager->_perPage;
139        }
140
141        if ($checkMaxLimit && $this->pager->_totalItems >= 0 && $this->pager->_totalItems < $end) {
142            $end = $this->pager->_totalItems;
143        }
144
145        $tmp = '<select name="'.$this->pager->_sessionVar.'"';
146        if (!empty($attributes)) {
147            $tmp .= ' '.$attributes;
148        }
149        if (!empty($extraParams['autoSubmit'])) {
150            if ('GET' == $this->pager->_httpMethod) {
151                $selector = '\' + '.'this.options[this.selectedIndex].value + \'';
152                if ($this->pager->_append) {
153                    $tmpLinkData = $this->pager->_linkData;
154                    if (isset($tmpLinkData[$this->pager->_urlVar])) {
155                        $tmpLinkData[$this->pager->_urlVar] = $this->pager->getCurrentPageID();
156                    }
157                    $tmpLinkData[$this->pager->_sessionVar] = '1';
158                    $href = '?' . $this->pager->_http_build_query_wrapper($tmpLinkData);
159                    $href = htmlentities($this->pager->_url, ENT_COMPAT, 'UTF-8'). preg_replace(
160                        '/(&|&amp;|\?)('.$this->pager->_sessionVar.'=)(\d+)/',
161                        '\\1\\2'.$selector,
162                        htmlentities($href, ENT_COMPAT, 'UTF-8')
163                    );
164                } else {
165                    $href = htmlentities($this->pager->_url . str_replace('%d', $selector, $this->pager->_fileName), ENT_COMPAT, 'UTF-8');
166                }
167                $tmp .= ' onchange="document.location.href=\''
168                     . $href .'\''
169                     . '"';
170            } elseif ($this->pager->_httpMethod == 'POST') {
171                $tmp .= " onchange='"
172                     . $this->pager->_generateFormOnClick($this->pager->_url, $this->pager->_linkData)
173                     . "'";
174                $tmp = preg_replace(
175                    '/(input\.name = \"'.$this->pager->_sessionVar.'\"; input\.value =) \"(\d+)\";/',
176                    '\\1 this.options[this.selectedIndex].value;',
177                    $tmp
178                );
179            }
180        }
181
182
183        $tmp .= '>';
184        $last = $start;
185        for ($i=$start; $i<=$end; $i+=$step) {
186            $last = $i;
187            $tmp .= '<option value="'.$i.'"';
188            if ($i == $selected) {
189                $tmp .= ' selected="selected"';
190            }
191            $tmp .= '>'.sprintf($optionText, $i).'</option>';
192        }
193        if ($showAllData && $last != $this->pager->_totalItems) {
194            $tmp .= '<option value="'.$this->pager->_totalItems.'"';
195            if ($this->pager->_totalItems == $selected) {
196                $tmp .= ' selected="selected"';
197            }
198            $tmp .= '>';
199            if (empty($this->pager->_showAllText)) {
200                $tmp .= str_replace('%d', $this->pager->_totalItems, $optionText);
201            } else {
202                $tmp .= $this->pager->_showAllText;
203            }
204            $tmp .= '</option>';
205        }
206        if (substr($tmp, -9, 9) !== '</option>') {
207            //empty select
208            $tmp .= '<option />';
209        }
210        $tmp .= '</select>';
211        return $tmp;
212    }
213
214    // }}}
215    // {{{ getPageSelectBox()
216
217    /**
218     * Returns a string with a XHTML SELECT menu with the page numbers,
219     * useful as an alternative to the links
220     *
221     * @param array  $params          - 'optionText': text to show in each option.
222     *                                  Use '%d' where you want to see the number
223     *                                  of pages selected.
224     *                                - 'autoSubmit': if TRUE, add some js code
225     *                                  to submit the form on the onChange event
226     * @param string $extraAttributes (html attributes) Tag attributes or
227     *                                HTML attributes (id="foo" pairs), will be
228     *                                inserted in the <select> tag
229     *
230     * @return string xhtml select box
231     * @access public
232     */
233    function getPageSelectBox($params = array(), $extraAttributes = '')
234    {
235        $optionText = '%d';
236        if (array_key_exists('optionText', $params)) {
237            $optionText = $params['optionText'];
238        }
239
240        if (!strstr($optionText, '%d')) {
241            return $this->pager->raiseError(
242                $this->pager->errorMessage(ERROR_PAGER_INVALID_PLACEHOLDER),
243                ERROR_PAGER_INVALID_PLACEHOLDER
244            );
245        }
246
247        $tmp = '<select name="'.$this->pager->_urlVar.'"';
248        if (!empty($extraAttributes)) {
249            $tmp .= ' '.$extraAttributes;
250        }
251        if (!empty($params['autoSubmit'])) {
252            if ($this->pager->_httpMethod == 'GET') {
253                $selector = '\' + '.'this.options[this.selectedIndex].value + \'';
254                if ($this->pager->_append) {
255                    $href = '?' . $this->pager->_http_build_query_wrapper($this->pager->_linkData);
256                    $href = htmlentities($this->pager->_url, ENT_COMPAT, 'UTF-8'). preg_replace(
257                        '/(&|&amp;|\?)('.$this->pager->_urlVar.'=)(\d+)/',
258                        '\\1\\2'.$selector,
259                        htmlentities($href, ENT_COMPAT, 'UTF-8')
260                    );
261                } else {
262                    $href = htmlentities($this->pager->_url . str_replace('%d', $selector, $this->pager->_fileName), ENT_COMPAT, 'UTF-8');
263                }
264                $tmp .= ' onchange="document.location.href=\''
265                     . $href .'\''
266                     . '"';
267            } elseif ($this->pager->_httpMethod == 'POST') {
268                $tmp .= " onchange='"
269                     . $this->pager->_generateFormOnClick($this->pager->_url, $this->pager->_linkData)
270                     . "'";
271                $tmp = preg_replace(
272                    '/(input\.name = \"'.$this->pager->_urlVar.'\"; input\.value =) \"(\d+)\";/',
273                    '\\1 this.options[this.selectedIndex].value;',
274                    $tmp
275                );
276            }
277        }
278        $tmp .= '>';
279        $start = 1;
280        $end   = $this->pager->numPages();
281        $selected = $this->pager->getCurrentPageID();
282        for ($i=$start; $i<=$end; $i++) {
283            $tmp .= '<option value="'.$i.'"';
284            if ($i == $selected) {
285                $tmp .= ' selected="selected"';
286            }
287            $tmp .= '>'.sprintf($optionText, $i).'</option>';
288        }
289        $tmp .= '</select>';
290        return $tmp;
291    }
292
293    // }}}
294}
295?>