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