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