Fixes display of member aliases in Xnet.
[platal.git] / classes / phone.php
CommitLineData
0b6c8b36
SJ
1<?php
2/***************************************************************************
5e1513f6 3 * Copyright (C) 2003-2011 Polytechnique.org *
0b6c8b36
SJ
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22/** Class Phone is meant to perform most of the access to the table profile_phones.
23 *
24 * profile_phone describes a Phone, which can be related to an Address,
25 * a Job, a Profile or a Company:
26 * - for a Profile:
27 * - `link_type` is set to 'user'
28 * - `link_id` is set to 0
29 * - `pid` is set to the id of the related Profile (in profiles)
30 *
31 * - for a Company:
32 * - `link_type` is set to 'hq'
33 * - `link_id` is set to the id of the related Company (in profile_job_enum)
34 * - `pid` is set to 0
35 *
36 * - for an Address (this only applies to a personal address)
37 * - `link_type` is set to 'address'
38 * - `link_id` is set to the related Address `id` (in profile_addresses)
39 * - `pid` is set to the related Address `pid` (in both profiles and profile_addresses)
40 *
41 * - for a Job:
42 * - `link_type` is set to 'pro'
43 * - `link_id` is set to the related Job `id` (not `jobid`) (in profile_job)
44 * - `pid` is set to the related Job `pid` (in both profiles and profile_job)
45 *
46 * Thus a Phone can be linked to a Company, a Profile, a Job, or a Profile-related Address.
47*/
48class Phone
49{
50 const TYPE_FAX = 'fax';
51 const TYPE_FIXED = 'fixed';
52 const TYPE_MOBILE = 'mobile';
53
54 const LINK_JOB = 'pro';
55 const LINK_ADDRESS = 'address';
56 const LINK_PROFILE = 'user';
57 const LINK_COMPANY = 'hq';
58
59 /** The following fields, but $error, all correspond to the fields of the
60 * database table profile_phones.
61 */
0b53817f
SJ
62 public $id = 0;
63 public $pid = 0;
64 public $search = '';
65 public $link_type = 'user';
66 public $link_id = 0;
0b6c8b36 67 // The following fields are the fields of the form in the profile edition.
0b53817f 68 public $type = 'fixed';
0b6c8b36 69 public $display = '';
f77a7f09 70 public $pub = 'ax';
0b6c8b36 71 public $comment = '';
0b53817f 72 public $error = false;
0b6c8b36
SJ
73
74 public function __construct(array $data = array())
75 {
76 if (count($data) > 0) {
77 foreach ($data as $key => $val) {
78 $this->$key = $val;
79 }
80 }
81 }
82
323ac187
SJ
83 public function setId($id)
84 {
85 $this->id = $id;
86 }
87
0b6c8b36
SJ
88 /** Returns the unique ID of a phone.
89 * This ID will allow to link it to an address, a user or a job.
90 * The format is address_addressId_phoneId (where phoneId is the id
91 * of the phone in the list of those associated with the address).
92 */
93 public function uniqueId() {
94 return $this->link_type . '_' . $this->link_id . '_' . $this->id;
95 }
96
97 public function hasFlags($flags) {
98 return $this->hasType($flags) && $this->hasLink($flags);
99 }
100
101 /** Returns true if this phone's type matches the flags.
102 */
103 public function hasType($flags) {
104 $flags = $flags & Profile::PHONE_TYPE_ANY;
105 return (
106 ($flags == Profile::PHONE_TYPE_ANY)
107 ||
108 (($flags & Profile::PHONE_TYPE_FAX) && $this->type == self::TYPE_FAX)
109 ||
110 (($flags & Profile::PHONE_TYPE_FIXED) && $this->type == self::TYPE_FIXED)
111 ||
112 (($flags & Profile::PHONE_TYPE_MOBILE) && $this->type == self::TYPE_MOBILE)
113 );
114 }
115
116 /** User-friendly accessible version of the type.
117 */
118 public function displayType($short = false)
119 {
120 switch ($this->type) {
121 case Phone::TYPE_FIXED:
122 return $short ? 'Tél' : 'Fixe';
123 case Phone::TYPE_FAX:
124 return 'Fax';
125 case Phone::TYPE_MOBILE:
126 return $short ? 'Mob' : 'Mobile';
127 default:
128 return $this->type;
129 }
130 }
131
132 /** Returns true if this phone's link matches the flags.
133 */
134 public function hasLink($flags)
135 {
136 $flags = $flags & Profile::PHONE_LINK_ANY;
137 return (
138 ($flags == Profile::PHONE_LINK_ANY)
139 ||
140 (($flags & Profile::PHONE_LINK_COMPANY) && $this->link_type == self::LINK_COMPANY)
141 ||
142 (($flags & Profile::PHONE_LINK_JOB) && $this->link_type == self::LINK_JOB)
143 ||
144 (($flags & Profile::PHONE_LINK_ADDRESS) && $this->link_type == self::LINK_ADDRESS)
145 ||
146 (($flags & Profile::PHONE_LINK_PROFILE) && $this->link_type == self::LINK_PROFILE)
147 );
148 }
149
150 /* Properly formats the search phone, based on actual display phone.
151 *
152 * Computes a base form of the phone number with the international prefix.
153 * This number only contains digits, thus does not begin with the '+' sign.
154 * Numbers starting with 0 (or '(0)') are considered as French.
155 * This assumes that non-French numbers have their international prefix.
156 */
157 private function formatSearch()
158 {
159 $tel = trim($this->display);
160 // Number starting with "(0)" is a French number.
161 if (substr($tel, 0, 3) === '(0)') {
162 $tel = '33' . $tel;
163 }
164 // Removes all "(0)" often used as local prefix.
165 $tel = str_replace('(0)', '', $tel);
166 // Removes all non-digit chars.
167 $tel = preg_replace('/[^0-9]/', '', $tel);
168
169 if (substr($tel, 0, 2) === '00') {
170 // Removes prefix for international calls.
171 $tel = substr($tel, 2);
172 } else if (substr($tel, 0, 1) === '0') {
173 // Number starting with 0 is a French number.
174 $tel = '33' . substr($tel, 1);
175 }
176 $this->search = $tel;
177 }
178
179 // Properly formats the display phone, it requires the search phone to be already formatted.
180 private function formatDisplay($format = array())
181 {
182 $tel = $this->search;
183 $ret = '';
184 $telLength = strlen($tel);
185 // Try to find the country by trying to find a matching prefix of 1, 2 or 3 digits.
186 if ((!isset($format['phoneprf'])) || ($format['phoneprf'] == '')) {
187 $res = XDB::query('SELECT phonePrefix AS phoneprf, phoneFormat AS format
188 FROM geoloc_countries
189 WHERE phonePrefix = {?} OR phonePrefix = {?} OR phonePrefix = {?}
190 LIMIT 1',
191 substr($tel, 0, 1), substr($tel, 0, 2), substr($tel, 0, 3));
192 if ($res->numRows() == 0) {
193 // No country found, does not format more than prepending a '+' sign.
194 $this->error = true;
195 $this->display = '+' . $tel;
196 return;
197 }
198 $format = $res->fetchOneAssoc();
199 }
200 if ($format['format'] == '') {
201 // If the country does not have a phone number format, the number will be displayed
202 // as "+prefix ## ## ## ##...".
555a4512 203 $format['format'] = '(+p)';
0b6c8b36
SJ
204 }
205
206 /* Formats the phone number according t the template with these rules:
207 * - p is replaced by the international prefix,
208 * - # is replaced by one digit,
209 * - other chars are left intact.
210 * If the number is longer than the format, remaining digits are
211 * appended by blocks of two digits separated by spaces.
212 * The last block can have 3 digits to avoid a final single-digit block.
213 */
214 $j = 0;
215 $i = strlen($format['phoneprf']);
216 $lengthFormat = strlen($format['format']);
217 while (($i < $telLength) && ($j < $lengthFormat)) {
218 if ($format['format'][$j] == '#') {
219 $ret .= $tel[$i];
220 ++$i;
221 } else if ($format['format'][$j] == 'p') {
222 $ret .= $format['phoneprf'];
223 } else {
224 $ret .= $format['format'][$j];
225 }
226 ++$j;
227 }
228 for (; $i < $telLength - 1; $i += 2) {
229 $ret .= ' ' . substr($tel, $i, 2);
230 }
231 // Appends last left alone numbers to the last block.
232 if ($i < $telLength) {
233 $ret .= substr($tel, $i);
234 }
235 $this->display = $ret;
236 }
237
238
239 public function format($format = array())
240 {
241 if (!($this->type == Phone::TYPE_FIXED
242 || $this->type == Phone::TYPE_MOBILE
243 || $this->type == Phone::TYPE_FAX)) {
244 $this->type = Phone::TYPE_FIXED;
245 }
246 $this->formatSearch();
247 $this->formatDisplay($format);
248 return !$this->error;
249 }
250
251 public function toFormArray()
252 {
253 return array(
254 'type' => $this->type,
255 'display' => $this->display,
256 'pub' => $this->pub,
257 'comment' => $this->comment,
258 'error' => $this->error
259 );
260 }
261
262 private function toString()
263 {
14aba233
SJ
264 static $pubs = array('public' => 'publique', 'ax' => 'annuaire AX', 'private' => 'privé');
265 static $types = array('fax' => 'fax', 'fixed' => 'fixe', 'mobile' => 'mobile');
266 return $this->display . ' (' . $types[$this->type] . (($this->comment) ? ', commentaire : « ' . $this->comment . ' »' : '')
267 . ', affichage ' . $pubs[$this->pub] . ')';
0b6c8b36
SJ
268 }
269
270 private function isEmpty()
271 {
272 return (!$this->search || $this->search == '');
273 }
274
275 public function save()
276 {
277 $this->format();
278 if (!$this->isEmpty()) {
0c1a29ba
SJ
279 XDB::execute('INSERT IGNORE INTO profile_phones (pid, link_type, link_id, tel_id, tel_type,
280 search_tel, display_tel, pub, comment)
281 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
0b6c8b36
SJ
282 $this->pid, $this->link_type, $this->link_id, $this->id, $this->type,
283 $this->search, $this->display, $this->pub, $this->comment);
284 }
285 }
286
781a24bc
SJ
287 public function delete()
288 {
289 XDB::execute('DELETE FROM profile_phones
290 WHERE pid = {?} AND link_type = {?} AND link_id = {?} AND tel_id = {?}',
291 $this->pid, $this->link_type, $this->link_id, $this->id);
292 }
293
6592a264 294 static public function deletePhones($pid, $link_type, $link_id = null, $deletePrivate = true)
0b6c8b36
SJ
295 {
296 $where = '';
297 if (!is_null($link_id)) {
298 $where = XDB::format(' AND link_id = {?}', $link_id);
299 }
300 XDB::execute('DELETE FROM profile_phones
6592a264 301 WHERE pid = {?} AND link_type = {?}' . $where . (($deletePrivate) ? '' : ' AND pub IN (\'public\', \'ax\')'),
0b6c8b36
SJ
302 $pid, $link_type);
303 }
304
305 /** Saves phones into the database.
306 * @param $data: an array of form formatted phones.
307 * @param $pid, $link_type, $link_id: pid, link_type and link_id concerned by the update.
308 */
309 static public function savePhones(array $data, $pid, $link_type, $link_id = null)
310 {
311 foreach ($data as $id => $value) {
312 $value['id'] = $id;
313 if (!is_null($pid)) {
314 $value['pid'] = $pid ;
315 }
316 if (!is_null($link_type)) {
317 $value['link_type'] = $link_type ;
318 }
319 if (!is_null($link_id)) {
320 $value['link_id'] = $link_id ;
321 }
322 $phone = new Phone($value);
323 $phone->save();
324 }
325 }
326
93a45366 327 static private function formArrayWalk(array $data, $function, &$success = true, $requiresEmptyPhone = false, $maxPublicity = null)
0b6c8b36
SJ
328 {
329 $phones = array();
330 foreach ($data as $item) {
331 $phone = new Phone($item);
42ec0fe2 332 $success = (!$phone->error && ($phone->format() || $phone->isEmpty()) && $success);
0b6c8b36 333 if (!$phone->isEmpty()) {
e7027060
SJ
334 if (!is_null($maxPublicity) && $maxPublicity->isVisible($phone->pub)) {
335 $phone->pub = $maxPublicity->level();
93a45366 336 }
0b6c8b36
SJ
337 $phones[] = call_user_func(array($phone, $function));
338 }
339 }
340 if (count($phones) == 0 && $requiresEmptyPhone) {
341 $phone = new Phone();
e7027060
SJ
342 if (!is_null($maxPublicity) && $maxPublicity->isVisible($phone->pub)) {
343 $phone->pub = $maxPublicity->level();
93a45366 344 }
0b6c8b36
SJ
345 $phones[] = call_user_func(array($phone, $function));
346 }
347 return $phones;
348 }
349
350 // Formats an array of form phones into an array of form formatted phones.
93a45366 351 static public function formatFormArray(array $data, &$success = true, $maxPublicity = null)
0b6c8b36 352 {
b3d5464e
SJ
353 $phones = self::formArrayWalk($data, 'toFormArray', $success, true, $maxPublicity);
354 usort($phones, 'ProfileVisibility::comparePublicity');
355 return $phones;
0b6c8b36
SJ
356 }
357
358 static public function formArrayToString(array $data)
359 {
14aba233 360 return implode(', ', self::formArrayWalk($data, 'toString'));
0b6c8b36
SJ
361 }
362
0c1a29ba
SJ
363 static public function hasPrivate(array $phones)
364 {
365 foreach ($phones as $phone) {
366 if ($phone['pub'] == 'private') {
367 return true;
368 }
369 }
370 return false;
371 }
372
0b6c8b36
SJ
373 static public function iterate(array $pids = array(), array $link_types = array(),
374 array $link_ids = array(), array $pubs = array())
375 {
376 return new PhoneIterator($pids, $link_types, $link_ids, $pubs);
377 }
378}
379
380/** Iterator over a set of Phones
381 *
382 * @param $pid, $link_type, $link_id, $pub
383 *
384 * The iterator contains the phones that correspond to the value stored in the
385 * parameters' arrays.
386 */
387class PhoneIterator implements PlIterator
388{
389 private $dbiter;
390
391 public function __construct(array $pids, array $link_types, array $link_ids, array $pubs)
392 {
393 $where = array();
394 if (count($pids) != 0) {
395 $where[] = XDB::format('(pid IN {?})', $pids);
396 }
397 if (count($link_types) != 0) {
398 $where[] = XDB::format('(link_type IN {?})', $link_types);
399 }
400 if (count($link_ids) != 0) {
401 $where[] = XDB::format('(link_id IN {?})', $link_ids);
402 }
403 if (count($pubs) != 0) {
404 $where[] = XDB::format('(pub IN {?})', $pubs);
405 }
406 $sql = 'SELECT search_tel AS search, display_tel AS display, comment, link_id,
407 tel_type AS type, link_type, tel_id AS id, pid, pub
408 FROM profile_phones
323ac187
SJ
409 ' . ((count($where) > 0) ? 'WHERE ' . implode(' AND ', $where) : '') . '
410 ORDER BY pid, link_id, tel_id';
0b6c8b36
SJ
411 $this->dbiter = XDB::iterator($sql);
412 }
413
414 public function next()
415 {
416 if (is_null($this->dbiter)) {
417 return null;
418 }
419 $data = $this->dbiter->next();
420 if (is_null($data)) {
421 return null;
422 }
423 return new Phone($data);
424 }
425
426 public function total()
427 {
428 return $this->dbiter->total();
429 }
430
431 public function first()
432 {
433 return $this->dbiter->first();
434 }
435
436 public function last()
437 {
438 return $this->dbiter->last();
439 }
440
441 public function value()
442 {
443 return $this->dbiter;
444 }
445}
446
447// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
448?>