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