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