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