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