d29474f6d4cdd8cae463283e6bb53af96d9cc88f
6 * @copyright © 1999-2007 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 ======================= */
96 * @param array $param backend options
99 function abook_local_file($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 * Open the addressbook file and store the file pointer.
144 * Use $file as the file to open, or the class' own
145 * filename property. If $param is empty and file is
147 * @param bool $new is file already opened
150 function open($new = false) {
152 $file = $this->filename
;
153 $create = $this->create
;
154 $fopenmode = (($this->writeable
&& sq_is_writable($file)) ?
'a+' : 'r');
156 /* Return true is file is open and $new is unset */
157 if($this->filehandle
&& !$new) {
161 /* Check that new file exitsts */
162 if((!(file_exists($file) && is_readable($file))) && !$create) {
163 return $this->set_error("$file: " . _("No such file or directory"));
166 /* Close old file, if any */
167 if($this->filehandle
) { $this->close(); }
170 if (! $this->detect_writeable
) {
171 $fh = @fopen
($file,$fopenmode);
173 $this->filehandle
= &$fh;
174 $this->filename
= $file;
176 return $this->set_error("$file: " . _("Open failed"));
179 /* Open file. First try to open for reading and writing,
180 * but fall back to read only. */
181 $fh = @fopen
($file, 'a+');
183 $this->filehandle
= &$fh;
184 $this->filename
= $file;
185 $this->writeable
= true;
187 $fh = @fopen
($file, 'r');
189 $this->filehandle
= &$fh;
190 $this->filename
= $file;
191 $this->writeable
= false;
193 return $this->set_error("$file: " . _("Open failed"));
200 /** Close the file and forget the filehandle */
202 @fclose
($this->filehandle
);
203 $this->filehandle
= 0;
204 $this->filename
= '';
205 $this->writable
= false;
208 /** Lock the datafile - try 20 times in 5 seconds */
210 for($i = 0 ; $i < 20 ; $i++
) {
211 if(flock($this->filehandle
, 2 +
4))
219 /** Unlock the datafile */
221 return flock($this->filehandle
, 3);
225 * Overwrite the file with data from $rows
226 * NOTE! Previous locks are broken by this function
227 * @param array $rows new data
230 function overwrite(&$rows) {
232 $newfh = @fopen
($this->filename
.'.tmp', 'w');
235 return $this->set_error($this->filename
. '.tmp:' . _("Open failed"));
238 for($i = 0, $cnt=sizeof($rows) ; $i < $cnt ; $i++
) {
239 if(is_array($rows[$i])) {
240 for($j = 0, $cnt_part=count($rows[$i]) ; $j < $cnt_part ; $j++
) {
241 $rows[$i][$j] = $this->quotevalue($rows[$i][$j]);
243 $tmpwrite = sq_fwrite($newfh, join('|', $rows[$i]) . "\n");
244 if ($tmpwrite === FALSE) {
245 return $this->set_error($this->filename
. '.tmp:' . _("Write failed"));
251 if (!@copy
($this->filename
. '.tmp' , $this->filename
)) {
252 return $this->set_error($this->filename
. ':' . _("Unable to update"));
254 @unlink
($this->filename
. '.tmp');
260 /* ========================== Public ======================== */
264 * @param string $expr search expression
265 * @return array search results
267 function search($expr) {
269 /* To be replaced by advanded search expression parsing */
270 if(is_array($expr)) { return; }
272 // don't allow wide search when listing is disabled.
273 if ($expr=='*' && ! $this->listing
)
276 /* Make regexp from glob'ed expression
277 * May want to quote other special characters like (, ), -, [, ], etc. */
278 $expr = str_replace('?', '.', $expr);
279 $expr = str_replace('*', '.*', $expr);
285 @rewind
($this->filehandle
);
287 while ($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
290 * address book is corrupted.
293 error_box(_("Address book is corrupted. Required fields are missing."));
294 $oTemplate->display('footer.tpl');
297 $line = join(' ', $row);
299 * TODO: regexp search is supported only in local_file backend.
300 * Do we check format of regexp or ignore errors?
302 // errors on eregi call are suppressed in order to prevent display of regexp compilation errors
303 if(@eregi
($expr, $line)) {
304 array_push($res, array('nickname' => $row[0],
305 'name' => $this->fullname($row[1], $row[2]),
306 'firstname' => $row[1],
307 'lastname' => $row[2],
310 'backend' => $this->bnum
,
311 'source' => &$this->sname
));
320 * Lookup an address by the indicated field.
322 * @param string $value The value to look up
323 * @param integer $field The field to look in, should be one
324 * of the SM_ABOOK_FIELD_* constants
325 * defined in include/constants.php
326 * (OPTIONAL; defaults to nickname field)
327 * NOTE: uniqueness is only guaranteed
328 * when the nickname field is used here;
329 * otherwise, the first matching address
332 * @return array Array with lookup results when the value
333 * was found, an empty array if the value was
337 function lookup($value, $field=SM_ABOOK_FIELD_NICKNAME
) {
342 $value = strtolower($value);
345 @rewind
($this->filehandle
);
347 while ($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
350 * address book is corrupted.
353 error_box(_("Address book is corrupted. Required fields are missing."));
354 $oTemplate->display('footer.tpl');
357 if(strtolower($row[$field]) == $value) {
358 return array('nickname' => $row[0],
359 'name' => $this->fullname($row[1], $row[2]),
360 'firstname' => $row[1],
361 'lastname' => $row[2],
364 'backend' => $this->bnum
,
365 'source' => &$this->sname
);
375 * @return array list of all addresses
377 function list_addr() {
380 if(isset($this->listing
) && !$this->listing
) {
385 @rewind
($this->filehandle
);
387 while ($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
390 * address book is corrupted. Don't be nice to people that
391 * violate address book formating.
394 error_box(_("Address book is corrupted. Required fields are missing."));
395 $oTemplate->display('footer.tpl');
398 array_push($res, array('nickname' => $row[0],
399 'name' => $this->fullname($row[1], $row[2]),
400 'firstname' => $row[1],
401 'lastname' => $row[2],
404 'backend' => $this->bnum
,
405 'source' => &$this->sname
));
413 * @param array $userdata new data
416 function add($userdata) {
417 if(!$this->writeable
) {
418 return $this->set_error(_("Address book is read-only"));
420 /* See if user exists already */
421 $ret = $this->lookup($userdata['nickname']);
423 // i18n: don't use html formating in translation
424 return $this->set_error(sprintf(_("User \"%s\" already exists"),$ret['nickname']));
427 /* Here is the data to write */
428 $data = $this->quotevalue($userdata['nickname']) . '|' .
429 $this->quotevalue($userdata['firstname']) . '|' .
430 $this->quotevalue((!empty($userdata['lastname'])?
$userdata['lastname']:'')) . '|' .
431 $this->quotevalue($userdata['email']) . '|' .
432 $this->quotevalue((!empty($userdata['label'])?
$userdata['label']:''));
434 /* Strip linefeeds */
435 $data = ereg_replace("[\r\n]", ' ', $data);
438 * Make sure that entry fits into allocated record space.
439 * One byte is reserved for linefeed
441 if (strlen($data) >= $this->line_length
) {
442 return $this->set_error(_("Address book entry is too big"));
445 /* Add linefeed at end */
446 $data = $data . "\n";
448 /* Reopen file, just to be sure */
450 if(!$this->writeable
) {
451 return $this->set_error(_("Address book is read-only"));
456 return $this->set_error(_("Could not lock datafile"));
460 $r = sq_fwrite($this->filehandle
, $data);
465 /* Test write result */
468 $this->set_error(_("Write to address book failed"));
477 * @param string $alias alias that has to be deleted
480 function remove($alias) {
481 if(!$this->writeable
) {
482 return $this->set_error(_("Address book is read-only"));
485 /* Lock the file to make sure we're the only process working
488 return $this->set_error(_("Could not lock datafile"));
491 /* Read file into memory, ignoring nicknames to delete */
492 @rewind
($this->filehandle
);
495 while($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
496 if(!in_array($row[0], $alias)) {
501 /* Write data back */
502 if(!$this->overwrite($rows)) {
513 * @param string $alias modified alias
514 * @param array $userdata new data
515 * @return bool true, if operation successful
517 function modify($alias, $userdata) {
518 if(!$this->writeable
) {
519 return $this->set_error(_("Address book is read-only"));
522 /* See if user exists */
523 $ret = $this->lookup($alias);
525 // i18n: don't use html formating in translation
526 return $this->set_error(sprintf(_("User \"%s\" does not exist"),$alias));
529 /* If the alias changed, see if the new alias exists */
530 if (strtolower($alias) != strtolower($userdata['nickname'])) {
531 $ret = $this->lookup($userdata['nickname']);
533 return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
537 /* Lock the file to make sure we're the only process working
540 return $this->set_error(_("Could not lock datafile"));
543 /* calculate userdata size */
544 $data = $this->quotevalue($userdata['nickname']) . '|'
545 . $this->quotevalue($userdata['firstname']) . '|'
546 . $this->quotevalue((!empty($userdata['lastname'])?
$userdata['lastname']:'')) . '|'
547 . $this->quotevalue($userdata['email']) . '|'
548 . $this->quotevalue((!empty($userdata['label'])?
$userdata['label']:''));
549 /* make sure that it fits into allocated space */
550 if (strlen($data) >= $this->line_length
) {
551 return $this->set_error(_("Address book entry is too big"));
554 /* Read file into memory, modifying the data for the
555 * user identified by $alias */
557 @rewind
($this->filehandle
);
560 while($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
561 if(strtolower($row[0]) != strtolower($alias)) {
564 $rows[$i++
] = array(0 => $userdata['nickname'],
565 1 => $userdata['firstname'],
566 2 => (!empty($userdata['lastname'])?
$userdata['lastname']:''),
567 3 => $userdata['email'],
568 4 => (!empty($userdata['label'])?
$userdata['label']:''));
572 /* Write data back */
573 if(!$this->overwrite($rows)) {
583 * Function for quoting values before saving
584 * @param string $value string that has to be quoted
585 * @param string quoted string
587 function quotevalue($value) {
588 /* Quote the field if it contains | or ". Double quotes need to
589 * be replaced with "" */
590 if(ereg("[|\"]", $value)) {
591 $value = '"' . str_replace('"', '""', $value) . '"';