abook_local_file.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. <?php
  2. /**
  3. * abook_local_file.php
  4. *
  5. * @copyright &copy; 1999-2007 The SquirrelMail Project Team
  6. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  7. * @version $Id$
  8. * @package squirrelmail
  9. * @subpackage addressbook
  10. */
  11. /**
  12. * Backend for address book as a pipe separated file
  13. *
  14. * Stores the address book in a local file
  15. *
  16. * An array with the following elements must be passed to
  17. * the class constructor (elements marked ? are optional):
  18. *<pre>
  19. * filename => path to addressbook file
  20. * ? create => if true: file is created if it does not exist.
  21. * ? umask => umask set before opening file.
  22. * ? name => name of address book.
  23. * ? detect_writeable => detect address book access permissions by
  24. * checking file permissions.
  25. * ? writeable => allow writing into address book. Used only when
  26. * detect_writeable is set to false.
  27. * ? listing => enable/disable listing
  28. *</pre>
  29. * NOTE. This class should not be used directly. Use the
  30. * "AddressBook" class instead.
  31. * @package squirrelmail
  32. */
  33. class abook_local_file extends addressbook_backend {
  34. /**
  35. * Backend type
  36. * @var string
  37. */
  38. var $btype = 'local';
  39. /**
  40. * Backend name
  41. * @var string
  42. */
  43. var $bname = 'local_file';
  44. /**
  45. * File used to store data
  46. * @var string
  47. */
  48. var $filename = '';
  49. /**
  50. * File handle
  51. * @var object
  52. */
  53. var $filehandle = 0;
  54. /**
  55. * Create file, if it not present
  56. * @var bool
  57. */
  58. var $create = false;
  59. /**
  60. * Detect, if address book is writeable by checking file permisions
  61. * @var bool
  62. */
  63. var $detect_writeable = true;
  64. /**
  65. * Control write access to address book
  66. *
  67. * Option does not have any effect, if 'detect_writeable' is 'true'
  68. * @var bool
  69. */
  70. var $writeable = false;
  71. /**
  72. * controls listing of address book
  73. * @var bool
  74. */
  75. var $listing = true;
  76. /**
  77. * Umask of the file
  78. * @var string
  79. */
  80. var $umask;
  81. /**
  82. * Sets max entry size (number of bytes used for all address book fields
  83. * (including escapes) + 4 delimiters + 1 linefeed)
  84. * @var integer
  85. * @since 1.5.2
  86. */
  87. var $line_length = 2048;
  88. /* ========================== Private ======================= */
  89. /**
  90. * Constructor
  91. * @param array $param backend options
  92. * @return bool
  93. */
  94. function abook_local_file($param) {
  95. $this->sname = _("Personal Address Book");
  96. $this->umask = Umask();
  97. if(is_array($param)) {
  98. if(empty($param['filename'])) {
  99. return $this->set_error('Invalid parameters');
  100. }
  101. if(!is_string($param['filename'])) {
  102. return $this->set_error($param['filename'] . ': '.
  103. _("Not a file name"));
  104. }
  105. $this->filename = $param['filename'];
  106. if(isset($param['create'])) {
  107. $this->create = $param['create'];
  108. }
  109. if(isset($param['umask'])) {
  110. $this->umask = $param['umask'];
  111. }
  112. if(isset($param['name'])) {
  113. $this->sname = $param['name'];
  114. }
  115. if(isset($param['detect_writeable'])) {
  116. $this->detect_writeable = $param['detect_writeable'];
  117. }
  118. if(!empty($param['writeable'])) {
  119. $this->writeable = $param['writeable'];
  120. }
  121. if(isset($param['listing'])) {
  122. $this->listing = $param['listing'];
  123. }
  124. if(isset($param['line_length']) && ! empty($param['line_length'])) {
  125. $this->line_length = (int) $param['line_length'];
  126. }
  127. $this->open(true);
  128. } else {
  129. $this->set_error('Invalid argument to constructor');
  130. }
  131. }
  132. /**
  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
  136. * open, do nothing.
  137. * @param bool $new is file already opened
  138. * @return bool
  139. */
  140. function open($new = false) {
  141. $this->error = '';
  142. $file = $this->filename;
  143. $create = $this->create;
  144. $fopenmode = (($this->writeable && sq_is_writable($file)) ? 'a+' : 'r');
  145. /* Return true is file is open and $new is unset */
  146. if($this->filehandle && !$new) {
  147. return true;
  148. }
  149. /* Check that new file exitsts */
  150. if((!(file_exists($file) && is_readable($file))) && !$create) {
  151. return $this->set_error("$file: " . _("No such file or directory"));
  152. }
  153. /* Close old file, if any */
  154. if($this->filehandle) { $this->close(); }
  155. umask($this->umask);
  156. if (! $this->detect_writeable) {
  157. $fh = @fopen($file,$fopenmode);
  158. if ($fh) {
  159. $this->filehandle = &$fh;
  160. $this->filename = $file;
  161. } else {
  162. return $this->set_error("$file: " . _("Open failed"));
  163. }
  164. } else {
  165. /* Open file. First try to open for reading and writing,
  166. * but fall back to read only. */
  167. $fh = @fopen($file, 'a+');
  168. if($fh) {
  169. $this->filehandle = &$fh;
  170. $this->filename = $file;
  171. $this->writeable = true;
  172. } else {
  173. $fh = @fopen($file, 'r');
  174. if($fh) {
  175. $this->filehandle = &$fh;
  176. $this->filename = $file;
  177. $this->writeable = false;
  178. } else {
  179. return $this->set_error("$file: " . _("Open failed"));
  180. }
  181. }
  182. }
  183. return true;
  184. }
  185. /** Close the file and forget the filehandle */
  186. function close() {
  187. @fclose($this->filehandle);
  188. $this->filehandle = 0;
  189. $this->filename = '';
  190. $this->writable = false;
  191. }
  192. /** Lock the datafile - try 20 times in 5 seconds */
  193. function lock() {
  194. for($i = 0 ; $i < 20 ; $i++) {
  195. if(flock($this->filehandle, 2 + 4))
  196. return true;
  197. else
  198. usleep(250000);
  199. }
  200. return false;
  201. }
  202. /** Unlock the datafile */
  203. function unlock() {
  204. return flock($this->filehandle, 3);
  205. }
  206. /**
  207. * Overwrite the file with data from $rows
  208. * NOTE! Previous locks are broken by this function
  209. * @param array $rows new data
  210. * @return bool
  211. */
  212. function overwrite(&$rows) {
  213. $this->unlock();
  214. $newfh = @fopen($this->filename.'.tmp', 'w');
  215. if(!$newfh) {
  216. return $this->set_error($this->filename. '.tmp:' . _("Open failed"));
  217. }
  218. for($i = 0, $cnt=sizeof($rows) ; $i < $cnt ; $i++) {
  219. if(is_array($rows[$i])) {
  220. for($j = 0, $cnt_part=count($rows[$i]) ; $j < $cnt_part ; $j++) {
  221. $rows[$i][$j] = $this->quotevalue($rows[$i][$j]);
  222. }
  223. $tmpwrite = sq_fwrite($newfh, join('|', $rows[$i]) . "\n");
  224. if ($tmpwrite === FALSE) {
  225. return $this->set_error($this->filename . '.tmp:' . _("Write failed"));
  226. }
  227. }
  228. }
  229. fclose($newfh);
  230. if (!@copy($this->filename . '.tmp' , $this->filename)) {
  231. return $this->set_error($this->filename . ':' . _("Unable to update"));
  232. }
  233. @unlink($this->filename . '.tmp');
  234. $this->unlock();
  235. $this->open(true);
  236. return true;
  237. }
  238. /* ========================== Public ======================== */
  239. /**
  240. * Search the file
  241. * @param string $expr search expression
  242. * @return array search results
  243. */
  244. function search($expr) {
  245. /* To be replaced by advanded search expression parsing */
  246. if(is_array($expr)) { return; }
  247. // don't allow wide search when listing is disabled.
  248. if ($expr=='*' && ! $this->listing)
  249. return array();
  250. /* Make regexp from glob'ed expression
  251. * May want to quote other special characters like (, ), -, [, ], etc. */
  252. $expr = str_replace('?', '.', $expr);
  253. $expr = str_replace('*', '.*', $expr);
  254. $res = array();
  255. if(!$this->open()) {
  256. return false;
  257. }
  258. @rewind($this->filehandle);
  259. while ($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  260. if (count($row)<5) {
  261. /**
  262. * address book is corrupted.
  263. */
  264. global $oTemplate;
  265. error_box(_("Address book is corrupted. Required fields are missing."));
  266. $oTemplate->display('footer.tpl');
  267. die();
  268. } else {
  269. $line = join(' ', $row);
  270. /**
  271. * TODO: regexp search is supported only in local_file backend.
  272. * Do we check format of regexp or ignore errors?
  273. */
  274. // errors on eregi call are suppressed in order to prevent display of regexp compilation errors
  275. if(@eregi($expr, $line)) {
  276. array_push($res, array('nickname' => $row[0],
  277. 'name' => $this->fullname($row[1], $row[2]),
  278. 'firstname' => $row[1],
  279. 'lastname' => $row[2],
  280. 'email' => $row[3],
  281. 'label' => $row[4],
  282. 'backend' => $this->bnum,
  283. 'source' => &$this->sname));
  284. }
  285. }
  286. }
  287. return $res;
  288. }
  289. /**
  290. * Lookup an address by the indicated field.
  291. *
  292. * @param string $value The value to look up
  293. * @param integer $field The field to look in, should be one
  294. * of the SM_ABOOK_FIELD_* constants
  295. * defined in include/constants.php
  296. * (OPTIONAL; defaults to nickname field)
  297. * NOTE: uniqueness is only guaranteed
  298. * when the nickname field is used here;
  299. * otherwise, the first matching address
  300. * is returned.
  301. *
  302. * @return array Array with lookup results when the value
  303. * was found, an empty array if the value was
  304. * not found.
  305. *
  306. */
  307. function lookup($value, $field=SM_ABOOK_FIELD_NICKNAME) {
  308. if(empty($value)) {
  309. return array();
  310. }
  311. $value = strtolower($value);
  312. $this->open();
  313. @rewind($this->filehandle);
  314. while ($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  315. if (count($row)<5) {
  316. /**
  317. * address book is corrupted.
  318. */
  319. global $oTemplate;
  320. error_box(_("Address book is corrupted. Required fields are missing."));
  321. $oTemplate->display('footer.tpl');
  322. die();
  323. } else {
  324. if(strtolower($row[$field]) == $value) {
  325. return array('nickname' => $row[0],
  326. 'name' => $this->fullname($row[1], $row[2]),
  327. 'firstname' => $row[1],
  328. 'lastname' => $row[2],
  329. 'email' => $row[3],
  330. 'label' => $row[4],
  331. 'backend' => $this->bnum,
  332. 'source' => &$this->sname);
  333. }
  334. }
  335. }
  336. return array();
  337. }
  338. /**
  339. * List all addresses
  340. * @return array list of all addresses
  341. */
  342. function list_addr() {
  343. $res = array();
  344. if(isset($this->listing) && !$this->listing) {
  345. return array();
  346. }
  347. $this->open();
  348. @rewind($this->filehandle);
  349. while ($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  350. if (count($row)<5) {
  351. /**
  352. * address book is corrupted. Don't be nice to people that
  353. * violate address book formating.
  354. */
  355. global $oTemplate;
  356. error_box(_("Address book is corrupted. Required fields are missing."));
  357. $oTemplate->display('footer.tpl');
  358. die();
  359. } else {
  360. array_push($res, array('nickname' => $row[0],
  361. 'name' => $this->fullname($row[1], $row[2]),
  362. 'firstname' => $row[1],
  363. 'lastname' => $row[2],
  364. 'email' => $row[3],
  365. 'label' => $row[4],
  366. 'backend' => $this->bnum,
  367. 'source' => &$this->sname));
  368. }
  369. }
  370. return $res;
  371. }
  372. /**
  373. * Add address
  374. * @param array $userdata new data
  375. * @return bool
  376. */
  377. function add($userdata) {
  378. if(!$this->writeable) {
  379. return $this->set_error(_("Address book is read-only"));
  380. }
  381. /* See if user exists already */
  382. $ret = $this->lookup($userdata['nickname']);
  383. if(!empty($ret)) {
  384. // i18n: don't use html formating in translation
  385. return $this->set_error(sprintf(_("User \"%s\" already exists"),$ret['nickname']));
  386. }
  387. /* Here is the data to write */
  388. $data = $this->quotevalue($userdata['nickname']) . '|' .
  389. $this->quotevalue($userdata['firstname']) . '|' .
  390. $this->quotevalue((!empty($userdata['lastname'])?$userdata['lastname']:'')) . '|' .
  391. $this->quotevalue($userdata['email']) . '|' .
  392. $this->quotevalue((!empty($userdata['label'])?$userdata['label']:''));
  393. /* Strip linefeeds */
  394. $data = ereg_replace("[\r\n]", ' ', $data);
  395. /**
  396. * Make sure that entry fits into allocated record space.
  397. * One byte is reserved for linefeed
  398. */
  399. if (strlen($data) >= $this->line_length) {
  400. return $this->set_error(_("Address book entry is too big"));
  401. }
  402. /* Add linefeed at end */
  403. $data = $data . "\n";
  404. /* Reopen file, just to be sure */
  405. $this->open(true);
  406. if(!$this->writeable) {
  407. return $this->set_error(_("Address book is read-only"));
  408. }
  409. /* Lock the file */
  410. if(!$this->lock()) {
  411. return $this->set_error(_("Could not lock datafile"));
  412. }
  413. /* Write */
  414. $r = sq_fwrite($this->filehandle, $data);
  415. /* Unlock file */
  416. $this->unlock();
  417. /* Test write result */
  418. if($r === FALSE) {
  419. /* Fail */
  420. $this->set_error(_("Write to address book failed"));
  421. return FALSE;
  422. }
  423. return TRUE;
  424. }
  425. /**
  426. * Delete address
  427. * @param string $alias alias that has to be deleted
  428. * @return bool
  429. */
  430. function remove($alias) {
  431. if(!$this->writeable) {
  432. return $this->set_error(_("Address book is read-only"));
  433. }
  434. /* Lock the file to make sure we're the only process working
  435. * on it. */
  436. if(!$this->lock()) {
  437. return $this->set_error(_("Could not lock datafile"));
  438. }
  439. /* Read file into memory, ignoring nicknames to delete */
  440. @rewind($this->filehandle);
  441. $i = 0;
  442. $rows = array();
  443. while($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  444. if(!in_array($row[0], $alias)) {
  445. $rows[$i++] = $row;
  446. }
  447. }
  448. /* Write data back */
  449. if(!$this->overwrite($rows)) {
  450. $this->unlock();
  451. return false;
  452. }
  453. $this->unlock();
  454. return true;
  455. }
  456. /**
  457. * Modify address
  458. * @param string $alias modified alias
  459. * @param array $userdata new data
  460. * @return bool true, if operation successful
  461. */
  462. function modify($alias, $userdata) {
  463. if(!$this->writeable) {
  464. return $this->set_error(_("Address book is read-only"));
  465. }
  466. /* See if user exists */
  467. $ret = $this->lookup($alias);
  468. if(empty($ret)) {
  469. // i18n: don't use html formating in translation
  470. return $this->set_error(sprintf(_("User \"%s\" does not exist"),$alias));
  471. }
  472. /* If the alias changed, see if the new alias exists */
  473. if (strtolower($alias) != strtolower($userdata['nickname'])) {
  474. $ret = $this->lookup($userdata['nickname']);
  475. if (!empty($ret)) {
  476. return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
  477. }
  478. }
  479. /* Lock the file to make sure we're the only process working
  480. * on it. */
  481. if(!$this->lock()) {
  482. return $this->set_error(_("Could not lock datafile"));
  483. }
  484. /* calculate userdata size */
  485. $data = $this->quotevalue($userdata['nickname']) . '|'
  486. . $this->quotevalue($userdata['firstname']) . '|'
  487. . $this->quotevalue((!empty($userdata['lastname'])?$userdata['lastname']:'')) . '|'
  488. . $this->quotevalue($userdata['email']) . '|'
  489. . $this->quotevalue((!empty($userdata['label'])?$userdata['label']:''));
  490. /* make sure that it fits into allocated space */
  491. if (strlen($data) >= $this->line_length) {
  492. return $this->set_error(_("Address book entry is too big"));
  493. }
  494. /* Read file into memory, modifying the data for the
  495. * user identified by $alias */
  496. $this->open(true);
  497. @rewind($this->filehandle);
  498. $i = 0;
  499. $rows = array();
  500. while($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  501. if(strtolower($row[0]) != strtolower($alias)) {
  502. $rows[$i++] = $row;
  503. } else {
  504. $rows[$i++] = array(0 => $userdata['nickname'],
  505. 1 => $userdata['firstname'],
  506. 2 => (!empty($userdata['lastname'])?$userdata['lastname']:''),
  507. 3 => $userdata['email'],
  508. 4 => (!empty($userdata['label'])?$userdata['label']:''));
  509. }
  510. }
  511. /* Write data back */
  512. if(!$this->overwrite($rows)) {
  513. $this->unlock();
  514. return false;
  515. }
  516. $this->unlock();
  517. return true;
  518. }
  519. /**
  520. * Function for quoting values before saving
  521. * @param string $value string that has to be quoted
  522. * @param string quoted string
  523. */
  524. function quotevalue($value) {
  525. /* Quote the field if it contains | or ". Double quotes need to
  526. * be replaced with "" */
  527. if(ereg("[|\"]", $value)) {
  528. $value = '"' . str_replace('"', '""', $value) . '"';
  529. }
  530. return $value;
  531. }
  532. }