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