PaginatorHelper.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. <?php
  2. /**
  3. * Pagination Helper class file.
  4. *
  5. * Generates pagination links
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.View.Helper
  17. * @since CakePHP(tm) v 1.2.0
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. App::uses('AppHelper', 'View/Helper');
  21. /**
  22. * Pagination Helper class for easy generation of pagination links.
  23. *
  24. * PaginationHelper encloses all methods needed when working with pagination.
  25. *
  26. * @package Cake.View.Helper
  27. * @property HtmlHelper $Html
  28. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html
  29. */
  30. class PaginatorHelper extends AppHelper {
  31. /**
  32. * Helper dependencies
  33. *
  34. * @var array
  35. */
  36. public $helpers = array('Html');
  37. /**
  38. * The class used for 'Ajax' pagination links. Defaults to JsHelper. You should make sure
  39. * that JsHelper is defined as a helper before PaginatorHelper, if you want to customize the JsHelper.
  40. *
  41. * @var string
  42. */
  43. protected $_ajaxHelperClass = 'Js';
  44. /**
  45. * Holds the default options for pagination links
  46. *
  47. * The values that may be specified are:
  48. *
  49. * - `format` Format of the counter. Supported formats are 'range' and 'pages'
  50. * and custom (default). In the default mode the supplied string is parsed and constants are replaced
  51. * by their actual values.
  52. * placeholders: %page%, %pages%, %current%, %count%, %start%, %end% .
  53. * - `separator` The separator of the actual page and number of pages (default: ' of ').
  54. * - `url` Url of the action. See Router::url()
  55. * - `url['sort']` the key that the recordset is sorted.
  56. * - `url['direction']` Direction of the sorting (default: 'asc').
  57. * - `url['page']` Page number to use in links.
  58. * - `model` The name of the model.
  59. * - `escape` Defines if the title field for the link should be escaped (default: true).
  60. * - `update` DOM id of the element updated with the results of the AJAX call.
  61. * If this key isn't specified Paginator will use plain HTML links.
  62. * - `paging['paramType']` The type of parameters to use when creating links. Valid options are
  63. * 'querystring' and 'named'. See PaginatorComponent::$settings for more information.
  64. * - `convertKeys` - A list of keys in url arrays that should be converted to querysting params
  65. * if paramType == 'querystring'.
  66. *
  67. * @var array
  68. */
  69. public $options = array(
  70. 'convertKeys' => array('page', 'limit', 'sort', 'direction')
  71. );
  72. /**
  73. * Constructor for the helper. Sets up the helper that is used for creating 'AJAX' links.
  74. *
  75. * Use `public $helpers = array('Paginator' => array('ajax' => 'CustomHelper'));` to set a custom Helper
  76. * or choose a non JsHelper Helper. If you want to use a specific library with JsHelper declare JsHelper and its
  77. * adapter before including PaginatorHelper in your helpers array.
  78. *
  79. * The chosen custom helper must implement a `link()` method.
  80. *
  81. * @param View $View the view object the helper is attached to.
  82. * @param array $settings Array of settings.
  83. * @throws CakeException When the AjaxProvider helper does not implement a link method.
  84. */
  85. public function __construct(View $View, $settings = array()) {
  86. $ajaxProvider = isset($settings['ajax']) ? $settings['ajax'] : 'Js';
  87. $this->helpers[] = $ajaxProvider;
  88. $this->_ajaxHelperClass = $ajaxProvider;
  89. App::uses($ajaxProvider . 'Helper', 'View/Helper');
  90. $classname = $ajaxProvider . 'Helper';
  91. if (!class_exists($classname) || !method_exists($classname, 'link')) {
  92. throw new CakeException(
  93. __d('cake_dev', '%s does not implement a %s method, it is incompatible with %s', $classname, 'link()', 'PaginatorHelper')
  94. );
  95. }
  96. parent::__construct($View, $settings);
  97. }
  98. /**
  99. * Before render callback. Overridden to merge passed args with url options.
  100. *
  101. * @param string $viewFile
  102. * @return void
  103. */
  104. public function beforeRender($viewFile) {
  105. $this->options['url'] = array_merge($this->request->params['pass'], $this->request->params['named']);
  106. if (!empty($this->request->query)) {
  107. $this->options['url']['?'] = $this->request->query;
  108. }
  109. parent::beforeRender($viewFile);
  110. }
  111. /**
  112. * Gets the current paging parameters from the resultset for the given model
  113. *
  114. * @param string $model Optional model name. Uses the default if none is specified.
  115. * @return array The array of paging parameters for the paginated resultset.
  116. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::params
  117. */
  118. public function params($model = null) {
  119. if (empty($model)) {
  120. $model = $this->defaultModel();
  121. }
  122. if (!isset($this->request->params['paging']) || empty($this->request->params['paging'][$model])) {
  123. return null;
  124. }
  125. return $this->request->params['paging'][$model];
  126. }
  127. /**
  128. * Convenience access to any of the paginator params.
  129. *
  130. * @param string $key Key of the paginator params array to retreive.
  131. * @param string $model Optional model name. Uses the default if none is specified.
  132. * @return mixed Content of the requested param.
  133. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::params
  134. */
  135. public function param($key, $model = null) {
  136. $params = $this->params($model);
  137. if (!isset($params[$key])) {
  138. return null;
  139. }
  140. return $params[$key];
  141. }
  142. /**
  143. * Sets default options for all pagination links
  144. *
  145. * @param array|string $options Default options for pagination links. If a string is supplied - it
  146. * is used as the DOM id element to update. See PaginatorHelper::$options for list of keys.
  147. * @return void
  148. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::options
  149. */
  150. public function options($options = array()) {
  151. if (is_string($options)) {
  152. $options = array('update' => $options);
  153. }
  154. if (!empty($options['paging'])) {
  155. if (!isset($this->request->params['paging'])) {
  156. $this->request->params['paging'] = array();
  157. }
  158. $this->request->params['paging'] = array_merge($this->request->params['paging'], $options['paging']);
  159. unset($options['paging']);
  160. }
  161. $model = $this->defaultModel();
  162. if (!empty($options[$model])) {
  163. if (!isset($this->request->params['paging'][$model])) {
  164. $this->request->params['paging'][$model] = array();
  165. }
  166. $this->request->params['paging'][$model] = array_merge(
  167. $this->request->params['paging'][$model], $options[$model]
  168. );
  169. unset($options[$model]);
  170. }
  171. if (!empty($options['convertKeys'])) {
  172. $options['convertKeys'] = array_merge($this->options['convertKeys'], $options['convertKeys']);
  173. }
  174. $this->options = array_filter(array_merge($this->options, $options));
  175. }
  176. /**
  177. * Gets the current page of the recordset for the given model
  178. *
  179. * @param string $model Optional model name. Uses the default if none is specified.
  180. * @return string The current page number of the recordset.
  181. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::current
  182. */
  183. public function current($model = null) {
  184. $params = $this->params($model);
  185. if (isset($params['page'])) {
  186. return $params['page'];
  187. }
  188. return 1;
  189. }
  190. /**
  191. * Gets the current key by which the recordset is sorted
  192. *
  193. * @param string $model Optional model name. Uses the default if none is specified.
  194. * @param array $options Options for pagination links. See #options for list of keys.
  195. * @return string The name of the key by which the recordset is being sorted, or
  196. * null if the results are not currently sorted.
  197. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::sortKey
  198. */
  199. public function sortKey($model = null, $options = array()) {
  200. if (empty($options)) {
  201. $params = $this->params($model);
  202. $options = $params['options'];
  203. }
  204. if (isset($options['sort']) && !empty($options['sort'])) {
  205. return $options['sort'];
  206. }
  207. if (isset($options['order'])) {
  208. return is_array($options['order']) ? key($options['order']) : $options['order'];
  209. }
  210. if (isset($params['order'])) {
  211. return is_array($params['order']) ? key($params['order']) : $params['order'];
  212. }
  213. return null;
  214. }
  215. /**
  216. * Gets the current direction the recordset is sorted
  217. *
  218. * @param string $model Optional model name. Uses the default if none is specified.
  219. * @param array $options Options for pagination links. See #options for list of keys.
  220. * @return string The direction by which the recordset is being sorted, or
  221. * null if the results are not currently sorted.
  222. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::sortDir
  223. */
  224. public function sortDir($model = null, $options = array()) {
  225. $dir = null;
  226. if (empty($options)) {
  227. $params = $this->params($model);
  228. $options = $params['options'];
  229. }
  230. if (isset($options['direction'])) {
  231. $dir = strtolower($options['direction']);
  232. } elseif (isset($options['order']) && is_array($options['order'])) {
  233. $dir = strtolower(current($options['order']));
  234. } elseif (isset($params['order']) && is_array($params['order'])) {
  235. $dir = strtolower(current($params['order']));
  236. }
  237. if ($dir === 'desc') {
  238. return 'desc';
  239. }
  240. return 'asc';
  241. }
  242. /**
  243. * Generates a "previous" link for a set of paged records
  244. *
  245. * ### Options:
  246. *
  247. * - `tag` The tag wrapping tag you want to use, defaults to 'span'. Set this to false to disable this option
  248. * - `escape` Whether you want the contents html entity encoded, defaults to true
  249. * - `model` The model to use, defaults to PaginatorHelper::defaultModel()
  250. * - `disabledTag` Tag to use instead of A tag when there is no previous page
  251. *
  252. * @param string $title Title for the link. Defaults to '<< Previous'.
  253. * @param array $options Options for pagination link. See #options for list of keys.
  254. * @param string $disabledTitle Title when the link is disabled.
  255. * @param array $disabledOptions Options for the disabled pagination link. See #options for list of keys.
  256. * @return string A "previous" link or $disabledTitle text if the link is disabled.
  257. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::prev
  258. */
  259. public function prev($title = '<< Previous', $options = array(), $disabledTitle = null, $disabledOptions = array()) {
  260. $defaults = array(
  261. 'rel' => 'prev'
  262. );
  263. $options = array_merge($defaults, (array)$options);
  264. return $this->_pagingLink('Prev', $title, $options, $disabledTitle, $disabledOptions);
  265. }
  266. /**
  267. * Generates a "next" link for a set of paged records
  268. *
  269. * ### Options:
  270. *
  271. * - `tag` The tag wrapping tag you want to use, defaults to 'span'. Set this to false to disable this option
  272. * - `escape` Whether you want the contents html entity encoded, defaults to true
  273. * - `model` The model to use, defaults to PaginatorHelper::defaultModel()
  274. * - `disabledTag` Tag to use instead of A tag when there is no next page
  275. *
  276. * @param string $title Title for the link. Defaults to 'Next >>'.
  277. * @param array $options Options for pagination link. See above for list of keys.
  278. * @param string $disabledTitle Title when the link is disabled.
  279. * @param array $disabledOptions Options for the disabled pagination link. See above for list of keys.
  280. * @return string A "next" link or $disabledTitle text if the link is disabled.
  281. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::next
  282. */
  283. public function next($title = 'Next >>', $options = array(), $disabledTitle = null, $disabledOptions = array()) {
  284. $defaults = array(
  285. 'rel' => 'next'
  286. );
  287. $options = array_merge($defaults, (array)$options);
  288. return $this->_pagingLink('Next', $title, $options, $disabledTitle, $disabledOptions);
  289. }
  290. /**
  291. * Generates a sorting link. Sets named parameters for the sort and direction. Handles
  292. * direction switching automatically.
  293. *
  294. * ### Options:
  295. *
  296. * - `escape` Whether you want the contents html entity encoded, defaults to true
  297. * - `model` The model to use, defaults to PaginatorHelper::defaultModel()
  298. * - `direction` The default direction to use when this link isn't active.
  299. *
  300. * @param string $key The name of the key that the recordset should be sorted.
  301. * @param string $title Title for the link. If $title is null $key will be used
  302. * for the title and will be generated by inflection.
  303. * @param array $options Options for sorting link. See above for list of keys.
  304. * @return string A link sorting default by 'asc'. If the resultset is sorted 'asc' by the specified
  305. * key the returned link will sort by 'desc'.
  306. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::sort
  307. */
  308. public function sort($key, $title = null, $options = array()) {
  309. $options = array_merge(array('url' => array(), 'model' => null), $options);
  310. $url = $options['url'];
  311. unset($options['url']);
  312. if (empty($title)) {
  313. $title = $key;
  314. if (strpos($title, '.') !== false) {
  315. $title = str_replace('.', ' ', $title);
  316. }
  317. $title = __(Inflector::humanize(preg_replace('/_id$/', '', $title)));
  318. }
  319. $dir = isset($options['direction']) ? $options['direction'] : 'asc';
  320. unset($options['direction']);
  321. $sortKey = $this->sortKey($options['model']);
  322. $defaultModel = $this->defaultModel();
  323. $isSorted = (
  324. $sortKey === $key ||
  325. $sortKey === $defaultModel . '.' . $key ||
  326. $key === $defaultModel . '.' . $sortKey
  327. );
  328. if ($isSorted) {
  329. $dir = $this->sortDir($options['model']) === 'asc' ? 'desc' : 'asc';
  330. $class = $dir === 'asc' ? 'desc' : 'asc';
  331. if (!empty($options['class'])) {
  332. $options['class'] .= ' ' . $class;
  333. } else {
  334. $options['class'] = $class;
  335. }
  336. }
  337. if (is_array($title) && array_key_exists($dir, $title)) {
  338. $title = $title[$dir];
  339. }
  340. $url = array_merge(array('sort' => $key, 'direction' => $dir), $url, array('order' => null));
  341. return $this->link($title, $url, $options);
  342. }
  343. /**
  344. * Generates a plain or Ajax link with pagination parameters
  345. *
  346. * ### Options
  347. *
  348. * - `update` The Id of the DOM element you wish to update. Creates Ajax enabled links
  349. * with the AjaxHelper.
  350. * - `escape` Whether you want the contents html entity encoded, defaults to true
  351. * - `model` The model to use, defaults to PaginatorHelper::defaultModel()
  352. *
  353. * @param string $title Title for the link.
  354. * @param string|array $url Url for the action. See Router::url()
  355. * @param array $options Options for the link. See #options for list of keys.
  356. * @return string A link with pagination parameters.
  357. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::link
  358. */
  359. public function link($title, $url = array(), $options = array()) {
  360. $options = array_merge(array('model' => null, 'escape' => true), $options);
  361. $model = $options['model'];
  362. unset($options['model']);
  363. if (!empty($this->options)) {
  364. $options = array_merge($this->options, $options);
  365. }
  366. if (isset($options['url'])) {
  367. $url = array_merge((array)$options['url'], (array)$url);
  368. unset($options['url']);
  369. }
  370. unset($options['convertKeys']);
  371. $url = $this->url($url, true, $model);
  372. $obj = isset($options['update']) ? $this->_ajaxHelperClass : 'Html';
  373. return $this->{$obj}->link($title, $url, $options);
  374. }
  375. /**
  376. * Merges passed URL options with current pagination state to generate a pagination URL.
  377. *
  378. * @param array $options Pagination/URL options array
  379. * @param boolean $asArray Return the url as an array, or a URI string
  380. * @param string $model Which model to paginate on
  381. * @return mixed By default, returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript)
  382. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::url
  383. */
  384. public function url($options = array(), $asArray = false, $model = null) {
  385. $paging = $this->params($model);
  386. $url = array_merge(array_filter($paging['options']), $options);
  387. if (isset($url['order'])) {
  388. $sort = $direction = null;
  389. if (is_array($url['order'])) {
  390. list($sort, $direction) = array($this->sortKey($model, $url), current($url['order']));
  391. }
  392. unset($url['order']);
  393. $url = array_merge($url, compact('sort', 'direction'));
  394. }
  395. $url = $this->_convertUrlKeys($url, $paging['paramType']);
  396. if (!empty($url['page']) && $url['page'] == 1) {
  397. $url['page'] = null;
  398. }
  399. if (!empty($url['?']['page']) && $url['?']['page'] == 1) {
  400. unset($url['?']['page']);
  401. }
  402. if ($asArray) {
  403. return $url;
  404. }
  405. return parent::url($url);
  406. }
  407. /**
  408. * Converts the keys being used into the format set by options.paramType
  409. *
  410. * @param array $url Array of url params to convert
  411. * @param string $type
  412. * @return array converted url params.
  413. */
  414. protected function _convertUrlKeys($url, $type) {
  415. if ($type === 'named') {
  416. return $url;
  417. }
  418. if (!isset($url['?'])) {
  419. $url['?'] = array();
  420. }
  421. foreach ($this->options['convertKeys'] as $key) {
  422. if (isset($url[$key])) {
  423. $url['?'][$key] = $url[$key];
  424. unset($url[$key]);
  425. }
  426. }
  427. return $url;
  428. }
  429. /**
  430. * Protected method for generating prev/next links
  431. *
  432. * @param string $which
  433. * @param string $title
  434. * @param array $options
  435. * @param string $disabledTitle
  436. * @param array $disabledOptions
  437. * @return string
  438. */
  439. protected function _pagingLink($which, $title = null, $options = array(), $disabledTitle = null, $disabledOptions = array()) {
  440. $check = 'has' . $which;
  441. $_defaults = array(
  442. 'url' => array(), 'step' => 1, 'escape' => true, 'model' => null,
  443. 'tag' => 'span', 'class' => strtolower($which), 'disabledTag' => null
  444. );
  445. $options = array_merge($_defaults, (array)$options);
  446. $paging = $this->params($options['model']);
  447. if (empty($disabledOptions)) {
  448. $disabledOptions = $options;
  449. }
  450. if (!$this->{$check}($options['model']) && (!empty($disabledTitle) || !empty($disabledOptions))) {
  451. if (!empty($disabledTitle) && $disabledTitle !== true) {
  452. $title = $disabledTitle;
  453. }
  454. $options = array_merge($_defaults, (array)$disabledOptions);
  455. } elseif (!$this->{$check}($options['model'])) {
  456. return null;
  457. }
  458. foreach (array_keys($_defaults) as $key) {
  459. ${$key} = $options[$key];
  460. unset($options[$key]);
  461. }
  462. if ($this->{$check}($model)) {
  463. $url = array_merge(
  464. array('page' => $paging['page'] + ($which === 'Prev' ? $step * -1 : $step)),
  465. $url
  466. );
  467. if ($tag === false) {
  468. return $this->link(
  469. $title,
  470. $url,
  471. compact('escape', 'model', 'class') + $options
  472. );
  473. }
  474. $link = $this->link($title, $url, compact('escape', 'model') + $options);
  475. return $this->Html->tag($tag, $link, compact('class'));
  476. }
  477. unset($options['rel']);
  478. if (!$tag) {
  479. if ($disabledTag) {
  480. $tag = $disabledTag;
  481. $disabledTag = null;
  482. } else {
  483. $tag = $_defaults['tag'];
  484. }
  485. }
  486. if ($disabledTag) {
  487. $title = $this->Html->tag($disabledTag, $title, compact('escape') + $options);
  488. return $this->Html->tag($tag, $title, compact('class'));
  489. }
  490. return $this->Html->tag($tag, $title, compact('escape', 'class') + $options);
  491. }
  492. /**
  493. * Returns true if the given result set is not at the first page
  494. *
  495. * @param string $model Optional model name. Uses the default if none is specified.
  496. * @return boolean True if the result set is not at the first page.
  497. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::hasPrev
  498. */
  499. public function hasPrev($model = null) {
  500. return $this->_hasPage($model, 'prev');
  501. }
  502. /**
  503. * Returns true if the given result set is not at the last page
  504. *
  505. * @param string $model Optional model name. Uses the default if none is specified.
  506. * @return boolean True if the result set is not at the last page.
  507. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::hasNext
  508. */
  509. public function hasNext($model = null) {
  510. return $this->_hasPage($model, 'next');
  511. }
  512. /**
  513. * Returns true if the given result set has the page number given by $page
  514. *
  515. * @param string $model Optional model name. Uses the default if none is specified.
  516. * @param integer $page The page number - if not set defaults to 1.
  517. * @return boolean True if the given result set has the specified page number.
  518. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::hasPage
  519. */
  520. public function hasPage($model = null, $page = 1) {
  521. if (is_numeric($model)) {
  522. $page = $model;
  523. $model = null;
  524. }
  525. $paging = $this->params($model);
  526. return $page <= $paging['pageCount'];
  527. }
  528. /**
  529. * Does $model have $page in its range?
  530. *
  531. * @param string $model Model name to get parameters for.
  532. * @param integer $page Page number you are checking.
  533. * @return boolean Whether model has $page
  534. */
  535. protected function _hasPage($model, $page) {
  536. $params = $this->params($model);
  537. return !empty($params) && $params[$page . 'Page'];
  538. }
  539. /**
  540. * Gets the default model of the paged sets
  541. *
  542. * @return string Model name or null if the pagination isn't initialized.
  543. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::defaultModel
  544. */
  545. public function defaultModel() {
  546. if ($this->_defaultModel) {
  547. return $this->_defaultModel;
  548. }
  549. if (empty($this->request->params['paging'])) {
  550. return null;
  551. }
  552. list($this->_defaultModel) = array_keys($this->request->params['paging']);
  553. return $this->_defaultModel;
  554. }
  555. /**
  556. * Returns a counter string for the paged result set
  557. *
  558. * ### Options
  559. *
  560. * - `model` The model to use, defaults to PaginatorHelper::defaultModel();
  561. * - `format` The format string you want to use, defaults to 'pages' Which generates output like '1 of 5'
  562. * set to 'range' to generate output like '1 - 3 of 13'. Can also be set to a custom string, containing
  563. * the following placeholders `{:page}`, `{:pages}`, `{:current}`, `{:count}`, `{:model}`, `{:start}`, `{:end}` and any
  564. * custom content you would like.
  565. * - `separator` The separator string to use, default to ' of '
  566. *
  567. * The `%page%` style placeholders also work, but are deprecated and will be removed in a future version.
  568. * @param array $options Options for the counter string. See #options for list of keys.
  569. * @return string Counter string.
  570. * @deprecated The %page% style placeholders are deprecated.
  571. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::counter
  572. */
  573. public function counter($options = array()) {
  574. if (is_string($options)) {
  575. $options = array('format' => $options);
  576. }
  577. $options = array_merge(
  578. array(
  579. 'model' => $this->defaultModel(),
  580. 'format' => 'pages',
  581. 'separator' => __d('cake', ' of ')
  582. ),
  583. $options);
  584. $paging = $this->params($options['model']);
  585. if (!$paging['pageCount']) {
  586. $paging['pageCount'] = 1;
  587. }
  588. $start = 0;
  589. if ($paging['count'] >= 1) {
  590. $start = (($paging['page'] - 1) * $paging['limit']) + 1;
  591. }
  592. $end = $start + $paging['limit'] - 1;
  593. if ($paging['count'] < $end) {
  594. $end = $paging['count'];
  595. }
  596. switch ($options['format']) {
  597. case 'range':
  598. if (!is_array($options['separator'])) {
  599. $options['separator'] = array(' - ', $options['separator']);
  600. }
  601. $out = $start . $options['separator'][0] . $end . $options['separator'][1];
  602. $out .= $paging['count'];
  603. break;
  604. case 'pages':
  605. $out = $paging['page'] . $options['separator'] . $paging['pageCount'];
  606. break;
  607. default:
  608. $map = array(
  609. '%page%' => $paging['page'],
  610. '%pages%' => $paging['pageCount'],
  611. '%current%' => $paging['current'],
  612. '%count%' => $paging['count'],
  613. '%start%' => $start,
  614. '%end%' => $end,
  615. '%model%' => strtolower(Inflector::humanize(Inflector::tableize($options['model'])))
  616. );
  617. $out = str_replace(array_keys($map), array_values($map), $options['format']);
  618. $newKeys = array(
  619. '{:page}', '{:pages}', '{:current}', '{:count}', '{:start}', '{:end}', '{:model}'
  620. );
  621. $out = str_replace($newKeys, array_values($map), $out);
  622. }
  623. return $out;
  624. }
  625. /**
  626. * Returns a set of numbers for the paged result set
  627. * uses a modulus to decide how many numbers to show on each side of the current page (default: 8).
  628. *
  629. * `$this->Paginator->numbers(array('first' => 2, 'last' => 2));`
  630. *
  631. * Using the first and last options you can create links to the beginning and end of the page set.
  632. *
  633. * ### Options
  634. *
  635. * - `before` Content to be inserted before the numbers
  636. * - `after` Content to be inserted after the numbers
  637. * - `model` Model to create numbers for, defaults to PaginatorHelper::defaultModel()
  638. * - `modulus` how many numbers to include on either side of the current page, defaults to 8.
  639. * - `separator` Separator content defaults to ' | '
  640. * - `tag` The tag to wrap links in, defaults to 'span'
  641. * - `first` Whether you want first links generated, set to an integer to define the number of 'first'
  642. * links to generate.
  643. * - `last` Whether you want last links generated, set to an integer to define the number of 'last'
  644. * links to generate.
  645. * - `ellipsis` Ellipsis content, defaults to '...'
  646. * - `class` Class for wrapper tag
  647. * - `currentClass` Class for wrapper tag on current active page, defaults to 'current'
  648. * - `currentTag` Tag to use for current page number, defaults to null
  649. *
  650. * @param array $options Options for the numbers, (before, after, model, modulus, separator)
  651. * @return string numbers string.
  652. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::numbers
  653. */
  654. public function numbers($options = array()) {
  655. if ($options === true) {
  656. $options = array(
  657. 'before' => ' | ', 'after' => ' | ', 'first' => 'first', 'last' => 'last'
  658. );
  659. }
  660. $defaults = array(
  661. 'tag' => 'span', 'before' => null, 'after' => null, 'model' => $this->defaultModel(), 'class' => null,
  662. 'modulus' => '8', 'separator' => ' | ', 'first' => null, 'last' => null, 'ellipsis' => '...',
  663. 'currentClass' => 'current', 'currentTag' => null
  664. );
  665. $options += $defaults;
  666. $params = (array)$this->params($options['model']) + array('page' => 1);
  667. unset($options['model']);
  668. if ($params['pageCount'] <= 1) {
  669. return false;
  670. }
  671. extract($options);
  672. unset($options['tag'], $options['before'], $options['after'], $options['model'],
  673. $options['modulus'], $options['separator'], $options['first'], $options['last'],
  674. $options['ellipsis'], $options['class'], $options['currentClass'], $options['currentTag']
  675. );
  676. $out = '';
  677. if ($modulus && $params['pageCount'] > $modulus) {
  678. $half = intval($modulus / 2);
  679. $end = $params['page'] + $half;
  680. if ($end > $params['pageCount']) {
  681. $end = $params['pageCount'];
  682. }
  683. $start = $params['page'] - ($modulus - ($end - $params['page']));
  684. if ($start <= 1) {
  685. $start = 1;
  686. $end = $params['page'] + ($modulus - $params['page']) + 1;
  687. }
  688. if ($first && $start > 1) {
  689. $offset = ($start <= (int)$first) ? $start - 1 : $first;
  690. if ($offset < $start - 1) {
  691. $out .= $this->first($offset, compact('tag', 'separator', 'ellipsis', 'class'));
  692. } else {
  693. $out .= $this->first($offset, compact('tag', 'separator', 'class', 'ellipsis') + array('after' => $separator));
  694. }
  695. }
  696. $out .= $before;
  697. for ($i = $start; $i < $params['page']; $i++) {
  698. $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class')) . $separator;
  699. }
  700. if ($class) {
  701. $currentClass .= ' ' . $class;
  702. }
  703. if ($currentTag) {
  704. $out .= $this->Html->tag($tag, $this->Html->tag($currentTag, $params['page']), array('class' => $currentClass));
  705. } else {
  706. $out .= $this->Html->tag($tag, $params['page'], array('class' => $currentClass));
  707. }
  708. if ($i != $params['pageCount']) {
  709. $out .= $separator;
  710. }
  711. $start = $params['page'] + 1;
  712. for ($i = $start; $i < $end; $i++) {
  713. $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class')) . $separator;
  714. }
  715. if ($end != $params['page']) {
  716. $out .= $this->Html->tag($tag, $this->link($i, array('page' => $end), $options), compact('class'));
  717. }
  718. $out .= $after;
  719. if ($last && $end < $params['pageCount']) {
  720. $offset = ($params['pageCount'] < $end + (int)$last) ? $params['pageCount'] - $end : $last;
  721. if ($offset <= $last && $params['pageCount'] - $end > $offset) {
  722. $out .= $this->last($offset, compact('tag', 'separator', 'ellipsis', 'class'));
  723. } else {
  724. $out .= $this->last($offset, compact('tag', 'separator', 'class', 'ellipsis') + array('before' => $separator));
  725. }
  726. }
  727. } else {
  728. $out .= $before;
  729. for ($i = 1; $i <= $params['pageCount']; $i++) {
  730. if ($i == $params['page']) {
  731. if ($class) {
  732. $currentClass .= ' ' . $class;
  733. }
  734. if ($currentTag) {
  735. $out .= $this->Html->tag($tag, $this->Html->tag($currentTag, $i), array('class' => $currentClass));
  736. } else {
  737. $out .= $this->Html->tag($tag, $i, array('class' => $currentClass));
  738. }
  739. } else {
  740. $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class'));
  741. }
  742. if ($i != $params['pageCount']) {
  743. $out .= $separator;
  744. }
  745. }
  746. $out .= $after;
  747. }
  748. return $out;
  749. }
  750. /**
  751. * Returns a first or set of numbers for the first pages.
  752. *
  753. * `echo $this->Paginator->first('< first');`
  754. *
  755. * Creates a single link for the first page. Will output nothing if you are on the first page.
  756. *
  757. * `echo $this->Paginator->first(3);`
  758. *
  759. * Will create links for the first 3 pages, once you get to the third or greater page. Prior to that
  760. * nothing will be output.
  761. *
  762. * ### Options:
  763. *
  764. * - `tag` The tag wrapping tag you want to use, defaults to 'span'
  765. * - `after` Content to insert after the link/tag
  766. * - `model` The model to use defaults to PaginatorHelper::defaultModel()
  767. * - `separator` Content between the generated links, defaults to ' | '
  768. * - `ellipsis` Content for ellipsis, defaults to '...'
  769. *
  770. * @param string|integer $first if string use as label for the link. If numeric, the number of page links
  771. * you want at the beginning of the range.
  772. * @param array $options An array of options.
  773. * @return string numbers string.
  774. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::first
  775. */
  776. public function first($first = '<< first', $options = array()) {
  777. $options = array_merge(
  778. array(
  779. 'tag' => 'span',
  780. 'after' => null,
  781. 'model' => $this->defaultModel(),
  782. 'separator' => ' | ',
  783. 'ellipsis' => '...',
  784. 'class' => null
  785. ),
  786. (array)$options);
  787. $params = array_merge(array('page' => 1), (array)$this->params($options['model']));
  788. unset($options['model']);
  789. if ($params['pageCount'] <= 1) {
  790. return false;
  791. }
  792. extract($options);
  793. unset($options['tag'], $options['after'], $options['model'], $options['separator'], $options['ellipsis'], $options['class']);
  794. $out = '';
  795. if (is_int($first) && $params['page'] >= $first) {
  796. if ($after === null) {
  797. $after = $ellipsis;
  798. }
  799. for ($i = 1; $i <= $first; $i++) {
  800. $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class'));
  801. if ($i != $first) {
  802. $out .= $separator;
  803. }
  804. }
  805. $out .= $after;
  806. } elseif ($params['page'] > 1 && is_string($first)) {
  807. $options += array('rel' => 'first');
  808. $out = $this->Html->tag($tag, $this->link($first, array('page' => 1), $options), compact('class')) . $after;
  809. }
  810. return $out;
  811. }
  812. /**
  813. * Returns a last or set of numbers for the last pages.
  814. *
  815. * `echo $this->Paginator->last('last >');`
  816. *
  817. * Creates a single link for the last page. Will output nothing if you are on the last page.
  818. *
  819. * `echo $this->Paginator->last(3);`
  820. *
  821. * Will create links for the last 3 pages. Once you enter the page range, no output will be created.
  822. *
  823. * ### Options:
  824. *
  825. * - `tag` The tag wrapping tag you want to use, defaults to 'span'
  826. * - `before` Content to insert before the link/tag
  827. * - `model` The model to use defaults to PaginatorHelper::defaultModel()
  828. * - `separator` Content between the generated links, defaults to ' | '
  829. * - `ellipsis` Content for ellipsis, defaults to '...'
  830. *
  831. * @param string|integer $last if string use as label for the link, if numeric print page numbers
  832. * @param array $options Array of options
  833. * @return string numbers string.
  834. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::last
  835. */
  836. public function last($last = 'last >>', $options = array()) {
  837. $options = array_merge(
  838. array(
  839. 'tag' => 'span',
  840. 'before' => null,
  841. 'model' => $this->defaultModel(),
  842. 'separator' => ' | ',
  843. 'ellipsis' => '...',
  844. 'class' => null
  845. ),
  846. (array)$options);
  847. $params = array_merge(array('page' => 1), (array)$this->params($options['model']));
  848. unset($options['model']);
  849. if ($params['pageCount'] <= 1) {
  850. return false;
  851. }
  852. extract($options);
  853. unset($options['tag'], $options['before'], $options['model'], $options['separator'], $options['ellipsis'], $options['class']);
  854. $out = '';
  855. $lower = $params['pageCount'] - $last + 1;
  856. if (is_int($last) && $params['page'] <= $lower) {
  857. if ($before === null) {
  858. $before = $ellipsis;
  859. }
  860. for ($i = $lower; $i <= $params['pageCount']; $i++) {
  861. $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class'));
  862. if ($i != $params['pageCount']) {
  863. $out .= $separator;
  864. }
  865. }
  866. $out = $before . $out;
  867. } elseif ($params['page'] < $params['pageCount'] && is_string($last)) {
  868. $options += array('rel' => 'last');
  869. $out = $before . $this->Html->tag(
  870. $tag, $this->link($last, array('page' => $params['pageCount']), $options), compact('class')
  871. );
  872. }
  873. return $out;
  874. }
  875. }