Passed
Push — master ( 1b35fc...f88b0e )
by Andreas
18:21
created

midcom_db_attachment::read()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
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 false|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
     * @return string
100
     */
101
    public function read()
102
    {
103
        $blob = new blob($this->__object);
104
        return $blob->read_content();
105
    }
106
107
    /**
108
     * Close the open write handle obtained by the open() call again.
109
     * It is required to call this function instead of a simple fclose to ensure proper
110
     * upgrade notifications.
111
     */
112 8
    public function close()
113
    {
114 8
        if ($this->_open_handle === null) {
115
            debug_add("Tried to close non-open attachment {$this->id}", MIDCOM_LOG_WARN);
116
            return;
117
        }
118
119 8
        fclose($this->_open_handle);
120 8
        $this->_open_handle = null;
121
122 8
        if ($this->_open_write_mode) {
123
            // We need to update the attachment now, this cannot be done in the Midgard Core
124
            // at this time.
125 8
            if (!$this->update()) {
126 1
                debug_add("Failed to update attachment {$this->id}", MIDCOM_LOG_WARN);
127 1
                return;
128
            }
129
130 7
            $this->file_to_cache();
131 7
            $this->_open_write_mode = false;
132
        }
133 8
    }
134
135
    /**
136
     * Rewrite a filename to URL safe form
137
     *
138
     * @param string $filename file name to rewrite
139
     * @param boolean $force_single_extension force file to single extension (defaults to true)
140
     * @todo add possibility to use the file utility to determine extension if missing.
141
     */
142 9
    public static function safe_filename(string $filename, bool $force_single_extension = true) : string
143
    {
144
        // we could use basename() here, except that it swallows multibyte chars at the
145
        // beginning of the string if we run in e.g. C locale..
146 9
        $parts = explode('/', trim($filename));
147 9
        $filename = end($parts);
148
149 9
        if ($force_single_extension) {
150 6
            $regex = '/^(.*)(\..*?)$/';
151
        } else {
152 3
            $regex = '/^(.*?)(\.[a-zA-Z0-9\.]*)$/';
153
        }
154 9
        if (preg_match($regex, $filename, $ext_matches)) {
155 5
            $name = $ext_matches[1];
156 5
            $ext = $ext_matches[2];
157
        } else {
158 4
            $name = $filename;
159 4
            $ext = '';
160
        }
161 9
        return midcom_helper_misc::urlize($name) . $ext;
162
    }
163
164
    /**
165
     * Get the path to the document in the static cache
166
     */
167 1
    private function get_cache_path() : string
168
    {
169
        // Copy the file to the static directory
170 1
        $cacheroot = midcom::get()->config->get('attachment_cache_root');
171 1
        $subdir = substr($this->guid, 0, 1);
172 1
        if (!file_exists("{$cacheroot}/{$subdir}/{$this->guid}")) {
173 1
            mkdir("{$cacheroot}/{$subdir}/{$this->guid}", 0777, true);
174
        }
175
176 1
        return "{$cacheroot}/{$subdir}/{$this->guid}/{$this->name}";
177
    }
178
179 6
    public static function get_url($attachment, string $name = null) : string
180
    {
181 6
        if (is_string($attachment)) {
182
            $guid = $attachment;
183
            if (null === $name) {
184
                $mc = self::new_collector('guid', $guid);
185
                $names = $mc->get_values('name');
186
                $name = array_pop($names);
187
            }
188 6
        } elseif (midcom::get()->dbfactory->is_a($attachment, 'midgard_attachment')) {
189 6
            $guid = $attachment->guid;
190 6
            $name = $attachment->name;
191
        } else {
192
            throw new midcom_error('Invalid attachment identifier');
193
        }
194
195 6
        if (midcom::get()->config->get('attachment_cache_enabled')) {
196
            $subdir = substr($guid, 0, 1);
197
198
            if (file_exists(midcom::get()->config->get('attachment_cache_root') . '/' . $subdir . '/' . $guid . '/' . $name)) {
199
                return midcom::get()->config->get('attachment_cache_url') . '/' . $subdir . '/' . $guid . '/' . urlencode($name);
200
            }
201
        }
202
203
        // Use regular MidCOM attachment server
204 6
        return midcom_connection::get_url('self') . 'midcom-serveattachmentguid-' . $guid . '/' . urlencode($name);
205
    }
206
207 7
    public function file_to_cache()
208
    {
209 7
        if (!midcom::get()->config->get('attachment_cache_enabled')) {
210 7
            return;
211
        }
212
213 1
        if (!$this->can_do('midgard:read', 'EVERYONE')) {
214
            debug_add("Attachment {$this->name} ({$this->guid}) is not publicly readable, not caching.");
215
            $this->remove_from_cache();
216
            return;
217
        }
218
219 1
        $filename = $this->get_cache_path();
220
221 1
        if (file_exists($filename) && is_link($filename)) {
222
            debug_add("Attachment {$this->name} ({$this->guid}) is already in cache as {$filename}, skipping.");
223
            return;
224
        }
225
226
        // Then symlink the file
227 1
        $blob = new blob($this->__object);
228
229 1
        if (@symlink($blob->get_path(), $filename)) {
230 1
            debug_add("Symlinked attachment {$this->name} ({$this->guid}) as {$filename}.");
231 1
            return;
232
        }
233
234
        // Symlink failed, actually copy the data
235
        if (!copy($blob->get_path(), $filename)) {
236
            debug_add("Failed to cache attachment {$this->name} ({$this->guid}), copying failed.");
237
            return;
238
        }
239
240
        debug_add("Symlinking attachment {$this->name} ({$this->guid}) as {$filename} failed, data copied instead.");
241
    }
242
243
    private function remove_from_cache()
244
    {
245
        $filename = $this->get_cache_path();
246
        if (file_exists($filename)) {
247
            @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

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