open file rw only if it is writable
[squirrelmail.git] / functions / abook_local_file.php
CommitLineData
5100704d 1<?php
35586184 2/**
3 * abook_local_file.php
4 *
6c84ba1e 5 * Copyright (c) 1999-2005 The SquirrelMail Project Team
35586184 6 * Licensed under the GNU GPL. For full terms see the file COPYING.
7 *
a9d318b0 8 * @version $Id$
d6c32258 9 * @package squirrelmail
a9d318b0 10 * @subpackage addressbook
35586184 11 */
5100704d 12
d6c32258 13/**
147e5af3 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.
675357d2 24 * ? name => name of address book.
91e0dccc 25 * ? detect_writeable => detect address book access permissions by
675357d2 26 * checking file permissions.
27 * ? writeable => allow writing into address book. Used only when
28 * detect_writeable is set to false.
147e5af3 29 *</pre>
30 * NOTE. This class should not be used directly. Use the
31 * "AddressBook" class instead.
8f6f9ba5 32 * @package squirrelmail
d6c32258 33 */
35586184 34class abook_local_file extends addressbook_backend {
4272758c 35 /**
36 * Backend type
91e0dccc 37 * @var string
4272758c 38 */
06b4facd 39 var $btype = 'local';
4272758c 40 /**
41 * Backend name
42 * @var string
43 */
06b4facd 44 var $bname = 'local_file';
45
4272758c 46 /**
47 * File used to store data
48 * @var string
49 */
50 var $filename = '';
51 /**
52 * File handle
53 * @var object
54 */
06b4facd 55 var $filehandle = 0;
4272758c 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 */
06b4facd 77 var $umask;
78
79 /* ========================== Private ======================= */
80
147e5af3 81 /**
82 * Constructor
83 * @param array $param backend options
84 * @return bool
85 */
06b4facd 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
147e5af3 101 if(isset($param['create'])) {
102 $this->create = $param['create'];
06b4facd 103 }
104 if(isset($param['umask'])) {
105 $this->umask = $param['umask'];
106 }
4272758c 107 if(isset($param['name'])) {
06b4facd 108 $this->sname = $param['name'];
109 }
4272758c 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 }
62f7daa5 116
06b4facd 117 $this->open(true);
118 } else {
119 $this->set_error('Invalid argument to constructor');
120 }
121 }
122
147e5af3 123 /**
124 * Open the addressbook file and store the file pointer.
62f7daa5 125 * Use $file as the file to open, or the class' own
126 * filename property. If $param is empty and file is
147e5af3 127 * open, do nothing.
128 * @param bool $new is file already opened
129 * @return bool
130 */
06b4facd 131 function open($new = false) {
132 $this->error = '';
133 $file = $this->filename;
134 $create = $this->create;
d5d43e57 135 $fopenmode = (($this->writeable && is_writable($file)) ? 'a+' : 'r');
62f7daa5 136
06b4facd 137 /* Return true is file is open and $new is unset */
138 if($this->filehandle && !$new) {
139 return true;
140 }
62f7daa5 141
06b4facd 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 }
62f7daa5 146
06b4facd 147 /* Close old file, if any */
148 if($this->filehandle) { $this->close(); }
62f7daa5 149
06b4facd 150 umask($this->umask);
4272758c 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 }
06b4facd 159 } else {
4272758c 160 /* Open file. First try to open for reading and writing,
161 * but fall back to read only. */
162 $fh = @fopen($file, 'a+');
06b4facd 163 if($fh) {
164 $this->filehandle = &$fh;
165 $this->filename = $file;
4272758c 166 $this->writeable = true;
06b4facd 167 } else {
4272758c 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 }
06b4facd 176 }
177 }
178 return true;
179 }
180
147e5af3 181 /** Close the file and forget the filehandle */
06b4facd 182 function close() {
183 @fclose($this->filehandle);
184 $this->filehandle = 0;
185 $this->filename = '';
186 $this->writable = false;
187 }
188
147e5af3 189 /** Lock the datafile - try 20 times in 5 seconds */
06b4facd 190 function lock() {
191 for($i = 0 ; $i < 20 ; $i++) {
62f7daa5 192 if(flock($this->filehandle, 2 + 4))
06b4facd 193 return true;
194 else
195 usleep(250000);
196 }
197 return false;
198 }
199
147e5af3 200 /** Unlock the datafile */
06b4facd 201 function unlock() {
202 return flock($this->filehandle, 3);
203 }
204
147e5af3 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 */
06b4facd 211 function overwrite(&$rows) {
01265fba 212 $this->unlock();
dabef6fd 213 $newfh = @fopen($this->filename.'.tmp', 'w');
214
06b4facd 215 if(!$newfh) {
dabef6fd 216 return $this->set_error($this->filename. '.tmp:' . _("Open failed"));
06b4facd 217 }
62f7daa5 218
dabef6fd 219 for($i = 0, $cnt=sizeof($rows) ; $i < $cnt ; $i++) {
06b4facd 220 if(is_array($rows[$i])) {
dabef6fd 221 for($j = 0, $cnt_part=count($rows[$i]) ; $j < $cnt_part ; $j++) {
77ec28e9 222 $rows[$i][$j] = $this->quotevalue($rows[$i][$j]);
223 }
3ecad5e6 224 $tmpwrite = sq_fwrite($newfh, join('|', $rows[$i]) . "\n");
225 if ($tmpwrite === FALSE) {
dabef6fd 226 return $this->set_error($this->filename . '.tmp:' . _("Write failed"));
227 }
06b4facd 228 }
62f7daa5 229 }
06b4facd 230
231 fclose($newfh);
baa59994 232 if (!@copy($this->filename . '.tmp' , $this->filename)) {
dabef6fd 233 return $this->set_error($this->filename . ':' . _("Unable to update"));
baa59994 234 }
dabef6fd 235 @unlink($this->filename . '.tmp');
06b4facd 236 $this->unlock();
237 $this->open(true);
238 return true;
239 }
62f7daa5 240
06b4facd 241 /* ========================== Public ======================== */
62f7daa5 242
147e5af3 243 /**
244 * Search the file
245 * @param string $expr search expression
246 * @return array search results
247 */
06b4facd 248 function search($expr) {
249
250 /* To be replaced by advanded search expression parsing */
251 if(is_array($expr)) { return; }
62f7daa5 252
06b4facd 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);
62f7daa5 257
06b4facd 258 $res = array();
259 if(!$this->open()) {
260 return false;
261 }
262 @rewind($this->filehandle);
62f7daa5 263
06b4facd 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 }
62f7daa5 277
06b4facd 278 return $res;
279 }
62f7daa5 280
147e5af3 281 /**
282 * Lookup alias
283 * @param string $alias alias
284 * @return array search results
285 */
06b4facd 286 function lookup($alias) {
287 if(empty($alias)) {
288 return array();
289 }
290
291 $alias = strtolower($alias);
62f7daa5 292
06b4facd 293 $this->open();
294 @rewind($this->filehandle);
62f7daa5 295
06b4facd 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 }
62f7daa5 308
06b4facd 309 return array();
310 }
311
147e5af3 312 /**
313 * List all addresses
314 * @return array list of all addresses
315 */
06b4facd 316 function list_addr() {
317 $res = array();
318 $this->open();
319 @rewind($this->filehandle);
62f7daa5 320
06b4facd 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
147e5af3 334 /**
335 * Add address
336 * @param array $userdata new data
337 * @return bool
338 */
06b4facd 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 }
62f7daa5 349
06b4facd 350 /* Here is the data to write */
77ec28e9 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
06b4facd 357 /* Strip linefeeds */
358 $data = ereg_replace("[\r\n]", ' ', $data);
359 /* Add linefeed at end */
360 $data = $data . "\n";
62f7daa5 361
06b4facd 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 }
62f7daa5 367
06b4facd 368 /* Lock the file */
369 if(!$this->lock()) {
370 return $this->set_error(_("Could not lock datafile"));
371 }
62f7daa5 372
06b4facd 373 /* Write */
3ecad5e6 374 $r = sq_fwrite($this->filehandle, $data);
62f7daa5 375
06b4facd 376 /* Unlock file */
377 $this->unlock();
62f7daa5 378
3ecad5e6 379 /* Test write result */
380 if($r === FALSE) {
147e5af3 381 /* Fail */
382 $this->set_error(_("Write to addressbook failed"));
383 return FALSE;
384 }
62f7daa5 385
3ecad5e6 386 return TRUE;
06b4facd 387 }
388
147e5af3 389 /**
390 * Delete address
391 * @param string $alias alias that has to be deleted
392 * @return bool
393 */
06b4facd 394 function remove($alias) {
395 if(!$this->writeable) {
396 return $this->set_error(_("Addressbook is read-only"));
397 }
62f7daa5 398
06b4facd 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 }
62f7daa5 404
06b4facd 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 }
62f7daa5 414
06b4facd 415 /* Write data back */
416 if(!$this->overwrite($rows)) {
417 $this->unlock();
418 return false;
419 }
62f7daa5 420
06b4facd 421 $this->unlock();
422 return true;
423 }
424
147e5af3 425 /**
426 * Modify address
427 * @param string $alias modified alias
428 * @param array $userdata new data
429 * @return bool true, if operation successful
430 */
06b4facd 431 function modify($alias, $userdata) {
432 if(!$this->writeable) {
433 return $this->set_error(_("Addressbook is read-only"));
434 }
62f7daa5 435
06b4facd 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 }
62f7daa5 442
06b4facd 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 }
62f7daa5 448
449 /* Read file into memory, modifying the data for the
06b4facd 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'],
62f7daa5 462 3 => $userdata['email'],
06b4facd 463 4 => $userdata['label']);
464 }
465 }
62f7daa5 466
06b4facd 467 /* Write data back */
468 if(!$this->overwrite($rows)) {
469 $this->unlock();
470 return false;
471 }
62f7daa5 472
06b4facd 473 $this->unlock();
474 return true;
475 }
62f7daa5 476
147e5af3 477 /**
478 * Function for quoting values before saving
479 * @param string $value string that has to be quoted
480 * @param string quoted string
481 */
77ec28e9 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
06b4facd 491} /* End of class abook_local_file */
62f7daa5 492?>