6 * @copyright © 1999-2006 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
&& 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
));
321 * @param string $alias alias
322 * @return array search results
324 function lookup($alias) {
329 $alias = strtolower($alias);
332 @rewind
($this->filehandle
);
334 while ($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
337 * address book is corrupted.
340 error_box(_("Address book is corrupted. Required fields are missing."));
341 $oTemplate->display('footer.tpl');
344 if(strtolower($row[0]) == $alias) {
345 return array('nickname' => $row[0],
346 'name' => $this->fullname($row[1], $row[2]),
347 'firstname' => $row[1],
348 'lastname' => $row[2],
351 'backend' => $this->bnum
,
352 'source' => &$this->sname
);
362 * @return array list of all addresses
364 function list_addr() {
367 if(isset($this->listing
) && !$this->listing
) {
372 @rewind
($this->filehandle
);
374 while ($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
377 * address book is corrupted. Don't be nice to people that
378 * violate address book formating.
381 error_box(_("Address book is corrupted. Required fields are missing."));
382 $oTemplate->display('footer.tpl');
385 array_push($res, array('nickname' => $row[0],
386 'name' => $this->fullname($row[1], $row[2]),
387 'firstname' => $row[1],
388 'lastname' => $row[2],
391 'backend' => $this->bnum
,
392 'source' => &$this->sname
));
400 * @param array $userdata new data
403 function add($userdata) {
404 if(!$this->writeable
) {
405 return $this->set_error(_("Address book is read-only"));
407 /* See if user exists already */
408 $ret = $this->lookup($userdata['nickname']);
410 // i18n: don't use html formating in translation
411 return $this->set_error(sprintf(_("User \"%s\" already exists"),$ret['nickname']));
414 /* Here is the data to write */
415 $data = $this->quotevalue($userdata['nickname']) . '|' .
416 $this->quotevalue($userdata['firstname']) . '|' .
417 $this->quotevalue((!empty($userdata['lastname'])?
$userdata['lastname']:'')) . '|' .
418 $this->quotevalue($userdata['email']) . '|' .
419 $this->quotevalue((!empty($userdata['label'])?
$userdata['label']:''));
421 /* Strip linefeeds */
422 $data = ereg_replace("[\r\n]", ' ', $data);
425 * Make sure that entry fits into allocated record space.
426 * One byte is reserved for linefeed
428 if (strlen($data) >= $this->line_length
) {
429 return $this->set_error(_("Address book entry is too big"));
432 /* Add linefeed at end */
433 $data = $data . "\n";
435 /* Reopen file, just to be sure */
437 if(!$this->writeable
) {
438 return $this->set_error(_("Address book is read-only"));
443 return $this->set_error(_("Could not lock datafile"));
447 $r = sq_fwrite($this->filehandle
, $data);
452 /* Test write result */
455 $this->set_error(_("Write to address book failed"));
464 * @param string $alias alias that has to be deleted
467 function remove($alias) {
468 if(!$this->writeable
) {
469 return $this->set_error(_("Address book is read-only"));
472 /* Lock the file to make sure we're the only process working
475 return $this->set_error(_("Could not lock datafile"));
478 /* Read file into memory, ignoring nicknames to delete */
479 @rewind
($this->filehandle
);
482 while($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
483 if(!in_array($row[0], $alias)) {
488 /* Write data back */
489 if(!$this->overwrite($rows)) {
500 * @param string $alias modified alias
501 * @param array $userdata new data
502 * @return bool true, if operation successful
504 function modify($alias, $userdata) {
505 if(!$this->writeable
) {
506 return $this->set_error(_("Address book is read-only"));
509 /* See if user exists */
510 $ret = $this->lookup($alias);
512 // i18n: don't use html formating in translation
513 return $this->set_error(sprintf(_("User \"%s\" does not exist"),$alias));
516 /* If the alias changed, see if the new alias exists */
517 if (strtolower($alias) != strtolower($userdata['nickname'])) {
518 $ret = $this->lookup($userdata['nickname']);
520 return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
524 /* Lock the file to make sure we're the only process working
527 return $this->set_error(_("Could not lock datafile"));
530 /* calculate userdata size */
531 $data = $this->quotevalue($userdata['nickname']) . '|'
532 . $this->quotevalue($userdata['firstname']) . '|'
533 . $this->quotevalue((!empty($userdata['lastname'])?
$userdata['lastname']:'')) . '|'
534 . $this->quotevalue($userdata['email']) . '|'
535 . $this->quotevalue((!empty($userdata['label'])?
$userdata['label']:''));
536 /* make sure that it fits into allocated space */
537 if (strlen($data) >= $this->line_length
) {
538 return $this->set_error(_("Address book entry is too big"));
541 /* Read file into memory, modifying the data for the
542 * user identified by $alias */
544 @rewind
($this->filehandle
);
547 while($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
548 if(strtolower($row[0]) != strtolower($alias)) {
551 $rows[$i++
] = array(0 => $userdata['nickname'],
552 1 => $userdata['firstname'],
553 2 => (!empty($userdata['lastname'])?
$userdata['lastname']:''),
554 3 => $userdata['email'],
555 4 => (!empty($userdata['label'])?
$userdata['label']:''));
559 /* Write data back */
560 if(!$this->overwrite($rows)) {
570 * Function for quoting values before saving
571 * @param string $value string that has to be quoted
572 * @param string quoted string
574 function quotevalue($value) {
575 /* Quote the field if it contains | or ". Double quotes need to
576 * be replaced with "" */
577 if(ereg("[|\"]", $value)) {
578 $value = '"' . str_replace('"', '""', $value) . '"';