documentation fix.
[squirrelmail.git] / functions / abook_database.php
1 <?php
2
3 /**
4 * abook_database.php
5 *
6 * @copyright &copy; 1999-2006 The SquirrelMail Project Team
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
8 * @version $Id$
9 * @package squirrelmail
10 * @subpackage addressbook
11 */
12
13 /**
14 * Needs the DB functions
15 * Don't display errors here. Error will be set in class constructor function.
16 */
17 @include_once('DB.php');
18
19 /**
20 * Address book in a database backend
21 *
22 * Backend for personal/shared address book stored in a database,
23 * accessed using the DB-classes in PEAR.
24 *
25 * IMPORTANT: The PEAR modules must be in the include path
26 * for this class to work.
27 *
28 * An array with the following elements must be passed to
29 * the class constructor (elements marked ? are optional):
30 * <pre>
31 * dsn => database DNS (see PEAR for syntax)
32 * table => table to store addresses in (must exist)
33 * owner => current user (owner of address data)
34 * ? name => name of address book
35 * ? writeable => set writeable flag (true/false)
36 * ? listing => enable/disable listing
37 * </pre>
38 * The table used should have the following columns:
39 * owner, nickname, firstname, lastname, email, label
40 * The pair (owner,nickname) should be unique (primary key).
41 *
42 * NOTE. This class should not be used directly. Use the
43 * "AddressBook" class instead.
44 * @package squirrelmail
45 * @subpackage addressbook
46 */
47 class abook_database extends addressbook_backend {
48 /**
49 * Backend type
50 * @var string
51 */
52 var $btype = 'local';
53 /**
54 * Backend name
55 * @var string
56 */
57 var $bname = 'database';
58
59 /**
60 * Data Source Name (connection description)
61 * @var string
62 */
63 var $dsn = '';
64 /**
65 * Table that stores addresses
66 * @var string
67 */
68 var $table = '';
69 /**
70 * Owner name
71 *
72 * Limits list of database entries visible to end user
73 * @var string
74 */
75 var $owner = '';
76 /**
77 * Database Handle
78 * @var resource
79 */
80 var $dbh = false;
81 /**
82 * Enable/disable writing into address book
83 * @var bool
84 */
85 var $writeable = true;
86 /**
87 * Enable/disable address book listing
88 * @var bool
89 */
90 var $listing = true;
91
92 /* ========================== Private ======================= */
93
94 /**
95 * Constructor
96 * @param array $param address book backend options
97 */
98 function abook_database($param) {
99 $this->sname = _("Personal address book");
100
101 /* test if Pear DB class is available and freak out if it is not */
102 if (! class_exists('DB')) {
103 // same error also in db_prefs.php
104 $error = _("Could not include PEAR database functions required for the database backend.") . "<br />\n";
105 $error .= sprintf(_("Is PEAR installed, and is the include path set correctly to find %s?"),
106 '<tt>DB.php</tt>') . "<br />\n";
107 $error .= _("Please contact your system administrator and report this error.");
108 return $this->set_error($error);
109 }
110
111 if (is_array($param)) {
112 if (empty($param['dsn']) ||
113 empty($param['table']) ||
114 empty($param['owner'])) {
115 return $this->set_error('Invalid parameters');
116 }
117
118 $this->dsn = $param['dsn'];
119 $this->table = $param['table'];
120 $this->owner = $param['owner'];
121
122 if (!empty($param['name'])) {
123 $this->sname = $param['name'];
124 }
125
126 if (isset($param['writeable'])) {
127 $this->writeable = $param['writeable'];
128 }
129
130 if (isset($param['listing'])) {
131 $this->listing = $param['listing'];
132 }
133
134 $this->open(true);
135 }
136 else {
137 return $this->set_error('Invalid argument to constructor');
138 }
139 }
140
141
142 /**
143 * Open the database.
144 * @param bool $new new connection if it is true
145 * @return bool
146 */
147 function open($new = false) {
148 $this->error = '';
149
150 /* Return true is file is open and $new is unset */
151 if ($this->dbh && !$new) {
152 return true;
153 }
154
155 /* Close old file, if any */
156 if ($this->dbh) {
157 $this->close();
158 }
159
160 $dbh = DB::connect($this->dsn, true);
161
162 if (DB::isError($dbh)) {
163 return $this->set_error(sprintf(_("Database error: %s"),
164 DB::errorMessage($dbh)));
165 }
166
167 $this->dbh = $dbh;
168 return true;
169 }
170
171 /**
172 * Close the file and forget the filehandle
173 */
174 function close() {
175 $this->dbh->disconnect();
176 $this->dbh = false;
177 }
178
179 /* ========================== Public ======================== */
180
181 /**
182 * Search the database
183 * @param string $expr search expression
184 * @return array search results
185 */
186 function search($expr) {
187 $ret = array();
188 if(!$this->open()) {
189 return false;
190 }
191
192 /* To be replaced by advanded search expression parsing */
193 if (is_array($expr)) {
194 return;
195 }
196
197 // don't allow wide search when listing is disabled.
198 if ($expr=='*' && ! $this->listing)
199 return array();
200
201 /* Make regexp from glob'ed expression */
202 $expr = str_replace('?', '_', $expr);
203 $expr = str_replace('*', '%', $expr);
204 $expr = $this->dbh->quoteString($expr);
205 $expr = "%$expr%";
206
207 $query = sprintf("SELECT * FROM %s WHERE owner='%s' AND " .
208 "(firstname LIKE '%s' OR lastname LIKE '%s')",
209 $this->table, $this->owner, $expr, $expr);
210 $res = $this->dbh->query($query);
211
212 if (DB::isError($res)) {
213 return $this->set_error(sprintf(_("Database error: %s"),
214 DB::errorMessage($res)));
215 }
216
217 while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
218 array_push($ret, array('nickname' => $row['nickname'],
219 'name' => "$row[firstname] $row[lastname]",
220 'firstname' => $row['firstname'],
221 'lastname' => $row['lastname'],
222 'email' => $row['email'],
223 'label' => $row['label'],
224 'backend' => $this->bnum,
225 'source' => &$this->sname));
226 }
227 return $ret;
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 if (!$this->open()) {
243 return false;
244 }
245
246 $query = sprintf("SELECT * FROM %s WHERE owner='%s' AND LOWER(nickname)='%s'",
247 $this->table, $this->owner, $this->dbh->quoteString($alias));
248
249 $res = $this->dbh->query($query);
250
251 if (DB::isError($res)) {
252 return $this->set_error(sprintf(_("Database error: %s"),
253 DB::errorMessage($res)));
254 }
255
256 if ($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
257 return array('nickname' => $row['nickname'],
258 'name' => "$row[firstname] $row[lastname]",
259 'firstname' => $row['firstname'],
260 'lastname' => $row['lastname'],
261 'email' => $row['email'],
262 'label' => $row['label'],
263 'backend' => $this->bnum,
264 'source' => &$this->sname);
265 }
266 return array();
267 }
268
269 /**
270 * List all addresses
271 * @return array search results
272 */
273 function list_addr() {
274 $ret = array();
275 if (!$this->open()) {
276 return false;
277 }
278
279 if(isset($this->listing) && !$this->listing) {
280 return array();
281 }
282
283
284 $query = sprintf("SELECT * FROM %s WHERE owner='%s'",
285 $this->table, $this->owner);
286
287 $res = $this->dbh->query($query);
288
289 if (DB::isError($res)) {
290 return $this->set_error(sprintf(_("Database error: %s"),
291 DB::errorMessage($res)));
292 }
293
294 while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
295 array_push($ret, array('nickname' => $row['nickname'],
296 'name' => "$row[firstname] $row[lastname]",
297 'firstname' => $row['firstname'],
298 'lastname' => $row['lastname'],
299 'email' => $row['email'],
300 'label' => $row['label'],
301 'backend' => $this->bnum,
302 'source' => &$this->sname));
303 }
304 return $ret;
305 }
306
307 /**
308 * Add address
309 * @param array $userdata added data
310 * @return bool
311 */
312 function add($userdata) {
313 if (!$this->writeable) {
314 return $this->set_error(_("Addressbook is read-only"));
315 }
316
317 if (!$this->open()) {
318 return false;
319 }
320
321 /* See if user exist already */
322 $ret = $this->lookup($userdata['nickname']);
323 if (!empty($ret)) {
324 return $this->set_error(sprintf(_("User \"%s\" already exists"),$ret['nickname']));
325 }
326
327 /* Create query */
328 $query = sprintf("INSERT INTO %s (owner, nickname, firstname, " .
329 "lastname, email, label) VALUES('%s','%s','%s'," .
330 "'%s','%s','%s')",
331 $this->table, $this->owner,
332 $this->dbh->quoteString($userdata['nickname']),
333 $this->dbh->quoteString($userdata['firstname']),
334 $this->dbh->quoteString((!empty($userdata['lastname'])?$userdata['lastname']:'')),
335 $this->dbh->quoteString($userdata['email']),
336 $this->dbh->quoteString((!empty($userdata['label'])?$userdata['label']:'')) );
337
338 /* Do the insert */
339 $r = $this->dbh->simpleQuery($query);
340 if ($r == DB_OK) {
341 return true;
342 }
343
344 /* Fail */
345 return $this->set_error(sprintf(_("Database error: %s"),
346 DB::errorMessage($r)));
347 }
348
349 /**
350 * Deletes address book entries
351 * @param array $alias aliases that have to be deleted. numerical
352 * array with nickname values
353 * @return bool
354 */
355 function remove($alias) {
356 if (!$this->writeable) {
357 return $this->set_error(_("Addressbook is read-only"));
358 }
359
360 if (!$this->open()) {
361 return false;
362 }
363
364 /* Create query */
365 $query = sprintf("DELETE FROM %s WHERE owner='%s' AND (",
366 $this->table, $this->owner);
367
368 $sepstr = '';
369 while (list($undef, $nickname) = each($alias)) {
370 $query .= sprintf("%s nickname='%s' ", $sepstr,
371 $this->dbh->quoteString($nickname));
372 $sepstr = 'OR';
373 }
374 $query .= ')';
375
376 /* Delete entry */
377 $r = $this->dbh->simpleQuery($query);
378 if ($r == DB_OK) {
379 return true;
380 }
381
382 /* Fail */
383 return $this->set_error(sprintf(_("Database error: %s"),
384 DB::errorMessage($r)));
385 }
386
387 /**
388 * Modify address
389 * @param string $alias modified alias
390 * @param array $userdata new data
391 * @return bool
392 */
393 function modify($alias, $userdata) {
394 if (!$this->writeable) {
395 return $this->set_error(_("Addressbook is read-only"));
396 }
397
398 if (!$this->open()) {
399 return false;
400 }
401
402 /* See if user exist */
403 $ret = $this->lookup($alias);
404 if (empty($ret)) {
405 return $this->set_error(sprintf(_("User \"%s\" does not exist"),$alias));
406 }
407
408 /* Create query */
409 $query = sprintf("UPDATE %s SET nickname='%s', firstname='%s', ".
410 "lastname='%s', email='%s', label='%s' ".
411 "WHERE owner='%s' AND nickname='%s'",
412 $this->table,
413 $this->dbh->quoteString($userdata['nickname']),
414 $this->dbh->quoteString($userdata['firstname']),
415 $this->dbh->quoteString((!empty($userdata['lastname'])?$userdata['lastname']:'')),
416 $this->dbh->quoteString($userdata['email']),
417 $this->dbh->quoteString((!empty($userdata['label'])?$userdata['label']:'')),
418 $this->owner,
419 $this->dbh->quoteString($alias) );
420
421 /* Do the insert */
422 $r = $this->dbh->simpleQuery($query);
423 if ($r == DB_OK) {
424 return true;
425 }
426
427 /* Fail */
428 return $this->set_error(sprintf(_("Database error: %s"),
429 DB::errorMessage($r)));
430 }
431 } /* End of class abook_database */
432
433 // vim: et ts=4
434 ?>