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