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