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