abook_local_file.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. <?php
  2. /**
  3. * abook_local_file.php
  4. *
  5. * @copyright &copy; 1999-2009 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. @chmod($this->filename, 0600);
  235. $this->unlock();
  236. $this->open(true);
  237. return true;
  238. }
  239. /* ========================== Public ======================== */
  240. /**
  241. * Search the file
  242. * @param string $expr search expression
  243. * @return array search results
  244. */
  245. function search($expr) {
  246. /* To be replaced by advanded search expression parsing */
  247. if(is_array($expr)) { return; }
  248. // don't allow wide search when listing is disabled.
  249. if ($expr=='*' && ! $this->listing)
  250. return array();
  251. /* Make regexp from glob'ed expression
  252. * May want to quote other special characters like (, ), -, [, ], etc. */
  253. $expr = str_replace('?', '.', $expr);
  254. $expr = str_replace('*', '.*', $expr);
  255. $res = array();
  256. if(!$this->open()) {
  257. return false;
  258. }
  259. @rewind($this->filehandle);
  260. while ($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  261. if (count($row)<5) {
  262. /**
  263. * address book is corrupted.
  264. */
  265. global $oTemplate;
  266. error_box(_("Address book is corrupted. Required fields are missing."));
  267. $oTemplate->display('footer.tpl');
  268. die();
  269. } else {
  270. $line = join(' ', $row);
  271. /**
  272. * TODO: regexp search is supported only in local_file backend.
  273. * Do we check format of regexp or ignore errors?
  274. */
  275. // errors on preg_match call are suppressed in order to prevent display of regexp compilation errors
  276. if(@preg_match('/' . $expr . '/i', $line)) {
  277. array_push($res, array('nickname' => $row[0],
  278. 'name' => $this->fullname($row[1], $row[2]),
  279. 'firstname' => $row[1],
  280. 'lastname' => $row[2],
  281. 'email' => $row[3],
  282. 'label' => $row[4],
  283. 'backend' => $this->bnum,
  284. 'source' => &$this->sname));
  285. }
  286. }
  287. }
  288. return $res;
  289. }
  290. /**
  291. * Lookup an address by the indicated field.
  292. *
  293. * @param string $value The value to look up
  294. * @param integer $field The field to look in, should be one
  295. * of the SM_ABOOK_FIELD_* constants
  296. * defined in include/constants.php
  297. * (OPTIONAL; defaults to nickname field)
  298. * NOTE: uniqueness is only guaranteed
  299. * when the nickname field is used here;
  300. * otherwise, the first matching address
  301. * is returned.
  302. *
  303. * @return array Array with lookup results when the value
  304. * was found, an empty array if the value was
  305. * not found.
  306. *
  307. */
  308. function lookup($value, $field=SM_ABOOK_FIELD_NICKNAME) {
  309. if(empty($value)) {
  310. return array();
  311. }
  312. $value = strtolower($value);
  313. $this->open();
  314. @rewind($this->filehandle);
  315. while ($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  316. if (count($row)<5) {
  317. /**
  318. * address book is corrupted.
  319. */
  320. global $oTemplate;
  321. error_box(_("Address book is corrupted. Required fields are missing."));
  322. $oTemplate->display('footer.tpl');
  323. die();
  324. } else {
  325. if(strtolower($row[$field]) == $value) {
  326. return array('nickname' => $row[0],
  327. 'name' => $this->fullname($row[1], $row[2]),
  328. 'firstname' => $row[1],
  329. 'lastname' => $row[2],
  330. 'email' => $row[3],
  331. 'label' => $row[4],
  332. 'backend' => $this->bnum,
  333. 'source' => &$this->sname);
  334. }
  335. }
  336. }
  337. return array();
  338. }
  339. /**
  340. * List all addresses
  341. * @return array list of all addresses
  342. */
  343. function list_addr() {
  344. $res = array();
  345. if(isset($this->listing) && !$this->listing) {
  346. return array();
  347. }
  348. $this->open();
  349. @rewind($this->filehandle);
  350. while ($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  351. if (count($row)<5) {
  352. /**
  353. * address book is corrupted. Don't be nice to people that
  354. * violate address book formating.
  355. */
  356. global $oTemplate;
  357. error_box(_("Address book is corrupted. Required fields are missing."));
  358. $oTemplate->display('footer.tpl');
  359. die();
  360. } else {
  361. array_push($res, array('nickname' => $row[0],
  362. 'name' => $this->fullname($row[1], $row[2]),
  363. 'firstname' => $row[1],
  364. 'lastname' => $row[2],
  365. 'email' => $row[3],
  366. 'label' => $row[4],
  367. 'backend' => $this->bnum,
  368. 'source' => &$this->sname));
  369. }
  370. }
  371. return $res;
  372. }
  373. /**
  374. * Add address
  375. * @param array $userdata new data
  376. * @return bool
  377. */
  378. function add($userdata) {
  379. if(!$this->writeable) {
  380. return $this->set_error(_("Address book is read-only"));
  381. }
  382. /* See if user exists already */
  383. $ret = $this->lookup($userdata['nickname']);
  384. if(!empty($ret)) {
  385. // i18n: don't use html formating in translation
  386. return $this->set_error(sprintf(_("User \"%s\" already exists"),$ret['nickname']));
  387. }
  388. /* Here is the data to write */
  389. $data = $this->quotevalue($userdata['nickname']) . '|' .
  390. $this->quotevalue($userdata['firstname']) . '|' .
  391. $this->quotevalue((!empty($userdata['lastname'])?$userdata['lastname']:'')) . '|' .
  392. $this->quotevalue($userdata['email']) . '|' .
  393. $this->quotevalue((!empty($userdata['label'])?$userdata['label']:''));
  394. /* Strip linefeeds */
  395. $nl_str = array("\r","\n");
  396. $data = str_replace($nl_str, ' ', $data);
  397. /**
  398. * Make sure that entry fits into allocated record space.
  399. * One byte is reserved for linefeed
  400. */
  401. if (strlen($data) >= $this->line_length) {
  402. return $this->set_error(_("Address book entry is too big"));
  403. }
  404. /* Add linefeed at end */
  405. $data = $data . "\n";
  406. /* Reopen file, just to be sure */
  407. $this->open(true);
  408. if(!$this->writeable) {
  409. return $this->set_error(_("Address book is read-only"));
  410. }
  411. /* Lock the file */
  412. if(!$this->lock()) {
  413. return $this->set_error(_("Could not lock datafile"));
  414. }
  415. /* Write */
  416. $r = sq_fwrite($this->filehandle, $data);
  417. /* Unlock file */
  418. $this->unlock();
  419. /* Test write result */
  420. if($r === FALSE) {
  421. /* Fail */
  422. $this->set_error(_("Write to address book failed"));
  423. return FALSE;
  424. }
  425. return TRUE;
  426. }
  427. /**
  428. * Delete address
  429. * @param string $alias alias that has to be deleted
  430. * @return bool
  431. */
  432. function remove($alias) {
  433. if(!$this->writeable) {
  434. return $this->set_error(_("Address book is read-only"));
  435. }
  436. /* Lock the file to make sure we're the only process working
  437. * on it. */
  438. if(!$this->lock()) {
  439. return $this->set_error(_("Could not lock datafile"));
  440. }
  441. /* Read file into memory, ignoring nicknames to delete */
  442. @rewind($this->filehandle);
  443. $i = 0;
  444. $rows = array();
  445. while($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  446. if(!in_array($row[0], $alias)) {
  447. $rows[$i++] = $row;
  448. }
  449. }
  450. /* Write data back */
  451. if(!$this->overwrite($rows)) {
  452. $this->unlock();
  453. return false;
  454. }
  455. $this->unlock();
  456. return true;
  457. }
  458. /**
  459. * Modify address
  460. * @param string $alias modified alias
  461. * @param array $userdata new data
  462. * @return bool true, if operation successful
  463. */
  464. function modify($alias, $userdata) {
  465. if(!$this->writeable) {
  466. return $this->set_error(_("Address book is read-only"));
  467. }
  468. /* See if user exists */
  469. $ret = $this->lookup($alias);
  470. if(empty($ret)) {
  471. // i18n: don't use html formating in translation
  472. return $this->set_error(sprintf(_("User \"%s\" does not exist"),$alias));
  473. }
  474. /* If the alias changed, see if the new alias exists */
  475. if (strtolower($alias) != strtolower($userdata['nickname'])) {
  476. $ret = $this->lookup($userdata['nickname']);
  477. if (!empty($ret)) {
  478. return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
  479. }
  480. }
  481. /* Lock the file to make sure we're the only process working
  482. * on it. */
  483. if(!$this->lock()) {
  484. return $this->set_error(_("Could not lock datafile"));
  485. }
  486. /* calculate userdata size */
  487. $data = $this->quotevalue($userdata['nickname']) . '|'
  488. . $this->quotevalue($userdata['firstname']) . '|'
  489. . $this->quotevalue((!empty($userdata['lastname'])?$userdata['lastname']:'')) . '|'
  490. . $this->quotevalue($userdata['email']) . '|'
  491. . $this->quotevalue((!empty($userdata['label'])?$userdata['label']:''));
  492. /* make sure that it fits into allocated space */
  493. if (strlen($data) >= $this->line_length) {
  494. return $this->set_error(_("Address book entry is too big"));
  495. }
  496. /* Read file into memory, modifying the data for the
  497. * user identified by $alias */
  498. $this->open(true);
  499. @rewind($this->filehandle);
  500. $i = 0;
  501. $rows = array();
  502. while($row = @fgetcsv($this->filehandle, $this->line_length, '|')) {
  503. if(strtolower($row[0]) != strtolower($alias)) {
  504. $rows[$i++] = $row;
  505. } else {
  506. $rows[$i++] = array(0 => $userdata['nickname'],
  507. 1 => $userdata['firstname'],
  508. 2 => (!empty($userdata['lastname'])?$userdata['lastname']:''),
  509. 3 => $userdata['email'],
  510. 4 => (!empty($userdata['label'])?$userdata['label']:''));
  511. }
  512. }
  513. /* Write data back */
  514. if(!$this->overwrite($rows)) {
  515. $this->unlock();
  516. return false;
  517. }
  518. $this->unlock();
  519. return true;
  520. }
  521. /**
  522. * Function for quoting values before saving
  523. * @param string $value string that has to be quoted
  524. * @param string quoted string
  525. */
  526. function quotevalue($value) {
  527. /* Quote the field if it contains | or ". Double quotes need to
  528. * be replaced with "" */
  529. if(stristr('"', $value) || stristr('|', $value)) {
  530. $value = '"' . str_replace('"', '""', $value) . '"';
  531. }
  532. return $value;
  533. }
  534. }