Passed
Push — master ( cbf088...fb4d6f )
by Andreas
18:48
created

midcom_helper_misc::get_mime_icon()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 12
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 19
ccs 0
cts 12
cp 0
crap 20
rs 9.8666
1
<?php
2
/**
3
 * @package midcom.helper
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 Cocur\Slugify\Slugify;
10
11
/**
12
 * Miscellaneous helper functions
13
 *
14
 * @package midcom.helper
15
 */
16
class midcom_helper_misc
17
{
18
    /**
19
     * @param integer $length
20
     * @param string $characters
21
     * @throws InvalidArgumentException
22
     */
23 13
    public static function random_string($length, $characters) : string
24
    {
25 13
        if ($length < 1) {
26
            throw new InvalidArgumentException('invalid length');
27
        }
28 13
        $size = strlen($characters) - 1;
29 13
        if ($size < 1) {
30
            throw new InvalidArgumentException('invalid characters');
31
        }
32 13
        $return = '';
33 13
        for ($i = 0; $i < $length; $i++) {
34 13
            $return .= $characters[random_int(0, $size)];
35
        }
36 13
        return $return;
37
    }
38
39
    /**
40
     * @param string $input
41
     */
42 27
    public static function urlize($input) : string
43
    {
44 27
        $slugify = new Slugify;
45 27
        return $slugify->slugify($input);
46
    }
47
48
    /**
49
     * Turn midcom config files into PHP arrays
50
     *
51
     * @param string $data The data to parse
52
     * @throws midcom_error
53
     */
54 479
    public static function parse_config($data) : array
55
    {
56
        try {
57 479
            return eval("return [{$data}\n];");
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
58
        } catch (ParseError $e) {
0 ignored issues
show
Unused Code introduced by
catch (\ParseError $e) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
59
            throw new midcom_error('Failed to parse config data: ' . $e->getMessage() . ' in line ' . $e->getLine());
60
        }
61
    }
62
63
    /**
64
     * This helper function searches for a snippet either in the Filesystem
65
     * or in the database and returns its content or code-field, respectively.
66
     *
67
     * Prefix the snippet Path with 'file:' for retrieval of a file relative to
68
     * MIDCOM_ROOT; omit it to get the code field of a Snippet.
69
     *
70
     * Any error (files not found) will return null. If you want to trigger an error,
71
     * look for midcom_helper_misc::get_snippet_content.
72
     *
73
     * @param string $path  The URL to the snippet.
74
     * @return string       The content of the snippet/file.
75
     */
76 479
    public static function get_snippet_content_graceful($path)
77
    {
78 479
        static $cached_snippets = [];
79
80 479
        if (!array_key_exists($path, $cached_snippets)) {
81 63
            if (substr($path, 0, 5) == 'file:') {
82 46
                $cached_snippets[$path] = self::load_from_file($path);
83 22
            } elseif (substr($path, 0, 5) == 'conf:') {
84 22
                $cached_snippets[$path] = self::load(midcom::get()->config->get('midcom_config_basedir') . '/midcom' . substr($path, 5));
85
            } else {
86 17
                $cached_snippets[$path] = self::load_from_snippet($path);
87
            }
88
        }
89
90 479
        return $cached_snippets[$path];
91
    }
92
93 17
    private static function load_from_snippet(string $path)
94
    {
95 17
        $snippet = new midgard_snippet();
96 17
        if (!$snippet->get_by_path($path)) {
97 17
            return null;
98
        }
99
        if (isset(midcom::get()->cache->content)) {
100
            midcom::get()->cache->content->register($snippet->guid);
101
        }
102
        return $snippet->code;
103
    }
104
105 46
    private static function load_from_file(string $path)
106
    {
107 46
        $filename = MIDCOM_ROOT . substr($path, 5);
108 46
        if (!file_exists($filename)) {
109
            // try in src
110 2
            $filename = preg_replace('/\/lib\/?$/', '/src', MIDCOM_ROOT) . substr($path, 5);
111 2
            if (!file_exists($filename)) {
112
                //If we can't find the file in-tree, we look for out-of-tree components before giving up
113
                $filename = substr($path, 6);
114
                if (preg_match('|.+?/.+?/.+?/|', $filename)) {
115
                    $component_name = preg_replace('|(.+?)/(.+?)/(.+?)/.+|', '$1.$2.$3', $filename);
116
                    if (midcom::get()->componentloader->is_installed($component_name)) {
117
                        $filename = substr($filename, strlen($component_name));
118
                        $filename = midcom::get()->componentloader->path_to_snippetpath($component_name) . $filename;
119
                    }
120
                }
121
            }
122
        }
123 46
        return self::load($filename);
124
    }
125
126 63
    private static function load(string $filename)
127
    {
128 63
        if (!file_exists($filename)) {
129 22
            return null;
130
        }
131 46
        return file_get_contents($filename);
132
    }
133
134
    /**
135
     * This helper function searches for a snippet either in the Filesystem
136
     * or in the database and returns its content or code-field, respectively.
137
     *
138
     * Prefix the snippet Path with 'file:' for retrieval of a file relative to
139
     * MIDCOM_ROOT; omit it to get the code field of a Snippet.
140
     *
141
     * Any error (files not found) will raise a MidCOM Error. If you want a more
142
     * graceful behavior, look for midcom_helper_misc::get_snippet_content_graceful
143
     *
144
     * @param string $path    The URL to the snippet.
145
     */
146 247
    public static function get_snippet_content($path) : string
147
    {
148 247
        $data = self::get_snippet_content_graceful($path);
149 247
        if ($data === null) {
0 ignored issues
show
introduced by
The condition $data === null is always false.
Loading history...
150
            throw new midcom_error("Could not load the contents of the snippet {$path}: Snippet does not exist.");
151
        }
152 247
        return $data;
153
    }
154
155
    /**
156
     * Find MIME type image for a document
157
     *
158
     * Used in midcom.helper.imagepopup, midgard.admin.asgard and org.openpsa.documents.
159
     *
160
     * @param string $mimetype  Document MIME type
161
     * @return string    Path to the icon
162
     */
163
    public static function get_mime_icon($mimetype) : string
164
    {
165
        $mime_fspath = MIDCOM_STATIC_ROOT . '/stock-icons/mime';
166
        $mime_urlpath = MIDCOM_STATIC_URL . '/stock-icons/mime';
167
        $mimetype_filename = str_replace('/', '-', $mimetype);
168
        if (!is_readable($mime_fspath)) {
169
            debug_add("Couldn't read directory {$mime_fspath}", MIDCOM_LOG_WARN);
170
        }
171
172
        if ($mimetype_filename == 'application-x-zip-compressed') {
173
            $filename = "gnome-application-zip.png";
174
        } else {
175
            $filename = "gnome-{$mimetype_filename}.png";
176
        }
177
        if (is_readable("{$mime_fspath}/{$filename}")) {
178
            return "{$mime_urlpath}/{$filename}";
179
        }
180
        // Default icon if there is none for the MIME type
181
        return $mime_urlpath . '/gnome-unknown.png';
182
    }
183
184
    /**
185
     * Pretty print file sizes
186
     *
187
     * @param int $size  File size in bytes
188
     */
189 7
    public static function filesize_to_string($size) : string
190
    {
191 7
        if ($size >= 1048576) {
192
            // More than a meg
193
            return sprintf("%01.1f", $size / 1048576) . " MB";
194
        }
195 7
        if ($size >= 1024) {
196
            // More than a kilo
197
            return sprintf("%01.1f", $size / 1024) . " KB";
198
        }
199 7
        return $size . " Bytes";
200
    }
201
202
    /**
203
     * Fix newline etc encoding issues in serialized data
204
     *
205
     * @param string $data The data to fix.
206
     * @return string $data with serializations fixed.
207
     */
208
    public static function fix_serialization($data)
209
    {
210
        //Skip on empty data
211
        if (empty($data)) {
212
            return $data;
213
        }
214
215
        $preg='/s:([0-9]+):"(.*?)";/ms';
216
        preg_match_all($preg, $data, $matches);
217
        $cache = [];
218
219
        foreach ($matches[0] as $k => $origFullStr) {
220
            $origLen = $matches[1][$k];
221
            $origStr = $matches[2][$k];
222
            $newLen = strlen($origStr);
223
            if ($newLen != $origLen) {
224
                $newFullStr = "s:$newLen:\"$origStr\";";
225
                //For performance we cache information on which strings have already been replaced
226
                if (!array_key_exists($origFullStr, $cache)) {
227
                    $data = str_replace($origFullStr, $newFullStr, $data);
228
                    $cache[$origFullStr] = true;
229
                }
230
            }
231
        }
232
233
        return $data;
234
    }
235
236
    /**
237
     * Returns the first instance of a given component on the site.
238
     *
239
     * @param string $component The component name
240
     * @return array NAP array of the first component instance found
241
     */
242 6
    public static function find_node_by_component($component)
243
    {
244 6
        static $cache = [];
245
246 6
        if (!array_key_exists($component, $cache)) {
247 2
            $cache[$component] = null;
248
249 2
            $nap = new midcom_helper_nav;
250 2
            $node_id = $nap->get_root_node();
251 2
            $root_node = $nap->get_node($node_id);
252
253 2
            if ($root_node[MIDCOM_NAV_COMPONENT] == $component) {
254
                $cache[$component] = $root_node;
255
            } else {
256 2
                $qb = midcom_db_topic::new_query_builder();
257 2
                $qb->add_constraint('component', '=', $component);
258 2
                $qb->add_constraint('name', '<>', '');
259 2
                $qb->add_constraint('up', 'INTREE', $node_id);
260 2
                $qb->set_limit(1);
261 2
                $topics = $qb->execute();
262
263 2
                if (count($topics) === 1) {
264 1
                    $cache[$component] = $nap->get_node($topics[0]->id);
265
                }
266
            }
267
        }
268
269 6
        return $cache[$component];
270
    }
271
}
272