Test Failed
Push — master ( 5ee9cd...818966 )
by Andreas
19:15
created

midcom_db_attachment::get_url()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 14.2702

Importance

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

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