Fixes ProfileAddresses
[platal.git] / classes / profile.php
CommitLineData
e7b93962
FB
1<?php
2/***************************************************************************
d4c08d89 3 * Copyright (C) 2003-2010 Polytechnique.org *
e7b93962
FB
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
22class Profile
23{
f5642983
FB
24 static private $v_values = array('public' => array('public'),
25 'ax' => array('ax', 'public'),
26 'private' => array('private', 'ax', 'public'));
913a4e90 27
f5642983
FB
28 const VISIBILITY_PUBLIC = 'public';
29 const VISIBILITY_AX = 'ax';
30 const VISIBILITY_PRIVATE = 'private';
31
913a4e90
RB
32 /* name tokens */
33 const LASTNAME = 'lastname';
34 const FIRSTNAME = 'firstname';
35 const NICKNAME = 'nickname';
36 const PSEUDONYM = 'pseudonym';
37 const NAME = 'name';
38 /* name variants */
39 const VN_MARITAL = 'marital';
40 const VN_ORDINARY = 'ordinary';
41 const VN_OTHER = 'other';
42 const VN_INI = 'ini';
43 /* display names */
44 const DN_FULL = 'directory_name';
45 const DN_DISPLAY = 'yourself';
46 const DN_YOURSELF = 'yourself';
47 const DN_DIRECTORY = 'directory_name';
48 const DN_PRIVATE = 'private_name';
49 const DN_PUBLIC = 'public_name';
50 const DN_SHORT = 'short_name';
51 const DN_SORT = 'sort_name';
e02d9fbb
SJ
52 /* education related names */
53 const EDU_X = 'École polytechnique';
54 const DEGREE_X = 'Ingénieur';
55 const DEGREE_M = 'Master';
56 const DEGREE_D = 'Doctorat';
913a4e90
RB
57
58 static public $name_variants = array(
59 self::LASTNAME => array(self::VN_MARITAL, self::VN_ORDINARY),
60 self::FIRSTNAME => array(self::VN_ORDINARY, self::VN_INI, self::VN_OTHER)
61 );
62
f5642983
FB
63 const ADDRESS_MAIN = 0x000001;
64 const ADDRESS_PERSO = 0x000002;
65 const ADDRESS_PRO = 0x000004;
66 const ADDRESS_ALL = 0x000006;
67 const ADDRESS_POSTAL = 0x000008;
68
69 const EDUCATION_MAIN = 0x000010;
4bc5b8f0
FB
70 const EDUCATION_EXTRA = 0x000020;
71 const EDUCATION_ALL = 0x000040;
72 const EDUCATION_FINISHED = 0x000080;
73 const EDUCATION_CURRENT = 0x000100;
f5642983 74
4bc5b8f0
FB
75 const JOBS_MAIN = 0x001000;
76 const JOBS_ALL = 0x002000;
77 const JOBS_FINISHED = 0x004000;
78 const JOBS_CURRENT = 0x008000;
f5642983 79
04a94b1d
FB
80 const NETWORKING_ALL = 0x000000;
81 const NETWORKING_WEB = 0x010000;
82 const NETWORKING_IM = 0x020000;
83 const NETWORKING_SOCIAL = 0x040000;
84
9f21bd15
RB
85 const FETCH_ADDRESSES = 0x00001;
86 const FETCH_CORPS = 0x00002;
87 const FETCH_EDU = 0x00004;
88 const FETCH_JOBS = 0x00008;
89 const FETCH_MEDALS = 0x00010;
90 const FETCH_NETWORKING = 0x00020;
91 const FETCH_PHONES = 0x00040;
92 const FETCH_PHOTO = 0x00080;
93
e7b93962
FB
94 private $pid;
95 private $hrpid;
3e53a496
FB
96 private $data = array();
97
f5642983
FB
98 private $visibility = null;
99
b774ddab 100 private function __construct(array $data)
e7b93962 101 {
b774ddab 102 $this->data = $data;
832e6fcb
FB
103 $this->pid = $this->data['pid'];
104 $this->hrpid = $this->data['hrpid'];
f74fb084
FB
105 if (!S::logged()) {
106 $this->setVisibilityLevel(self::VISIBILITY_PUBLIC);
107 }
e7b93962
FB
108 }
109
9f21bd15
RB
110 static private $contexts = array();
111
112 /** Returns the best visibility context toward $visibility
113 * @param $visibility A wished visibility level
114 * @return The closest allowed visibility level
115 *
116 * if $visibility is null, the best visibility is returned
117 */
118 static public function getVisibilityContext($visibility = null)
119 {
120 if (array_key_exists($visibility, self::$contexts)) {
121 return self::$contexts[$visibility];
122 }
123
124 $asked_vis = $visibility;
125
126 if (S::logged()) {
127 $minvis = self::VISIBILITY_PRIVATE;
128 } else {
129 $minvis = self::VISIBILITY_PUBLIC;
130 }
131 if ($visibility == null) {
132 $visibility = array($minvis);
133 }
134
135 if ($minvis == self::VISIBILITY_PUBLIC) {
136 $visibility = array(self::VISIBILITY_PUBLIC);
137 }
138
139 self::$contexts[$asked_vis] = $visibility;
140
141 return $visibility;
142 }
143
e7b93962
FB
144 public function id()
145 {
146 return $this->pid;
147 }
148
149 public function hrid()
150 {
151 return $this->hrpid;
152 }
153
d5e60905
FB
154 public function promo()
155 {
156 return $this->promo;
157 }
158
845f0a4d
SJ
159 public function yearpromo()
160 {
161 return intval(substr($this->promo, 1, 4));
162 }
163
94b72319
FB
164 /** Print a name with the given formatting:
165 * %s = • for women
166 * %f = firstname
167 * %l = lastname
168 * %F = fullname
169 * %S = shortname
170 * %p = promo
171 */
172 public function name($format)
173 {
174 return str_replace(array('%s', '%f', '%l', '%F', '%S', '%p'),
175 array($this->isFemale() ? '•' : '',
faf75faf
SJ
176 $this->firstName(), $this->lastName(),
177 $this->fullName(), $this->shortName(),
178 $this->promo()), $format);
94b72319
FB
179 }
180
181 public function fullName($with_promo = false)
182 {
183 if ($with_promo) {
184 return $this->full_name . ' (' . $this->promo . ')';
185 }
186 return $this->full_name;
187 }
188
189 public function shortName($with_promo = false)
190 {
191 if ($with_promo) {
192 return $this->short_name . ' (' . $this->promo . ')';
193 }
194 return $this->short_name;
195 }
196
197 public function firstName()
198 {
08c91036 199 return $this->firstname;
94b72319
FB
200 }
201
5c005b37
RB
202 public function firstNames()
203 {
204 return $this->nameVariants(self::FIRSTNAME);
205 }
206
94b72319
FB
207 public function lastName()
208 {
08c91036 209 return $this->lastname;
94b72319
FB
210 }
211
5c005b37
RB
212 public function lastNames()
213 {
214 return $this->nameVariants(self::LASTNAME);
215 }
216
94b72319
FB
217 public function isFemale()
218 {
219 return $this->sex == PlUser::GENDER_FEMALE;
220 }
221
222 public function data()
223 {
224 $this->first_name;
225 return $this->data;
226 }
227
5c005b37
RB
228 private function nameVariants($type)
229 {
230 $vals = array($this->$type);
231 foreach (self::$name_variants[$type] as $var) {
232 $vartype = $type . '_' . $var;
233 $varname = $this->$vartype;
234 if ($varname != null && $varname != "") {
235 $vals[] = $varname;
236 }
237 }
238 return array_unique($vals);
239 }
240
b6569a95
FB
241 public function nationalities()
242 {
243 $nats = array();
244 if ($this->nationality1) {
245 $nats[] = $this->nationality1;
246 }
247 if ($this->nationality2) {
248 $nats[] = $this->nationality2;
249 }
250 if ($this->nationality3) {
251 $nats[] = $this->nationality3;
252 }
253 return $nats;
254 }
255
3e53a496
FB
256 public function __get($name)
257 {
258 if (property_exists($this, $name)) {
259 return $this->$name;
260 }
261
3e53a496
FB
262 if (isset($this->data[$name])) {
263 return $this->data[$name];
264 }
265
266 return null;
267 }
268
269 public function __isset($name)
270 {
271 return property_exists($this, $name) || isset($this->data[$name]);
272 }
273
c159e50f
RB
274 /** Sets the level of visibility of the profile
275 * Sets $this->visibility to a list of valid visibilities.
276 * @param one of the self::VISIBILITY_* values
277 */
f5642983
FB
278 public function setVisibilityLevel($visibility)
279 {
0d906109
RB
280 if ($visibility != self::VISIBILITY_PRIVATE
281 && $visibility != self::VISIBILITY_AX
f5642983
FB
282 && $visibility != self::VISIBILITY_PUBLIC) {
283 Platal::page()->kill("Visibility invalide: " . $visibility);
284 }
285 $this->visibility = self::$v_values[$visibility];
5c005b37 286 if ($this->mobile && !in_array($this->mobile_pub, $this->visibility)) {
46e9eb99
FB
287 unset($this->data['mobile']);
288 }
f5642983
FB
289 }
290
c159e50f
RB
291 /** Determine whether an item with visibility $visibility can be displayed
292 * with the current level of visibility of the profile
293 * @param $visibility The level of visibility to be checked
294 */
295 public function isVisible($visibility)
296 {
297 return in_array($visibility, $this->visibility);
298 }
4bc5b8f0 299
9f21bd15
RB
300 public static function getCompatibleVisibilities($visibility)
301 {
302 return self::$v_values[$visibility];
303 }
304
833a6e86
FB
305 /* Photo
306 */
9f21bd15
RB
307 private $photo = null;
308 public function setPhoto(ProfilePhoto $photo)
309 {
310 $this->photo = $photo;
311 }
312
833a6e86
FB
313 public function getPhoto($fallback = true)
314 {
9f21bd15
RB
315 if ($this->photo != null) {
316 return $this->photo->pic;
317 } else if ($fallback) {
318 return PlImage::fromFile(dirname(__FILE__).'/../htdocs/images/none.png',
319 'image/png');
320 }
321 return null;
322 }
323 /*
833a6e86
FB
324 $cond = '';
325 if ($this->visibility) {
9f21bd15 326 $cond = ' AND pub IN ' . XDB::formatArray($this->visibility);
833a6e86 327 }
5d83c3be 328 $res = XDB::query("SELECT *
5c4ea53f 329 FROM profile_photos
5d83c3be
SJ
330 WHERE attachmime IN ('jpeg', 'png')
331 " . $cond . ' AND pid = {?}',
833a6e86
FB
332 $this->id());
333 if ($res->numRows() > 0) {
334 $photo = $res->fetchOneAssoc();
335 return PlImage::fromData($photo['attach'], 'image/' . $photo['attachmime'],
336 $photo['x'], $photo['y']);
337 } else if ($fallback) {
338 return PlImage::fromFile(dirname(__FILE__).'/../htdocs/images/none.png',
339 'image/png');
340 }
341 return null;
342 }
9f21bd15 343 */
4bc5b8f0
FB
344 /* Addresses
345 */
346 public function getAddresses($flags, $limit = null)
f5642983
FB
347 {
348 $where = XDB::format('pa.pid = {?}', $this->id());
349 if ($flags & self::ADDRESS_MAIN) {
350 $where .= ' AND FIND_IN_SET(\'current\', pa.flags)';
351 }
352 if ($flags & self::ADDRESS_POSTAL) {
353 $where .= ' AND FIND_IN_SET(\'mail\', pa.flags)';
354 }
355 if ($this->visibility) {
9f21bd15 356 $where .= ' AND pa.pub IN ' . XDB::formatArray($this->visibility);
f5642983
FB
357 }
358 $type = array();
359 if ($flags & self::ADDRESS_PRO) {
360 $type[] = 'job';
361 }
362 if ($flags & self::ADDRESS_PERSO) {
363 $type[] = 'home';
364 }
365 if (count($type) > 0) {
9f21bd15 366 $where .= ' AND pa.type IN ' . XDB::formatArray($type);
f5642983 367 }
4bc5b8f0 368 $limit = is_null($limit) ? '' : XDB::format('LIMIT {?}', (int)$limit);
f5642983
FB
369 return XDB::iterator('SELECT pa.text, pa.postalCode, pa.type, pa.latitude, pa.longitude,
370 gl.name AS locality, gas.name AS subAdministrativeArea,
371 ga.name AS administrativeArea, gc.countryFR AS country,
6b83ce06 372 ppfix.display_tel AS fixed_tel, ppfax.display_tel AS fax_tel,
f5642983
FB
373 FIND_IN_SET(\'current\', pa.flags) AS current,
374 FIND_IN_SET(\'temporary\', pa.flags) AS temporary,
375 FIND_IN_SET(\'secondary\', pa.flags) AS secondary,
376 FIND_IN_SET(\'mail\', pa.flags) AS mail, pa.type
377 FROM profile_addresses AS pa
378 LEFT JOIN geoloc_localities AS gl ON (gl.id = pa.localityId)
379 LEFT JOIN geoloc_administrativeareas AS ga ON (ga.id = pa.administrativeAreaId)
380 LEFT JOIN geoloc_administrativeareas AS gas ON (gas.id = pa.subAdministrativeAreaId)
381 LEFT JOIN geoloc_countries AS gc ON (gc.iso_3166_1_a2 = pa.countryId)
ce0b2c6f
FB
382 LEFT JOIN profile_phones AS ppfix ON (ppfix.link_type = \'address\' AND ppfix.pid = pa.pid AND ppfix.link_id = pa.id AND ppfix.tel_type = \'fixed\')
383 LEFT JOIN profile_phones AS ppfax ON (ppfax.link_type = \'address\' AND ppfax.pid = pa.pid AND ppfax.link_id = pa.id AND ppfax.tel_type = \'fax\')
4bc5b8f0
FB
384 WHERE ' . $where . '
385 ORDER BY pa.id
386 ' . $limit);
f5642983
FB
387 }
388
389 public function getMainAddress()
390 {
391 $it = $this->getAddresses(self::ADDRESS_PERSO | self::ADDRESS_MAIN);
392 if ($it->total() == 0) {
393 return null;
394 } else {
395 return $it->next();
396 }
397 }
3e53a496 398
4bc5b8f0
FB
399
400 /* Educations
401 */
402 public function getEducations($flags, $limit = null)
403 {
ce0b2c6f 404 $where = XDB::format('pe.pid = {?}', $this->id());
4bc5b8f0
FB
405 if ($flags & self::EDUCATION_MAIN) {
406 $where .= ' AND FIND_IN_SET(\'primary\', pe.flags)';
407 } else if ($flags & self::EDUCATION_EXTRA) {
408 $where .= ' AND NOT FIND_IN_SET(\'primary\', pe.flags)';
409 } else if ($flags & self::EDUCATION_FINISHED) {
410 $where .= ' AND pe.grad_year <= YEAR(CURDATE())';
411 } else if ($flags & self::EDUCATION_CURRENT) {
412 $where .= ' AND pe.grad_year > YEAR(CURDATE())';
413 }
414 $limit = is_null($limit) ? '' : XDB::format('LIMIT {?}', (int)$limit);
415 return XDB::iterator('SELECT pe.entry_year, pe.grad_year, pe.program,
416 pee.name AS school, pee.abbreviation AS school_short, pee.url AS school_url, gc.countryFR AS country,
417 pede.degree, pede.abbreviation AS degree_short, pede.level AS degree_level, pefe.field,
418 FIND_IN_SET(\'primary\', pe.flags) AS prim
419 FROM profile_education AS pe
420 INNER JOIN profile_education_enum AS pee ON (pe.eduid = pee.id)
421 LEFT JOIN geoloc_countries AS gc ON (gc.iso_3166_1_a2 = pee.country)
422 INNER JOIN profile_education_degree_enum AS pede ON (pe.degreeid = pede.id)
423 LEFT JOIN profile_education_field_enum AS pefe ON (pe.fieldid = pefe.id)
424 WHERE ' . $where . '
425 ORDER BY NOT FIND_IN_SET(\'primary\', pe.flags), pe.entry_year, pe.id
426 ' . $limit);
427 }
428
429 public function getExtraEducations($limit = null)
430 {
431 return $this->getEducations(self::EDUCATION_EXTRA, $limit);
432 }
433
434
04a94b1d
FB
435 /** Networking
436 */
437
438 public function getNetworking($flags, $limit = null)
439 {
ce0b2c6f 440 $where = XDB::format('pn.pid = {?}', $this->id());
04a94b1d
FB
441 if ($flags & self::NETWORKING_WEB) {
442 $where .= ' AND pn.network_type = 0'; // XXX hardcoded reference to web site index
443 }
444 if ($this->visibility) {
9f21bd15 445 $where .= ' AND pn.pub IN ' . XDB::formatArray($this->visibility);
04a94b1d
FB
446 }
447 $limit = is_null($limit) ? '' : XDB::format('LIMIT {?}', (int)$limit);
448 return XDB::iterator('SELECT pne.name, pne.icon,
449 IF (LENGTH(pne.link) > 0, REPLACE(pne.link, \'%s\', pn.address),
450 pn.address) AS address
451 FROM profile_networking AS pn
452 INNER JOIN profile_networking_enum AS pne ON (pn.network_type = pne.network_type)
453 WHERE ' . $where . '
454 ORDER BY pn.network_type, pn.nwid
455 ' . $limit);
456 }
457
458 public function getWebSite()
459 {
460 $site = $this->getNetworking(self::NETWORKING_WEB, 1);
461 if ($site->total() != 1) {
462 return null;
463 }
464 $site = $site->next();
465 return $site['address'];
466 }
467
468
e718bd18
FB
469 /** Jobs
470 */
471
472 public function getJobs($flags, $limit = null)
473 {
ce0b2c6f 474 $where = XDB::format('pj.pid = {?}', $this->id());
e718bd18
FB
475 $cond = 'TRUE';
476 if ($this->visibility) {
9f21bd15
RB
477 $where .= ' AND pj.pub IN ' . XDB::formatArray($this->visibility);
478 $cond = 'pj.email_pub IN ' . XDB::formatArray($this->visibility);
e718bd18
FB
479 }
480 $limit = is_null($limit) ? '' : XDB::format('LIMIT {?}', (int)$limit);
481 return XDB::iterator('SELECT pje.name, pje.acronym, pje.url, pje.email, pje.NAF_code,
482 pj.description, pj.url AS user_site,
483 IF (' . $cond . ', pj.email, NULL) AS user_email,
83ff5281
SJ
484 pjse.name AS sector, pjsse.name AS subsector,
485 pjssse.name AS subsubsector
e718bd18
FB
486 FROM profile_job AS pj
487 INNER JOIN profile_job_enum AS pje ON (pje.id = pj.jobid)
e718bd18
FB
488 LEFT JOIN profile_job_sector_enum AS pjse ON (pjse.id = pj.sectorid)
489 LEFT JOIN profile_job_subsector_enum AS pjsse ON (pjsse.id = pj.subsectorid)
490 LEFT JOIN profile_job_subsubsector_enum AS pjssse ON (pjssse.id = pj.subsubsectorid)
491 WHERE ' . $where . '
492 ORDER BY pj.id
493 ' . $limit);
494 }
495
496 public function getMailJob()
497 {
498 $job = $this->getJobs(self::JOBS_MAIN, 1);
499 if ($job->total() != 1) {
500 return null;
501 }
502 return $job->next();
503 }
504
5c005b37
RB
505 /* Binets
506 */
507 public function getBinets()
508 {
509 return XDB::fetchColumn('SELECT binet_id
5c8a71f2 510 FROM profile_binets
bdd977d7 511 WHERE pid = {?}', $this->id());
5c005b37
RB
512 }
513
e718bd18 514
e7b93962
FB
515 public function owner()
516 {
517 return User::getSilent($this);
518 }
519
94590511
SJ
520 public function compareNames($firstname, $lastname)
521 {
522 $_lastname = mb_strtoupper($this->lastName());
523 $_firstname = mb_strtoupper($this->firstName());
524 $lastname = mb_strtoupper($lastname);
525 $firstname = mb_strtoupper($firstname);
526
527 $isOk = (mb_strtoupper($_firstname) == mb_strtoupper($firstname));
528 $tokens = preg_split("/[ \-']/", $lastname, -1, PREG_SPLIT_NO_EMPTY);
529 $maxlen = 0;
530
531 foreach ($tokens as $str) {
532 $isOk &= (strpos($_lastname, $str) !== false);
533 $maxlen = max($maxlen, strlen($str));
534 }
535
536 return ($isOk && ($maxlen > 2 || $maxlen == strlen($_lastname)));
537 }
538
9f21bd15 539 private static function fetchProfileData(array $pids, $respect_order = true, $fields = 0x0000, $visibility = null)
b774ddab
FB
540 {
541 if (count($pids) == 0) {
542 return array();
543 }
0d906109
RB
544
545 if ($respect_order) {
546 $order = 'ORDER BY ' . XDB::formatCustomOrder('p.pid', $pids);
547 } else {
548 $order = '';
549 }
550
9f21bd15
RB
551
552 $it = XDB::Iterator('SELECT p.*, p.sex = \'female\' AS sex, pe.entry_year, pe.grad_year,
553 pn_f.name AS firstname, pn_l.name AS lastname, pn_n.name AS nickname,
554 IF(pn_uf.name IS NULL, pn_f.name, pn_uf.name) AS firstname_ordinary,
555 IF(pn_ul.name IS NULL, pn_l.name, pn_ul.name) AS lastname_ordinary,
556 pd.promo AS promo, pd.short_name, pd.directory_name AS full_name,
557 pd.directory_name, pp.display_tel AS mobile, pp.pub AS mobile_pub,
558 ph.attach IS NOT NULL AS has_photo, ph.pub AS photo_pub,
559 p.last_change < DATE_SUB(NOW(), INTERVAL 365 DAY) AS is_old,
560 ap.uid AS owner_id
561 FROM profiles AS p
562 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
563 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
564 INNER JOIN profile_name AS pn_f ON (pn_f.pid = p.pid
565 AND pn_f.typeid = ' . self::getNameTypeId('firstname', true) . ')
566 INNER JOIN profile_name AS pn_l ON (pn_l.pid = p.pid
567 AND pn_l.typeid = ' . self::getNameTypeId('lastname', true) . ')
568 LEFT JOIN profile_name AS pn_uf ON (pn_uf.pid = p.pid
569 AND pn_uf.typeid = ' . self::getNameTypeId('firstname_ordinary', true) . ')
570 LEFT JOIN profile_name AS pn_ul ON (pn_ul.pid = p.pid
571 AND pn_ul.typeid = ' . self::getNameTypeId('lastname_ordinary', true) . ')
572 LEFT JOIN profile_name AS pn_n ON (pn_n.pid = p.pid
573 AND pn_n.typeid = ' . self::getNameTypeId('nickname', true) . ')
574 LEFT JOIN profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = \'user\' AND tel_type = \'mobile\')
575 LEFT JOIN profile_photos AS ph ON (ph.pid = p.pid)
576 LEFT JOIN account_profiles AS ap ON (ap.pid = p.pid AND FIND_IN_SET(\'owner\', ap.perms))
577 WHERE p.pid IN ' . XDB::formatArray($pids) . '
578 GROUP BY p.pid
579 ' . $order);
580 return new ProfileDataIterator($it, $pids, $fields, $visibility);
b774ddab
FB
581 }
582
583 public static function getPID($login)
584 {
585 if ($login instanceof PlUser) {
586 return XDB::fetchOneCell('SELECT pid
587 FROM account_profiles
588 WHERE uid = {?} AND FIND_IN_SET(\'owner\', perms)',
589 $login->id());
9f21bd15 590 } else if (ctype_digit($login)) {
b774ddab
FB
591 return XDB::fetchOneCell('SELECT pid
592 FROM profiles
593 WHERE pid = {?}', $login);
594 } else {
595 return XDB::fetchOneCell('SELECT pid
596 FROM profiles
597 WHERE hrpid = {?}', $login);
598 }
599 }
600
0d906109
RB
601 public static function getPIDsFromUIDs($uids, $respect_order = true)
602 {
603 if ($respect_order) {
604 $order = 'ORDER BY ' . XDB::formatCustomOrder('uid', $uids);
605 } else {
606 $order = '';
607 }
608 return XDB::fetchAllAssoc('uid', 'SELECT ap.uid, ap.pid
609 FROM account_profiles AS ap
610 WHERE FIND_IN_SET(\'owner\', ap.perms)
9f21bd15
RB
611 AND ap.uid IN ' . XDB::formatArray($uids) .'
612 ' . $order);
0d906109 613 }
b774ddab 614
e7b93962
FB
615 /** Return the profile associated with the given login.
616 */
9f21bd15 617 public static function get($login, $fields = 0x0000, $visibility = null)
a3118782 618 {
641f2115
FB
619 if (is_array($login)) {
620 return new Profile($login);
621 }
b774ddab
FB
622 $pid = self::getPID($login);
623 if (!is_null($pid)) {
9f21bd15 624 $it = self::iterOverPIDs(array($pid), false, $fields, $visibility);
0d906109 625 return $it->next();
b774ddab 626 } else {
efe597c5
FB
627 /* Let say we can identify a profile using the identifiers of its owner.
628 */
455ea0c9
FB
629 if (!($login instanceof PlUser)) {
630 $user = User::getSilent($login);
631 if ($user && $user->hasProfile()) {
632 return $user->profile();
633 }
efe597c5 634 }
3e53a496 635 return null;
e7b93962
FB
636 }
637 }
a3118782 638
9f21bd15 639 public static function iterOverUIDs($uids, $respect_order = true, $fields = 0x0000, $visibility = null)
0d906109 640 {
9f21bd15 641 return self::iterOverPIDs(self::getPIDsFromUIDs($uids), $respect_order, $fields, $visibility);
0d906109
RB
642 }
643
9f21bd15 644 public static function iterOverPIDs($pids, $respect_order = true, $fields = 0x0000, $visibility = null)
0d906109 645 {
9f21bd15 646 return self::fetchProfileData($pids, $respect_order, $fields, $visibility);
0d906109
RB
647 }
648
b774ddab
FB
649 /** Return profiles for the list of pids.
650 */
9f21bd15 651 public static function getBulkProfilesWithPIDs(array $pids, $fields = 0x0000, $visibility = null)
b774ddab
FB
652 {
653 if (count($pids) == 0) {
654 return array();
655 }
9f21bd15 656 $it = self::iterOverPIDs($pids, true, $fields, $visibility);
b774ddab 657 $profiles = array();
0d906109
RB
658 while ($p = $it->next()) {
659 $profiles[$p->id()] = $p;
b774ddab
FB
660 }
661 return $profiles;
662 }
663
664 /** Return profiles for uids.
665 */
9f21bd15 666 public static function getBulkProfilesWithUIDS(array $uids, $fields = 0x000, $visibility = null)
b774ddab
FB
667 {
668 if (count($uids) == 0) {
669 return array();
670 }
9f21bd15 671 return self::getBulkProfilesWithPIDs(self::getPIDsFromUIDs($uids), $fields, $visibility);
b774ddab
FB
672 }
673
913a4e90
RB
674 public static function isDisplayName($name)
675 {
676 return $name == self::DN_FULL || $name == self::DN_DISPLAY
677 || $name == self::DN_YOURSELF || $name == self::DN_DIRECTORY
678 || $name == self::DN_PRIVATE || $name == self::DN_PUBLIC
679 || $name == self::DN_SHORT || $name == self::DN_SORT;
680 }
681
9f21bd15
RB
682 public static function getNameTypeId($type, $for_sql = false)
683 {
684 if (!S::has('name_types')) {
685 $table = XDB::fetchAllAssoc('type', 'SELECT id, type
686 FROM profile_name_enum');
687 S::set('name_types', $table);
688 } else {
689 $table = S::v('name_types');
690 }
691 if ($for_sql) {
692 return XDB::escape($table[$type]);
693 } else {
694 return $table[$type];
695 }
696 }
697
726eaf7a
SJ
698 public static function rebuildSearchTokens($pid)
699 {
700 XDB::execute('DELETE FROM search_name
6dbb167e 701 WHERE pid = {?}',
726eaf7a
SJ
702 $pid);
703 $keys = XDB::iterator("SELECT CONCAT(n.particle, n.name) AS name, e.score,
704 FIND_IN_SET('public', e.flags) AS public
705 FROM profile_name AS n
706 INNER JOIN profile_name_enum AS e ON (n.typeid = e.id)
707 WHERE n.pid = {?}",
708 $pid);
709
710 foreach ($keys as $i => $key) {
711 if ($key['name'] == '') {
712 continue;
713 }
714 $toks = preg_split('/[ \'\-]+/', $key['name']);
715 $token = '';
716 $first = 5;
717 while ($toks) {
718 $token = strtolower(replace_accent(array_pop($toks) . $token));
719 $score = ($toks ? 0 : 10 + $first) * ($key['score'] / 10);
6dbb167e 720 XDB::execute('REPLACE INTO search_name (token, pid, soundex, score, flags)
726eaf7a 721 VALUES ({?}, {?}, {?}, {?}, {?})',
6dbb167e 722 $token, $pid, soundex_fr($token), $score, $key['public']);
726eaf7a
SJ
723 $first = 0;
724 }
725 }
69b46857
SJ
726 }
727
728 /** The school identifier consists of 6 digits. The first 3 represent the
729 * promotion entry year. The last 3 indicate the student's rank.
730 *
731 * Our identifier consists of 8 digits and both half have the same role.
732 * This enables us to deal with bigger promotions and with a wider range
733 * of promotions.
734 *
735 * getSchoolId returns a school identifier given one of ours.
736 * getXorgId returns a X.org identifier given a school identifier.
737 */
738 public static function getSchoolId($xorgId)
739 {
740 if (!preg_match('/^[0-9]{8}$/', $xorgId)) {
741 return null;
742 }
743
744 $year = intval(substr($xorgId, 0, 4));
745 $rank = intval(substr($xorgId, 5, 3));
746 if ($year < 1996) {
747 return null;
748 } elseif ($year < 2000) {
749 $year = intval(substr(1900 - $year, 1, 3));
750 return sprintf('%02u0%03u', $year, $rank);
751 } else {
752 $year = intval(substr(1900 - $year, 1, 3));
753 return sprintf('%03u%03u', $year, $rank);
754 }
755 }
726eaf7a 756
69b46857
SJ
757 public static function getXorgId($schoolId)
758 {
94590511 759 if (!preg_match('/^[0-9]{6}$/', $schoolId)) {
a292484d
SJ
760 return null;
761 }
762
69b46857
SJ
763 $year = intval(substr($schoolId, 0, 3));
764 $rank = intval(substr($schoolId, 3, 3));
726eaf7a 765
69b46857
SJ
766 if ($year > 200) {
767 $year /= 10;
768 }
769 if ($year < 96) {
770 return null;
771 } else {
772 return sprintf('%04u%04u', 1900 + $year, $rank);
773 }
726eaf7a 774 }
e7b93962
FB
775}
776
9f21bd15
RB
777class ProfileDataIterator
778{
779 private $iterator = null;
780 private $fields;
781
782 public function __construct(PlIterator $it, array $pids, $fields = 0x0000, $visibility = null)
783 {
784 require_once 'profilefields.inc.php';
785 $visibility = Profile::getVisibilityContext($visibility);
786 $this->fields = $fields;
787
788 $subits = array();
789 $callbacks = array();
790
791 $subits[0] = $it;
792 $callbacks[0] = PlIteratorUtils::arrayValueCallback('pid');
793 $cb = PlIteratorUtils::objectPropertyCallback('pid');
794
795 if ($fields & Profile::FETCH_ADDRESSES) {
796 $callbacks[Profile::FETCH_ADDRESSES] = $cb;
797 $subits[Profile::FETCH_ADDRESSES] = new ProfileFieldIterator('ProfileAddresses', $pids, $visibility);
798 }
799
800 if ($fields & Profile::FETCH_CORPS) {
801 $callbacks[Profile::FETCH_CORPS] = $cb;
802 $subits[Profile::FETCH_CORPS] = new ProfileFieldIterator('ProfileCorps', $pids, $visibility);
803 }
804
805 if ($fields & Profile::FETCH_EDU) {
806 $callbacks[Profile::FETCH_EDU] = $cb;
807 $subits[Profile::FETCH_EDU] = new ProfileFieldIterator('ProfileEducation', $pids, $visibility);
808 }
809
810 if ($fields & Profile::FETCH_JOBS) {
811 $callbacks[Profile::FETCH_JOBS] = $cb;
812 $subits[Profile::FETCH_JOBS] = new ProfileFieldIterator('ProfileJobs', $pids, $visibility);
813 }
814
815 if ($fields & Profile::FETCH_MEDALS) {
816 $callbacks[Profile::FETCH_MEDALS] = $cb;
817 $subits[Profile::FETCH_MEDALS] = new ProfileFieldIterator('ProfileMedals', $pids, $visibility);
818 }
819
820 if ($fields & Profile::FETCH_NETWORKING) {
821 $callbacks[Profile::FETCH_NETWORKING] = $cb;
822 $subits[Profile::FETCH_NETWORKING] = new ProfileFieldIterator('ProfileNetworking', $pids, $visibility);
823 }
824
825 if ($fields & Profile::FETCH_PHONES) {
826 $callbacks[Profile::FETCH_PHONES] = $cb;
827 $subits[Profile::FETCH_PHONES] = new ProfileFieldIterator('ProfilePhones', $pids, $visibility);
828 }
829
830 if ($fields & Profile::FETCH_PHOTO) {
831 $callbacks[Profile::FETCH_PHOTO] = $cb;
832 $subits[Profile::FETCH_PHOTO] = new ProfileFieldIterator('ProfilePhoto', $pids, $visibility);
833 }
834
835 $this->iterator = PlIteratorUtils::parallelIterator($subits, $callbacks, 0);
836 }
837
838 private function consolidateFields(array $pf)
839 {
840 if ($this->fields & Profile::FETCH_PHONES) {
841 $phones = $pf[Profile::FETCH_PHONES];
842
843 if ($this->fields & Profile::FETCH_ADDRESSES) {
844 $pf[Profile::FETCH_ADDRESSES]->addPhones($phones);
845 }
846 if ($this->fields & Profile::FETCH_JOBS) {
847 $pf[Profile::FETCH_JOBS]->addPhones($phones);
848 }
849 }
850
851 if ($this->fields & Profile::FETCH_ADDRESSES) {
852 $addrs = $pf[Profile::FETCH_ADDRESSES];
853 if ($this->fields & Profile::FETCH_JOBS) {
854 $pf[Profile::FETCH_JOBS]->addAddresses($addrs);
855 }
856 }
857
858 return $pf;
859 }
860
861 private function fillProfile(array $vals)
862 {
863 $vals = $this->consolidateFields($vals);
864
865 $pf = Profile::get($vals[0]);
866 if ($this->fields & Profile::FETCH_ADDRESSES) {
867 $pf->setAddresses($vals[Profile::FETCH_ADDRESSES]);
868 }
869 if ($this->fields & Profile::FETCH_CORPS) {
870 $pf->setCorps($vals[Profile::FETCH_CORPS]);
871 }
872 if ($this->fields & Profile::FETCH_EDU) {
873 $pf->setEdu($vals[Profile::FETCH_EDU]);
874 }
875 if ($this->fields & Profile::FETCH_JOBS) {
876 $pf->setJobs($vals[Profile::FETCH_JOBS]);
877 }
878 if ($this->fields & Profile::FETCH_MEDALS) {
879 $pf->setMedals($vals[Profile::FETCH_MEDALS]);
880 }
881 if ($this->fields & Profile::FETCH_NETWORKING) {
882 $pf->setNetworking($vals[Profile::FETCH_NETWORKING]);
883 }
884 if ($this->fields & Profile::FETCH_PHONES) {
885 $pf->setPhones($vals[Profile::FETCH_PHONES]);
886 }
887 if ($this->fields & Profile::FETCH_PHOTO) {
888 if ($vals[Profile::FETCH_PHOTO] != null) {
889 $pf->setPhoto($vals[Profile::FETCH_PHOTO]);
890 }
891 }
892
893 return $pf;
894 }
895
896 public function next()
897 {
898 $vals = $this->iterator->next();
899 if ($vals == null) {
900 return null;
901 }
902 return $this->fillProfile($vals);
903 }
904
905 public function first()
906 {
907 return $this->iterator->first();
908 }
909
910 public function last()
911 {
912 return $this->iterator->last();
913 }
914
915 public function total()
916 {
917 return $this->iterator->total();
918 }
919}
920
0d906109
RB
921/** Iterator over a set of Profiles
922 * @param an XDB::Iterator obtained from a Profile::fetchProfileData
923 */
924class ProfileIterator implements PlIterator
925{
9f21bd15 926 private $pdi;
0d906109
RB
927 private $dbiter;
928
9f21bd15 929 public function __construct(ProfileDataIterator &$pdi)
0d906109 930 {
9f21bd15
RB
931 $this->pdi = $pdi;
932 $this->dbiter = $pdi->iterator();
0d906109
RB
933 }
934
935 public function next()
936 {
937 $data = $this->dbiter->next();
938 if ($data == null) {
939 return null;
940 } else {
9f21bd15 941 return $this->pdi->fillProfile(Profile::get($data));
0d906109
RB
942 }
943 }
944
945 public function total()
946 {
947 return $this->dbiter->total();
948 }
949
950 public function first()
951 {
952 return $this->dbiter->first();
953 }
954
955 public function last()
956 {
957 return $this->dbiter->last();
958 }
959}
960
e7b93962
FB
961// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
962?>