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 public static function educationDuration($education)
278 switch ($education) {
290 /** Number of years between the promotion year until the
291 * graduation year. In standard schools it's 0, but for
292 * Polytechnique the promo year is the entry year.
294 public function deltaPromoToGradYear()
296 if ($this->mainEducation() == 'X') {
297 return $this->mainEducationDuration();
302 // Returns the profile's color.
303 public function promoColor()
305 switch ($this->mainEducation()) {
307 if (($this->yearpromo() %
2) === 0) {
321 /** Print a name with the given formatting:
329 public function name($format)
331 return str_replace(array('%s', '%f', '%l', '%F', '%S', '%p'),
332 array($this->isFemale() ?
'•' : '',
333 $this->firstName(), $this->lastName(),
334 $this->fullName(), $this->shortName(),
335 $this->promo()), $format);
338 public function fullName($with_promo = false
)
341 return $this->full_name
. ' (' . $this->promo
. ')';
343 return $this->full_name
;
346 public function shortName($with_promo = false
)
349 return $this->short_name
. ' (' . $this->promo
. ')';
351 return $this->short_name
;
354 public function firstName()
356 return $this->firstname
;
359 public function firstNames()
361 return $this->nameVariants(self
::FIRSTNAME
);
364 public function lastName()
366 return $this->lastname
;
369 public function lastNames()
371 return $this->nameVariants(self
::LASTNAME
);
374 public function isFemale()
376 return $this->sex
== PlUser
::GENDER_FEMALE
;
379 public function isDead()
381 return ($this->deathdate
!= null
);
384 public function displayEmail()
388 return $o->bestEmail();
390 return $this->email_directory
;
394 public function data()
400 private function nameVariants($type)
402 $vals = array($this->$type);
403 foreach (self
::$name_variants[$type] as $var) {
404 $vartype = $type . '_' . $var;
405 $varname = $this->$vartype;
406 if ($varname != null
&& $varname != "") {
410 return array_unique($vals);
413 public function nationalities()
416 $nationalities = DirEnum
::getOptions(DirEnum
::NATIONALITIES
);
417 if ($this->nationality1
) {
418 $nats[$this->nationality1
] = $nationalities[$this->nationality1
];
420 if ($this->nationality2
) {
421 $nats[$this->nationality2
] = $nationalities[$this->nationality2
];
423 if ($this->nationality3
) {
424 $nats[$this->nationality3
] = $nationalities[$this->nationality3
];
429 public function __get($name)
431 if (property_exists($this, $name)) {
435 if (isset($this->data
[$name])) {
436 return $this->data
[$name];
442 public function __isset($name)
444 return property_exists($this, $name) ||
isset($this->data
[$name]);
447 public function __unset($name)
449 if (property_exists($this, $name)) {
452 unset($this->data
[$name]);
459 * *always deletes in: profile_addresses, profile_binets, profile_deltaten,
460 * profile_job, profile_langskills, profile_mentor, profile_networking,
461 * profile_phones, profile_skills, watch_profile
462 * *always keeps in: profile_corps, profile_display, profile_education,
463 * profile_medals, profile_*_names, profile_photos, search_name
464 * *modifies: profiles
466 public function clear()
469 'profile_job', 'profile_langskills', 'profile_mentor',
470 'profile_networking', 'profile_skills', 'watch_profile',
471 'profile_phones', 'profile_addresses', 'profile_binets',
474 foreach ($tables as $t) {
475 XDB
::execute('DELETE FROM ' . $t . '
480 XDB
::execute("UPDATE profiles
481 SET cv = NULL, freetext = NULL, freetext_pub = 'private',
482 medals_pub = 'private', alias_pub = 'private',
483 email_directory = NULL
488 /** Sets the level of visibility of the profile
489 * Sets $this->visibility to a list of valid visibilities.
490 * @param one of the self::VIS_* values
492 public function setVisibilityLevel($visibility)
494 $this->visibility
->setLevel($visibility);
497 /** Determine whether an item with visibility $visibility can be displayed
498 * with the current level of visibility of the profile
499 * @param $visibility The level of visibility to be checked
501 public function isVisible($visibility)
503 return $this->visibility
->isVisible($visibility);
506 /** Stores the list of fields which have already been fetched for this Profile
508 public function setFetchedFields($fields)
510 if (($fields | self
::FETCH_ALL
) != self
::FETCH_ALL
) {
511 Platal
::page()->kill("Invalid fetched fields: $fields");
514 $this->fetched_fields
= $fields;
517 /** Have we already fetched this field ?
519 private function fetched($field)
521 if (!array_key_exists($field, ProfileField
::$fields)) {
522 Platal
::page()->kill("Invalid field: $field");
525 return ($this->fetched_fields
& $field);
528 /** If not already done, fetches data for the given field
529 * @param $field One of the Profile::FETCH_*
530 * @return A ProfileField, or null
532 private function getProfileField($field)
534 if (!array_key_exists($field, ProfileField
::$fields)) {
535 Platal
::page()->kill("Invalid field: $field");
537 if ($this->fetched($field)) {
540 $this->fetched_fields
= $this->fetched_fields |
$field;
543 $cls = ProfileField
::$fields[$field];
545 return ProfileField
::getForPID($cls, $this->id(), $this->visibility
);
548 /** Consolidates internal data (addresses, phones, jobs)
550 private function consolidateFields()
552 // Link phones to addresses
553 if ($this->phones
!= null
) {
554 if ($this->addresses
!= null
) {
555 $this->addresses
->addPhones($this->phones
);
558 if ($this->jobs
!= null
) {
559 $this->jobs
->addPhones($this->phones
);
563 // Link addresses to jobs
564 if ($this->addresses
!= null
&& $this->jobs
!= null
) {
565 $this->jobs
->addAddresses($this->addresses
);
568 // Link jobterms to jobs
569 if ($this->jobs
!= null
&& $this->jobterms
!= null
) {
570 $this->jobs
->addJobTerms($this->jobterms
);
576 private $photo = null
;
577 public function getPhoto($fallback = true
, $data = false
)
579 if ($this->has_photo
) {
580 if ($data && ($this->photo
== null ||
$this->photo
->mimeType
== null
)) {
581 $res = XDB
::fetchOneAssoc('SELECT attach, attachmime, x, y, last_update
583 WHERE pid = {?}', $this->pid
);
584 $this->photo
= PlImage
::fromData($res['attach'], 'image/' .$res['attachmime'], $res['x'], $res['y'], $res['last_update']);
585 } else if ($this->photo
== null
) {
586 $this->photo
= PlImage
::fromData(null
, null
, $this->photo_width
, $this->photo_height
);
589 } else if ($fallback) {
590 if ($this->mainEducation() == 'X') {
591 return PlImage
::fromFile(dirname(__FILE__
) . '/../htdocs/images/none_x.png', 'image/png');
593 return PlImage
::fromFile(dirname(__FILE__
) . '/../htdocs/images/none_md.png', 'image/png');
600 private $addresses = null
;
601 public function setAddresses(ProfileAddresses
$addr)
603 $this->addresses
= $addr;
604 $this->consolidateFields();
607 private function fetchAddresses()
609 if ($this->addresses
== null
&& !$this->fetched(self
::FETCH_ADDRESSES
)) {
610 $addr = $this->getProfileField(self
::FETCH_ADDRESSES
);
612 $this->setAddresses($addr);
613 $this->fetchPhones();
618 public function getAddresses($flags, $limit = null
)
620 $this->fetchAddresses();
622 if ($this->addresses
== null
) {
625 return $this->addresses
->get($flags, $limit);
628 public function iterAddresses($flags, $limit = null
)
630 return PlIteratorUtils
::fromArray($this->getAddresses($flags, $limit), 1, true
);
633 public function getMainAddress()
635 $main = $this->getAddresses(self
::ADDRESS_MAIN
);
636 $perso = $this->getAddresses(self
::ADDRESS_PERSO
);
639 return array_pop($main);
640 } else if (count($perso)) {
641 return array_pop($perso);
649 private $phones = null
;
650 public function setPhones(ProfilePhones
$phones)
652 $this->phones
= $phones;
653 $this->consolidateFields();
656 private function fetchPhones()
658 if ($this->phones
== null
&& !$this->fetched(self
::FETCH_PHONES
)) {
659 $phones = $this->getProfileField(self
::FETCH_PHONES
);
660 if (isset($phones)) {
661 $this->setPhones($phones);
666 public function getPhones($flags, $limit = null
)
668 $this->fetchPhones();
669 if ($this->phones
== null
) {
672 return $this->phones
->get($flags, $limit);
677 private $educations = null
;
678 public function setEducations(ProfileEducation
$edu)
680 $this->educations
= $edu;
683 public function getEducations($flags, $limit = null
)
685 if ($this->educations
== null
&& !$this->fetched(self
::FETCH_EDU
)) {
686 $this->setEducations($this->getProfileField(self
::FETCH_EDU
));
689 if ($this->educations
== null
) {
692 return $this->educations
->get($flags, $limit);
695 public function getExtraEducations($limit = null
)
697 return $this->getEducations(self
::EDUCATION_EXTRA
, $limit);
702 private $corps = null
;
703 public function setCorps(ProfileCorps
$corps)
705 $this->corps
= $corps;
708 public function getCorps()
710 if ($this->corps
== null
&& !$this->fetched(self
::FETCH_CORPS
)) {
711 $this->setCorps($this->getProfileField(self
::FETCH_CORPS
));
718 private $networks = null
;
719 public function setNetworking(ProfileNetworking
$nw)
721 $this->networks
= $nw;
724 public function getNetworking($flags, $limit = null
)
726 if ($this->networks
== null
&& !$this->fetched(self
::FETCH_NETWORKING
)) {
727 $nw = $this->getProfileField(self
::FETCH_NETWORKING
);
729 $this->setNetworking($nw);
732 if ($this->networks
== null
) {
735 return $this->networks
->get($flags, $limit);
738 public function getWebSite()
740 $site = $this->getNetworking(self
::NETWORKING_WEB
, 1);
741 if (count($site) != 1) {
744 $site = array_pop($site);
751 private $jobs = null
;
752 public function setJobs(ProfileJobs
$jobs)
755 $this->consolidateFields();
758 private function fetchJobs()
760 if ($this->jobs
== null
&& !$this->fetched(self
::FETCH_JOBS
)) {
761 $jobs = $this->getProfileField(self
::FETCH_JOBS
);
763 $this->setJobs($jobs);
764 $this->fetchAddresses();
769 public function getJobs($flags, $limit = null
)
773 if ($this->jobs
== null
) {
776 return $this->jobs
->get($flags, $limit);
779 public function getMainJob()
781 $job = $this->getJobs(self
::JOBS_MAIN
, 1);
782 if (count($job) != 1) {
785 return array_pop($job);
790 private $jobterms = null
;
791 public function setJobTerms(ProfileJobTerms
$jobterms)
793 $this->jobterms
= $jobterms;
794 $this->consolidateFields();
797 private $mentor_countries = null
;
798 public function setMentoringCountries(ProfileMentoringCountries
$countries)
800 $this->mentor_countries
= $countries;
803 public function getMentoringCountries()
805 if ($this->mentor_countries
== null
&& !$this->fetched(self
::FETCH_MENTOR_COUNTRY
)) {
806 $this->setMentoringCountries($this->getProfileField(self
::FETCH_MENTOR_COUNTRY
));
809 if ($this->mentor_countries
== null
) {
812 return $this->mentor_countries
->countries
;
816 /** List of job terms to specify mentoring */
817 private $mentor_terms = null
;
819 * set job terms to specify mentoring
820 * @param $terms a ProfileMentoringTerms object listing terms only for this profile
822 public function setMentoringTerms(ProfileMentoringTerms
$terms)
824 $this->mentor_terms
= $terms;
827 * get all job terms that specify mentoring
828 * @return an array of JobTerms objects
830 public function getMentoringTerms()
832 if ($this->mentor_terms
== null
&& !$this->fetched(self
::FETCH_MENTOR_TERMS
)) {
833 $this->setMentoringTerms($this->getProfileField(self
::FETCH_MENTOR_TERMS
));
836 if ($this->mentor_terms
== null
) {
839 return $this->mentor_terms
->get();
846 /** Find out whether this profile may take part to the "DeltaTen" operation.
847 * @param $role Which role to select ('young' or 'old')
848 * @return Boolean: whether it is enabled.
850 const DELTATEN_YOUNG
= 'young';
851 const DELTATEN_OLD
= 'old';
852 public function isDeltaTenEnabled($role)
856 case self
::DELTATEN_YOUNG
:
857 return ($this->mainGrade() == UserFilter
::GRADE_ING
&& $this->yearpromo() >= $globals->deltaten
->first_promo_young
);
858 case self
::DELTATEN_OLD
:
859 // Roughly compute the current promo in second year on the campus:
860 // Promo 2010 is in second year between 09/2011 and 08/2012 => use 2012.
861 // DeltaTen program begins around January of the second year.
862 $promo_on_platal = ((int) date('Y')) - 2;
863 return ($this->mainGrade() == UserFilter
::GRADE_ING
&& $this->yearpromo() >= $globals->deltaten
->first_promo_young
- 10 && $this->yearpromo() <= $promo_on_platal - 10);
865 Platal
::assert(false
, "Invalid DeltaTen role $role");
869 /** Retrieve the "Deltaten" message of the user.
870 * Returns "null" if the message is empty or the user is not taking part to the
871 * DeltaTen operation.
873 public function getDeltatenMessage()
875 if ($this->isDeltaTenEnabled(self
::DELTATEN_OLD
)) {
876 return $this->deltaten_message
;
884 public function getBinets()
886 if ($this->visibility
->isVisible(ProfileVisibility
::VIS_PRIVATE
)) {
887 return XDB
::fetchColumn('SELECT binet_id
889 WHERE pid = {?}', $this->id());
894 public function getBinetsNames()
896 if ($this->visibility
->isVisible(ProfileVisibility
::VIS_PRIVATE
)) {
897 return XDB
::fetchColumn('SELECT text
898 FROM profile_binets AS pb
899 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
900 WHERE pb.pid = {?}', $this->id());
908 private $medals = null
;
909 public function setMedals(ProfileMedals
$medals)
911 $this->medals
= $medals;
914 public function getMedals()
916 if ($this->medals
== null
&& !$this->fetched(self
::FETCH_MEDALS
)) {
917 $this->setMedals($this->getProfileField(self
::FETCH_MEDALS
));
919 if ($this->medals
== null
) {
922 return $this->medals
->medals
;
925 public function compareNames($firstname, $lastname)
927 $_lastname = mb_strtoupper($this->lastName());
928 $_firstname = mb_strtoupper($this->firstName());
929 $lastname = mb_strtoupper($lastname);
930 $firstname = mb_strtoupper($firstname);
932 $isOk = (mb_strtoupper($_firstname) == mb_strtoupper($firstname));
933 $tokens = preg_split("/[ \-']/", $lastname, -1, PREG_SPLIT_NO_EMPTY
);
936 foreach ($tokens as $str) {
937 $isOk &= (strpos($_lastname, $str) !== false
);
938 $maxlen = max($maxlen, strlen($str));
941 return ($isOk && ($maxlen > 2 ||
$maxlen == strlen($_lastname)));
946 public function export()
949 'hrpid' => $this->hrid(),
950 'display_name' => $this->shortName(),
951 'full_name' => $this->fullName(),
952 'directory_name' => $this->directory_name
,
953 'promo' => $this->promo(),
954 'year_promo' => $this->yearpromo(),
955 'is_active' => $this->isActive(),
956 'first_name' => $this->firstName(),
957 'last_name' => $this->lastName(),
958 'is_female' => $this->isFemale(),
962 private static function fetchProfileData(array $pids, $respect_order = true
, $fields = 0x0000, $visibility = null
)
964 if (count($pids) == 0) {
968 if ($respect_order) {
969 $order = 'ORDER BY ' . XDB
::formatCustomOrder('p.pid', $pids);
974 $visibility = new ProfileVisibility($visibility);
976 $it = XDB
::Iterator('SELECT p.pid, p.hrpid, p.xorg_id, p.ax_id, p.birthdate, p.birthdate_ref,
977 p.next_birthday, p.deathdate, p.deathdate_rec, p.sex = \'female\' AS sex,
978 IF ({?}, p.cv, NULL) AS cv, p.medals_pub, p.alias_pub, p.email_directory,
979 p.last_change, p.nationality1, p.nationality2, p.nationality3,
980 IF (p.freetext_pub IN {?}, p.freetext, NULL) AS freetext,
981 pe.entry_year, pe.grad_year, pe.promo_year, pe.program, pe.fieldid,
982 IF ({?}, pse.text, NULL) AS section,
983 ppn.firstname_main AS firstname, ppn.lastname_main AS lastname, IF ({?}, pn.name, NULL) AS nickname,
984 IF (ppn.firstname_ordinary = \'\', ppn.firstname_main, ppn.firstname_ordinary) AS firstname_ordinary,
985 IF (ppn.lastname_ordinary = \'\', ppn.firstname_main, ppn.lastname_ordinary) AS lastname_ordinary,
986 pd.yourself, pd.promo, pd.short_name, pd.public_name AS full_name,
987 pd.directory_name, pd.public_name, pd.private_name,
988 IF (pp.pub IN {?}, pp.display_tel, NULL) AS mobile,
989 (ph.pub IN {?} AND ph.attach IS NOT NULL) AS has_photo,
990 ph.x AS photo_width, ph.y AS photo_height,
991 p.last_change < DATE_SUB(NOW(), INTERVAL 365 DAY) AS is_old,
992 pm.expertise AS mentor_expertise,
993 IF ({?}, pdt.message, NULL) AS deltaten_message,
996 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
997 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
998 LEFT JOIN profile_section_enum AS pse ON (pse.id = p.section)
999 INNER JOIN profile_public_names AS ppn ON (ppn.pid = p.pid)
1000 LEFT JOIN profile_private_names AS pn ON (pn.pid = p.pid AND type = \'nickname\')
1001 LEFT JOIN profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = \'user\' AND tel_type = \'mobile\')
1002 LEFT JOIN profile_photos AS ph ON (ph.pid = p.pid)
1003 LEFT JOIN profile_mentor AS pm ON (pm.pid = p.pid)
1004 LEFT JOIN profile_deltaten AS pdt ON (pdt.pid = p.pid)
1005 LEFT JOIN account_profiles AS ap ON (ap.pid = p.pid AND FIND_IN_SET(\'owner\', ap.perms))
1009 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // CV
1010 $visibility->levels(), // freetext
1011 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // section
1012 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // nickname
1013 $visibility->levels(), // mobile
1014 $visibility->levels(), // photo
1015 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // deltaten_message
1018 return new ProfileIterator($it, $pids, $fields, $visibility);
1021 public static function getPID($login)
1023 if ($login instanceof PlUser
) {
1024 return XDB
::fetchOneCell('SELECT pid
1025 FROM account_profiles
1026 WHERE uid = {?} AND FIND_IN_SET(\'owner\', perms)',
1028 } else if (ctype_digit($login)) {
1029 return XDB
::fetchOneCell('SELECT pid
1031 WHERE pid = {?}', $login);
1033 return XDB
::fetchOneCell('SELECT pid
1035 WHERE hrpid = {?}', $login);
1039 public static function getPIDsFromUIDs($uids, $respect_order = true
)
1041 if ($respect_order) {
1042 $order = 'ORDER BY ' . XDB
::formatCustomOrder('uid', $uids);
1046 return XDB
::fetchAllAssoc('uid', 'SELECT ap.uid, ap.pid
1047 FROM account_profiles AS ap
1048 WHERE FIND_IN_SET(\'owner\', ap.perms)
1049 AND ap.uid IN ' . XDB
::formatArray($uids) .'
1053 /** Return the profile associated with the given login.
1055 public static function get($login, $fields = 0x0000, $visibility = null
)
1057 if (is_array($login)) {
1058 $pf = new Profile($login);
1059 $pf->setVisibilityLevel($visibility);
1062 $pid = self
::getPID($login);
1063 if (!is_null($pid)) {
1064 $it = self
::iterOverPIDs(array($pid), false
, $fields, $visibility);
1067 /* Let say we can identify a profile using the identifiers of its owner.
1069 if (!($login instanceof PlUser
)) {
1070 $user = User
::getSilent($login);
1071 if ($user && $user->hasProfile()) {
1072 return $user->profile();
1079 public static function iterOverUIDs($uids, $respect_order = true
, $fields = 0x0000, $visibility = null
)
1081 return self
::iterOverPIDs(self
::getPIDsFromUIDs($uids), $respect_order, $fields, $visibility);
1084 public static function iterOverPIDs($pids, $respect_order = true
, $fields = 0x0000, $visibility = null
)
1086 return self
::fetchProfileData($pids, $respect_order, $fields, $visibility);
1089 /** Return profiles for the list of pids.
1091 public static function getBulkProfilesWithPIDs(array $pids, $fields = 0x0000, $visibility = null
)
1093 if (count($pids) == 0) {
1096 $it = self
::iterOverPIDs($pids, true
, $fields, $visibility);
1097 $profiles = array();
1098 while ($p = $it->next()) {
1099 $profiles[$p->id()] = $p;
1104 /** Return profiles for uids.
1106 public static function getBulkProfilesWithUIDS(array $uids, $fields = 0x000, $visibility = null
)
1108 if (count($uids) == 0) {
1111 return self
::getBulkProfilesWithPIDs(self
::getPIDsFromUIDs($uids), $fields, $visibility);
1114 public static function isDisplayName($name)
1116 return $name == self
::DN_FULL ||
$name == self
::DN_DISPLAY
1117 ||
$name == self
::DN_YOURSELF ||
$name == self
::DN_DIRECTORY
1118 ||
$name == self
::DN_PRIVATE ||
$name == self
::DN_PUBLIC
1119 ||
$name == self
::DN_SHORT ||
$name == self
::DN_SORT
;
1122 /** Returns the closest "accounts only" name type for $name
1124 public static function getAccountEquivalentName($name)
1128 case self
::DN_DIRECTORY
:
1130 return 'directory_name';
1132 case self
::DN_PUBLIC
:
1134 case self
::DN_PRIVATE
:
1135 case self
::DN_SHORT
:
1136 case self
::DN_YOURSELF
:
1138 return 'display_name';
1142 public static function rebuildSearchTokens($pids, $transaction = true
)
1144 require_once 'name.func.inc.php';
1145 if (!is_array($pids)) {
1146 $pids = array($pids);
1148 $keys = XDB
::iterator("(SELECT pid, name, type, IF(type = 'nickname', 2, 1) AS score, '' AS public
1149 FROM profile_private_names
1152 (SELECT pid, lastname_main, 'lastname' AS type, 10 AS score, 'public' AS public
1153 FROM profile_public_names
1154 WHERE lastname_main != '' AND pid IN {?})
1156 (SELECT pid, lastname_marital, 'lastname' AS type, 10 AS score, 'public' AS public
1157 FROM profile_public_names
1158 WHERE lastname_marital != '' AND pid IN {?})
1160 (SELECT pid, lastname_ordinary, 'lastname' AS type, 10 AS score, 'public' AS public
1161 FROM profile_public_names
1162 WHERE lastname_ordinary != '' AND pid IN {?})
1164 (SELECT pid, firstname_main, 'firstname' AS type, 10 AS score, 'public' AS public
1165 FROM profile_public_names
1166 WHERE firstname_main != '' AND pid IN {?})
1168 (SELECT pid, firstname_ordinary, 'firstname' AS type, 10 AS score, 'public' AS public
1169 FROM profile_public_names
1170 WHERE firstname_ordinary != '' AND pid IN {?})
1172 (SELECT pid, pseudonym, 'nickname' AS type, 10 AS score, 'public' AS public
1173 FROM profile_public_names
1174 WHERE pseudonym != '' AND pid IN {?})",
1175 $pids, $pids, $pids, $pids, $pids, $pids, $pids);
1177 while ($key = $keys->next()) {
1178 if ($key['name'] == '') {
1182 $toks = split_name_for_search($key['name']);
1183 $toks = array_reverse($toks);
1185 /* Split the score between the tokens to avoid the user to be over-rated.
1186 * Let says my user name is "Machin-Truc Bidule" and I also have a user named
1187 * 'Machin Truc'. Distributing the score force "Machin Truc" to be displayed
1188 * before "Machin-Truc" for both "Machin Truc" and "Machin" searches.
1190 $eltScore = ceil(((float)$key['score'])/((float)count($toks)));
1192 foreach ($toks as $tok) {
1193 $token = $tok . $token;
1194 $names["$pid-$token"] = XDB
::format('({?}, {?}, {?}, {?}, {?}, {?})',
1195 $token, $pid, soundex_fr($token),
1196 $eltScore, $key['public'], $key['type']);
1200 XDB
::startTransaction();
1202 XDB
::execute('DELETE FROM search_name
1205 if (count($names) > 0) {
1206 XDB
::rawExecute('INSERT INTO search_name (token, pid, soundex, score, flags, general_type)
1207 VALUES ' . implode(', ', $names));
1214 /** The school identifier consists of 6 digits. The first 3 represent the
1215 * promotion entry year. The last 3 indicate the student's rank.
1217 * Our identifier consists of 8 digits and both half have the same role.
1218 * This enables us to deal with bigger promotions and with a wider range
1221 * getSchoolId returns a school identifier given one of ours.
1222 * getXorgId returns a X.org identifier given a school identifier.
1224 public static function getSchoolId($xorgId)
1226 if (!preg_match('/^[0-9]{8}$/', $xorgId)) {
1230 $year = intval(substr($xorgId, 0, 4));
1231 $rank = intval(substr($xorgId, 5, 3));
1234 } elseif ($year < 2000) {
1235 $year = intval(substr(1900 - $year, 1, 3));
1236 return sprintf('%02u0%03u', $year, $rank);
1238 $year = intval(substr(1900 - $year, 1, 3));
1239 return sprintf('%03u%03u', $year, $rank);
1243 public static function getXorgId($schoolId)
1245 if (!preg_match('/^[0-9]{6}$/', $schoolId)) {
1249 $year = intval(substr($schoolId, 0, 3));
1250 $rank = intval(substr($schoolId, 3, 3));
1258 return sprintf('%04u%04u', 1900 +
$year, $rank);
1264 /** Iterator over a set of Profiles
1266 class ProfileIterator
implements PlIterator
1268 private $iterator = null
;
1270 private $visibility;
1272 const FETCH_ALL
= 0x000033F; // FETCH_ADDRESSES | FETCH_CORPS | FETCH_EDU | FETCH_JOBS | FETCH_MEDALS | FETCH_NETWORKING | FETCH_PHONES | FETCH_JOB_TERMS
1274 public function __construct(PlIterator
$it, array $pids, $fields = 0x0000, ProfileVisibility
$visibility = null
)
1276 require_once 'profilefields.inc.php';
1278 if ($visibility == null
) {
1279 $visibility = new ProfileVisibility();
1282 $this->fields
= $fields;
1283 $this->visibility
= $visibility;
1286 $callbacks = array();
1289 $callbacks[0] = PlIteratorUtils
::arrayValueCallback('pid');
1290 $cb = PlIteratorUtils
::objectPropertyCallback('pid');
1292 $fields = $fields & self
::FETCH_ALL
;
1293 for ($field = 1; $field < $fields; $field *= 2) {
1294 if (($fields & $field) ) {
1295 $callbacks[$field] = $cb;
1296 $subits[$field] = new ProfileFieldIterator($field, $pids, $visibility);
1300 $this->iterator
= PlIteratorUtils
::parallelIterator($subits, $callbacks, 0);
1303 private function hasData($field, $vals)
1305 return ($this->fields
& $field) && ($vals[$field] != null
);
1308 private function fillProfile(array $vals)
1310 $pf = Profile
::get($vals[0]);
1311 $pf->setVisibilityLevel($this->visibility
->level());
1312 $pf->setFetchedFields($this->fields
);
1314 if ($this->hasData(Profile
::FETCH_PHONES
, $vals)) {
1315 $pf->setPhones($vals[Profile
::FETCH_PHONES
]);
1317 if ($this->hasData(Profile
::FETCH_ADDRESSES
, $vals)) {
1318 $pf->setAddresses($vals[Profile
::FETCH_ADDRESSES
]);
1320 if ($this->hasData(Profile
::FETCH_JOBS
, $vals)) {
1321 $pf->setJobs($vals[Profile
::FETCH_JOBS
]);
1323 if ($this->hasData(Profile
::FETCH_JOB_TERMS
, $vals)) {
1324 $pf->setJobTerms($vals[Profile
::FETCH_JOB_TERMS
]);
1327 if ($this->hasData(Profile
::FETCH_CORPS
, $vals)) {
1328 $pf->setCorps($vals[Profile
::FETCH_CORPS
]);
1330 if ($this->hasData(Profile
::FETCH_EDU
, $vals)) {
1331 $pf->setEducations($vals[Profile
::FETCH_EDU
]);
1333 if ($this->hasData(Profile
::FETCH_MEDALS
, $vals)) {
1334 $pf->setMedals($vals[Profile
::FETCH_MEDALS
]);
1336 if ($this->hasData(Profile
::FETCH_NETWORKING
, $vals)) {
1337 $pf->setNetworking($vals[Profile
::FETCH_NETWORKING
]);
1343 public function next()
1345 $vals = $this->iterator
->next();
1346 if ($vals == null
) {
1349 return $this->fillProfile($vals);
1352 public function first()
1354 return $this->iterator
->first();
1357 public function last()
1359 return $this->iterator
->last();
1362 public function total()
1364 return $this->iterator
->total();
1368 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: