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