5ad9c545013287479a992b6da4f3360e95bd81a6
[platal.git] / classes / profile.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 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 class ProfileVisibility
23 {
24 static private $v_values = array(self::VIS_PUBLIC => array(self::VIS_PUBLIC),
25 self::VIS_AX => array(self::VIS_AX, self::VIS_PUBLIC),
26 self::VIS_PRIVATE => array(self::VIS_PRIVATE, self::VIS_AX, self::VIS_PUBLIC));
27
28 const VIS_PUBLIC = 'public';
29 const VIS_AX = 'ax';
30 const VIS_PRIVATE = 'private';
31
32 private $level;
33
34 public function __construct($level = null)
35 {
36 $this->setLevel($level);
37 }
38
39 public function setLevel($level = self::VIS_PUBLIC)
40 {
41 if ($level != null && $level != self::VIS_PRIVATE && $level != self::VIS_AX && $level != self::VIS_PUBLIC) {
42 Platal::page()->kill("Invalid visibility: " . $level);
43 }
44
45 if (!S::logged()) {
46 $level = self::VIS_PUBLIC;
47 } else if ($level == null) {
48 $level = self::VIS_PRIVATE;
49 }
50
51 if ($this->level == null || $this->level == self::VIS_PRIVATE) {
52 $this->level = $level;
53 } else if ($this->level == self::VIS_AX && $level == self::VIS_PRIVATE) {
54 return;
55 } else {
56 $this->level = self::VIS_PUBLIC;
57 }
58 }
59
60 public function level()
61 {
62 if ($this->level == null) {
63 return self::VIS_PUBLIC;
64 } else {
65 return $this->level;
66 }
67 }
68
69 public function levels()
70 {
71 return self::$v_values[$this->level()];
72 }
73
74 public function isVisible($visibility)
75 {
76 return in_array($visibility, $this->levels());
77 }
78 }
79
80 class Profile
81 {
82
83 /* name tokens */
84 const LASTNAME = 'lastname';
85 const FIRSTNAME = 'firstname';
86 const NICKNAME = 'nickname';
87 const PSEUDONYM = 'pseudonym';
88 const NAME = 'name';
89 /* name variants */
90 const VN_MARITAL = 'marital';
91 const VN_ORDINARY = 'ordinary';
92 const VN_OTHER = 'other';
93 const VN_INI = 'ini';
94 /* display names */
95 const DN_FULL = 'directory_name';
96 const DN_DISPLAY = 'yourself';
97 const DN_YOURSELF = 'yourself';
98 const DN_DIRECTORY = 'directory_name';
99 const DN_PRIVATE = 'private_name';
100 const DN_PUBLIC = 'public_name';
101 const DN_SHORT = 'short_name';
102 const DN_SORT = 'sort_name';
103 /* education related names */
104 const EDU_X = 'École polytechnique';
105 const DEGREE_X = 'Ingénieur';
106 const DEGREE_M = 'Master';
107 const DEGREE_D = 'Doctorat';
108
109 static public $name_variants = array(
110 self::LASTNAME => array(self::VN_MARITAL, self::VN_ORDINARY),
111 self::FIRSTNAME => array(self::VN_ORDINARY, self::VN_INI, self::VN_OTHER)
112 );
113
114 const ADDRESS_MAIN = 0x000001;
115 const ADDRESS_PERSO = 0x000002;
116 const ADDRESS_PRO = 0x000004;
117 const ADDRESS_ALL = 0x000006;
118 const ADDRESS_POSTAL = 0x000008;
119
120 const EDUCATION_MAIN = 0x000010;
121 const EDUCATION_EXTRA = 0x000020;
122 const EDUCATION_ALL = 0x000040;
123 const EDUCATION_FINISHED = 0x000080;
124 const EDUCATION_CURRENT = 0x000100;
125
126 const JOBS_MAIN = 0x001000;
127 const JOBS_ALL = 0x002000;
128 const JOBS_FINISHED = 0x004000;
129 const JOBS_CURRENT = 0x008000;
130
131 const NETWORKING_ALL = 0x000000;
132 const NETWORKING_WEB = 0x010000;
133 const NETWORKING_IM = 0x020000;
134 const NETWORKING_SOCIAL = 0x040000;
135
136 const FETCH_ADDRESSES = 0x000001;
137 const FETCH_CORPS = 0x000002;
138 const FETCH_EDU = 0x000004;
139 const FETCH_JOBS = 0x000008;
140 const FETCH_MEDALS = 0x000010;
141 const FETCH_NETWORKING = 0x000020;
142 const FETCH_MENTOR_SECTOR = 0x000040;
143 const FETCH_MENTOR_COUNTRY = 0x000080;
144 const FETCH_PHONES = 0x000100;
145
146 const FETCH_MINIFICHES = 0x00012D; // FETCH_ADDRESSES | FETCH_EDU | FETCH_JOBS | FETCH_NETWORKING | FETCH_PHONES
147
148 const FETCH_ALL = 0x0001FF; // OR of FETCH_*
149
150 private $fetched_fields = 0x000000;
151
152 private $pid;
153 private $hrpid;
154 private $owner;
155 private $owner_fetched = false;
156 private $data = array();
157
158 private $visibility = null;
159
160
161 private function __construct(array $data)
162 {
163 $this->data = $data;
164 $this->pid = $this->data['pid'];
165 $this->hrpid = $this->data['hrpid'];
166 $this->visibility = new ProfileVisibility();
167 }
168
169 public function id()
170 {
171 return $this->pid;
172 }
173
174 public function hrid()
175 {
176 return $this->hrpid;
177 }
178
179 public function owner()
180 {
181 if ($this->owner == null && !$this->owner_fetched) {
182 $this->owner_fetched = true;
183 $this->owner = User::getSilent($this);
184 }
185 return $this->owner;
186 }
187
188 public function promo()
189 {
190 return $this->promo;
191 }
192
193 public function yearpromo()
194 {
195 return intval(substr($this->promo, 1, 4));
196 }
197
198 public function mainEducation()
199 {
200 if (empty($this->promo)) {
201 return null;
202 } else {
203 return $this->promo{0};
204 }
205 }
206
207 public function mainEducationDuration()
208 {
209 switch ($this->mainEducation()) {
210 case 'X':
211 return 3;
212 case 'M':
213 return 2;
214 case 'D':
215 return 3;
216 default:
217 return 0;
218 }
219 }
220
221 /** Print a name with the given formatting:
222 * %s = • for women
223 * %f = firstname
224 * %l = lastname
225 * %F = fullname
226 * %S = shortname
227 * %p = promo
228 */
229 public function name($format)
230 {
231 return str_replace(array('%s', '%f', '%l', '%F', '%S', '%p'),
232 array($this->isFemale() ? '•' : '',
233 $this->firstName(), $this->lastName(),
234 $this->fullName(), $this->shortName(),
235 $this->promo()), $format);
236 }
237
238 public function fullName($with_promo = false)
239 {
240 if ($with_promo) {
241 return $this->full_name . ' (' . $this->promo . ')';
242 }
243 return $this->full_name;
244 }
245
246 public function shortName($with_promo = false)
247 {
248 if ($with_promo) {
249 return $this->short_name . ' (' . $this->promo . ')';
250 }
251 return $this->short_name;
252 }
253
254 public function firstName()
255 {
256 return $this->firstname;
257 }
258
259 public function firstNames()
260 {
261 return $this->nameVariants(self::FIRSTNAME);
262 }
263
264 public function lastName()
265 {
266 return $this->lastname;
267 }
268
269 public function lastNames()
270 {
271 return $this->nameVariants(self::LASTNAME);
272 }
273
274 public function isFemale()
275 {
276 return $this->sex == PlUser::GENDER_FEMALE;
277 }
278
279 public function isDead()
280 {
281 return ($this->deathdate != null);
282 }
283
284 public function displayEmail()
285 {
286 $o = $this->owner();
287 if ($o != null) {
288 return $o->bestEmail();
289 } else {
290 return $this->email_directory;
291 }
292 }
293
294 public function data()
295 {
296 $this->first_name;
297 return $this->data;
298 }
299
300 private function nameVariants($type)
301 {
302 $vals = array($this->$type);
303 foreach (self::$name_variants[$type] as $var) {
304 $vartype = $type . '_' . $var;
305 $varname = $this->$vartype;
306 if ($varname != null && $varname != "") {
307 $vals[] = $varname;
308 }
309 }
310 return array_unique($vals);
311 }
312
313 public function nationalities()
314 {
315 $nats = array();
316 if ($this->nationality1) {
317 $nats[] = $this->nationality1;
318 }
319 if ($this->nationality2) {
320 $nats[] = $this->nationality2;
321 }
322 if ($this->nationality3) {
323 $nats[] = $this->nationality3;
324 }
325 return $nats;
326 }
327
328 public function __get($name)
329 {
330 if (property_exists($this, $name)) {
331 return $this->$name;
332 }
333
334 if (isset($this->data[$name])) {
335 return $this->data[$name];
336 }
337
338 return null;
339 }
340
341 public function __isset($name)
342 {
343 return property_exists($this, $name) || isset($this->data[$name]);
344 }
345
346 /** Sets the level of visibility of the profile
347 * Sets $this->visibility to a list of valid visibilities.
348 * @param one of the self::VIS_* values
349 */
350 public function setVisibilityLevel($visibility)
351 {
352 $this->visibility->setLevel($visibility);
353 }
354
355 /** Determine whether an item with visibility $visibility can be displayed
356 * with the current level of visibility of the profile
357 * @param $visibility The level of visibility to be checked
358 */
359 public function isVisible($visibility)
360 {
361 return $this->visibility->isVisible($visibility);
362 }
363
364 /** Stores the list of fields which have already been fetched for this Profile
365 */
366 public function setFetchedFields($fields)
367 {
368 if (($fields | self::FETCH_ALL) != self::FETCH_ALL) {
369 Platal::page()->kill("Invalid fetched fields: $fields");
370 }
371
372 $this->fetched_fields = $fields;
373 }
374
375 private function fetched($field)
376 {
377 if (!array_key_exists($field, ProfileField::$fields)) {
378 Platal::page()->kill("Invalid field: $field");
379 }
380
381 return ($this->fetched_fields & $field);
382 }
383
384 /** If not already done, fetches data for the given field
385 * @param $field One of the Profile::FETCH_*
386 * @return A ProfileField, or null
387 */
388 private function getProfileField($field)
389 {
390 if ($this->fetched($field)) {
391 return null;
392 } else {
393 $this->fetched_fields = $this->fetched_fields | $field;
394 }
395
396 $cls = ProfileField::$fields[$field];
397
398 return ProfileField::getForPID($cls, $this->id(), $this->visibility);
399 }
400
401 /** Consolidates internal data (addresses, phones, jobs)
402 */
403 private function consolidateFields()
404 {
405 if ($this->phones != null) {
406 if ($this->addresses != null) {
407 $this->addresses->addPhones($this->phones);
408 }
409
410 if ($this->jobs != null) {
411 $this->jobs->addPhones($this->phones);
412 }
413 }
414
415 if ($this->addresses != null && $this->jobs != null) {
416 $this->jobs->addAddresses($this->addresses);
417 }
418 }
419
420 /* Photo
421 */
422 private $photo = null;
423 public function getPhoto($fallback = true, $data = false)
424 {
425 if ($this->has_photo) {
426 if ($data && ($this->photo == null || $this->photo->mimeType == null)) {
427 $res = XDB::fetchOneAssoc('SELECT attach, attachmime, x, y
428 FROM profile_photos
429 WHERE pid = {?}', $this->pid);
430 $this->photo = PlImage::fromData($res['attach'], $res['attachmime'], $res['x'], $res['y']);
431 } else if ($this->photo == null) {
432 $this->photo = PlImage::fromData(null, null, $this->photo_width, $this->photo_height);
433 }
434 return $this->photo;
435 } else if ($fallback) {
436 return PlImage::fromFile(dirname(__FILE__).'/../htdocs/images/none.png',
437 'image/png');
438 }
439 return null;
440 }
441
442 /* Addresses
443 */
444 private $addresses = null;
445 public function setAddresses(ProfileAddresses $addr)
446 {
447 $this->addresses = $addr;
448 $this->consolidateFields();
449 }
450
451 public function getAddresses($flags, $limit = null)
452 {
453 if ($this->addresses == null && !$this->fetched(self::FETCH_ADDRESSES)) {
454 $this->setAddresses($this->getProfileField(self::FETCH_ADDRESSES));
455 }
456
457 if ($this->addresses == null) {
458 return array();
459 }
460 return $this->addresses->get($flags, $limit);
461 }
462
463 public function iterAddresses($flags, $limit = null)
464 {
465 return PlIteratorUtils::fromArray($this->getAddresses($flags, $limit), 1, true);
466 }
467
468 public function getMainAddress()
469 {
470 $addr = $this->getAddresses(self::ADDRESS_PERSO | self::ADDRESS_MAIN);
471 if (count($addr) == 0) {
472 return null;
473 } else {
474 return array_pop($addr);
475 }
476 }
477
478 /* Phones
479 */
480 private $phones = null;
481 public function setPhones(ProfilePhones $phones)
482 {
483 $this->phones = $phones;
484 $this->consolidateFields();
485 }
486
487 public function getPhones($flags, $limit = null)
488 {
489 if ($this->phones == null && !$this->fetched(self::FETCH_PHONES)) {
490 $this->setPhones($this->getProfileField(self::FETCH_PHONES));
491 }
492
493 if ($this->phones == null) {
494 return array();
495 }
496 return $this->phones->get($flags, $limit);
497 }
498
499 /* Educations
500 */
501 private $educations = null;
502 public function setEducations(ProfileEducation $edu)
503 {
504 $this->educations = $edu;
505 }
506
507 public function getEducations($flags, $limit = null)
508 {
509 if ($this->educations == null && !$this->fetched(self::FETCH_EDU)) {
510 $this->setEducations($this->getProfileField(self::FETCH_EDU));
511 }
512
513 if ($this->educations == null) {
514 return array();
515 }
516 return $this->educations->get($flags, $limit);
517 }
518
519 public function getExtraEducations($limit = null)
520 {
521 return $this->getEducations(self::EDUCATION_EXTRA, $limit);
522 }
523
524 /* Corps
525 */
526 private $corps = null;
527 public function setCorps(ProfileCorps $corps)
528 {
529 $this->corps = $corps;
530 }
531
532 public function getCorps()
533 {
534 if ($this->corps == null && !$this->fetched(self::FETCH_CORPS)) {
535 $this->setCorps($this->getProfileField(self::FETCH_CORPS));
536 }
537 return $this->corps;
538 }
539
540 /** Networking
541 */
542 private $networks = null;
543 public function setNetworking(ProfileNetworking $nw)
544 {
545 $this->networks = $nw;
546 }
547
548 public function getNetworking($flags, $limit = null)
549 {
550 if ($this->networks == null && !$this->fetched(self::FETCH_NETWORKING)) {
551 $this->setNetworking($this->getProfileField(self::FETCH_NETWORKING));
552 }
553 if ($this->networks == null) {
554 return array();
555 }
556 return $this->networks->get($flags, $limit);
557 }
558
559 public function getWebSite()
560 {
561 $site = $this->getNetworking(self::NETWORKING_WEB, 1);
562 if (count($site) != 1) {
563 return null;
564 }
565 $site = array_pop($site);
566 return $site['address'];
567 }
568
569
570 /** Jobs
571 */
572 private $jobs = null;
573 public function setJobs(ProfileJobs $jobs)
574 {
575 $this->jobs = $jobs;
576 $this->consolidateFields();
577 }
578
579 public function getJobs($flags, $limit = null)
580 {
581 if ($this->jobs == null && !$this->fetched(self::FETCH_JOBS)) {
582 $this->setJobs($this->getProfileField(self::FETCH_JOBS));
583 }
584
585 if ($this->jobs == null) {
586 return array();
587 }
588 return $this->jobs->get($flags, $limit);
589 }
590
591 public function getMainJob()
592 {
593 $job = $this->getJobs(self::JOBS_MAIN, 1);
594 if (count($job) != 1) {
595 return null;
596 }
597 return array_pop($job);
598 }
599
600 /* Mentoring
601 */
602 private $mentor_sectors = null;
603 public function setMentoringSectors(ProfileMentoringSectors $sectors)
604 {
605 $this->mentor_sectors = $sectors;
606 }
607
608 public function getMentoringSectors()
609 {
610 if ($this->mentor_sectors == null && !$this->fetched(self::FETCH_MENTOR_SECTOR)) {
611 $this->setMentoringSectors($this->getProfileField(self::FETCH_MENTOR_SECTOR));
612 }
613
614 if ($this->mentor_sectors == null) {
615 return array();
616 } else {
617 return $this->mentor_sectors->sectors;
618 }
619 }
620
621 private $mentor_countries = null;
622 public function setMentoringCountries(ProfileMentoringCountries $countries)
623 {
624 $this->mentor_countries = $countries;
625 }
626
627 public function getMentoringCountries()
628 {
629 if ($this->mentor_countries == null && !$this->fetched(self::FETCH_MENTOR_COUNTRY)) {
630 $this->setMentoringCountries($this->getProfileField(self::FETCH_MENTOR_COUNTRY));
631 }
632
633 if ($this->mentor_countries == null) {
634 return array();
635 } else {
636 return $this->mentor_countries->countries;
637 }
638 }
639
640 /* Binets
641 */
642 public function getBinets()
643 {
644 if ($this->visibility->isVisible(ProfileVisibility::VIS_PRIVATE)) {
645 return XDB::fetchColumn('SELECT binet_id
646 FROM profile_binets
647 WHERE pid = {?}', $this->id());
648 } else {
649 return array();
650 }
651 }
652 public function getBinetsNames()
653 {
654 if ($this->visibility->isVisible(ProfileVisibility::VIS_PRIVATE)) {
655 return XDB::fetchColumn('SELECT text
656 FROM profile_binets AS pb
657 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
658 WHERE pb.pid = {?}', $this->id());
659 } else {
660 return array();
661 }
662 }
663
664 /* Medals
665 */
666 private $medals = null;
667 public function setMedals(ProfileMedals $medals)
668 {
669 $this->medals = $medals;
670 }
671
672 public function getMedals()
673 {
674 if ($this->medals == null && !$this->fetched(self::FETCH_MEDALS)) {
675 $this->setMedals($this->getProfileField(self::FETCH_MEDALS));
676 }
677 if ($this->medals == null) {
678 return array();
679 }
680 return $this->medals->medals;
681 }
682
683 public function compareNames($firstname, $lastname)
684 {
685 $_lastname = mb_strtoupper($this->lastName());
686 $_firstname = mb_strtoupper($this->firstName());
687 $lastname = mb_strtoupper($lastname);
688 $firstname = mb_strtoupper($firstname);
689
690 $isOk = (mb_strtoupper($_firstname) == mb_strtoupper($firstname));
691 $tokens = preg_split("/[ \-']/", $lastname, -1, PREG_SPLIT_NO_EMPTY);
692 $maxlen = 0;
693
694 foreach ($tokens as $str) {
695 $isOk &= (strpos($_lastname, $str) !== false);
696 $maxlen = max($maxlen, strlen($str));
697 }
698
699 return ($isOk && ($maxlen > 2 || $maxlen == strlen($_lastname)));
700 }
701
702 private static function fetchProfileData(array $pids, $respect_order = true, $fields = 0x0000, $visibility = null)
703 {
704 if (count($pids) == 0) {
705 return array();
706 }
707
708 if ($respect_order) {
709 $order = 'ORDER BY ' . XDB::formatCustomOrder('p.pid', $pids);
710 } else {
711 $order = '';
712 }
713
714 $visibility = new ProfileVisibility($visibility);
715
716 $it = XDB::Iterator('SELECT p.pid, p.hrpid, p.xorg_id, p.ax_id, p.birthdate, p.birthdate_ref,
717 p.next_birthday, p.deathdate, p.deathdate_rec, p.sex = \'female\' AS sex,
718 p.cv, p.medals_pub, p.alias_pub, p.email_directory, p.last_change,
719 p.nationality1, p.nationality2, p.nationality3,
720 IF (p.freetext_pub IN {?}, p.freetext, NULL) AS freetext,
721 pe.entry_year, pe.grad_year,
722 IF ({?} IN {?}, pse.text, NULL) AS section,
723 pn_f.name AS firstname, pn_l.name AS lastname, pn_n.name AS nickname,
724 IF(pn_uf.name IS NULL, pn_f.name, pn_uf.name) AS firstname_ordinary,
725 IF(pn_ul.name IS NULL, pn_l.name, pn_ul.name) AS lastname_ordinary,
726 pd.promo AS promo, pd.short_name, pd.directory_name AS full_name,
727 pd.directory_name, IF(pp.pub IN {?}, pp.display_tel, NULL) AS mobile,
728 (ph.pub IN {?} AND ph.attach IS NOT NULL) AS has_photo,
729 ph.x AS photo_width, ph.y AS photo_height,
730 p.last_change < DATE_SUB(NOW(), INTERVAL 365 DAY) AS is_old,
731 pm.expertise AS mentor_expertise,
732 ap.uid AS owner_id
733 FROM profiles AS p
734 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
735 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
736 LEFT JOIN profile_section_enum AS pse ON (pse.id = p.section)
737 INNER JOIN profile_name AS pn_f ON (pn_f.pid = p.pid
738 AND pn_f.typeid = ' . self::getNameTypeId('firstname', true) . ')
739 INNER JOIN profile_name AS pn_l ON (pn_l.pid = p.pid
740 AND pn_l.typeid = ' . self::getNameTypeId('lastname', true) . ')
741 LEFT JOIN profile_name AS pn_uf ON (pn_uf.pid = p.pid
742 AND pn_uf.typeid = ' . self::getNameTypeId('firstname_ordinary', true) . ')
743 LEFT JOIN profile_name AS pn_ul ON (pn_ul.pid = p.pid
744 AND pn_ul.typeid = ' . self::getNameTypeId('lastname_ordinary', true) . ')
745 LEFT JOIN profile_name AS pn_n ON (pn_n.pid = p.pid
746 AND pn_n.typeid = ' . self::getNameTypeId('nickname', true) . ')
747 LEFT JOIN profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = \'user\' AND tel_type = \'mobile\')
748 LEFT JOIN profile_photos AS ph ON (ph.pid = p.pid)
749 LEFT JOIN profile_mentor AS pm ON (pm.pid = p.pid)
750 LEFT JOIN account_profiles AS ap ON (ap.pid = p.pid AND FIND_IN_SET(\'owner\', ap.perms))
751 WHERE p.pid IN {?}
752 GROUP BY p.pid
753 ' . $order,
754 $visibility->levels(),
755 ProfileVisibility::VIS_PRIVATE, $visibility->levels(),
756 $visibility->levels(), $visibility->levels(),
757 $pids
758 );
759 return new ProfileIterator($it, $pids, $fields, $visibility);
760 }
761
762 public static function getPID($login)
763 {
764 if ($login instanceof PlUser) {
765 return XDB::fetchOneCell('SELECT pid
766 FROM account_profiles
767 WHERE uid = {?} AND FIND_IN_SET(\'owner\', perms)',
768 $login->id());
769 } else if (ctype_digit($login)) {
770 return XDB::fetchOneCell('SELECT pid
771 FROM profiles
772 WHERE pid = {?}', $login);
773 } else {
774 return XDB::fetchOneCell('SELECT pid
775 FROM profiles
776 WHERE hrpid = {?}', $login);
777 }
778 }
779
780 public static function getPIDsFromUIDs($uids, $respect_order = true)
781 {
782 if ($respect_order) {
783 $order = 'ORDER BY ' . XDB::formatCustomOrder('uid', $uids);
784 } else {
785 $order = '';
786 }
787 return XDB::fetchAllAssoc('uid', 'SELECT ap.uid, ap.pid
788 FROM account_profiles AS ap
789 WHERE FIND_IN_SET(\'owner\', ap.perms)
790 AND ap.uid IN ' . XDB::formatArray($uids) .'
791 ' . $order);
792 }
793
794 /** Return the profile associated with the given login.
795 */
796 public static function get($login, $fields = 0x0000, $visibility = null)
797 {
798 if (is_array($login)) {
799 $pf = new Profile($login);
800 $pf->setVisibilityLevel($visibility);
801 return $pf;
802 }
803 $pid = self::getPID($login);
804 if (!is_null($pid)) {
805 $it = self::iterOverPIDs(array($pid), false, $fields, $visibility);
806 return $it->next();
807 } else {
808 /* Let say we can identify a profile using the identifiers of its owner.
809 */
810 if (!($login instanceof PlUser)) {
811 $user = User::getSilent($login);
812 if ($user && $user->hasProfile()) {
813 return $user->profile();
814 }
815 }
816 return null;
817 }
818 }
819
820 public static function iterOverUIDs($uids, $respect_order = true, $fields = 0x0000, $visibility = null)
821 {
822 return self::iterOverPIDs(self::getPIDsFromUIDs($uids), $respect_order, $fields, $visibility);
823 }
824
825 public static function iterOverPIDs($pids, $respect_order = true, $fields = 0x0000, $visibility = null)
826 {
827 return self::fetchProfileData($pids, $respect_order, $fields, $visibility);
828 }
829
830 /** Return profiles for the list of pids.
831 */
832 public static function getBulkProfilesWithPIDs(array $pids, $fields = 0x0000, $visibility = null)
833 {
834 if (count($pids) == 0) {
835 return array();
836 }
837 $it = self::iterOverPIDs($pids, true, $fields, $visibility);
838 $profiles = array();
839 while ($p = $it->next()) {
840 $profiles[$p->id()] = $p;
841 }
842 return $profiles;
843 }
844
845 /** Return profiles for uids.
846 */
847 public static function getBulkProfilesWithUIDS(array $uids, $fields = 0x000, $visibility = null)
848 {
849 if (count($uids) == 0) {
850 return array();
851 }
852 return self::getBulkProfilesWithPIDs(self::getPIDsFromUIDs($uids), $fields, $visibility);
853 }
854
855 public static function isDisplayName($name)
856 {
857 return $name == self::DN_FULL || $name == self::DN_DISPLAY
858 || $name == self::DN_YOURSELF || $name == self::DN_DIRECTORY
859 || $name == self::DN_PRIVATE || $name == self::DN_PUBLIC
860 || $name == self::DN_SHORT || $name == self::DN_SORT;
861 }
862
863 public static function getNameTypeId($type, $for_sql = false)
864 {
865 if (!S::has('name_types')) {
866 $table = XDB::fetchAllAssoc('type', 'SELECT id, type
867 FROM profile_name_enum');
868 S::set('name_types', $table);
869 } else {
870 $table = S::v('name_types');
871 }
872 if ($for_sql) {
873 return XDB::escape($table[$type]);
874 } else {
875 return $table[$type];
876 }
877 }
878
879 public static function rebuildSearchTokens($pid)
880 {
881 XDB::execute('DELETE FROM search_name
882 WHERE pid = {?}',
883 $pid);
884 $keys = XDB::iterator("SELECT CONCAT(n.particle, n.name) AS name, e.score,
885 FIND_IN_SET('public', e.flags) AS public
886 FROM profile_name AS n
887 INNER JOIN profile_name_enum AS e ON (n.typeid = e.id)
888 WHERE n.pid = {?}",
889 $pid);
890
891 foreach ($keys as $i => $key) {
892 if ($key['name'] == '') {
893 continue;
894 }
895 $toks = preg_split('/[ \'\-]+/', $key['name']);
896 $token = '';
897 $first = 5;
898 while ($toks) {
899 $token = strtolower(replace_accent(array_pop($toks) . $token));
900 $score = ($toks ? 0 : 10 + $first) * ($key['score'] / 10);
901 XDB::execute('REPLACE INTO search_name (token, pid, soundex, score, flags)
902 VALUES ({?}, {?}, {?}, {?}, {?})',
903 $token, $pid, soundex_fr($token), $score, $key['public']);
904 $first = 0;
905 }
906 }
907 }
908
909 /** The school identifier consists of 6 digits. The first 3 represent the
910 * promotion entry year. The last 3 indicate the student's rank.
911 *
912 * Our identifier consists of 8 digits and both half have the same role.
913 * This enables us to deal with bigger promotions and with a wider range
914 * of promotions.
915 *
916 * getSchoolId returns a school identifier given one of ours.
917 * getXorgId returns a X.org identifier given a school identifier.
918 */
919 public static function getSchoolId($xorgId)
920 {
921 if (!preg_match('/^[0-9]{8}$/', $xorgId)) {
922 return null;
923 }
924
925 $year = intval(substr($xorgId, 0, 4));
926 $rank = intval(substr($xorgId, 5, 3));
927 if ($year < 1996) {
928 return null;
929 } elseif ($year < 2000) {
930 $year = intval(substr(1900 - $year, 1, 3));
931 return sprintf('%02u0%03u', $year, $rank);
932 } else {
933 $year = intval(substr(1900 - $year, 1, 3));
934 return sprintf('%03u%03u', $year, $rank);
935 }
936 }
937
938 public static function getXorgId($schoolId)
939 {
940 if (!preg_match('/^[0-9]{6}$/', $schoolId)) {
941 return null;
942 }
943
944 $year = intval(substr($schoolId, 0, 3));
945 $rank = intval(substr($schoolId, 3, 3));
946
947 if ($year > 200) {
948 $year /= 10;
949 }
950 if ($year < 96) {
951 return null;
952 } else {
953 return sprintf('%04u%04u', 1900 + $year, $rank);
954 }
955 }
956 }
957
958
959 /** Iterator over a set of Profiles
960 */
961 class ProfileIterator implements PlIterator
962 {
963 private $iterator = null;
964 private $fields;
965 private $visibility;
966
967 public function __construct(PlIterator $it, array $pids, $fields = 0x0000, ProfileVisibility $visibility = null)
968 {
969 require_once 'profilefields.inc.php';
970
971 if ($visibility == null) {
972 $visibility = new ProfileVisibility();
973 }
974
975 $this->fields = $fields;
976 $this->visibility = $visibility;
977
978 $subits = array();
979 $callbacks = array();
980
981 $subits[0] = $it;
982 $callbacks[0] = PlIteratorUtils::arrayValueCallback('pid');
983 $cb = PlIteratorUtils::objectPropertyCallback('pid');
984
985 if ($fields & Profile::FETCH_ADDRESSES) {
986 $callbacks[Profile::FETCH_ADDRESSES] = $cb;
987 $subits[Profile::FETCH_ADDRESSES] = new ProfileFieldIterator('ProfileAddresses', $pids, $visibility);
988 }
989
990 if ($fields & Profile::FETCH_CORPS) {
991 $callbacks[Profile::FETCH_CORPS] = $cb;
992 $subits[Profile::FETCH_CORPS] = new ProfileFieldIterator('ProfileCorps', $pids, $visibility);
993 }
994
995 if ($fields & Profile::FETCH_EDU) {
996 $callbacks[Profile::FETCH_EDU] = $cb;
997 $subits[Profile::FETCH_EDU] = new ProfileFieldIterator('ProfileEducation', $pids, $visibility);
998 }
999
1000 if ($fields & Profile::FETCH_JOBS) {
1001 $callbacks[Profile::FETCH_JOBS] = $cb;
1002 $subits[Profile::FETCH_JOBS] = new ProfileFieldIterator('ProfileJobs', $pids, $visibility);
1003 }
1004
1005 if ($fields & Profile::FETCH_MEDALS) {
1006 $callbacks[Profile::FETCH_MEDALS] = $cb;
1007 $subits[Profile::FETCH_MEDALS] = new ProfileFieldIterator('ProfileMedals', $pids, $visibility);
1008 }
1009
1010 if ($fields & Profile::FETCH_NETWORKING) {
1011 $callbacks[Profile::FETCH_NETWORKING] = $cb;
1012 $subits[Profile::FETCH_NETWORKING] = new ProfileFieldIterator('ProfileNetworking', $pids, $visibility);
1013 }
1014
1015 if ($fields & Profile::FETCH_PHONES) {
1016 $callbacks[Profile::FETCH_PHONES] = $cb;
1017 $subits[Profile::FETCH_PHONES] = new ProfileFieldIterator('ProfilePhones', $pids, $visibility);
1018 }
1019
1020 $this->iterator = PlIteratorUtils::parallelIterator($subits, $callbacks, 0);
1021 }
1022
1023 private function hasData($field, $vals)
1024 {
1025 return ($this->fields & $field) && ($vals[$field] != null);
1026 }
1027
1028 private function fillProfile(array $vals)
1029 {
1030 $pf = Profile::get($vals[0]);
1031 $pf->setVisibilityLevel($this->visibility->level());
1032 $pf->setFetchedFields($this->fields);
1033
1034 if ($this->hasData(Profile::FETCH_PHONES, $vals)) {
1035 $pf->setPhones($vals[Profile::FETCH_PHONES]);
1036 }
1037 if ($this->hasData(Profile::FETCH_ADDRESSES, $vals)) {
1038 $pf->setAddresses($vals[Profile::FETCH_ADDRESSES]);
1039 }
1040 if ($this->hasData(Profile::FETCH_JOBS, $vals)) {
1041 $pf->setJobs($vals[Profile::FETCH_JOBS]);
1042 }
1043
1044 if ($this->hasData(Profile::FETCH_CORPS, $vals)) {
1045 $pf->setCorps($vals[Profile::FETCH_CORPS]);
1046 }
1047 if ($this->hasData(Profile::FETCH_EDU, $vals)) {
1048 $pf->setEducations($vals[Profile::FETCH_EDU]);
1049 }
1050 if ($this->hasData(Profile::FETCH_MEDALS, $vals)) {
1051 $pf->setMedals($vals[Profile::FETCH_MEDALS]);
1052 }
1053 if ($this->hasData(Profile::FETCH_NETWORKING, $vals)) {
1054 $pf->setNetworking($vals[Profile::FETCH_NETWORKING]);
1055 }
1056
1057 return $pf;
1058 }
1059
1060 public function next()
1061 {
1062 $vals = $this->iterator->next();
1063 if ($vals == null) {
1064 return null;
1065 }
1066 return $this->fillProfile($vals);
1067 }
1068
1069 public function first()
1070 {
1071 return $this->iterator->first();
1072 }
1073
1074 public function last()
1075 {
1076 return $this->iterator->last();
1077 }
1078
1079 public function total()
1080 {
1081 return $this->iterator->total();
1082 }
1083 }
1084
1085 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1086 ?>