Passed
Push — master ( ce2bf3...a6b8d2 )
by Andreas
18:36
created

midcom_db_attachment::file_to_cache()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 13.125

Importance

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

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