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