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