open file rw only if it is writable
[squirrelmail.git] / functions / abook_local_file.php
1 <?php
2 /**
3 * abook_local_file.php
4 *
5 * Copyright (c) 1999-2005 The SquirrelMail Project Team
6 * Licensed under the GNU GPL. For full terms see the file COPYING.
7 *
8 * @version $Id$
9 * @package squirrelmail
10 * @subpackage addressbook
11 */
12
13 /**
14 * Backend for address book as a pipe separated file
15 *
16 * Stores the address book in a local file
17 *
18 * An array with the following elements must be passed to
19 * the class constructor (elements marked ? are optional):
20 *<pre>
21 * filename => path to addressbook file
22 * ? create => if true: file is created if it does not exist.
23 * ? umask => umask set before opening file.
24 * ? name => name of address book.
25 * ? detect_writeable => detect address book access permissions by
26 * checking file permissions.
27 * ? writeable => allow writing into address book. Used only when
28 * detect_writeable is set to false.
29 *</pre>
30 * NOTE. This class should not be used directly. Use the
31 * "AddressBook" class instead.
32 * @package squirrelmail
33 */
34 class abook_local_file extends addressbook_backend {
35 /**
36 * Backend type
37 * @var string
38 */
39 var $btype = 'local';
40 /**
41 * Backend name
42 * @var string
43 */
44 var $bname = 'local_file';
45
46 /**
47 * File used to store data
48 * @var string
49 */
50 var $filename = '';
51 /**
52 * File handle
53 * @var object
54 */
55 var $filehandle = 0;
56 /**
57 * Create file, if it not present
58 * @var bool
59 */
60 var $create = false;
61 /**
62 * Detect, if address book is writeable by checking file permisions
63 * @var bool
64 */
65 var $detect_writeable = true;
66 /**
67 * Control write access to address book
68 *
69 * Option does not have any effect, if 'detect_writeable' is 'true'
70 * @var bool
71 */
72 var $writeable = false;
73 /**
74 * Umask of the file
75 * @var string
76 */
77 var $umask;
78
79 /* ========================== Private ======================= */
80
81 /**
82 * Constructor
83 * @param array $param backend options
84 * @return bool
85 */
86 function abook_local_file($param) {
87 $this->sname = _("Personal address book");
88 $this->umask = Umask();
89
90 if(is_array($param)) {
91 if(empty($param['filename'])) {
92 return $this->set_error('Invalid parameters');
93 }
94 if(!is_string($param['filename'])) {
95 return $this->set_error($param['filename'] . ': '.
96 _("Not a file name"));
97 }
98
99 $this->filename = $param['filename'];
100
101 if(isset($param['create'])) {
102 $this->create = $param['create'];
103 }
104 if(isset($param['umask'])) {
105 $this->umask = $param['umask'];
106 }
107 if(isset($param['name'])) {
108 $this->sname = $param['name'];
109 }
110 if(isset($param['detect_writeable'])) {
111 $this->detect_writeable = $param['detect_writeable'];
112 }
113 if(!empty($param['writeable'])) {
114 $this->writeable = $param['writeable'];
115 }
116
117 $this->open(true);
118 } else {
119 $this->set_error('Invalid argument to constructor');
120 }
121 }
122
123 /**
124 * Open the addressbook file and store the file pointer.
125 * Use $file as the file to open, or the class' own
126 * filename property. If $param is empty and file is
127 * open, do nothing.
128 * @param bool $new is file already opened
129 * @return bool
130 */
131 function open($new = false) {
132 $this->error = '';
133 $file = $this->filename;
134 $create = $this->create;
135 $fopenmode = (($this->writeable && is_writable($file)) ? 'a+' : 'r');
136
137 /* Return true is file is open and $new is unset */
138 if($this->filehandle && !$new) {
139 return true;
140 }
141
142 /* Check that new file exitsts */
143 if((!(file_exists($file) && is_readable($file))) && !$create) {
144 return $this->set_error("$file: " . _("No such file or directory"));
145 }
146
147 /* Close old file, if any */
148 if($this->filehandle) { $this->close(); }
149
150 umask($this->umask);
151 if (! $this->detect_writeable) {
152 $fh = @fopen($file,$fopenmode);
153 if ($fh) {
154 $this->filehandle = &$fh;
155 $this->filename = $file;
156 } else {
157 return $this->set_error("$file: " . _("Open failed"));
158 }
159 } else {
160 /* Open file. First try to open for reading and writing,
161 * but fall back to read only. */
162 $fh = @fopen($file, 'a+');
163 if($fh) {
164 $this->filehandle = &$fh;
165 $this->filename = $file;
166 $this->writeable = true;
167 } else {
168 $fh = @fopen($file, 'r');
169 if($fh) {
170 $this->filehandle = &$fh;
171 $this->filename = $file;
172 $this->writeable = false;
173 } else {
174 return $this->set_error("$file: " . _("Open failed"));
175 }
176 }
177 }
178 return true;
179 }
180
181 /** Close the file and forget the filehandle */
182 function close() {
183 @fclose($this->filehandle);
184 $this->filehandle = 0;
185 $this->filename = '';
186 $this->writable = false;
187 }
188
189 /** Lock the datafile - try 20 times in 5 seconds */
190 function lock() {
191 for($i = 0 ; $i < 20 ; $i++) {
192 if(flock($this->filehandle, 2 + 4))
193 return true;
194 else
195 usleep(250000);
196 }
197 return false;
198 }
199
200 /** Unlock the datafile */
201 function unlock() {
202 return flock($this->filehandle, 3);
203 }
204
205 /**
206 * Overwrite the file with data from $rows
207 * NOTE! Previous locks are broken by this function
208 * @param array $rows new data
209 * @return bool
210 */
211 function overwrite(&$rows) {
212 $this->unlock();
213 $newfh = @fopen($this->filename.'.tmp', 'w');
214
215 if(!$newfh) {
216 return $this->set_error($this->filename. '.tmp:' . _("Open failed"));
217 }
218
219 for($i = 0, $cnt=sizeof($rows) ; $i < $cnt ; $i++) {
220 if(is_array($rows[$i])) {
221 for($j = 0, $cnt_part=count($rows[$i]) ; $j < $cnt_part ; $j++) {
222 $rows[$i][$j] = $this->quotevalue($rows[$i][$j]);
223 }
224 $tmpwrite = sq_fwrite($newfh, join('|', $rows[$i]) . "\n");
225 if ($tmpwrite === FALSE) {
226 return $this->set_error($this->filename . '.tmp:' . _("Write failed"));
227 }
228 }
229 }
230
231 fclose($newfh);
232 if (!@copy($this->filename . '.tmp' , $this->filename)) {
233 return $this->set_error($this->filename . ':' . _("Unable to update"));
234 }
235 @unlink($this->filename . '.tmp');
236 $this->unlock();
237 $this->open(true);
238 return true;
239 }
240
241 /* ========================== Public ======================== */
242
243 /**
244 * Search the file
245 * @param string $expr search expression
246 * @return array search results
247 */
248 function search($expr) {
249
250 /* To be replaced by advanded search expression parsing */
251 if(is_array($expr)) { return; }
252
253 /* Make regexp from glob'ed expression
254 * May want to quote other special characters like (, ), -, [, ], etc. */
255 $expr = str_replace('?', '.', $expr);
256 $expr = str_replace('*', '.*', $expr);
257
258 $res = array();
259 if(!$this->open()) {
260 return false;
261 }
262 @rewind($this->filehandle);
263
264 while ($row = @fgetcsv($this->filehandle, 2048, '|')) {
265 $line = join(' ', $row);
266 if(eregi($expr, $line)) {
267 array_push($res, array('nickname' => $row[0],
268 'name' => $row[1] . ' ' . $row[2],
269 'firstname' => $row[1],
270 'lastname' => $row[2],
271 'email' => $row[3],
272 'label' => $row[4],
273 'backend' => $this->bnum,
274 'source' => &$this->sname));
275 }
276 }
277
278 return $res;
279 }
280
281 /**
282 * Lookup alias
283 * @param string $alias alias
284 * @return array search results
285 */
286 function lookup($alias) {
287 if(empty($alias)) {
288 return array();
289 }
290
291 $alias = strtolower($alias);
292
293 $this->open();
294 @rewind($this->filehandle);
295
296 while ($row = @fgetcsv($this->filehandle, 2048, '|')) {
297 if(strtolower($row[0]) == $alias) {
298 return array('nickname' => $row[0],
299 'name' => $row[1] . ' ' . $row[2],
300 'firstname' => $row[1],
301 'lastname' => $row[2],
302 'email' => $row[3],
303 'label' => $row[4],
304 'backend' => $this->bnum,
305 'source' => &$this->sname);
306 }
307 }
308
309 return array();
310 }
311
312 /**
313 * List all addresses
314 * @return array list of all addresses
315 */
316 function list_addr() {
317 $res = array();
318 $this->open();
319 @rewind($this->filehandle);
320
321 while ($row = @fgetcsv($this->filehandle, 2048, '|')) {
322 array_push($res, array('nickname' => $row[0],
323 'name' => $row[1] . ' ' . $row[2],
324 'firstname' => $row[1],
325 'lastname' => $row[2],
326 'email' => $row[3],
327 'label' => $row[4],
328 'backend' => $this->bnum,
329 'source' => &$this->sname));
330 }
331 return $res;
332 }
333
334 /**
335 * Add address
336 * @param array $userdata new data
337 * @return bool
338 */
339 function add($userdata) {
340 if(!$this->writeable) {
341 return $this->set_error(_("Addressbook is read-only"));
342 }
343 /* See if user exists already */
344 $ret = $this->lookup($userdata['nickname']);
345 if(!empty($ret)) {
346 return $this->set_error(sprintf(_("User '%s' already exist"),
347 $ret['nickname']));
348 }
349
350 /* Here is the data to write */
351 $data = $this->quotevalue($userdata['nickname']) . '|' .
352 $this->quotevalue($userdata['firstname']) . '|' .
353 $this->quotevalue($userdata['lastname']) . '|' .
354 $this->quotevalue($userdata['email']) . '|' .
355 $this->quotevalue($userdata['label']);
356
357 /* Strip linefeeds */
358 $data = ereg_replace("[\r\n]", ' ', $data);
359 /* Add linefeed at end */
360 $data = $data . "\n";
361
362 /* Reopen file, just to be sure */
363 $this->open(true);
364 if(!$this->writeable) {
365 return $this->set_error(_("Addressbook is read-only"));
366 }
367
368 /* Lock the file */
369 if(!$this->lock()) {
370 return $this->set_error(_("Could not lock datafile"));
371 }
372
373 /* Write */
374 $r = sq_fwrite($this->filehandle, $data);
375
376 /* Unlock file */
377 $this->unlock();
378
379 /* Test write result */
380 if($r === FALSE) {
381 /* Fail */
382 $this->set_error(_("Write to addressbook failed"));
383 return FALSE;
384 }
385
386 return TRUE;
387 }
388
389 /**
390 * Delete address
391 * @param string $alias alias that has to be deleted
392 * @return bool
393 */
394 function remove($alias) {
395 if(!$this->writeable) {
396 return $this->set_error(_("Addressbook is read-only"));
397 }
398
399 /* Lock the file to make sure we're the only process working
400 * on it. */
401 if(!$this->lock()) {
402 return $this->set_error(_("Could not lock datafile"));
403 }
404
405 /* Read file into memory, ignoring nicknames to delete */
406 @rewind($this->filehandle);
407 $i = 0;
408 $rows = array();
409 while($row = @fgetcsv($this->filehandle, 2048, '|')) {
410 if(!in_array($row[0], $alias)) {
411 $rows[$i++] = $row;
412 }
413 }
414
415 /* Write data back */
416 if(!$this->overwrite($rows)) {
417 $this->unlock();
418 return false;
419 }
420
421 $this->unlock();
422 return true;
423 }
424
425 /**
426 * Modify address
427 * @param string $alias modified alias
428 * @param array $userdata new data
429 * @return bool true, if operation successful
430 */
431 function modify($alias, $userdata) {
432 if(!$this->writeable) {
433 return $this->set_error(_("Addressbook is read-only"));
434 }
435
436 /* See if user exists */
437 $ret = $this->lookup($alias);
438 if(empty($ret)) {
439 return $this->set_error(sprintf(_("User '%s' does not exist"),
440 $alias));
441 }
442
443 /* Lock the file to make sure we're the only process working
444 * on it. */
445 if(!$this->lock()) {
446 return $this->set_error(_("Could not lock datafile"));
447 }
448
449 /* Read file into memory, modifying the data for the
450 * user identified by $alias */
451 $this->open(true);
452 @rewind($this->filehandle);
453 $i = 0;
454 $rows = array();
455 while($row = @fgetcsv($this->filehandle, 2048, '|')) {
456 if(strtolower($row[0]) != strtolower($alias)) {
457 $rows[$i++] = $row;
458 } else {
459 $rows[$i++] = array(0 => $userdata['nickname'],
460 1 => $userdata['firstname'],
461 2 => $userdata['lastname'],
462 3 => $userdata['email'],
463 4 => $userdata['label']);
464 }
465 }
466
467 /* Write data back */
468 if(!$this->overwrite($rows)) {
469 $this->unlock();
470 return false;
471 }
472
473 $this->unlock();
474 return true;
475 }
476
477 /**
478 * Function for quoting values before saving
479 * @param string $value string that has to be quoted
480 * @param string quoted string
481 */
482 function quotevalue($value) {
483 /* Quote the field if it contains | or ". Double quotes need to
484 * be replaced with "" */
485 if(ereg("[|\"]", $value)) {
486 $value = '"' . str_replace('"', '""', $value) . '"';
487 }
488 return $value;
489 }
490
491 } /* End of class abook_local_file */
492 ?>