f72796b496dfb2edb5ea7e12d9ad0a5eda463152
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
&& 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)
328 * @return array Array with lookup results when the value
329 * was found, an empty array if the value was
333 function lookup($value, $field=SM_ABOOK_FIELD_NICKNAME
) {
338 $value = strtolower($value);
341 @rewind
($this->filehandle
);
343 while ($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
346 * address book is corrupted.
349 error_box(_("Address book is corrupted. Required fields are missing."));
350 $oTemplate->display('footer.tpl');
353 if(strtolower($row[$field]) == $value) {
354 return array('nickname' => $row[0],
355 'name' => $this->fullname($row[1], $row[2]),
356 'firstname' => $row[1],
357 'lastname' => $row[2],
360 'backend' => $this->bnum
,
361 'source' => &$this->sname
);
371 * @return array list of all addresses
373 function list_addr() {
376 if(isset($this->listing
) && !$this->listing
) {
381 @rewind
($this->filehandle
);
383 while ($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
386 * address book is corrupted. Don't be nice to people that
387 * violate address book formating.
390 error_box(_("Address book is corrupted. Required fields are missing."));
391 $oTemplate->display('footer.tpl');
394 array_push($res, array('nickname' => $row[0],
395 'name' => $this->fullname($row[1], $row[2]),
396 'firstname' => $row[1],
397 'lastname' => $row[2],
400 'backend' => $this->bnum
,
401 'source' => &$this->sname
));
409 * @param array $userdata new data
412 function add($userdata) {
413 if(!$this->writeable
) {
414 return $this->set_error(_("Address book is read-only"));
416 /* See if user exists already */
417 $ret = $this->lookup($userdata['nickname']);
419 // i18n: don't use html formating in translation
420 return $this->set_error(sprintf(_("User \"%s\" already exists"),$ret['nickname']));
423 /* Here is the data to write */
424 $data = $this->quotevalue($userdata['nickname']) . '|' .
425 $this->quotevalue($userdata['firstname']) . '|' .
426 $this->quotevalue((!empty($userdata['lastname'])?
$userdata['lastname']:'')) . '|' .
427 $this->quotevalue($userdata['email']) . '|' .
428 $this->quotevalue((!empty($userdata['label'])?
$userdata['label']:''));
430 /* Strip linefeeds */
431 $data = ereg_replace("[\r\n]", ' ', $data);
434 * Make sure that entry fits into allocated record space.
435 * One byte is reserved for linefeed
437 if (strlen($data) >= $this->line_length
) {
438 return $this->set_error(_("Address book entry is too big"));
441 /* Add linefeed at end */
442 $data = $data . "\n";
444 /* Reopen file, just to be sure */
446 if(!$this->writeable
) {
447 return $this->set_error(_("Address book is read-only"));
452 return $this->set_error(_("Could not lock datafile"));
456 $r = sq_fwrite($this->filehandle
, $data);
461 /* Test write result */
464 $this->set_error(_("Write to address book failed"));
473 * @param string $alias alias that has to be deleted
476 function remove($alias) {
477 if(!$this->writeable
) {
478 return $this->set_error(_("Address book is read-only"));
481 /* Lock the file to make sure we're the only process working
484 return $this->set_error(_("Could not lock datafile"));
487 /* Read file into memory, ignoring nicknames to delete */
488 @rewind
($this->filehandle
);
491 while($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
492 if(!in_array($row[0], $alias)) {
497 /* Write data back */
498 if(!$this->overwrite($rows)) {
509 * @param string $alias modified alias
510 * @param array $userdata new data
511 * @return bool true, if operation successful
513 function modify($alias, $userdata) {
514 if(!$this->writeable
) {
515 return $this->set_error(_("Address book is read-only"));
518 /* See if user exists */
519 $ret = $this->lookup($alias);
521 // i18n: don't use html formating in translation
522 return $this->set_error(sprintf(_("User \"%s\" does not exist"),$alias));
525 /* If the alias changed, see if the new alias exists */
526 if (strtolower($alias) != strtolower($userdata['nickname'])) {
527 $ret = $this->lookup($userdata['nickname']);
529 return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
533 /* Lock the file to make sure we're the only process working
536 return $this->set_error(_("Could not lock datafile"));
539 /* calculate userdata size */
540 $data = $this->quotevalue($userdata['nickname']) . '|'
541 . $this->quotevalue($userdata['firstname']) . '|'
542 . $this->quotevalue((!empty($userdata['lastname'])?
$userdata['lastname']:'')) . '|'
543 . $this->quotevalue($userdata['email']) . '|'
544 . $this->quotevalue((!empty($userdata['label'])?
$userdata['label']:''));
545 /* make sure that it fits into allocated space */
546 if (strlen($data) >= $this->line_length
) {
547 return $this->set_error(_("Address book entry is too big"));
550 /* Read file into memory, modifying the data for the
551 * user identified by $alias */
553 @rewind
($this->filehandle
);
556 while($row = @fgetcsv
($this->filehandle
, $this->line_length
, '|')) {
557 if(strtolower($row[0]) != strtolower($alias)) {
560 $rows[$i++
] = array(0 => $userdata['nickname'],
561 1 => $userdata['firstname'],
562 2 => (!empty($userdata['lastname'])?
$userdata['lastname']:''),
563 3 => $userdata['email'],
564 4 => (!empty($userdata['label'])?
$userdata['label']:''));
568 /* Write data back */
569 if(!$this->overwrite($rows)) {
579 * Function for quoting values before saving
580 * @param string $value string that has to be quoted
581 * @param string quoted string
583 function quotevalue($value) {
584 /* Quote the field if it contains | or ". Double quotes need to
585 * be replaced with "" */
586 if(ereg("[|\"]", $value)) {
587 $value = '"' . str_replace('"', '""', $value) . '"';