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