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)
166 $this->pid
= $this->data
['pid'];
167 $this->hrpid
= $this->data
['hrpid'];
168 $this->visibility
= new ProfileVisibility();
176 public function hrid()
181 public function owner()
183 if ($this->owner
== null
&& !$this->owner_fetched
) {
184 $this->owner_fetched
= true
;
185 $this->owner
= User
::getSilent($this);
190 public function isActive()
192 if ($this->owner()) {
193 return $this->owner
->isActive();
198 public function promo($details = false
)
200 if ($details && ($this->program ||
$this->fieldid
)) {
202 if ($this->program
) {
203 $text[] = $this->program
;
205 if ($this->fieldid
) {
206 $fieldsList = DirEnum
::getOptions(DirEnum
::EDUFIELDS
);
207 $text[] = $fieldsList[$this->fieldid
];
209 return $this->promo
. ' (' . implode(', ', $text) . ')';
215 public function yearpromo()
217 return $this->promo_year
;
220 /** Check if user is an orange (associated with several promos)
222 public function isMultiPromo()
224 return $this->grad_year
!= $this->entry_year +
$this->mainEducationDuration();
227 /** Returns an array with all associated promo years.
229 public function yearspromo()
232 $d = -$this->deltaPromoToGradYear();
233 for ($g = $this->entry_year +
$this->mainEducationDuration(); $g <= $this->grad_year
; ++
$g) {
239 public function mainEducation()
241 if (empty($this->promo
)) {
244 return $this->promo
{0};
248 public function mainGrade()
250 switch ($this->mainEducation()) {
252 return UserFilter
::GRADE_ING
;
254 return UserFilter
::GRADE_MST
;
256 return UserFilter
::GRADE_PHD
;
262 public function mainEducationDuration()
264 switch ($this->mainEducation()) {
276 /** Number of years between the promotion year until the
277 * graduation year. In standard schools it's 0, but for
278 * Polytechnique the promo year is the entry year.
280 public function deltaPromoToGradYear()
282 if ($this->mainEducation() == 'X') {
283 return $this->mainEducationDuration();
288 // Returns the profile's color.
289 public function promoColor()
291 switch ($this->mainEducation()) {
293 if (($this->yearpromo() %
2) === 0) {
307 /** Print a name with the given formatting:
315 public function name($format)
317 return str_replace(array('%s', '%f', '%l', '%F', '%S', '%p'),
318 array($this->isFemale() ?
'•' : '',
319 $this->firstName(), $this->lastName(),
320 $this->fullName(), $this->shortName(),
321 $this->promo()), $format);
324 public function fullName($with_promo = false
)
327 return $this->full_name
. ' (' . $this->promo
. ')';
329 return $this->full_name
;
332 public function shortName($with_promo = false
)
335 return $this->short_name
. ' (' . $this->promo
. ')';
337 return $this->short_name
;
340 public function firstName()
342 return $this->firstname
;
345 public function firstNames()
347 return $this->nameVariants(self
::FIRSTNAME
);
350 public function lastName()
352 return $this->lastname
;
355 public function lastNames()
357 return $this->nameVariants(self
::LASTNAME
);
360 public function isFemale()
362 return $this->sex
== PlUser
::GENDER_FEMALE
;
365 public function isDead()
367 return ($this->deathdate
!= null
);
370 public function displayEmail()
374 return $o->bestEmail();
376 return $this->email_directory
;
380 public function data()
386 private function nameVariants($type)
388 $vals = array($this->$type);
389 foreach (self
::$name_variants[$type] as $var) {
390 $vartype = $type . '_' . $var;
391 $varname = $this->$vartype;
392 if ($varname != null
&& $varname != "") {
396 return array_unique($vals);
399 public function nationalities()
402 $nationalities = DirEnum
::getOptions(DirEnum
::NATIONALITIES
);
403 if ($this->nationality1
) {
404 $nats[$this->nationality1
] = $nationalities[$this->nationality1
];
406 if ($this->nationality2
) {
407 $nats[$this->nationality2
] = $nationalities[$this->nationality2
];
409 if ($this->nationality3
) {
410 $nats[$this->nationality3
] = $nationalities[$this->nationality3
];
415 public function __get($name)
417 if (property_exists($this, $name)) {
421 if (isset($this->data
[$name])) {
422 return $this->data
[$name];
428 public function __isset($name)
430 return property_exists($this, $name) ||
isset($this->data
[$name]);
433 public function __unset($name)
435 if (property_exists($this, $name)) {
438 unset($this->data
[$name]);
445 * *always deletes in: profile_addresses, profile_binets, profile_deltaten,
446 * profile_job, profile_langskills, profile_mentor, profile_networking,
447 * profile_phones, profile_skills, watch_profile
448 * *always keeps in: profile_corps, profile_display, profile_education,
449 * profile_medals, profile_name, profile_photos, search_name
450 * *modifies: profiles
452 public function clear()
455 'profile_job', 'profile_langskills', 'profile_mentor',
456 'profile_networking', 'profile_skills', 'watch_profile',
457 'profile_phones', 'profile_addresses', 'profile_binets',
460 foreach ($tables as $t) {
461 XDB
::execute('DELETE FROM ' . $t . '
466 XDB
::execute("UPDATE profiles
467 SET cv = NULL, freetext = NULL, freetext_pub = 'private',
468 medals_pub = 'private', alias_pub = 'private',
469 email_directory = NULL
474 /** Sets the level of visibility of the profile
475 * Sets $this->visibility to a list of valid visibilities.
476 * @param one of the self::VIS_* values
478 public function setVisibilityLevel($visibility)
480 $this->visibility
->setLevel($visibility);
483 /** Determine whether an item with visibility $visibility can be displayed
484 * with the current level of visibility of the profile
485 * @param $visibility The level of visibility to be checked
487 public function isVisible($visibility)
489 return $this->visibility
->isVisible($visibility);
492 /** Stores the list of fields which have already been fetched for this Profile
494 public function setFetchedFields($fields)
496 if (($fields | self
::FETCH_ALL
) != self
::FETCH_ALL
) {
497 Platal
::page()->kill("Invalid fetched fields: $fields");
500 $this->fetched_fields
= $fields;
503 /** Have we already fetched this field ?
505 private function fetched($field)
507 if (!array_key_exists($field, ProfileField
::$fields)) {
508 Platal
::page()->kill("Invalid field: $field");
511 return ($this->fetched_fields
& $field);
514 /** If not already done, fetches data for the given field
515 * @param $field One of the Profile::FETCH_*
516 * @return A ProfileField, or null
518 private function getProfileField($field)
520 if (!array_key_exists($field, ProfileField
::$fields)) {
521 Platal
::page()->kill("Invalid field: $field");
523 if ($this->fetched($field)) {
526 $this->fetched_fields
= $this->fetched_fields |
$field;
529 $cls = ProfileField
::$fields[$field];
531 return ProfileField
::getForPID($cls, $this->id(), $this->visibility
);
534 /** Consolidates internal data (addresses, phones, jobs)
536 private function consolidateFields()
538 // Link phones to addresses
539 if ($this->phones
!= null
) {
540 if ($this->addresses
!= null
) {
541 $this->addresses
->addPhones($this->phones
);
544 if ($this->jobs
!= null
) {
545 $this->jobs
->addPhones($this->phones
);
549 // Link addresses to jobs
550 if ($this->addresses
!= null
&& $this->jobs
!= null
) {
551 $this->jobs
->addAddresses($this->addresses
);
554 // Link jobterms to jobs
555 if ($this->jobs
!= null
&& $this->jobterms
!= null
) {
556 $this->jobs
->addJobTerms($this->jobterms
);
562 private $photo = null
;
563 public function getPhoto($fallback = true
, $data = false
)
565 if ($this->has_photo
) {
566 if ($data && ($this->photo
== null ||
$this->photo
->mimeType
== null
)) {
567 $res = XDB
::fetchOneAssoc('SELECT attach, attachmime, x, y, last_update
569 WHERE pid = {?}', $this->pid
);
570 $this->photo
= PlImage
::fromData($res['attach'], 'image/' .$res['attachmime'], $res['x'], $res['y'], $res['last_update']);
571 } else if ($this->photo
== null
) {
572 $this->photo
= PlImage
::fromData(null
, null
, $this->photo_width
, $this->photo_height
);
575 } else if ($fallback) {
576 if ($this->mainEducation() == 'X') {
577 return PlImage
::fromFile(dirname(__FILE__
) . '/../htdocs/images/none_x.png', 'image/png');
579 return PlImage
::fromFile(dirname(__FILE__
) . '/../htdocs/images/none_md.png', 'image/png');
586 private $addresses = null
;
587 public function setAddresses(ProfileAddresses
$addr)
589 $this->addresses
= $addr;
590 $this->consolidateFields();
593 private function fetchAddresses()
595 if ($this->addresses
== null
&& !$this->fetched(self
::FETCH_ADDRESSES
)) {
596 $addr = $this->getProfileField(self
::FETCH_ADDRESSES
);
598 $this->setAddresses($addr);
599 $this->fetchPhones();
604 public function getAddresses($flags, $limit = null
)
606 $this->fetchAddresses();
608 if ($this->addresses
== null
) {
611 return $this->addresses
->get($flags, $limit);
614 public function iterAddresses($flags, $limit = null
)
616 return PlIteratorUtils
::fromArray($this->getAddresses($flags, $limit), 1, true
);
619 public function getMainAddress()
621 $main = $this->getAddresses(self
::ADDRESS_MAIN
);
622 $perso = $this->getAddresses(self
::ADDRESS_PERSO
);
625 return array_pop($main);
626 } else if (count($perso)) {
627 return array_pop($perso);
635 private $phones = null
;
636 public function setPhones(ProfilePhones
$phones)
638 $this->phones
= $phones;
639 $this->consolidateFields();
642 private function fetchPhones()
644 if ($this->phones
== null
&& !$this->fetched(self
::FETCH_PHONES
)) {
645 $phones = $this->getProfileField(self
::FETCH_PHONES
);
646 if (isset($phones)) {
647 $this->setPhones($phones);
652 public function getPhones($flags, $limit = null
)
654 $this->fetchPhones();
655 if ($this->phones
== null
) {
658 return $this->phones
->get($flags, $limit);
663 private $educations = null
;
664 public function setEducations(ProfileEducation
$edu)
666 $this->educations
= $edu;
669 public function getEducations($flags, $limit = null
)
671 if ($this->educations
== null
&& !$this->fetched(self
::FETCH_EDU
)) {
672 $this->setEducations($this->getProfileField(self
::FETCH_EDU
));
675 if ($this->educations
== null
) {
678 return $this->educations
->get($flags, $limit);
681 public function getExtraEducations($limit = null
)
683 return $this->getEducations(self
::EDUCATION_EXTRA
, $limit);
688 private $corps = null
;
689 public function setCorps(ProfileCorps
$corps)
691 $this->corps
= $corps;
694 public function getCorps()
696 if ($this->corps
== null
&& !$this->fetched(self
::FETCH_CORPS
)) {
697 $this->setCorps($this->getProfileField(self
::FETCH_CORPS
));
704 private $networks = null
;
705 public function setNetworking(ProfileNetworking
$nw)
707 $this->networks
= $nw;
710 public function getNetworking($flags, $limit = null
)
712 if ($this->networks
== null
&& !$this->fetched(self
::FETCH_NETWORKING
)) {
713 $nw = $this->getProfileField(self
::FETCH_NETWORKING
);
715 $this->setNetworking($nw);
718 if ($this->networks
== null
) {
721 return $this->networks
->get($flags, $limit);
724 public function getWebSite()
726 $site = $this->getNetworking(self
::NETWORKING_WEB
, 1);
727 if (count($site) != 1) {
730 $site = array_pop($site);
737 private $jobs = null
;
738 public function setJobs(ProfileJobs
$jobs)
741 $this->consolidateFields();
744 private function fetchJobs()
746 if ($this->jobs
== null
&& !$this->fetched(self
::FETCH_JOBS
)) {
747 $jobs = $this->getProfileField(self
::FETCH_JOBS
);
749 $this->setJobs($jobs);
750 $this->fetchAddresses();
755 public function getJobs($flags, $limit = null
)
759 if ($this->jobs
== null
) {
762 return $this->jobs
->get($flags, $limit);
765 public function getMainJob()
767 $job = $this->getJobs(self
::JOBS_MAIN
, 1);
768 if (count($job) != 1) {
771 return array_pop($job);
776 private $jobterms = null
;
777 public function setJobTerms(ProfileJobTerms
$jobterms)
779 $this->jobterms
= $jobterms;
780 $this->consolidateFields();
783 private $mentor_countries = null
;
784 public function setMentoringCountries(ProfileMentoringCountries
$countries)
786 $this->mentor_countries
= $countries;
789 public function getMentoringCountries()
791 if ($this->mentor_countries
== null
&& !$this->fetched(self
::FETCH_MENTOR_COUNTRY
)) {
792 $this->setMentoringCountries($this->getProfileField(self
::FETCH_MENTOR_COUNTRY
));
795 if ($this->mentor_countries
== null
) {
798 return $this->mentor_countries
->countries
;
802 /** List of job terms to specify mentoring */
803 private $mentor_terms = null
;
805 * set job terms to specify mentoring
806 * @param $terms a ProfileMentoringTerms object listing terms only for this profile
808 public function setMentoringTerms(ProfileMentoringTerms
$terms)
810 $this->mentor_terms
= $terms;
813 * get all job terms that specify mentoring
814 * @return an array of JobTerms objects
816 public function getMentoringTerms()
818 if ($this->mentor_terms
== null
&& !$this->fetched(self
::FETCH_MENTOR_TERMS
)) {
819 $this->setMentoringTerms($this->getProfileField(self
::FETCH_MENTOR_TERMS
));
822 if ($this->mentor_terms
== null
) {
825 return $this->mentor_terms
->get();
832 /** Find out whether this profile may take part to the "DeltaTen" operation.
833 * @param $role Which role to select ('young' or 'old')
834 * @return Boolean: whether it is enabled.
836 const DELTATEN_YOUNG
= 'young';
837 const DELTATEN_OLD
= 'old';
838 public function isDeltaTenEnabled($role)
842 case self
::DELTATEN_YOUNG
:
843 return ($this->mainGrade() == UserFilter
::GRADE_ING
&& $this->yearpromo() >= $globals->deltaten
->first_promo_young
);
844 case self
::DELTATEN_OLD
:
845 // Roughly compute the current promo in second year on the campus:
846 // Promo 2010 is in second year between 09/2011 and 08/2012 => use 2012.
847 // DeltaTen program begins around January of the second year.
848 $promo_on_platal = ((int) date('Y')) - 2;
849 return ($this->mainGrade() == UserFilter
::GRADE_ING
&& $this->yearpromo() >= $globals->deltaten
->first_promo_young
- 10 && $this->yearpromo() <= $promo_on_platal - 10);
851 Platal
::assert(false
, "Invalid DeltaTen role $role");
855 /** Retrieve the "Deltaten" message of the user.
856 * Returns "null" if the message is empty or the user is not taking part to the
857 * DeltaTen operation.
859 public function getDeltatenMessage()
861 if ($this->isDeltaTenEnabled(self
::DELTATEN_OLD
)) {
862 return $this->deltaten_message
;
870 public function getBinets()
872 if ($this->visibility
->isVisible(ProfileVisibility
::VIS_PRIVATE
)) {
873 return XDB
::fetchColumn('SELECT binet_id
875 WHERE pid = {?}', $this->id());
880 public function getBinetsNames()
882 if ($this->visibility
->isVisible(ProfileVisibility
::VIS_PRIVATE
)) {
883 return XDB
::fetchColumn('SELECT text
884 FROM profile_binets AS pb
885 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
886 WHERE pb.pid = {?}', $this->id());
894 private $medals = null
;
895 public function setMedals(ProfileMedals
$medals)
897 $this->medals
= $medals;
900 public function getMedals()
902 if ($this->medals
== null
&& !$this->fetched(self
::FETCH_MEDALS
)) {
903 $this->setMedals($this->getProfileField(self
::FETCH_MEDALS
));
905 if ($this->medals
== null
) {
908 return $this->medals
->medals
;
911 public function compareNames($firstname, $lastname)
913 $_lastname = mb_strtoupper($this->lastName());
914 $_firstname = mb_strtoupper($this->firstName());
915 $lastname = mb_strtoupper($lastname);
916 $firstname = mb_strtoupper($firstname);
918 $isOk = (mb_strtoupper($_firstname) == mb_strtoupper($firstname));
919 $tokens = preg_split("/[ \-']/", $lastname, -1, PREG_SPLIT_NO_EMPTY
);
922 foreach ($tokens as $str) {
923 $isOk &= (strpos($_lastname, $str) !== false
);
924 $maxlen = max($maxlen, strlen($str));
927 return ($isOk && ($maxlen > 2 ||
$maxlen == strlen($_lastname)));
932 public function export()
935 'hrpid' => $this->hrid(),
936 'display_name' => $this->shortName(),
937 'full_name' => $this->fullName(),
938 'directory_name' => $this->directory_name
,
939 'promo' => $this->promo(),
940 'year_promo' => $this->yearpromo(),
941 'is_active' => $this->isActive(),
942 'first_name' => $this->firstName(),
943 'last_name' => $this->lastName(),
944 'is_female' => $this->isFemale(),
948 private static function fetchProfileData(array $pids, $respect_order = true
, $fields = 0x0000, $visibility = null
)
950 if (count($pids) == 0) {
954 if ($respect_order) {
955 $order = 'ORDER BY ' . XDB
::formatCustomOrder('p.pid', $pids);
960 $visibility = new ProfileVisibility($visibility);
962 $it = XDB
::Iterator('SELECT p.pid, p.hrpid, p.xorg_id, p.ax_id, p.birthdate, p.birthdate_ref,
963 p.next_birthday, p.deathdate, p.deathdate_rec, p.sex = \'female\' AS sex,
964 IF ({?}, p.cv, NULL) AS cv, p.medals_pub, p.alias_pub, p.email_directory,
965 p.last_change, p.nationality1, p.nationality2, p.nationality3,
966 IF (p.freetext_pub IN {?}, p.freetext, NULL) AS freetext,
967 pe.entry_year, pe.grad_year, pe.promo_year, pe.program, pe.fieldid,
968 IF ({?}, pse.text, NULL) AS section,
969 pn_f.name AS firstname, pn_l.name AS lastname,
970 IF ({?}, pn_n.name, NULL) AS nickname,
971 IF (pn_uf.name IS NULL, pn_f.name, pn_uf.name) AS firstname_ordinary,
972 IF (pn_ul.name IS NULL, pn_l.name, pn_ul.name) AS lastname_ordinary,
973 pd.yourself, pd.promo, pd.short_name, pd.public_name AS full_name,
974 pd.directory_name, pd.public_name, pd.private_name,
975 IF (pp.pub IN {?}, pp.display_tel, NULL) AS mobile,
976 (ph.pub IN {?} AND ph.attach IS NOT NULL) AS has_photo,
977 ph.x AS photo_width, ph.y AS photo_height,
978 p.last_change < DATE_SUB(NOW(), INTERVAL 365 DAY) AS is_old,
979 pm.expertise AS mentor_expertise,
980 IF ({?}, pdt.message, NULL) AS deltaten_message,
983 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
984 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
985 LEFT JOIN profile_section_enum AS pse ON (pse.id = p.section)
986 INNER JOIN profile_name AS pn_f ON (pn_f.pid = p.pid
987 AND pn_f.typeid = ' . self
::getNameTypeId('firstname', true
) . ')
988 INNER JOIN profile_name AS pn_l ON (pn_l.pid = p.pid
989 AND pn_l.typeid = ' . self
::getNameTypeId('lastname', true
) . ')
990 LEFT JOIN profile_name AS pn_uf ON (pn_uf.pid = p.pid
991 AND pn_uf.typeid = ' . self
::getNameTypeId('firstname_ordinary', true
) . ')
992 LEFT JOIN profile_name AS pn_ul ON (pn_ul.pid = p.pid
993 AND pn_ul.typeid = ' . self
::getNameTypeId('lastname_ordinary', true
) . ')
994 LEFT JOIN profile_name AS pn_n ON (pn_n.pid = p.pid
995 AND pn_n.typeid = ' . self
::getNameTypeId('nickname', true
) . ')
996 LEFT JOIN profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = \'user\' AND tel_type = \'mobile\')
997 LEFT JOIN profile_photos AS ph ON (ph.pid = p.pid)
998 LEFT JOIN profile_mentor AS pm ON (pm.pid = p.pid)
999 LEFT JOIN profile_deltaten AS pdt ON (pdt.pid = p.pid)
1000 LEFT JOIN account_profiles AS ap ON (ap.pid = p.pid AND FIND_IN_SET(\'owner\', ap.perms))
1004 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // CV
1005 $visibility->levels(), // freetext
1006 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // section
1007 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // nickname
1008 $visibility->levels(), // mobile
1009 $visibility->levels(), // photo
1010 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // deltaten_message
1013 return new ProfileIterator($it, $pids, $fields, $visibility);
1016 public static function getPID($login)
1018 if ($login instanceof PlUser
) {
1019 return XDB
::fetchOneCell('SELECT pid
1020 FROM account_profiles
1021 WHERE uid = {?} AND FIND_IN_SET(\'owner\', perms)',
1023 } else if (ctype_digit($login)) {
1024 return XDB
::fetchOneCell('SELECT pid
1026 WHERE pid = {?}', $login);
1028 return XDB
::fetchOneCell('SELECT pid
1030 WHERE hrpid = {?}', $login);
1034 public static function getPIDsFromUIDs($uids, $respect_order = true
)
1036 if ($respect_order) {
1037 $order = 'ORDER BY ' . XDB
::formatCustomOrder('uid', $uids);
1041 return XDB
::fetchAllAssoc('uid', 'SELECT ap.uid, ap.pid
1042 FROM account_profiles AS ap
1043 WHERE FIND_IN_SET(\'owner\', ap.perms)
1044 AND ap.uid IN ' . XDB
::formatArray($uids) .'
1048 /** Return the profile associated with the given login.
1050 public static function get($login, $fields = 0x0000, $visibility = null
)
1052 if (is_array($login)) {
1053 $pf = new Profile($login);
1054 $pf->setVisibilityLevel($visibility);
1057 $pid = self
::getPID($login);
1058 if (!is_null($pid)) {
1059 $it = self
::iterOverPIDs(array($pid), false
, $fields, $visibility);
1062 /* Let say we can identify a profile using the identifiers of its owner.
1064 if (!($login instanceof PlUser
)) {
1065 $user = User
::getSilent($login);
1066 if ($user && $user->hasProfile()) {
1067 return $user->profile();
1074 public static function iterOverUIDs($uids, $respect_order = true
, $fields = 0x0000, $visibility = null
)
1076 return self
::iterOverPIDs(self
::getPIDsFromUIDs($uids), $respect_order, $fields, $visibility);
1079 public static function iterOverPIDs($pids, $respect_order = true
, $fields = 0x0000, $visibility = null
)
1081 return self
::fetchProfileData($pids, $respect_order, $fields, $visibility);
1084 /** Return profiles for the list of pids.
1086 public static function getBulkProfilesWithPIDs(array $pids, $fields = 0x0000, $visibility = null
)
1088 if (count($pids) == 0) {
1091 $it = self
::iterOverPIDs($pids, true
, $fields, $visibility);
1092 $profiles = array();
1093 while ($p = $it->next()) {
1094 $profiles[$p->id()] = $p;
1099 /** Return profiles for uids.
1101 public static function getBulkProfilesWithUIDS(array $uids, $fields = 0x000, $visibility = null
)
1103 if (count($uids) == 0) {
1106 return self
::getBulkProfilesWithPIDs(self
::getPIDsFromUIDs($uids), $fields, $visibility);
1109 public static function isDisplayName($name)
1111 return $name == self
::DN_FULL ||
$name == self
::DN_DISPLAY
1112 ||
$name == self
::DN_YOURSELF ||
$name == self
::DN_DIRECTORY
1113 ||
$name == self
::DN_PRIVATE ||
$name == self
::DN_PUBLIC
1114 ||
$name == self
::DN_SHORT ||
$name == self
::DN_SORT
;
1117 /** Returns the closest "accounts only" name type for $name
1119 public static function getAccountEquivalentName($name)
1123 case self
::DN_DIRECTORY
:
1125 return 'directory_name';
1127 case self
::DN_PUBLIC
:
1129 case self
::DN_PRIVATE
:
1130 case self
::DN_SHORT
:
1131 case self
::DN_YOURSELF
:
1133 return 'display_name';
1137 public static function getNameTypeId($type, $for_sql = false
)
1139 if (!S
::has('name_types')) {
1140 $table = XDB
::fetchAllAssoc('type', 'SELECT id, type
1141 FROM profile_name_enum');
1142 S
::set('name_types', $table);
1144 $table = S
::v('name_types');
1147 return XDB
::escape($table[$type]);
1149 return $table[$type];
1153 public static function rebuildSearchTokens($pids, $transaction = true
)
1155 if (!is_array($pids)) {
1156 $pids = array($pids);
1158 $keys = XDB
::iterator("(SELECT n.pid AS pid, n.name AS name, e.score AS score, e.general_type,
1159 IF(FIND_IN_SET('public', e.flags), 'public', '') AS public
1160 FROM profile_name AS n
1161 INNER JOIN profile_name_enum AS e ON (n.typeid = e.id)
1162 WHERE n.pid IN {?} AND NOT FIND_IN_SET('not_displayed', e.flags))
1164 (SELECT n.pid AS pid, n.particle AS name, 0 AS score, e.general_type,
1165 IF(FIND_IN_SET('public', e.flags), 'public', '') AS public
1166 FROM profile_name AS n
1167 INNER JOIN profile_name_enum AS e ON (n.typeid = e.id)
1168 WHERE n.pid IN {?} AND NOT FIND_IN_SET('not_displayed', e.flags))
1172 while ($key = $keys->next()) {
1173 if ($key['name'] == '') {
1177 require_once 'name.func.inc.php';
1178 $toks = split_name_for_search($key['name']);
1179 $toks = array_reverse($toks);
1181 /* Split the score between the tokens to avoid the user to be over-rated.
1182 * Let says my user name is "Machin-Truc Bidule" and I also have a user named
1183 * 'Machin Truc'. Distributing the score force "Machin Truc" to be displayed
1184 * before "Machin-Truc" for both "Machin Truc" and "Machin" searches.
1186 $eltScore = ceil(((float)$key['score'])/((float)count($toks)));
1188 foreach ($toks as $tok) {
1189 $token = $tok . $token;
1190 $names["$pid-$token"] = XDB
::format('({?}, {?}, {?}, {?}, {?}, {?})',
1191 $token, $pid, soundex_fr($token),
1192 $eltScore, $key['public'], $key['general_type']);
1196 XDB
::startTransaction();
1198 XDB
::execute('DELETE FROM search_name
1201 if (count($names) > 0) {
1202 XDB
::rawExecute('INSERT INTO search_name (token, pid, soundex, score, flags, general_type)
1203 VALUES ' . implode(', ', $names));
1210 /** The school identifier consists of 6 digits. The first 3 represent the
1211 * promotion entry year. The last 3 indicate the student's rank.
1213 * Our identifier consists of 8 digits and both half have the same role.
1214 * This enables us to deal with bigger promotions and with a wider range
1217 * getSchoolId returns a school identifier given one of ours.
1218 * getXorgId returns a X.org identifier given a school identifier.
1220 public static function getSchoolId($xorgId)
1222 if (!preg_match('/^[0-9]{8}$/', $xorgId)) {
1226 $year = intval(substr($xorgId, 0, 4));
1227 $rank = intval(substr($xorgId, 5, 3));
1230 } elseif ($year < 2000) {
1231 $year = intval(substr(1900 - $year, 1, 3));
1232 return sprintf('%02u0%03u', $year, $rank);
1234 $year = intval(substr(1900 - $year, 1, 3));
1235 return sprintf('%03u%03u', $year, $rank);
1239 public static function getXorgId($schoolId)
1241 if (!preg_match('/^[0-9]{6}$/', $schoolId)) {
1245 $year = intval(substr($schoolId, 0, 3));
1246 $rank = intval(substr($schoolId, 3, 3));
1254 return sprintf('%04u%04u', 1900 +
$year, $rank);
1260 /** Iterator over a set of Profiles
1262 class ProfileIterator
implements PlIterator
1264 private $iterator = null
;
1266 private $visibility;
1268 const FETCH_ALL
= 0x000033F; // FETCH_ADDRESSES | FETCH_CORPS | FETCH_EDU | FETCH_JOBS | FETCH_MEDALS | FETCH_NETWORKING | FETCH_PHONES | FETCH_JOB_TERMS
1270 public function __construct(PlIterator
$it, array $pids, $fields = 0x0000, ProfileVisibility
$visibility = null
)
1272 require_once 'profilefields.inc.php';
1274 if ($visibility == null
) {
1275 $visibility = new ProfileVisibility();
1278 $this->fields
= $fields;
1279 $this->visibility
= $visibility;
1282 $callbacks = array();
1285 $callbacks[0] = PlIteratorUtils
::arrayValueCallback('pid');
1286 $cb = PlIteratorUtils
::objectPropertyCallback('pid');
1288 $fields = $fields & self
::FETCH_ALL
;
1289 for ($field = 1; $field < $fields; $field *= 2) {
1290 if (($fields & $field) ) {
1291 $callbacks[$field] = $cb;
1292 $subits[$field] = new ProfileFieldIterator($field, $pids, $visibility);
1296 $this->iterator
= PlIteratorUtils
::parallelIterator($subits, $callbacks, 0);
1299 private function hasData($field, $vals)
1301 return ($this->fields
& $field) && ($vals[$field] != null
);
1304 private function fillProfile(array $vals)
1306 $pf = Profile
::get($vals[0]);
1307 $pf->setVisibilityLevel($this->visibility
->level());
1308 $pf->setFetchedFields($this->fields
);
1310 if ($this->hasData(Profile
::FETCH_PHONES
, $vals)) {
1311 $pf->setPhones($vals[Profile
::FETCH_PHONES
]);
1313 if ($this->hasData(Profile
::FETCH_ADDRESSES
, $vals)) {
1314 $pf->setAddresses($vals[Profile
::FETCH_ADDRESSES
]);
1316 if ($this->hasData(Profile
::FETCH_JOBS
, $vals)) {
1317 $pf->setJobs($vals[Profile
::FETCH_JOBS
]);
1319 if ($this->hasData(Profile
::FETCH_JOB_TERMS
, $vals)) {
1320 $pf->setJobTerms($vals[Profile
::FETCH_JOB_TERMS
]);
1323 if ($this->hasData(Profile
::FETCH_CORPS
, $vals)) {
1324 $pf->setCorps($vals[Profile
::FETCH_CORPS
]);
1326 if ($this->hasData(Profile
::FETCH_EDU
, $vals)) {
1327 $pf->setEducations($vals[Profile
::FETCH_EDU
]);
1329 if ($this->hasData(Profile
::FETCH_MEDALS
, $vals)) {
1330 $pf->setMedals($vals[Profile
::FETCH_MEDALS
]);
1332 if ($this->hasData(Profile
::FETCH_NETWORKING
, $vals)) {
1333 $pf->setNetworking($vals[Profile
::FETCH_NETWORKING
]);
1339 public function next()
1341 $vals = $this->iterator
->next();
1342 if ($vals == null
) {
1345 return $this->fillProfile($vals);
1348 public function first()
1350 return $this->iterator
->first();
1353 public function last()
1355 return $this->iterator
->last();
1358 public function total()
1360 return $this->iterator
->total();
1364 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: