Filesystem.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. <?php
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 1.1.1
  11. */
  12. namespace PrivateBin\Data;
  13. use PrivateBin\Json;
  14. use PrivateBin\Model\Paste;
  15. /**
  16. * Filesystem
  17. *
  18. * Model for filesystem data access, implemented as a singleton.
  19. */
  20. class Filesystem extends AbstractData
  21. {
  22. /**
  23. * First line in JSON files, to hide contents
  24. *
  25. * @const string
  26. */
  27. const PROTECTION_LINE = '<?php http_response_code(403); /*' . PHP_EOL;
  28. /**
  29. * directory where data is stored
  30. *
  31. * @access private
  32. * @static
  33. * @var string
  34. */
  35. private static $_dir = 'data/';
  36. /**
  37. * get instance of singleton
  38. *
  39. * @access public
  40. * @static
  41. * @param array $options
  42. * @return Filesystem
  43. */
  44. public static function getInstance($options = null)
  45. {
  46. // if given update the data directory
  47. if (
  48. is_array($options) &&
  49. array_key_exists('dir', $options)
  50. ) {
  51. self::$_dir = $options['dir'] . DIRECTORY_SEPARATOR;
  52. }
  53. // if needed initialize the singleton
  54. if (!(self::$_instance instanceof self)) {
  55. self::$_instance = new self;
  56. self::_init();
  57. }
  58. return self::$_instance;
  59. }
  60. /**
  61. * Create a paste.
  62. *
  63. * @access public
  64. * @param string $pasteid
  65. * @param array $paste
  66. * @throws Exception
  67. * @return bool
  68. */
  69. public function create($pasteid, $paste)
  70. {
  71. $storagedir = self::_dataid2path($pasteid);
  72. if (is_file($storagedir . $pasteid . '.php')) {
  73. return false;
  74. }
  75. if (!is_dir($storagedir)) {
  76. mkdir($storagedir, 0700, true);
  77. }
  78. return (bool) file_put_contents($storagedir . $pasteid . '.php', self::PROTECTION_LINE . Json::encode($paste));
  79. }
  80. /**
  81. * Read a paste.
  82. *
  83. * @access public
  84. * @param string $pasteid
  85. * @return stdClass|false
  86. */
  87. public function read($pasteid)
  88. {
  89. if (!$this->exists($pasteid)) {
  90. return false;
  91. }
  92. $paste = self::_decodeFile(self::_dataid2path($pasteid) . $pasteid . '.php');
  93. if (property_exists($paste->meta, 'attachment')) {
  94. $paste->attachment = $paste->meta->attachment;
  95. unset($paste->meta->attachment);
  96. if (property_exists($paste->meta, 'attachmentname')) {
  97. $paste->attachmentname = $paste->meta->attachmentname;
  98. unset($paste->meta->attachmentname);
  99. }
  100. }
  101. return $paste;
  102. }
  103. /**
  104. * Delete a paste and its discussion.
  105. *
  106. * @access public
  107. * @param string $pasteid
  108. * @return void
  109. */
  110. public function delete($pasteid)
  111. {
  112. $pastedir = self::_dataid2path($pasteid);
  113. if (is_dir($pastedir)) {
  114. // Delete the paste itself.
  115. if (is_file($pastedir . $pasteid . '.php')) {
  116. unlink($pastedir . $pasteid . '.php');
  117. }
  118. // Delete discussion if it exists.
  119. $discdir = self::_dataid2discussionpath($pasteid);
  120. if (is_dir($discdir)) {
  121. // Delete all files in discussion directory
  122. $dir = dir($discdir);
  123. while (false !== ($filename = $dir->read())) {
  124. if (is_file($discdir . $filename)) {
  125. unlink($discdir . $filename);
  126. }
  127. }
  128. $dir->close();
  129. rmdir($discdir);
  130. }
  131. }
  132. }
  133. /**
  134. * Test if a paste exists.
  135. *
  136. * @access public
  137. * @param string $pasteid
  138. * @return bool
  139. */
  140. public function exists($pasteid)
  141. {
  142. $basePath = self::_dataid2path($pasteid) . $pasteid;
  143. $pastePath = $basePath . '.php';
  144. // convert to PHP protected files if needed
  145. if (is_readable($basePath)) {
  146. $context = stream_context_create();
  147. // don't overwrite already converted file
  148. if (!is_file($pastePath)) {
  149. $handle = fopen($basePath, 'r', false, $context);
  150. file_put_contents($pastePath, self::PROTECTION_LINE);
  151. file_put_contents($pastePath, $handle, FILE_APPEND);
  152. fclose($handle);
  153. }
  154. unlink($basePath);
  155. // convert comments, too
  156. $discdir = self::_dataid2discussionpath($pasteid);
  157. if (is_dir($discdir)) {
  158. $dir = dir($discdir);
  159. while (false !== ($filename = $dir->read())) {
  160. if (substr($filename, -4) !== '.php' && strlen($filename) >= 16) {
  161. $commentFilename = $discdir . $filename . '.php';
  162. // don't overwrite already converted file
  163. if (!is_file($commentFilename)) {
  164. $handle = fopen($discdir . $filename, 'r', false, $context);
  165. file_put_contents($commentFilename, self::PROTECTION_LINE);
  166. file_put_contents($commentFilename, $handle, FILE_APPEND);
  167. fclose($handle);
  168. }
  169. unlink($discdir . $filename);
  170. }
  171. }
  172. $dir->close();
  173. }
  174. }
  175. return is_readable($pastePath);
  176. }
  177. /**
  178. * Create a comment in a paste.
  179. *
  180. * @access public
  181. * @param string $pasteid
  182. * @param string $parentid
  183. * @param string $commentid
  184. * @param array $comment
  185. * @throws Exception
  186. * @return bool
  187. */
  188. public function createComment($pasteid, $parentid, $commentid, $comment)
  189. {
  190. $storagedir = self::_dataid2discussionpath($pasteid);
  191. $filename = $pasteid . '.' . $commentid . '.' . $parentid . '.php';
  192. if (is_file($storagedir . $filename)) {
  193. return false;
  194. }
  195. if (!is_dir($storagedir)) {
  196. mkdir($storagedir, 0700, true);
  197. }
  198. return (bool) file_put_contents($storagedir . $filename, self::PROTECTION_LINE . Json::encode($comment));
  199. }
  200. /**
  201. * Read all comments of paste.
  202. *
  203. * @access public
  204. * @param string $pasteid
  205. * @return array
  206. */
  207. public function readComments($pasteid)
  208. {
  209. $comments = array();
  210. $discdir = self::_dataid2discussionpath($pasteid);
  211. if (is_dir($discdir)) {
  212. $dir = dir($discdir);
  213. while (false !== ($filename = $dir->read())) {
  214. // Filename is in the form pasteid.commentid.parentid.php:
  215. // - pasteid is the paste this reply belongs to.
  216. // - commentid is the comment identifier itself.
  217. // - parentid is the comment this comment replies to (It can be pasteid)
  218. if (is_file($discdir . $filename)) {
  219. $comment = self::_decodeFile($discdir . $filename);
  220. $items = explode('.', $filename);
  221. // Add some meta information not contained in file.
  222. $comment->id = $items[1];
  223. $comment->parentid = $items[2];
  224. // Store in array
  225. $key = $this->getOpenSlot($comments, (int) $comment->meta->postdate);
  226. $comments[$key] = $comment;
  227. }
  228. }
  229. $dir->close();
  230. // Sort comments by date, oldest first.
  231. ksort($comments);
  232. }
  233. return $comments;
  234. }
  235. /**
  236. * Test if a comment exists.
  237. *
  238. * @access public
  239. * @param string $pasteid
  240. * @param string $parentid
  241. * @param string $commentid
  242. * @return bool
  243. */
  244. public function existsComment($pasteid, $parentid, $commentid)
  245. {
  246. return is_file(
  247. self::_dataid2discussionpath($pasteid) .
  248. $pasteid . '.' . $commentid . '.' . $parentid . '.php'
  249. );
  250. }
  251. /**
  252. * Returns up to batch size number of paste ids that have expired
  253. *
  254. * @access private
  255. * @param int $batchsize
  256. * @return array
  257. */
  258. protected function _getExpiredPastes($batchsize)
  259. {
  260. $pastes = array();
  261. $firstLevel = array_filter(
  262. scandir(self::$_dir),
  263. 'self::_isFirstLevelDir'
  264. );
  265. if (count($firstLevel) > 0) {
  266. // try at most 10 times the $batchsize pastes before giving up
  267. for ($i = 0, $max = $batchsize * 10; $i < $max; ++$i) {
  268. $firstKey = array_rand($firstLevel);
  269. $secondLevel = array_filter(
  270. scandir(self::$_dir . $firstLevel[$firstKey]),
  271. 'self::_isSecondLevelDir'
  272. );
  273. // skip this folder in the next checks if it is empty
  274. if (count($secondLevel) == 0) {
  275. unset($firstLevel[$firstKey]);
  276. continue;
  277. }
  278. $secondKey = array_rand($secondLevel);
  279. $path = self::$_dir . $firstLevel[$firstKey] .
  280. DIRECTORY_SEPARATOR . $secondLevel[$secondKey];
  281. if (!is_dir($path)) {
  282. continue;
  283. }
  284. $thirdLevel = array_filter(
  285. array_map(
  286. function($filename) {
  287. return strlen($filename) >= 20 ?
  288. substr($filename, 0, -4) :
  289. $filename;
  290. },
  291. scandir($path)
  292. ),
  293. 'PrivateBin\\Model\\Paste::isValidId'
  294. );
  295. if (count($thirdLevel) == 0) {
  296. continue;
  297. }
  298. $thirdKey = array_rand($thirdLevel);
  299. $pasteid = $thirdLevel[$thirdKey];
  300. if (in_array($pasteid, $pastes)) {
  301. continue;
  302. }
  303. if ($this->exists($pasteid)) {
  304. $data = $this->read($pasteid);
  305. if (
  306. property_exists($data->meta, 'expire_date') &&
  307. $data->meta->expire_date < time()
  308. ) {
  309. $pastes[] = $pasteid;
  310. if (count($pastes) >= $batchsize) {
  311. break;
  312. }
  313. }
  314. }
  315. }
  316. }
  317. return $pastes;
  318. }
  319. /**
  320. * initialize privatebin
  321. *
  322. * @access private
  323. * @static
  324. * @return void
  325. */
  326. private static function _init()
  327. {
  328. // Create storage directory if it does not exist.
  329. if (!is_dir(self::$_dir)) {
  330. mkdir(self::$_dir, 0700);
  331. }
  332. // Create .htaccess file if it does not exist.
  333. if (!is_file(self::$_dir . '.htaccess')) {
  334. file_put_contents(
  335. self::$_dir . '.htaccess',
  336. 'Allow from none' . PHP_EOL .
  337. 'Deny from all' . PHP_EOL
  338. );
  339. }
  340. }
  341. /**
  342. * Convert paste id to storage path.
  343. *
  344. * The idea is to creates subdirectories in order to limit the number of files per directory.
  345. * (A high number of files in a single directory can slow things down.)
  346. * eg. "f468483c313401e8" will be stored in "data/f4/68/f468483c313401e8"
  347. * High-trafic websites may want to deepen the directory structure (like Squid does).
  348. *
  349. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/'
  350. *
  351. * @access private
  352. * @static
  353. * @param string $dataid
  354. * @return string
  355. */
  356. private static function _dataid2path($dataid)
  357. {
  358. return self::$_dir . substr($dataid, 0, 2) . DIRECTORY_SEPARATOR .
  359. substr($dataid, 2, 2) . DIRECTORY_SEPARATOR;
  360. }
  361. /**
  362. * Convert paste id to discussion storage path.
  363. *
  364. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/e3570978f9e4aa90.discussion/'
  365. *
  366. * @access private
  367. * @static
  368. * @param string $dataid
  369. * @return string
  370. */
  371. private static function _dataid2discussionpath($dataid)
  372. {
  373. return self::_dataid2path($dataid) . $dataid .
  374. '.discussion' . DIRECTORY_SEPARATOR;
  375. }
  376. /**
  377. * Check that the given element is a valid first level directory.
  378. *
  379. * @access private
  380. * @static
  381. * @param string $element
  382. * @return bool
  383. */
  384. private static function _isFirstLevelDir($element)
  385. {
  386. return self::_isSecondLevelDir($element) &&
  387. is_dir(self::$_dir . DIRECTORY_SEPARATOR . $element);
  388. }
  389. /**
  390. * Check that the given element is a valid second level directory.
  391. *
  392. * @access private
  393. * @static
  394. * @param string $element
  395. * @return bool
  396. */
  397. private static function _isSecondLevelDir($element)
  398. {
  399. return (bool) preg_match('/^[a-f0-9]{2}$/', $element);
  400. }
  401. /**
  402. * Decodes a paste or comment file.
  403. *
  404. * @access private
  405. * @static
  406. * @param string $file
  407. * @return array
  408. */
  409. private static function _decodeFile($file)
  410. {
  411. return json_decode(substr(file_get_contents($file), strlen(self::PROTECTION_LINE)));
  412. }
  413. }