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