Merge branch 'xorg/maint' into xorg/master
[platal.git] / classes / profile.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class Profile implements PlExportable
23 {
24
25 /* name tokens */
26 const LASTNAME = 'lastname';
27 const FIRSTNAME = 'firstname';
28 const NICKNAME = 'nickname';
29 const PSEUDONYM = 'pseudonym';
30 const NAME = 'name';
31 /* name variants */
32 const VN_MARITAL = 'marital';
33 const VN_ORDINARY = 'ordinary';
34 const VN_OTHER = 'other';
35 const VN_INI = 'ini';
36 /* display names */
37 const DN_FULL = 'directory_name';
38 const DN_DISPLAY = 'yourself';
39 const DN_YOURSELF = 'yourself';
40 const DN_DIRECTORY = 'directory_name';
41 const DN_PRIVATE = 'private_name';
42 const DN_PUBLIC = 'public_name';
43 const DN_SHORT = 'short_name';
44 const DN_SORT = 'sort_name';
45 /* education related names */
46 const EDU_X = 'École polytechnique';
47 const DEGREE_X = 'Ingénieur';
48 const DEGREE_M = 'Master';
49 const DEGREE_D = 'Doctorat';
50
51 static public $cycles = array(
52 self::DEGREE_X => 'polytechnicien',
53 self::DEGREE_M => 'master',
54 self::DEGREE_D => 'docteur'
55 );
56 static public $cycle_prefixes = array(
57 self::DEGREE_X => 'X',
58 self::DEGREE_M => 'M',
59 self::DEGREE_D => 'D'
60 );
61
62 static public $name_variants = array(
63 self::LASTNAME => array(self::VN_MARITAL, self::VN_ORDINARY),
64 self::FIRSTNAME => array(self::VN_ORDINARY, self::VN_INI, self::VN_OTHER)
65 );
66
67 const ADDRESS_MAIN = 0x00000001;
68 const ADDRESS_PERSO = 0x00000002;
69 const ADDRESS_PRO = 0x00000004;
70 const ADDRESS_ALL = 0x00000006;
71 const ADDRESS_POSTAL = 0x00000008;
72
73 const EDUCATION_MAIN = 0x00000010;
74 const EDUCATION_EXTRA = 0x00000020;
75 const EDUCATION_ALL = 0x00000040;
76 const EDUCATION_FINISHED = 0x00000080;
77 const EDUCATION_CURRENT = 0x00000100;
78
79 const JOBS_MAIN = 0x00001000;
80 const JOBS_ALL = 0x00002000;
81 const JOBS_FINISHED = 0x00004000;
82 const JOBS_CURRENT = 0x00008000;
83
84 const NETWORKING_ALL = 0x00070000;
85 const NETWORKING_WEB = 0x00010000;
86 const NETWORKING_IM = 0x00020000;
87 const NETWORKING_SOCIAL = 0x00040000;
88
89 const PHONE_LINK_JOB = 0x00100000;
90 const PHONE_LINK_ADDRESS = 0x00200000;
91 const PHONE_LINK_PROFILE = 0x00400000;
92 const PHONE_LINK_COMPANY = 0x00800000;
93 const PHONE_LINK_ANY = 0x00F00000;
94
95 const PHONE_TYPE_FAX = 0x01000000;
96 const PHONE_TYPE_FIXED = 0x02000000;
97 const PHONE_TYPE_MOBILE = 0x04000000;
98 const PHONE_TYPE_ANY = 0x07000000;
99
100 const PHONE_ANY = 0x07F00000;
101
102 const FETCH_ADDRESSES = 0x000001;
103 const FETCH_CORPS = 0x000002;
104 const FETCH_EDU = 0x000004;
105 const FETCH_JOBS = 0x000008;
106 const FETCH_MEDALS = 0x000010;
107 const FETCH_NETWORKING = 0x000020;
108 const FETCH_MENTOR_COUNTRY = 0x000080;
109 const FETCH_PHONES = 0x000100;
110 const FETCH_JOB_TERMS = 0x000200;
111 const FETCH_MENTOR_TERMS = 0x000400;
112 const FETCH_DELTATEN = 0x000800;
113 const FETCH_PARTNER = 0x001000;
114 const FETCH_SKILL = 0x002000;
115 const FETCH_LANGUAGE = 0x004000;
116
117 const FETCH_MINIFICHES = 0x00012D; // FETCH_ADDRESSES | FETCH_EDU | FETCH_JOBS | FETCH_NETWORKING | FETCH_PHONES
118
119 const FETCH_ALL = 0x007FFF; // OR of FETCH_*
120
121 static public $descriptions = array(
122 'search_names' => 'Noms',
123 'nationality1' => 'Nationalité',
124 'nationality2' => '2e nationalité',
125 'nationality3' => '3e nationalité',
126 'promo_display' => 'Promotion affichée',
127 'email_directory' => 'Email annuaire papier',
128 'networking' => 'Messageries…',
129 'tels' => 'Téléphones',
130 'edus' => 'Formations',
131 'main_edus' => 'Formations à l\'X',
132 'promo' => 'Promotion de sortie',
133 'birthdate' => 'Date de naissance',
134 'yourself' => 'Nom affiché',
135 'freetext' => 'Commentaire',
136 'freetext_pub' => 'Affichage du commentaire',
137 'photo' => 'Photographie',
138 'photo_pub' => 'Affichage de la photographie',
139 'addresses' => 'Adresses',
140 'corps' => 'Corps',
141 'cv' => 'CV',
142 'jobs' => 'Emplois',
143 'section' => 'Section',
144 'binets' => 'Binets',
145 'medals' => 'Décorations',
146 'medals_pub' => 'Affichage des décorations',
147 'competences' => 'Compétences',
148 'langues' => 'Langues',
149 'expertise' => 'Expertises (mentoring)',
150 'terms' => 'Compétences (mentoring)',
151 'countries' => 'Pays (mentoring)',
152 'deltaten' => 'Opération N N-10',
153 );
154
155 private $fetched_fields = 0x000000;
156
157 private $pid;
158 private $hrpid;
159 private $owner;
160 private $owner_fetched = false;
161 private $data = array();
162
163 private $visibility = null;
164
165
166 private function __construct(array $data, Visibility $visibility)
167 {
168 $this->data = $data;
169 $this->pid = $this->data['pid'];
170 $this->hrpid = $this->data['hrpid'];
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 && $this->isVisible(Visibility::EXPORT_PRIVATE)) {
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_partnersharing_settings, profile_phones, profile_skills,
465 * watch_profile
466 * *always keeps in: profile_corps, profile_display, profile_education,
467 * profile_medals, profile_*_names, profile_photos, search_name
468 * *modifies: profiles
469 */
470 public function clear()
471 {
472 $tables = array(
473 'profile_job', 'profile_langskills', 'profile_mentor',
474 'profile_networking', 'profile_skills', 'watch_profile',
475 'profile_phones', 'profile_addresses', 'profile_binets',
476 'profile_deltaten', 'profile_partnersharing_settings');
477
478 foreach ($tables as $t) {
479 XDB::execute('DELETE FROM ' . $t . '
480 WHERE pid = {?}',
481 $this->id());
482 }
483
484 XDB::execute("UPDATE profiles
485 SET cv = NULL, freetext = NULL, freetext_pub = 'private',
486 medals_pub = 'private', alias_pub = 'private',
487 email_directory = NULL
488 WHERE pid = {?}",
489 $this->id());
490 }
491
492 /** Determine whether an item with visibility $visibility can be displayed
493 * with the current level of visibility of the profile
494 * @param $visibility The level of visibility to be checked
495 */
496 public function isVisible($visibility)
497 {
498 return $this->visibility->isVisible($visibility);
499 }
500
501 /** Stores the list of fields which have already been fetched for this Profile
502 */
503 public function setFetchedFields($fields)
504 {
505 if (($fields | self::FETCH_ALL) != self::FETCH_ALL) {
506 Platal::page()->kill("Invalid fetched fields: $fields");
507 }
508
509 $this->fetched_fields = $fields;
510 }
511
512 /** Have we already fetched this field ?
513 */
514 private function fetched($field)
515 {
516 if (!array_key_exists($field, ProfileField::$fields)) {
517 Platal::page()->kill("Invalid field: $field");
518 }
519
520 return ($this->fetched_fields & $field);
521 }
522
523 /** If not already done, fetches data for the given field
524 * @param $field One of the Profile::FETCH_*
525 * @return A ProfileField, or null
526 */
527 private function getProfileField($field)
528 {
529 if (!array_key_exists($field, ProfileField::$fields)) {
530 Platal::page()->kill("Invalid field: $field");
531 }
532 if ($this->fetched($field)) {
533 return null;
534 } else {
535 $this->fetched_fields = $this->fetched_fields | $field;
536 }
537
538 $cls = ProfileField::$fields[$field];
539
540 return ProfileField::getForPID($cls, $this->id(), $this->visibility);
541 }
542
543 /** Consolidates internal data (addresses, phones, jobs)
544 */
545 private function consolidateFields()
546 {
547 // Link phones to addresses
548 if ($this->phones != null) {
549 if ($this->addresses != null) {
550 $this->addresses->addPhones($this->phones);
551 }
552
553 if ($this->jobs != null) {
554 $this->jobs->addPhones($this->phones);
555 }
556 }
557
558 // Link addresses to jobs
559 if ($this->addresses != null && $this->jobs != null) {
560 $this->jobs->addAddresses($this->addresses);
561 }
562
563 // Link jobterms to jobs
564 if ($this->jobs != null && $this->jobterms != null) {
565 $this->jobs->addJobTerms($this->jobterms);
566 }
567 }
568
569 /* Photo
570 */
571 private $photo = null;
572 public function getPhoto($fallback = true, $data = false)
573 {
574 if ($this->has_photo) {
575 if ($data && ($this->photo == null || $this->photo->mimeType == null)) {
576 $res = XDB::fetchOneAssoc('SELECT attach, attachmime, x, y, last_update
577 FROM profile_photos
578 WHERE pid = {?}', $this->pid);
579 $this->photo = PlImage::fromData($res['attach'], 'image/' .$res['attachmime'], $res['x'], $res['y'], $res['last_update']);
580 } else if ($this->photo == null) {
581 $this->photo = PlImage::fromData(null, null, $this->photo_width, $this->photo_height);
582 }
583 return $this->photo;
584 } else if ($fallback) {
585 if ($this->mainEducation() == 'X') {
586 return PlImage::fromFile(dirname(__FILE__) . '/../htdocs/images/none_x.png', 'image/png');
587 }
588 return PlImage::fromFile(dirname(__FILE__) . '/../htdocs/images/none_md.png', 'image/png');
589 }
590 return null;
591 }
592
593 /* Addresses
594 */
595 private $addresses = null;
596 public function setAddresses(ProfileAddresses $addr)
597 {
598 $this->addresses = $addr;
599 $this->consolidateFields();
600 }
601
602 private function fetchAddresses()
603 {
604 if ($this->addresses == null && !$this->fetched(self::FETCH_ADDRESSES)) {
605 $addr = $this->getProfileField(self::FETCH_ADDRESSES);
606 if ($addr) {
607 $this->setAddresses($addr);
608 $this->fetchPhones();
609 }
610 }
611 }
612
613 public function getAddresses($flags, $limit = null)
614 {
615 $this->fetchAddresses();
616
617 if ($this->addresses == null) {
618 return array();
619 }
620 return $this->addresses->get($flags, $limit);
621 }
622
623 public function iterAddresses($flags, $limit = null)
624 {
625 return PlIteratorUtils::fromArray($this->getAddresses($flags, $limit), 1, true);
626 }
627
628 public function getMainAddress()
629 {
630 $main = $this->getAddresses(self::ADDRESS_MAIN);
631 $perso = $this->getAddresses(self::ADDRESS_PERSO);
632
633 if (count($main)) {
634 return array_pop($main);
635 } else if (count($perso)) {
636 return array_pop($perso);
637 } else {
638 return null;
639 }
640 }
641
642 /* Phones
643 */
644 private $phones = null;
645 public function setPhones(ProfilePhones $phones)
646 {
647 $this->phones = $phones;
648 $this->consolidateFields();
649 }
650
651 private function fetchPhones()
652 {
653 if ($this->phones == null && !$this->fetched(self::FETCH_PHONES)) {
654 $phones = $this->getProfileField(self::FETCH_PHONES);
655 if (isset($phones)) {
656 $this->setPhones($phones);
657 }
658 }
659 }
660
661 public function getPhones($flags, $limit = null)
662 {
663 $this->fetchPhones();
664 if ($this->phones == null) {
665 return array();
666 }
667 return $this->phones->get($flags, $limit);
668 }
669
670 /* Educations
671 */
672 private $educations = null;
673 public function setEducations(ProfileEducation $edu)
674 {
675 $this->educations = $edu;
676 }
677
678 public function getEducations($flags, $limit = null)
679 {
680 if ($this->educations == null && !$this->fetched(self::FETCH_EDU)) {
681 $educations = $this->getProfileField(self::FETCH_EDU);
682 if ($educations) {
683 $this->setEducations($educations);
684 }
685 }
686
687 if ($this->educations == null) {
688 return array();
689 }
690 return $this->educations->get($flags, $limit);
691 }
692
693 public function getExtraEducations($limit = null)
694 {
695 return $this->getEducations(self::EDUCATION_EXTRA, $limit);
696 }
697
698 /* Corps
699 */
700 private $corps = null;
701 public function setCorps(ProfileCorps $corps)
702 {
703 $this->corps = $corps;
704 }
705
706 public function getCorps()
707 {
708 if ($this->corps == null && !$this->fetched(self::FETCH_CORPS)) {
709 $corps = $this->getProfileField(self::FETCH_CORPS);
710 if ($corps) {
711 $this->setCorps($corps);
712 }
713 }
714 return $this->corps;
715 }
716
717 /** Networking
718 */
719 private $networks = null;
720 public function setNetworking(ProfileNetworking $nw)
721 {
722 $this->networks = $nw;
723 }
724
725 public function getNetworking($flags, $limit = null)
726 {
727 if ($this->networks == null && !$this->fetched(self::FETCH_NETWORKING)) {
728 $nw = $this->getProfileField(self::FETCH_NETWORKING);
729 if ($nw) {
730 $this->setNetworking($nw);
731 }
732 }
733 if ($this->networks == null) {
734 return array();
735 }
736 return $this->networks->get($flags, $limit);
737 }
738
739 public function getWebSite()
740 {
741 $site = $this->getNetworking(self::NETWORKING_WEB, 1);
742 if (count($site) != 1) {
743 return null;
744 }
745 $site = array_pop($site);
746 return $site;
747 }
748
749
750 /** Jobs
751 */
752 private $jobs = null;
753 public function setJobs(ProfileJobs $jobs)
754 {
755 $this->jobs = $jobs;
756 $this->consolidateFields();
757 }
758
759 private function fetchJobs()
760 {
761 if ($this->jobs == null && !$this->fetched(self::FETCH_JOBS)) {
762 $jobs = $this->getProfileField(self::FETCH_JOBS);
763 if ($jobs) {
764 $this->setJobs($jobs);
765 $this->fetchAddresses();
766 }
767 }
768 }
769
770 public function getJobs($flags, $limit = null)
771 {
772 $this->fetchJobs();
773
774 if ($this->jobs == null) {
775 return array();
776 }
777 return $this->jobs->get($flags, $limit);
778 }
779
780 public function getMainJob()
781 {
782 $job = $this->getJobs(self::JOBS_MAIN, 1);
783 if (count($job) != 1) {
784 return null;
785 }
786 return array_pop($job);
787 }
788
789 /** JobTerms
790 */
791 private $jobterms = null;
792 public function setJobTerms(ProfileJobTerms $jobterms)
793 {
794 $this->jobterms = $jobterms;
795 $this->consolidateFields();
796 }
797
798 private $mentor_countries = null;
799 public function setMentoringCountries(ProfileMentoringCountries $countries)
800 {
801 $this->mentor_countries = $countries;
802 }
803
804 public function getMentoringCountries()
805 {
806 if ($this->mentor_countries == null && !$this->fetched(self::FETCH_MENTOR_COUNTRY)) {
807 $countries = $this->getProfileField(self::FETCH_MENTOR_COUNTRY);
808 if ($countries) {
809 $this->setMentoringCountries($countries);
810 }
811 }
812
813 if ($this->mentor_countries == null) {
814 return array();
815 } else {
816 return $this->mentor_countries->countries;
817 }
818 }
819
820 /** List of job terms to specify mentoring */
821 private $mentor_terms = null;
822 /**
823 * set job terms to specify mentoring
824 * @param $terms a ProfileMentoringTerms object listing terms only for this profile
825 */
826 public function setMentoringTerms(ProfileMentoringTerms $terms)
827 {
828 $this->mentor_terms = $terms;
829 }
830 /**
831 * get all job terms that specify mentoring
832 * @return an array of JobTerms objects
833 */
834 public function getMentoringTerms()
835 {
836 if ($this->mentor_terms == null && !$this->fetched(self::FETCH_MENTOR_TERMS)) {
837 $terms = $this->getProfileField(self::FETCH_MENTOR_TERMS);
838 if ($terms) {
839 $this->setMentoringTerms($terms);
840 }
841 }
842
843 if ($this->mentor_terms == null) {
844 return array();
845 } else {
846 return $this->mentor_terms->get();
847 }
848 }
849
850 /* Skills */
851 private $skills = null;
852 public function setSkills(ProfileSkills $skills)
853 {
854 $this->skills = $skills;
855 }
856 public function getSkills()
857 {
858 if ($this->skills == null && !$this->fetched(self::FETCH_SKILL)) {
859 $skills = $this->getProfileField(self::FETCH_SKILL);
860 if ($skills) {
861 $this->setSkills($skills);
862 }
863 }
864
865 if ($this->skills == null) {
866 return array();
867 } else {
868 return $this->skills->skills;
869 }
870 }
871
872 /* Languades */
873 private $languages = null;
874 public function setLanguages(ProfileLanguages $languages)
875 {
876 $this->languages = $languages;
877 }
878 public function getLanguages()
879 {
880 if ($this->languages == null && !$this->fetched(self::FETCH_LANGUAGE)) {
881 $languages = $this->getProfileField(self::FETCH_LANGUAGE);
882 if ($languages) {
883 $this->setLanguages($languages);
884 }
885 }
886
887 if ($this->languages == null) {
888 return array();
889 } else {
890 return $this->languages->languages;
891 }
892 }
893
894 /** DeltaTen
895 */
896
897 /** Find out whether this profile may take part to the "DeltaTen" operation.
898 * @param $role Which role to select ('young' or 'old')
899 * @return Boolean: whether it is enabled.
900 */
901 const DELTATEN_YOUNG = 'young';
902 const DELTATEN_OLD = 'old';
903 public function isDeltaTenEnabled($role)
904 {
905 global $globals;
906 switch ($role) {
907 case self::DELTATEN_YOUNG:
908 return ($this->mainGrade() == UserFilter::GRADE_ING && $this->yearpromo() >= $globals->deltaten->first_promo_young);
909 case self::DELTATEN_OLD:
910 // Roughly compute the current promo in second year on the campus:
911 // Promo 2010 is in second year between 09/2011 and 08/2012 => use 2012.
912 // DeltaTen program begins around January of the second year.
913 $promo_on_platal = ((int) date('Y')) - 2;
914 return ($this->mainGrade() == UserFilter::GRADE_ING && $this->yearpromo() >= $globals->deltaten->first_promo_young - 10 && $this->yearpromo() <= $promo_on_platal - 10);
915 default:
916 Platal::assert(false, "Invalid DeltaTen role $role");
917 }
918 }
919
920 /** Retrieve the "Deltaten" message of the user.
921 * Returns "null" if the message is empty or the user is not taking part to the
922 * DeltaTen operation.
923 */
924 public function getDeltatenMessage()
925 {
926 if ($this->isDeltaTenEnabled(self::DELTATEN_OLD)) {
927 return $this->deltaten_message;
928 } else {
929 return null;
930 }
931 }
932
933 /* Binets
934 */
935 public function getBinets()
936 {
937 if ($this->visibility->isVisible(Visibility::EXPORT_PRIVATE)) {
938 return XDB::fetchColumn('SELECT binet_id
939 FROM profile_binets
940 WHERE pid = {?}', $this->id());
941 } else {
942 return array();
943 }
944 }
945 public function getBinetsNames()
946 {
947 if ($this->visibility->isVisible(Visibility::EXPORT_PRIVATE)) {
948 return XDB::fetchColumn('SELECT text
949 FROM profile_binets AS pb
950 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
951 WHERE pb.pid = {?}', $this->id());
952 } else {
953 return array();
954 }
955 }
956
957 /* Medals
958 */
959 private $medals = null;
960 public function setMedals(ProfileMedals $medals)
961 {
962 $this->medals = $medals;
963 }
964
965 public function getMedals()
966 {
967 if ($this->medals == null && !$this->fetched(self::FETCH_MEDALS)) {
968 $medals = $this->getProfileField(self::FETCH_MEDALS);
969 if ($medals) {
970 $this->setMedals($medals);
971 }
972 }
973 if ($this->medals == null) {
974 return array();
975 }
976 return $this->medals->medals;
977 }
978
979 /** Sharing data with partner websites
980 */
981 private $partners_settings = null;
982 public function setPartnersSettings(ProfilePartnerSharing $partners_settings)
983 {
984 $this->partners_settings = $partners_settings;
985 }
986
987 public function getPartnerSettings($partner_id)
988 {
989 if ($this->partners_settings === null && !$this->fetched(self::FETCH_PARTNER)) {
990 $settings = $this->getProfileField(self::FETCH_PARTNER);
991 if ($settings) {
992 $this->setPartnersSettings($settings);
993 }
994 }
995 if ($this->partners_settings === null) {
996 return PartnerSettings::getEmpty($partner_id);
997 }
998 return $this->partners_settings->get($partner_id);
999 }
1000
1001 public function compareNames($firstname, $lastname)
1002 {
1003 $_lastname = mb_strtoupper($this->lastName());
1004 $_firstname = mb_strtoupper($this->firstName());
1005 $lastname = mb_strtoupper($lastname);
1006 $firstname = mb_strtoupper($firstname);
1007
1008 $isOk = (mb_strtoupper($_firstname) == mb_strtoupper($firstname));
1009 $tokens = preg_split("/[ \-']/", $lastname, -1, PREG_SPLIT_NO_EMPTY);
1010 $maxlen = 0;
1011
1012 foreach ($tokens as $str) {
1013 $isOk &= (strpos($_lastname, $str) !== false);
1014 $maxlen = max($maxlen, strlen($str));
1015 }
1016
1017 return ($isOk && ($maxlen > 2 || $maxlen == strlen($_lastname)));
1018 }
1019
1020 /* Export to JSON
1021 */
1022 public function export()
1023 {
1024 return array(
1025 'hrpid' => $this->hrid(),
1026 'display_name' => $this->shortName(),
1027 'full_name' => $this->fullName(),
1028 'directory_name' => $this->directory_name,
1029 'promo' => $this->promo(),
1030 'year_promo' => $this->yearpromo(),
1031 'is_active' => $this->isActive(),
1032 'first_name' => $this->firstName(),
1033 'last_name' => $this->lastName(),
1034 'is_female' => $this->isFemale(),
1035 );
1036 }
1037
1038 private static function fetchProfileData(array $pids, $respect_order = true, $fields = 0x0000, $visibility = null)
1039 {
1040 if (count($pids) == 0) {
1041 return null;
1042 }
1043
1044 if ($respect_order) {
1045 $order = 'ORDER BY ' . XDB::formatCustomOrder('p.pid', $pids);
1046 } else {
1047 $order = '';
1048 }
1049
1050 if ($visibility === null) {
1051 $visibility = Visibility::defaultForRead();
1052 }
1053
1054 $it = XDB::Iterator('SELECT p.pid, p.hrpid, p.xorg_id, p.ax_id, p.birthdate, p.birthdate_ref,
1055 p.next_birthday, p.deathdate, p.deathdate_rec, p.sex = \'female\' AS sex,
1056 IF ({?}, p.cv, NULL) AS cv, p.medals_pub, p.alias_pub, p.email_directory,
1057 p.last_change, p.nationality1, p.nationality2, p.nationality3,
1058 IF (p.freetext_pub >= {?}, p.freetext, NULL) AS freetext,
1059 pe.entry_year, pe.grad_year, pe.promo_year, pe.program, pe.fieldid,
1060 IF ({?}, pse.text, NULL) AS section,
1061 ppn.firstname_main AS firstname, ppn.lastname_main AS lastname, IF ({?}, pn.name, NULL) AS nickname,
1062 IF (ppn.firstname_ordinary = \'\', ppn.firstname_main, ppn.firstname_ordinary) AS firstname_ordinary,
1063 IF (ppn.lastname_ordinary = \'\', ppn.firstname_main, ppn.lastname_ordinary) AS lastname_ordinary,
1064 pd.yourself, pd.promo, pd.short_name, pd.public_name AS full_name,
1065 pd.directory_name, pd.public_name, pd.private_name,
1066 IF (pp.pub >= {?}, pp.display_tel, NULL) AS mobile,
1067 (ph.pub >= {?} AND ph.attach IS NOT NULL) AS has_photo, ph.pub as photo_pub,
1068 ph.x AS photo_width, ph.y AS photo_height,
1069 p.last_change < DATE_SUB(NOW(), INTERVAL 365 DAY) AS is_old,
1070 pm.expertise AS mentor_expertise,
1071 IF ({?}, pdt.message, NULL) AS deltaten_message,
1072 ap.uid AS owner_id
1073 FROM profiles AS p
1074 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1075 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
1076 LEFT JOIN profile_section_enum AS pse ON (pse.id = p.section)
1077 INNER JOIN profile_public_names AS ppn ON (ppn.pid = p.pid)
1078 LEFT JOIN profile_private_names AS pn ON (pn.pid = p.pid AND type = \'nickname\')
1079 LEFT JOIN profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = \'user\' AND tel_type = \'mobile\')
1080 LEFT JOIN profile_photos AS ph ON (ph.pid = p.pid)
1081 LEFT JOIN profile_mentor AS pm ON (pm.pid = p.pid)
1082 LEFT JOIN profile_deltaten AS pdt ON (pdt.pid = p.pid)
1083 LEFT JOIN account_profiles AS ap ON (ap.pid = p.pid AND FIND_IN_SET(\'owner\', ap.perms))
1084 WHERE p.pid IN {?}
1085 GROUP BY p.pid
1086 ' . $order,
1087 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // CV
1088 $visibility->level(), // freetext
1089 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // section
1090 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // nickname
1091 $visibility->level(), // mobile
1092 $visibility->level(), // photo
1093 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // deltaten_message
1094 $pids
1095 );
1096 return new ProfileIterator($it, $pids, $fields, $visibility);
1097 }
1098
1099 public static function getPID($login)
1100 {
1101 if ($login instanceof PlUser) {
1102 return XDB::fetchOneCell('SELECT pid
1103 FROM account_profiles
1104 WHERE uid = {?} AND FIND_IN_SET(\'owner\', perms)',
1105 $login->id());
1106 } else if (ctype_digit($login)) {
1107 return XDB::fetchOneCell('SELECT pid
1108 FROM profiles
1109 WHERE pid = {?}', $login);
1110 } else {
1111 return XDB::fetchOneCell('SELECT pid
1112 FROM profiles
1113 WHERE hrpid = {?}', $login);
1114 }
1115 }
1116
1117 public static function getPIDsFromUIDs($uids, $respect_order = true)
1118 {
1119 if ($respect_order) {
1120 $order = 'ORDER BY ' . XDB::formatCustomOrder('uid', $uids);
1121 } else {
1122 $order = '';
1123 }
1124 return XDB::fetchAllAssoc('uid', 'SELECT ap.uid, ap.pid
1125 FROM account_profiles AS ap
1126 WHERE FIND_IN_SET(\'owner\', ap.perms)
1127 AND ap.uid IN ' . XDB::formatArray($uids) .'
1128 ' . $order);
1129 }
1130
1131 /** Return the profile associated with the given login.
1132 */
1133 public static function get($login, $fields = 0x0000, $visibility = null)
1134 {
1135 if ($visibility === null) {
1136 $visibility = Visibility::defaultForRead();
1137 }
1138
1139 if (is_array($login)) {
1140 $pf = new Profile($login, $visibility);
1141 return $pf;
1142 }
1143 $pid = self::getPID($login);
1144 if (!is_null($pid)) {
1145 $it = self::iterOverPIDs(array($pid), false, $fields, $visibility);
1146 return $it->next();
1147 } else {
1148 /* Let say we can identify a profile using the identifiers of its owner.
1149 */
1150 if (!($login instanceof PlUser)) {
1151 $user = User::getSilent($login);
1152 if ($user && $user->hasProfile()) {
1153 return $user->profile(false, $fields, $visibility);
1154 }
1155 }
1156 return null;
1157 }
1158 }
1159
1160 public static function iterOverUIDs($uids, $respect_order = true, $fields = 0x0000, $visibility = null)
1161 {
1162 return self::iterOverPIDs(self::getPIDsFromUIDs($uids), $respect_order, $fields, $visibility);
1163 }
1164
1165 public static function iterOverPIDs($pids, $respect_order = true, $fields = 0x0000, $visibility = null)
1166 {
1167 return self::fetchProfileData($pids, $respect_order, $fields, $visibility);
1168 }
1169
1170 /** Return profiles for the list of pids.
1171 */
1172 public static function getBulkProfilesWithPIDs(array $pids, $fields = 0x0000, $visibility = null)
1173 {
1174 if (count($pids) == 0) {
1175 return array();
1176 }
1177 $it = self::iterOverPIDs($pids, true, $fields, $visibility);
1178 $profiles = array();
1179 while ($p = $it->next()) {
1180 $profiles[$p->id()] = $p;
1181 }
1182 return $profiles;
1183 }
1184
1185 /** Return profiles for uids.
1186 */
1187 public static function getBulkProfilesWithUIDS(array $uids, $fields = 0x000, $visibility = null)
1188 {
1189 if (count($uids) == 0) {
1190 return array();
1191 }
1192 return self::getBulkProfilesWithPIDs(self::getPIDsFromUIDs($uids), $fields, $visibility);
1193 }
1194
1195 public static function isDisplayName($name)
1196 {
1197 return $name == self::DN_FULL || $name == self::DN_DISPLAY
1198 || $name == self::DN_YOURSELF || $name == self::DN_DIRECTORY
1199 || $name == self::DN_PRIVATE || $name == self::DN_PUBLIC
1200 || $name == self::DN_SHORT || $name == self::DN_SORT;
1201 }
1202
1203 /** Returns the closest "accounts only" name type for $name
1204 */
1205 public static function getAccountEquivalentName($name)
1206 {
1207 switch ($name)
1208 {
1209 case self::DN_DIRECTORY:
1210 case self::DN_SORT:
1211 return 'directory_name';
1212 case self::DN_FULL:
1213 case self::DN_PUBLIC:
1214 return 'full_name';
1215 case self::DN_PRIVATE:
1216 case self::DN_SHORT:
1217 case self::DN_YOURSELF:
1218 default:
1219 return 'display_name';
1220 }
1221 }
1222
1223 public static function rebuildSearchTokens($pids, $transaction = true)
1224 {
1225 require_once 'name.func.inc.php';
1226 if (!is_array($pids)) {
1227 $pids = array($pids);
1228 }
1229 $keys = XDB::iterator("(SELECT pid, name, type, IF(type = 'nickname', 2, 1) AS score, '' AS public
1230 FROM profile_private_names
1231 WHERE pid IN {?})
1232 UNION
1233 (SELECT pid, lastname_main, 'lastname' AS type, 10 AS score, 'public' AS public
1234 FROM profile_public_names
1235 WHERE lastname_main != '' AND pid IN {?})
1236 UNION
1237 (SELECT pid, lastname_marital, 'lastname' AS type, 10 AS score, 'public' AS public
1238 FROM profile_public_names
1239 WHERE lastname_marital != '' AND pid IN {?})
1240 UNION
1241 (SELECT pid, lastname_ordinary, 'lastname' AS type, 10 AS score, 'public' AS public
1242 FROM profile_public_names
1243 WHERE lastname_ordinary != '' AND pid IN {?})
1244 UNION
1245 (SELECT pid, firstname_main, 'firstname' AS type, 10 AS score, 'public' AS public
1246 FROM profile_public_names
1247 WHERE firstname_main != '' AND pid IN {?})
1248 UNION
1249 (SELECT pid, firstname_ordinary, 'firstname' AS type, 10 AS score, 'public' AS public
1250 FROM profile_public_names
1251 WHERE firstname_ordinary != '' AND pid IN {?})
1252 UNION
1253 (SELECT pid, pseudonym, 'nickname' AS type, 10 AS score, 'public' AS public
1254 FROM profile_public_names
1255 WHERE pseudonym != '' AND pid IN {?})",
1256 $pids, $pids, $pids, $pids, $pids, $pids, $pids);
1257 $names = array();
1258 while ($key = $keys->next()) {
1259 if ($key['name'] == '') {
1260 continue;
1261 }
1262 $pid = $key['pid'];
1263 $toks = split_name_for_search($key['name']);
1264 $toks = array_reverse($toks);
1265
1266 /* Split the score between the tokens to avoid the user to be over-rated.
1267 * Let says my user name is "Machin-Truc Bidule" and I also have a user named
1268 * 'Machin Truc'. Distributing the score force "Machin Truc" to be displayed
1269 * before "Machin-Truc" for both "Machin Truc" and "Machin" searches.
1270 */
1271 $eltScore = ceil(((float)$key['score'])/((float)count($toks)));
1272 $token = '';
1273 foreach ($toks as $tok) {
1274 $token = $tok . $token;
1275 $names["$pid-$token"] = XDB::format('({?}, {?}, {?}, {?}, {?}, {?})',
1276 $token, $pid, soundex_fr($token),
1277 $eltScore, $key['public'], $key['type']);
1278 }
1279 }
1280 if ($transaction) {
1281 XDB::startTransaction();
1282 }
1283 XDB::execute('DELETE FROM search_name
1284 WHERE pid IN {?}',
1285 $pids);
1286 if (count($names) > 0) {
1287 XDB::rawExecute('INSERT INTO search_name (token, pid, soundex, score, flags, general_type)
1288 VALUES ' . implode(', ', $names));
1289 }
1290 if ($transaction) {
1291 XDB::commit();
1292 }
1293 }
1294
1295 /** The school identifier consists of 6 digits. The first 3 represent the
1296 * promotion entry year. The last 3 indicate the student's rank.
1297 *
1298 * Our identifier consists of 8 digits and both half have the same role.
1299 * This enables us to deal with bigger promotions and with a wider range
1300 * of promotions.
1301 *
1302 * getSchoolId returns a school identifier given one of ours.
1303 * getXorgId returns a X.org identifier given a school identifier.
1304 */
1305 public static function getSchoolId($xorgId)
1306 {
1307 if (!preg_match('/^[0-9]{8}$/', $xorgId)) {
1308 return null;
1309 }
1310
1311 $year = intval(substr($xorgId, 0, 4));
1312 $rank = intval(substr($xorgId, 5, 3));
1313 if ($year < 1996) {
1314 return null;
1315 } elseif ($year < 2000) {
1316 $year = intval(substr(1900 - $year, 1, 3));
1317 return sprintf('%02u0%03u', $year, $rank);
1318 } else {
1319 $year = intval(substr(1900 - $year, 1, 3));
1320 return sprintf('%03u%03u', $year, $rank);
1321 }
1322 }
1323
1324 public static function getXorgId($schoolId)
1325 {
1326 if (!preg_match('/^[0-9]{6}$/', $schoolId)) {
1327 return null;
1328 }
1329
1330 $year = intval(substr($schoolId, 0, 3));
1331 $rank = intval(substr($schoolId, 3, 3));
1332
1333 if ($year > 200) {
1334 $year /= 10;
1335 }
1336 if ($year < 96) {
1337 return null;
1338 } else {
1339 return sprintf('%04u%04u', 1900 + $year, $rank);
1340 }
1341 }
1342 }
1343
1344
1345 /** Iterator over a set of Profiles
1346 */
1347 class ProfileIterator implements PlIterator
1348 {
1349 private $iterator = null;
1350 private $fields;
1351 private $visibility;
1352
1353 const FETCH_ALL = 0x000033F; // FETCH_ADDRESSES | FETCH_CORPS | FETCH_EDU | FETCH_JOBS | FETCH_MEDALS | FETCH_NETWORKING | FETCH_PHONES | FETCH_JOB_TERMS
1354
1355 public function __construct(PlIterator $it, array $pids, $fields = 0x0000, $visibility = null)
1356 {
1357 require_once 'profilefields.inc.php';
1358
1359 if ($visibility === null) {
1360 $visibility = Visibility::defaultForRead();
1361 }
1362
1363 $this->fields = $fields;
1364 $this->visibility = $visibility;
1365
1366 $subits = array();
1367 $callbacks = array();
1368
1369 $subits[0] = $it;
1370 $callbacks[0] = PlIteratorUtils::arrayValueCallback('pid');
1371 $cb = PlIteratorUtils::objectPropertyCallback('pid');
1372
1373 $fields = $fields & self::FETCH_ALL;
1374 for ($field = 1; $field < $fields; $field *= 2) {
1375 if (($fields & $field) ) {
1376 $callbacks[$field] = $cb;
1377 $subits[$field] = new ProfileFieldIterator($field, $pids, $visibility);
1378 }
1379 }
1380
1381 $this->iterator = PlIteratorUtils::parallelIterator($subits, $callbacks, 0);
1382 }
1383
1384 private function hasData($field, $vals)
1385 {
1386 return ($this->fields & $field) && ($vals[$field] != null);
1387 }
1388
1389 private function fillProfile(array $vals)
1390 {
1391 $pf = Profile::get($vals[0], 0x0, $this->visibility);
1392 $pf->setFetchedFields($this->fields);
1393
1394 if ($this->hasData(Profile::FETCH_PHONES, $vals)) {
1395 $pf->setPhones($vals[Profile::FETCH_PHONES]);
1396 }
1397 if ($this->hasData(Profile::FETCH_ADDRESSES, $vals)) {
1398 $pf->setAddresses($vals[Profile::FETCH_ADDRESSES]);
1399 }
1400 if ($this->hasData(Profile::FETCH_JOBS, $vals)) {
1401 $pf->setJobs($vals[Profile::FETCH_JOBS]);
1402 }
1403 if ($this->hasData(Profile::FETCH_JOB_TERMS, $vals)) {
1404 $pf->setJobTerms($vals[Profile::FETCH_JOB_TERMS]);
1405 }
1406
1407 if ($this->hasData(Profile::FETCH_CORPS, $vals)) {
1408 $pf->setCorps($vals[Profile::FETCH_CORPS]);
1409 }
1410 if ($this->hasData(Profile::FETCH_EDU, $vals)) {
1411 $pf->setEducations($vals[Profile::FETCH_EDU]);
1412 }
1413 if ($this->hasData(Profile::FETCH_MEDALS, $vals)) {
1414 $pf->setMedals($vals[Profile::FETCH_MEDALS]);
1415 }
1416 if ($this->hasData(Profile::FETCH_NETWORKING, $vals)) {
1417 $pf->setNetworking($vals[Profile::FETCH_NETWORKING]);
1418 }
1419
1420 return $pf;
1421 }
1422
1423 public function next()
1424 {
1425 $vals = $this->iterator->next();
1426 if ($vals == null) {
1427 return null;
1428 }
1429 return $this->fillProfile($vals);
1430 }
1431
1432 public function first()
1433 {
1434 return $this->iterator->first();
1435 }
1436
1437 public function last()
1438 {
1439 return $this->iterator->last();
1440 }
1441
1442 public function total()
1443 {
1444 return $this->iterator->total();
1445 }
1446 }
1447
1448 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1449 ?>