Revert my changes on this plugin, I didn't notice that the globals were dynamically...
[squirrelmail.git] / functions / abook_local_file.php
1 <?php
2 /**
3 * abook_local_file.php
4 *
5 * Copyright (c) 1999-2004 The SquirrelMail Project Team
6 * Licensed under the GNU GPL. For full terms see the file COPYING.
7 *
8 * @version $Id$
9 * @package squirrelmail
10 * @subpackage addressbook
11 */
12
13 /**
14 * Backend for address book as a pipe separated file
15 *
16 * Stores the address book in a local file
17 *
18 * An array with the following elements must be passed to
19 * the class constructor (elements marked ? are optional):
20 *<pre>
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 *</pre>
26 * NOTE. This class should not be used directly. Use the
27 * "AddressBook" class instead.
28 * @package squirrelmail
29 */
30 class abook_local_file extends addressbook_backend {
31 /** @var string backend type */
32 var $btype = 'local';
33 /** @var string backend name */
34 var $bname = 'local_file';
35
36 /** @var string file used to store data */
37 var $filename = '';
38 /** @var object file handle */
39 var $filehandle = 0;
40 /** @var bool create file if it is not present */
41 var $create = false;
42 /** @var string umask of the file */
43 var $umask;
44
45 /* ========================== Private ======================= */
46
47 /**
48 * Constructor
49 * @param array $param backend options
50 * @return bool
51 */
52 function abook_local_file($param) {
53 $this->sname = _("Personal address book");
54 $this->umask = Umask();
55
56 if(is_array($param)) {
57 if(empty($param['filename'])) {
58 return $this->set_error('Invalid parameters');
59 }
60 if(!is_string($param['filename'])) {
61 return $this->set_error($param['filename'] . ': '.
62 _("Not a file name"));
63 }
64
65 $this->filename = $param['filename'];
66
67 if(isset($param['create'])) {
68 $this->create = $param['create'];
69 }
70 if(isset($param['umask'])) {
71 $this->umask = $param['umask'];
72 }
73 if(!empty($param['name'])) {
74 $this->sname = $param['name'];
75 }
76
77 $this->open(true);
78 } else {
79 $this->set_error('Invalid argument to constructor');
80 }
81 }
82
83 /**
84 * Open the addressbook file and store the file pointer.
85 * Use $file as the file to open, or the class' own
86 * filename property. If $param is empty and file is
87 * open, do nothing.
88 * @param bool $new is file already opened
89 * @return bool
90 */
91 function open($new = false) {
92 $this->error = '';
93 $file = $this->filename;
94 $create = $this->create;
95
96 /* Return true is file is open and $new is unset */
97 if($this->filehandle && !$new) {
98 return true;
99 }
100
101 /* Check that new file exitsts */
102 if((!(file_exists($file) && is_readable($file))) && !$create) {
103 return $this->set_error("$file: " . _("No such file or directory"));
104 }
105
106 /* Close old file, if any */
107 if($this->filehandle) { $this->close(); }
108
109 /* Open file. First try to open for reading and writing,
110 * but fall back to read only. */
111 umask($this->umask);
112 $fh = @fopen($file, 'a+');
113 if($fh) {
114 $this->filehandle = &$fh;
115 $this->filename = $file;
116 $this->writeable = true;
117 } else {
118 $fh = @fopen($file, 'r');
119 if($fh) {
120 $this->filehandle = &$fh;
121 $this->filename = $file;
122 $this->writeable = false;
123 } else {
124 return $this->set_error("$file: " . _("Open failed"));
125 }
126 }
127 return true;
128 }
129
130 /** Close the file and forget the filehandle */
131 function close() {
132 @fclose($this->filehandle);
133 $this->filehandle = 0;
134 $this->filename = '';
135 $this->writable = false;
136 }
137
138 /** Lock the datafile - try 20 times in 5 seconds */
139 function lock() {
140 for($i = 0 ; $i < 20 ; $i++) {
141 if(flock($this->filehandle, 2 + 4))
142 return true;
143 else
144 usleep(250000);
145 }
146 return false;
147 }
148
149 /** Unlock the datafile */
150 function unlock() {
151 return flock($this->filehandle, 3);
152 }
153
154 /**
155 * Overwrite the file with data from $rows
156 * NOTE! Previous locks are broken by this function
157 * @param array $rows new data
158 * @return bool
159 */
160 function overwrite(&$rows) {
161 $this->unlock();
162 $newfh = @fopen($this->filename.'.tmp', 'w');
163
164 if(!$newfh) {
165 return $this->set_error($this->filename. '.tmp:' . _("Open failed"));
166 }
167
168 for($i = 0, $cnt=sizeof($rows) ; $i < $cnt ; $i++) {
169 if(is_array($rows[$i])) {
170 for($j = 0, $cnt_part=count($rows[$i]) ; $j < $cnt_part ; $j++) {
171 $rows[$i][$j] = $this->quotevalue($rows[$i][$j]);
172 }
173 $tmpwrite = sq_fwrite($newfh, join('|', $rows[$i]) . "\n");
174 if ($tmpwrite === FALSE) {
175 return $this->set_error($this->filename . '.tmp:' . _("Write failed"));
176 }
177 }
178 }
179
180 fclose($newfh);
181 if (!@copy($this->filename . '.tmp' , $this->filename)) {
182 return $this->set_error($this->filename . ':' . _("Unable to update"));
183 }
184 @unlink($this->filename . '.tmp');
185 $this->unlock();
186 $this->open(true);
187 return true;
188 }
189
190 /* ========================== Public ======================== */
191
192 /**
193 * Search the file
194 * @param string $expr search expression
195 * @return array search results
196 */
197 function search($expr) {
198
199 /* To be replaced by advanded search expression parsing */
200 if(is_array($expr)) { return; }
201
202 /* Make regexp from glob'ed expression
203 * May want to quote other special characters like (, ), -, [, ], etc. */
204 $expr = str_replace('?', '.', $expr);
205 $expr = str_replace('*', '.*', $expr);
206
207 $res = array();
208 if(!$this->open()) {
209 return false;
210 }
211 @rewind($this->filehandle);
212
213 while ($row = @fgetcsv($this->filehandle, 2048, '|')) {
214 $line = join(' ', $row);
215 if(eregi($expr, $line)) {
216 array_push($res, array('nickname' => $row[0],
217 'name' => $row[1] . ' ' . $row[2],
218 'firstname' => $row[1],
219 'lastname' => $row[2],
220 'email' => $row[3],
221 'label' => $row[4],
222 'backend' => $this->bnum,
223 'source' => &$this->sname));
224 }
225 }
226
227 return $res;
228 }
229
230 /**
231 * Lookup alias
232 * @param string $alias alias
233 * @return array search results
234 */
235 function lookup($alias) {
236 if(empty($alias)) {
237 return array();
238 }
239
240 $alias = strtolower($alias);
241
242 $this->open();
243 @rewind($this->filehandle);
244
245 while ($row = @fgetcsv($this->filehandle, 2048, '|')) {
246 if(strtolower($row[0]) == $alias) {
247 return array('nickname' => $row[0],
248 'name' => $row[1] . ' ' . $row[2],
249 'firstname' => $row[1],
250 'lastname' => $row[2],
251 'email' => $row[3],
252 'label' => $row[4],
253 'backend' => $this->bnum,
254 'source' => &$this->sname);
255 }
256 }
257
258 return array();
259 }
260
261 /**
262 * List all addresses
263 * @return array list of all addresses
264 */
265 function list_addr() {
266 $res = array();
267 $this->open();
268 @rewind($this->filehandle);
269
270 while ($row = @fgetcsv($this->filehandle, 2048, '|')) {
271 array_push($res, array('nickname' => $row[0],
272 'name' => $row[1] . ' ' . $row[2],
273 'firstname' => $row[1],
274 'lastname' => $row[2],
275 'email' => $row[3],
276 'label' => $row[4],
277 'backend' => $this->bnum,
278 'source' => &$this->sname));
279 }
280 return $res;
281 }
282
283 /**
284 * Add address
285 * @param array $userdata new data
286 * @return bool
287 */
288 function add($userdata) {
289 if(!$this->writeable) {
290 return $this->set_error(_("Addressbook is read-only"));
291 }
292 /* See if user exists already */
293 $ret = $this->lookup($userdata['nickname']);
294 if(!empty($ret)) {
295 return $this->set_error(sprintf(_("User '%s' already exist"),
296 $ret['nickname']));
297 }
298
299 /* Here is the data to write */
300 $data = $this->quotevalue($userdata['nickname']) . '|' .
301 $this->quotevalue($userdata['firstname']) . '|' .
302 $this->quotevalue($userdata['lastname']) . '|' .
303 $this->quotevalue($userdata['email']) . '|' .
304 $this->quotevalue($userdata['label']);
305
306 /* Strip linefeeds */
307 $data = ereg_replace("[\r\n]", ' ', $data);
308 /* Add linefeed at end */
309 $data = $data . "\n";
310
311 /* Reopen file, just to be sure */
312 $this->open(true);
313 if(!$this->writeable) {
314 return $this->set_error(_("Addressbook is read-only"));
315 }
316
317 /* Lock the file */
318 if(!$this->lock()) {
319 return $this->set_error(_("Could not lock datafile"));
320 }
321
322 /* Write */
323 $r = sq_fwrite($this->filehandle, $data);
324
325 /* Unlock file */
326 $this->unlock();
327
328 /* Test write result */
329 if($r === FALSE) {
330 /* Fail */
331 $this->set_error(_("Write to addressbook failed"));
332 return FALSE;
333 }
334
335 return TRUE;
336 }
337
338 /**
339 * Delete address
340 * @param string $alias alias that has to be deleted
341 * @return bool
342 */
343 function remove($alias) {
344 if(!$this->writeable) {
345 return $this->set_error(_("Addressbook is read-only"));
346 }
347
348 /* Lock the file to make sure we're the only process working
349 * on it. */
350 if(!$this->lock()) {
351 return $this->set_error(_("Could not lock datafile"));
352 }
353
354 /* Read file into memory, ignoring nicknames to delete */
355 @rewind($this->filehandle);
356 $i = 0;
357 $rows = array();
358 while($row = @fgetcsv($this->filehandle, 2048, '|')) {
359 if(!in_array($row[0], $alias)) {
360 $rows[$i++] = $row;
361 }
362 }
363
364 /* Write data back */
365 if(!$this->overwrite($rows)) {
366 $this->unlock();
367 return false;
368 }
369
370 $this->unlock();
371 return true;
372 }
373
374 /**
375 * Modify address
376 * @param string $alias modified alias
377 * @param array $userdata new data
378 * @return bool true, if operation successful
379 */
380 function modify($alias, $userdata) {
381 if(!$this->writeable) {
382 return $this->set_error(_("Addressbook is read-only"));
383 }
384
385 /* See if user exists */
386 $ret = $this->lookup($alias);
387 if(empty($ret)) {
388 return $this->set_error(sprintf(_("User '%s' does not exist"),
389 $alias));
390 }
391
392 /* Lock the file to make sure we're the only process working
393 * on it. */
394 if(!$this->lock()) {
395 return $this->set_error(_("Could not lock datafile"));
396 }
397
398 /* Read file into memory, modifying the data for the
399 * user identified by $alias */
400 $this->open(true);
401 @rewind($this->filehandle);
402 $i = 0;
403 $rows = array();
404 while($row = @fgetcsv($this->filehandle, 2048, '|')) {
405 if(strtolower($row[0]) != strtolower($alias)) {
406 $rows[$i++] = $row;
407 } else {
408 $rows[$i++] = array(0 => $userdata['nickname'],
409 1 => $userdata['firstname'],
410 2 => $userdata['lastname'],
411 3 => $userdata['email'],
412 4 => $userdata['label']);
413 }
414 }
415
416 /* Write data back */
417 if(!$this->overwrite($rows)) {
418 $this->unlock();
419 return false;
420 }
421
422 $this->unlock();
423 return true;
424 }
425
426 /**
427 * Function for quoting values before saving
428 * @param string $value string that has to be quoted
429 * @param string quoted string
430 */
431 function quotevalue($value) {
432 /* Quote the field if it contains | or ". Double quotes need to
433 * be replaced with "" */
434 if(ereg("[|\"]", $value)) {
435 $value = '"' . str_replace('"', '""', $value) . '"';
436 }
437 return $value;
438 }
439
440 } /* End of class abook_local_file */
441 ?>