file_store.class.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. *
  4. * @copyright (c) 2012 University of Geneva
  5. * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
  6. * @author Laurent Opprecht <laurent@opprecht.info>
  7. */
  8. class FileStore
  9. {
  10. /**
  11. *
  12. * @param int $c_id
  13. * @param string $sub_path
  14. * @return FileStore
  15. */
  16. static function course($c_id, $sub_path = '')
  17. {
  18. $sys_path = api_get_path(SYS_COURSE_PATH);
  19. $course = api_get_course_info_by_id($c_id);
  20. $course_path = $course['path'];
  21. $path = $sys_path . $course_path . $sub_path;
  22. if (!is_dir($path)) {
  23. $mode = api_get_permissions_for_new_directories();
  24. $success = mkdir($path, $mode, true);
  25. if (!$success) {
  26. return false;
  27. }
  28. }
  29. return new self($path);
  30. }
  31. protected $root = '';
  32. public function __construct($root)
  33. {
  34. $root = ltrim($root, '/');
  35. $root .= '/';
  36. $this->root = $root;
  37. }
  38. public function root()
  39. {
  40. return $this->root;
  41. }
  42. function accept($filename)
  43. {
  44. return (bool) filter_extension($filename);
  45. }
  46. function add($path)
  47. {
  48. $root = $this->root();
  49. $id = $this->new_id();
  50. $new_path = "$root/$id";
  51. $success = @move_uploaded_file($path, $new_path);
  52. return $success ? $id : false;
  53. }
  54. function remove($path){
  55. $root = $this->root();
  56. $full_path = "$root/$path";
  57. if(is_file($full_path)){
  58. $result = unlink($full_path);
  59. return $result;
  60. }
  61. return false;
  62. }
  63. function get($id)
  64. {
  65. $root = $this->root();
  66. $result = "$root/$id";
  67. return $result;
  68. }
  69. function new_id()
  70. {
  71. $root = $this->root();
  72. $id = uniqid('');
  73. $path = "$root/$id";
  74. while (file_exists($path)) {
  75. $id = uniqid('');
  76. $path = "$root/$id";
  77. }
  78. return $id;
  79. }
  80. }