summaryrefslogtreecommitdiff
path: root/app/Model/File.php
blob: 16bf079e6cc233540da0247a3668f9e952eba203 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
<?php

namespace Model;

use Event\FileEvent;

/**
 * File model
 *
 * @package  model
 * @author   Frederic Guillot
 */
class File extends Base
{
    /**
     * SQL table name
     *
     * @var string
     */
    const TABLE = 'files';

    /**
     * Events
     *
     * @var string
     */
    const EVENT_CREATE = 'file.create';

    /**
     * Get a file by the id
     *
     * @access public
     * @param  integer   $file_id    File id
     * @return array
     */
    public function getById($file_id)
    {
        return $this->db->table(self::TABLE)->eq('id', $file_id)->findOne();
    }

    /**
     * Remove a file
     *
     * @access public
     * @param  integer   $file_id    File id
     * @return bool
     */
    public function remove($file_id)
    {
        $file = $this->getbyId($file_id);

        if (! empty($file) && @unlink(FILES_DIR.$file['path'])) {
            return $this->db->table(self::TABLE)->eq('id', $file_id)->remove();
        }

        return false;
    }

    /**
     * Remove all files for a given task
     *
     * @access public
     * @param  integer   $task_id    Task id
     * @return bool
     */
    public function removeAll($task_id)
    {
        $files = $this->getAll($task_id);

        foreach ($files as $file) {
            $this->remove($file['id']);
        }
    }

    /**
     * Create a file entry in the database
     *
     * @access public
     * @param  integer  $task_id    Task id
     * @param  string   $name       Filename
     * @param  string   $path       Path on the disk
     * @param  bool     $is_image   Image or not
     * @param  integer  $size       File size
     * @return bool
     */
    public function create($task_id, $name, $path, $is_image, $size)
    {
        $this->container['dispatcher']->dispatch(
            self::EVENT_CREATE,
            new FileEvent(array('task_id' => $task_id, 'name' => $name))
        );

        return $this->db->table(self::TABLE)->save(array(
            'task_id' => $task_id,
            'name' => substr($name, 0, 255),
            'path' => $path,
            'is_image' => $is_image ? '1' : '0',
            'size' => $size,
            'user_id' => $this->userSession->getId() ?: 0,
            'date' => time(),
        ));
    }

    /**
     * Get all files for a given task
     *
     * @access public
     * @param  integer   $task_id    Task id
     * @return array
     */
    public function getAll($task_id)
    {
        return $this->db
            ->table(self::TABLE)
            ->columns(
                self::TABLE.'.id',
                self::TABLE.'.name',
                self::TABLE.'.path',
                self::TABLE.'.is_image',
                self::TABLE.'.task_id',
                self::TABLE.'.date',
                self::TABLE.'.user_id',
                self::TABLE.'.size',
                User::TABLE.'.username',
                User::TABLE.'.name as user_name'
            )
            ->join(User::TABLE, 'id', 'user_id')
            ->eq('task_id', $task_id)
            ->asc(self::TABLE.'.name')
            ->findAll();
    }

    /**
     * Get all images for a given task
     *
     * @access public
     * @param  integer   $task_id    Task id
     * @return array
     */
    public function getAllImages($task_id)
    {
        return $this->db
            ->table(self::TABLE)
            ->columns(
                self::TABLE.'.id',
                self::TABLE.'.name',
                self::TABLE.'.path',
                self::TABLE.'.is_image',
                self::TABLE.'.task_id',
                self::TABLE.'.date',
                self::TABLE.'.user_id',
                self::TABLE.'.size',
                User::TABLE.'.username',
                User::TABLE.'.name as user_name'
            )
            ->join(User::TABLE, 'id', 'user_id')
            ->eq('task_id', $task_id)
            ->eq('is_image', 1)
            ->asc(self::TABLE.'.name')
            ->findAll();
    }

    /**
     * Get all files without images for a given task
     *
     * @access public
     * @param  integer   $task_id    Task id
     * @return array
     */
    public function getAllDocuments($task_id)
    {
        return $this->db
            ->table(self::TABLE)
            ->columns(
                self::TABLE.'.id',
                self::TABLE.'.name',
                self::TABLE.'.path',
                self::TABLE.'.is_image',
                self::TABLE.'.task_id',
                self::TABLE.'.date',
                self::TABLE.'.user_id',
                self::TABLE.'.size',
                User::TABLE.'.username',
                User::TABLE.'.name as user_name'
            )
            ->join(User::TABLE, 'id', 'user_id')
            ->eq('task_id', $task_id)
            ->eq('is_image', 0)
            ->asc(self::TABLE.'.name')
            ->findAll();
    }

    /**
     * Check if a filename is an image
     *
     * @access public
     * @param  string   $filename   Filename
     * @return bool
     */
    public function isImage($filename)
    {
        $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        switch ($extension) {
            case 'jpeg':
            case 'jpg':
            case 'png':
            case 'gif':
                return true;
        }

        return false;
    }

    /**
     * Generate the path for a new filename
     *
     * @access public
     * @param  integer   $project_id    Project id
     * @param  integer   $task_id       Task id
     * @param  string    $filename      Filename
     * @return string
     */
    public function generatePath($project_id, $task_id, $filename)
    {
        return $project_id.DIRECTORY_SEPARATOR.$task_id.DIRECTORY_SEPARATOR.hash('sha1', $filename.time());
    }

    /**
     * Check if the base directory is created correctly
     *
     * @access public
     */
    public function setup()
    {
        if (! is_dir(FILES_DIR)) {
            if (! mkdir(FILES_DIR, 0755, true)) {
                die('Unable to create the upload directory: "'.FILES_DIR.'"');
            }
        }

        if (! is_writable(FILES_DIR)) {
            die('The directory "'.FILES_DIR.'" must be writeable by your webserver user');
        }
    }

    /**
     * Handle file upload
     *
     * @access public
     * @param  integer  $project_id    Project id
     * @param  integer  $task_id       Task id
     * @param  string   $form_name     File form name
     * @return bool
     */
    public function upload($project_id, $task_id, $form_name)
    {
        $this->setup();
        $result = array();

        if (! empty($_FILES[$form_name])) {

            foreach ($_FILES[$form_name]['error'] as $key => $error) {

                if ($error == UPLOAD_ERR_OK && $_FILES[$form_name]['size'][$key] > 0) {

                    $original_filename = basename($_FILES[$form_name]['name'][$key]);
                    $uploaded_filename = $_FILES[$form_name]['tmp_name'][$key];
                    $destination_filename = $this->generatePath($project_id, $task_id, $original_filename);

                    @mkdir(FILES_DIR.dirname($destination_filename), 0755, true);

                    if (@move_uploaded_file($uploaded_filename, FILES_DIR.$destination_filename)) {

                        $result[] = $this->create(
                            $task_id,
                            $original_filename,
                            $destination_filename,
                            $this->isImage($original_filename),
                            $_FILES[$form_name]['size'][$key]
                        );
                    }
                }
            }
        }

        return count(array_unique($result)) === 1;
    }

    /**
     * Handle screenshot upload
     *
     * @access public
     * @param  integer  $project_id   Project id
     * @param  integer  $task_id      Task id
     * @param  string   $blob         Base64 encoded image
     * @return bool
     */
    public function uploadScreenshot($project_id, $task_id, $blob)
    {
        $data = base64_decode($blob);

        if (empty($data)) {
            return false;
        }

        $original_filename = e('Screenshot taken %s', dt('%B %e, %Y at %k:%M %p', time()));
        $destination_filename = $this->generatePath($project_id, $task_id, $original_filename);

        @mkdir(FILES_DIR.dirname($destination_filename), 0755, true);
        @file_put_contents(FILES_DIR.$destination_filename, $data);

        return $this->create(
            $task_id,
            $original_filename,
            $destination_filename,
            true,
            strlen($data)
        );
    }

    /**
     * Handle file upload (base64 encoded content)
     *
     * @access public
     * @param  integer  $project_id   Project id
     * @param  integer  $task_id      Task id
     * @param  string   $filename     Filename
     * @param  bool     $is_image     Is image file?
     * @param  string   $blob         Base64 encoded image
     * @return bool
     */
    public function uploadContent($project_id, $task_id, $filename, $is_image, &$blob)
    {
        $data = base64_decode($blob);

        if (empty($data)) {
            return false;
        }

        $destination_filename = $this->generatePath($project_id, $task_id, $filename);

        @mkdir(FILES_DIR.dirname($destination_filename), 0755, true);
        @file_put_contents(FILES_DIR.$destination_filename, $data);

        return $this->create(
            $task_id,
            $filename,
            $destination_filename,
            $is_image,
            strlen($data)
        );
    }

    /**
     * Generate a jpeg thumbnail from an image (output directly the image)
     *
     * @access public
     * @param  string    $filename         Source image
     * @param  integer   $resize_width     Desired image width
     * @param  integer   $resize_height    Desired image height
     */
    public function generateThumbnail($filename, $resize_width, $resize_height)
    {
        $metadata = getimagesize($filename);
        $src_width = $metadata[0];
        $src_height = $metadata[1];
        $dst_y = 0;
        $dst_x = 0;

        if (empty($metadata['mime'])) {
            return;
        }

        if ($resize_width == 0 && $resize_height == 0) {
            $resize_width = 100;
            $resize_height = 100;
        }

        if ($resize_width > 0 && $resize_height == 0) {
            $dst_width = $resize_width;
            $dst_height = floor($src_height * ($resize_width / $src_width));
            $dst_image = imagecreatetruecolor($dst_width, $dst_height);
        }
        elseif ($resize_width == 0 && $resize_height > 0) {
            $dst_width = floor($src_width * ($resize_height / $src_height));
            $dst_height = $resize_height;
            $dst_image = imagecreatetruecolor($dst_width, $dst_height);
        }
        else {

            $src_ratio = $src_width / $src_height;
            $resize_ratio = $resize_width / $resize_height;

            if ($src_ratio <= $resize_ratio) {
                $dst_width = $resize_width;
                $dst_height = floor($src_height * ($resize_width / $src_width));

                $dst_y = ($dst_height - $resize_height) / 2 * (-1);
            }
            else {
                $dst_width = floor($src_width * ($resize_height / $src_height));
                $dst_height = $resize_height;

                $dst_x = ($dst_width - $resize_width) / 2 * (-1);
            }

            $dst_image = imagecreatetruecolor($resize_width, $resize_height);
        }

        switch ($metadata['mime']) {
            case 'image/jpeg':
            case 'image/jpg':
                $src_image = imagecreatefromjpeg($filename);
                break;
            case 'image/png':
                $src_image = imagecreatefrompng($filename);
                break;
            case 'image/gif':
                $src_image = imagecreatefromgif($filename);
                break;
            default:
                return;
        }

        imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
        imagejpeg($dst_image);
    }
}