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 /* ========================== Private ======================= */
89 * @param array $param backend options
92 function abook_local_file($param) {
93 $this->sname
= _("Personal address book");
94 $this->umask
= Umask();
96 if(is_array($param)) {
97 if(empty($param['filename'])) {
98 return $this->set_error('Invalid parameters');
100 if(!is_string($param['filename'])) {
101 return $this->set_error($param['filename'] . ': '.
102 _("Not a file name"));
105 $this->filename
= $param['filename'];
107 if(isset($param['create'])) {
108 $this->create
= $param['create'];
110 if(isset($param['umask'])) {
111 $this->umask
= $param['umask'];
113 if(isset($param['name'])) {
114 $this->sname
= $param['name'];
116 if(isset($param['detect_writeable'])) {
117 $this->detect_writeable
= $param['detect_writeable'];
119 if(!empty($param['writeable'])) {
120 $this->writeable
= $param['writeable'];
122 if(isset($param['listing'])) {
123 $this->listing
= $param['listing'];
128 $this->set_error('Invalid argument to constructor');
133 * Open the addressbook file and store the file pointer.
134 * Use $file as the file to open, or the class' own
135 * filename property. If $param is empty and file is
137 * @param bool $new is file already opened
140 function open($new = false) {
142 $file = $this->filename
;
143 $create = $this->create
;
144 $fopenmode = (($this->writeable
&& is_writable($file)) ?
'a+' : 'r');
146 /* Return true is file is open and $new is unset */
147 if($this->filehandle
&& !$new) {
151 /* Check that new file exitsts */
152 if((!(file_exists($file) && is_readable($file))) && !$create) {
153 return $this->set_error("$file: " . _("No such file or directory"));
156 /* Close old file, if any */
157 if($this->filehandle
) { $this->close(); }
160 if (! $this->detect_writeable
) {
161 $fh = @fopen
($file,$fopenmode);
163 $this->filehandle
= &$fh;
164 $this->filename
= $file;
166 return $this->set_error("$file: " . _("Open failed"));
169 /* Open file. First try to open for reading and writing,
170 * but fall back to read only. */
171 $fh = @fopen
($file, 'a+');
173 $this->filehandle
= &$fh;
174 $this->filename
= $file;
175 $this->writeable
= true;
177 $fh = @fopen
($file, 'r');
179 $this->filehandle
= &$fh;
180 $this->filename
= $file;
181 $this->writeable
= false;
183 return $this->set_error("$file: " . _("Open failed"));
190 /** Close the file and forget the filehandle */
192 @fclose
($this->filehandle
);
193 $this->filehandle
= 0;
194 $this->filename
= '';
195 $this->writable
= false;
198 /** Lock the datafile - try 20 times in 5 seconds */
200 for($i = 0 ; $i < 20 ; $i++
) {
201 if(flock($this->filehandle
, 2 +
4))
209 /** Unlock the datafile */
211 return flock($this->filehandle
, 3);
215 * Overwrite the file with data from $rows
216 * NOTE! Previous locks are broken by this function
217 * @param array $rows new data
220 function overwrite(&$rows) {
222 $newfh = @fopen
($this->filename
.'.tmp', 'w');
225 return $this->set_error($this->filename
. '.tmp:' . _("Open failed"));
228 for($i = 0, $cnt=sizeof($rows) ; $i < $cnt ; $i++
) {
229 if(is_array($rows[$i])) {
230 for($j = 0, $cnt_part=count($rows[$i]) ; $j < $cnt_part ; $j++
) {
231 $rows[$i][$j] = $this->quotevalue($rows[$i][$j]);
233 $tmpwrite = sq_fwrite($newfh, join('|', $rows[$i]) . "\n");
234 if ($tmpwrite === FALSE) {
235 return $this->set_error($this->filename
. '.tmp:' . _("Write failed"));
241 if (!@copy
($this->filename
. '.tmp' , $this->filename
)) {
242 return $this->set_error($this->filename
. ':' . _("Unable to update"));
244 @unlink
($this->filename
. '.tmp');
250 /* ========================== Public ======================== */
254 * @param string $expr search expression
255 * @return array search results
257 function search($expr) {
259 /* To be replaced by advanded search expression parsing */
260 if(is_array($expr)) { return; }
262 // don't allow wide search when listing is disabled.
263 if ($expr=='*' && ! $this->listing
)
266 /* Make regexp from glob'ed expression
267 * May want to quote other special characters like (, ), -, [, ], etc. */
268 $expr = str_replace('?', '.', $expr);
269 $expr = str_replace('*', '.*', $expr);
275 @rewind
($this->filehandle
);
277 while ($row = @fgetcsv
($this->filehandle
, 2048, '|')) {
278 $line = join(' ', $row);
280 * TODO: regexp search is supported only in local_file backend.
281 * Do we check format of regexp or ignore errors?
283 // errors on eregi call are suppressed in order to prevent display of regexp compilation errors
284 if(@eregi
($expr, $line)) {
285 array_push($res, array('nickname' => $row[0],
286 'name' => $row[1] . ' ' . $row[2],
287 'firstname' => $row[1],
288 'lastname' => $row[2],
291 'backend' => $this->bnum
,
292 'source' => &$this->sname
));
301 * @param string $alias alias
302 * @return array search results
304 function lookup($alias) {
309 $alias = strtolower($alias);
312 @rewind
($this->filehandle
);
314 while ($row = @fgetcsv
($this->filehandle
, 2048, '|')) {
315 if(strtolower($row[0]) == $alias) {
316 return array('nickname' => $row[0],
317 'name' => $row[1] . ' ' . $row[2],
318 'firstname' => $row[1],
319 'lastname' => $row[2],
322 'backend' => $this->bnum
,
323 'source' => &$this->sname
);
332 * @return array list of all addresses
334 function list_addr() {
337 if(isset($this->listing
) && !$this->listing
) {
342 @rewind
($this->filehandle
);
344 while ($row = @fgetcsv
($this->filehandle
, 2048, '|')) {
345 array_push($res, array('nickname' => $row[0],
346 'name' => $row[1] . ' ' . $row[2],
347 'firstname' => $row[1],
348 'lastname' => $row[2],
351 'backend' => $this->bnum
,
352 'source' => &$this->sname
));
359 * @param array $userdata new data
362 function add($userdata) {
363 if(!$this->writeable
) {
364 return $this->set_error(_("Addressbook is read-only"));
366 /* See if user exists already */
367 $ret = $this->lookup($userdata['nickname']);
369 // i18n: don't use html formating in translation
370 return $this->set_error(sprintf(_("User \"%s\" already exists"),$ret['nickname']));
373 /* Here is the data to write */
374 $data = $this->quotevalue($userdata['nickname']) . '|' .
375 $this->quotevalue($userdata['firstname']) . '|' .
376 $this->quotevalue((!empty($userdata['lastname'])?
$userdata['lastname']:'')) . '|' .
377 $this->quotevalue($userdata['email']) . '|' .
378 $this->quotevalue((!empty($userdata['label'])?
$userdata['label']:''));
380 /* Strip linefeeds */
381 $data = ereg_replace("[\r\n]", ' ', $data);
382 /* Add linefeed at end */
383 $data = $data . "\n";
385 /* Reopen file, just to be sure */
387 if(!$this->writeable
) {
388 return $this->set_error(_("Addressbook is read-only"));
393 return $this->set_error(_("Could not lock datafile"));
397 $r = sq_fwrite($this->filehandle
, $data);
402 /* Test write result */
405 $this->set_error(_("Write to addressbook failed"));
414 * @param string $alias alias that has to be deleted
417 function remove($alias) {
418 if(!$this->writeable
) {
419 return $this->set_error(_("Addressbook is read-only"));
422 /* Lock the file to make sure we're the only process working
425 return $this->set_error(_("Could not lock datafile"));
428 /* Read file into memory, ignoring nicknames to delete */
429 @rewind
($this->filehandle
);
432 while($row = @fgetcsv
($this->filehandle
, 2048, '|')) {
433 if(!in_array($row[0], $alias)) {
438 /* Write data back */
439 if(!$this->overwrite($rows)) {
450 * @param string $alias modified alias
451 * @param array $userdata new data
452 * @return bool true, if operation successful
454 function modify($alias, $userdata) {
455 if(!$this->writeable
) {
456 return $this->set_error(_("Addressbook is read-only"));
459 /* See if user exists */
460 $ret = $this->lookup($alias);
462 // i18n: don't use html formating in translation
463 return $this->set_error(sprintf(_("User \"%s\" does not exist"),$alias));
466 /* Lock the file to make sure we're the only process working
469 return $this->set_error(_("Could not lock datafile"));
472 /* Read file into memory, modifying the data for the
473 * user identified by $alias */
475 @rewind
($this->filehandle
);
478 while($row = @fgetcsv
($this->filehandle
, 2048, '|')) {
479 if(strtolower($row[0]) != strtolower($alias)) {
482 $rows[$i++
] = array(0 => $userdata['nickname'],
483 1 => $userdata['firstname'],
484 2 => (!empty($userdata['lastname'])?
$userdata['lastname']:''),
485 3 => $userdata['email'],
486 4 => (!empty($userdata['label'])?
$userdata['label']:''));
490 /* Write data back */
491 if(!$this->overwrite($rows)) {
501 * Function for quoting values before saving
502 * @param string $value string that has to be quoted
503 * @param string quoted string
505 function quotevalue($value) {
506 /* Quote the field if it contains | or ". Double quotes need to
507 * be replaced with "" */
508 if(ereg("[|\"]", $value)) {
509 $value = '"' . str_replace('"', '""', $value) . '"';
514 } /* End of class abook_local_file */