Passed
Push — master ( 25e012...c75434 )
by Andreas
11:25
created

midcom_db_attachment   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 362
Duplicated Lines 0 %

Test Coverage

Coverage 62.42%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 140
c 2
b 0
f 0
dl 0
loc 362
ccs 93
cts 149
cp 0.6242
rs 6.96
wmc 53

18 Methods

Rating   Name   Duplication   Size   Complexity  
A open() 0 26 4
A close() 0 20 4
A read() 0 4 1
A safe_filename() 0 14 2
A copy_from_handle() 0 8 2
A copy_from_file() 0 11 2
A _on_deleted() 0 5 2
A _create_attachment_location() 0 20 3
A copy_from_memory() 0 8 2
A get_cache_path() 0 12 3
A get_url() 0 28 6
A update_cache() 0 7 3
A get_path() 0 6 2
A _on_updated() 0 3 1
A remove_from_cache() 0 5 3
A stat() 0 15 3
A _on_creating() 0 9 2
B file_to_cache() 0 35 8

How to fix   Complexity   

Complex Class

Complex classes like midcom_db_attachment often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use midcom_db_attachment, and based on these observations, apply Extract Interface, too.

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] = $ext_matches;
135
        } else {
136 3
            $name = $filename;
137 3
            $ext = '';
138
        }
139 7
        return midcom_helper_misc::urlize($name) . $ext;
140
    }
141
142
    /**
143
     * Get the path to the document in the static cache
144
     */
145 1
    private function get_cache_path() : ?string
146
    {
147
        // Copy the file to the static directory
148 1
        $cacheroot = midcom::get()->config->get('attachment_cache_root');
149 1
        $subdir = $this->guid[0];
150 1
        if (!file_exists("{$cacheroot}/{$subdir}/{$this->guid}")) {
151 1
            if (!mkdir("{$cacheroot}/{$subdir}/{$this->guid}", 0777, true)) {
152
                return null;
153
            }
154
        }
155
156 1
        return "{$cacheroot}/{$subdir}/{$this->guid}/{$this->name}";
157
    }
158
159 6
    public static function get_url(midgard_attachment|midcom_db_attachment|string $attachment, ?string $name = null) : string
160
    {
161 6
        if (is_string($attachment)) {
162
            $guid = $attachment;
163
            if (null === $name) {
164
                $mc = self::new_collector('guid', $guid);
165
                $names = $mc->get_values('name');
166
                $name = array_pop($names);
167
            }
168
        } else {
169 6
            $guid = $attachment->guid;
170 6
            $name = $attachment->name;
171
        }
172
173 6
        if (!$guid) {
174 2
            return '';
175
        }
176
177 4
        if (midcom::get()->config->get('attachment_cache_enabled')) {
178
            $subdir = $guid[0];
179
180
            if (file_exists(midcom::get()->config->get('attachment_cache_root') . '/' . $subdir . '/' . $guid . '/' . $name)) {
181
                return midcom::get()->config->get('attachment_cache_url') . '/' . $subdir . '/' . $guid . '/' . urlencode($name);
182
            }
183
        }
184
185
        // Use regular MidCOM attachment server
186 4
        return midcom_connection::get_url('self') . 'midcom-serveattachmentguid-' . $guid . '/' . urlencode($name);
187
    }
188
189 7
    public function file_to_cache()
190
    {
191 7
        if (!midcom::get()->config->get('attachment_cache_enabled')) {
192 7
            return;
193
        }
194
195 1
        if (!$this->can_do('midgard:read', 'EVERYONE')) {
196
            debug_add("Attachment {$this->name} ({$this->guid}) is not publicly readable, not caching.");
197
            $this->remove_from_cache();
198
            return;
199
        }
200
201 1
        $filename = $this->get_cache_path();
202
203 1
        if (!$filename) {
204
            debug_add("Failed to create cache dir, skipping.");
205
            return;
206
        }
207
208 1
        if (file_exists($filename) && is_link($filename)) {
209
            debug_add("Attachment {$this->name} ({$this->guid}) is already in cache as {$filename}, skipping.");
210
            return;
211
        }
212
213
        // Then symlink the file
214 1
        if (@symlink($this->get_path(), $filename)) {
215 1
            debug_add("Symlinked attachment {$this->name} ({$this->guid}) as {$filename}.");
216 1
            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
        } else {
223
            debug_add("Symlinking attachment {$this->name} ({$this->guid}) as {$filename} failed, data copied instead.");
224
        }
225
    }
226
227
    private function remove_from_cache()
228
    {
229
        $filename = $this->get_cache_path();
230
        if ($filename && file_exists($filename)) {
231
            @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

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