Add sugar.
[platal.git] / classes / userfilter.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 interface UserFilterCondition
23 {
24 const COND_TRUE = 'TRUE';
25 const COND_FALSE = 'FALSE';
26
27 /** Check that the given user matches the rule.
28 */
29 public function buildCondition(UserFilter &$uf);
30 }
31
32 abstract class UFC_OneChild implements UserFilterCondition
33 {
34 protected $child;
35
36 public function __construct($child = null)
37 {
38 if (!is_null($child) && ($child instanceof UserFilterCondition)) {
39 $this->setChild($child);
40 }
41 }
42
43 public function setChild(UserFilterCondition &$cond)
44 {
45 $this->child =& $cond;
46 }
47 }
48
49 abstract class UFC_NChildren implements UserFilterCondition
50 {
51 protected $children = array();
52
53 public function __construct()
54 {
55 $children = func_get_args();
56 foreach ($children as &$child) {
57 if (!is_null($child) && ($child instanceof UserFilterCondition)) {
58 $this->addChild($child);
59 }
60 }
61 }
62
63 public function addChild(UserFilterCondition &$cond)
64 {
65 $this->children[] =& $cond;
66 }
67
68 protected function catConds(array $cond, $op, $fallback)
69 {
70 if (count($cond) == 0) {
71 return $fallback;
72 } else if (count($cond) == 1) {
73 return $cond[0];
74 } else {
75 return '(' . implode(') ' . $op . ' (', $conds) . ')';
76 }
77 }
78 }
79
80 class UFC_True implements UserFilterCondition
81 {
82 public function buildCondition(UserFilter &$uf)
83 {
84 return self::COND_TRUE;
85 }
86 }
87
88 class UFC_False implements UserFilterCondition
89 {
90 public function buildCondition(UserFilter &$uf)
91 {
92 return self::COND_FALSE;
93 }
94 }
95
96 class UFC_Not extends UFC_OneChild
97 {
98 public function buildCondition(UserFilter &$uf)
99 {
100 $val = $this->child->buildCondition($uf);
101 if ($val == self::COND_TRUE) {
102 return self::COND_FALSE;
103 } else if ($val == self::COND_FALSE) {
104 return self::COND_TRUE;
105 } else {
106 return 'NOT (' . $val . ')';
107 }
108 }
109 }
110
111 class UFC_And extends UFC_NChildren
112 {
113 public function buildCondition(UserFilter &$uf)
114 {
115 if (empty($this->children)) {
116 return self::COND_FALSE;
117 } else {
118 $true = self::COND_FALSE;
119 $conds = array();
120 foreach ($this->children as &$child) {
121 $val = $child->buildCondition($uf);
122 if ($val == self::COND_TRUE) {
123 $true = self::COND_TRUE;
124 } else if ($val == self::COND_FALSE) {
125 return self::COND_FALSE;
126 } else {
127 $conds[] = $val;
128 }
129 }
130 return $this->catConds($conds, 'AND', $true);
131 }
132 }
133 }
134
135 class UFC_Or extends UFC_NChildren
136 {
137 public function buildCondition(UserFilter &$uf)
138 {
139 if (empty($this->children)) {
140 return self::COND_TRUE;
141 } else {
142 $true = self::COND_TRUE;
143 $conds = array();
144 foreach ($this->children as &$child) {
145 $val = $child->buildCondition($uf);
146 if ($val == self::COND_TRUE) {
147 return self::COND_TRUE;
148 } else if ($val == self::COND_FALSE) {
149 $true = self::COND_FALSE;
150 } else {
151 $conds[] = $val;
152 }
153 }
154 return $this->catConds($conds, 'OR', $true);
155 }
156 }
157 }
158
159 class UFC_Promo implements UserFilterCondition
160 {
161
162 private $grade;
163 private $promo;
164 private $comparison;
165
166 public function __construct($comparison, $grade, $promo)
167 {
168 $this->grade = $grade;
169 $this->comparison = $comparison;
170 $this->promo = $promo;
171 UserFilter::assertGrade($this->grade);
172 }
173
174 public function buildCondition(UserFilter &$uf)
175 {
176 // XXX: Definition of promotion for phds and masters might change in near future.
177 if ($this->grade == UserFilter::GRADE_ING) {
178 $promo_year = 'entry_year';
179 } else {
180 $promo_year = 'grad_year';
181 }
182 $sub = $uf->addEducationFilter(true, $this->grade);
183 $field = 'pe' . $sub . '.' . $promo_year;
184 return $field . ' IS NOT NULL AND ' . $field . ' ' . $this->comparison . ' ' . XDB::format('{?}', $this->promo);
185 }
186 }
187
188 class UFC_Name implements UserFilterCondition
189 {
190 const PREFIX = 1;
191 const SUFFIX = 2;
192 const PARTICLE = 7;
193 const VARIANTS = 8;
194 const CONTAINS = 3;
195
196 private $type;
197 private $text;
198 private $mode;
199
200 public function __construct($type, $text, $mode)
201 {
202 $this->type = $type;
203 $this->text = $text;
204 $this->mode = $mode;
205 }
206
207 private function buildNameQuery($type, $variant, $where, UserFilter &$uf)
208 {
209 $sub = $uf->addNameFilter($type, $variant);
210 return str_replace('$ME', 'pn' . $sub, $where);
211 }
212
213 public function buildCondition(UserFilter &$uf)
214 {
215 $left = '$ME.name';
216 $op = ' LIKE ';
217 if (($this->mode & self::PARTICLE) == self::PARTICLE) {
218 $left = 'CONCAT($ME.particle, \' \', $ME.name)';
219 }
220 if (($this->mode & self::CONTAINS) == 0) {
221 $right = XDB::format('{?}', $this->text);
222 $op = ' = ';
223 } else if (($this->mode & self::CONTAINS) == self::PREFIX) {
224 $right = XDB::format('CONCAT({?}, \'%\')', $this->text);
225 } else if (($this->mode & self::CONTAINS) == self::SUFFIX) {
226 $right = XDB::format('CONCAT(\'%\', {?})', $this->text);
227 } else {
228 $right = XDB::format('CONCAT(\'%\', {?}, \'%\')', $this->text);
229 }
230 $cond = $left . $op . $right;
231 $conds = array($this->buildNameQuery($this->type, null, $cond, $uf));
232 if (($this->mode & self::VARIANTS) != 0) {
233 foreach (UserFilter::$name_variants[$this->type] as $var) {
234 $conds[] = $this->buildNameQuery($this->type, $var, $cond, $uf);
235 }
236 }
237 return implode(' OR ', $conds);
238 }
239 }
240
241 class UserFilter
242 {
243 private $root;
244 private $query = null;
245
246 public function __construct($cond = null)
247 {
248 if (!is_null($cond)) {
249 if ($cond instanceof UserFilterCondition) {
250 $this->setCondition($cond);
251 }
252 }
253 }
254
255 private function buildQuery()
256 {
257 if (is_null($this->query)) {
258 $where = $this->root->buildCondition($this);
259 $joins = $this->buildJoins();
260 $this->query = 'FROM accounts AS a
261 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET(\'owner\', ap.perms))
262 INNER JOIN profiles AS p ON (p.pid = ap.pid)
263 ' . $joins . '
264 WHERE (' . $where . ')';
265 }
266 }
267
268 private function formatJoin(array $joins)
269 {
270 $str = '';
271 foreach ($joins as $key => $infos) {
272 $mode = $infos[0];
273 $table = $infos[1];
274 if ($mode == 'inner') {
275 $str .= 'INNER JOIN ';
276 } else if ($mode == 'left') {
277 $str .= 'LEFT JOIN ';
278 } else {
279 Platal::page()->kill("Join mode error");
280 }
281 $str .= $table . ' AS ' . $key;
282 if (isset($infos[2])) {
283 $str .= ' ON (' . str_replace(array('$ME', '$PID'), array($key, 'p.pid'), $infos[2]) . ')';
284 }
285 $str .= "\n";
286 }
287 return $str;
288 }
289
290 private function buildJoins()
291 {
292 $joins = $this->educationJoins() + $this->nameJoins();
293 return $this->formatJoin($joins);
294 }
295
296 /** Check that the user match the given rule.
297 */
298 public function checkUser(PlUser &$user)
299 {
300 $this->buildQuery();
301 $count = (int)XDB::fetchOneCell('SELECT COUNT(*)
302 ' . $this->query . XDB::format(' AND a.uid = {?}', $user->id()));
303 return $count == 1;
304 }
305
306 /** Filter a list of user to extract the users matching the rule.
307 */
308 public function filter(array $users)
309 {
310 $output = array();
311 foreach ($users as &$user) {
312 if ($this->checkUser($user)) {
313 $output[] = $user;
314 }
315 }
316 return $output;
317 }
318
319 public function setCondition(UserFilterCondition &$cond)
320 {
321 $this->root =& $cond;
322 $this->query = null;
323 }
324
325 static public function getLegacy($promo_min, $promo_max)
326 {
327 if ($promo_min != 0) {
328 $min = new UFC_Promo('>=', self::GRADE_ING, intval($promo_min));
329 } else {
330 $min = new UFC_True();
331 }
332 if ($promo_max != 0) {
333 $max = new UFC_Promo('<=', self::GRADE_ING, intval($promo_max));
334 } else {
335 $max = new UFC_True();
336 }
337 return new UserFilter(new UFC_And($min, $max));
338 }
339
340
341 /** NAMES
342 */
343 const LASTNAME = 'lastname';
344 const FIRSTNAME = 'firstname';
345 const NICKNAME = 'nickname';
346 const PSEUDONYM = 'pseudonym';
347 const NAME = 'name';
348 const VN_MARITAL = 'marital';
349 const VN_ORDINARY = 'ordinary';
350 const VN_OTHER = 'other';
351 const VN_INI = 'ini';
352
353 static public $name_variants = array(
354 self::LASTNAME => array(self::VN_MARITAL, self::VN_ORDINARY),
355 self::FIRSTNAME => array(self::VN_ORDINARY, self::VN_INI, self::VN_OTHER),
356 self::NICKNAME => array(), self::PSEUDONYM => array(),
357 self::NAME => array());
358
359 static public function assertName($name)
360 {
361 if (!Profile::getNameTypeId($name)) {
362 Platal::page()->kill('Invalid name type');
363 }
364 }
365
366 private $pn = array();
367 private $pno = 0;
368 public function addNameFilter($type, $variant = null)
369 {
370 if (!is_null($variant)) {
371 $ft = $type . '_' . $variant;
372 } else {
373 $ft = $type;
374 }
375 $sub = '_' . $ft;
376 self::assertName($ft);
377
378 if (!is_null($variant) && $variant == 'other') {
379 $sub .= $this->pno++;
380 }
381 $this->pn[$sub] = Profile::getNameTypeId($ft);
382 return $sub;
383 }
384
385 private function nameJoins()
386 {
387 $joins = array();
388 foreach ($this->pn as $sub => $type) {
389 $joins['pn' . $sub] = array('left', 'profile_name', '$ME.pid = $PID AND $ME.typeid = ' . $type);
390 }
391 return $joins;
392 }
393
394
395 /** EDUCATION
396 */
397 const GRADE_ING = 'Ing.';
398 const GRADE_PHD = 'PhD';
399 const GRADE_MST = 'M%';
400 static public function isGrade($grade)
401 {
402 return $grade == self::GRADE_ING || self::$grade == GRADE_PHD || self::$grade == GRADE_MST;
403 }
404
405 static public function assertGrade($grade)
406 {
407 if (!self::isGrade($grade)) {
408 Platal::page()->killError("DiplĂ´me non valide");
409 }
410 }
411
412 private $pepe = array();
413 private $with_pee = false;
414 private $pe_g = 0;
415 public function addEducationFilter($x = false, $grade = null)
416 {
417 if (!$x) {
418 $index = $this->pe_g;
419 $sub = $this->pe_g++;
420 } else {
421 self::assertGrade($grade);
422 $index = $grade;
423 $sub = $grade[0];
424 $this->with_pee = true;
425 }
426 $sub = '_' . $sub;
427 $this->pepe[$index] = $sub;
428 return $sub;
429 }
430
431 private function educationJoins()
432 {
433 $joins = array();
434 if ($this->with_pee) {
435 $joins['pee'] = array('inner', 'profile_education_enum', 'pee.abbreviation = \'X\'');
436 }
437 foreach ($this->pepe as $grade => $sub) {
438 if ($this->isGrade($grade)) {
439 $joins['pe' . $sub] = array('left', 'profile_education', '$ME.eduid = pee.id AND $ME.uid = $PID');
440 $joins['pede' . $sub] = array('inner', 'profile_education_degree_enum', '$ME.id = pe' . $sub . '.degreeid AND $ME.abbreviation LIKE ' .
441 XDB::format('{?}', $grade));
442 } else {
443 $joins['pe' . $sub] = array('left', 'profile_education', '$ME.uid = $PID');
444 $joins['pee' . $sub] = array('inner', 'profile_education_enum', '$ME.id = pe' . $sub . '.eduid');
445 $joins['pede' . $sub] = array('inner', 'profile_education_degree_enum', '$ME.id = pe' . $sub . '.degreeid');
446 }
447 }
448 return $joins;
449 }
450 }
451
452 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
453 ?>