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