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