4d28f865c3e33a7407a431673d917c2513b55967
[platal.git] / classes / plset.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22
23 /** UserSet is a light-weight Model/View tool for displaying a set of items
24 */
25 abstract class PlSet
26 {
27 const DEFAULT_MAX_RES = 20;
28
29 protected $conds = null;
30 protected $orders = array();
31 protected $limit = null;
32
33 protected $count = null;
34 protected $total_count = null;
35 protected $groups = false;
36
37 // Handle the "restrict to values of the current order"
38 protected $restrict_to = null;
39
40 // A list of available views
41 private $mods = array();
42 // An array of $view_name => array($parameters)
43 private $modParams = array();
44 // The current view name
45 private $mod = null;
46 // The default view name
47 private $default = null;
48
49 public function __construct(PlFilterCondition $cond, $orders = null)
50 {
51 if ($cond instanceof PFC_And) {
52 $this->conds = $cond;
53 } else {
54 $this->conds = new PFC_And($cond);
55 }
56
57 if (!is_null($orders) && $orders instanceof PlFilterOrder) {
58 $this->addSort($orders);
59 } else if (is_array($orders)){
60 foreach ($orders as $order) {
61 $this->addSort($order);
62 }
63 }
64 }
65
66 /** Adds a new view (minifiche, trombi, map)
67 * @param $name The name of the view (cf buildView)
68 * @param $description A user-friendly name for the view
69 * @param $default Whether this is the default view
70 * @param $params Parameters used to tune the view (display promo, order by
71 * score...)
72 */
73 public function addMod($name, $description, $default = false, array $params = array())
74 {
75 $name = strtolower($name);
76 $this->mods[$name] = $description;
77 $this->modParams[$name] = $params;
78 if ($default) {
79 $this->default = $name;
80 }
81 }
82
83 public function rmMod($name)
84 {
85 $name = strtolower($name);
86 unset($this->mods[$name]);
87 }
88
89 /** Adds a new sort (on the PlFilter)
90 */
91 public function addSort(PlFilterOrder $order)
92 {
93 $this->orders[] = $order;
94 }
95
96 /** Adds a new condition to the PlFilter
97 */
98 public function addCond(PlFilterCondition $cond)
99 {
100 $this->conds->addChild($cond);
101 }
102
103 /** Restricts a PlFilter to values of a given PlFilterOrder
104 */
105 public function restrictTo($value)
106 {
107 $this->restrict_to = $value;
108 }
109
110 /** This function builds the right kind of PlFilter from given data
111 * @param $cond The PlFilterCondition for the filter
112 * @param $orders An array of PlFilterOrder for the filter
113 * @return a PlFilter
114 */
115 abstract protected function buildFilter(PlFilterCondition $cond, $orders);
116
117 /** This function returns the results of the given filter
118 * within $limit; can be use to replace the default $pf->get call.
119 * @param $pf The filter
120 * @param $limit The PlLimit
121 * @return The results of the filter
122 */
123 protected function &getFilterResults(PlFilter $pf, PlLimit $limit)
124 {
125 $res = $pf->get($limit);
126 return $res;
127 }
128
129 /** Helper function, calls buildFilter with the adequate condition/orders.
130 * @param $orders Additional orders to use before the default ones.
131 * @return A newly created PlFilter.
132 */
133 private function buildFilterHelper($orders = array(), $extra_cond=null)
134 {
135 if (!is_array($orders)) {
136 $orders = array($orders);
137 }
138 $orders = array_merge($orders, $this->orders);
139
140 if ($extra_cond != null) {
141 $conds = clone $this->conds;
142 $conds->addChild($extra_cond);
143 } else {
144 $conds = $this->conds;
145 }
146 return $this->buildFilter($conds, $orders);
147 }
148
149 /** This function returns the values of the set, and sets $count with the
150 * total number of results.
151 * @param $limit A PlLimit for selecting users
152 * @param $orders An optional array of PFO to use before the "default" ones
153 * @return The result of $pf->get();
154 */
155 public function &get(PlLimit $limit = null, $orders = array())
156 {
157 if (is_null($limit)) {
158 $limit = new PlLimit(self::DEFAULT_MAX_RES, 0);
159 }
160 $pf_res = $this->buildFilterHelper($orders);
161 $pf_groups = $pf_res;
162 $this->total_count = $pf_res->getTotalCount();
163 if ($this->restrict_to != null
164 && count($this->orders)
165 && $this->orders[0] instanceof PlFilterGroupableOrder)
166 {
167 $main_order = $this->orders[0];
168 $pf_res = $this->buildFilterHelper($orders, $main_order->getCondition($this->restrict_to));
169 }
170
171 $it = $this->getFilterResults($pf_res, $limit);
172 $this->count = $pf_res->getTotalCount();
173 if ($pf_groups->hasGroups()) {
174 $this->groups = $pf_groups->getGroups();
175 } else {
176 $this->groups = null;
177 }
178 return $it;
179 }
180
181 /** This function returns the ids of the set, and sets $count with the
182 * total number of results.
183 * @param $limit A PlLimit for selecting profiles
184 * @param $orders An optional array of PFO to use before the "default" ones
185 * @return The result of $pf->getId();
186 */
187 public function &getIds(PlLimit $limit = null, $orders = array())
188 {
189 if (is_null($limit)) {
190 $limit = new PlLimit(self::DEFAULT_MAX_RES, 0);
191 }
192 $pf = $this->buildFilterHelper($orders);
193 $result = $pf->getIds($limit);
194 $this->count = count($result);
195 return $result;
196 }
197
198 /** Return an array containing all pertinent parameters for this page
199 * Generated from $_GET, after some cleanup (remove 'n' (plat/al field
200 * for the handler path)
201 */
202 public function args()
203 {
204 $get = $_GET;
205 unset($get['n']);
206 return $get;
207 }
208
209 /** Convert an array into an URL query (?foo=bar)
210 * @param $args An associative array to convert to a query string
211 * @param $encode Whether to url-encode the string
212 */
213 protected function encodeArgs(array $args, $encode = false)
214 {
215 $qs = '?';
216 $sep = '&';
217 foreach ($args as $k=>$v) {
218 if (!$encode) {
219 $k = urlencode($k);
220 $v = urlencode($v);
221 }
222 $qs .= "$k=$v$sep";
223 }
224 return $encode ? urlencode($qs) : $qs;
225 }
226
227 public function count()
228 {
229 return $this->count;
230 }
231
232 /** Builds the view class from the given parameters
233 * @param $view A string ('profile' for 'ProfileView'); if null,
234 * the default view is used.
235 * @return A new PlView instance.
236 */
237 private function &buildView($view)
238 {
239 $view = strtolower($view);
240 if (!$view || !class_exists($view . 'View') || !isset($this->mods[$view])) {
241 reset($this->mods);
242 $view = $this->default ? $this->default : key($this->mods);
243 }
244 $this->mod = $view;
245 $class = $view . 'View';
246 if (!class_exists($class)) {
247 $view = null;
248 } else {
249 $view = new $class($this, $this->modParams[$this->mod]);
250 if (!$view instanceof PlView) {
251 $view = null;
252 }
253 }
254 return $view;
255 }
256
257 /** Creates the view: sets the page template, assigns Smarty vars.
258 * @param $baseurl The base URL for this (for instance, "search/")
259 * @param $page The page in which the view should be loaded
260 * @param $view The name of the view; if null, the default one will be used.
261 */
262 public function apply($baseurl, PlPage $page, $view = null)
263 {
264 $view =& $this->buildView($view);
265 if (is_null($view)) {
266 return false;
267 }
268 $args = $view->args();
269 $page->coreTpl('plset.tpl');
270 $page->assign('plset_base', $baseurl);
271 $page->assign('plset_mods', $this->mods);
272 $page->assign('plset_mod', $this->mod);
273 $page->assign('plset_args', $this->encodeArgs($args));
274 $page->assign('plset_args_enc', $this->encodeArgs($args, true));
275 foreach ($this->modParams[$this->mod] as $param=>$value) {
276 $page->assign($this->mod . '_' . $param, $value);
277 }
278 $page->assign('plset_content', $view->apply($page));
279 $page->assign('plset_count', $this->count);
280 $page->assign('plset_total_count', $this->total_count);
281 $page->assign('plset_has_groups', $this->groups != null);
282 $page->assign('plset_groups', $this->groups);
283 return true;
284 }
285 }
286
287 interface PlView
288 {
289 /** Constructs a new PlView
290 * @param $set The set
291 * @param $params Parameters to tune the view (sort by score, include promo...)
292 */
293 public function __construct(PlSet $set, array $params);
294
295 /** Applies the view to a page
296 * The content of the set is fetched here.
297 * @param $page Page to which the view will be applied
298 * @return The name of the global view template (for displaying the view,
299 * not the items of the set)
300 */
301 public function apply(PlPage $page);
302
303 /** As PlSet->args(), returns the ?foo=bar part of the URL for generating
304 * this PlSet, after adding the necessary components and removing useless ones.
305 */
306 public function args();
307 }
308
309 /** This class describes an Order as used in a PlView :
310 * - It is based on a PlFilterOrder
311 * - It has a short identifier
312 * - It has a full name, to display on the page
313 */
314 class PlViewOrder
315 {
316 public $pfos = null;
317 public $name = null;
318 public $displaytext = null;
319
320 /** Build a PlViewOrder
321 * @param $name Name of the order (key)
322 * @param $displaytext Text to display
323 * @param $pfos Array of PlFilterOrder for the order
324 */
325 public function __construct($name, $pfos, $displaytext = null)
326 {
327 $this->name = $name;
328 if (is_null($displaytext)) {
329 $this->displaytext = ucfirst($name);
330 } else {
331 $this->displaytext = $displaytext;
332 }
333 $this->pfos = $pfos;
334 }
335 }
336
337 abstract class MultipageView implements PlView
338 {
339 protected $set;
340
341 public $pages = 1;
342 public $page = 1;
343 public $restrict = null;
344 public $offset = 0;
345
346 protected $entriesPerPage = 20;
347 protected $params = array();
348
349 protected $sortkeys = array();
350 protected $defaultkey = null;
351
352 protected $bound_field = null;
353
354 /** Builds a MultipageView
355 * @param $set The associated PlSet
356 * @param $params Parameters of the view
357 */
358 public function __construct(PlSet $set, array $params)
359 {
360 $this->set =& $set;
361 $this->page = Env::i('page', 1);
362 $this->restrict = Env::s('restrict', null);
363 $this->offset = $this->entriesPerPage * ($this->page - 1);
364 $this->params = $params;
365 }
366
367 /** Add an order to the view
368 */
369 protected function addSort(PlViewOrder $pvo, $default = false)
370 {
371 $this->sortkeys[$pvo->name] = $pvo;
372 if (!$this->defaultkey || $default) {
373 $this->defaultkey = $pvo->name;
374 }
375 }
376
377 /** Returns a list of PFO objects in accordance with the user's choice
378 */
379 public function order()
380 {
381 $order = Env::v('order', $this->defaultkey);
382 $invert = ($order{0} == '-');
383 if ($invert) {
384 $order = substr($order, 1);
385 }
386
387 $ordering = $this->sortkeys[$order];
388 if ($invert) {
389 foreach ($ordering->pfos as $pfo) {
390 $pfo->toggleDesc();
391 }
392 }
393 return $ordering->pfos;
394 }
395
396 /** Returns information on the order of bounds
397 * @return * 1 if normal bounds
398 * * -1 if inversed bounds
399 * * 0 if bounds shouldn't be displayed
400 */
401 public function bounds()
402 {
403 return null;
404 }
405
406 public function limit()
407 {
408 return new PlLimit($this->entriesPerPage, $this->offset);
409 }
410
411 /** Name of the template to use for displaying items of the view
412 * e.g plview.minifiche.tpl, plview.trombi.pl, ...
413 */
414 abstract public function templateName();
415
416 /** Returns the value of a boundary of the current view (in order
417 * to show "from C to F")
418 * @param $obj The boundary result whose value must be shown to the user
419 * (e.g a Profile, ...)
420 * @return The bound
421 */
422 abstract protected function getBoundValue($obj);
423
424 public function apply(PlPage $page)
425 {
426 foreach ($this->order() as $order) {
427 if (!is_null($order)) {
428 $this->set->addSort($order);
429 }
430 }
431 if ($this->restrict != null) {
432 $this->set->restrictTo($this->restrict);
433 }
434 $res = $this->set->get($this->limit());
435
436 $show_bounds = $this->bounds();
437 if ($show_bounds) {
438 $start = current($res);
439 $end = end($res);
440 if ($show_bounds == 1) {
441 $first = $this->getBoundValue($start);
442 $last = $this->getBoundValue($end);
443 } elseif ($show_bounds == -1) {
444 $first = $this->getBoundValue($end);
445 $last = $this->getBoundValue($start);
446 }
447 $page->assign('first', $first);
448 $page->assign('last', $last);
449 }
450
451 $page->assign('show_bounds', $show_bounds);
452 $page->assign('order', Env::v('order', $this->defaultkey));
453 $page->assign('orders', $this->sortkeys);
454 $page->assign('restrict', $this->restrict);
455 $page->assign_by_ref('plview', $this);
456 if (is_array($res)) {
457 $page->assign('set_keys', array_keys($res));
458 }
459 $page->assign_by_ref('set', $res);
460 $count = $this->set->count();
461 $this->pages = intval(ceil($count / $this->entriesPerPage));
462 return PlPage::getCoreTpl('plview.multipage.tpl');
463 }
464
465 /** Arguments are those needed by the set, minus 'page' and 'order' which
466 * will be set to new values in the html links.
467 */
468 public function args()
469 {
470 $list = $this->set->args();
471 unset($list['page']);
472 unset($list['order']);
473 unset($list['restrict']);
474 return $list;
475 }
476 }
477
478 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
479 ?>