2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 class Profile
implements PlExportable
26 const LASTNAME
= 'lastname';
27 const FIRSTNAME
= 'firstname';
28 const NICKNAME
= 'nickname';
29 const PSEUDONYM
= 'pseudonym';
32 const VN_MARITAL
= 'marital';
33 const VN_ORDINARY
= 'ordinary';
34 const VN_OTHER
= 'other';
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';
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';
51 static public $cycles = array(
52 self
::DEGREE_X
=> 'polytechnicien',
53 self
::DEGREE_M
=> 'master',
54 self
::DEGREE_D
=> 'docteur'
56 static public $cycle_prefixes = array(
57 self
::DEGREE_X
=> 'X',
58 self
::DEGREE_M
=> 'M',
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
)
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;
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;
79 const JOBS_MAIN
= 0x00001000;
80 const JOBS_ALL
= 0x00002000;
81 const JOBS_FINISHED
= 0x00004000;
82 const JOBS_CURRENT
= 0x00008000;
84 const NETWORKING_ALL
= 0x00070000;
85 const NETWORKING_WEB
= 0x00010000;
86 const NETWORKING_IM
= 0x00020000;
87 const NETWORKING_SOCIAL
= 0x00040000;
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;
95 const PHONE_TYPE_FAX
= 0x01000000;
96 const PHONE_TYPE_FIXED
= 0x02000000;
97 const PHONE_TYPE_MOBILE
= 0x04000000;
98 const PHONE_TYPE_ANY
= 0x07000000;
100 const PHONE_ANY
= 0x07F00000;
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;
108 const FETCH_MENTOR_COUNTRY
= 0x000080;
109 const FETCH_PHONES
= 0x000100;
110 const FETCH_JOB_TERMS
= 0x000200;
111 const FETCH_MENTOR_TERMS
= 0x000400;
112 const FETCH_DELTATEN
= 0x000800;
114 const FETCH_MINIFICHES
= 0x00012D; // FETCH_ADDRESSES | FETCH_EDU | FETCH_JOBS | FETCH_NETWORKING | FETCH_PHONES
116 const FETCH_ALL
= 0x000FFF; // OR of FETCH_*
118 static public $descriptions = array(
119 'search_names' => 'Noms',
120 'nationality1' => 'Nationalité',
121 'nationality2' => '2e nationalité',
122 'nationality3' => '3e nationalité',
123 'promo_display' => 'Promotion affichée',
124 'email_directory' => 'Email annuaire papier',
125 'networking' => 'Messageries…',
126 'tels' => 'Téléphones',
127 'edus' => 'Formations',
128 'main_edus' => 'Formations à l\'X',
129 'promo' => 'Promotion de sortie',
130 'birthdate' => 'Date de naissance',
131 'yourself' => 'Nom affiché',
132 'freetext' => 'Commentaire',
133 'freetext_pub' => 'Affichage du commentaire',
134 'photo' => 'Photographie',
135 'photo_pub' => 'Affichage de la photographie',
136 'addresses' => 'Adresses',
140 'section' => 'Section',
141 'binets' => 'Binets',
142 'medals' => 'Décorations',
143 'medals_pub' => 'Affichage des décorations',
144 'competences' => 'Compétences',
145 'langues' => 'Langues',
146 'expertise' => 'Expertises (mentoring)',
147 'terms' => 'Compétences (mentoring)',
148 'countries' => 'Pays (mentoring)',
149 'deltaten' => 'Opération N N-10',
152 private $fetched_fields = 0x000000;
157 private $owner_fetched = false
;
158 private $data = array();
160 private $visibility = null
;
163 private function __construct(array $data, ProfileVisibility
$visibility = null
)
166 $this->pid
= $this->data
['pid'];
167 $this->hrpid
= $this->data
['hrpid'];
168 if ($visibility == null
) {
169 $visibility = ProfileVisibility
::defaultForRead();
171 $this->visibility
= $visibility;
179 public function hrid()
184 public function owner()
186 if ($this->owner
== null
&& !$this->owner_fetched
) {
187 $this->owner_fetched
= true
;
188 $this->owner
= User
::getSilent($this);
193 public function isActive()
195 if ($this->owner()) {
196 return $this->owner
->isActive();
201 public function promo($details = false
)
203 if ($details && ($this->program ||
$this->fieldid
)) {
205 if ($this->program
) {
206 $text[] = $this->program
;
208 if ($this->fieldid
) {
209 $fieldsList = DirEnum
::getOptions(DirEnum
::EDUFIELDS
);
210 $text[] = $fieldsList[$this->fieldid
];
212 return $this->promo
. ' (' . implode(', ', $text) . ')';
218 public function yearpromo()
220 return $this->promo_year
;
223 /** Check if user is an orange (associated with several promos)
225 public function isMultiPromo()
227 return $this->grad_year
!= $this->entry_year +
$this->mainEducationDuration();
230 /** Returns an array with all associated promo years.
232 public function yearspromo()
235 $d = -$this->deltaPromoToGradYear();
236 for ($g = $this->entry_year +
$this->mainEducationDuration(); $g <= $this->grad_year
; ++
$g) {
242 public function mainEducation()
244 if (empty($this->promo
)) {
247 return $this->promo
{0};
251 public function mainGrade()
253 switch ($this->mainEducation()) {
255 return UserFilter
::GRADE_ING
;
257 return UserFilter
::GRADE_MST
;
259 return UserFilter
::GRADE_PHD
;
265 public function mainEducationDuration()
267 switch ($this->mainEducation()) {
279 public static function educationDuration($education)
281 switch ($education) {
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.
297 public function deltaPromoToGradYear()
299 if ($this->mainEducation() == 'X') {
300 return $this->mainEducationDuration();
305 // Returns the profile's color.
306 public function promoColor()
308 switch ($this->mainEducation()) {
310 if (($this->yearpromo() %
2) === 0) {
324 /** Print a name with the given formatting:
332 public function name($format)
334 return str_replace(array('%s', '%f', '%l', '%F', '%S', '%p'),
335 array($this->isFemale() ?
'•' : '',
336 $this->firstName(), $this->lastName(),
337 $this->fullName(), $this->shortName(),
338 $this->promo()), $format);
341 public function fullName($with_promo = false
)
344 return $this->full_name
. ' (' . $this->promo
. ')';
346 return $this->full_name
;
349 public function shortName($with_promo = false
)
352 return $this->short_name
. ' (' . $this->promo
. ')';
354 return $this->short_name
;
357 public function firstName()
359 return $this->firstname
;
362 public function firstNames()
364 return $this->nameVariants(self
::FIRSTNAME
);
367 public function lastName()
369 return $this->lastname
;
372 public function lastNames()
374 return $this->nameVariants(self
::LASTNAME
);
377 public function isFemale()
379 return $this->sex
== PlUser
::GENDER_FEMALE
;
382 public function isDead()
384 return ($this->deathdate
!= null
);
387 public function displayEmail()
390 if ($o != null
&& $this->isVisible(ProfileVisibility
::VIS_PRIVATE
)) {
391 return $o->bestEmail();
393 return $this->email_directory
;
397 public function data()
403 private function nameVariants($type)
405 $vals = array($this->$type);
406 foreach (self
::$name_variants[$type] as $var) {
407 $vartype = $type . '_' . $var;
408 $varname = $this->$vartype;
409 if ($varname != null
&& $varname != "") {
413 return array_unique($vals);
416 public function nationalities()
419 $nationalities = DirEnum
::getOptions(DirEnum
::NATIONALITIES
);
420 if ($this->nationality1
) {
421 $nats[$this->nationality1
] = $nationalities[$this->nationality1
];
423 if ($this->nationality2
) {
424 $nats[$this->nationality2
] = $nationalities[$this->nationality2
];
426 if ($this->nationality3
) {
427 $nats[$this->nationality3
] = $nationalities[$this->nationality3
];
432 public function __get($name)
434 if (property_exists($this, $name)) {
438 if (isset($this->data
[$name])) {
439 return $this->data
[$name];
445 public function __isset($name)
447 return property_exists($this, $name) ||
isset($this->data
[$name]);
450 public function __unset($name)
452 if (property_exists($this, $name)) {
455 unset($this->data
[$name]);
462 * *always deletes in: profile_addresses, profile_binets, profile_deltaten,
463 * profile_job, profile_langskills, profile_mentor, profile_networking,
464 * profile_phones, profile_skills, watch_profile
465 * *always keeps in: profile_corps, profile_display, profile_education,
466 * profile_medals, profile_*_names, profile_photos, search_name
467 * *modifies: profiles
469 public function clear()
472 'profile_job', 'profile_langskills', 'profile_mentor',
473 'profile_networking', 'profile_skills', 'watch_profile',
474 'profile_phones', 'profile_addresses', 'profile_binets',
477 foreach ($tables as $t) {
478 XDB
::execute('DELETE FROM ' . $t . '
483 XDB
::execute("UPDATE profiles
484 SET cv = NULL, freetext = NULL, freetext_pub = 'private',
485 medals_pub = 'private', alias_pub = 'private',
486 email_directory = NULL
491 /** Determine whether an item with visibility $visibility can be displayed
492 * with the current level of visibility of the profile
493 * @param $visibility The level of visibility to be checked
495 public function isVisible($visibility)
497 return $this->visibility
->isVisible($visibility);
500 /** Stores the list of fields which have already been fetched for this Profile
502 public function setFetchedFields($fields)
504 if (($fields | self
::FETCH_ALL
) != self
::FETCH_ALL
) {
505 Platal
::page()->kill("Invalid fetched fields: $fields");
508 $this->fetched_fields
= $fields;
511 /** Have we already fetched this field ?
513 private function fetched($field)
515 if (!array_key_exists($field, ProfileField
::$fields)) {
516 Platal
::page()->kill("Invalid field: $field");
519 return ($this->fetched_fields
& $field);
522 /** If not already done, fetches data for the given field
523 * @param $field One of the Profile::FETCH_*
524 * @return A ProfileField, or null
526 private function getProfileField($field)
528 if (!array_key_exists($field, ProfileField
::$fields)) {
529 Platal
::page()->kill("Invalid field: $field");
531 if ($this->fetched($field)) {
534 $this->fetched_fields
= $this->fetched_fields |
$field;
537 $cls = ProfileField
::$fields[$field];
539 return ProfileField
::getForPID($cls, $this->id(), $this->visibility
);
542 /** Consolidates internal data (addresses, phones, jobs)
544 private function consolidateFields()
546 // Link phones to addresses
547 if ($this->phones
!= null
) {
548 if ($this->addresses
!= null
) {
549 $this->addresses
->addPhones($this->phones
);
552 if ($this->jobs
!= null
) {
553 $this->jobs
->addPhones($this->phones
);
557 // Link addresses to jobs
558 if ($this->addresses
!= null
&& $this->jobs
!= null
) {
559 $this->jobs
->addAddresses($this->addresses
);
562 // Link jobterms to jobs
563 if ($this->jobs
!= null
&& $this->jobterms
!= null
) {
564 $this->jobs
->addJobTerms($this->jobterms
);
570 private $photo = null
;
571 public function getPhoto($fallback = true
, $data = false
)
573 if ($this->has_photo
) {
574 if ($data && ($this->photo
== null ||
$this->photo
->mimeType
== null
)) {
575 $res = XDB
::fetchOneAssoc('SELECT attach, attachmime, x, y, last_update
577 WHERE pid = {?}', $this->pid
);
578 $this->photo
= PlImage
::fromData($res['attach'], 'image/' .$res['attachmime'], $res['x'], $res['y'], $res['last_update']);
579 } else if ($this->photo
== null
) {
580 $this->photo
= PlImage
::fromData(null
, null
, $this->photo_width
, $this->photo_height
);
583 } else if ($fallback) {
584 if ($this->mainEducation() == 'X') {
585 return PlImage
::fromFile(dirname(__FILE__
) . '/../htdocs/images/none_x.png', 'image/png');
587 return PlImage
::fromFile(dirname(__FILE__
) . '/../htdocs/images/none_md.png', 'image/png');
594 private $addresses = null
;
595 public function setAddresses(ProfileAddresses
$addr)
597 $this->addresses
= $addr;
598 $this->consolidateFields();
601 private function fetchAddresses()
603 if ($this->addresses
== null
&& !$this->fetched(self
::FETCH_ADDRESSES
)) {
604 $addr = $this->getProfileField(self
::FETCH_ADDRESSES
);
606 $this->setAddresses($addr);
607 $this->fetchPhones();
612 public function getAddresses($flags, $limit = null
)
614 $this->fetchAddresses();
616 if ($this->addresses
== null
) {
619 return $this->addresses
->get($flags, $limit);
622 public function iterAddresses($flags, $limit = null
)
624 return PlIteratorUtils
::fromArray($this->getAddresses($flags, $limit), 1, true
);
627 public function getMainAddress()
629 $main = $this->getAddresses(self
::ADDRESS_MAIN
);
630 $perso = $this->getAddresses(self
::ADDRESS_PERSO
);
633 return array_pop($main);
634 } else if (count($perso)) {
635 return array_pop($perso);
643 private $phones = null
;
644 public function setPhones(ProfilePhones
$phones)
646 $this->phones
= $phones;
647 $this->consolidateFields();
650 private function fetchPhones()
652 if ($this->phones
== null
&& !$this->fetched(self
::FETCH_PHONES
)) {
653 $phones = $this->getProfileField(self
::FETCH_PHONES
);
654 if (isset($phones)) {
655 $this->setPhones($phones);
660 public function getPhones($flags, $limit = null
)
662 $this->fetchPhones();
663 if ($this->phones
== null
) {
666 return $this->phones
->get($flags, $limit);
671 private $educations = null
;
672 public function setEducations(ProfileEducation
$edu)
674 $this->educations
= $edu;
677 public function getEducations($flags, $limit = null
)
679 if ($this->educations
== null
&& !$this->fetched(self
::FETCH_EDU
)) {
680 $this->setEducations($this->getProfileField(self
::FETCH_EDU
));
683 if ($this->educations
== null
) {
686 return $this->educations
->get($flags, $limit);
689 public function getExtraEducations($limit = null
)
691 return $this->getEducations(self
::EDUCATION_EXTRA
, $limit);
696 private $corps = null
;
697 public function setCorps(ProfileCorps
$corps)
699 $this->corps
= $corps;
702 public function getCorps()
704 if ($this->corps
== null
&& !$this->fetched(self
::FETCH_CORPS
)) {
705 $this->setCorps($this->getProfileField(self
::FETCH_CORPS
));
712 private $networks = null
;
713 public function setNetworking(ProfileNetworking
$nw)
715 $this->networks
= $nw;
718 public function getNetworking($flags, $limit = null
)
720 if ($this->networks
== null
&& !$this->fetched(self
::FETCH_NETWORKING
)) {
721 $nw = $this->getProfileField(self
::FETCH_NETWORKING
);
723 $this->setNetworking($nw);
726 if ($this->networks
== null
) {
729 return $this->networks
->get($flags, $limit);
732 public function getWebSite()
734 $site = $this->getNetworking(self
::NETWORKING_WEB
, 1);
735 if (count($site) != 1) {
738 $site = array_pop($site);
745 private $jobs = null
;
746 public function setJobs(ProfileJobs
$jobs)
749 $this->consolidateFields();
752 private function fetchJobs()
754 if ($this->jobs
== null
&& !$this->fetched(self
::FETCH_JOBS
)) {
755 $jobs = $this->getProfileField(self
::FETCH_JOBS
);
757 $this->setJobs($jobs);
758 $this->fetchAddresses();
763 public function getJobs($flags, $limit = null
)
767 if ($this->jobs
== null
) {
770 return $this->jobs
->get($flags, $limit);
773 public function getMainJob()
775 $job = $this->getJobs(self
::JOBS_MAIN
, 1);
776 if (count($job) != 1) {
779 return array_pop($job);
784 private $jobterms = null
;
785 public function setJobTerms(ProfileJobTerms
$jobterms)
787 $this->jobterms
= $jobterms;
788 $this->consolidateFields();
791 private $mentor_countries = null
;
792 public function setMentoringCountries(ProfileMentoringCountries
$countries)
794 $this->mentor_countries
= $countries;
797 public function getMentoringCountries()
799 if ($this->mentor_countries
== null
&& !$this->fetched(self
::FETCH_MENTOR_COUNTRY
)) {
800 $this->setMentoringCountries($this->getProfileField(self
::FETCH_MENTOR_COUNTRY
));
803 if ($this->mentor_countries
== null
) {
806 return $this->mentor_countries
->countries
;
810 /** List of job terms to specify mentoring */
811 private $mentor_terms = null
;
813 * set job terms to specify mentoring
814 * @param $terms a ProfileMentoringTerms object listing terms only for this profile
816 public function setMentoringTerms(ProfileMentoringTerms
$terms)
818 $this->mentor_terms
= $terms;
821 * get all job terms that specify mentoring
822 * @return an array of JobTerms objects
824 public function getMentoringTerms()
826 if ($this->mentor_terms
== null
&& !$this->fetched(self
::FETCH_MENTOR_TERMS
)) {
827 $this->setMentoringTerms($this->getProfileField(self
::FETCH_MENTOR_TERMS
));
830 if ($this->mentor_terms
== null
) {
833 return $this->mentor_terms
->get();
840 /** Find out whether this profile may take part to the "DeltaTen" operation.
841 * @param $role Which role to select ('young' or 'old')
842 * @return Boolean: whether it is enabled.
844 const DELTATEN_YOUNG
= 'young';
845 const DELTATEN_OLD
= 'old';
846 public function isDeltaTenEnabled($role)
850 case self
::DELTATEN_YOUNG
:
851 return ($this->mainGrade() == UserFilter
::GRADE_ING
&& $this->yearpromo() >= $globals->deltaten
->first_promo_young
);
852 case self
::DELTATEN_OLD
:
853 // Roughly compute the current promo in second year on the campus:
854 // Promo 2010 is in second year between 09/2011 and 08/2012 => use 2012.
855 // DeltaTen program begins around January of the second year.
856 $promo_on_platal = ((int) date('Y')) - 2;
857 return ($this->mainGrade() == UserFilter
::GRADE_ING
&& $this->yearpromo() >= $globals->deltaten
->first_promo_young
- 10 && $this->yearpromo() <= $promo_on_platal - 10);
859 Platal
::assert(false
, "Invalid DeltaTen role $role");
863 /** Retrieve the "Deltaten" message of the user.
864 * Returns "null" if the message is empty or the user is not taking part to the
865 * DeltaTen operation.
867 public function getDeltatenMessage()
869 if ($this->isDeltaTenEnabled(self
::DELTATEN_OLD
)) {
870 return $this->deltaten_message
;
878 public function getBinets()
880 if ($this->visibility
->isVisible(ProfileVisibility
::VIS_PRIVATE
)) {
881 return XDB
::fetchColumn('SELECT binet_id
883 WHERE pid = {?}', $this->id());
888 public function getBinetsNames()
890 if ($this->visibility
->isVisible(ProfileVisibility
::VIS_PRIVATE
)) {
891 return XDB
::fetchColumn('SELECT text
892 FROM profile_binets AS pb
893 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
894 WHERE pb.pid = {?}', $this->id());
902 private $medals = null
;
903 public function setMedals(ProfileMedals
$medals)
905 $this->medals
= $medals;
908 public function getMedals()
910 if ($this->medals
== null
&& !$this->fetched(self
::FETCH_MEDALS
)) {
911 $this->setMedals($this->getProfileField(self
::FETCH_MEDALS
));
913 if ($this->medals
== null
) {
916 return $this->medals
->medals
;
919 public function compareNames($firstname, $lastname)
921 $_lastname = mb_strtoupper($this->lastName());
922 $_firstname = mb_strtoupper($this->firstName());
923 $lastname = mb_strtoupper($lastname);
924 $firstname = mb_strtoupper($firstname);
926 $isOk = (mb_strtoupper($_firstname) == mb_strtoupper($firstname));
927 $tokens = preg_split("/[ \-']/", $lastname, -1, PREG_SPLIT_NO_EMPTY
);
930 foreach ($tokens as $str) {
931 $isOk &= (strpos($_lastname, $str) !== false
);
932 $maxlen = max($maxlen, strlen($str));
935 return ($isOk && ($maxlen > 2 ||
$maxlen == strlen($_lastname)));
940 public function export()
943 'hrpid' => $this->hrid(),
944 'display_name' => $this->shortName(),
945 'full_name' => $this->fullName(),
946 'directory_name' => $this->directory_name
,
947 'promo' => $this->promo(),
948 'year_promo' => $this->yearpromo(),
949 'is_active' => $this->isActive(),
950 'first_name' => $this->firstName(),
951 'last_name' => $this->lastName(),
952 'is_female' => $this->isFemale(),
956 private static function fetchProfileData(array $pids, $respect_order = true
, $fields = 0x0000, ProfileVisibility
$visibility = null
)
958 if (count($pids) == 0) {
962 if ($respect_order) {
963 $order = 'ORDER BY ' . XDB
::formatCustomOrder('p.pid', $pids);
968 if ($visibility == null
) {
969 $visibility = ProfileVisibility
::defaultForRead();
972 $it = XDB
::Iterator('SELECT p.pid, p.hrpid, p.xorg_id, p.ax_id, p.birthdate, p.birthdate_ref,
973 p.next_birthday, p.deathdate, p.deathdate_rec, p.sex = \'female\' AS sex,
974 IF ({?}, p.cv, NULL) AS cv, p.medals_pub, p.alias_pub, p.email_directory,
975 p.last_change, p.nationality1, p.nationality2, p.nationality3,
976 IF (p.freetext_pub >= {?}, p.freetext, NULL) AS freetext,
977 pe.entry_year, pe.grad_year, pe.promo_year, pe.program, pe.fieldid,
978 IF ({?}, pse.text, NULL) AS section,
979 ppn.firstname_main AS firstname, ppn.lastname_main AS lastname, IF ({?}, pn.name, NULL) AS nickname,
980 IF (ppn.firstname_ordinary = \'\', ppn.firstname_main, ppn.firstname_ordinary) AS firstname_ordinary,
981 IF (ppn.lastname_ordinary = \'\', ppn.firstname_main, ppn.lastname_ordinary) AS lastname_ordinary,
982 pd.yourself, pd.promo, pd.short_name, pd.public_name AS full_name,
983 pd.directory_name, pd.public_name, pd.private_name,
984 IF (pp.pub >= {?}, pp.display_tel, NULL) AS mobile,
985 (ph.pub >= {?} AND ph.attach IS NOT NULL) AS has_photo,
986 ph.x AS photo_width, ph.y AS photo_height,
987 p.last_change < DATE_SUB(NOW(), INTERVAL 365 DAY) AS is_old,
988 pm.expertise AS mentor_expertise,
989 IF ({?}, pdt.message, NULL) AS deltaten_message,
992 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
993 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
994 LEFT JOIN profile_section_enum AS pse ON (pse.id = p.section)
995 INNER JOIN profile_public_names AS ppn ON (ppn.pid = p.pid)
996 LEFT JOIN profile_private_names AS pn ON (pn.pid = p.pid AND type = \'nickname\')
997 LEFT JOIN profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = \'user\' AND tel_type = \'mobile\')
998 LEFT JOIN profile_photos AS ph ON (ph.pid = p.pid)
999 LEFT JOIN profile_mentor AS pm ON (pm.pid = p.pid)
1000 LEFT JOIN profile_deltaten AS pdt ON (pdt.pid = p.pid)
1001 LEFT JOIN account_profiles AS ap ON (ap.pid = p.pid AND FIND_IN_SET(\'owner\', ap.perms))
1005 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // CV
1006 $visibility->level(), // freetext
1007 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // section
1008 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // nickname
1009 $visibility->level(), // mobile
1010 $visibility->level(), // photo
1011 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // deltaten_message
1014 return new ProfileIterator($it, $pids, $fields, $visibility);
1017 public static function getPID($login)
1019 if ($login instanceof PlUser
) {
1020 return XDB
::fetchOneCell('SELECT pid
1021 FROM account_profiles
1022 WHERE uid = {?} AND FIND_IN_SET(\'owner\', perms)',
1024 } else if (ctype_digit($login)) {
1025 return XDB
::fetchOneCell('SELECT pid
1027 WHERE pid = {?}', $login);
1029 return XDB
::fetchOneCell('SELECT pid
1031 WHERE hrpid = {?}', $login);
1035 public static function getPIDsFromUIDs($uids, $respect_order = true
)
1037 if ($respect_order) {
1038 $order = 'ORDER BY ' . XDB
::formatCustomOrder('uid', $uids);
1042 return XDB
::fetchAllAssoc('uid', 'SELECT ap.uid, ap.pid
1043 FROM account_profiles AS ap
1044 WHERE FIND_IN_SET(\'owner\', ap.perms)
1045 AND ap.uid IN ' . XDB
::formatArray($uids) .'
1049 /** Return the profile associated with the given login.
1051 public static function get($login, $fields = 0x0000, ProfileVisibility
$visibility = null
)
1053 if ($visibility == null
) {
1054 $visibility = ProfileVisibility
::defaultForRead();
1057 if (is_array($login)) {
1058 $pf = new Profile($login, $visibility);
1061 $pid = self
::getPID($login);
1062 if (!is_null($pid)) {
1063 $it = self
::iterOverPIDs(array($pid), false
, $fields, $visibility);
1066 /* Let say we can identify a profile using the identifiers of its owner.
1068 if (!($login instanceof PlUser
)) {
1069 $user = User
::getSilent($login);
1070 if ($user && $user->hasProfile()) {
1071 return $user->profile();
1078 public static function iterOverUIDs($uids, $respect_order = true
, $fields = 0x0000, ProfileVisibility
$visibility = null
)
1080 return self
::iterOverPIDs(self
::getPIDsFromUIDs($uids), $respect_order, $fields, $visibility);
1083 public static function iterOverPIDs($pids, $respect_order = true
, $fields = 0x0000, ProfileVisibility
$visibility = null
)
1085 return self
::fetchProfileData($pids, $respect_order, $fields, $visibility);
1088 /** Return profiles for the list of pids.
1090 public static function getBulkProfilesWithPIDs(array $pids, $fields = 0x0000, ProfileVisibility
$visibility = null
)
1092 if (count($pids) == 0) {
1095 $it = self
::iterOverPIDs($pids, true
, $fields, $visibility);
1096 $profiles = array();
1097 while ($p = $it->next()) {
1098 $profiles[$p->id()] = $p;
1103 /** Return profiles for uids.
1105 public static function getBulkProfilesWithUIDS(array $uids, $fields = 0x000, ProfileVisibility
$visibility = null
)
1107 if (count($uids) == 0) {
1110 return self
::getBulkProfilesWithPIDs(self
::getPIDsFromUIDs($uids), $fields, $visibility);
1113 public static function isDisplayName($name)
1115 return $name == self
::DN_FULL ||
$name == self
::DN_DISPLAY
1116 ||
$name == self
::DN_YOURSELF ||
$name == self
::DN_DIRECTORY
1117 ||
$name == self
::DN_PRIVATE ||
$name == self
::DN_PUBLIC
1118 ||
$name == self
::DN_SHORT ||
$name == self
::DN_SORT
;
1121 /** Returns the closest "accounts only" name type for $name
1123 public static function getAccountEquivalentName($name)
1127 case self
::DN_DIRECTORY
:
1129 return 'directory_name';
1131 case self
::DN_PUBLIC
:
1133 case self
::DN_PRIVATE
:
1134 case self
::DN_SHORT
:
1135 case self
::DN_YOURSELF
:
1137 return 'display_name';
1141 public static function rebuildSearchTokens($pids, $transaction = true
)
1143 require_once 'name.func.inc.php';
1144 if (!is_array($pids)) {
1145 $pids = array($pids);
1147 $keys = XDB
::iterator("(SELECT pid, name, type, IF(type = 'nickname', 2, 1) AS score, '' AS public
1148 FROM profile_private_names
1151 (SELECT pid, lastname_main, 'lastname' AS type, 10 AS score, 'public' AS public
1152 FROM profile_public_names
1153 WHERE lastname_main != '' AND pid IN {?})
1155 (SELECT pid, lastname_marital, 'lastname' AS type, 10 AS score, 'public' AS public
1156 FROM profile_public_names
1157 WHERE lastname_marital != '' AND pid IN {?})
1159 (SELECT pid, lastname_ordinary, 'lastname' AS type, 10 AS score, 'public' AS public
1160 FROM profile_public_names
1161 WHERE lastname_ordinary != '' AND pid IN {?})
1163 (SELECT pid, firstname_main, 'firstname' AS type, 10 AS score, 'public' AS public
1164 FROM profile_public_names
1165 WHERE firstname_main != '' AND pid IN {?})
1167 (SELECT pid, firstname_ordinary, 'firstname' AS type, 10 AS score, 'public' AS public
1168 FROM profile_public_names
1169 WHERE firstname_ordinary != '' AND pid IN {?})
1171 (SELECT pid, pseudonym, 'nickname' AS type, 10 AS score, 'public' AS public
1172 FROM profile_public_names
1173 WHERE pseudonym != '' AND pid IN {?})",
1174 $pids, $pids, $pids, $pids, $pids, $pids, $pids);
1176 while ($key = $keys->next()) {
1177 if ($key['name'] == '') {
1181 $toks = split_name_for_search($key['name']);
1182 $toks = array_reverse($toks);
1184 /* Split the score between the tokens to avoid the user to be over-rated.
1185 * Let says my user name is "Machin-Truc Bidule" and I also have a user named
1186 * 'Machin Truc'. Distributing the score force "Machin Truc" to be displayed
1187 * before "Machin-Truc" for both "Machin Truc" and "Machin" searches.
1189 $eltScore = ceil(((float)$key['score'])/((float)count($toks)));
1191 foreach ($toks as $tok) {
1192 $token = $tok . $token;
1193 $names["$pid-$token"] = XDB
::format('({?}, {?}, {?}, {?}, {?}, {?})',
1194 $token, $pid, soundex_fr($token),
1195 $eltScore, $key['public'], $key['type']);
1199 XDB
::startTransaction();
1201 XDB
::execute('DELETE FROM search_name
1204 if (count($names) > 0) {
1205 XDB
::rawExecute('INSERT INTO search_name (token, pid, soundex, score, flags, general_type)
1206 VALUES ' . implode(', ', $names));
1213 /** The school identifier consists of 6 digits. The first 3 represent the
1214 * promotion entry year. The last 3 indicate the student's rank.
1216 * Our identifier consists of 8 digits and both half have the same role.
1217 * This enables us to deal with bigger promotions and with a wider range
1220 * getSchoolId returns a school identifier given one of ours.
1221 * getXorgId returns a X.org identifier given a school identifier.
1223 public static function getSchoolId($xorgId)
1225 if (!preg_match('/^[0-9]{8}$/', $xorgId)) {
1229 $year = intval(substr($xorgId, 0, 4));
1230 $rank = intval(substr($xorgId, 5, 3));
1233 } elseif ($year < 2000) {
1234 $year = intval(substr(1900 - $year, 1, 3));
1235 return sprintf('%02u0%03u', $year, $rank);
1237 $year = intval(substr(1900 - $year, 1, 3));
1238 return sprintf('%03u%03u', $year, $rank);
1242 public static function getXorgId($schoolId)
1244 if (!preg_match('/^[0-9]{6}$/', $schoolId)) {
1248 $year = intval(substr($schoolId, 0, 3));
1249 $rank = intval(substr($schoolId, 3, 3));
1257 return sprintf('%04u%04u', 1900 +
$year, $rank);
1263 /** Iterator over a set of Profiles
1265 class ProfileIterator
implements PlIterator
1267 private $iterator = null
;
1269 private $visibility;
1271 const FETCH_ALL
= 0x000033F; // FETCH_ADDRESSES | FETCH_CORPS | FETCH_EDU | FETCH_JOBS | FETCH_MEDALS | FETCH_NETWORKING | FETCH_PHONES | FETCH_JOB_TERMS
1273 public function __construct(PlIterator
$it, array $pids, $fields = 0x0000, ProfileVisibility
$visibility = null
)
1275 require_once 'profilefields.inc.php';
1277 if ($visibility == null
) {
1278 $visibility = ProfileVisibility
::defaultForRead();
1281 $this->fields
= $fields;
1282 $this->visibility
= $visibility;
1285 $callbacks = array();
1288 $callbacks[0] = PlIteratorUtils
::arrayValueCallback('pid');
1289 $cb = PlIteratorUtils
::objectPropertyCallback('pid');
1291 $fields = $fields & self
::FETCH_ALL
;
1292 for ($field = 1; $field < $fields; $field *= 2) {
1293 if (($fields & $field) ) {
1294 $callbacks[$field] = $cb;
1295 $subits[$field] = new ProfileFieldIterator($field, $pids, $visibility);
1299 $this->iterator
= PlIteratorUtils
::parallelIterator($subits, $callbacks, 0);
1302 private function hasData($field, $vals)
1304 return ($this->fields
& $field) && ($vals[$field] != null
);
1307 private function fillProfile(array $vals)
1309 $pf = Profile
::get($vals[0], $this->visibility
);
1310 $pf->setFetchedFields($this->fields
);
1312 if ($this->hasData(Profile
::FETCH_PHONES
, $vals)) {
1313 $pf->setPhones($vals[Profile
::FETCH_PHONES
]);
1315 if ($this->hasData(Profile
::FETCH_ADDRESSES
, $vals)) {
1316 $pf->setAddresses($vals[Profile
::FETCH_ADDRESSES
]);
1318 if ($this->hasData(Profile
::FETCH_JOBS
, $vals)) {
1319 $pf->setJobs($vals[Profile
::FETCH_JOBS
]);
1321 if ($this->hasData(Profile
::FETCH_JOB_TERMS
, $vals)) {
1322 $pf->setJobTerms($vals[Profile
::FETCH_JOB_TERMS
]);
1325 if ($this->hasData(Profile
::FETCH_CORPS
, $vals)) {
1326 $pf->setCorps($vals[Profile
::FETCH_CORPS
]);
1328 if ($this->hasData(Profile
::FETCH_EDU
, $vals)) {
1329 $pf->setEducations($vals[Profile
::FETCH_EDU
]);
1331 if ($this->hasData(Profile
::FETCH_MEDALS
, $vals)) {
1332 $pf->setMedals($vals[Profile
::FETCH_MEDALS
]);
1334 if ($this->hasData(Profile
::FETCH_NETWORKING
, $vals)) {
1335 $pf->setNetworking($vals[Profile
::FETCH_NETWORKING
]);
1341 public function next()
1343 $vals = $this->iterator
->next();
1344 if ($vals == null
) {
1347 return $this->fillProfile($vals);
1350 public function first()
1352 return $this->iterator
->first();
1355 public function last()
1357 return $this->iterator
->last();
1360 public function total()
1362 return $this->iterator
->total();
1366 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: