Passed
Push — master ( f35cc9...e819cb )
by Andreas
18:06
created

get_modify_filename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 9
ccs 8
cts 8
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author lukasz chalat
4
 * @package midcom.helper.imagepopup
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
/**
10
 * This handler get uploaded file and save it in database and write to file.
11
 *
12
 * @package midcom.helper.imagepopup
13
 */
14
class midcom_helper_imagepopup_handler_upload extends midcom_baseclasses_components_handler
15
{
16 2
    public function _handler_upload(array &$data, string $guid = null)
17
    {
18
        // Get the file
19 2
        reset($_FILES);
20 2
        $temp = array_shift($_FILES);
21
22 2
        if (is_uploaded_file($temp['tmp_name'])) {
23
            // Verify file extension
24
            if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), ["gif", "jpg", "png"])) {
0 ignored issues
show
Bug introduced by
It seems like pathinfo($temp['name'], PATHINFO_EXTENSION) can also be of type array; however, parameter $string of strtolower() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

24
            if (!in_array(strtolower(/** @scrutinizer ignore-type */ pathinfo($temp['name'], PATHINFO_EXTENSION)), ["gif", "jpg", "png"])) {
Loading history...
25
                throw new midcom_error('Invalid extension.');
26
            }
27
        }
28
29
        // Get the data
30 2
        $temp_name = $temp['tmp_name'];
31 2
        $mimetype = $temp['type'];
32 2
        $parentguid = $guid ?: $this->_topic->guid;
33
34
        // Set modified filename
35 2
        $filename = $this->get_modify_filename($temp['name']);
36
37
        // Insert the image into database
38 2
        $attachment = $this->insert_database($filename, $mimetype, $parentguid);
39
40 2
        $data['attachment'] = $attachment;
41
42
        // Get target to write the file
43 2
        $target = $this->get_data_from_database($filename, $parentguid);
44
45
        // Write the file
46 2
        $this->write_the_file($temp_name, $target);
47
48
        // Make a response for editor.uploadImages() function
49 2
        $location = midcom_db_attachment::get_url($attachment);
50
51 2
        $data['location'] = $location;
52
53
        // Return image location as JSON
54 2
        return new midcom_response_json(['location' => $location]);
55
    }
56
57 2
    private function get_modify_filename(string $filename) : string
58
    {
59 2
        $filename = midcom_db_attachment::safe_filename($filename);
60 2
        $pieces = explode('.', $filename);
61 2
        $core = array_shift($pieces);
62 2
        $split = preg_split("/-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})/", $core);
63 2
        $core = array_shift($split);
64 2
        $extension = array_pop($pieces);
65 2
        return $core . "-" . date('Y-m-d-H-i-s', time()) . "." . $extension;
66
    }
67
68 2
    private function get_data_from_database(string $filename, string $parentguid) : midcom_db_attachment
69
    {
70 2
        $query = midcom_db_attachment::new_query_builder();
71 2
        $query->add_constraint('name', '=', $filename);
72 2
        $query->add_constraint('parentguid', '=', $parentguid);
73 2
        $entry = $query->execute();
74
75 2
        if (empty($entry)) {
76
            throw new midcom_error_notfound("There is no match in database " . midcom_connection::get_error_string());
77
        }
78 2
        if (count($entry) == 1) {
79 2
            return $entry[0];
80
        }
81
        throw new midcom_error('There is more than just one object' . midcom_connection::get_error_string());
82
    }
83
84
    /**
85
     * @param string $tmp The temporary location of file
86
     * @param midcom_db_attachment $target The final destination for file
87
     */
88 2
    private function write_the_file(string $tmp, midcom_db_attachment $target)
89
    {
90 2
        $source = fopen($tmp, 'r');
91 2
        if (!$source) {
0 ignored issues
show
introduced by
$source is of type resource, thus it always evaluated to false.
Loading history...
92
            throw new midcom_error("Could not open file " . $tmp . " for reading.");
93
        }
94 2
        $stat = $target->copy_from_handle($source);
95 2
        fclose($source);
96 2
        if (!$stat) {
97
            throw new midcom_error('Failed to copy from handle: ' . midcom_connection::get_error_string());
98
        }
99 2
    }
100
101 2
    private function insert_database(string $filename, string $mimetype, string $parentguid) : midcom_db_attachment
102
    {
103 2
        $attachment = new midcom_db_attachment();
104 2
        $attachment->name = $filename;
105 2
        $attachment->title = $filename;
106 2
        $attachment->mimetype = $mimetype;
107 2
        $attachment->parentguid = $parentguid;
108 2
        if (!$attachment->create()) {
109
            throw new midcom_error('Failed to create derived image: ' . midcom_connection::get_error_string());
110
        }
111
112 2
        return $attachment;
113
    }
114
}
115