Passed
Push — master ( 179526...2874e4 )
by Andreas
28:11
created

midcom_db_attachment::get_url()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 10.5

Importance

Changes 0
Metric Value
cc 6
eloc 16
nc 12
nop 2
dl 0
loc 28
ccs 8
cts 16
cp 0.5
crap 10.5
rs 9.1111
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 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(midgard_attachment|midcom_db_attachment|string $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
        } else {
168 6
            $guid = $attachment->guid;
169 6
            $name = $attachment->name;
170
        }
171
172 6
        if (!$guid) {
173 2
            return '';
174
        }
175
176 4
        if (midcom::get()->config->get('attachment_cache_enabled')) {
177
            $subdir = $guid[0];
178
179
            if (file_exists(midcom::get()->config->get('attachment_cache_root') . '/' . $subdir . '/' . $guid . '/' . $name)) {
180
                return midcom::get()->config->get('attachment_cache_url') . '/' . $subdir . '/' . $guid . '/' . urlencode($name);
181
            }
182
        }
183
184
        // Use regular MidCOM attachment server
185 4
        return midcom_connection::get_url('self') . 'midcom-serveattachmentguid-' . $guid . '/' . urlencode($name);
186
    }
187
188 7
    public function file_to_cache()
189
    {
190 7
        if (!midcom::get()->config->get('attachment_cache_enabled')) {
191 7
            return;
192
        }
193
194 1
        if (!$this->can_do('midgard:read', 'EVERYONE')) {
195
            debug_add("Attachment {$this->name} ({$this->guid}) is not publicly readable, not caching.");
196
            $this->remove_from_cache();
197
            return;
198
        }
199
200 1
        $filename = $this->get_cache_path();
201
202 1
        if (file_exists($filename) && is_link($filename)) {
203
            debug_add("Attachment {$this->name} ({$this->guid}) is already in cache as {$filename}, skipping.");
204
            return;
205
        }
206
207
        // Then symlink the file
208 1
        if (@symlink($this->get_path(), $filename)) {
209 1
            debug_add("Symlinked attachment {$this->name} ({$this->guid}) as {$filename}.");
210 1
            return;
211
        }
212
213
        // Symlink failed, actually copy the data
214
        if (!copy($this->get_path(), $filename)) {
215
            debug_add("Failed to cache attachment {$this->name} ({$this->guid}), copying failed.");
216
            return;
217
        }
218
219
        debug_add("Symlinking attachment {$this->name} ({$this->guid}) as {$filename} failed, data copied instead.");
220
    }
221
222
    private function remove_from_cache()
223
    {
224
        $filename = $this->get_cache_path();
225
        if (file_exists($filename)) {
226
            @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

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