abook_local_file.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 && 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 alias
  291. * @param string $alias alias
  292. * @return array search results
  293. */
  294. function lookup($alias) {
  295. if(empty($alias)) {
  296. return array();
  297. }
  298. $alias = strtolower($alias);
  299. $this->open();
  300. @rewind($this->filehandle);
  301. while ($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  302. if (count($row)<5) {
  303. /**
  304. * address book is corrupted.
  305. */
  306. global $oTemplate;
  307. error_box(_("Address book is corrupted. Required fields are missing."));
  308. $oTemplate->display('footer.tpl');
  309. die();
  310. } else {
  311. if(strtolower($row[0]) == $alias) {
  312. return array('nickname' => $row[0],
  313. 'name' => $this->fullname($row[1], $row[2]),
  314. 'firstname' => $row[1],
  315. 'lastname' => $row[2],
  316. 'email' => $row[3],
  317. 'label' => $row[4],
  318. 'backend' => $this->bnum,
  319. 'source' => &$this->sname);
  320. }
  321. }
  322. }
  323. return array();
  324. }
  325. /**
  326. * List all addresses
  327. * @return array list of all addresses
  328. */
  329. function list_addr() {
  330. $res = array();
  331. if(isset($this->listing) && !$this->listing) {
  332. return array();
  333. }
  334. $this->open();
  335. @rewind($this->filehandle);
  336. while ($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  337. if (count($row)<5) {
  338. /**
  339. * address book is corrupted. Don't be nice to people that
  340. * violate address book formating.
  341. */
  342. global $oTemplate;
  343. error_box(_("Address book is corrupted. Required fields are missing."));
  344. $oTemplate->display('footer.tpl');
  345. die();
  346. } else {
  347. array_push($res, array('nickname' => $row[0],
  348. 'name' => $this->fullname($row[1], $row[2]),
  349. 'firstname' => $row[1],
  350. 'lastname' => $row[2],
  351. 'email' => $row[3],
  352. 'label' => $row[4],
  353. 'backend' => $this->bnum,
  354. 'source' => &$this->sname));
  355. }
  356. }
  357. return $res;
  358. }
  359. /**
  360. * Add address
  361. * @param array $userdata new data
  362. * @return bool
  363. */
  364. function add($userdata) {
  365. if(!$this->writeable) {
  366. return $this->set_error(_("Address book is read-only"));
  367. }
  368. /* See if user exists already */
  369. $ret = $this->lookup($userdata['nickname']);
  370. if(!empty($ret)) {
  371. // i18n: don't use html formating in translation
  372. return $this->set_error(sprintf(_("User \"%s\" already exists"),$ret['nickname']));
  373. }
  374. /* Here is the data to write */
  375. $data = $this->quotevalue($userdata['nickname']) . '|' .
  376. $this->quotevalue($userdata['firstname']) . '|' .
  377. $this->quotevalue((!empty($userdata['lastname'])?$userdata['lastname']:'')) . '|' .
  378. $this->quotevalue($userdata['email']) . '|' .
  379. $this->quotevalue((!empty($userdata['label'])?$userdata['label']:''));
  380. /* Strip linefeeds */
  381. $data = ereg_replace("[\r\n]", ' ', $data);
  382. /**
  383. * Make sure that entry fits into allocated record space.
  384. * One byte is reserved for linefeed
  385. */
  386. if (strlen($data) >= $this->line_length) {
  387. return $this->set_error(_("Address book entry is too big"));
  388. }
  389. /* Add linefeed at end */
  390. $data = $data . "\n";
  391. /* Reopen file, just to be sure */
  392. $this->open(true);
  393. if(!$this->writeable) {
  394. return $this->set_error(_("Address book is read-only"));
  395. }
  396. /* Lock the file */
  397. if(!$this->lock()) {
  398. return $this->set_error(_("Could not lock datafile"));
  399. }
  400. /* Write */
  401. $r = sq_fwrite($this->filehandle, $data);
  402. /* Unlock file */
  403. $this->unlock();
  404. /* Test write result */
  405. if($r === FALSE) {
  406. /* Fail */
  407. $this->set_error(_("Write to address book failed"));
  408. return FALSE;
  409. }
  410. return TRUE;
  411. }
  412. /**
  413. * Delete address
  414. * @param string $alias alias that has to be deleted
  415. * @return bool
  416. */
  417. function remove($alias) {
  418. if(!$this->writeable) {
  419. return $this->set_error(_("Address book is read-only"));
  420. }
  421. /* Lock the file to make sure we're the only process working
  422. * on it. */
  423. if(!$this->lock()) {
  424. return $this->set_error(_("Could not lock datafile"));
  425. }
  426. /* Read file into memory, ignoring nicknames to delete */
  427. @rewind($this->filehandle);
  428. $i = 0;
  429. $rows = array();
  430. while($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  431. if(!in_array($row[0], $alias)) {
  432. $rows[$i++] = $row;
  433. }
  434. }
  435. /* Write data back */
  436. if(!$this->overwrite($rows)) {
  437. $this->unlock();
  438. return false;
  439. }
  440. $this->unlock();
  441. return true;
  442. }
  443. /**
  444. * Modify address
  445. * @param string $alias modified alias
  446. * @param array $userdata new data
  447. * @return bool true, if operation successful
  448. */
  449. function modify($alias, $userdata) {
  450. if(!$this->writeable) {
  451. return $this->set_error(_("Address book is read-only"));
  452. }
  453. /* See if user exists */
  454. $ret = $this->lookup($alias);
  455. if(empty($ret)) {
  456. // i18n: don't use html formating in translation
  457. return $this->set_error(sprintf(_("User \"%s\" does not exist"),$alias));
  458. }
  459. /* If the alias changed, see if the new alias exists */
  460. if (strtolower($alias) != strtolower($userdata['nickname'])) {
  461. $ret = $this->lookup($userdata['nickname']);
  462. if (!empty($ret)) {
  463. return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
  464. }
  465. }
  466. /* Lock the file to make sure we're the only process working
  467. * on it. */
  468. if(!$this->lock()) {
  469. return $this->set_error(_("Could not lock datafile"));
  470. }
  471. /* calculate userdata size */
  472. $data = $this->quotevalue($userdata['nickname']) . '|'
  473. . $this->quotevalue($userdata['firstname']) . '|'
  474. . $this->quotevalue((!empty($userdata['lastname'])?$userdata['lastname']:'')) . '|'
  475. . $this->quotevalue($userdata['email']) . '|'
  476. . $this->quotevalue((!empty($userdata['label'])?$userdata['label']:''));
  477. /* make sure that it fits into allocated space */
  478. if (strlen($data) >= $this->line_length) {
  479. return $this->set_error(_("Address book entry is too big"));
  480. }
  481. /* Read file into memory, modifying the data for the
  482. * user identified by $alias */
  483. $this->open(true);
  484. @rewind($this->filehandle);
  485. $i = 0;
  486. $rows = array();
  487. while($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  488. if(strtolower($row[0]) != strtolower($alias)) {
  489. $rows[$i++] = $row;
  490. } else {
  491. $rows[$i++] = array(0 => $userdata['nickname'],
  492. 1 => $userdata['firstname'],
  493. 2 => (!empty($userdata['lastname'])?$userdata['lastname']:''),
  494. 3 => $userdata['email'],
  495. 4 => (!empty($userdata['label'])?$userdata['label']:''));
  496. }
  497. }
  498. /* Write data back */
  499. if(!$this->overwrite($rows)) {
  500. $this->unlock();
  501. return false;
  502. }
  503. $this->unlock();
  504. return true;
  505. }
  506. /**
  507. * Function for quoting values before saving
  508. * @param string $value string that has to be quoted
  509. * @param string quoted string
  510. */
  511. function quotevalue($value) {
  512. /* Quote the field if it contains | or ". Double quotes need to
  513. * be replaced with "" */
  514. if(ereg("[|\"]", $value)) {
  515. $value = '"' . str_replace('"', '""', $value) . '"';
  516. }
  517. return $value;
  518. }
  519. }