Issues (50)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/helpers/StringHelper.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
4
namespace carono\janitor\helpers;
5
6
7
class StringHelper
8
{
9
    /**
10
     * Returns the number of bytes in the given string.
11
     * This method ensures the string is treated as a byte array by using `mb_strlen()`.
12
     *
13
     * @param string $string the string being measured for length
14
     * @return int the number of bytes in the given string.
15
     */
16
    public static function byteLength($string)
17
    {
18
        return mb_strlen($string, '8bit');
19
    }
20
21
    /**
22
     * Returns the portion of string specified by the start and length parameters.
23
     * This method ensures the string is treated as a byte array by using `mb_substr()`.
24
     *
25
     * @param string $string the input string. Must be one character or longer.
26
     * @param int $start the starting position
27
     * @param int $length the desired portion length. If not specified or `null`, there will be
28
     * no limit on length i.e. the output will be until the end of the string.
29
     * @return string the extracted part of string, or FALSE on failure or an empty string.
30
     * @see https://secure.php.net/manual/en/function.substr.php
31
     */
32
    public static function byteSubstr($string, $start, $length = null)
33
    {
34
        return mb_substr($string, $start, $length === null ? mb_strlen($string, '8bit') : $length, '8bit');
35
    }
36
37
    /**
38
     * Returns the trailing name component of a path.
39
     * This method is similar to the php function `basename()` except that it will
40
     * treat both \ and / as directory separators, independent of the operating system.
41
     * This method was mainly created to work on php namespaces. When working with real
42
     * file paths, php's `basename()` should work fine for you.
43
     * Note: this method is not aware of the actual filesystem, or path components such as "..".
44
     *
45
     * @param string $path A path string.
46
     * @param string $suffix If the name component ends in suffix this will also be cut off.
47
     * @return string the trailing name component of the given path.
48
     * @see https://secure.php.net/manual/en/function.basename.php
49
     */
50
    public static function basename($path, $suffix = '')
51
    {
52
        if (($len = mb_strlen($suffix)) > 0 && mb_substr($path, -$len) === $suffix) {
53
            $path = mb_substr($path, 0, -$len);
54
        }
55
        $path = rtrim(str_replace('\\', '/', $path), '/\\');
56
        if (($pos = mb_strrpos($path, '/')) !== false) {
57
            return mb_substr($path, $pos + 1);
58
        }
59
60
        return $path;
61
    }
62
63
    /**
64
     * Returns parent directory's path.
65
     * This method is similar to `dirname()` except that it will treat
66
     * both \ and / as directory separators, independent of the operating system.
67
     *
68
     * @param string $path A path string.
69
     * @return string the parent directory's path.
70
     * @see https://secure.php.net/manual/en/function.basename.php
71
     */
72
    public static function dirname($path)
73
    {
74
        $pos = mb_strrpos(str_replace('\\', '/', $path), '/');
75
        if ($pos !== false) {
76
            return mb_substr($path, 0, $pos);
77
        }
78
79
        return '';
80
    }
81
82
    /**
83
     * Truncates a string to the number of words specified.
84
     *
85
     * @param string $string The string to truncate.
86
     * @param int $count How many words from original string to include into truncated string.
87
     * @param string $suffix String to append to the end of truncated string.
88
     * @param bool $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags.
89
     * This parameter is available since version 2.0.1.
90
     * @return string the truncated string.
91
     */
92
    public static function truncateWords($string, $count, $suffix = '...', $asHtml = false)
93
    {
94
        if ($asHtml) {
95
            return static::truncateHtml($string, $count, $suffix);
0 ignored issues
show
The method truncateHtml() does not seem to exist on object<carono\janitor\helpers\StringHelper>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
96
        }
97
98
        $words = preg_split('/(\s+)/u', trim($string), null, PREG_SPLIT_DELIM_CAPTURE);
99
        if (count($words) / 2 > $count) {
100
            return implode('', array_slice($words, 0, ($count * 2) - 1)) . $suffix;
101
        }
102
103
        return $string;
104
    }
105
106
    /**
107
     * Check if given string starts with specified substring.
108
     * Binary and multibyte safe.
109
     *
110
     * @param string $string Input string
111
     * @param string $with Part to search inside the $string
112
     * @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the starting of the string in order to get a true value.
113
     * @return bool Returns true if first input starts with second input, false otherwise
114
     */
115
    public static function startsWith($string, $with, $caseSensitive = true)
116
    {
117
        if (!$bytes = static::byteLength($with)) {
118
            return true;
119
        }
120
        if ($caseSensitive) {
121
            return strncmp($string, $with, $bytes) === 0;
122
123
        }
124
        $encoding = 'UTF-8';
125
        return mb_strtolower(mb_substr($string, 0, $bytes, '8bit'), $encoding) === mb_strtolower($with, $encoding);
126
    }
127
128
    /**
129
     * Check if given string ends with specified substring.
130
     * Binary and multibyte safe.
131
     *
132
     * @param string $string Input string to check
133
     * @param string $with Part to search inside of the $string.
134
     * @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the ending of the string in order to get a true value.
135
     * @return bool Returns true if first input ends with second input, false otherwise
136
     */
137
    public static function endsWith($string, $with, $caseSensitive = true)
138
    {
139
        if (!$bytes = static::byteLength($with)) {
140
            return true;
141
        }
142
        if ($caseSensitive) {
143
            // Warning check, see https://secure.php.net/manual/en/function.substr-compare.php#refsect1-function.substr-compare-returnvalues
144
            if (static::byteLength($string) < $bytes) {
145
                return false;
146
            }
147
148
            return substr_compare($string, $with, -$bytes, $bytes) === 0;
149
        }
150
151
        $encoding = 'UTF-8';
152
        return mb_strtolower(mb_substr($string, -$bytes, mb_strlen($string, '8bit'), '8bit'), $encoding) === mb_strtolower($with, $encoding);
153
    }
154
155
    /**
156
     * Explodes string into array, optionally trims values and skips empty ones.
157
     *
158
     * @param string $string String to be exploded.
159
     * @param string $delimiter Delimiter. Default is ','.
160
     * @param mixed $trim Whether to trim each element. Can be:
161
     *   - boolean - to trim normally;
162
     *   - string - custom characters to trim. Will be passed as a second argument to `trim()` function.
163
     *   - callable - will be called for each value instead of trim. Takes the only argument - value.
164
     * @param bool $skipEmpty Whether to skip empty strings between delimiters. Default is false.
165
     * @return array
166
     * @since 2.0.4
167
     */
168
    public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false)
169
    {
170
        $result = explode($delimiter, $string);
171
        if ($trim !== false) {
172
            if ($trim === true) {
173
                $trim = 'trim';
174
            } elseif (!is_callable($trim)) {
175
                $trim = function ($v) use ($trim) {
176
                    return trim($v, $trim);
177
                };
178
            }
179
            $result = array_map($trim, $result);
180
        }
181
        if ($skipEmpty) {
182
            // Wrapped with array_values to make array keys sequential after empty values removing
183
            $result = array_values(array_filter($result, function ($value) {
184
                return $value !== '';
185
            }));
186
        }
187
188
        return $result;
189
    }
190
191
    /**
192
     * Counts words in a string.
193
     *
194
     * @since 2.0.8
195
     *
196
     * @param string $string
197
     * @return int
198
     */
199
    public static function countWords($string)
200
    {
201
        return count(preg_split('/\s+/u', $string, null, PREG_SPLIT_NO_EMPTY));
202
    }
203
204
    /**
205
     * Returns string representation of number value with replaced commas to dots, if decimal point
206
     * of current locale is comma.
207
     *
208
     * @param int|float|string $value
209
     * @return string
210
     * @since 2.0.11
211
     */
212
    public static function normalizeNumber($value)
213
    {
214
        $value = (string)$value;
215
216
        $localeInfo = localeconv();
217
        $decimalSeparator = isset($localeInfo['decimal_point']) ? $localeInfo['decimal_point'] : null;
218
219
        if ($decimalSeparator !== null && $decimalSeparator !== '.') {
220
            $value = str_replace($decimalSeparator, '.', $value);
221
        }
222
223
        return $value;
224
    }
225
226
    /**
227
     * Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
228
     *
229
     * > Note: Base 64 padding `=` may be at the end of the returned string.
230
     * > `=` is not transparent to URL encoding.
231
     *
232
     * @see https://tools.ietf.org/html/rfc4648#page-7
233
     * @param string $input the string to encode.
234
     * @return string encoded string.
235
     * @since 2.0.12
236
     */
237
    public static function base64UrlEncode($input)
238
    {
239
        return strtr(base64_encode($input), '+/', '-_');
240
    }
241
242
    /**
243
     * Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
244
     *
245
     * @see https://tools.ietf.org/html/rfc4648#page-7
246
     * @param string $input encoded string.
247
     * @return string decoded string.
248
     * @since 2.0.12
249
     */
250
    public static function base64UrlDecode($input)
251
    {
252
        return base64_decode(strtr($input, '-_', '+/'));
253
    }
254
255
    /**
256
     * Safely casts a float to string independent of the current locale.
257
     *
258
     * The decimal separator will always be `.`.
259
     *
260
     * @param float|int $number a floating point number or integer.
261
     * @return string the string representation of the number.
262
     * @since 2.0.13
263
     */
264
    public static function floatToString($number)
265
    {
266
        // . and , are the only decimal separators known in ICU data,
267
        // so its safe to call str_replace here
268
        return str_replace(',', '.', (string)$number);
269
    }
270
271
    /**
272
     * Checks if the passed string would match the given shell wildcard pattern.
273
     * This function emulates [[fnmatch()]], which may be unavailable at certain environment, using PCRE.
274
     *
275
     * @param string $pattern the shell wildcard pattern.
276
     * @param string $string the tested string.
277
     * @param array $options options for matching. Valid options are:
278
     *
279
     * - caseSensitive: bool, whether pattern should be case sensitive. Defaults to `true`.
280
     * - escape: bool, whether backslash escaping is enabled. Defaults to `true`.
281
     * - filePath: bool, whether slashes in string only matches slashes in the given pattern. Defaults to `false`.
282
     *
283
     * @return bool whether the string matches pattern or not.
284
     * @since 2.0.14
285
     */
286
    public static function matchWildcard($pattern, $string, $options = [])
287
    {
288
        if ($pattern === '*' && empty($options['filePath'])) {
289
            return true;
290
        }
291
292
        $replacements = [
293
            '\\\\\\\\' => '\\\\',
294
            '\\\\\\*' => '[*]',
295
            '\\\\\\?' => '[?]',
296
            '\*' => '.*',
297
            '\?' => '.',
298
            '\[\!' => '[^',
299
            '\[' => '[',
300
            '\]' => ']',
301
            '\-' => '-',
302
        ];
303
304
        if (isset($options['escape']) && !$options['escape']) {
305
            unset($replacements['\\\\\\\\']);
306
            unset($replacements['\\\\\\*']);
307
            unset($replacements['\\\\\\?']);
308
        }
309
310
        if (!empty($options['filePath'])) {
311
            $replacements['\*'] = '[^/\\\\]*';
312
            $replacements['\?'] = '[^/\\\\]';
313
        }
314
315
        $pattern = strtr(preg_quote($pattern, '#'), $replacements);
316
        $pattern = '#^' . $pattern . '$#us';
317
318
        if (isset($options['caseSensitive']) && !$options['caseSensitive']) {
319
            $pattern .= 'i';
320
        }
321
322
        return preg_match($pattern, $string) === 1;
323
    }
324
325
    /**
326
     * This method provides a unicode-safe implementation of built-in PHP function `ucfirst()`.
327
     *
328
     * @param string $string the string to be proceeded
329
     * @param string $encoding Optional, defaults to "UTF-8"
330
     * @return string
331
     * @see https://secure.php.net/manual/en/function.ucfirst.php
332
     * @since 2.0.16
333
     */
334
    public static function mb_ucfirst($string, $encoding = 'UTF-8')
335
    {
336
        $firstChar = mb_substr($string, 0, 1, $encoding);
337
        $rest = mb_substr($string, 1, null, $encoding);
338
339
        return mb_strtoupper($firstChar, $encoding) . $rest;
340
    }
341
342
    /**
343
     * This method provides a unicode-safe implementation of built-in PHP function `ucwords()`.
344
     *
345
     * @param string $string the string to be proceeded
346
     * @param string $encoding Optional, defaults to "UTF-8"
347
     * @return string
348
     * @see https://secure.php.net/manual/en/function.ucwords.php
349
     * @since 2.0.16
350
     */
351
    public static function mb_ucwords($string, $encoding = 'UTF-8')
352
    {
353
        $words = preg_split("/\s/u", $string, -1, PREG_SPLIT_NO_EMPTY);
354
355
        $titelized = array_map(function ($word) use ($encoding) {
356
            return static::mb_ucfirst($word, $encoding);
357
        }, $words);
358
359
        return implode(' ', $titelized);
360
    }
361
}