Add ax_id field in the postal address export.
[platal.git] / classes / profile.php
CommitLineData
e7b93962
FB
1<?php
2/***************************************************************************
c441aabe 3 * Copyright (C) 2003-2014 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
bc0276a2
NI
734 /**
735 * Retrieve the name of the corps which has been done.
736 *
737 * Note: this function first tries getCorps(), and if this field is blank
738 * tries to find an education which degree is "Corps".
739 *
740 * Returns an empty string if nothing has been found.
741 */
742 public function getCorpsName()
743 {
744 $corps = $this->getCorps();
745 if ($corps && $corps->current) {
746 $corpsList = DirEnum::getOptions(DirEnum::CURRENTCORPS);
747 return $corpsList[$corps->current];
748 }
749
750 foreach ($this->getExtraEducations() as $edu) {
751 if (!strcasecmp($edu->degree, 'Corps')) {
752 if ($edu->school_short) {
753 return $edu->school_short;
754 } elseif ($edu->school) {
755 return $edu->school;
756 }
757 }
758 }
759 return '';
760 }
761
04a94b1d
FB
762 /** Networking
763 */
d4d395bb
RB
764 private $networks = null;
765 public function setNetworking(ProfileNetworking $nw)
766 {
767 $this->networks = $nw;
768 }
04a94b1d
FB
769
770 public function getNetworking($flags, $limit = null)
771 {
1f8250e4 772 if ($this->networks == null && !$this->fetched(self::FETCH_NETWORKING)) {
dad85695
FB
773 $nw = $this->getProfileField(self::FETCH_NETWORKING);
774 if ($nw) {
775 $this->setNetworking($nw);
776 }
04a94b1d 777 }
0907501b 778 if ($this->networks == null) {
598c57f6 779 return array();
0907501b 780 }
d4d395bb 781 return $this->networks->get($flags, $limit);
04a94b1d
FB
782 }
783
784 public function getWebSite()
785 {
786 $site = $this->getNetworking(self::NETWORKING_WEB, 1);
598c57f6 787 if (count($site) != 1) {
04a94b1d
FB
788 return null;
789 }
598c57f6 790 $site = array_pop($site);
dad85695 791 return $site;
04a94b1d
FB
792 }
793
794
e718bd18
FB
795 /** Jobs
796 */
949fc736
RB
797 private $jobs = null;
798 public function setJobs(ProfileJobs $jobs)
799 {
800 $this->jobs = $jobs;
801 $this->consolidateFields();
802 }
e718bd18 803
dbcc3b3d 804 private function fetchJobs()
e718bd18 805 {
1f8250e4 806 if ($this->jobs == null && !$this->fetched(self::FETCH_JOBS)) {
61ee68c7
FB
807 $jobs = $this->getProfileField(self::FETCH_JOBS);
808 if ($jobs) {
809 $this->setJobs($jobs);
dbcc3b3d 810 $this->fetchAddresses();
61ee68c7 811 }
e718bd18 812 }
dbcc3b3d
RB
813 }
814
815 public function getJobs($flags, $limit = null)
816 {
817 $this->fetchJobs();
949fc736 818
0907501b 819 if ($this->jobs == null) {
598c57f6 820 return array();
0907501b 821 }
949fc736 822 return $this->jobs->get($flags, $limit);
e718bd18
FB
823 }
824
44ec5eb5 825 public function getMainJob()
e718bd18
FB
826 {
827 $job = $this->getJobs(self::JOBS_MAIN, 1);
598c57f6 828 if (count($job) != 1) {
e718bd18
FB
829 return null;
830 }
598c57f6 831 return array_pop($job);
e718bd18
FB
832 }
833
3ac45f10
PC
834 /** JobTerms
835 */
836 private $jobterms = null;
837 public function setJobTerms(ProfileJobTerms $jobterms)
838 {
839 $this->jobterms = $jobterms;
840 $this->consolidateFields();
841 }
842
4d1f0f6b
RB
843 private $mentor_countries = null;
844 public function setMentoringCountries(ProfileMentoringCountries $countries)
845 {
846 $this->mentor_countries = $countries;
847 }
848
849 public function getMentoringCountries()
850 {
851 if ($this->mentor_countries == null && !$this->fetched(self::FETCH_MENTOR_COUNTRY)) {
67972120
SJ
852 $countries = $this->getProfileField(self::FETCH_MENTOR_COUNTRY);
853 if ($countries) {
854 $this->setMentoringCountries($countries);
855 }
4d1f0f6b
RB
856 }
857
858 if ($this->mentor_countries == null) {
859 return array();
860 } else {
861 return $this->mentor_countries->countries;
862 }
863 }
864
3ac45f10
PC
865 /** List of job terms to specify mentoring */
866 private $mentor_terms = null;
867 /**
868 * set job terms to specify mentoring
869 * @param $terms a ProfileMentoringTerms object listing terms only for this profile
870 */
871 public function setMentoringTerms(ProfileMentoringTerms $terms)
872 {
873 $this->mentor_terms = $terms;
874 }
875 /**
876 * get all job terms that specify mentoring
877 * @return an array of JobTerms objects
878 */
879 public function getMentoringTerms()
880 {
881 if ($this->mentor_terms == null && !$this->fetched(self::FETCH_MENTOR_TERMS)) {
67972120
SJ
882 $terms = $this->getProfileField(self::FETCH_MENTOR_TERMS);
883 if ($terms) {
884 $this->setMentoringTerms($terms);
885 }
3ac45f10
PC
886 }
887
888 if ($this->mentor_terms == null) {
889 return array();
890 } else {
891 return $this->mentor_terms->get();
892 }
893 }
894
7e0635c2
SJ
895 /* Skills */
896 private $skills = null;
897 public function setSkills(ProfileSkills $skills)
898 {
899 $this->skills = $skills;
900 }
901 public function getSkills()
902 {
903 if ($this->skills == null && !$this->fetched(self::FETCH_SKILL)) {
67972120
SJ
904 $skills = $this->getProfileField(self::FETCH_SKILL);
905 if ($skills) {
906 $this->setSkills($skills);
907 }
7e0635c2
SJ
908 }
909
910 if ($this->skills == null) {
911 return array();
912 } else {
913 return $this->skills->skills;
914 }
915 }
916
917 /* Languades */
918 private $languages = null;
919 public function setLanguages(ProfileLanguages $languages)
920 {
921 $this->languages = $languages;
922 }
923 public function getLanguages()
924 {
925 if ($this->languages == null && !$this->fetched(self::FETCH_LANGUAGE)) {
67972120
SJ
926 $languages = $this->getProfileField(self::FETCH_LANGUAGE);
927 if ($languages) {
928 $this->setLanguages($languages);
929 }
7e0635c2
SJ
930 }
931
932 if ($this->languages == null) {
933 return array();
934 } else {
935 return $this->languages->languages;
936 }
937 }
938
080632c7
RB
939 /** DeltaTen
940 */
941
942 /** Find out whether this profile may take part to the "DeltaTen" operation.
943 * @param $role Which role to select ('young' or 'old')
944 * @return Boolean: whether it is enabled.
945 */
946 const DELTATEN_YOUNG = 'young';
947 const DELTATEN_OLD = 'old';
948 public function isDeltaTenEnabled($role)
949 {
950 global $globals;
951 switch ($role) {
952 case self::DELTATEN_YOUNG:
953 return ($this->mainGrade() == UserFilter::GRADE_ING && $this->yearpromo() >= $globals->deltaten->first_promo_young);
954 case self::DELTATEN_OLD:
955 // Roughly compute the current promo in second year on the campus:
956 // Promo 2010 is in second year between 09/2011 and 08/2012 => use 2012.
957 // DeltaTen program begins around January of the second year.
958 $promo_on_platal = ((int) date('Y')) - 2;
959 return ($this->mainGrade() == UserFilter::GRADE_ING && $this->yearpromo() >= $globals->deltaten->first_promo_young - 10 && $this->yearpromo() <= $promo_on_platal - 10);
960 default:
961 Platal::assert(false, "Invalid DeltaTen role $role");
962 }
963 }
964
965 /** Retrieve the "Deltaten" message of the user.
966 * Returns "null" if the message is empty or the user is not taking part to the
967 * DeltaTen operation.
968 */
969 public function getDeltatenMessage()
970 {
971 if ($this->isDeltaTenEnabled(self::DELTATEN_OLD)) {
972 return $this->deltaten_message;
973 } else {
974 return null;
975 }
976 }
3ac45f10 977
5c005b37
RB
978 /* Binets
979 */
980 public function getBinets()
981 {
22771578 982 if ($this->visibility->isVisible(Visibility::EXPORT_PRIVATE)) {
875a88d3
RB
983 return XDB::fetchColumn('SELECT binet_id
984 FROM profile_binets
985 WHERE pid = {?}', $this->id());
986 } else {
987 return array();
988 }
5c005b37 989 }
ccf88cca 990
7f3c6bf4
TM
991 public function getFullBinets()
992 {
993 if ($this->visibility->isVisible(Visibility::EXPORT_PRIVATE)) {
994 return XDB::fetchAllAssoc('SELECT binet_id, text, url
995 FROM profile_binets AS pb
996 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
997 WHERE pid = {?}', $this->id());
998 } else {
999 return array();
1000 }
1001 }
ccf88cca 1002
97b71de5
RB
1003 public function getBinetsNames()
1004 {
22771578 1005 if ($this->visibility->isVisible(Visibility::EXPORT_PRIVATE)) {
875a88d3
RB
1006 return XDB::fetchColumn('SELECT text
1007 FROM profile_binets AS pb
1008 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
1009 WHERE pb.pid = {?}', $this->id());
1010 } else {
1011 return array();
1012 }
97b71de5 1013 }
5c005b37 1014
26ca919b
RB
1015 /* Medals
1016 */
1017 private $medals = null;
1018 public function setMedals(ProfileMedals $medals)
1019 {
1020 $this->medals = $medals;
1021 }
1022
1023 public function getMedals()
1024 {
1f8250e4 1025 if ($this->medals == null && !$this->fetched(self::FETCH_MEDALS)) {
67972120
SJ
1026 $medals = $this->getProfileField(self::FETCH_MEDALS);
1027 if ($medals) {
1028 $this->setMedals($medals);
1029 }
26ca919b
RB
1030 }
1031 if ($this->medals == null) {
1032 return array();
1033 }
1034 return $this->medals->medals;
1035 }
e718bd18 1036
148af7a9
RB
1037 /** Sharing data with partner websites
1038 */
1039 private $partners_settings = null;
1040 public function setPartnersSettings(ProfilePartnerSharing $partners_settings)
1041 {
1042 $this->partners_settings = $partners_settings;
1043 }
1044
1045 public function getPartnerSettings($partner_id)
1046 {
f0f8c375 1047 if ($this->partners_settings === null && !$this->fetched(self::FETCH_PARTNER)) {
67972120
SJ
1048 $settings = $this->getProfileField(self::FETCH_PARTNER);
1049 if ($settings) {
1050 $this->setPartnersSettings($settings);
1051 }
148af7a9 1052 }
f0f8c375 1053 if ($this->partners_settings === null) {
148af7a9
RB
1054 return PartnerSettings::getEmpty($partner_id);
1055 }
1056 return $this->partners_settings->get($partner_id);
1057 }
1058
94590511
SJ
1059 public function compareNames($firstname, $lastname)
1060 {
1061 $_lastname = mb_strtoupper($this->lastName());
1062 $_firstname = mb_strtoupper($this->firstName());
1063 $lastname = mb_strtoupper($lastname);
1064 $firstname = mb_strtoupper($firstname);
1065
1066 $isOk = (mb_strtoupper($_firstname) == mb_strtoupper($firstname));
1067 $tokens = preg_split("/[ \-']/", $lastname, -1, PREG_SPLIT_NO_EMPTY);
1068 $maxlen = 0;
1069
1070 foreach ($tokens as $str) {
1071 $isOk &= (strpos($_lastname, $str) !== false);
1072 $maxlen = max($maxlen, strlen($str));
1073 }
1074
1075 return ($isOk && ($maxlen > 2 || $maxlen == strlen($_lastname)));
1076 }
1077
aaffb7b2
FB
1078 /* Export to JSON
1079 */
1080 public function export()
1081 {
1082 return array(
1083 'hrpid' => $this->hrid(),
1084 'display_name' => $this->shortName(),
1085 'full_name' => $this->fullName(),
1086 'directory_name' => $this->directory_name,
1087 'promo' => $this->promo(),
1088 'year_promo' => $this->yearpromo(),
1089 'is_active' => $this->isActive(),
1090 'first_name' => $this->firstName(),
1091 'last_name' => $this->lastName(),
1092 'is_female' => $this->isFemale(),
1093 );
1094 }
1095
22771578 1096 private static function fetchProfileData(array $pids, $respect_order = true, $fields = 0x0000, $visibility = null)
b774ddab
FB
1097 {
1098 if (count($pids) == 0) {
7a8da8e8 1099 return null;
b774ddab 1100 }
0d906109
RB
1101
1102 if ($respect_order) {
1103 $order = 'ORDER BY ' . XDB::formatCustomOrder('p.pid', $pids);
1104 } else {
1105 $order = '';
1106 }
1107
22771578
RB
1108 if ($visibility === null) {
1109 $visibility = Visibility::defaultForRead();
38a86f60 1110 }
9f21bd15 1111
3e2442cd
RB
1112 $it = XDB::Iterator('SELECT p.pid, p.hrpid, p.xorg_id, p.ax_id, p.birthdate, p.birthdate_ref,
1113 p.next_birthday, p.deathdate, p.deathdate_rec, p.sex = \'female\' AS sex,
77d2ae52
RB
1114 IF ({?}, p.cv, NULL) AS cv, p.medals_pub, p.alias_pub, p.email_directory,
1115 p.last_change, p.nationality1, p.nationality2, p.nationality3,
38a86f60 1116 IF (p.freetext_pub >= {?}, p.freetext, NULL) AS freetext,
d718e91c 1117 pe.entry_year, pe.grad_year, pe.promo_year, pe.program, pe.fieldid,
348b3844 1118 IF ({?}, pse.text, NULL) AS section,
0e1dfbad
SJ
1119 ppn.firstname_main AS firstname, ppn.lastname_main AS lastname, IF ({?}, pn.name, NULL) AS nickname,
1120 IF (ppn.firstname_ordinary = \'\', ppn.firstname_main, ppn.firstname_ordinary) AS firstname_ordinary,
8fc92b60 1121 IF (ppn.lastname_ordinary = \'\', ppn.lastname_main, ppn.lastname_ordinary) AS lastname_ordinary,
09e54905
SJ
1122 pd.yourself, pd.promo, pd.short_name, pd.public_name AS full_name,
1123 pd.directory_name, pd.public_name, pd.private_name,
38a86f60 1124 IF (pp.pub >= {?}, pp.display_tel, NULL) AS mobile,
db492b02 1125 (ph.pub >= {?} AND ph.attach IS NOT NULL) AS has_photo, ph.pub as photo_pub,
7988f7d6 1126 ph.x AS photo_width, ph.y AS photo_height,
9f21bd15 1127 p.last_change < DATE_SUB(NOW(), INTERVAL 365 DAY) AS is_old,
bdef0d33 1128 pm.expertise AS mentor_expertise,
080632c7 1129 IF ({?}, pdt.message, NULL) AS deltaten_message,
9f21bd15
RB
1130 ap.uid AS owner_id
1131 FROM profiles AS p
1132 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1133 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
97b71de5 1134 LEFT JOIN profile_section_enum AS pse ON (pse.id = p.section)
0e1dfbad
SJ
1135 INNER JOIN profile_public_names AS ppn ON (ppn.pid = p.pid)
1136 LEFT JOIN profile_private_names AS pn ON (pn.pid = p.pid AND type = \'nickname\')
9f21bd15
RB
1137 LEFT JOIN profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = \'user\' AND tel_type = \'mobile\')
1138 LEFT JOIN profile_photos AS ph ON (ph.pid = p.pid)
bdef0d33 1139 LEFT JOIN profile_mentor AS pm ON (pm.pid = p.pid)
080632c7 1140 LEFT JOIN profile_deltaten AS pdt ON (pdt.pid = p.pid)
9f21bd15 1141 LEFT JOIN account_profiles AS ap ON (ap.pid = p.pid AND FIND_IN_SET(\'owner\', ap.perms))
3e2442cd 1142 WHERE p.pid IN {?}
9f21bd15 1143 GROUP BY p.pid
3e2442cd 1144 ' . $order,
22771578 1145 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // CV
38a86f60 1146 $visibility->level(), // freetext
22771578
RB
1147 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // section
1148 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // nickname
38a86f60
RB
1149 $visibility->level(), // mobile
1150 $visibility->level(), // photo
22771578 1151 $visibility->isVisible(Visibility::EXPORT_PRIVATE), // deltaten_message
3e2442cd
RB
1152 $pids
1153 );
31ef12ef 1154 return new ProfileIterator($it, $pids, $fields, $visibility);
b774ddab
FB
1155 }
1156
1157 public static function getPID($login)
1158 {
1159 if ($login instanceof PlUser) {
1160 return XDB::fetchOneCell('SELECT pid
1161 FROM account_profiles
1162 WHERE uid = {?} AND FIND_IN_SET(\'owner\', perms)',
1163 $login->id());
9f21bd15 1164 } else if (ctype_digit($login)) {
b774ddab
FB
1165 return XDB::fetchOneCell('SELECT pid
1166 FROM profiles
1167 WHERE pid = {?}', $login);
1168 } else {
1169 return XDB::fetchOneCell('SELECT pid
1170 FROM profiles
1171 WHERE hrpid = {?}', $login);
1172 }
1173 }
1174
0d906109
RB
1175 public static function getPIDsFromUIDs($uids, $respect_order = true)
1176 {
1177 if ($respect_order) {
1178 $order = 'ORDER BY ' . XDB::formatCustomOrder('uid', $uids);
1179 } else {
1180 $order = '';
1181 }
1182 return XDB::fetchAllAssoc('uid', 'SELECT ap.uid, ap.pid
1183 FROM account_profiles AS ap
1184 WHERE FIND_IN_SET(\'owner\', ap.perms)
9f21bd15
RB
1185 AND ap.uid IN ' . XDB::formatArray($uids) .'
1186 ' . $order);
0d906109 1187 }
b774ddab 1188
e7b93962
FB
1189 /** Return the profile associated with the given login.
1190 */
22771578 1191 public static function get($login, $fields = 0x0000, $visibility = null)
a3118782 1192 {
22771578
RB
1193 if ($visibility === null) {
1194 $visibility = Visibility::defaultForRead();
38a86f60
RB
1195 }
1196
641f2115 1197 if (is_array($login)) {
38a86f60 1198 $pf = new Profile($login, $visibility);
1a9affb7 1199 return $pf;
641f2115 1200 }
b774ddab
FB
1201 $pid = self::getPID($login);
1202 if (!is_null($pid)) {
9f21bd15 1203 $it = self::iterOverPIDs(array($pid), false, $fields, $visibility);
0d906109 1204 return $it->next();
b774ddab 1205 } else {
efe597c5
FB
1206 /* Let say we can identify a profile using the identifiers of its owner.
1207 */
455ea0c9
FB
1208 if (!($login instanceof PlUser)) {
1209 $user = User::getSilent($login);
1210 if ($user && $user->hasProfile()) {
22771578 1211 return $user->profile(false, $fields, $visibility);
455ea0c9 1212 }
efe597c5 1213 }
3e53a496 1214 return null;
e7b93962
FB
1215 }
1216 }
a3118782 1217
22771578 1218 public static function iterOverUIDs($uids, $respect_order = true, $fields = 0x0000, $visibility = null)
0d906109 1219 {
9f21bd15 1220 return self::iterOverPIDs(self::getPIDsFromUIDs($uids), $respect_order, $fields, $visibility);
0d906109
RB
1221 }
1222
22771578 1223 public static function iterOverPIDs($pids, $respect_order = true, $fields = 0x0000, $visibility = null)
0d906109 1224 {
9f21bd15 1225 return self::fetchProfileData($pids, $respect_order, $fields, $visibility);
0d906109
RB
1226 }
1227
b774ddab
FB
1228 /** Return profiles for the list of pids.
1229 */
22771578 1230 public static function getBulkProfilesWithPIDs(array $pids, $fields = 0x0000, $visibility = null)
b774ddab
FB
1231 {
1232 if (count($pids) == 0) {
1233 return array();
1234 }
9f21bd15 1235 $it = self::iterOverPIDs($pids, true, $fields, $visibility);
b774ddab 1236 $profiles = array();
0d906109
RB
1237 while ($p = $it->next()) {
1238 $profiles[$p->id()] = $p;
b774ddab
FB
1239 }
1240 return $profiles;
1241 }
1242
1243 /** Return profiles for uids.
1244 */
22771578 1245 public static function getBulkProfilesWithUIDS(array $uids, $fields = 0x000, $visibility = null)
b774ddab
FB
1246 {
1247 if (count($uids) == 0) {
1248 return array();
1249 }
e4f1d258 1250 return self::getBulkProfilesWithPIDs(self::getPIDsFromUIDs($uids), $fields, $visibility);
b774ddab
FB
1251 }
1252
913a4e90
RB
1253 public static function isDisplayName($name)
1254 {
1255 return $name == self::DN_FULL || $name == self::DN_DISPLAY
1256 || $name == self::DN_YOURSELF || $name == self::DN_DIRECTORY
1257 || $name == self::DN_PRIVATE || $name == self::DN_PUBLIC
1258 || $name == self::DN_SHORT || $name == self::DN_SORT;
1259 }
1260
a9ef52c9
RB
1261 /** Returns the closest "accounts only" name type for $name
1262 */
1263 public static function getAccountEquivalentName($name)
1264 {
b0788bf4
SJ
1265 switch ($name) {
1266 case self::DN_DIRECTORY:
a9ef52c9 1267 return 'directory_name';
b0788bf4
SJ
1268 case self::DN_SORT:
1269 return 'sort_name';
1270 case self::DN_FULL:
1271 case self::DN_PUBLIC:
1272 case self::DN_PRIVATE:
1273 case self::DN_SHORT:
a9ef52c9 1274 return 'full_name';
b0788bf4
SJ
1275 case self::DN_YOURSELF:
1276 return 'display_name';
1277 default:
a9ef52c9
RB
1278 return 'display_name';
1279 }
1280 }
1281
bedc4295 1282 public static function rebuildSearchTokens($pids, $transaction = true)
726eaf7a 1283 {
0e1dfbad 1284 require_once 'name.func.inc.php';
5acd53a9
FB
1285 if (!is_array($pids)) {
1286 $pids = array($pids);
1287 }
0e1dfbad
SJ
1288 $keys = XDB::iterator("(SELECT pid, name, type, IF(type = 'nickname', 2, 1) AS score, '' AS public
1289 FROM profile_private_names
1290 WHERE pid IN {?})
1291 UNION
1292 (SELECT pid, lastname_main, 'lastname' AS type, 10 AS score, 'public' AS public
1293 FROM profile_public_names
1294 WHERE lastname_main != '' AND pid IN {?})
1295 UNION
1296 (SELECT pid, lastname_marital, 'lastname' AS type, 10 AS score, 'public' AS public
1297 FROM profile_public_names
1298 WHERE lastname_marital != '' AND pid IN {?})
1299 UNION
1300 (SELECT pid, lastname_ordinary, 'lastname' AS type, 10 AS score, 'public' AS public
1301 FROM profile_public_names
1302 WHERE lastname_ordinary != '' AND pid IN {?})
1303 UNION
1304 (SELECT pid, firstname_main, 'firstname' AS type, 10 AS score, 'public' AS public
1305 FROM profile_public_names
1306 WHERE firstname_main != '' AND pid IN {?})
1307 UNION
1308 (SELECT pid, firstname_ordinary, 'firstname' AS type, 10 AS score, 'public' AS public
1309 FROM profile_public_names
1310 WHERE firstname_ordinary != '' AND pid IN {?})
1311 UNION
1312 (SELECT pid, pseudonym, 'nickname' AS type, 10 AS score, 'public' AS public
1313 FROM profile_public_names
1314 WHERE pseudonym != '' AND pid IN {?})",
1315 $pids, $pids, $pids, $pids, $pids, $pids, $pids);
5acd53a9 1316 $names = array();
2f62eba7 1317 while ($key = $keys->next()) {
726eaf7a
SJ
1318 if ($key['name'] == '') {
1319 continue;
1320 }
0e1dfbad 1321 $pid = $key['pid'];
5ed1cce8 1322 $toks = split_name_for_search($key['name']);
80bc45c2
FB
1323 $toks = array_reverse($toks);
1324
1325 /* Split the score between the tokens to avoid the user to be over-rated.
1326 * Let says my user name is "Machin-Truc Bidule" and I also have a user named
1327 * 'Machin Truc'. Distributing the score force "Machin Truc" to be displayed
1328 * before "Machin-Truc" for both "Machin Truc" and "Machin" searches.
1329 */
1330 $eltScore = ceil(((float)$key['score'])/((float)count($toks)));
726eaf7a 1331 $token = '';
80bc45c2
FB
1332 foreach ($toks as $tok) {
1333 $token = $tok . $token;
5600b2fe 1334 $names["$pid-$token"] = XDB::format('({?}, {?}, {?}, {?}, {?}, {?})',
5acd53a9 1335 $token, $pid, soundex_fr($token),
0e1dfbad 1336 $eltScore, $key['public'], $key['type']);
726eaf7a
SJ
1337 }
1338 }
bedc4295
FB
1339 if ($transaction) {
1340 XDB::startTransaction();
1341 }
5acd53a9
FB
1342 XDB::execute('DELETE FROM search_name
1343 WHERE pid IN {?}',
1344 $pids);
1345 if (count($names) > 0) {
5600b2fe 1346 XDB::rawExecute('INSERT INTO search_name (token, pid, soundex, score, flags, general_type)
80bc45c2 1347 VALUES ' . implode(', ', $names));
5acd53a9 1348 }
bedc4295
FB
1349 if ($transaction) {
1350 XDB::commit();
1351 }
69b46857
SJ
1352 }
1353
1354 /** The school identifier consists of 6 digits. The first 3 represent the
1355 * promotion entry year. The last 3 indicate the student's rank.
aab2ffdd 1356 *
69b46857
SJ
1357 * Our identifier consists of 8 digits and both half have the same role.
1358 * This enables us to deal with bigger promotions and with a wider range
1359 * of promotions.
1360 *
1361 * getSchoolId returns a school identifier given one of ours.
1362 * getXorgId returns a X.org identifier given a school identifier.
1363 */
1364 public static function getSchoolId($xorgId)
1365 {
1366 if (!preg_match('/^[0-9]{8}$/', $xorgId)) {
1367 return null;
1368 }
1369
1370 $year = intval(substr($xorgId, 0, 4));
1371 $rank = intval(substr($xorgId, 5, 3));
1372 if ($year < 1996) {
1373 return null;
1374 } elseif ($year < 2000) {
1375 $year = intval(substr(1900 - $year, 1, 3));
1376 return sprintf('%02u0%03u', $year, $rank);
1377 } else {
1378 $year = intval(substr(1900 - $year, 1, 3));
1379 return sprintf('%03u%03u', $year, $rank);
1380 }
1381 }
726eaf7a 1382
69b46857
SJ
1383 public static function getXorgId($schoolId)
1384 {
94590511 1385 if (!preg_match('/^[0-9]{6}$/', $schoolId)) {
a292484d
SJ
1386 return null;
1387 }
1388
69b46857
SJ
1389 $year = intval(substr($schoolId, 0, 3));
1390 $rank = intval(substr($schoolId, 3, 3));
726eaf7a 1391
69b46857
SJ
1392 if ($year > 200) {
1393 $year /= 10;
1394 }
1395 if ($year < 96) {
1396 return null;
1397 } else {
1398 return sprintf('%04u%04u', 1900 + $year, $rank);
1399 }
726eaf7a 1400 }
e7b93962
FB
1401}
1402
31ef12ef
RB
1403
1404/** Iterator over a set of Profiles
1405 */
1406class ProfileIterator implements PlIterator
9f21bd15
RB
1407{
1408 private $iterator = null;
1409 private $fields;
1a9affb7 1410 private $visibility;
9f21bd15 1411
3ac45f10
PC
1412 const FETCH_ALL = 0x000033F; // FETCH_ADDRESSES | FETCH_CORPS | FETCH_EDU | FETCH_JOBS | FETCH_MEDALS | FETCH_NETWORKING | FETCH_PHONES | FETCH_JOB_TERMS
1413
22771578 1414 public function __construct(PlIterator $it, array $pids, $fields = 0x0000, $visibility = null)
9f21bd15
RB
1415 {
1416 require_once 'profilefields.inc.php';
1a9affb7 1417
22771578
RB
1418 if ($visibility === null) {
1419 $visibility = Visibility::defaultForRead();
1a9affb7
RB
1420 }
1421
9f21bd15 1422 $this->fields = $fields;
1a9affb7 1423 $this->visibility = $visibility;
9f21bd15
RB
1424
1425 $subits = array();
1426 $callbacks = array();
1427
1428 $subits[0] = $it;
1429 $callbacks[0] = PlIteratorUtils::arrayValueCallback('pid');
1430 $cb = PlIteratorUtils::objectPropertyCallback('pid');
1431
3ac45f10
PC
1432 $fields = $fields & self::FETCH_ALL;
1433 for ($field = 1; $field < $fields; $field *= 2) {
1434 if (($fields & $field) ) {
1435 $callbacks[$field] = $cb;
1436 $subits[$field] = new ProfileFieldIterator($field, $pids, $visibility);
1437 }
9f21bd15
RB
1438 }
1439
9f21bd15
RB
1440 $this->iterator = PlIteratorUtils::parallelIterator($subits, $callbacks, 0);
1441 }
1442
1f8250e4 1443 private function hasData($field, $vals)
9f21bd15 1444 {
1f8250e4 1445 return ($this->fields & $field) && ($vals[$field] != null);
9f21bd15
RB
1446 }
1447
1448 private function fillProfile(array $vals)
1449 {
22771578 1450 $pf = Profile::get($vals[0], 0x0, $this->visibility);
1f8250e4 1451 $pf->setFetchedFields($this->fields);
1a9affb7 1452
8cf886dc
RB
1453 if ($this->hasData(Profile::FETCH_PHONES, $vals)) {
1454 $pf->setPhones($vals[Profile::FETCH_PHONES]);
9f21bd15 1455 }
8cf886dc
RB
1456 if ($this->hasData(Profile::FETCH_ADDRESSES, $vals)) {
1457 $pf->setAddresses($vals[Profile::FETCH_ADDRESSES]);
1458 }
1459 if ($this->hasData(Profile::FETCH_JOBS, $vals)) {
1460 $pf->setJobs($vals[Profile::FETCH_JOBS]);
1461 }
3ac45f10
PC
1462 if ($this->hasData(Profile::FETCH_JOB_TERMS, $vals)) {
1463 $pf->setJobTerms($vals[Profile::FETCH_JOB_TERMS]);
1464 }
8cf886dc
RB
1465
1466 if ($this->hasData(Profile::FETCH_CORPS, $vals)) {
9f21bd15
RB
1467 $pf->setCorps($vals[Profile::FETCH_CORPS]);
1468 }
8cf886dc 1469 if ($this->hasData(Profile::FETCH_EDU, $vals)) {
26ca919b 1470 $pf->setEducations($vals[Profile::FETCH_EDU]);
9f21bd15 1471 }
8cf886dc 1472 if ($this->hasData(Profile::FETCH_MEDALS, $vals)) {
9f21bd15
RB
1473 $pf->setMedals($vals[Profile::FETCH_MEDALS]);
1474 }
8cf886dc 1475 if ($this->hasData(Profile::FETCH_NETWORKING, $vals)) {
9f21bd15
RB
1476 $pf->setNetworking($vals[Profile::FETCH_NETWORKING]);
1477 }
9f21bd15
RB
1478
1479 return $pf;
1480 }
1481
1482 public function next()
1483 {
1484 $vals = $this->iterator->next();
1485 if ($vals == null) {
1486 return null;
1487 }
1488 return $this->fillProfile($vals);
1489 }
1490
1491 public function first()
1492 {
1493 return $this->iterator->first();
1494 }
1495
1496 public function last()
1497 {
1498 return $this->iterator->last();
1499 }
1500
1501 public function total()
1502 {
1503 return $this->iterator->total();
1504 }
1505}
1506
448c8cdc 1507// vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
e7b93962 1508?>