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