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