Passed
Push — master ( 4d005d...179526 )
by Andreas
24:40
created

midcom_db_attachment::copy_from_handle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 5
cts 6
cp 0.8333
crap 2.0185
rs 10
1
<?php
2
/**
3
 * @package midcom.db
4
 * @author The Midgard Project, http://www.midgard-project.org
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
use midgard\portable\api\blob;
10
11
/**
12
 * MidCOM level replacement for the Midgard Attachment record with framework support.
13
 *
14
 * @property string $name Filename of the attachment
15
 * @property string $title Title of the attachment
16
 * @property string $location Location of the attachment in the blob directory structure
17
 * @property string $mimetype MIME type of the attachment
18
 * @property string $parentguid GUID of the object the attachment is attached to
19
 * @package midcom.db
20
 */
21
class midcom_db_attachment extends midcom_core_dbaobject
22
{
23
    public string $__midcom_class_name__ = __CLASS__;
24
    public string $__mgdschema_class_name__ = 'midgard_attachment';
25
26
    public bool $_use_rcs = false;
27
28
    /**
29
     * Internal tracking state variable, holds the file handle of any open
30
     * attachment.
31
     *
32
     * @var resource
33
     */
34
    private $_open_handle;
35
36
    /**
37
     * Internal tracking state variable, true if the attachment has a handle opened in write mode
38
     */
39
    private bool $_open_write_mode = false;
40
41
    /**
42
     * Opens the attachment for file IO.
43
     *
44
     * Returns a filehandle that can be used with the usual PHP file functions if successful,
45
     * the handle has to be closed with the close() method when you no longer need it, don't
46
     * let it fall over the end of the script.
47
     *
48
     * <b>Important Note:</b> It is important to use the close() member function of
49
     * this class to close the file handle, not just fclose(). Otherwise, the upgrade
50
     * notification switches will fail.
51
     *
52
     * @param string $mode The mode which should be used to open the attachment, same as
53
     *     the mode parameter of the PHP fopen call. This defaults to write access.
54
     * @return resource|false A file handle to the attachment if successful, false on failure.
55
     */
56 18
    public function open(string $mode = 'w')
57
    {
58 18
        if (!$this->id) {
59
            debug_add('Cannot open a non-persistent attachment.', MIDCOM_LOG_WARN);
60
            debug_print_r('Object state:', $this);
61
            return false;
62
        }
63
64 18
        if ($this->_open_handle !== null) {
65
            debug_add("Warning, the attachment {$this->id} already had an open file handle, we close it implicitly.", MIDCOM_LOG_WARN);
66
            $this->close();
67
        }
68
69 18
        $blob = new blob($this->__object);
70 18
        $handle = $blob->get_handler($mode);
71
72 18
        if (!$handle) {
0 ignored issues
show
introduced by
$handle is of type resource, thus it always evaluated to false.
Loading history...
73
            debug_add("Failed to open attachment with mode {$mode}, last PHP error was: ", MIDCOM_LOG_WARN);
74
            midcom::get()->debug->log_php_error(MIDCOM_LOG_WARN);
75
            return false;
76
        }
77
78 18
        $this->_open_write_mode = ($mode[0] != 'r');
79 18
        $this->_open_handle = $handle;
80
81 18
        return $handle;
82
    }
83
84
    /**
85
     * Read the file and return its contents
86
     */
87
    public function read() : ?string
88
    {
89
        $blob = new blob($this->__object);
90
        return $blob->read_content();
91
    }
92
93
    /**
94
     * Close the open write handle obtained by the open() call again.
95
     * It is required to call this function instead of a simple fclose to ensure proper
96
     * upgrade notifications.
97
     */
98 18
    public function close()
99
    {
100 18
        if ($this->_open_handle === null) {
101
            debug_add("Tried to close non-open attachment {$this->id}", MIDCOM_LOG_WARN);
102
            return;
103
        }
104
105 18
        fclose($this->_open_handle);
106 18
        $this->_open_handle = null;
107
108 18
        if ($this->_open_write_mode) {
109
            // We need to update the attachment now, this cannot be done in the Midgard Core
110
            // at this time.
111 18
            if (!$this->update()) {
112 11
                debug_add("Failed to update attachment {$this->id}", MIDCOM_LOG_WARN);
113 11
                return;
114
            }
115
116 7
            $this->file_to_cache();
117 7
            $this->_open_write_mode = false;
118
        }
119
    }
120
121
    /**
122
     * Rewrite a filename to URL safe form
123
     *
124
     * @todo add possibility to use the file utility to determine extension if missing.
125
     */
126 7
    public static function safe_filename(string $filename) : string
127
    {
128
        // we could use basename() or pathinfo() here, except that it swallows multibyte chars at the
129
        // beginning of the string if we run in e.g. C locale..
130 7
        $parts = explode('/', trim($filename));
131 7
        $filename = end($parts);
132
133 7
        if (preg_match('/^(.*)(\..*?)$/', $filename, $ext_matches)) {
134 4
            $name = $ext_matches[1];
135 4
            $ext = $ext_matches[2];
136
        } else {
137 3
            $name = $filename;
138 3
            $ext = '';
139
        }
140 7
        return midcom_helper_misc::urlize($name) . $ext;
141
    }
142
143
    /**
144
     * Get the path to the document in the static cache
145
     */
146 1
    private function get_cache_path() : string
147
    {
148
        // Copy the file to the static directory
149 1
        $cacheroot = midcom::get()->config->get('attachment_cache_root');
150 1
        $subdir = $this->guid[0];
151 1
        if (!file_exists("{$cacheroot}/{$subdir}/{$this->guid}")) {
152 1
            mkdir("{$cacheroot}/{$subdir}/{$this->guid}", 0777, true);
153
        }
154
155 1
        return "{$cacheroot}/{$subdir}/{$this->guid}/{$this->name}";
156
    }
157
158 6
    public static function get_url($attachment, string $name = null) : string
159
    {
160 6
        if (is_string($attachment)) {
161
            $guid = $attachment;
162
            if (null === $name) {
163
                $mc = self::new_collector('guid', $guid);
164
                $names = $mc->get_values('name');
165
                $name = array_pop($names);
166
            }
167 6
        } elseif (midcom::get()->dbfactory->is_a($attachment, 'midgard_attachment')) {
168 6
            $guid = $attachment->guid;
169 6
            $name = $attachment->name;
170
        } else {
171
            throw new midcom_error('Invalid attachment identifier');
172
        }
173
174 6
        if (!$guid) {
175 2
            return '';
176
        }
177
178 4
        if (midcom::get()->config->get('attachment_cache_enabled')) {
179
            $subdir = $guid[0];
180
181
            if (file_exists(midcom::get()->config->get('attachment_cache_root') . '/' . $subdir . '/' . $guid . '/' . $name)) {
182
                return midcom::get()->config->get('attachment_cache_url') . '/' . $subdir . '/' . $guid . '/' . urlencode($name);
183
            }
184
        }
185
186
        // Use regular MidCOM attachment server
187 4
        return midcom_connection::get_url('self') . 'midcom-serveattachmentguid-' . $guid . '/' . urlencode($name);
188
    }
189
190 7
    public function file_to_cache()
191
    {
192 7
        if (!midcom::get()->config->get('attachment_cache_enabled')) {
193 7
            return;
194
        }
195
196 1
        if (!$this->can_do('midgard:read', 'EVERYONE')) {
197
            debug_add("Attachment {$this->name} ({$this->guid}) is not publicly readable, not caching.");
198
            $this->remove_from_cache();
199
            return;
200
        }
201
202 1
        $filename = $this->get_cache_path();
203
204 1
        if (file_exists($filename) && is_link($filename)) {
205
            debug_add("Attachment {$this->name} ({$this->guid}) is already in cache as {$filename}, skipping.");
206
            return;
207
        }
208
209
        // Then symlink the file
210 1
        if (@symlink($this->get_path(), $filename)) {
211 1
            debug_add("Symlinked attachment {$this->name} ({$this->guid}) as {$filename}.");
212 1
            return;
213
        }
214
215
        // Symlink failed, actually copy the data
216
        if (!copy($this->get_path(), $filename)) {
217
            debug_add("Failed to cache attachment {$this->name} ({$this->guid}), copying failed.");
218
            return;
219
        }
220
221
        debug_add("Symlinking attachment {$this->name} ({$this->guid}) as {$filename} failed, data copied instead.");
222
    }
223
224
    private function remove_from_cache()
225
    {
226
        $filename = $this->get_cache_path();
227
        if (file_exists($filename)) {
228
            @unlink($filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

228
            /** @scrutinizer ignore-unhandled */ @unlink($filename);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
229
        }
230
    }
231
232
    /**
233
     * Simple wrapper for stat() on the blob object.
234
     *
235
     * @return mixed Either a stat array as for stat() or false on failure.
236
     */
237 5
    public function stat()
238
    {
239 5
        if (!$this->id) {
240
            debug_add('Cannot open a non-persistent attachment.', MIDCOM_LOG_WARN);
241
            debug_print_r('Object state:', $this);
242
            return false;
243
        }
244
245 5
        $path = $this->get_path();
246 5
        if (!file_exists($path)) {
247
            debug_add("File {$path} that blob {$this->guid} points to cannot be found", MIDCOM_LOG_WARN);
248
            return false;
249
        }
250
251 5
        return stat($path);
252
    }
253
254 8
    public function get_path() : string
255
    {
256 8
        if (!$this->id) {
257
            return '';
258
        }
259 8
        return (new blob($this->__object))->get_path();
260
    }
261
262
    /**
263
     * Internal helper, computes an MD5 string which is used as an attachment location.
264
     * If the location already exists, it will iterate until an unused location is found.
265
     */
266 21
    private function _create_attachment_location() : string
267
    {
268 21
        $max_tries = 500;
269
270 21
        for ($i = 0; $i < $max_tries; $i++) {
271 21
            $name = strtolower(md5(uniqid('', true)));
272 21
            $location = strtoupper($name[0] . '/' . $name[1]) . '/' . $name;
273
274
            // Check uniqueness
275 21
            $qb = self::new_query_builder();
276 21
            $qb->add_constraint('location', '=', $location);
277 21
            $result = $qb->count_unchecked();
278
279 21
            if ($result == 0) {
280 21
                debug_add("Created this location: {$location}");
281 21
                return $location;
282
            }
283
            debug_add("Location {$location} is in use, retrying");
284
        }
285
        throw new midcom_error('could not create attachment location');
286
    }
287
288
    /**
289
     * Simple creation event handler which fills out the location field if it
290
     * is still empty with a location generated by _create_attachment_location().
291
     */
292 21
    public function _on_creating() : bool
293
    {
294 21
        if (empty($this->mimetype)) {
295 15
            $this->mimetype = 'application/octet-stream';
296
        }
297
298 21
        $this->location = $this->_create_attachment_location();
299
300 21
        return true;
301
    }
302
303 8
    public function update_cache()
304
    {
305
        // Check if the attachment can be read anonymously
306 8
        if (   midcom::get()->config->get('attachment_cache_enabled')
307 8
            && !$this->can_do('midgard:read', 'EVERYONE')) {
308
            // Not public file, ensure it is removed
309
            $this->remove_from_cache();
310
        }
311
    }
312
313
    /**
314
     * Updated callback, triggers watches on the parent(!) object.
315
     */
316 8
    public function _on_updated()
317
    {
318 8
        $this->update_cache();
319
    }
320
321
    /**
322
     * Deleted callback, triggers watches on the parent(!) object.
323
     */
324 19
    public function _on_deleted()
325
    {
326 19
        if (midcom::get()->config->get('attachment_cache_enabled')) {
327
            // Remove attachment cache
328
            $this->remove_from_cache();
329
        }
330
    }
331
332
    /**
333
     * Updates the contents of the attachments with the contents given.
334
     *
335
     * @param mixed $source File contents.
336
     */
337
    public function copy_from_memory($source) : bool
338
    {
339
        if ($dest = $this->open()) {
340
            fwrite($dest, $source);
341
            $this->close();
342
            return true;
343
        }
344
        return false;
345
    }
346
347
    /**
348
     * Updates the contents of the attachments with the contents of the resource identified
349
     * by the filehandle passed.
350
     *
351
     * @param resource $source The handle to read from.
352
     */
353 18
    public function copy_from_handle($source) : bool
354
    {
355 18
        if ($dest = $this->open()) {
356 18
            stream_copy_to_stream($source, $dest);
357 18
            $this->close();
358 18
            return true;
359
        }
360
        return false;
361
    }
362
363
    /**
364
     * Updates the contents of the attachments with the contents of the file specified.
365
     * This is a wrapper for copy_from_handle.
366
     *
367
     * @param string $filename The file to read.
368
     */
369 16
    public function copy_from_file($filename) : bool
370
    {
371 16
        $source = @fopen($filename, 'r');
372 16
        if (!$source) {
0 ignored issues
show
introduced by
$source is of type false|resource, thus it always evaluated to false.
Loading history...
373
            debug_add('Could not open file for reading.' . midcom_connection::get_error_string(), MIDCOM_LOG_WARN);
374
            midcom::get()->debug->log_php_error(MIDCOM_LOG_WARN);
375
            return false;
376
        }
377 16
        $result = $this->copy_from_handle($source);
378 16
        fclose($source);
379 16
        return $result;
380
    }
381
}
382