1 <?php
2
3 /*
4 * This file is part of the Icybee package.
5 *
6 * (c) Olivier Laviale <olivier.laviale@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Icybee\Modules\Files;
13
14 /**
15 * Representation of a managed file.
16 *
17 * @property-read string $extension The file extension. If any, the extension includes the dot,
18 * e.g. ".zip".
19 */
20 class File extends \Icybee\Modules\Nodes\Node
21 {
22 const PATH = 'path';
23 const MIME = 'mime';
24 const SIZE = 'size';
25 const DESCRIPTION = 'description';
26 const HTTP_FILE = 'file';
27
28 /**
29 * Path of the file, relative to the DOCUMENT_ROOT.
30 *
31 * @var string
32 */
33 public $path;
34
35 /**
36 * MIME type of the file.
37 *
38 * @var string
39 */
40 public $mime;
41
42 /**
43 * Size of the file.
44 *
45 * @var int
46 */
47 public $size;
48
49 /**
50 * Description of the file.
51 *
52 * @var string
53 */
54 public $description = '';
55
56 /**
57 * Defaults the model to "files".
58 */
59 public function __construct($model='files')
60 {
61 parent::__construct($model);
62 }
63
64 /**
65 * If {@link HTTP_FILE} is defined, the {@link \ICanBoogie\HTTP\File} instance is used to
66 * set the {@link $mime} and {@link $size} properties, as well as the {@link $title} property
67 * if it is empty.
68 *
69 * After the record is saved, the {@link HTTP_FILE} property is removed. Also, the
70 * {@link $path} property is updated.
71 */
72 public function save()
73 {
74 if (isset($this->{ self::HTTP_FILE }))
75 {
76 /* @var $file \ICanBoogie\HTTP\File */
77
78 $file = $this->{ self::HTTP_FILE };
79
80 $this->mime = $file->type;
81 $this->size = $file->size;
82
83 if (!$this->title)
84 {
85 $this->title = $file->unsuffixed_name;
86 }
87 }
88
89 $rc = parent::save();
90
91 unset($this->{ self::HTTP_FILE });
92
93 if ($rc)
94 {
95 $this->path = $this->model->select(self::PATH)->filter_by_nid($rc)->rc;
96 }
97
98 return $rc;
99 }
100
101 /**
102 * Returns the extension of the file.
103 *
104 * Note: The dot is included e.g. ".zip".
105 *
106 * @return string
107 */
108 protected function get_extension()
109 {
110 $extension = pathinfo($this->path, PATHINFO_EXTENSION);
111
112 if (!$extension)
113 {
114 return;
115 }
116
117 return '.' . $extension;
118 }
119
120 public function url($type='view')
121 {
122 if ($type == 'download')
123 {
124 return ($this->siteid ? $this->site->path : '') . '/api/' . $this->constructor . '/' . $this->nid . '/download';
125 }
126
127 return parent::url($type);
128 }
129 }