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 $name_variants = array(
52 self
::LASTNAME
=> array(self
::VN_MARITAL
, self
::VN_ORDINARY
),
53 self
::FIRSTNAME
=> array(self
::VN_ORDINARY
, self
::VN_INI
, self
::VN_OTHER
)
56 const ADDRESS_MAIN
= 0x00000001;
57 const ADDRESS_PERSO
= 0x00000002;
58 const ADDRESS_PRO
= 0x00000004;
59 const ADDRESS_ALL
= 0x00000006;
60 const ADDRESS_POSTAL
= 0x00000008;
62 const EDUCATION_MAIN
= 0x00000010;
63 const EDUCATION_EXTRA
= 0x00000020;
64 const EDUCATION_ALL
= 0x00000040;
65 const EDUCATION_FINISHED
= 0x00000080;
66 const EDUCATION_CURRENT
= 0x00000100;
68 const JOBS_MAIN
= 0x00001000;
69 const JOBS_ALL
= 0x00002000;
70 const JOBS_FINISHED
= 0x00004000;
71 const JOBS_CURRENT
= 0x00008000;
73 const NETWORKING_ALL
= 0x00070000;
74 const NETWORKING_WEB
= 0x00010000;
75 const NETWORKING_IM
= 0x00020000;
76 const NETWORKING_SOCIAL
= 0x00040000;
78 const PHONE_LINK_JOB
= 0x00100000;
79 const PHONE_LINK_ADDRESS
= 0x00200000;
80 const PHONE_LINK_PROFILE
= 0x00400000;
81 const PHONE_LINK_COMPANY
= 0x00800000;
82 const PHONE_LINK_ANY
= 0x00F00000;
84 const PHONE_TYPE_FAX
= 0x01000000;
85 const PHONE_TYPE_FIXED
= 0x02000000;
86 const PHONE_TYPE_MOBILE
= 0x04000000;
87 const PHONE_TYPE_ANY
= 0x07000000;
89 const PHONE_ANY
= 0x07F00000;
91 const FETCH_ADDRESSES
= 0x000001;
92 const FETCH_CORPS
= 0x000002;
93 const FETCH_EDU
= 0x000004;
94 const FETCH_JOBS
= 0x000008;
95 const FETCH_MEDALS
= 0x000010;
96 const FETCH_NETWORKING
= 0x000020;
97 const FETCH_MENTOR_COUNTRY
= 0x000080;
98 const FETCH_PHONES
= 0x000100;
99 const FETCH_JOB_TERMS
= 0x000200;
100 const FETCH_MENTOR_TERMS
= 0x000400;
102 const FETCH_MINIFICHES
= 0x00012D; // FETCH_ADDRESSES | FETCH_EDU | FETCH_JOBS | FETCH_NETWORKING | FETCH_PHONES
104 const FETCH_ALL
= 0x0007FF; // OR of FETCH_*
106 static public $descriptions = array(
107 'search_names' => 'Noms',
108 'nationality1' => 'Nationalité',
109 'nationality2' => '2e nationalité',
110 'nationality3' => '3e nationalité',
111 'promo_display' => 'Promotion affichée',
112 'email_directory' => 'Email annuaire papier',
113 'networking' => 'Messageries…',
114 'tels' => 'Téléphones',
115 'edus' => 'Formations',
116 'main_edus' => 'Formations à l\'X',
117 'promo' => 'Promotion de sortie',
118 'birthdate' => 'Date de naissance',
119 'yourself' => 'Nom affiché',
120 'freetext' => 'Commentaire',
121 'freetext_pub' => 'Affichage du commentaire',
122 'photo' => 'Photographie',
123 'photo_pub' => 'Affichage de la photographie',
124 'addresses' => 'Adresses',
128 'section' => 'Section',
129 'binets' => 'Binets',
130 'medals' => 'Décorations',
131 'medals_pub' => 'Affichage des décorations',
132 'competences' => 'Compétences',
133 'langues' => 'Langues',
134 'expertise' => 'Expertises (mentoring)',
135 'terms' => 'Compétences (mentoring)',
136 'countries' => 'Pays (mentoring)'
139 private $fetched_fields = 0x000000;
144 private $owner_fetched = false
;
145 private $data = array();
147 private $visibility = null
;
150 private function __construct(array $data)
153 $this->pid
= $this->data
['pid'];
154 $this->hrpid
= $this->data
['hrpid'];
155 $this->visibility
= new ProfileVisibility();
163 public function hrid()
168 public function owner()
170 if ($this->owner
== null
&& !$this->owner_fetched
) {
171 $this->owner_fetched
= true
;
172 $this->owner
= User
::getSilent($this);
177 public function isActive()
179 if ($this->owner()) {
180 return $this->owner
->isActive();
185 public function promo()
190 public function yearpromo()
192 return $this->promo_year
;
195 /** Check if user is an orange (associated with several promos)
197 public function isMultiPromo()
199 return $this->grad_year
!= $this->entry_year +
$this->mainEducationDuration();
202 /** Returns an array with all associated promo years.
204 public function yearspromo()
207 $d = -$this->deltaPromoToGradYear();
208 for ($g = $this->entry_year +
$this->mainEducationDuration(); $g <= $this->grad_year
; ++
$g) {
214 public function mainEducation()
216 if (empty($this->promo
)) {
219 return $this->promo
{0};
223 public function mainGrade()
225 switch ($this->mainEducation()) {
227 return UserFilter
::GRADE_ING
;
229 return UserFilter
::GRADE_MST
;
231 return UserFilter
::GRADE_PHD
;
237 public function mainEducationDuration()
239 switch ($this->mainEducation()) {
251 /** Number of years between the promotion year until the
252 * graduation year. In standard schools it's 0, but for
253 * Polytechnique the promo year is the entry year.
255 public function deltaPromoToGradYear()
257 if ($this->mainEducation() == 'X') {
258 return $this->mainEducationDuration();
263 /** Print a name with the given formatting:
271 public function name($format)
273 return str_replace(array('%s', '%f', '%l', '%F', '%S', '%p'),
274 array($this->isFemale() ?
'•' : '',
275 $this->firstName(), $this->lastName(),
276 $this->fullName(), $this->shortName(),
277 $this->promo()), $format);
280 public function fullName($with_promo = false
)
283 return $this->full_name
. ' (' . $this->promo
. ')';
285 return $this->full_name
;
288 public function shortName($with_promo = false
)
291 return $this->short_name
. ' (' . $this->promo
. ')';
293 return $this->short_name
;
296 public function firstName()
298 return $this->firstname
;
301 public function firstNames()
303 return $this->nameVariants(self
::FIRSTNAME
);
306 public function lastName()
308 return $this->lastname
;
311 public function lastNames()
313 return $this->nameVariants(self
::LASTNAME
);
316 public function isFemale()
318 return $this->sex
== PlUser
::GENDER_FEMALE
;
321 public function isDead()
323 return ($this->deathdate
!= null
);
326 public function displayEmail()
330 return $o->bestEmail();
332 return $this->email_directory
;
336 public function data()
342 private function nameVariants($type)
344 $vals = array($this->$type);
345 foreach (self
::$name_variants[$type] as $var) {
346 $vartype = $type . '_' . $var;
347 $varname = $this->$vartype;
348 if ($varname != null
&& $varname != "") {
352 return array_unique($vals);
355 public function nationalities()
358 $countries = DirEnum
::getOptions(DirEnum
::COUNTRIES
);
359 if ($this->nationality1
) {
360 $nats[$this->nationality1
] = $countries[$this->nationality1
];
362 if ($this->nationality2
) {
363 $nats[$this->nationality2
] = $countries[$this->nationality2
];
365 if ($this->nationality3
) {
366 $nats[$this->nationality3
] = $countries[$this->nationality3
];
371 public function __get($name)
373 if (property_exists($this, $name)) {
377 if (isset($this->data
[$name])) {
378 return $this->data
[$name];
384 public function __isset($name)
386 return property_exists($this, $name) ||
isset($this->data
[$name]);
389 public function __unset($name)
391 if (property_exists($this, $name)) {
394 unset($this->data
[$name]);
401 * *always deletes in: profile_addresses, profile_binets, profile_job,
402 * profile_langskills, profile_mentor, profile_networking,
403 * profile_phones, profile_skills, watch_profile
404 * *always keeps in: profile_corps, profile_display, profile_education,
405 * profile_medals, profile_name, profile_photos, search_name
406 * *modifies: profiles
408 public function clear()
411 'profile_job', 'profile_langskills', 'profile_mentor',
412 'profile_networking', 'profile_skills', 'watch_profile',
413 'profile_phones', 'profile_addresses', 'profile_binets');
415 foreach ($tables as $t) {
416 XDB
::execute('DELETE FROM ' . $t . '
421 XDB
::execute("UPDATE profiles
422 SET cv = NULL, freetext = NULL, freetext_pub = 'private',
423 medals_pub = 'private', alias_pub = 'private',
424 email_directory = NULL
429 /** Sets the level of visibility of the profile
430 * Sets $this->visibility to a list of valid visibilities.
431 * @param one of the self::VIS_* values
433 public function setVisibilityLevel($visibility)
435 $this->visibility
->setLevel($visibility);
438 /** Determine whether an item with visibility $visibility can be displayed
439 * with the current level of visibility of the profile
440 * @param $visibility The level of visibility to be checked
442 public function isVisible($visibility)
444 return $this->visibility
->isVisible($visibility);
447 /** Stores the list of fields which have already been fetched for this Profile
449 public function setFetchedFields($fields)
451 if (($fields | self
::FETCH_ALL
) != self
::FETCH_ALL
) {
452 Platal
::page()->kill("Invalid fetched fields: $fields");
455 $this->fetched_fields
= $fields;
458 /** Have we already fetched this field ?
460 private function fetched($field)
462 if (!array_key_exists($field, ProfileField
::$fields)) {
463 Platal
::page()->kill("Invalid field: $field");
466 return ($this->fetched_fields
& $field);
469 /** If not already done, fetches data for the given field
470 * @param $field One of the Profile::FETCH_*
471 * @return A ProfileField, or null
473 private function getProfileField($field)
475 if (!array_key_exists($field, ProfileField
::$fields)) {
476 Platal
::page()->kill("Invalid field: $field");
478 if ($this->fetched($field)) {
481 $this->fetched_fields
= $this->fetched_fields |
$field;
484 $cls = ProfileField
::$fields[$field];
486 return ProfileField
::getForPID($cls, $this->id(), $this->visibility
);
489 /** Consolidates internal data (addresses, phones, jobs)
491 private function consolidateFields()
493 // Link phones to addresses
494 if ($this->phones
!= null
) {
495 if ($this->addresses
!= null
) {
496 $this->addresses
->addPhones($this->phones
);
499 if ($this->jobs
!= null
) {
500 $this->jobs
->addPhones($this->phones
);
504 // Link addresses to jobs
505 if ($this->addresses
!= null
&& $this->jobs
!= null
) {
506 $this->jobs
->addAddresses($this->addresses
);
509 // Link jobterms to jobs
510 if ($this->jobs
!= null
&& $this->jobterms
!= null
) {
511 $this->jobs
->addJobTerms($this->jobterms
);
517 private $photo = null
;
518 public function getPhoto($fallback = true
, $data = false
)
520 if ($this->has_photo
) {
521 if ($data && ($this->photo
== null ||
$this->photo
->mimeType
== null
)) {
522 $res = XDB
::fetchOneAssoc('SELECT attach, attachmime, x, y, last_update
524 WHERE pid = {?}', $this->pid
);
525 $this->photo
= PlImage
::fromData($res['attach'], 'image/' .$res['attachmime'], $res['x'], $res['y'], $res['last_update']);
526 } else if ($this->photo
== null
) {
527 $this->photo
= PlImage
::fromData(null
, null
, $this->photo_width
, $this->photo_height
);
530 } else if ($fallback) {
531 if ($this->mainEducation() == 'X') {
532 return PlImage
::fromFile(dirname(__FILE__
) . '/../htdocs/images/none_x.png', 'image/png');
534 return PlImage
::fromFile(dirname(__FILE__
) . '/../htdocs/images/none_md.png', 'image/png');
541 private $addresses = null
;
542 public function setAddresses(ProfileAddresses
$addr)
544 $this->addresses
= $addr;
545 $this->consolidateFields();
548 private function fetchAddresses()
550 if ($this->addresses
== null
&& !$this->fetched(self
::FETCH_ADDRESSES
)) {
551 $addr = $this->getProfileField(self
::FETCH_ADDRESSES
);
553 $this->setAddresses($addr);
554 $this->fetchPhones();
559 public function getAddresses($flags, $limit = null
)
561 $this->fetchAddresses();
563 if ($this->addresses
== null
) {
566 return $this->addresses
->get($flags, $limit);
569 public function iterAddresses($flags, $limit = null
)
571 return PlIteratorUtils
::fromArray($this->getAddresses($flags, $limit), 1, true
);
574 public function getMainAddress()
576 $main = $this->getAddresses(self
::ADDRESS_MAIN
);
577 $perso = $this->getAddresses(self
::ADDRESS_PERSO
);
580 return array_pop($main);
581 } else if (count($perso)) {
582 return array_pop($perso);
590 private $phones = null
;
591 public function setPhones(ProfilePhones
$phones)
593 $this->phones
= $phones;
594 $this->consolidateFields();
597 private function fetchPhones()
599 if ($this->phones
== null
&& !$this->fetched(self
::FETCH_PHONES
)) {
600 $phones = $this->getProfileField(self
::FETCH_PHONES
);
601 if (isset($phones)) {
602 $this->setPhones($phones);
607 public function getPhones($flags, $limit = null
)
609 $this->fetchPhones();
610 if ($this->phones
== null
) {
613 return $this->phones
->get($flags, $limit);
618 private $educations = null
;
619 public function setEducations(ProfileEducation
$edu)
621 $this->educations
= $edu;
624 public function getEducations($flags, $limit = null
)
626 if ($this->educations
== null
&& !$this->fetched(self
::FETCH_EDU
)) {
627 $this->setEducations($this->getProfileField(self
::FETCH_EDU
));
630 if ($this->educations
== null
) {
633 return $this->educations
->get($flags, $limit);
636 public function getExtraEducations($limit = null
)
638 return $this->getEducations(self
::EDUCATION_EXTRA
, $limit);
643 private $corps = null
;
644 public function setCorps(ProfileCorps
$corps)
646 $this->corps
= $corps;
649 public function getCorps()
651 if ($this->corps
== null
&& !$this->fetched(self
::FETCH_CORPS
)) {
652 $this->setCorps($this->getProfileField(self
::FETCH_CORPS
));
659 private $networks = null
;
660 public function setNetworking(ProfileNetworking
$nw)
662 $this->networks
= $nw;
665 public function getNetworking($flags, $limit = null
)
667 if ($this->networks
== null
&& !$this->fetched(self
::FETCH_NETWORKING
)) {
668 $nw = $this->getProfileField(self
::FETCH_NETWORKING
);
670 $this->setNetworking($nw);
673 if ($this->networks
== null
) {
676 return $this->networks
->get($flags, $limit);
679 public function getWebSite()
681 $site = $this->getNetworking(self
::NETWORKING_WEB
, 1);
682 if (count($site) != 1) {
685 $site = array_pop($site);
692 private $jobs = null
;
693 public function setJobs(ProfileJobs
$jobs)
696 $this->consolidateFields();
699 private function fetchJobs()
701 if ($this->jobs
== null
&& !$this->fetched(self
::FETCH_JOBS
)) {
702 $jobs = $this->getProfileField(self
::FETCH_JOBS
);
704 $this->setJobs($jobs);
705 $this->fetchAddresses();
710 public function getJobs($flags, $limit = null
)
714 if ($this->jobs
== null
) {
717 return $this->jobs
->get($flags, $limit);
720 public function getMainJob()
722 $job = $this->getJobs(self
::JOBS_MAIN
, 1);
723 if (count($job) != 1) {
726 return array_pop($job);
731 private $jobterms = null
;
732 public function setJobTerms(ProfileJobTerms
$jobterms)
734 $this->jobterms
= $jobterms;
735 $this->consolidateFields();
738 private $mentor_countries = null
;
739 public function setMentoringCountries(ProfileMentoringCountries
$countries)
741 $this->mentor_countries
= $countries;
744 public function getMentoringCountries()
746 if ($this->mentor_countries
== null
&& !$this->fetched(self
::FETCH_MENTOR_COUNTRY
)) {
747 $this->setMentoringCountries($this->getProfileField(self
::FETCH_MENTOR_COUNTRY
));
750 if ($this->mentor_countries
== null
) {
753 return $this->mentor_countries
->countries
;
757 /** List of job terms to specify mentoring */
758 private $mentor_terms = null
;
760 * set job terms to specify mentoring
761 * @param $terms a ProfileMentoringTerms object listing terms only for this profile
763 public function setMentoringTerms(ProfileMentoringTerms
$terms)
765 $this->mentor_terms
= $terms;
768 * get all job terms that specify mentoring
769 * @return an array of JobTerms objects
771 public function getMentoringTerms()
773 if ($this->mentor_terms
== null
&& !$this->fetched(self
::FETCH_MENTOR_TERMS
)) {
774 $this->setMentoringTerms($this->getProfileField(self
::FETCH_MENTOR_TERMS
));
777 if ($this->mentor_terms
== null
) {
780 return $this->mentor_terms
->get();
787 public function getBinets()
789 if ($this->visibility
->isVisible(ProfileVisibility
::VIS_PRIVATE
)) {
790 return XDB
::fetchColumn('SELECT binet_id
792 WHERE pid = {?}', $this->id());
797 public function getBinetsNames()
799 if ($this->visibility
->isVisible(ProfileVisibility
::VIS_PRIVATE
)) {
800 return XDB
::fetchColumn('SELECT text
801 FROM profile_binets AS pb
802 LEFT JOIN profile_binet_enum AS pbe ON (pbe.id = pb.binet_id)
803 WHERE pb.pid = {?}', $this->id());
811 private $medals = null
;
812 public function setMedals(ProfileMedals
$medals)
814 $this->medals
= $medals;
817 public function getMedals()
819 if ($this->medals
== null
&& !$this->fetched(self
::FETCH_MEDALS
)) {
820 $this->setMedals($this->getProfileField(self
::FETCH_MEDALS
));
822 if ($this->medals
== null
) {
825 return $this->medals
->medals
;
828 public function compareNames($firstname, $lastname)
830 $_lastname = mb_strtoupper($this->lastName());
831 $_firstname = mb_strtoupper($this->firstName());
832 $lastname = mb_strtoupper($lastname);
833 $firstname = mb_strtoupper($firstname);
835 $isOk = (mb_strtoupper($_firstname) == mb_strtoupper($firstname));
836 $tokens = preg_split("/[ \-']/", $lastname, -1, PREG_SPLIT_NO_EMPTY
);
839 foreach ($tokens as $str) {
840 $isOk &= (strpos($_lastname, $str) !== false
);
841 $maxlen = max($maxlen, strlen($str));
844 return ($isOk && ($maxlen > 2 ||
$maxlen == strlen($_lastname)));
849 public function export()
852 'hrpid' => $this->hrid(),
853 'display_name' => $this->shortName(),
854 'full_name' => $this->fullName(),
855 'directory_name' => $this->directory_name
,
856 'promo' => $this->promo(),
857 'year_promo' => $this->yearpromo(),
858 'is_active' => $this->isActive(),
859 'first_name' => $this->firstName(),
860 'last_name' => $this->lastName(),
861 'is_female' => $this->isFemale(),
865 private static function fetchProfileData(array $pids, $respect_order = true
, $fields = 0x0000, $visibility = null
)
867 if (count($pids) == 0) {
871 if ($respect_order) {
872 $order = 'ORDER BY ' . XDB
::formatCustomOrder('p.pid', $pids);
877 $visibility = new ProfileVisibility($visibility);
879 $it = XDB
::Iterator('SELECT p.pid, p.hrpid, p.xorg_id, p.ax_id, p.birthdate, p.birthdate_ref,
880 p.next_birthday, p.deathdate, p.deathdate_rec, p.sex = \'female\' AS sex,
881 IF ({?}, p.cv, NULL) AS cv, p.medals_pub, p.alias_pub, p.email_directory,
882 p.last_change, p.nationality1, p.nationality2, p.nationality3,
883 IF (p.freetext_pub IN {?}, p.freetext, NULL) AS freetext,
884 pe.entry_year, pe.grad_year, pe.promo_year,
885 IF ({?}, pse.text, NULL) AS section,
886 pn_f.name AS firstname, pn_l.name AS lastname,
887 IF( {?}, pn_n.name, NULL) AS nickname,
888 IF(pn_uf.name IS NULL, pn_f.name, pn_uf.name) AS firstname_ordinary,
889 IF(pn_ul.name IS NULL, pn_l.name, pn_ul.name) AS lastname_ordinary,
890 pd.yourself, pd.promo, pd.short_name, pd.public_name AS full_name,
891 pd.directory_name, pd.public_name, pd.private_name,
892 IF(pp.pub IN {?}, pp.display_tel, NULL) AS mobile,
893 (ph.pub IN {?} AND ph.attach IS NOT NULL) AS has_photo,
894 ph.x AS photo_width, ph.y AS photo_height,
895 p.last_change < DATE_SUB(NOW(), INTERVAL 365 DAY) AS is_old,
896 pm.expertise AS mentor_expertise,
899 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
900 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
901 LEFT JOIN profile_section_enum AS pse ON (pse.id = p.section)
902 INNER JOIN profile_name AS pn_f ON (pn_f.pid = p.pid
903 AND pn_f.typeid = ' . self
::getNameTypeId('firstname', true
) . ')
904 INNER JOIN profile_name AS pn_l ON (pn_l.pid = p.pid
905 AND pn_l.typeid = ' . self
::getNameTypeId('lastname', true
) . ')
906 LEFT JOIN profile_name AS pn_uf ON (pn_uf.pid = p.pid
907 AND pn_uf.typeid = ' . self
::getNameTypeId('firstname_ordinary', true
) . ')
908 LEFT JOIN profile_name AS pn_ul ON (pn_ul.pid = p.pid
909 AND pn_ul.typeid = ' . self
::getNameTypeId('lastname_ordinary', true
) . ')
910 LEFT JOIN profile_name AS pn_n ON (pn_n.pid = p.pid
911 AND pn_n.typeid = ' . self
::getNameTypeId('nickname', true
) . ')
912 LEFT JOIN profile_phones AS pp ON (pp.pid = p.pid AND pp.link_type = \'user\' AND tel_type = \'mobile\')
913 LEFT JOIN profile_photos AS ph ON (ph.pid = p.pid)
914 LEFT JOIN profile_mentor AS pm ON (pm.pid = p.pid)
915 LEFT JOIN account_profiles AS ap ON (ap.pid = p.pid AND FIND_IN_SET(\'owner\', ap.perms))
919 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // CV
920 $visibility->levels(), // freetext
921 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // section
922 $visibility->isVisible(ProfileVisibility
::VIS_PRIVATE
), // nickname
923 $visibility->levels(), // mobile
924 $visibility->levels(), // photo
927 return new ProfileIterator($it, $pids, $fields, $visibility);
930 public static function getPID($login)
932 if ($login instanceof PlUser
) {
933 return XDB
::fetchOneCell('SELECT pid
934 FROM account_profiles
935 WHERE uid = {?} AND FIND_IN_SET(\'owner\', perms)',
937 } else if (ctype_digit($login)) {
938 return XDB
::fetchOneCell('SELECT pid
940 WHERE pid = {?}', $login);
942 return XDB
::fetchOneCell('SELECT pid
944 WHERE hrpid = {?}', $login);
948 public static function getPIDsFromUIDs($uids, $respect_order = true
)
950 if ($respect_order) {
951 $order = 'ORDER BY ' . XDB
::formatCustomOrder('uid', $uids);
955 return XDB
::fetchAllAssoc('uid', 'SELECT ap.uid, ap.pid
956 FROM account_profiles AS ap
957 WHERE FIND_IN_SET(\'owner\', ap.perms)
958 AND ap.uid IN ' . XDB
::formatArray($uids) .'
962 /** Return the profile associated with the given login.
964 public static function get($login, $fields = 0x0000, $visibility = null
)
966 if (is_array($login)) {
967 $pf = new Profile($login);
968 $pf->setVisibilityLevel($visibility);
971 $pid = self
::getPID($login);
972 if (!is_null($pid)) {
973 $it = self
::iterOverPIDs(array($pid), false
, $fields, $visibility);
976 /* Let say we can identify a profile using the identifiers of its owner.
978 if (!($login instanceof PlUser
)) {
979 $user = User
::getSilent($login);
980 if ($user && $user->hasProfile()) {
981 return $user->profile();
988 public static function iterOverUIDs($uids, $respect_order = true
, $fields = 0x0000, $visibility = null
)
990 return self
::iterOverPIDs(self
::getPIDsFromUIDs($uids), $respect_order, $fields, $visibility);
993 public static function iterOverPIDs($pids, $respect_order = true
, $fields = 0x0000, $visibility = null
)
995 return self
::fetchProfileData($pids, $respect_order, $fields, $visibility);
998 /** Return profiles for the list of pids.
1000 public static function getBulkProfilesWithPIDs(array $pids, $fields = 0x0000, $visibility = null
)
1002 if (count($pids) == 0) {
1005 $it = self
::iterOverPIDs($pids, true
, $fields, $visibility);
1006 $profiles = array();
1007 while ($p = $it->next()) {
1008 $profiles[$p->id()] = $p;
1013 /** Return profiles for uids.
1015 public static function getBulkProfilesWithUIDS(array $uids, $fields = 0x000, $visibility = null
)
1017 if (count($uids) == 0) {
1020 return self
::getBulkProfilesWithPIDs(self
::getPIDsFromUIDs($uids), $fields, $visibility);
1023 public static function isDisplayName($name)
1025 return $name == self
::DN_FULL ||
$name == self
::DN_DISPLAY
1026 ||
$name == self
::DN_YOURSELF ||
$name == self
::DN_DIRECTORY
1027 ||
$name == self
::DN_PRIVATE ||
$name == self
::DN_PUBLIC
1028 ||
$name == self
::DN_SHORT ||
$name == self
::DN_SORT
;
1031 /** Returns the closest "accounts only" name type for $name
1033 public static function getAccountEquivalentName($name)
1037 case self
::DN_DIRECTORY
:
1039 return 'directory_name';
1041 case self
::DN_PUBLIC
:
1043 case self
::DN_PRIVATE
:
1044 case self
::DN_SHORT
:
1045 case self
::DN_YOURSELF
:
1047 return 'display_name';
1051 public static function getNameTypeId($type, $for_sql = false
)
1053 if (!S
::has('name_types')) {
1054 $table = XDB
::fetchAllAssoc('type', 'SELECT id, type
1055 FROM profile_name_enum');
1056 S
::set('name_types', $table);
1058 $table = S
::v('name_types');
1061 return XDB
::escape($table[$type]);
1063 return $table[$type];
1067 public static function rebuildSearchTokens($pids, $transaction = true
)
1069 if (!is_array($pids)) {
1070 $pids = array($pids);
1072 $keys = XDB
::iterator("(SELECT n.pid AS pid, n.name AS name, e.score AS score,
1073 IF(FIND_IN_SET('public', e.flags), 'public', '') AS public
1074 FROM profile_name AS n
1075 INNER JOIN profile_name_enum AS e ON (n.typeid = e.id)
1076 WHERE n.pid IN {?} AND NOT FIND_IN_SET('not_displayed', e.flags))
1078 (SELECT n.pid AS pid, n.particle AS name, 0 AS score,
1079 IF(FIND_IN_SET('public', e.flags), 'public', '') AS public
1080 FROM profile_name AS n
1081 INNER JOIN profile_name_enum AS e ON (n.typeid = e.id)
1082 WHERE n.pid IN {?} AND NOT FIND_IN_SET('not_displayed', e.flags))
1086 while ($key = $keys->next()) {
1087 if ($key['name'] == '') {
1091 require_once 'name.func.inc.php';
1092 $toks = split_name_for_search($key['name']);
1093 $toks = array_reverse($toks);
1095 /* Split the score between the tokens to avoid the user to be over-rated.
1096 * Let says my user name is "Machin-Truc Bidule" and I also have a user named
1097 * 'Machin Truc'. Distributing the score force "Machin Truc" to be displayed
1098 * before "Machin-Truc" for both "Machin Truc" and "Machin" searches.
1100 $eltScore = ceil(((float)$key['score'])/((float)count($toks)));
1102 foreach ($toks as $tok) {
1103 $token = $tok . $token;
1104 $names["$pid-$token"] = XDB
::format('({?}, {?}, {?}, {?}, {?})',
1105 $token, $pid, soundex_fr($token),
1106 $eltScore, $key['public']);
1110 XDB
::startTransaction();
1112 XDB
::execute('DELETE FROM search_name
1115 if (count($names) > 0) {
1116 XDB
::rawExecute('INSERT INTO search_name (token, pid, soundex, score, flags)
1117 VALUES ' . implode(', ', $names));
1124 /** The school identifier consists of 6 digits. The first 3 represent the
1125 * promotion entry year. The last 3 indicate the student's rank.
1127 * Our identifier consists of 8 digits and both half have the same role.
1128 * This enables us to deal with bigger promotions and with a wider range
1131 * getSchoolId returns a school identifier given one of ours.
1132 * getXorgId returns a X.org identifier given a school identifier.
1134 public static function getSchoolId($xorgId)
1136 if (!preg_match('/^[0-9]{8}$/', $xorgId)) {
1140 $year = intval(substr($xorgId, 0, 4));
1141 $rank = intval(substr($xorgId, 5, 3));
1144 } elseif ($year < 2000) {
1145 $year = intval(substr(1900 - $year, 1, 3));
1146 return sprintf('%02u0%03u', $year, $rank);
1148 $year = intval(substr(1900 - $year, 1, 3));
1149 return sprintf('%03u%03u', $year, $rank);
1153 public static function getXorgId($schoolId)
1155 if (!preg_match('/^[0-9]{6}$/', $schoolId)) {
1159 $year = intval(substr($schoolId, 0, 3));
1160 $rank = intval(substr($schoolId, 3, 3));
1168 return sprintf('%04u%04u', 1900 +
$year, $rank);
1174 /** Iterator over a set of Profiles
1176 class ProfileIterator
implements PlIterator
1178 private $iterator = null
;
1180 private $visibility;
1182 const FETCH_ALL
= 0x000033F; // FETCH_ADDRESSES | FETCH_CORPS | FETCH_EDU | FETCH_JOBS | FETCH_MEDALS | FETCH_NETWORKING | FETCH_PHONES | FETCH_JOB_TERMS
1184 public function __construct(PlIterator
$it, array $pids, $fields = 0x0000, ProfileVisibility
$visibility = null
)
1186 require_once 'profilefields.inc.php';
1188 if ($visibility == null
) {
1189 $visibility = new ProfileVisibility();
1192 $this->fields
= $fields;
1193 $this->visibility
= $visibility;
1196 $callbacks = array();
1199 $callbacks[0] = PlIteratorUtils
::arrayValueCallback('pid');
1200 $cb = PlIteratorUtils
::objectPropertyCallback('pid');
1202 $fields = $fields & self
::FETCH_ALL
;
1203 for ($field = 1; $field < $fields; $field *= 2) {
1204 if (($fields & $field) ) {
1205 $callbacks[$field] = $cb;
1206 $subits[$field] = new ProfileFieldIterator($field, $pids, $visibility);
1210 $this->iterator
= PlIteratorUtils
::parallelIterator($subits, $callbacks, 0);
1213 private function hasData($field, $vals)
1215 return ($this->fields
& $field) && ($vals[$field] != null
);
1218 private function fillProfile(array $vals)
1220 $pf = Profile
::get($vals[0]);
1221 $pf->setVisibilityLevel($this->visibility
->level());
1222 $pf->setFetchedFields($this->fields
);
1224 if ($this->hasData(Profile
::FETCH_PHONES
, $vals)) {
1225 $pf->setPhones($vals[Profile
::FETCH_PHONES
]);
1227 if ($this->hasData(Profile
::FETCH_ADDRESSES
, $vals)) {
1228 $pf->setAddresses($vals[Profile
::FETCH_ADDRESSES
]);
1230 if ($this->hasData(Profile
::FETCH_JOBS
, $vals)) {
1231 $pf->setJobs($vals[Profile
::FETCH_JOBS
]);
1233 if ($this->hasData(Profile
::FETCH_JOB_TERMS
, $vals)) {
1234 $pf->setJobTerms($vals[Profile
::FETCH_JOB_TERMS
]);
1237 if ($this->hasData(Profile
::FETCH_CORPS
, $vals)) {
1238 $pf->setCorps($vals[Profile
::FETCH_CORPS
]);
1240 if ($this->hasData(Profile
::FETCH_EDU
, $vals)) {
1241 $pf->setEducations($vals[Profile
::FETCH_EDU
]);
1243 if ($this->hasData(Profile
::FETCH_MEDALS
, $vals)) {
1244 $pf->setMedals($vals[Profile
::FETCH_MEDALS
]);
1246 if ($this->hasData(Profile
::FETCH_NETWORKING
, $vals)) {
1247 $pf->setNetworking($vals[Profile
::FETCH_NETWORKING
]);
1253 public function next()
1255 $vals = $this->iterator
->next();
1256 if ($vals == null
) {
1259 return $this->fillProfile($vals);
1262 public function first()
1264 return $this->iterator
->first();
1267 public function last()
1269 return $this->iterator
->last();
1272 public function total()
1274 return $this->iterator
->total();
1278 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: