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