6 * @copyright 1999-2021 The SquirrelMail Project Team
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
9 * @package squirrelmail
10 * @subpackage addressbook
14 * Backend for address book as a pipe separated file
16 * Stores the address book in a local file
18 * An array with the following elements must be passed to
19 * the class constructor (elements marked ? are optional):
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 * ? listing => enable/disable listing
31 * NOTE. This class should not be used directly. Use the
32 * "AddressBook" class instead.
33 * @package squirrelmail
35 class abook_local_file
extends addressbook_backend
{
45 var $bname = 'local_file';
48 * File used to store data
58 * Create file, if it not present
63 * Detect, if address book is writeable by checking file permisions
66 var $detect_writeable = true;
68 * Control write access to address book
70 * Option does not have any effect, if 'detect_writeable' is 'true'
73 var $writeable = false;
75 * controls listing of address book
85 * Sets max entry size (number of bytes used for all address book fields
86 * (including escapes) + 4 delimiters + 1 linefeed)
90 var $line_length = 2048;
92 /* ========================== Private ======================= */
95 * Constructor (PHP5 style, required in some future version of PHP)
96 * @param array $param backend options
99 function __construct($param) {
100 $this->sname
= _("Personal Address Book");
101 $this->umask
= Umask();
103 if(is_array($param)) {
104 if(empty($param['filename'])) {
105 return $this->set_error('Invalid parameters');
107 if(!is_string($param['filename'])) {
108 return $this->set_error($param['filename'] . ': '.
109 _("Not a file name"));
112 $this->filename
= $param['filename'];
114 if(isset($param['create'])) {
115 $this->create
= $param['create'];
117 if(isset($param['umask'])) {
118 $this->umask
= $param['umask'];
120 if(isset($param['name'])) {
121 $this->sname
= $param['name'];
123 if(isset($param['detect_writeable'])) {
124 $this->detect_writeable
= $param['detect_writeable'];
126 if(!empty($param['writeable'])) {
127 $this->writeable
= $param['writeable'];
129 if(isset($param['listing'])) {
130 $this->listing
= $param['listing'];
132 if(isset($param['line_length']) && ! empty($param['line_length'])) {
133 $this->line_length
= (int) $param['line_length'];
138 $this->set_error('Invalid argument to constructor');
143 * Constructor (PHP4 style, kept for compatibility reasons)
144 * @param array $param backend options
147 function abook_local_file($param) {
148 return self
::__construct($param);
152 * Open the addressbook file and store the file pointer.
153 * Use $file as the file to open, or the class' own
154 * filename property. If $param is empty and file is
156 * @param bool $new is file already opened
159 function open($new = false) {
161 $file = $this->filename
;
162 $create = $this->create
;
163 $fopenmode = (($this->writeable
&& sq_is_writable($file)) ?
'a+' : 'r');
165 /* Return true is file is open and $new is unset */
166 if($this->filehandle
&& !$new) {
170 /* Check that new file exitsts */
171 if((!(file_exists($file) && is_readable($file))) && !$create) {
172 return $this->set_error("$file: " . _("No such file or directory"));
175 /* Close old file, if any */
176 if($this->filehandle
) { $this->close(); }
179 if (! $this->detect_writeable
) {
180 $fh = @fopen
($file,$fopenmode);
182 $this->filehandle
= &$fh;
183 $this->filename
= $file;
185 return $this->set_error("$file: " . _("Open failed"));
188 /* Open file. First try to open for reading and writing,
189 * but fall back to read only. */
190 $fh = @fopen
($file, 'a+');
192 $this->filehandle
= &$fh;
193 $this->filename
= $file;
194 $this->writeable
= true;
196 $fh = @fopen
($file, 'r');
198 $this->filehandle
= &$fh;
199 $this->filename
= $file;
200 $this->writeable
= false;
202 return $this->set_error("$file: " . _("Open failed"));
209 /** Close the file and forget the filehandle */
211 @fclose
($this->filehandle
);
212 $this->filehandle
= 0;
213 $this->filename
= '';
214 $this->writable
= false;
217 /** Lock the datafile - try 20 times in 5 seconds */
219 for($i = 0 ; $i < 20 ; $i++
) {
220 if(flock($this->filehandle
, 2 +
4))
228 /** Unlock the datafile */
230 return flock($this->filehandle
, 3);
234 * Overwrite the file with data from $rows
235 * NOTE! Previous locks are broken by this function
236 * @param array $rows new data
239 function overwrite(&$rows) {
241 $newfh = @fopen
($this->filename
.'.tmp', 'w');
244 return $this->set_error($this->filename
. '.tmp:' . _("Open failed"));
247 for($i = 0, $cnt=sizeof($rows) ; $i < $cnt ; $i++
) {
248 if(is_array($rows[$i])) {
249 for($j = 0, $cnt_part=count($rows[$i]) ; $j < $cnt_part ; $j++
) {
250 $rows[$i][$j] = $this->quotevalue($rows[$i][$j]);
252 $tmpwrite = sq_fwrite($newfh, join('|', $rows[$i]) . "\n");
253 if ($tmpwrite === FALSE) {
254 return $this->set_error($this->filename
. '.tmp:' . _("Write failed"));
260 if (!@copy
($this->filename
. '.tmp' , $this->filename
)) {
261 return $this->set_error($this->filename
. ':' . _("Unable to update"));
263 @unlink
($this->filename
. '.tmp');
264 @chmod
($this->filename
, 0600);
270 /* ========================== Public ======================== */
274 * @param string $expr search expression
275 * @return array search results
277 function search($expr) {
279 /* To be replaced by advanded search expression parsing */
280 if(is_array($expr)) { return; }
282 // don't allow wide search when listing is disabled.
283 if ($expr=='*' && ! $this->listing
)
286 // Make regexp from glob'ed expression
287 $expr = preg_quote($expr);
288 $expr = str_replace(array('\\?', '\\*'), array('.', '.*'), $expr);
294 @rewind
($this->filehandle
);
296 while ($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
299 * address book is corrupted.
302 error_box(_("Address book is corrupted. Required fields are missing."));
303 $oTemplate->display('footer.tpl');
307 * TODO: regexp search is supported only in local_file backend.
308 * Do we check format of regexp or ignore errors?
310 // errors on preg_match call are suppressed in order to prevent display of regexp compilation errors
311 if (@preg_match
('/' . $expr . '/i', $row[0]) // nickname
312 || @preg_match
('/' . $expr . '/i', $row[1]) // firstname
313 || @preg_match
('/' . $expr . '/i', $row[2]) // lastname
314 || @preg_match
('/' . $expr . '/i', $row[3])) { // email
315 array_push($res, array('nickname' => $row[0],
316 'name' => $this->fullname($row[1], $row[2]),
317 'firstname' => $row[1],
318 'lastname' => $row[2],
321 'backend' => $this->bnum
,
322 'source' => &$this->sname
));
331 * Lookup an address by the indicated field.
333 * @param string $value The value to look up
334 * @param integer $field The field to look in, should be one
335 * of the SM_ABOOK_FIELD_* constants
336 * defined in include/constants.php
337 * (OPTIONAL; defaults to nickname field)
338 * NOTE: uniqueness is only guaranteed
339 * when the nickname field is used here;
340 * otherwise, the first matching address
343 * @return array Array with lookup results when the value
344 * was found, an empty array if the value was
348 function lookup($value, $field=SM_ABOOK_FIELD_NICKNAME
) {
353 $value = strtolower($value);
356 @rewind
($this->filehandle
);
358 while ($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
361 * address book is corrupted.
364 error_box(_("Address book is corrupted. Required fields are missing."));
365 $oTemplate->display('footer.tpl');
368 if(strtolower($row[$field]) == $value) {
369 return array('nickname' => $row[0],
370 'name' => $this->fullname($row[1], $row[2]),
371 'firstname' => $row[1],
372 'lastname' => $row[2],
375 'backend' => $this->bnum
,
376 'source' => &$this->sname
);
386 * @return array list of all addresses
388 function list_addr() {
391 if(isset($this->listing
) && !$this->listing
) {
396 @rewind
($this->filehandle
);
398 while ($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
401 * address book is corrupted. Don't be nice to people that
402 * violate address book formating.
405 error_box(_("Address book is corrupted. Required fields are missing."));
406 $oTemplate->display('footer.tpl');
409 array_push($res, array('nickname' => $row[0],
410 'name' => $this->fullname($row[1], $row[2]),
411 'firstname' => $row[1],
412 'lastname' => $row[2],
415 'backend' => $this->bnum
,
416 'source' => &$this->sname
));
424 * @param array $userdata new data
427 function add($userdata) {
428 if(!$this->writeable
) {
429 return $this->set_error(_("Address book is read-only"));
431 /* See if user exists already */
432 $ret = $this->lookup($userdata['nickname']);
434 // i18n: don't use html formating in translation
435 return $this->set_error(sprintf(_("User \"%s\" already exists"),$ret['nickname']));
438 /* Here is the data to write */
439 $data = $this->quotevalue($userdata['nickname']) . '|' .
440 $this->quotevalue($userdata['firstname']) . '|' .
441 $this->quotevalue((!empty($userdata['lastname'])?
$userdata['lastname']:'')) . '|' .
442 $this->quotevalue($userdata['email']) . '|' .
443 $this->quotevalue((!empty($userdata['label'])?
$userdata['label']:''));
445 /* Strip linefeeds */
446 $nl_str = array("\r","\n");
447 $data = str_replace($nl_str, ' ', $data);
450 * Make sure that entry fits into allocated record space.
451 * One byte is reserved for linefeed
453 if (strlen($data) >= $this->line_length
) {
454 return $this->set_error(_("Address book entry is too big"));
457 /* Add linefeed at end */
458 $data = $data . "\n";
460 /* Reopen file, just to be sure */
462 if(!$this->writeable
) {
463 return $this->set_error(_("Address book is read-only"));
468 return $this->set_error(_("Could not lock datafile"));
472 $r = sq_fwrite($this->filehandle
, $data);
477 /* Test write result */
480 $this->set_error(_("Write to address book failed"));
489 * @param string $alias alias that has to be deleted
492 function remove($alias) {
493 if(!$this->writeable
) {
494 return $this->set_error(_("Address book is read-only"));
497 /* Lock the file to make sure we're the only process working
500 return $this->set_error(_("Could not lock datafile"));
503 /* Read file into memory, ignoring nicknames to delete */
504 @rewind
($this->filehandle
);
507 while($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
508 if(!in_array($row[0], $alias)) {
513 /* Write data back */
514 if(!$this->overwrite($rows)) {
525 * @param string $alias modified alias
526 * @param array $userdata new data
527 * @return bool true, if operation successful
529 function modify($alias, $userdata) {
530 if(!$this->writeable
) {
531 return $this->set_error(_("Address book is read-only"));
534 /* See if user exists */
535 $ret = $this->lookup($alias);
537 // i18n: don't use html formating in translation
538 return $this->set_error(sprintf(_("User \"%s\" does not exist"),$alias));
541 /* If the alias changed, see if the new alias exists */
542 if (strtolower($alias) != strtolower($userdata['nickname'])) {
543 $ret = $this->lookup($userdata['nickname']);
545 return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
549 /* Lock the file to make sure we're the only process working
552 return $this->set_error(_("Could not lock datafile"));
555 /* calculate userdata size */
556 $data = $this->quotevalue($userdata['nickname']) . '|'
557 . $this->quotevalue($userdata['firstname']) . '|'
558 . $this->quotevalue((!empty($userdata['lastname'])?
$userdata['lastname']:'')) . '|'
559 . $this->quotevalue($userdata['email']) . '|'
560 . $this->quotevalue((!empty($userdata['label'])?
$userdata['label']:''));
561 /* make sure that it fits into allocated space */
562 if (strlen($data) >= $this->line_length
) {
563 return $this->set_error(_("Address book entry is too big"));
566 /* Read file into memory, modifying the data for the
567 * user identified by $alias */
569 @rewind
($this->filehandle
);
572 while($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
573 if(strtolower($row[0]) != strtolower($alias)) {
576 $rows[$i++
] = array(0 => $userdata['nickname'],
577 1 => $userdata['firstname'],
578 2 => (!empty($userdata['lastname'])?
$userdata['lastname']:''),
579 3 => $userdata['email'],
580 4 => (!empty($userdata['label'])?
$userdata['label']:''));
584 /* Write data back */
585 if(!$this->overwrite($rows)) {
595 * Function for quoting values before saving
596 * @param string $value string that has to be quoted
597 * @param string quoted string
599 function quotevalue($value) {
600 /* Quote the field if it contains | or ". Double quotes need to
601 * be replaced with "" */
602 if(stristr($value, '"') ||
stristr($value, '|')) {
603 $value = '"' . str_replace('"', '""', $value) . '"';