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