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