__destruct should be public.
[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
aaffb7b2 22class Profile implements PlExportable
1a9affb7 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 50
9fd2ca04
SJ
51 static public $cycles = array(
52 self::DEGREE_X => 'polytechnicien',
53 self::DEGREE_M => 'master',
54 self::DEGREE_D => 'docteur'
55 );
e4860774
SJ
56 static public $cycle_prefixes = array(
57 self::DEGREE_X => 'X',
58 self::DEGREE_M => 'M',
59 self::DEGREE_D => 'D'
60 );
9fd2ca04 61
913a4e90
RB
62 static public $name_variants = array(
63 self::LASTNAME => array(self::VN_MARITAL, self::VN_ORDINARY),
64 self::FIRSTNAME => array(self::VN_ORDINARY, self::VN_INI, self::VN_OTHER)
65 );
66
3c985c08
RB
67 const ADDRESS_MAIN = 0x00000001;
68 const ADDRESS_PERSO = 0x00000002;
69 const ADDRESS_PRO = 0x00000004;
70 const ADDRESS_ALL = 0x00000006;
71 const ADDRESS_POSTAL = 0x00000008;
72
73 const EDUCATION_MAIN = 0x00000010;
74 const EDUCATION_EXTRA = 0x00000020;
75 const EDUCATION_ALL = 0x00000040;
76 const EDUCATION_FINISHED = 0x00000080;
77 const EDUCATION_CURRENT = 0x00000100;
78
79 const JOBS_MAIN = 0x00001000;
80 const JOBS_ALL = 0x00002000;
81 const JOBS_FINISHED = 0x00004000;
82 const JOBS_CURRENT = 0x00008000;
83
34de4b20 84 const NETWORKING_ALL = 0x00070000;
3c985c08
RB
85 const NETWORKING_WEB = 0x00010000;
86 const NETWORKING_IM = 0x00020000;
87 const NETWORKING_SOCIAL = 0x00040000;
88
89 const PHONE_LINK_JOB = 0x00100000;
90 const PHONE_LINK_ADDRESS = 0x00200000;
91 const PHONE_LINK_PROFILE = 0x00400000;
92 const PHONE_LINK_COMPANY = 0x00800000;
93 const PHONE_LINK_ANY = 0x00F00000;
94
95 const PHONE_TYPE_FAX = 0x01000000;
96 const PHONE_TYPE_FIXED = 0x02000000;
97 const PHONE_TYPE_MOBILE = 0x04000000;
98 const PHONE_TYPE_ANY = 0x07000000;
99
100 const PHONE_ANY = 0x07F00000;
04a94b1d 101
4d1f0f6b
RB
102 const FETCH_ADDRESSES = 0x000001;
103 const FETCH_CORPS = 0x000002;
104 const FETCH_EDU = 0x000004;
105 const FETCH_JOBS = 0x000008;
106 const FETCH_MEDALS = 0x000010;
107 const FETCH_NETWORKING = 0x000020;
4d1f0f6b
RB
108 const FETCH_MENTOR_COUNTRY = 0x000080;
109 const FETCH_PHONES = 0x000100;
3ac45f10
PC
110 const FETCH_JOB_TERMS = 0x000200;
111 const FETCH_MENTOR_TERMS = 0x000400;
080632c7 112 const FETCH_DELTATEN = 0x000800;
148af7a9 113 const FETCH_PARTNER = 0x001000;
7e0635c2
SJ
114 const FETCH_SKILL = 0x002000;
115 const FETCH_LANGUAGE = 0x004000;
9f21bd15 116
4d1f0f6b 117 const FETCH_MINIFICHES = 0x00012D; // FETCH_ADDRESSES | FETCH_EDU | FETCH_JOBS | FETCH_NETWORKING | FETCH_PHONES
fa9994fa 118
7e0635c2 119 const FETCH_ALL = 0x007FFF; // OR of FETCH_*
6b5008ec 120
7a9680aa
SJ
121 static public $descriptions = array(
122 'search_names' => 'Noms',
123 'nationality1' => 'Nationalité',
124 'nationality2' => '2e nationalité',
125 'nationality3' => '3e nationalité',
126 'promo_display' => 'Promotion affichée',
127 'email_directory' => 'Email annuaire papier',
128 'networking' => 'Messageries…',
129 'tels' => 'Téléphones',
130 'edus' => 'Formations',
d7de04af 131 'main_edus' => 'Formations à l\'X',
7a9680aa
SJ
132 'promo' => 'Promotion de sortie',
133 'birthdate' => 'Date de naissance',
134 'yourself' => 'Nom affiché',
135 'freetext' => 'Commentaire',
136 'freetext_pub' => 'Affichage du commentaire',
137 'photo' => 'Photographie',
138 'photo_pub' => 'Affichage de la photographie',
139 'addresses' => 'Adresses',
140 'corps' => 'Corps',
141 'cv' => 'CV',
142 'jobs' => 'Emplois',
143 'section' => 'Section',
144 'binets' => 'Binets',
145 'medals' => 'Décorations',
146 'medals_pub' => 'Affichage des décorations',
147 'competences' => 'Compétences',
148 'langues' => 'Langues',
149 'expertise' => 'Expertises (mentoring)',
150 'terms' => 'Compétences (mentoring)',
080632c7
RB
151 'countries' => 'Pays (mentoring)',
152 'deltaten' => 'Opération N N-10',
7a9680aa
SJ
153 );
154
1f8250e4
RB
155 private $fetched_fields = 0x000000;
156
e7b93962
FB
157 private $pid;
158 private $hrpid;
564e2b2a
RB
159 private $owner;
160 private $owner_fetched = false;
3e53a496
FB
161 private $data = array();
162
f5642983
FB
163 private $visibility = null;
164
1f8250e4 165
22771578 166 private function __construct(array $data, Visibility $visibility)
e7b93962 167 {
b774ddab 168 $this->data = $data;
832e6fcb
FB
169 $this->pid = $this->data['pid'];
170 $this->hrpid = $this->data['hrpid'];
38a86f60 171 $this->visibility = $visibility;
9f21bd15
RB
172 }
173
dcb7e67d 174 public function __destruct()
2c61c11c
RB
175 {
176 // Need to delete objects allocated by the profile
177 // http://www.php.net/manual/en/function.unset.php#98692
178 unset($this->owner);
179 }
180
e7b93962
FB
181 public function id()
182 {
183 return $this->pid;
184 }
185
186 public function hrid()
187 {
188 return $this->hrpid;
189 }
190
564e2b2a
RB
191 public function owner()
192 {
193 if ($this->owner == null && !$this->owner_fetched) {
194 $this->owner_fetched = true;
195 $this->owner = User::getSilent($this);
196 }
197 return $this->owner;
198 }
199
280806d9
SJ
200 public function isActive()
201 {
202 if ($this->owner()) {
203 return $this->owner->isActive();
204 }
205 return false;
206 }
207
d718e91c 208 public function promo($details = false)
d5e60905 209 {
d718e91c
SJ
210 if ($details && ($this->program || $this->fieldid)) {
211 $text = array();
212 if ($this->program) {
213 $text[] = $this->program;
214 }
215 if ($this->fieldid) {
216 $fieldsList = DirEnum::getOptions(DirEnum::EDUFIELDS);
217 $text[] = $fieldsList[$this->fieldid];
218 }
219 return $this->promo . ' (' . implode(', ', $text) . ')';
220 }
221
d5e60905
FB
222 return $this->promo;
223 }
224
845f0a4d
SJ
225 public function yearpromo()
226 {
7733ade1 227 return $this->promo_year;
845f0a4d
SJ
228 }
229
1168306a
PC
230 /** Check if user is an orange (associated with several promos)
231 */
232 public function isMultiPromo()
233 {
234 return $this->grad_year != $this->entry_year + $this->mainEducationDuration();
235 }
236
237 /** Returns an array with all associated promo years.
238 */
239 public function yearspromo()
240 {
241 $promos = array();
242 $d = -$this->deltaPromoToGradYear();
243 for ($g = $this->entry_year + $this->mainEducationDuration(); $g <= $this->grad_year; ++$g) {
244 $promos[] = $g + $d;
245 }
246 return $promos;
247 }
248
963bc7fc
SJ
249 public function mainEducation()
250 {
39e2c58c
FB
251 if (empty($this->promo)) {
252 return null;
253 } else {
254 return $this->promo{0};
255 }
963bc7fc
SJ
256 }
257
02d9dff0
FB
258 public function mainGrade()
259 {
260 switch ($this->mainEducation()) {
261 case 'X':
262 return UserFilter::GRADE_ING;
263 case 'M':
264 return UserFilter::GRADE_MST;
265 case 'D':
266 return UserFilter::GRADE_PHD;
267 default:
268 return null;
269 }
270 }
271
963bc7fc
SJ
272 public function mainEducationDuration()
273 {
274 switch ($this->mainEducation()) {
275 case 'X':
276 return 3;
277 case 'M':
278 return 2;
279 case 'D':
280 return 3;
281 default:
282 return 0;
283 }
284 }
285
edc03014
SJ
286 public static function educationDuration($education)
287 {
288 switch ($education) {
289 case self::DEGREE_X:
290 return 3;
291 case self::DEGREE_M:
292 return 2;
293 case self::DEGREE_D:
294 return 3;
295 default:
296 return 0;
297 }
298 }
299
1168306a
PC
300 /** Number of years between the promotion year until the
301 * graduation year. In standard schools it's 0, but for
302 * Polytechnique the promo year is the entry year.
303 */
304 public function deltaPromoToGradYear()
305 {
306 if ($this->mainEducation() == 'X') {
307 return $this->mainEducationDuration();
308 }
309 return 0;
310 }
311
3ac6d61d
SJ
312 // Returns the profile's color.
313 public function promoColor()
314 {
315 switch ($this->mainEducation()) {
316 case 'X':
317 if (($this->yearpromo() % 2) === 0) {
318 return 'red';
319 } else {
320 return 'yellow';
321 }
322 case 'M':
323 return 'green';
324 case 'D':
325 return 'blue';
326 default:
327 return 'gray';
328 }
329 }
330
06740f52
SJ
331 // Returns younger/older promotion year for a given education.
332 static public function extremePromotions($education)
333 {
334 return XDB::fetchOneRow("SELECT MIN(pe.promo_year) AS min, MAX(pe.promo_year) AS max
335 FROM profile_education AS pe
336 INNER JOIN profile_education_degree_enum AS pede ON (pe.degreeid = pede.id)
337 WHERE pede.degree = {?} AND FIND_IN_SET('primary', pe.flags)",
338 $education);
339 }
340
94b72319
FB
341 /** Print a name with the given formatting:
342 * %s = • for women
343 * %f = firstname
344 * %l = lastname
345 * %F = fullname
346 * %S = shortname
347 * %p = promo
348 */
349 public function name($format)
350 {
351 return str_replace(array('%s', '%f', '%l', '%F', '%S', '%p'),
352 array($this->isFemale() ? '•' : '',
faf75faf
SJ
353 $this->firstName(), $this->lastName(),
354 $this->fullName(), $this->shortName(),
355 $this->promo()), $format);
94b72319
FB
356 }
357
358 public function fullName($with_promo = false)
359 {
360 if ($with_promo) {
361 return $this->full_name . ' (' . $this->promo . ')';
362 }
363 return $this->full_name;
364 }
365
366 public function shortName($with_promo = false)
367 {
368 if ($with_promo) {
369 return $this->short_name . ' (' . $this->promo . ')';
370 }
371 return $this->short_name;
372 }
373
374 public function firstName()
375 {
5d2e1546 376 return $this->firstname_ordinary;
94b72319
FB
377 }
378
5c005b37
RB
379 public function firstNames()
380 {
381 return $this->nameVariants(self::FIRSTNAME);
382 }
383
94b72319
FB
384 public function lastName()
385 {
5d2e1546 386 return $this->lastname_ordinary;
94b72319
FB
387 }
388
5c005b37
RB
389 public function lastNames()
390 {
391 return $this->nameVariants(self::LASTNAME);
392 }
393
94b72319
FB
394 public function isFemale()
395 {
396 return $this->sex == PlUser::GENDER_FEMALE;
397 }
398
400ac338
RB
399 public function isDead()
400 {
401 return ($this->deathdate != null);
402 }
403
564e2b2a
RB
404 public function displayEmail()
405 {
406 $o = $this->owner();
22771578 407 if ($o != null && $this->isVisible(Visibility::EXPORT_PRIVATE)) {
564e2b2a
RB
408 return $o->bestEmail();
409 } else {
410 return $this->email_directory;
411 }
412 }
413
94b72319
FB
414 public function data()
415 {
416 $this->first_name;
417 return $this->data;
418 }
419
5c005b37
RB
420 private function nameVariants($type)
421 {
422 $vals = array($this->$type);
423 foreach (self::$name_variants[$type] as $var) {
424 $vartype = $type . '_' . $var;
425 $varname = $this->$vartype;
426 if ($varname != null && $varname != "") {
427 $vals[] = $varname;
428 }
429 }
430 return array_unique($vals);
431 }
432
b6569a95
FB
433 public function nationalities()
434 {
435 $nats = array();
3a2985f9 436 $nationalities = DirEnum::getOptions(DirEnum::NATIONALITIES);
b6569a95 437 if ($this->nationality1) {
3a2985f9 438 $nats[$this->nationality1] = $nationalities[$this->nationality1];
b6569a95
FB
439 }
440 if ($this->nationality2) {
3a2985f9 441 $nats[$this->nationality2] = $nationalities[$this->nationality2];
b6569a95
FB
442 }
443 if ($this->nationality3) {
3a2985f9 444 $nats[$this->nationality3] = $nationalities[$this->nationality3];
b6569a95
FB
445 }
446 return $nats;
447 }
448
3e53a496
FB
449 public function __get($name)
450 {
451 if (property_exists($this, $name)) {
452 return $this->$name;
453 }
454
3e53a496
FB
455 if (isset($this->data[$name])) {
456 return $this->data[$name];
457 }
458
459 return null;
460 }
461
462 public function __isset($name)
463 {
464 return property_exists($this, $name) || isset($this->data[$name]);
465 }
466
ddbebe4c
FB
467 public function __unset($name)
468 {
469 if (property_exists($this, $name)) {
470 $this->$name = null;
471 } else {
472 unset($this->data[$name]);
473 }
474 }
475
476
405d70cc
RB
477 /**
478 * Clears a profile.
080632c7
RB
479 * *always deletes in: profile_addresses, profile_binets, profile_deltaten,
480 * profile_job, profile_langskills, profile_mentor, profile_networking,
148af7a9
RB
481 * profile_partnersharing_settings, profile_phones, profile_skills,
482 * watch_profile
405d70cc 483 * *always keeps in: profile_corps, profile_display, profile_education,
0e1dfbad 484 * profile_medals, profile_*_names, profile_photos, search_name
405d70cc
RB
485 * *modifies: profiles
486 */
487 public function clear()
488 {
489 $tables = array(
490 'profile_job', 'profile_langskills', 'profile_mentor',
491 'profile_networking', 'profile_skills', 'watch_profile',
080632c7 492 'profile_phones', 'profile_addresses', 'profile_binets',
148af7a9 493 'profile_deltaten', 'profile_partnersharing_settings');
405d70cc
RB
494
495 foreach ($tables as $t) {
496 XDB::execute('DELETE FROM ' . $t . '
497 WHERE pid = {?}',
498 $this->id());
499 }
500
501 XDB::execute("UPDATE profiles
502 SET cv = NULL, freetext = NULL, freetext_pub = 'private',
fe6080a4 503 medals_pub = 'private', alias_pub = 'hidden',
405d70cc
RB
504 email_directory = NULL
505 WHERE pid = {?}",
506 $this->id());
507 }
508
c159e50f
RB
509 /** Determine whether an item with visibility $visibility can be displayed
510 * with the current level of visibility of the profile
511 * @param $visibility The level of visibility to be checked
512 */
513 public function isVisible($visibility)
514 {
1a9affb7 515 return $this->visibility->isVisible($visibility);
9f21bd15
RB
516 }
517
a0f5fa32 518 /** Stores the list of fields which have already been fetched for this Profile
1f8250e4
RB
519 */
520 public function setFetchedFields($fields)
990cb17b 521 {
1f8250e4
RB
522 if (($fields | self::FETCH_ALL) != self::FETCH_ALL) {
523 Platal::page()->kill("Invalid fetched fields: $fields");
524 }
525
526 $this->fetched_fields = $fields;
527 }
528
4ec03752
RB
529 /** Have we already fetched this field ?
530 */
1f8250e4
RB
531 private function fetched($field)
532 {
4ec03752
RB
533 if (!array_key_exists($field, ProfileField::$fields)) {
534 Platal::page()->kill("Invalid field: $field");
1f8250e4
RB
535 }
536
537 return ($this->fetched_fields & $field);
538 }
539
540 /** If not already done, fetches data for the given field
541 * @param $field One of the Profile::FETCH_*
542 * @return A ProfileField, or null
543 */
544 private function getProfileField($field)
545 {
3ac45f10
PC
546 if (!array_key_exists($field, ProfileField::$fields)) {
547 Platal::page()->kill("Invalid field: $field");
548 }
1f8250e4
RB
549 if ($this->fetched($field)) {
550 return null;
551 } else {
552 $this->fetched_fields = $this->fetched_fields | $field;
553 }
554
555 $cls = ProfileField::$fields[$field];
556
990cb17b
RB
557 return ProfileField::getForPID($cls, $this->id(), $this->visibility);
558 }
559
8cf886dc
RB
560 /** Consolidates internal data (addresses, phones, jobs)
561 */
562 private function consolidateFields()
563 {
4ec03752 564 // Link phones to addresses
8cf886dc
RB
565 if ($this->phones != null) {
566 if ($this->addresses != null) {
567 $this->addresses->addPhones($this->phones);
568 }
569
570 if ($this->jobs != null) {
571 $this->jobs->addPhones($this->phones);
572 }
573 }
574
4ec03752 575 // Link addresses to jobs
8cf886dc
RB
576 if ($this->addresses != null && $this->jobs != null) {
577 $this->jobs->addAddresses($this->addresses);
578 }
4ec03752
RB
579
580 // Link jobterms to jobs
3ac45f10
PC
581 if ($this->jobs != null && $this->jobterms != null) {
582 $this->jobs->addJobTerms($this->jobterms);
583 }
8cf886dc
RB
584 }
585
833a6e86
FB
586 /* Photo
587 */
1a9affb7 588 private $photo = null;
7988f7d6 589 public function getPhoto($fallback = true, $data = false)
9f21bd15 590 {
1a9affb7
RB
591 if ($this->has_photo) {
592 if ($data && ($this->photo == null || $this->photo->mimeType == null)) {
8d6bbca3 593 $res = XDB::fetchOneAssoc('SELECT attach, attachmime, x, y, last_update
1f8250e4
RB
594 FROM profile_photos
595 WHERE pid = {?}', $this->pid);
8d6bbca3 596 $this->photo = PlImage::fromData($res['attach'], 'image/' .$res['attachmime'], $res['x'], $res['y'], $res['last_update']);
1a9affb7
RB
597 } else if ($this->photo == null) {
598 $this->photo = PlImage::fromData(null, null, $this->photo_width, $this->photo_height);
599 }
600 return $this->photo;
9f21bd15 601 } else if ($fallback) {
fa671a30
SJ
602 if ($this->mainEducation() == 'X') {
603 return PlImage::fromFile(dirname(__FILE__) . '/../htdocs/images/none_x.png', 'image/png');
604 }
605 return PlImage::fromFile(dirname(__FILE__) . '/../htdocs/images/none_md.png', 'image/png');
9f21bd15
RB
606 }
607 return null;
608 }
7d0ebdf5 609
4bc5b8f0
FB
610 /* Addresses
611 */
7d0ebdf5
RB
612 private $addresses = null;
613 public function setAddresses(ProfileAddresses $addr)
614 {
615 $this->addresses = $addr;
8cf886dc 616 $this->consolidateFields();
7d0ebdf5
RB
617 }
618
dbcc3b3d 619 private function fetchAddresses()
f5642983 620 {
1f8250e4 621 if ($this->addresses == null && !$this->fetched(self::FETCH_ADDRESSES)) {
61ee68c7
FB
622 $addr = $this->getProfileField(self::FETCH_ADDRESSES);
623 if ($addr) {
624 $this->setAddresses($addr);
dbcc3b3d 625 $this->fetchPhones();
61ee68c7 626 }
f5642983 627 }
dbcc3b3d
RB
628 }
629
630 public function getAddresses($flags, $limit = null)
631 {
632 $this->fetchAddresses();
0907501b
RB
633
634 if ($this->addresses == null) {
598c57f6 635 return array();
0907501b 636 }
990cb17b 637 return $this->addresses->get($flags, $limit);
f5642983
FB
638 }
639
598c57f6
RB
640 public function iterAddresses($flags, $limit = null)
641 {
642 return PlIteratorUtils::fromArray($this->getAddresses($flags, $limit), 1, true);
643 }
644
f5642983
FB
645 public function getMainAddress()
646 {
b0ffc881
RB
647 $main = $this->getAddresses(self::ADDRESS_MAIN);
648 $perso = $this->getAddresses(self::ADDRESS_PERSO);
649
650 if (count($main)) {
651 return array_pop($main);
652 } else if (count($perso)) {
653 return array_pop($perso);
f5642983 654 } else {
b0ffc881 655 return null;
f5642983
FB
656 }
657 }
3e53a496 658
bdef0d33
RB
659 /* Phones
660 */
661 private $phones = null;
662 public function setPhones(ProfilePhones $phones)
663 {
664 $this->phones = $phones;
665 $this->consolidateFields();
666 }
667
dbcc3b3d 668 private function fetchPhones()
bdef0d33 669 {
1f8250e4 670 if ($this->phones == null && !$this->fetched(self::FETCH_PHONES)) {
56721636
PC
671 $phones = $this->getProfileField(self::FETCH_PHONES);
672 if (isset($phones)) {
673 $this->setPhones($phones);
674 }
bdef0d33 675 }
dbcc3b3d 676 }
bdef0d33 677
dbcc3b3d
RB
678 public function getPhones($flags, $limit = null)
679 {
680 $this->fetchPhones();
bdef0d33 681 if ($this->phones == null) {
598c57f6 682 return array();
bdef0d33
RB
683 }
684 return $this->phones->get($flags, $limit);
685 }
4bc5b8f0
FB
686
687 /* Educations
688 */
d4d395bb 689 private $educations = null;
a060e1c3
RB
690 public function setEducations(ProfileEducation $edu)
691 {
692 $this->educations = $edu;
693 }
694
4bc5b8f0
FB
695 public function getEducations($flags, $limit = null)
696 {
1f8250e4 697 if ($this->educations == null && !$this->fetched(self::FETCH_EDU)) {
67972120
SJ
698 $educations = $this->getProfileField(self::FETCH_EDU);
699 if ($educations) {
700 $this->setEducations($educations);
701 }
d4d395bb 702 }
0907501b
RB
703
704 if ($this->educations == null) {
598c57f6 705 return array();
0907501b 706 }
a060e1c3 707 return $this->educations->get($flags, $limit);
4bc5b8f0
FB
708 }
709
710 public function getExtraEducations($limit = null)
711 {
712 return $this->getEducations(self::EDUCATION_EXTRA, $limit);
713 }
714
0396c259
RB
715 /* Corps
716 */
717 private $corps = null;
718 public function setCorps(ProfileCorps $corps)
719 {
720 $this->corps = $corps;
721 }
722
723 public function getCorps()
724 {
1f8250e4 725 if ($this->corps == null && !$this->fetched(self::FETCH_CORPS)) {
67972120
SJ
726 $corps = $this->getProfileField(self::FETCH_CORPS);
727 if ($corps) {
728 $this->setCorps($corps);
729 }
0396c259
RB
730 }
731 return $this->corps;
732 }
4bc5b8f0 733
04a94b1d
FB
734 /** Networking
735 */
d4d395bb
RB
736 private $networks = null;
737 public function setNetworking(ProfileNetworking $nw)
738 {
739 $this->networks = $nw;
740 }
04a94b1d
FB
741
742 public function getNetworking($flags, $limit = null)
743 {
1f8250e4 744 if ($this->networks == null && !$this->fetched(self::FETCH_NETWORKING)) {
dad85695
FB
745 $nw = $this->getProfileField(self::FETCH_NETWORKING);
746 if ($nw) {
747 $this->setNetworking($nw);
748 }
04a94b1d 749 }
0907501b 750 if ($this->networks == null) {
598c57f6 751 return array();
0907501b 752 }
d4d395bb 753 return $this->networks->get($flags, $limit);
04a94b1d
FB
754 }
755
756 public function getWebSite()
757 {
758 $site = $this->getNetworking(self::NETWORKING_WEB, 1);
598c57f6 759 if (count($site) != 1) {
04a94b1d
FB
760 return null;
761 }
598c57f6 762 $site = array_pop($site);
dad85695 763 return $site;
04a94b1d
FB
764 }
765
766
e718bd18
FB
767 /** Jobs
768 */
949fc736
RB
769 private $jobs = null;
770 public function setJobs(ProfileJobs $jobs)
771 {
772 $this->jobs = $jobs;
773 $this->consolidateFields();
774 }
e718bd18 775
dbcc3b3d 776 private function fetchJobs()
e718bd18 777 {
1f8250e4 778 if ($this->jobs == null && !$this->fetched(self::FETCH_JOBS)) {
61ee68c7
FB
779 $jobs = $this->getProfileField(self::FETCH_JOBS);
780 if ($jobs) {
781 $this->setJobs($jobs);
dbcc3b3d 782 $this->fetchAddresses();
61ee68c7 783 }
e718bd18 784 }
dbcc3b3d
RB
785 }
786
787 public function getJobs($flags, $limit = null)
788 {
789 $this->fetchJobs();
949fc736 790
0907501b 791 if ($this->jobs == null) {
598c57f6 792 return array();
0907501b 793 }
949fc736 794 return $this->jobs->get($flags, $limit);
e718bd18
FB
795 }
796
44ec5eb5 797 public function getMainJob()
e718bd18
FB
798 {
799 $job = $this->getJobs(self::JOBS_MAIN, 1);
598c57f6 800 if (count($job) != 1) {
e718bd18
FB
801 return null;
802 }
598c57f6 803 return array_pop($job);
e718bd18
FB
804 }
805
3ac45f10
PC
806 /** JobTerms
807 */
808 private $jobterms = null;
809 public function setJobTerms(ProfileJobTerms $jobterms)
810 {
811 $this->jobterms = $jobterms;
812 $this->consolidateFields();
813 }
814
4d1f0f6b
RB
815 private $mentor_countries = null;
816 public function setMentoringCountries(ProfileMentoringCountries $countries)
817 {
818 $this->mentor_countries = $countries;
819 }
820
821 public function getMentoringCountries()
822 {
823 if ($this->mentor_countries == null && !$this->fetched(self::FETCH_MENTOR_COUNTRY)) {
67972120
SJ
824 $countries = $this->getProfileField(self::FETCH_MENTOR_COUNTRY);
825 if ($countries) {
826 $this->setMentoringCountries($countries);
827 }
4d1f0f6b
RB
828 }
829
830 if ($this->mentor_countries == null) {
831 return array();
832 } else {
833 return $this->mentor_countries->countries;
834 }
835 }
836
3ac45f10
PC
837 /** List of job terms to specify mentoring */
838 private $mentor_terms = null;
839 /**
840 * set job terms to specify mentoring
841 * @param $terms a ProfileMentoringTerms object listing terms only for this profile
842 */
843 public function setMentoringTerms(ProfileMentoringTerms $terms)
844 {
845 $this->mentor_terms = $terms;
846 }
847 /**
848 * get all job terms that specify mentoring
849 * @return an array of JobTerms objects
850 */
851 public function getMentoringTerms()
852 {
853 if ($this->mentor_terms == null && !$this->fetched(self::FETCH_MENTOR_TERMS)) {
67972120
SJ
854 $terms = $this->getProfileField(self::FETCH_MENTOR_TERMS);
855 if ($terms) {
856 $this->setMentoringTerms($terms);
857 }
3ac45f10
PC
858 }
859
860 if ($this->mentor_terms == null) {
861 return array();
862 } else {
863 return $this->mentor_terms->get();
864 }
865 }
866
7e0635c2
SJ
867 /* Skills */
868 private $skills = null;
869 public function setSkills(ProfileSkills $skills)
870 {
871 $this->skills = $skills;
872 }
873 public function getSkills()
874 {
875 if ($this->skills == null && !$this->fetched(self::FETCH_SKILL)) {
67972120
SJ
876 $skills = $this->getProfileField(self::FETCH_SKILL);
877 if ($skills) {
878 $this->setSkills($skills);
879 }
7e0635c2
SJ
880 }
881
882 if ($this->skills == null) {
883 return array();
884 } else {
885 return $this->skills->skills;
886 }
887 }
888
889 /* Languades */
890 private $languages = null;
891 public function setLanguages(ProfileLanguages $languages)
892 {
893 $this->languages = $languages;
894 }
895 public function getLanguages()
896 {
897 if ($this->languages == null && !$this->fetched(self::FETCH_LANGUAGE)) {
67972120
SJ
898 $languages = $this->getProfileField(self::FETCH_LANGUAGE);
899 if ($languages) {
900 $this->setLanguages($languages);
901 }
7e0635c2
SJ
902 }
903
904 if ($this->languages == null) {
905 return array();
906 } else {
907 return $this->languages->languages;
908 }
909 }
910
080632c7
RB
911 /** DeltaTen
912 */
913
914 /** Find out whether this profile may take part to the "DeltaTen" operation.
915 * @param $role Which role to select ('young' or 'old')
916 * @return Boolean: whether it is enabled.
917 */
918 const DELTATEN_YOUNG = 'young';
919 const DELTATEN_OLD = 'old';
920 public function isDeltaTenEnabled($role)
921 {
922 global $globals;
923 switch ($role) {
924 case self::DELTATEN_YOUNG:
925 return ($this->mainGrade() == UserFilter::GRADE_ING && $this->yearpromo() >= $globals->deltaten->first_promo_young);
926 case self::DELTATEN_OLD:
927 // Roughly compute the current promo in second year on the campus:
928 // Promo 2010 is in second year between 09/2011 and 08/2012 => use 2012.
929 // DeltaTen program begins around January of the second year.
930 $promo_on_platal = ((int) date('Y')) - 2;
931 return ($this->mainGrade() == UserFilter::GRADE_ING && $this->yearpromo() >= $globals->deltaten->first_promo_young - 10 && $this->yearpromo() <= $promo_on_platal - 10);
932 default:
933 Platal::assert(false, "Invalid DeltaTen role $role");
934 }
935 }
936
937 /** Retrieve the "Deltaten" message of the user.
938 * Returns "null" if the message is empty or the user is not taking part to the
939 * DeltaTen operation.
940 */
941 public function getDeltatenMessage()
942 {
943 if ($this->isDeltaTenEnabled(self::DELTATEN_OLD)) {
944 return $this->deltaten_message;
945 } else {
946 return null;
947 }
948 }
3ac45f10 949
5c005b37
RB
950 /* Binets
951 */
952 public function getBinets()
953 {
22771578 954 if ($this->visibility->isVisible(Visibility::EXPORT_PRIVATE)) {
875a88d3
RB
955 return XDB::fetchColumn('SELECT binet_id
956 FROM profile_binets
957 WHERE pid = {?}', $this->id());
958 } else {
959 return array();
960 }
5c005b37 961 }
ccf88cca 962
7f3c6bf4
TM
963 public function getFullBinets()
964 {
965 if ($this->visibility->isVisible(Visibility::EXPORT_PRIVATE)) {
966 return XDB::fetchAllAssoc('SELECT binet_id, text, url
967 FROM profile_binets AS pb
968 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
969 WHERE pid = {?}', $this->id());
970 } else {
971 return array();
972 }
973 }
ccf88cca 974
97b71de5
RB
975 public function getBinetsNames()
976 {
22771578 977 if ($this->visibility->isVisible(Visibility::EXPORT_PRIVATE)) {
875a88d3
RB
978 return XDB::fetchColumn('SELECT text
979 FROM profile_binets AS pb
980 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
981 WHERE pb.pid = {?}', $this->id());
982 } else {
983 return array();
984 }
97b71de5 985 }
5c005b37 986
26ca919b
RB
987 /* Medals
988 */
989 private $medals = null;
990 public function setMedals(ProfileMedals $medals)
991 {
992 $this->medals = $medals;
993 }
994
995 public function getMedals()
996 {
1f8250e4 997 if ($this->medals == null && !$this->fetched(self::FETCH_MEDALS)) {
67972120
SJ
998 $medals = $this->getProfileField(self::FETCH_MEDALS);
999 if ($medals) {
1000 $this->setMedals($medals);
1001 }
26ca919b
RB
1002 }
1003 if ($this->medals == null) {
1004 return array();
1005 }
1006 return $this->medals->medals;
1007 }
e718bd18 1008
148af7a9
RB
1009 /** Sharing data with partner websites
1010 */
1011 private $partners_settings = null;
1012 public function setPartnersSettings(ProfilePartnerSharing $partners_settings)
1013 {
1014 $this->partners_settings = $partners_settings;
1015 }
1016
1017 public function getPartnerSettings($partner_id)
1018 {
f0f8c375 1019 if ($this->partners_settings === null && !$this->fetched(self::FETCH_PARTNER)) {
67972120
SJ
1020 $settings = $this->getProfileField(self::FETCH_PARTNER);
1021 if ($settings) {
1022 $this->setPartnersSettings($settings);
1023 }
148af7a9 1024 }
f0f8c375 1025 if ($this->partners_settings === null) {
148af7a9
RB
1026 return PartnerSettings::getEmpty($partner_id);
1027 }
1028 return $this->partners_settings->get($partner_id);
1029 }
1030
94590511
SJ
1031 public function compareNames($firstname, $lastname)
1032 {
1033 $_lastname = mb_strtoupper($this->lastName());
1034 $_firstname = mb_strtoupper($this->firstName());
1035 $lastname = mb_strtoupper($lastname);
1036 $firstname = mb_strtoupper($firstname);
1037
1038 $isOk = (mb_strtoupper($_firstname) == mb_strtoupper($firstname));
1039 $tokens = preg_split("/[ \-']/", $lastname, -1, PREG_SPLIT_NO_EMPTY);
1040 $maxlen = 0;
1041
1042 foreach ($tokens as $str) {
1043 $isOk &= (strpos($_lastname, $str) !== false);
1044 $maxlen = max($maxlen, strlen($str));
1045 }
1046
1047 return ($isOk && ($maxlen > 2 || $maxlen == strlen($_lastname)));
1048 }
1049
aaffb7b2
FB
1050 /* Export to JSON
1051 */
1052 public function export()
1053 {
1054 return array(
1055 'hrpid' => $this->hrid(),
1056 'display_name' => $this->shortName(),
1057 'full_name' => $this->fullName(),
1058 'directory_name' => $this->directory_name,
1059 'promo' => $this->promo(),
1060 'year_promo' => $this->yearpromo(),
1061 'is_active' => $this->isActive(),
1062 'first_name' => $this->firstName(),
1063 'last_name' => $this->lastName(),
1064 'is_female' => $this->isFemale(),
1065 );
1066 }
1067
22771578 1068 private static function fetchProfileData(array $pids, $respect_order = true, $fields = 0x0000, $visibility = null)
b774ddab
FB
1069 {
1070 if (count($pids) == 0) {
7a8da8e8 1071 return null;
b774ddab 1072 }
0d906109
RB
1073
1074 if ($respect_order) {
1075 $order = 'ORDER BY ' . XDB::formatCustomOrder('p.pid', $pids);
1076 } else {
1077 $order = '';
1078 }
1079
22771578
RB
1080 if ($visibility === null) {
1081 $visibility = Visibility::defaultForRead();
38a86f60 1082 }
9f21bd15 1083
3e2442cd
RB
1084 $it = XDB::Iterator('SELECT p.pid, p.hrpid, p.xorg_id, p.ax_id, p.birthdate, p.birthdate_ref,
1085 p.next_birthday, p.deathdate, p.deathdate_rec, p.sex = \'female\' AS sex,
77d2ae52
RB
1086 IF ({?}, p.cv, NULL) AS cv, p.medals_pub, p.alias_pub, p.email_directory,
1087 p.last_change, p.nationality1, p.nationality2, p.nationality3,
38a86f60 1088 IF (p.freetext_pub >= {?}, p.freetext, NULL) AS freetext,
d718e91c 1089 pe.entry_year, pe.grad_year, pe.promo_year, pe.program, pe.fieldid,
348b3844 1090 IF ({?}, pse.text, NULL) AS section,
0e1dfbad
SJ
1091 ppn.firstname_main AS firstname, ppn.lastname_main AS lastname, IF ({?}, pn.name, NULL) AS nickname,
1092 IF (ppn.firstname_ordinary = \'\', ppn.firstname_main, ppn.firstname_ordinary) AS firstname_ordinary,
8fc92b60 1093 IF (ppn.lastname_ordinary = \'\', ppn.lastname_main, ppn.lastname_ordinary) AS lastname_ordinary,
09e54905
SJ
1094 pd.yourself, pd.promo, pd.short_name, pd.public_name AS full_name,
1095 pd.directory_name, pd.public_name, pd.private_name,
38a86f60 1096 IF (pp.pub >= {?}, pp.display_tel, NULL) AS mobile,
db492b02 1097 (ph.pub >= {?} AND ph.attach IS NOT NULL) AS has_photo, ph.pub as photo_pub,
7988f7d6 1098 ph.x AS photo_width, ph.y AS photo_height,
9f21bd15 1099 p.last_change < DATE_SUB(NOW(), INTERVAL 365 DAY) AS is_old,
bdef0d33 1100 pm.expertise AS mentor_expertise,
080632c7 1101 IF ({?}, pdt.message, NULL) AS deltaten_message,
9f21bd15
RB
1102 ap.uid AS owner_id
1103 FROM profiles AS p
1104 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1105 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
97b71de5 1106 LEFT JOIN profile_section_enum AS pse ON (pse.id = p.section)
0e1dfbad
SJ
1107 INNER JOIN profile_public_names AS ppn ON (ppn.pid = p.pid)
1108 LEFT JOIN profile_private_names AS pn ON (pn.pid = p.pid AND type = \'nickname\')
9f21bd15
RB
1109 LEFT JOIN profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = \'user\' AND tel_type = \'mobile\')
1110 LEFT JOIN profile_photos AS ph ON (ph.pid = p.pid)
bdef0d33 1111 LEFT JOIN profile_mentor AS pm ON (pm.pid = p.pid)
080632c7 1112 LEFT JOIN profile_deltaten AS pdt ON (pdt.pid = p.pid)
9f21bd15 1113 LEFT JOIN account_profiles AS ap ON (ap.pid = p.pid AND FIND_IN_SET(\'owner\', ap.perms))
3e2442cd 1114 WHERE p.pid IN {?}
9f21bd15 1115 GROUP BY p.pid
3e2442cd 1116 ' . $order,
22771578 1117 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // CV
38a86f60 1118 $visibility->level(), // freetext
22771578
RB
1119 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // section
1120 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // nickname
38a86f60
RB
1121 $visibility->level(), // mobile
1122 $visibility->level(), // photo
22771578 1123 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // deltaten_message
3e2442cd
RB
1124 $pids
1125 );
31ef12ef 1126 return new ProfileIterator($it, $pids, $fields, $visibility);
b774ddab
FB
1127 }
1128
1129 public static function getPID($login)
1130 {
1131 if ($login instanceof PlUser) {
1132 return XDB::fetchOneCell('SELECT pid
1133 FROM account_profiles
1134 WHERE uid = {?} AND FIND_IN_SET(\'owner\', perms)',
1135 $login->id());
9f21bd15 1136 } else if (ctype_digit($login)) {
b774ddab
FB
1137 return XDB::fetchOneCell('SELECT pid
1138 FROM profiles
1139 WHERE pid = {?}', $login);
1140 } else {
1141 return XDB::fetchOneCell('SELECT pid
1142 FROM profiles
1143 WHERE hrpid = {?}', $login);
1144 }
1145 }
1146
0d906109
RB
1147 public static function getPIDsFromUIDs($uids, $respect_order = true)
1148 {
1149 if ($respect_order) {
1150 $order = 'ORDER BY ' . XDB::formatCustomOrder('uid', $uids);
1151 } else {
1152 $order = '';
1153 }
1154 return XDB::fetchAllAssoc('uid', 'SELECT ap.uid, ap.pid
1155 FROM account_profiles AS ap
1156 WHERE FIND_IN_SET(\'owner\', ap.perms)
9f21bd15
RB
1157 AND ap.uid IN ' . XDB::formatArray($uids) .'
1158 ' . $order);
0d906109 1159 }
b774ddab 1160
e7b93962
FB
1161 /** Return the profile associated with the given login.
1162 */
22771578 1163 public static function get($login, $fields = 0x0000, $visibility = null)
a3118782 1164 {
22771578
RB
1165 if ($visibility === null) {
1166 $visibility = Visibility::defaultForRead();
38a86f60
RB
1167 }
1168
641f2115 1169 if (is_array($login)) {
38a86f60 1170 $pf = new Profile($login, $visibility);
1a9affb7 1171 return $pf;
641f2115 1172 }
b774ddab
FB
1173 $pid = self::getPID($login);
1174 if (!is_null($pid)) {
9f21bd15 1175 $it = self::iterOverPIDs(array($pid), false, $fields, $visibility);
0d906109 1176 return $it->next();
b774ddab 1177 } else {
efe597c5
FB
1178 /* Let say we can identify a profile using the identifiers of its owner.
1179 */
455ea0c9
FB
1180 if (!($login instanceof PlUser)) {
1181 $user = User::getSilent($login);
1182 if ($user && $user->hasProfile()) {
22771578 1183 return $user->profile(false, $fields, $visibility);
455ea0c9 1184 }
efe597c5 1185 }
3e53a496 1186 return null;
e7b93962
FB
1187 }
1188 }
a3118782 1189
22771578 1190 public static function iterOverUIDs($uids, $respect_order = true, $fields = 0x0000, $visibility = null)
0d906109 1191 {
9f21bd15 1192 return self::iterOverPIDs(self::getPIDsFromUIDs($uids), $respect_order, $fields, $visibility);
0d906109
RB
1193 }
1194
22771578 1195 public static function iterOverPIDs($pids, $respect_order = true, $fields = 0x0000, $visibility = null)
0d906109 1196 {
9f21bd15 1197 return self::fetchProfileData($pids, $respect_order, $fields, $visibility);
0d906109
RB
1198 }
1199
b774ddab
FB
1200 /** Return profiles for the list of pids.
1201 */
22771578 1202 public static function getBulkProfilesWithPIDs(array $pids, $fields = 0x0000, $visibility = null)
b774ddab
FB
1203 {
1204 if (count($pids) == 0) {
1205 return array();
1206 }
9f21bd15 1207 $it = self::iterOverPIDs($pids, true, $fields, $visibility);
b774ddab 1208 $profiles = array();
0d906109
RB
1209 while ($p = $it->next()) {
1210 $profiles[$p->id()] = $p;
b774ddab
FB
1211 }
1212 return $profiles;
1213 }
1214
1215 /** Return profiles for uids.
1216 */
22771578 1217 public static function getBulkProfilesWithUIDS(array $uids, $fields = 0x000, $visibility = null)
b774ddab
FB
1218 {
1219 if (count($uids) == 0) {
1220 return array();
1221 }
e4f1d258 1222 return self::getBulkProfilesWithPIDs(self::getPIDsFromUIDs($uids), $fields, $visibility);
b774ddab
FB
1223 }
1224
913a4e90
RB
1225 public static function isDisplayName($name)
1226 {
1227 return $name == self::DN_FULL || $name == self::DN_DISPLAY
1228 || $name == self::DN_YOURSELF || $name == self::DN_DIRECTORY
1229 || $name == self::DN_PRIVATE || $name == self::DN_PUBLIC
1230 || $name == self::DN_SHORT || $name == self::DN_SORT;
1231 }
1232
a9ef52c9
RB
1233 /** Returns the closest "accounts only" name type for $name
1234 */
1235 public static function getAccountEquivalentName($name)
1236 {
b0788bf4
SJ
1237 switch ($name) {
1238 case self::DN_DIRECTORY:
a9ef52c9 1239 return 'directory_name';
b0788bf4
SJ
1240 case self::DN_SORT:
1241 return 'sort_name';
1242 case self::DN_FULL:
1243 case self::DN_PUBLIC:
1244 case self::DN_PRIVATE:
1245 case self::DN_SHORT:
a9ef52c9 1246 return 'full_name';
b0788bf4
SJ
1247 case self::DN_YOURSELF:
1248 return 'display_name';
1249 default:
a9ef52c9
RB
1250 return 'display_name';
1251 }
1252 }
1253
bedc4295 1254 public static function rebuildSearchTokens($pids, $transaction = true)
726eaf7a 1255 {
0e1dfbad 1256 require_once 'name.func.inc.php';
5acd53a9
FB
1257 if (!is_array($pids)) {
1258 $pids = array($pids);
1259 }
0e1dfbad
SJ
1260 $keys = XDB::iterator("(SELECT pid, name, type, IF(type = 'nickname', 2, 1) AS score, '' AS public
1261 FROM profile_private_names
1262 WHERE pid IN {?})
1263 UNION
1264 (SELECT pid, lastname_main, 'lastname' AS type, 10 AS score, 'public' AS public
1265 FROM profile_public_names
1266 WHERE lastname_main != '' AND pid IN {?})
1267 UNION
1268 (SELECT pid, lastname_marital, 'lastname' AS type, 10 AS score, 'public' AS public
1269 FROM profile_public_names
1270 WHERE lastname_marital != '' AND pid IN {?})
1271 UNION
1272 (SELECT pid, lastname_ordinary, 'lastname' AS type, 10 AS score, 'public' AS public
1273 FROM profile_public_names
1274 WHERE lastname_ordinary != '' AND pid IN {?})
1275 UNION
1276 (SELECT pid, firstname_main, 'firstname' AS type, 10 AS score, 'public' AS public
1277 FROM profile_public_names
1278 WHERE firstname_main != '' AND pid IN {?})
1279 UNION
1280 (SELECT pid, firstname_ordinary, 'firstname' AS type, 10 AS score, 'public' AS public
1281 FROM profile_public_names
1282 WHERE firstname_ordinary != '' AND pid IN {?})
1283 UNION
1284 (SELECT pid, pseudonym, 'nickname' AS type, 10 AS score, 'public' AS public
1285 FROM profile_public_names
1286 WHERE pseudonym != '' AND pid IN {?})",
1287 $pids, $pids, $pids, $pids, $pids, $pids, $pids);
5acd53a9 1288 $names = array();
2f62eba7 1289 while ($key = $keys->next()) {
726eaf7a
SJ
1290 if ($key['name'] == '') {
1291 continue;
1292 }
0e1dfbad 1293 $pid = $key['pid'];
5ed1cce8 1294 $toks = split_name_for_search($key['name']);
80bc45c2
FB
1295 $toks = array_reverse($toks);
1296
1297 /* Split the score between the tokens to avoid the user to be over-rated.
1298 * Let says my user name is "Machin-Truc Bidule" and I also have a user named
1299 * 'Machin Truc'. Distributing the score force "Machin Truc" to be displayed
1300 * before "Machin-Truc" for both "Machin Truc" and "Machin" searches.
1301 */
1302 $eltScore = ceil(((float)$key['score'])/((float)count($toks)));
726eaf7a 1303 $token = '';
80bc45c2
FB
1304 foreach ($toks as $tok) {
1305 $token = $tok . $token;
5600b2fe 1306 $names["$pid-$token"] = XDB::format('({?}, {?}, {?}, {?}, {?}, {?})',
5acd53a9 1307 $token, $pid, soundex_fr($token),
0e1dfbad 1308 $eltScore, $key['public'], $key['type']);
726eaf7a
SJ
1309 }
1310 }
bedc4295
FB
1311 if ($transaction) {
1312 XDB::startTransaction();
1313 }
5acd53a9
FB
1314 XDB::execute('DELETE FROM search_name
1315 WHERE pid IN {?}',
1316 $pids);
1317 if (count($names) > 0) {
5600b2fe 1318 XDB::rawExecute('INSERT INTO search_name (token, pid, soundex, score, flags, general_type)
80bc45c2 1319 VALUES ' . implode(', ', $names));
5acd53a9 1320 }
bedc4295
FB
1321 if ($transaction) {
1322 XDB::commit();
1323 }
69b46857
SJ
1324 }
1325
1326 /** The school identifier consists of 6 digits. The first 3 represent the
1327 * promotion entry year. The last 3 indicate the student's rank.
aab2ffdd 1328 *
69b46857
SJ
1329 * Our identifier consists of 8 digits and both half have the same role.
1330 * This enables us to deal with bigger promotions and with a wider range
1331 * of promotions.
1332 *
1333 * getSchoolId returns a school identifier given one of ours.
1334 * getXorgId returns a X.org identifier given a school identifier.
1335 */
1336 public static function getSchoolId($xorgId)
1337 {
1338 if (!preg_match('/^[0-9]{8}$/', $xorgId)) {
1339 return null;
1340 }
1341
1342 $year = intval(substr($xorgId, 0, 4));
1343 $rank = intval(substr($xorgId, 5, 3));
1344 if ($year < 1996) {
1345 return null;
1346 } elseif ($year < 2000) {
1347 $year = intval(substr(1900 - $year, 1, 3));
1348 return sprintf('%02u0%03u', $year, $rank);
1349 } else {
1350 $year = intval(substr(1900 - $year, 1, 3));
1351 return sprintf('%03u%03u', $year, $rank);
1352 }
1353 }
726eaf7a 1354
69b46857
SJ
1355 public static function getXorgId($schoolId)
1356 {
94590511 1357 if (!preg_match('/^[0-9]{6}$/', $schoolId)) {
a292484d
SJ
1358 return null;
1359 }
1360
69b46857
SJ
1361 $year = intval(substr($schoolId, 0, 3));
1362 $rank = intval(substr($schoolId, 3, 3));
726eaf7a 1363
69b46857
SJ
1364 if ($year > 200) {
1365 $year /= 10;
1366 }
1367 if ($year < 96) {
1368 return null;
1369 } else {
1370 return sprintf('%04u%04u', 1900 + $year, $rank);
1371 }
726eaf7a 1372 }
e7b93962
FB
1373}
1374
31ef12ef
RB
1375
1376/** Iterator over a set of Profiles
1377 */
1378class ProfileIterator implements PlIterator
9f21bd15
RB
1379{
1380 private $iterator = null;
1381 private $fields;
1a9affb7 1382 private $visibility;
9f21bd15 1383
3ac45f10
PC
1384 const FETCH_ALL = 0x000033F; // FETCH_ADDRESSES | FETCH_CORPS | FETCH_EDU | FETCH_JOBS | FETCH_MEDALS | FETCH_NETWORKING | FETCH_PHONES | FETCH_JOB_TERMS
1385
22771578 1386 public function __construct(PlIterator $it, array $pids, $fields = 0x0000, $visibility = null)
9f21bd15
RB
1387 {
1388 require_once 'profilefields.inc.php';
1a9affb7 1389
22771578
RB
1390 if ($visibility === null) {
1391 $visibility = Visibility::defaultForRead();
1a9affb7
RB
1392 }
1393
9f21bd15 1394 $this->fields = $fields;
1a9affb7 1395 $this->visibility = $visibility;
9f21bd15
RB
1396
1397 $subits = array();
1398 $callbacks = array();
1399
1400 $subits[0] = $it;
1401 $callbacks[0] = PlIteratorUtils::arrayValueCallback('pid');
1402 $cb = PlIteratorUtils::objectPropertyCallback('pid');
1403
3ac45f10
PC
1404 $fields = $fields & self::FETCH_ALL;
1405 for ($field = 1; $field < $fields; $field *= 2) {
1406 if (($fields & $field) ) {
1407 $callbacks[$field] = $cb;
1408 $subits[$field] = new ProfileFieldIterator($field, $pids, $visibility);
1409 }
9f21bd15
RB
1410 }
1411
9f21bd15
RB
1412 $this->iterator = PlIteratorUtils::parallelIterator($subits, $callbacks, 0);
1413 }
1414
1f8250e4 1415 private function hasData($field, $vals)
9f21bd15 1416 {
1f8250e4 1417 return ($this->fields & $field) && ($vals[$field] != null);
9f21bd15
RB
1418 }
1419
1420 private function fillProfile(array $vals)
1421 {
22771578 1422 $pf = Profile::get($vals[0], 0x0, $this->visibility);
1f8250e4 1423 $pf->setFetchedFields($this->fields);
1a9affb7 1424
8cf886dc
RB
1425 if ($this->hasData(Profile::FETCH_PHONES, $vals)) {
1426 $pf->setPhones($vals[Profile::FETCH_PHONES]);
9f21bd15 1427 }
8cf886dc
RB
1428 if ($this->hasData(Profile::FETCH_ADDRESSES, $vals)) {
1429 $pf->setAddresses($vals[Profile::FETCH_ADDRESSES]);
1430 }
1431 if ($this->hasData(Profile::FETCH_JOBS, $vals)) {
1432 $pf->setJobs($vals[Profile::FETCH_JOBS]);
1433 }
3ac45f10
PC
1434 if ($this->hasData(Profile::FETCH_JOB_TERMS, $vals)) {
1435 $pf->setJobTerms($vals[Profile::FETCH_JOB_TERMS]);
1436 }
8cf886dc
RB
1437
1438 if ($this->hasData(Profile::FETCH_CORPS, $vals)) {
9f21bd15
RB
1439 $pf->setCorps($vals[Profile::FETCH_CORPS]);
1440 }
8cf886dc 1441 if ($this->hasData(Profile::FETCH_EDU, $vals)) {
26ca919b 1442 $pf->setEducations($vals[Profile::FETCH_EDU]);
9f21bd15 1443 }
8cf886dc 1444 if ($this->hasData(Profile::FETCH_MEDALS, $vals)) {
9f21bd15
RB
1445 $pf->setMedals($vals[Profile::FETCH_MEDALS]);
1446 }
8cf886dc 1447 if ($this->hasData(Profile::FETCH_NETWORKING, $vals)) {
9f21bd15
RB
1448 $pf->setNetworking($vals[Profile::FETCH_NETWORKING]);
1449 }
9f21bd15
RB
1450
1451 return $pf;
1452 }
1453
1454 public function next()
1455 {
1456 $vals = $this->iterator->next();
1457 if ($vals == null) {
1458 return null;
1459 }
1460 return $this->fillProfile($vals);
1461 }
1462
1463 public function first()
1464 {
1465 return $this->iterator->first();
1466 }
1467
1468 public function last()
1469 {
1470 return $this->iterator->last();
1471 }
1472
1473 public function total()
1474 {
1475 return $this->iterator->total();
1476 }
1477}
1478
e7b93962
FB
1479// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1480?>