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