Updates statistics for m/d.
[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
57 static public $name_variants = array(
58 self::LASTNAME => array(self::VN_MARITAL, self::VN_ORDINARY),
59 self::FIRSTNAME => array(self::VN_ORDINARY, self::VN_INI, self::VN_OTHER)
60 );
61
62 const ADDRESS_MAIN = 0x00000001;
63 const ADDRESS_PERSO = 0x00000002;
64 const ADDRESS_PRO = 0x00000004;
65 const ADDRESS_ALL = 0x00000006;
66 const ADDRESS_POSTAL = 0x00000008;
67
68 const EDUCATION_MAIN = 0x00000010;
69 const EDUCATION_EXTRA = 0x00000020;
70 const EDUCATION_ALL = 0x00000040;
71 const EDUCATION_FINISHED = 0x00000080;
72 const EDUCATION_CURRENT = 0x00000100;
73
74 const JOBS_MAIN = 0x00001000;
75 const JOBS_ALL = 0x00002000;
76 const JOBS_FINISHED = 0x00004000;
77 const JOBS_CURRENT = 0x00008000;
78
79 const NETWORKING_ALL = 0x00070000;
80 const NETWORKING_WEB = 0x00010000;
81 const NETWORKING_IM = 0x00020000;
82 const NETWORKING_SOCIAL = 0x00040000;
83
84 const PHONE_LINK_JOB = 0x00100000;
85 const PHONE_LINK_ADDRESS = 0x00200000;
86 const PHONE_LINK_PROFILE = 0x00400000;
87 const PHONE_LINK_COMPANY = 0x00800000;
88 const PHONE_LINK_ANY = 0x00F00000;
89
90 const PHONE_TYPE_FAX = 0x01000000;
91 const PHONE_TYPE_FIXED = 0x02000000;
92 const PHONE_TYPE_MOBILE = 0x04000000;
93 const PHONE_TYPE_ANY = 0x07000000;
94
95 const PHONE_ANY = 0x07F00000;
96
97 const FETCH_ADDRESSES = 0x000001;
98 const FETCH_CORPS = 0x000002;
99 const FETCH_EDU = 0x000004;
100 const FETCH_JOBS = 0x000008;
101 const FETCH_MEDALS = 0x000010;
102 const FETCH_NETWORKING = 0x000020;
103 const FETCH_MENTOR_COUNTRY = 0x000080;
104 const FETCH_PHONES = 0x000100;
105 const FETCH_JOB_TERMS = 0x000200;
106 const FETCH_MENTOR_TERMS = 0x000400;
107
108 const FETCH_MINIFICHES = 0x00012D; // FETCH_ADDRESSES | FETCH_EDU | FETCH_JOBS | FETCH_NETWORKING | FETCH_PHONES
109
110 const FETCH_ALL = 0x0007FF; // OR of FETCH_*
111
112 static public $descriptions = array(
113 'search_names' => 'Noms',
114 'nationality1' => 'Nationalité',
115 'nationality2' => '2e nationalité',
116 'nationality3' => '3e nationalité',
117 'promo_display' => 'Promotion affichée',
118 'email_directory' => 'Email annuaire papier',
119 'networking' => 'Messageries…',
120 'tels' => 'Téléphones',
121 'edus' => 'Formations',
122 'main_edus' => 'Formations à l\'X',
123 'promo' => 'Promotion de sortie',
124 'birthdate' => 'Date de naissance',
125 'yourself' => 'Nom affiché',
126 'freetext' => 'Commentaire',
127 'freetext_pub' => 'Affichage du commentaire',
128 'photo' => 'Photographie',
129 'photo_pub' => 'Affichage de la photographie',
130 'addresses' => 'Adresses',
131 'corps' => 'Corps',
132 'cv' => 'CV',
133 'jobs' => 'Emplois',
134 'section' => 'Section',
135 'binets' => 'Binets',
136 'medals' => 'Décorations',
137 'medals_pub' => 'Affichage des décorations',
138 'competences' => 'Compétences',
139 'langues' => 'Langues',
140 'expertise' => 'Expertises (mentoring)',
141 'terms' => 'Compétences (mentoring)',
142 'countries' => 'Pays (mentoring)'
143 );
144
145 private $fetched_fields = 0x000000;
146
147 private $pid;
148 private $hrpid;
149 private $owner;
150 private $owner_fetched = false;
151 private $data = array();
152
153 private $visibility = null;
154
155
156 private function __construct(array $data)
157 {
158 $this->data = $data;
159 $this->pid = $this->data['pid'];
160 $this->hrpid = $this->data['hrpid'];
161 $this->visibility = new ProfileVisibility();
162 }
163
164 public function id()
165 {
166 return $this->pid;
167 }
168
169 public function hrid()
170 {
171 return $this->hrpid;
172 }
173
174 public function owner()
175 {
176 if ($this->owner == null && !$this->owner_fetched) {
177 $this->owner_fetched = true;
178 $this->owner = User::getSilent($this);
179 }
180 return $this->owner;
181 }
182
183 public function isActive()
184 {
185 if ($this->owner()) {
186 return $this->owner->isActive();
187 }
188 return false;
189 }
190
191 public function promo($details = false)
192 {
193 if ($details && ($this->program || $this->fieldid)) {
194 $text = array();
195 if ($this->program) {
196 $text[] = $this->program;
197 }
198 if ($this->fieldid) {
199 $fieldsList = DirEnum::getOptions(DirEnum::EDUFIELDS);
200 $text[] = $fieldsList[$this->fieldid];
201 }
202 return $this->promo . ' (' . implode(', ', $text) . ')';
203 }
204
205 return $this->promo;
206 }
207
208 public function yearpromo()
209 {
210 return $this->promo_year;
211 }
212
213 /** Check if user is an orange (associated with several promos)
214 */
215 public function isMultiPromo()
216 {
217 return $this->grad_year != $this->entry_year + $this->mainEducationDuration();
218 }
219
220 /** Returns an array with all associated promo years.
221 */
222 public function yearspromo()
223 {
224 $promos = array();
225 $d = -$this->deltaPromoToGradYear();
226 for ($g = $this->entry_year + $this->mainEducationDuration(); $g <= $this->grad_year; ++$g) {
227 $promos[] = $g + $d;
228 }
229 return $promos;
230 }
231
232 public function mainEducation()
233 {
234 if (empty($this->promo)) {
235 return null;
236 } else {
237 return $this->promo{0};
238 }
239 }
240
241 public function mainGrade()
242 {
243 switch ($this->mainEducation()) {
244 case 'X':
245 return UserFilter::GRADE_ING;
246 case 'M':
247 return UserFilter::GRADE_MST;
248 case 'D':
249 return UserFilter::GRADE_PHD;
250 default:
251 return null;
252 }
253 }
254
255 public function mainEducationDuration()
256 {
257 switch ($this->mainEducation()) {
258 case 'X':
259 return 3;
260 case 'M':
261 return 2;
262 case 'D':
263 return 3;
264 default:
265 return 0;
266 }
267 }
268
269 /** Number of years between the promotion year until the
270 * graduation year. In standard schools it's 0, but for
271 * Polytechnique the promo year is the entry year.
272 */
273 public function deltaPromoToGradYear()
274 {
275 if ($this->mainEducation() == 'X') {
276 return $this->mainEducationDuration();
277 }
278 return 0;
279 }
280
281 /** Print a name with the given formatting:
282 * %s = • for women
283 * %f = firstname
284 * %l = lastname
285 * %F = fullname
286 * %S = shortname
287 * %p = promo
288 */
289 public function name($format)
290 {
291 return str_replace(array('%s', '%f', '%l', '%F', '%S', '%p'),
292 array($this->isFemale() ? '•' : '',
293 $this->firstName(), $this->lastName(),
294 $this->fullName(), $this->shortName(),
295 $this->promo()), $format);
296 }
297
298 public function fullName($with_promo = false)
299 {
300 if ($with_promo) {
301 return $this->full_name . ' (' . $this->promo . ')';
302 }
303 return $this->full_name;
304 }
305
306 public function shortName($with_promo = false)
307 {
308 if ($with_promo) {
309 return $this->short_name . ' (' . $this->promo . ')';
310 }
311 return $this->short_name;
312 }
313
314 public function firstName()
315 {
316 return $this->firstname;
317 }
318
319 public function firstNames()
320 {
321 return $this->nameVariants(self::FIRSTNAME);
322 }
323
324 public function lastName()
325 {
326 return $this->lastname;
327 }
328
329 public function lastNames()
330 {
331 return $this->nameVariants(self::LASTNAME);
332 }
333
334 public function isFemale()
335 {
336 return $this->sex == PlUser::GENDER_FEMALE;
337 }
338
339 public function isDead()
340 {
341 return ($this->deathdate != null);
342 }
343
344 public function displayEmail()
345 {
346 $o = $this->owner();
347 if ($o != null) {
348 return $o->bestEmail();
349 } else {
350 return $this->email_directory;
351 }
352 }
353
354 public function data()
355 {
356 $this->first_name;
357 return $this->data;
358 }
359
360 private function nameVariants($type)
361 {
362 $vals = array($this->$type);
363 foreach (self::$name_variants[$type] as $var) {
364 $vartype = $type . '_' . $var;
365 $varname = $this->$vartype;
366 if ($varname != null && $varname != "") {
367 $vals[] = $varname;
368 }
369 }
370 return array_unique($vals);
371 }
372
373 public function nationalities()
374 {
375 $nats = array();
376 $countries = DirEnum::getOptions(DirEnum::COUNTRIES);
377 if ($this->nationality1) {
378 $nats[$this->nationality1] = $countries[$this->nationality1];
379 }
380 if ($this->nationality2) {
381 $nats[$this->nationality2] = $countries[$this->nationality2];
382 }
383 if ($this->nationality3) {
384 $nats[$this->nationality3] = $countries[$this->nationality3];
385 }
386 return $nats;
387 }
388
389 public function __get($name)
390 {
391 if (property_exists($this, $name)) {
392 return $this->$name;
393 }
394
395 if (isset($this->data[$name])) {
396 return $this->data[$name];
397 }
398
399 return null;
400 }
401
402 public function __isset($name)
403 {
404 return property_exists($this, $name) || isset($this->data[$name]);
405 }
406
407 public function __unset($name)
408 {
409 if (property_exists($this, $name)) {
410 $this->$name = null;
411 } else {
412 unset($this->data[$name]);
413 }
414 }
415
416
417 /**
418 * Clears a profile.
419 * *always deletes in: profile_addresses, profile_binets, profile_job,
420 * profile_langskills, profile_mentor, profile_networking,
421 * profile_phones, profile_skills, watch_profile
422 * *always keeps in: profile_corps, profile_display, profile_education,
423 * profile_medals, profile_name, profile_photos, search_name
424 * *modifies: profiles
425 */
426 public function clear()
427 {
428 $tables = array(
429 'profile_job', 'profile_langskills', 'profile_mentor',
430 'profile_networking', 'profile_skills', 'watch_profile',
431 'profile_phones', 'profile_addresses', 'profile_binets');
432
433 foreach ($tables as $t) {
434 XDB::execute('DELETE FROM ' . $t . '
435 WHERE pid = {?}',
436 $this->id());
437 }
438
439 XDB::execute("UPDATE profiles
440 SET cv = NULL, freetext = NULL, freetext_pub = 'private',
441 medals_pub = 'private', alias_pub = 'private',
442 email_directory = NULL
443 WHERE pid = {?}",
444 $this->id());
445 }
446
447 /** Sets the level of visibility of the profile
448 * Sets $this->visibility to a list of valid visibilities.
449 * @param one of the self::VIS_* values
450 */
451 public function setVisibilityLevel($visibility)
452 {
453 $this->visibility->setLevel($visibility);
454 }
455
456 /** Determine whether an item with visibility $visibility can be displayed
457 * with the current level of visibility of the profile
458 * @param $visibility The level of visibility to be checked
459 */
460 public function isVisible($visibility)
461 {
462 return $this->visibility->isVisible($visibility);
463 }
464
465 /** Stores the list of fields which have already been fetched for this Profile
466 */
467 public function setFetchedFields($fields)
468 {
469 if (($fields | self::FETCH_ALL) != self::FETCH_ALL) {
470 Platal::page()->kill("Invalid fetched fields: $fields");
471 }
472
473 $this->fetched_fields = $fields;
474 }
475
476 /** Have we already fetched this field ?
477 */
478 private function fetched($field)
479 {
480 if (!array_key_exists($field, ProfileField::$fields)) {
481 Platal::page()->kill("Invalid field: $field");
482 }
483
484 return ($this->fetched_fields & $field);
485 }
486
487 /** If not already done, fetches data for the given field
488 * @param $field One of the Profile::FETCH_*
489 * @return A ProfileField, or null
490 */
491 private function getProfileField($field)
492 {
493 if (!array_key_exists($field, ProfileField::$fields)) {
494 Platal::page()->kill("Invalid field: $field");
495 }
496 if ($this->fetched($field)) {
497 return null;
498 } else {
499 $this->fetched_fields = $this->fetched_fields | $field;
500 }
501
502 $cls = ProfileField::$fields[$field];
503
504 return ProfileField::getForPID($cls, $this->id(), $this->visibility);
505 }
506
507 /** Consolidates internal data (addresses, phones, jobs)
508 */
509 private function consolidateFields()
510 {
511 // Link phones to addresses
512 if ($this->phones != null) {
513 if ($this->addresses != null) {
514 $this->addresses->addPhones($this->phones);
515 }
516
517 if ($this->jobs != null) {
518 $this->jobs->addPhones($this->phones);
519 }
520 }
521
522 // Link addresses to jobs
523 if ($this->addresses != null && $this->jobs != null) {
524 $this->jobs->addAddresses($this->addresses);
525 }
526
527 // Link jobterms to jobs
528 if ($this->jobs != null && $this->jobterms != null) {
529 $this->jobs->addJobTerms($this->jobterms);
530 }
531 }
532
533 /* Photo
534 */
535 private $photo = null;
536 public function getPhoto($fallback = true, $data = false)
537 {
538 if ($this->has_photo) {
539 if ($data && ($this->photo == null || $this->photo->mimeType == null)) {
540 $res = XDB::fetchOneAssoc('SELECT attach, attachmime, x, y, last_update
541 FROM profile_photos
542 WHERE pid = {?}', $this->pid);
543 $this->photo = PlImage::fromData($res['attach'], 'image/' .$res['attachmime'], $res['x'], $res['y'], $res['last_update']);
544 } else if ($this->photo == null) {
545 $this->photo = PlImage::fromData(null, null, $this->photo_width, $this->photo_height);
546 }
547 return $this->photo;
548 } else if ($fallback) {
549 if ($this->mainEducation() == 'X') {
550 return PlImage::fromFile(dirname(__FILE__) . '/../htdocs/images/none_x.png', 'image/png');
551 }
552 return PlImage::fromFile(dirname(__FILE__) . '/../htdocs/images/none_md.png', 'image/png');
553 }
554 return null;
555 }
556
557 /* Addresses
558 */
559 private $addresses = null;
560 public function setAddresses(ProfileAddresses $addr)
561 {
562 $this->addresses = $addr;
563 $this->consolidateFields();
564 }
565
566 private function fetchAddresses()
567 {
568 if ($this->addresses == null && !$this->fetched(self::FETCH_ADDRESSES)) {
569 $addr = $this->getProfileField(self::FETCH_ADDRESSES);
570 if ($addr) {
571 $this->setAddresses($addr);
572 $this->fetchPhones();
573 }
574 }
575 }
576
577 public function getAddresses($flags, $limit = null)
578 {
579 $this->fetchAddresses();
580
581 if ($this->addresses == null) {
582 return array();
583 }
584 return $this->addresses->get($flags, $limit);
585 }
586
587 public function iterAddresses($flags, $limit = null)
588 {
589 return PlIteratorUtils::fromArray($this->getAddresses($flags, $limit), 1, true);
590 }
591
592 public function getMainAddress()
593 {
594 $main = $this->getAddresses(self::ADDRESS_MAIN);
595 $perso = $this->getAddresses(self::ADDRESS_PERSO);
596
597 if (count($main)) {
598 return array_pop($main);
599 } else if (count($perso)) {
600 return array_pop($perso);
601 } else {
602 return null;
603 }
604 }
605
606 /* Phones
607 */
608 private $phones = null;
609 public function setPhones(ProfilePhones $phones)
610 {
611 $this->phones = $phones;
612 $this->consolidateFields();
613 }
614
615 private function fetchPhones()
616 {
617 if ($this->phones == null && !$this->fetched(self::FETCH_PHONES)) {
618 $phones = $this->getProfileField(self::FETCH_PHONES);
619 if (isset($phones)) {
620 $this->setPhones($phones);
621 }
622 }
623 }
624
625 public function getPhones($flags, $limit = null)
626 {
627 $this->fetchPhones();
628 if ($this->phones == null) {
629 return array();
630 }
631 return $this->phones->get($flags, $limit);
632 }
633
634 /* Educations
635 */
636 private $educations = null;
637 public function setEducations(ProfileEducation $edu)
638 {
639 $this->educations = $edu;
640 }
641
642 public function getEducations($flags, $limit = null)
643 {
644 if ($this->educations == null && !$this->fetched(self::FETCH_EDU)) {
645 $this->setEducations($this->getProfileField(self::FETCH_EDU));
646 }
647
648 if ($this->educations == null) {
649 return array();
650 }
651 return $this->educations->get($flags, $limit);
652 }
653
654 public function getExtraEducations($limit = null)
655 {
656 return $this->getEducations(self::EDUCATION_EXTRA, $limit);
657 }
658
659 /* Corps
660 */
661 private $corps = null;
662 public function setCorps(ProfileCorps $corps)
663 {
664 $this->corps = $corps;
665 }
666
667 public function getCorps()
668 {
669 if ($this->corps == null && !$this->fetched(self::FETCH_CORPS)) {
670 $this->setCorps($this->getProfileField(self::FETCH_CORPS));
671 }
672 return $this->corps;
673 }
674
675 /** Networking
676 */
677 private $networks = null;
678 public function setNetworking(ProfileNetworking $nw)
679 {
680 $this->networks = $nw;
681 }
682
683 public function getNetworking($flags, $limit = null)
684 {
685 if ($this->networks == null && !$this->fetched(self::FETCH_NETWORKING)) {
686 $nw = $this->getProfileField(self::FETCH_NETWORKING);
687 if ($nw) {
688 $this->setNetworking($nw);
689 }
690 }
691 if ($this->networks == null) {
692 return array();
693 }
694 return $this->networks->get($flags, $limit);
695 }
696
697 public function getWebSite()
698 {
699 $site = $this->getNetworking(self::NETWORKING_WEB, 1);
700 if (count($site) != 1) {
701 return null;
702 }
703 $site = array_pop($site);
704 return $site;
705 }
706
707
708 /** Jobs
709 */
710 private $jobs = null;
711 public function setJobs(ProfileJobs $jobs)
712 {
713 $this->jobs = $jobs;
714 $this->consolidateFields();
715 }
716
717 private function fetchJobs()
718 {
719 if ($this->jobs == null && !$this->fetched(self::FETCH_JOBS)) {
720 $jobs = $this->getProfileField(self::FETCH_JOBS);
721 if ($jobs) {
722 $this->setJobs($jobs);
723 $this->fetchAddresses();
724 }
725 }
726 }
727
728 public function getJobs($flags, $limit = null)
729 {
730 $this->fetchJobs();
731
732 if ($this->jobs == null) {
733 return array();
734 }
735 return $this->jobs->get($flags, $limit);
736 }
737
738 public function getMainJob()
739 {
740 $job = $this->getJobs(self::JOBS_MAIN, 1);
741 if (count($job) != 1) {
742 return null;
743 }
744 return array_pop($job);
745 }
746
747 /** JobTerms
748 */
749 private $jobterms = null;
750 public function setJobTerms(ProfileJobTerms $jobterms)
751 {
752 $this->jobterms = $jobterms;
753 $this->consolidateFields();
754 }
755
756 private $mentor_countries = null;
757 public function setMentoringCountries(ProfileMentoringCountries $countries)
758 {
759 $this->mentor_countries = $countries;
760 }
761
762 public function getMentoringCountries()
763 {
764 if ($this->mentor_countries == null && !$this->fetched(self::FETCH_MENTOR_COUNTRY)) {
765 $this->setMentoringCountries($this->getProfileField(self::FETCH_MENTOR_COUNTRY));
766 }
767
768 if ($this->mentor_countries == null) {
769 return array();
770 } else {
771 return $this->mentor_countries->countries;
772 }
773 }
774
775 /** List of job terms to specify mentoring */
776 private $mentor_terms = null;
777 /**
778 * set job terms to specify mentoring
779 * @param $terms a ProfileMentoringTerms object listing terms only for this profile
780 */
781 public function setMentoringTerms(ProfileMentoringTerms $terms)
782 {
783 $this->mentor_terms = $terms;
784 }
785 /**
786 * get all job terms that specify mentoring
787 * @return an array of JobTerms objects
788 */
789 public function getMentoringTerms()
790 {
791 if ($this->mentor_terms == null && !$this->fetched(self::FETCH_MENTOR_TERMS)) {
792 $this->setMentoringTerms($this->getProfileField(self::FETCH_MENTOR_TERMS));
793 }
794
795 if ($this->mentor_terms == null) {
796 return array();
797 } else {
798 return $this->mentor_terms->get();
799 }
800 }
801
802
803 /* Binets
804 */
805 public function getBinets()
806 {
807 if ($this->visibility->isVisible(ProfileVisibility::VIS_PRIVATE)) {
808 return XDB::fetchColumn('SELECT binet_id
809 FROM profile_binets
810 WHERE pid = {?}', $this->id());
811 } else {
812 return array();
813 }
814 }
815 public function getBinetsNames()
816 {
817 if ($this->visibility->isVisible(ProfileVisibility::VIS_PRIVATE)) {
818 return XDB::fetchColumn('SELECT text
819 FROM profile_binets AS pb
820 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
821 WHERE pb.pid = {?}', $this->id());
822 } else {
823 return array();
824 }
825 }
826
827 /* Medals
828 */
829 private $medals = null;
830 public function setMedals(ProfileMedals $medals)
831 {
832 $this->medals = $medals;
833 }
834
835 public function getMedals()
836 {
837 if ($this->medals == null && !$this->fetched(self::FETCH_MEDALS)) {
838 $this->setMedals($this->getProfileField(self::FETCH_MEDALS));
839 }
840 if ($this->medals == null) {
841 return array();
842 }
843 return $this->medals->medals;
844 }
845
846 public function compareNames($firstname, $lastname)
847 {
848 $_lastname = mb_strtoupper($this->lastName());
849 $_firstname = mb_strtoupper($this->firstName());
850 $lastname = mb_strtoupper($lastname);
851 $firstname = mb_strtoupper($firstname);
852
853 $isOk = (mb_strtoupper($_firstname) == mb_strtoupper($firstname));
854 $tokens = preg_split("/[ \-']/", $lastname, -1, PREG_SPLIT_NO_EMPTY);
855 $maxlen = 0;
856
857 foreach ($tokens as $str) {
858 $isOk &= (strpos($_lastname, $str) !== false);
859 $maxlen = max($maxlen, strlen($str));
860 }
861
862 return ($isOk && ($maxlen > 2 || $maxlen == strlen($_lastname)));
863 }
864
865 /* Export to JSON
866 */
867 public function export()
868 {
869 return array(
870 'hrpid' => $this->hrid(),
871 'display_name' => $this->shortName(),
872 'full_name' => $this->fullName(),
873 'directory_name' => $this->directory_name,
874 'promo' => $this->promo(),
875 'year_promo' => $this->yearpromo(),
876 'is_active' => $this->isActive(),
877 'first_name' => $this->firstName(),
878 'last_name' => $this->lastName(),
879 'is_female' => $this->isFemale(),
880 );
881 }
882
883 private static function fetchProfileData(array $pids, $respect_order = true, $fields = 0x0000, $visibility = null)
884 {
885 if (count($pids) == 0) {
886 return null;
887 }
888
889 if ($respect_order) {
890 $order = 'ORDER BY ' . XDB::formatCustomOrder('p.pid', $pids);
891 } else {
892 $order = '';
893 }
894
895 $visibility = new ProfileVisibility($visibility);
896
897 $it = XDB::Iterator('SELECT p.pid, p.hrpid, p.xorg_id, p.ax_id, p.birthdate, p.birthdate_ref,
898 p.next_birthday, p.deathdate, p.deathdate_rec, p.sex = \'female\' AS sex,
899 IF ({?}, p.cv, NULL) AS cv, p.medals_pub, p.alias_pub, p.email_directory,
900 p.last_change, p.nationality1, p.nationality2, p.nationality3,
901 IF (p.freetext_pub IN {?}, p.freetext, NULL) AS freetext,
902 pe.entry_year, pe.grad_year, pe.promo_year, pe.program, pe.fieldid,
903 IF ({?}, pse.text, NULL) AS section,
904 pn_f.name AS firstname, pn_l.name AS lastname,
905 IF( {?}, pn_n.name, NULL) AS nickname,
906 IF(pn_uf.name IS NULL, pn_f.name, pn_uf.name) AS firstname_ordinary,
907 IF(pn_ul.name IS NULL, pn_l.name, pn_ul.name) AS lastname_ordinary,
908 pd.yourself, pd.promo, pd.short_name, pd.public_name AS full_name,
909 pd.directory_name, pd.public_name, pd.private_name,
910 IF(pp.pub IN {?}, pp.display_tel, NULL) AS mobile,
911 (ph.pub IN {?} AND ph.attach IS NOT NULL) AS has_photo,
912 ph.x AS photo_width, ph.y AS photo_height,
913 p.last_change < DATE_SUB(NOW(), INTERVAL 365 DAY) AS is_old,
914 pm.expertise AS mentor_expertise,
915 ap.uid AS owner_id
916 FROM profiles AS p
917 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
918 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
919 LEFT JOIN profile_section_enum AS pse ON (pse.id = p.section)
920 INNER JOIN profile_name AS pn_f ON (pn_f.pid = p.pid
921 AND pn_f.typeid = ' . self::getNameTypeId('firstname', true) . ')
922 INNER JOIN profile_name AS pn_l ON (pn_l.pid = p.pid
923 AND pn_l.typeid = ' . self::getNameTypeId('lastname', true) . ')
924 LEFT JOIN profile_name AS pn_uf ON (pn_uf.pid = p.pid
925 AND pn_uf.typeid = ' . self::getNameTypeId('firstname_ordinary', true) . ')
926 LEFT JOIN profile_name AS pn_ul ON (pn_ul.pid = p.pid
927 AND pn_ul.typeid = ' . self::getNameTypeId('lastname_ordinary', true) . ')
928 LEFT JOIN profile_name AS pn_n ON (pn_n.pid = p.pid
929 AND pn_n.typeid = ' . self::getNameTypeId('nickname', true) . ')
930 LEFT JOIN profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = \'user\' AND tel_type = \'mobile\')
931 LEFT JOIN profile_photos AS ph ON (ph.pid = p.pid)
932 LEFT JOIN profile_mentor AS pm ON (pm.pid = p.pid)
933 LEFT JOIN account_profiles AS ap ON (ap.pid = p.pid AND FIND_IN_SET(\'owner\', ap.perms))
934 WHERE p.pid IN {?}
935 GROUP BY p.pid
936 ' . $order,
937 $visibility->isVisible(ProfileVisibility::VIS_PRIVATE), // CV
938 $visibility->levels(), // freetext
939 $visibility->isVisible(ProfileVisibility::VIS_PRIVATE), // section
940 $visibility->isVisible(ProfileVisibility::VIS_PRIVATE), // nickname
941 $visibility->levels(), // mobile
942 $visibility->levels(), // photo
943 $pids
944 );
945 return new ProfileIterator($it, $pids, $fields, $visibility);
946 }
947
948 public static function getPID($login)
949 {
950 if ($login instanceof PlUser) {
951 return XDB::fetchOneCell('SELECT pid
952 FROM account_profiles
953 WHERE uid = {?} AND FIND_IN_SET(\'owner\', perms)',
954 $login->id());
955 } else if (ctype_digit($login)) {
956 return XDB::fetchOneCell('SELECT pid
957 FROM profiles
958 WHERE pid = {?}', $login);
959 } else {
960 return XDB::fetchOneCell('SELECT pid
961 FROM profiles
962 WHERE hrpid = {?}', $login);
963 }
964 }
965
966 public static function getPIDsFromUIDs($uids, $respect_order = true)
967 {
968 if ($respect_order) {
969 $order = 'ORDER BY ' . XDB::formatCustomOrder('uid', $uids);
970 } else {
971 $order = '';
972 }
973 return XDB::fetchAllAssoc('uid', 'SELECT ap.uid, ap.pid
974 FROM account_profiles AS ap
975 WHERE FIND_IN_SET(\'owner\', ap.perms)
976 AND ap.uid IN ' . XDB::formatArray($uids) .'
977 ' . $order);
978 }
979
980 /** Return the profile associated with the given login.
981 */
982 public static function get($login, $fields = 0x0000, $visibility = null)
983 {
984 if (is_array($login)) {
985 $pf = new Profile($login);
986 $pf->setVisibilityLevel($visibility);
987 return $pf;
988 }
989 $pid = self::getPID($login);
990 if (!is_null($pid)) {
991 $it = self::iterOverPIDs(array($pid), false, $fields, $visibility);
992 return $it->next();
993 } else {
994 /* Let say we can identify a profile using the identifiers of its owner.
995 */
996 if (!($login instanceof PlUser)) {
997 $user = User::getSilent($login);
998 if ($user && $user->hasProfile()) {
999 return $user->profile();
1000 }
1001 }
1002 return null;
1003 }
1004 }
1005
1006 public static function iterOverUIDs($uids, $respect_order = true, $fields = 0x0000, $visibility = null)
1007 {
1008 return self::iterOverPIDs(self::getPIDsFromUIDs($uids), $respect_order, $fields, $visibility);
1009 }
1010
1011 public static function iterOverPIDs($pids, $respect_order = true, $fields = 0x0000, $visibility = null)
1012 {
1013 return self::fetchProfileData($pids, $respect_order, $fields, $visibility);
1014 }
1015
1016 /** Return profiles for the list of pids.
1017 */
1018 public static function getBulkProfilesWithPIDs(array $pids, $fields = 0x0000, $visibility = null)
1019 {
1020 if (count($pids) == 0) {
1021 return array();
1022 }
1023 $it = self::iterOverPIDs($pids, true, $fields, $visibility);
1024 $profiles = array();
1025 while ($p = $it->next()) {
1026 $profiles[$p->id()] = $p;
1027 }
1028 return $profiles;
1029 }
1030
1031 /** Return profiles for uids.
1032 */
1033 public static function getBulkProfilesWithUIDS(array $uids, $fields = 0x000, $visibility = null)
1034 {
1035 if (count($uids) == 0) {
1036 return array();
1037 }
1038 return self::getBulkProfilesWithPIDs(self::getPIDsFromUIDs($uids), $fields, $visibility);
1039 }
1040
1041 public static function isDisplayName($name)
1042 {
1043 return $name == self::DN_FULL || $name == self::DN_DISPLAY
1044 || $name == self::DN_YOURSELF || $name == self::DN_DIRECTORY
1045 || $name == self::DN_PRIVATE || $name == self::DN_PUBLIC
1046 || $name == self::DN_SHORT || $name == self::DN_SORT;
1047 }
1048
1049 /** Returns the closest "accounts only" name type for $name
1050 */
1051 public static function getAccountEquivalentName($name)
1052 {
1053 switch ($name)
1054 {
1055 case self::DN_DIRECTORY:
1056 case self::DN_SORT:
1057 return 'directory_name';
1058 case self::DN_FULL:
1059 case self::DN_PUBLIC:
1060 return 'full_name';
1061 case self::DN_PRIVATE:
1062 case self::DN_SHORT:
1063 case self::DN_YOURSELF:
1064 default:
1065 return 'display_name';
1066 }
1067 }
1068
1069 public static function getNameTypeId($type, $for_sql = false)
1070 {
1071 if (!S::has('name_types')) {
1072 $table = XDB::fetchAllAssoc('type', 'SELECT id, type
1073 FROM profile_name_enum');
1074 S::set('name_types', $table);
1075 } else {
1076 $table = S::v('name_types');
1077 }
1078 if ($for_sql) {
1079 return XDB::escape($table[$type]);
1080 } else {
1081 return $table[$type];
1082 }
1083 }
1084
1085 public static function rebuildSearchTokens($pids, $transaction = true)
1086 {
1087 if (!is_array($pids)) {
1088 $pids = array($pids);
1089 }
1090 $keys = XDB::iterator("(SELECT n.pid AS pid, n.name AS name, e.score AS score,
1091 IF(FIND_IN_SET('public', e.flags), 'public', '') AS public
1092 FROM profile_name AS n
1093 INNER JOIN profile_name_enum AS e ON (n.typeid = e.id)
1094 WHERE n.pid IN {?} AND NOT FIND_IN_SET('not_displayed', e.flags))
1095 UNION
1096 (SELECT n.pid AS pid, n.particle AS name, 0 AS score,
1097 IF(FIND_IN_SET('public', e.flags), 'public', '') AS public
1098 FROM profile_name AS n
1099 INNER JOIN profile_name_enum AS e ON (n.typeid = e.id)
1100 WHERE n.pid IN {?} AND NOT FIND_IN_SET('not_displayed', e.flags))
1101 ",
1102 $pids, $pids);
1103 $names = array();
1104 while ($key = $keys->next()) {
1105 if ($key['name'] == '') {
1106 continue;
1107 }
1108 $pid = $key['pid'];
1109 require_once 'name.func.inc.php';
1110 $toks = split_name_for_search($key['name']);
1111 $toks = array_reverse($toks);
1112
1113 /* Split the score between the tokens to avoid the user to be over-rated.
1114 * Let says my user name is "Machin-Truc Bidule" and I also have a user named
1115 * 'Machin Truc'. Distributing the score force "Machin Truc" to be displayed
1116 * before "Machin-Truc" for both "Machin Truc" and "Machin" searches.
1117 */
1118 $eltScore = ceil(((float)$key['score'])/((float)count($toks)));
1119 $token = '';
1120 foreach ($toks as $tok) {
1121 $token = $tok . $token;
1122 $names["$pid-$token"] = XDB::format('({?}, {?}, {?}, {?}, {?})',
1123 $token, $pid, soundex_fr($token),
1124 $eltScore, $key['public']);
1125 }
1126 }
1127 if ($transaction) {
1128 XDB::startTransaction();
1129 }
1130 XDB::execute('DELETE FROM search_name
1131 WHERE pid IN {?}',
1132 $pids);
1133 if (count($names) > 0) {
1134 XDB::rawExecute('INSERT INTO search_name (token, pid, soundex, score, flags)
1135 VALUES ' . implode(', ', $names));
1136 }
1137 if ($transaction) {
1138 XDB::commit();
1139 }
1140 }
1141
1142 /** The school identifier consists of 6 digits. The first 3 represent the
1143 * promotion entry year. The last 3 indicate the student's rank.
1144 *
1145 * Our identifier consists of 8 digits and both half have the same role.
1146 * This enables us to deal with bigger promotions and with a wider range
1147 * of promotions.
1148 *
1149 * getSchoolId returns a school identifier given one of ours.
1150 * getXorgId returns a X.org identifier given a school identifier.
1151 */
1152 public static function getSchoolId($xorgId)
1153 {
1154 if (!preg_match('/^[0-9]{8}$/', $xorgId)) {
1155 return null;
1156 }
1157
1158 $year = intval(substr($xorgId, 0, 4));
1159 $rank = intval(substr($xorgId, 5, 3));
1160 if ($year < 1996) {
1161 return null;
1162 } elseif ($year < 2000) {
1163 $year = intval(substr(1900 - $year, 1, 3));
1164 return sprintf('%02u0%03u', $year, $rank);
1165 } else {
1166 $year = intval(substr(1900 - $year, 1, 3));
1167 return sprintf('%03u%03u', $year, $rank);
1168 }
1169 }
1170
1171 public static function getXorgId($schoolId)
1172 {
1173 if (!preg_match('/^[0-9]{6}$/', $schoolId)) {
1174 return null;
1175 }
1176
1177 $year = intval(substr($schoolId, 0, 3));
1178 $rank = intval(substr($schoolId, 3, 3));
1179
1180 if ($year > 200) {
1181 $year /= 10;
1182 }
1183 if ($year < 96) {
1184 return null;
1185 } else {
1186 return sprintf('%04u%04u', 1900 + $year, $rank);
1187 }
1188 }
1189 }
1190
1191
1192 /** Iterator over a set of Profiles
1193 */
1194 class ProfileIterator implements PlIterator
1195 {
1196 private $iterator = null;
1197 private $fields;
1198 private $visibility;
1199
1200 const FETCH_ALL = 0x000033F; // FETCH_ADDRESSES | FETCH_CORPS | FETCH_EDU | FETCH_JOBS | FETCH_MEDALS | FETCH_NETWORKING | FETCH_PHONES | FETCH_JOB_TERMS
1201
1202 public function __construct(PlIterator $it, array $pids, $fields = 0x0000, ProfileVisibility $visibility = null)
1203 {
1204 require_once 'profilefields.inc.php';
1205
1206 if ($visibility == null) {
1207 $visibility = new ProfileVisibility();
1208 }
1209
1210 $this->fields = $fields;
1211 $this->visibility = $visibility;
1212
1213 $subits = array();
1214 $callbacks = array();
1215
1216 $subits[0] = $it;
1217 $callbacks[0] = PlIteratorUtils::arrayValueCallback('pid');
1218 $cb = PlIteratorUtils::objectPropertyCallback('pid');
1219
1220 $fields = $fields & self::FETCH_ALL;
1221 for ($field = 1; $field < $fields; $field *= 2) {
1222 if (($fields & $field) ) {
1223 $callbacks[$field] = $cb;
1224 $subits[$field] = new ProfileFieldIterator($field, $pids, $visibility);
1225 }
1226 }
1227
1228 $this->iterator = PlIteratorUtils::parallelIterator($subits, $callbacks, 0);
1229 }
1230
1231 private function hasData($field, $vals)
1232 {
1233 return ($this->fields & $field) && ($vals[$field] != null);
1234 }
1235
1236 private function fillProfile(array $vals)
1237 {
1238 $pf = Profile::get($vals[0]);
1239 $pf->setVisibilityLevel($this->visibility->level());
1240 $pf->setFetchedFields($this->fields);
1241
1242 if ($this->hasData(Profile::FETCH_PHONES, $vals)) {
1243 $pf->setPhones($vals[Profile::FETCH_PHONES]);
1244 }
1245 if ($this->hasData(Profile::FETCH_ADDRESSES, $vals)) {
1246 $pf->setAddresses($vals[Profile::FETCH_ADDRESSES]);
1247 }
1248 if ($this->hasData(Profile::FETCH_JOBS, $vals)) {
1249 $pf->setJobs($vals[Profile::FETCH_JOBS]);
1250 }
1251 if ($this->hasData(Profile::FETCH_JOB_TERMS, $vals)) {
1252 $pf->setJobTerms($vals[Profile::FETCH_JOB_TERMS]);
1253 }
1254
1255 if ($this->hasData(Profile::FETCH_CORPS, $vals)) {
1256 $pf->setCorps($vals[Profile::FETCH_CORPS]);
1257 }
1258 if ($this->hasData(Profile::FETCH_EDU, $vals)) {
1259 $pf->setEducations($vals[Profile::FETCH_EDU]);
1260 }
1261 if ($this->hasData(Profile::FETCH_MEDALS, $vals)) {
1262 $pf->setMedals($vals[Profile::FETCH_MEDALS]);
1263 }
1264 if ($this->hasData(Profile::FETCH_NETWORKING, $vals)) {
1265 $pf->setNetworking($vals[Profile::FETCH_NETWORKING]);
1266 }
1267
1268 return $pf;
1269 }
1270
1271 public function next()
1272 {
1273 $vals = $this->iterator->next();
1274 if ($vals == null) {
1275 return null;
1276 }
1277 return $this->fillProfile($vals);
1278 }
1279
1280 public function first()
1281 {
1282 return $this->iterator->first();
1283 }
1284
1285 public function last()
1286 {
1287 return $this->iterator->last();
1288 }
1289
1290 public function total()
1291 {
1292 return $this->iterator->total();
1293 }
1294 }
1295
1296 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1297 ?>