Passed
Push — master ( 9faf51...d66cff )
by Ferry
03:27
created

str_limit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 2
rs 10
1
<?php
2
3
/*
4
 * Theme Helper
5
 */
6
if(!function_exists("themeLoginBackground")) {
7
    function themeLoginBackground() {
8
        return "crudbooster::layouts.login_background_css";
9
    }
10
}
11
if(!function_exists("themeFlashMessageAlert")) {
12
    function themeFlashMessageAlert() {
13
        return "crudbooster::layouts.flash_message_alert";
14
    }
15
}
16
17
if(!function_exists("themeFlashMessage")) {
18
    function themeFlashMessage() {
19
        return "crudbooster::layouts.flash_message";
20
    }
21
}
22
23
if(!function_exists("themeAlertMessage")) {
24
    function themeAlertMessage() {
25
        return "crudbooster::layouts.alert_message";
26
    }
27
}
28
29
if(!function_exists("themeLayoutPageTitleAndButton")) {
30
    function themeLayoutPageTitleAndButton() {
31
        return 'crudbooster::module.index.index_head_buttons';
32
    }
33
}
34
35
if(!function_exists("themeLayoutHead")) {
36
    function themeLayoutHead() {
37
        return "crudbooster::layouts.head";
38
    }
39
}
40
if(!function_exists("themeTitle")) {
41
    function themeTitle($page_title) {
42
        $page_title = isset($page_title)?$page_title:module()->getPageTitle();
43
        return (isset($page_title))?cb()->getAppName().': '.strip_tags($page_title):"Admin Area";
44
    }
45
}
46
47
if(!function_exists("getThemePath")) {
48
    function getThemePath($path = null) {
49
        return getSetting("theme_path", "crudbooster::themes.adminlte").(($path)?".".$path:null);
50
    }
51
}
52
53
// End Theme Helper
54
55
if(!function_exists("isConfigCached")) {
56
    function isConfigCached()
57
    {
58
        if(env("APP_NAME")=="" || env("APP_NAME")==null) return true;
59
        else return false;
60
    }
61
}
62
63
if(!function_exists("miscellanousSingleton")) {
64
    /**
65
     * @return \crocodicstudio\crudbooster\helpers\MiscellanousSingleton
66
     */
67
    function miscellanousSingleton() {
68
        return app("MiscellanousSingleton");
0 ignored issues
show
Bug Best Practice introduced by
The expression return app('MiscellanousSingleton') also could return the type Illuminate\Contracts\Foundation\Application which is incompatible with the documented return type crocodicstudio\crudboost...s\MiscellanousSingleton.
Loading history...
69
    }
70
}
71
72
if(!function_exists("makeReferalUrl")) {
73
    function makeReferalUrl($name = null) {
74
        $ref = [];
75
        $ref['url'] = request()->fullUrl();
76
        $ref['name'] = $name;
77
        $md5Hash = md5(serialize($ref));
78
79
        if($exist = \Illuminate\Support\Facades\Cache::get("refurl_".$md5Hash)) {
80
            return $exist['id'];
81
        }
82
83
        $ref['id'] = $newID = \Illuminate\Support\Str::random(7);
84
85
        \Illuminate\Support\Facades\Cache::forever("refurl_token_".$newID, $md5Hash);
86
        \Illuminate\Support\Facades\Cache::forever("refurl_".$md5Hash, $ref);
87
        return $newID;
88
    }
89
}
90
91
if(!function_exists("getReferalUrl")) {
92
    function getReferalUrl($key = null) {
93
        if(verifyReferalUrl()) {
94
            $md5hash = \Illuminate\Support\Facades\Cache::get("refurl_token_".request("ref"));
0 ignored issues
show
Bug introduced by
Are you sure request('ref') of type Illuminate\Http\Request|array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

94
            $md5hash = \Illuminate\Support\Facades\Cache::get("refurl_token_"./** @scrutinizer ignore-type */ request("ref"));
Loading history...
95
            $ref = \Illuminate\Support\Facades\Cache::get("refurl_".$md5hash);
96
            if($key) {
97
                return @$ref[$key];
98
            } else {
99
                return $ref;
100
            }
101
        }
102
        return null;
103
    }
104
}
105
106
if(!function_exists("verifyReferalUrl")) {
107
    function verifyReferalUrl()
108
    {
109
        if(request("ref")) {
110
            if($md5hash = \Illuminate\Support\Facades\Cache::get("refurl_token_".request("ref"))) {
0 ignored issues
show
Bug introduced by
Are you sure request('ref') of type Illuminate\Http\Request|array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

110
            if($md5hash = \Illuminate\Support\Facades\Cache::get("refurl_token_"./** @scrutinizer ignore-type */ request("ref"))) {
Loading history...
111
                $ref = \Illuminate\Support\Facades\Cache::get("refurl_".$md5hash);
112
                if(filter_var($ref['url'], FILTER_VALIDATE_URL)) {
113
                    return true;
114
                }
115
            }
116
        }
117
        return false;
118
    }
119
}
120
121
if(!function_exists("putHtaccess")) {
122
    function putHtaccess($stringToPut)
123
    {
124
        file_put_contents(base_path(".htaccess"), "\n".$stringToPut, FILE_APPEND);
125
        file_put_contents(public_path(".htaccess"), "\n".$stringToPut, FILE_APPEND);
126
    }
127
}
128
129
if(!function_exists("checkHtaccess")) {
130
    function checkHtaccess($stringToCheck)
131
    {
132
        if(file_exists(base_path(".htaccess")) && file_exists(public_path(".htaccess"))) {
133
            $htaccess = file_get_contents(base_path(".htaccess"));
134
            $htaccess2= file_get_contents(public_path(".htaccess"));
135
            if(\Illuminate\Support\Str::contains($htaccess, $stringToCheck) && \Illuminate\Support\Str::contains($htaccess2, $stringToCheck)) {
136
                return true;
137
            }
138
        }
139
140
        return false;
141
    }
142
}
143
144
if(!function_exists("setEnvironmentValue")) {
145
    function setEnvironmentValue(array $values)
146
    {
147
        $envFile = app()->environmentFilePath();
0 ignored issues
show
introduced by
The method environmentFilePath() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

147
        $envFile = app()->/** @scrutinizer ignore-call */ environmentFilePath();
Loading history...
148
        $str = file_get_contents($envFile);
149
150
        if (count($values) > 0) {
151
            foreach ($values as $envKey => $envValue) {
152
153
                $str .= "\n"; // In case the searched variable is in the last line without \n
154
                $keyPosition = strpos($str, "{$envKey}=");
155
                $endOfLinePosition = strpos($str, "\n", $keyPosition);
156
                $oldLine = substr($str, $keyPosition, $endOfLinePosition - $keyPosition);
157
158
                // If key does not exist, add it
159
                if (!$keyPosition || !$endOfLinePosition || !$oldLine) {
160
                    $str .= "{$envKey}={$envValue}\n";
161
                } else {
162
                    $str = str_replace($oldLine, "{$envKey}={$envValue}", $str);
163
                }
164
165
            }
166
        }
167
168
        $str = substr($str, 0, -1);
169
        if (!file_put_contents($envFile, $str)) return false;
170
        return true;
171
    }
172
}
173
174
175
if(!function_exists("cbLang")) {
176
    /**
177
     * @param string $key
178
     * @param array $replace
179
     * @return array|\Illuminate\Contracts\Translation\Translator|null|string
180
     */
181
    function cbLang($key, $replace = [])
182
    {
183
        return trans("cb::cb.".$key, $replace);
184
    }
185
}
186
187
if(!function_exists('rglob')) {
188
    function rglob($pattern, $flags = 0) {
189
        $files = glob($pattern, $flags);
190
        foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
191
            $files = array_merge($files, rglob($dir.'/'.basename($pattern), $flags));
0 ignored issues
show
Bug introduced by
It seems like $files can also be of type false; however, parameter $array1 of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

191
            $files = array_merge(/** @scrutinizer ignore-type */ $files, rglob($dir.'/'.basename($pattern), $flags));
Loading history...
Bug introduced by
It seems like rglob($dir . '/' . basename($pattern), $flags) can also be of type false; however, parameter $array2 of array_merge() does only seem to accept array|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

191
            $files = array_merge($files, /** @scrutinizer ignore-type */ rglob($dir.'/'.basename($pattern), $flags));
Loading history...
192
        }
193
        return $files;
194
    }
195
}
196
197
if(!function_exists('convertPHPToMomentFormat')) {
198
    function convertPHPToMomentFormat($format)
199
    {
200
        $replacements = [
201
            'd' => 'DD',
202
            'D' => 'ddd',
203
            'j' => 'D',
204
            'l' => 'dddd',
205
            'N' => 'E',
206
            'S' => 'o',
207
            'w' => 'e',
208
            'z' => 'DDD',
209
            'W' => 'W',
210
            'F' => 'MMMM',
211
            'm' => 'MM',
212
            'M' => 'MMM',
213
            'n' => 'M',
214
            't' => '', // no equivalent
215
            'L' => '', // no equivalent
216
            'o' => 'YYYY',
217
            'Y' => 'YYYY',
218
            'y' => 'YY',
219
            'a' => 'a',
220
            'A' => 'A',
221
            'B' => '', // no equivalent
222
            'g' => 'h',
223
            'G' => 'H',
224
            'h' => 'hh',
225
            'H' => 'HH',
226
            'i' => 'mm',
227
            's' => 'ss',
228
            'u' => 'SSS',
229
            'e' => 'zz', // deprecated since version 1.6.0 of moment.js
230
            'I' => '', // no equivalent
231
            'O' => '', // no equivalent
232
            'P' => '', // no equivalent
233
            'T' => '', // no equivalent
234
            'Z' => '', // no equivalent
235
            'c' => '', // no equivalent
236
            'r' => '', // no equivalent
237
            'U' => 'X',
238
        ];
239
        $momentFormat = strtr($format, $replacements);
240
        return $momentFormat;
241
    }
242
}
243
244
if(!function_exists('slug')) {
245
    function slug($string, $separator = '-') {
246
        return \Illuminate\Support\Str::slug($string, $separator);
247
    }
248
}
249
250
if(!function_exists('columnSingleton')) {
251
    /**
252
     * @return \crocodicstudio\crudbooster\controllers\scaffolding\singletons\ColumnSingleton
253
     */
254
    function columnSingleton() {
255
        return app('ColumnSingleton');
0 ignored issues
show
Bug Best Practice introduced by
The expression return app('ColumnSingleton') also could return the type Illuminate\Contracts\Foundation\Application which is incompatible with the documented return type crocodicstudio\crudboost...gletons\ColumnSingleton.
Loading history...
256
    }
257
}
258
259
if(!function_exists('cbHook'))
260
{
261
    /**
262
     * @return crocodicstudio\crudbooster\hooks\CBHook
263
     */
264
    function cbHook()
265
    {
266
        $className = "\App\Http\CBHook";
267
        return new $className();
268
    }
269
}
270
271
if(!function_exists('getTypeHook'))
272
{
273
    /**
274
     * @param string $type
275
     * @return crocodicstudio\crudbooster\types\TypesHookInterface
276
     */
277
    function getTypeHook($type) {
278
        $className = '\crocodicstudio\crudbooster\types\\'.$type.'\Hook';
279
        $typeClass = new $className();
280
        return $typeClass;
281
    }
282
}
283
284
if(!function_exists('getPrimaryKey'))
285
{
286
    function getPrimaryKey($table_name)
287
    {
288
        return cb()->pk($table_name);
289
    }
290
}
291
292
if(!function_exists('cb'))
293
{
294
    function cb()
295
    {
296
        return new \crocodicstudio\crudbooster\helpers\CB();
297
    }
298
}
299
300
if(!function_exists("cbAssetPath")) {
301
    function cbAssetPath($path = null) {
302
        return "cb_asset".(($path)?"/".$path:null);
303
    }
304
}
305
if(!function_exists('cbAsset')) {
306
    function cbAsset($path, $secure = null) {
307
        return asset(cbAssetPath()."/".$path, $secure);
308
    }
309
}
310
311
if(!function_exists("cbConfig")) {
312
    function cbConfig($name, $default = null) {
313
        return config("crudbooster.".$name, $default);
314
    }
315
}
316
317
if(!function_exists("strRandom")) {
318
    function strRandom($length = 5) {
319
        return \Illuminate\Support\Str::random($length);
320
    }
321
}
322
323
if(!function_exists('module')) {
324
    function module()
325
    {
326
        $module = new \crocodicstudio\crudbooster\helpers\Module();
327
        return $module;
328
    }
329
}
330
331
if(!function_exists('getAdminLoginURL')) {
332
    function getAdminLoginURL()
333
    {
334
        return cb()->getAdminUrl("login");
335
    }
336
}
337
338
if(!function_exists('dummyPhoto')) {
339
    function dummyPhoto()
340
    {
341
        return getSetting("dummy_photo","cb_asset/images/user8-128x128.jpg");
342
    }
343
}
344
345
if(!function_exists("str_limit")) {
346
    function str_limit($string, $limit = 100, $end = "...") {
347
        return \Illuminate\Support\Str::limit($string, $limit, $end);
348
    }
349
}
350
351
if(!function_exists('extract_unit')) {	
352
	/*
353
	Credits: Bit Repository
354
	URL: http://www.bitrepository.com/extract-content-between-two-delimiters-with-php.html
355
	*/
356
	function extract_unit($string, $start, $end)
357
	{
358
	$pos = stripos($string, $start);
359
	$str = substr($string, $pos);
360
	$str_two = substr($str, strlen($start));
361
	$second_pos = stripos($str_two, $end);
362
	$str_three = substr($str_two, 0, $second_pos);
363
	$unit = trim($str_three); // remove whitespaces
364
	return $unit;
365
	}
366
}
367
368
/* 
369
| --------------------------------------------------------------------------------------------------------------
370
| Get data from input post/get more simply
371
| --------------------------------------------------------------------------------------------------------------
372
| $name = name of input
373
|
374
*/
375
376
if(!function_exists('putSetting')) {
377
    function putSetting($key, $value)
378
    {
379
        if(file_exists(storage_path('.cbconfig'))) {
380
            $settings = file_get_contents(storage_path('.cbconfig'));
381
            $settings = decrypt($settings);
382
            $settings = unserialize($settings);
383
        }else{
384
            $settings = [];
385
        }
386
387
        $settings[$key] = $value;
388
389
        \Illuminate\Support\Facades\Cache::forget("setting_".$key);
390
391
        $settings = serialize($settings);
392
        $settings = encrypt($settings);
393
        file_put_contents(storage_path('.cbconfig'), $settings);
394
    }
395
}
396
397
if(!function_exists('getSetting')) {
398
    function getSetting($key, $default = null)
399
    {
400
        if($cache = \Illuminate\Support\Facades\Cache::get("setting_".$key)) {
401
            return $cache;
402
        }
403
404
        if(file_exists(storage_path('.cbconfig'))) {
405
            $settings = file_get_contents(storage_path('.cbconfig'));
406
            $settings = decrypt($settings);
407
            $settings = unserialize($settings);
408
        }else{
409
            $settings = [];
410
        }
411
412
        if(isset($settings[$key])) {
413
            \Illuminate\Support\Facades\Cache::forever("setting_".$key, $settings[$key]);
414
            return $settings[$key]?:$default;
415
        }else{
416
            return $default;
417
        }
418
    }
419
}
420
421
if(!function_exists('timeAgo')) {
422
    function timeAgo($datetime_to, $datetime_from = null, $full = false)
423
    {
424
        $datetime_from = ($datetime_from) ?: date('Y-m-d H:i:s');
425
        $now = new \DateTime;
426
        if ($datetime_from != '') {
427
            $now = new \DateTime($datetime_from);
428
        }
429
        $ago = new \DateTime($datetime_to);
430
        $diff = $now->diff($ago);
431
432
        $diff->w = floor($diff->d / 7);
0 ignored issues
show
Bug introduced by
The property w does not seem to exist on DateInterval.
Loading history...
433
        $diff->d -= $diff->w * 7;
434
435
        $string = [
436
            'y' => 'year',
437
            'm' => 'month',
438
            'w' => 'week',
439
            'd' => 'day',
440
            'h' => 'hour',
441
            'i' => 'minute',
442
            's' => 'second',
443
        ];
444
        foreach ($string as $k => &$v) {
445
            if ($diff->$k) {
446
                $v = $diff->$k.' '.$v.($diff->$k > 1 ? 's' : '');
447
            } else {
448
                unset($string[$k]);
449
            }
450
        }
451
452
        if (! $full) {
453
            $string = array_slice($string, 0, 1);
454
        }
455
456
        return $string ? implode(', ', $string).' ' : 'just now';
457
    }
458
}
459
460
if(!function_exists("array_map_r")) {
461
    function array_map_r( $func, $arr )
462
    {
463
        $newArr = array();
464
465
        foreach( $arr as $key => $value )
466
        {
467
            $key = $func($key);
468
            $newArr[ $key ] = ( is_array( $value ) ? array_map_r( $func, $value ) : ( is_array($func) ? call_user_func_array($func, $value) : $func( $value ) ) );
469
        }
470
471
        return $newArr;
472
    }
473
}
474
475
if(!function_exists("sanitizeXSS"))
476
{
477
    function sanitizeXSS($value)
478
    {
479
        $value = filter_var($value, FILTER_SANITIZE_STRING);
480
        $value = strip_tags($value);
481
        $value = htmlspecialchars($value);
482
        $value = preg_replace('~\r\n?~', "\n", $value);
483
        return $value;
484
    }
485
}
486
487
if(!function_exists("requestAll")) {
488
    function requestAll() {
489
        $all = array_map_r("sanitizeXSS", request()->all());
490
        return $all;
491
    }
492
}
493
494
495
496
if(!function_exists('getURLFormat')) {
497
    function getURLFormat($name) {
498
        $url = request($name);
499
        if(filter_var($url, FILTER_VALIDATE_URL)) {
500
            return $url;
501
        }else{
502
            return request()->url();
503
        }
504
    }
505
}
506
507
if(!function_exists('g')) {
508
    function g($name, $safe = true) {
509
        if($safe == true) {
510
            $response = request($name);
511
            if(is_string($response)) {
512
                $response = sanitizeXSS($response);
513
            }elseif (is_array($response)) {
514
                array_walk_recursive($response, function(&$response) {
515
                    $response = sanitizeXSS($response);
516
                });
517
            }
518
519
            return $response;
520
        }else{
521
            return Request::get($name);
522
        }
523
    }
524
}
525
526
if(!function_exists('min_var_export')) {
527
    function min_var_export($input) {
528
        if(is_array($input)) {
529
            $buffer = [];
530
            foreach($input as $key => $value)
531
                $buffer[] = var_export($key, true)."=>".min_var_export($value);
532
            return "[".implode(",",$buffer)."]";
533
        } else
534
            return var_export($input, true);
535
    }
536
}
537
538
if(!function_exists('rrmdir')) {
539
	/*
540
	* http://stackoverflow.com/questions/3338123/how-do-i-recursively-delete-a-directory-and-its-entire-contents-files-sub-dir
541
	*/
542
	function rrmdir($dir) { 
543
	   if (is_dir($dir)) { 
544
	     $objects = scandir($dir); 
545
	     foreach ($objects as $object) { 
546
	       if ($object != "." && $object != "..") { 
547
	         if (is_dir($dir."/".$object))
548
	           rrmdir($dir."/".$object);
549
	         else
550
	           unlink($dir."/".$object); 
551
	       } 
552
	     }
553
	     rmdir($dir); 
554
	   } 
555
	 }
556
}
557
558