CRUDBooster::myId()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
nc 1
nop 0
dl 0
loc 3
c 0
b 0
f 0
cc 1
rs 10
1
<?php
2
3
namespace crocodicstudio\crudbooster\helpers;
4
5
use Cache;
6
use DB;
7
use Image;
8
use Request;
9
use Route;
10
use Schema;
11
use Session;
12
use Storage;
13
use Validator;
14
15
class CRUDBooster
16
{
17
    /**
18
    *	Comma-delimited data output from the child table
19
    */
20
    public static function echoSelect2Mult($values, $table, $id, $name) {
21
        $values = explode(",", $values);
22
        return implode(", ", DB::table($table)->whereIn($id, $values)->pluck($name)->toArray());
23
        //implode(", ", DB::table("syudo_list_pokemons_types")->whereIn("id", explode(",", $row->type))->pluck("name")->toArray())
24
        
25
    }
26
    
27
    public static function uploadBase64($value, $id = null)
28
    {
29
        if (! self::myId()) {
30
            $userID = 0;
31
        } else {
32
            $userID = self::myId();
33
        }
34
35
        if ($id) {
36
            $userID = $id;
37
        }
38
39
        $filedata = base64_decode($value);
40
        $f = finfo_open();
41
        $mime_type = finfo_buffer($f, $filedata, FILEINFO_MIME_TYPE);
42
        @$mime_type = explode('/', $mime_type);
0 ignored issues
show
Bug introduced by
$mime_type of type string[] is incompatible with the type string expected by parameter $string of explode(). ( Ignorable by Annotation )

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

42
        @$mime_type = explode('/', /** @scrutinizer ignore-type */ $mime_type);
Loading history...
43
        @$mime_type = $mime_type[1];
44
        if ($mime_type) {
45
            $filePath = 'uploads/'.$userID.'/'.date('Y-m');
46
		Storage::makeDirectory($filePath);
47
		$filename = md5(str_random(5)).'.'.$mime_type;
0 ignored issues
show
Deprecated Code introduced by
The function str_random() has been deprecated: Str::random() should be used directly instead. Will be removed in Laravel 6.0. ( Ignorable by Annotation )

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

47
		$filename = md5(/** @scrutinizer ignore-deprecated */ str_random(5)).'.'.$mime_type;

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
48
		if (Storage::put($filePath.'/'.$filename, $filedata)) {
49
		    self::resizeImage($filePath.'/'.$filename);
50
51
		    return $filePath.'/'.$filename;
52
		}
53
        }
54
    }
55
56
    public static function uploadFile($name, $encrypt = false, $resize_width = null, $resize_height = null, $id = null)
57
    {
58
        if (Request::hasFile($name)) {
59
            if (! self::myId()) {
60
                $userID = 0;
61
            } else {
62
                $userID = self::myId();
63
            }
64
65
            if ($id) {
66
                $userID = $id;
67
            }
68
69
            $file = Request::file($name);
70
            $ext = $file->getClientOriginalExtension();
71
            $filename = str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
0 ignored issues
show
Deprecated Code introduced by
The function str_slug() has been deprecated: Str::slug() should be used directly instead. Will be removed in Laravel 6.0. ( Ignorable by Annotation )

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

71
            $filename = /** @scrutinizer ignore-deprecated */ str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
72
            $filesize = $file->getClientSize() / 1024;
0 ignored issues
show
Unused Code introduced by
The assignment to $filesize is dead and can be removed.
Loading history...
Deprecated Code introduced by
The function Symfony\Component\HttpFo...edFile::getClientSize() has been deprecated: since Symfony 4.1, use getSize() instead. ( Ignorable by Annotation )

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

72
            $filesize = /** @scrutinizer ignore-deprecated */ $file->getClientSize() / 1024;

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
73
            $file_path = 'uploads/'.$userID.'/'.date('Y-m');
74
75
            //Create Directory Monthly
76
            Storage::makeDirectory($file_path);
77
78
            if ($encrypt == true) {
79
                $filename = md5(str_random(5)).'.'.$ext;
0 ignored issues
show
Deprecated Code introduced by
The function str_random() has been deprecated: Str::random() should be used directly instead. Will be removed in Laravel 6.0. ( Ignorable by Annotation )

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

79
                $filename = md5(/** @scrutinizer ignore-deprecated */ str_random(5)).'.'.$ext;

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
80
            } else {
81
                $filename = str_slug($filename, '_').'.'.$ext;
0 ignored issues
show
Deprecated Code introduced by
The function str_slug() has been deprecated: Str::slug() should be used directly instead. Will be removed in Laravel 6.0. ( Ignorable by Annotation )

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

81
                $filename = /** @scrutinizer ignore-deprecated */ str_slug($filename, '_').'.'.$ext;

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
82
            }
83
84
            if (Storage::putFileAs($file_path, $file, $filename)) {
85
                self::resizeImage($file_path.'/'.$filename, $resize_width, $resize_height);
86
87
                return $file_path.'/'.$filename;
88
            } else {
89
                return null;
90
            }
91
        } else {
92
            return null;
93
        }
94
    }
95
96
    private static function resizeImage($fullFilePath, $resize_width = null, $resize_height = null, $qty = 100, $thumbQty = 75)
97
    {
98
        $images_ext = config('crudbooster.IMAGE_EXTENSIONS', 'jpg,png,gif,bmp');
99
        $images_ext = explode(',', $images_ext);
100
101
        $filename = basename($fullFilePath);
102
        $file_path = trim(str_replace($filename, '', $fullFilePath), '/');
103
104
        $file_path_thumbnail = 'uploads_thumbnail/'.date('Y-m');
105
        Storage::makeDirectory($file_path_thumbnail);
106
107
        if (in_array(strtolower($ext), $images_ext)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ext seems to be never defined.
Loading history...
108
109
            if ($resize_width && $resize_height) {
110
                $img = Image::make(storage_path('app/'.$file_path.'/'.$filename));
111
                $img->fit($resize_width, $resize_height);
112
                $img->save(storage_path('app/'.$file_path.'/'.$filename), $qty);
113
            } elseif ($resize_width && ! $resize_height) {
114
                $img = Image::make(storage_path('app/'.$file_path.'/'.$filename));
115
                $img->resize($resize_width, null, function ($constraint) {
116
                    $constraint->aspectRatio();
117
                });
118
                $img->save(storage_path('app/'.$file_path.'/'.$filename), $qty);
119
            } elseif (! $resize_width && $resize_height) {
120
                $img = Image::make(storage_path('app/'.$file_path.'/'.$filename));
121
                $img->resize(null, $resize_height, function ($constraint) {
122
                    $constraint->aspectRatio();
123
                });
124
                $img->save(storage_path('app/'.$file_path.'/'.$filename), $qty);
125
            } else {
126
                $img = Image::make(storage_path('app/'.$file_path.'/'.$filename));
127
                if ($img->width() > 1300) {
128
                    $img->resize(1300, null, function ($constraint) {
129
                        $constraint->aspectRatio();
130
                    });
131
                }
132
                $img->save(storage_path('app/'.$file_path.'/'.$filename), $qty);
133
            }
134
135
            $img = Image::make(storage_path('app/'.$file_path.'/'.$filename));
136
            $img->fit(350, 350);
137
            $img->save(storage_path('app/'.$file_path_thumbnail.'/'.$filename), $thumbQty);
138
        }
139
    }
140
141
    public static function getSetting($name)
142
    {
143
        if (Cache::has('setting_'.$name)) {
144
            return Cache::get('setting_'.$name);
145
        }
146
147
        $query = DB::table('cms_settings')->where('name', $name)->first();
148
        Cache::forever('setting_'.$name, $query->content);
149
150
        return $query->content;
151
    }
152
153
    public static function insert($table, $data = [])
154
    {
155
        $data['id'] = DB::table($table)->max('id') + 1;
156
        if (! $data['created_at']) {
157
            if (Schema::hasColumn($table, 'created_at')) {
158
                $data['created_at'] = date('Y-m-d H:i:s');
159
            }
160
        }
161
162
        if (DB::table($table)->insert($data)) {
163
            return $data['id'];
164
        } else {
165
            return false;
166
        }
167
    }
168
169
    public static function first($table, $id)
170
    {
171
        $table = self::parseSqlTable($table)['table'];
172
        if (is_array($id)) {
173
            $first = DB::table($table);
174
            foreach ($id as $k => $v) {
175
                $first->where($k, $v);
176
            }
177
178
            return $first->first();
179
        } else {
180
            $pk = self::pk($table);
181
182
            return DB::table($table)->where($pk, $id)->first();
183
        }
184
    }
185
186
    public static function get($table, $string_conditions = null, $orderby = null, $limit = null, $skip = null)
187
    {
188
        $table = self::parseSqlTable($table);
189
        $table = $table['table'];
190
        $query = DB::table($table);
191
        if ($string_conditions) {
192
            $query->whereraw($string_conditions);
193
        }
194
        if ($orderby) {
195
            $query->orderbyraw($orderby);
196
        }
197
        if ($limit) {
198
            $query->take($limit);
199
        }
200
        if ($skip) {
201
            $query->skip($skip);
202
        }
203
204
        return $query->get();
205
    }
206
207
    public static function me()
208
    {
209
        return DB::table(config('crudbooster.USER_TABLE'))->where('id', Session::get('admin_id'))->first();
210
    }
211
212
    public static function myId()
213
    {
214
        return Session::get('admin_id');
215
    }
216
217
    public static function isSuperadmin()
218
    {
219
        return Session::get('admin_is_superadmin');
220
    }
221
222
    public static function myName()
223
    {
224
        return Session::get('admin_name');
225
    }
226
227
    public static function myPhoto()
228
    {
229
        return Session::get('admin_photo');
230
    }
231
232
    public static function myPrivilege()
233
    {
234
        $roles = Session::get('admin_privileges_roles');
235
        if ($roles) {
236
            foreach ($roles as $role) {
237
                if ($role->path == CRUDBooster::getModulePath()) {
238
                    return $role;
239
                }
240
            }
241
        }
242
    }
243
244
    public static function myPrivilegeId()
245
    {
246
        return Session::get('admin_privileges');
247
    }
248
249
    public static function myPrivilegeName()
250
    {
251
        return Session::get('admin_privileges_name');
252
    }
253
254
    public static function isLocked()
255
    {
256
        return Session::get('admin_lock');
257
    }
258
259
    public static function redirectBack($message, $type = 'warning')
260
    {
261
262
        if (Request::ajax()) {
263
            $resp = response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $_SERVER['HTTP_REFERER']])->send();
0 ignored issues
show
Unused Code introduced by
The assignment to $resp is dead and can be removed.
Loading history...
264
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
265
        } else {
266
            $resp = redirect()->back()->with(['message' => $message, 'message_type' => $type]);
267
            Session::driver()->save();
268
            $resp->send();
269
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
270
        }
271
    }
272
273
    public static function redirect($to, $message, $type = 'warning')
274
    {
275
276
        if (Request::ajax()) {
277
            $resp = response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $to])->send();
0 ignored issues
show
Unused Code introduced by
The assignment to $resp is dead and can be removed.
Loading history...
278
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
279
        } else {
280
            $resp = redirect($to)->with(['message' => $message, 'message_type' => $type]);
281
            Session::driver()->save();
282
            $resp->send();
283
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
284
        }
285
    }
286
287
    public static function isView()
288
    {
289
        if (self::isSuperadmin()) {
290
            return true;
291
        }
292
293
        $session = Session::get('admin_privileges_roles');
294
        foreach ($session as $v) {
295
            if ($v->path == self::getModulePath()) {
296
                return (bool) $v->is_visible;
297
            }
298
        }
299
    }
300
301
    public static function isUpdate()
302
    {
303
        if (self::isSuperadmin()) {
304
            return true;
305
        }
306
307
        $session = Session::get('admin_privileges_roles');
308
        foreach ($session as $v) {
309
            if ($v->path == self::getModulePath()) {
310
                return (bool) $v->is_edit;
311
            }
312
        }
313
    }
314
315
    public static function isCreate()
316
    {
317
        if (self::isSuperadmin()) {
318
            return true;
319
        }
320
321
        $session = Session::get('admin_privileges_roles');
322
        foreach ($session as $v) {
323
            if ($v->path == self::getModulePath()) {
324
                return (bool) $v->is_create;
325
            }
326
        }
327
    }
328
329
    public static function isRead()
330
    {
331
        if (self::isSuperadmin()) {
332
            return true;
333
        }
334
335
        $session = Session::get('admin_privileges_roles');
336
        foreach ($session as $v) {
337
            if ($v->path == self::getModulePath()) {
338
                return (bool) $v->is_read;
339
            }
340
        }
341
    }
342
343
    public static function isDelete()
344
    {
345
        if (self::isSuperadmin()) {
346
            return true;
347
        }
348
349
        $session = Session::get('admin_privileges_roles');
350
        foreach ($session as $v) {
351
            if ($v->path == self::getModulePath()) {
352
                return (bool) $v->is_delete;
353
            }
354
        }
355
    }
356
357
    public static function isCRUD()
358
    {
359
        if (self::isSuperadmin()) {
360
            return true;
361
        }
362
363
        $session = Session::get('admin_privileges_roles');
364
        foreach ($session as $v) {
365
            if ($v->path == self::getModulePath()) {
366
                if ($v->is_visible && $v->is_create && $v->is_read && $v->is_edit && $v->is_delete) {
367
                    return true;
368
                } else {
369
                    return false;
370
                }
371
            }
372
        }
373
    }
374
375
    public static function getCurrentModule()
376
    {
377
	$modulepath = self::getModulePath();
378
379
	if (Cache::has('moduls_'.$modulepath)) {
380
	    return Cache::get('moduls_'.$modulepath);
381
	} else {
382
383
	    $module = DB::table('cms_moduls')->where('path', self::getModulePath())->first();
384
	    
385
	    //supply modulpath instead of $module incase where user decides to create form and custom url that does not exist in cms_moduls table.
386
	    return ($module)?:$modulepath; 
387
	}
388
    }
389
390
    public static function getCurrentDashboardId()
391
    {
392
        if (Request::get('d') != null) {
393
            Session::put('currentDashboardId', Request::get('d'));
394
            Session::put('currentMenuId', 0);
395
396
            return Request::get('d');
397
        } else {
398
            return Session::get('currentDashboardId');
399
        }
400
    }
401
402
    public static function getCurrentMenuId()
403
    {
404
        if (Request::get('m') != null) {
405
            Session::put('currentMenuId', Request::get('m'));
406
            Session::put('currentDashboardId', 0);
407
408
            return Request::get('m');
409
        } else {
410
            return Session::get('currentMenuId');
411
        }
412
    }
413
414
    public static function sidebarDashboard()
415
    {
416
417
        $menu = DB::table('cms_menus')->whereRaw("cms_menus.id IN (select id_cms_menus from cms_menus_privileges where id_cms_privileges = '".self::myPrivilegeId()."')")->where('is_dashboard', 1)->where('is_active', 1)->first();
418
419
        switch ($menu->type) {
420
            case 'Route':
421
                $url = route($menu->path);
422
                break;
423
            default:
424
            case 'URL':
425
                $url = $menu->path;
426
                break;
427
            case 'Controller & Method':
428
                $url = action($menu->path);
429
                break;
430
            case 'Module':
431
            case 'Statistic':
432
                $url = self::adminPath($menu->path);
433
                break;
434
        }
435
436
        @$menu->url = $url;
437
438
        return $menu;
439
    }
440
441
    public static function sidebarMenu()
442
    {
443
        $menu_active = DB::table('cms_menus')->whereRaw("cms_menus.id IN (select id_cms_menus from cms_menus_privileges where id_cms_privileges = '".self::myPrivilegeId()."')")->where('parent_id', 0)->where('is_active', 1)->where('is_dashboard', 0)->orderby('sorting', 'asc')->select('cms_menus.*')->get();
444
445
        foreach ($menu_active as &$menu) {
446
447
            try {
448
                switch ($menu->type) {
449
                    case 'Route':
450
                        $url = route($menu->path);
451
                        break;
452
                    default:
453
                    case 'URL':
454
                        $url = $menu->path;
455
                        break;
456
                    case 'Controller & Method':
457
                        $url = action($menu->path);
458
                        break;
459
                    case 'Module':
460
                    case 'Statistic':
461
                        $url = self::adminPath($menu->path);
462
                        break;
463
                }
464
465
                $menu->is_broken = false;
466
            } catch (\Exception $e) {
467
                $url = "#";
468
                $menu->is_broken = true;
469
            }
470
471
            $menu->url = $url;
472
            $menu->url_path = trim(str_replace(url('/'), '', $url), "/");
473
474
            $child = DB::table('cms_menus')->whereRaw("cms_menus.id IN (select id_cms_menus from cms_menus_privileges where id_cms_privileges = '".self::myPrivilegeId()."')")->where('is_dashboard', 0)->where('is_active', 1)->where('parent_id', $menu->id)->select('cms_menus.*')->orderby('sorting', 'asc')->get();
475
            if (count($child)) {
476
477
                foreach ($child as &$c) {
478
479
                    try {
480
                        switch ($c->type) {
481
                            case 'Route':
482
                                $url = route($c->path);
483
                                break;
484
                            default:
485
                            case 'URL':
486
                                $url = $c->path;
487
                                break;
488
                            case 'Controller & Method':
489
                                $url = action($c->path);
490
                                break;
491
                            case 'Module':
492
                            case 'Statistic':
493
                                $url = self::adminPath($c->path);
494
                                break;
495
                        }
496
                        $c->is_broken = false;
497
                    } catch (\Exception $e) {
498
                        $url = "#";
499
                        $c->is_broken = true;
500
                    }
501
502
                    $c->url = $url;
503
                    $c->url_path = trim(str_replace(url('/'), '', $url), "/");
504
                }
505
506
                $menu->children = $child;
507
            }
508
        }
509
510
        return $menu_active;
511
    }
512
513
    public static function deleteConfirm($redirectTo)
514
    {
515
        echo "swal({   
516
				title: \"".trans('crudbooster.delete_title_confirm')."\",   
0 ignored issues
show
Bug introduced by
Are you sure trans('crudbooster.delete_title_confirm') of type 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

516
				title: \""./** @scrutinizer ignore-type */ trans('crudbooster.delete_title_confirm')."\",   
Loading history...
517
				text: \"".trans('crudbooster.delete_description_confirm')."\",   
0 ignored issues
show
Bug introduced by
Are you sure trans('crudbooster.delete_description_confirm') of type 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

517
				text: \""./** @scrutinizer ignore-type */ trans('crudbooster.delete_description_confirm')."\",   
Loading history...
518
				type: \"warning\",   
519
				showCancelButton: true,   
520
				confirmButtonColor: \"#ff0000\",   
521
				confirmButtonText: \"".trans('crudbooster.confirmation_yes')."\",  
0 ignored issues
show
Bug introduced by
Are you sure trans('crudbooster.confirmation_yes') of type 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

521
				confirmButtonText: \""./** @scrutinizer ignore-type */ trans('crudbooster.confirmation_yes')."\",  
Loading history...
522
				cancelButtonText: \"".trans('crudbooster.confirmation_no')."\",  
0 ignored issues
show
Bug introduced by
Are you sure trans('crudbooster.confirmation_no') of type 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

522
				cancelButtonText: \""./** @scrutinizer ignore-type */ trans('crudbooster.confirmation_no')."\",  
Loading history...
523
				closeOnConfirm: false }, 
524
				function(){  location.href=\"$redirectTo\" });";
525
    }
526
527
    public static function getModulePath()
528
    {
529
          // Check to position of admin_path
530
          if(config("crudbooster.ADMIN_PATH")) {
531
              $adminPathSegments = explode('/', Request::path());
532
              $no = 1;
533
              foreach($adminPathSegments as $path) {
534
                  if($path == config("crudbooster.ADMIN_PATH")) {
535
                      $segment = $no+1;
536
                      break;
537
                  }
538
                  $no++;
539
              }
540
          } else {
541
              $segment = 1;
542
          }
543
544
          return Request::segment($segment);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $segment does not seem to be defined for all execution paths leading up to this point.
Loading history...
545
    }	
546
547
    public static function mainpath($path = null)
548
    {
549
550
        $controllername = str_replace(["\crocodicstudio\crudbooster\controllers\\", "App\Http\Controllers\\"], "", strtok(Route::currentRouteAction(), '@'));
551
        $route_url = route($controllername.'GetIndex');
552
553
        if ($path) {
554
            if (substr($path, 0, 1) == '?') {
555
                return trim($route_url, '/').$path;
556
            } else {
557
                return $route_url.'/'.$path;
558
            }
559
        } else {
560
            return trim($route_url, '/');
561
        }
562
    }
563
564
    public static function adminPath($path = null)
565
    {
566
        return url(config('crudbooster.ADMIN_PATH').'/'.$path);
567
    }
568
569
    public static function getCurrentId()
570
    {
571
        $id = Session::get('current_row_id');
572
        $id = intval($id);
573
        $id = (! $id) ? Request::segment(4) : $id;
574
        $id = intval($id);
575
576
        return $id;
577
    }
578
579
    public static function getCurrentMethod()
580
    {
581
        $action = str_replace("App\Http\Controllers", "", Route::currentRouteAction());
582
        $atloc = strpos($action, '@') + 1;
583
        $method = substr($action, $atloc);
584
585
        return $method;
586
    }
587
588
    public static function clearCache($name)
589
    {
590
        if (Cache::forget($name)) {
591
            return true;
592
        } else {
593
            return false;
594
        }
595
    }
596
597
    public static function isColumnNULL($table, $field)
598
    {
599
        if (Cache::has('field_isNull_'.$table.'_'.$field)) {
600
            return Cache::get('field_isNull_'.$table.'_'.$field);
601
        }
602
603
        try {
604
            //MySQL & SQL Server
605
            $isNULL = DB::select(DB::raw("select IS_NULLABLE from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='$table' and COLUMN_NAME = '$field'"))[0]->IS_NULLABLE;
606
            $isNULL = ($isNULL == 'YES') ? true : false;
607
            Cache::forever('field_isNull_'.$table.'_'.$field, $isNULL);
608
        } catch (\Exception $e) {
609
            $isNULL = false;
610
            Cache::forever('field_isNull_'.$table.'_'.$field, $isNULL);
611
        }
612
613
        return $isNULL;
614
    }
615
616
    public static function getFieldType($table, $field)
617
    {
618
        if (Cache::has('field_type_'.$table.'_'.$field)) {
619
            return Cache::get('field_type_'.$table.'_'.$field);
620
        }
621
622
        $typedata = Cache::rememberForever('field_type_'.$table.'_'.$field, function () use ($table, $field) {
623
624
            try {
625
                //MySQL & SQL Server
626
                $typedata = DB::select(DB::raw("select DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='$table' and COLUMN_NAME = '$field'"))[0]->DATA_TYPE;
627
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
628
629
            }
630
631
            if (! $typedata) {
632
                $typedata = 'varchar';
633
            }
634
635
            return $typedata;
636
        });
637
638
        return $typedata;
639
    }
640
641
    public static function getValueFilter($field)
642
    {
643
        $filter = Request::get('filter_column');
644
        if ($filter[$field]) {
645
            return $filter[$field]['value'];
646
        }
647
    }
648
649
    public static function getSortingFilter($field)
650
    {
651
        $filter = Request::get('filter_column');
652
        if ($filter[$field]) {
653
            return $filter[$field]['sorting'];
654
        }
655
    }
656
657
    public static function getTypeFilter($field)
658
    {
659
        $filter = Request::get('filter_column');
660
        if ($filter[$field]) {
661
            return $filter[$field]['type'];
662
        }
663
    }
664
665
    public static function stringBetween($string, $start, $end)
666
    {
667
        $string = ' '.$string;
668
        $ini = strpos($string, $start);
669
        if ($ini == 0) {
670
            return '';
671
        }
672
        $ini += strlen($start);
673
        $len = strpos($string, $end, $ini) - $ini;
674
675
        return substr($string, $ini, $len);
676
    }
677
678
    public static function timeAgo($datetime_to, $datetime_from = null, $full = false)
679
    {
680
        $datetime_from = ($datetime_from) ?: date('Y-m-d H:i:s');
681
        $now = new \DateTime;
682
        if ($datetime_from != '') {
683
            $now = new \DateTime($datetime_from);
684
        }
685
        $ago = new \DateTime($datetime_to);
686
        $diff = $now->diff($ago);
687
688
        $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...
689
        $diff->d -= $diff->w * 7;
690
691
        $string = [
692
            'y' => 'year',
693
            'm' => 'month',
694
            'w' => 'week',
695
            'd' => 'day',
696
            'h' => 'hour',
697
            'i' => 'minute',
698
            's' => 'second',
699
        ];
700
        foreach ($string as $k => &$v) {
701
            if ($diff->$k) {
702
                $v = $diff->$k.' '.$v.($diff->$k > 1 ? 's' : '');
703
            } else {
704
                unset($string[$k]);
705
            }
706
        }
707
708
        if (! $full) {
709
            $string = array_slice($string, 0, 1);
710
        }
711
712
        return $string ? implode(', ', $string).' ' : 'just now';
713
    }
714
715
    public static function sendEmailQueue($queue)
716
    {
717
        \Config::set('mail.driver', self::getSetting('smtp_driver'));
718
        \Config::set('mail.host', self::getSetting('smtp_host'));
719
        \Config::set('mail.port', self::getSetting('smtp_port'));
720
        \Config::set('mail.username', self::getSetting('smtp_username'));
721
        \Config::set('mail.password', self::getSetting('smtp_password'));
722
723
        $html = $queue->email_content;
724
        $to = $queue->email_recipient;
725
        $subject = $queue->email_subject;
726
        $from_email = $queue->email_from_email;
727
        $from_name = $queue->email_from_name;
728
        $cc_email = $queue->email_cc_email;
729
        $attachments = unserialize($queue->email_attachments);
730
731
        \Mail::send("crudbooster::emails.blank", ['content' => $html], function ($message) use (
732
            $html,
0 ignored issues
show
Unused Code introduced by
The import $html is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
733
            $to,
734
            $subject,
735
            $from_email,
736
            $from_name,
737
            $cc_email,
738
            $attachments
739
        ) {
740
            $message->priority(1);
741
            $message->to($to);
742
            $message->from($from_email, $from_name);
743
            $message->cc($cc_email);
744
745
            if (count($attachments)) {
746
                foreach ($attachments as $attachment) {
747
                    $message->attach($attachment);
748
                }
749
            }
750
751
            $message->subject($subject);
752
        });
753
    }
754
755
    public static function sendEmail($config = [])
756
    {
757
758
        \Config::set('mail.driver', self::getSetting('smtp_driver'));
759
        \Config::set('mail.host', self::getSetting('smtp_host'));
760
        \Config::set('mail.port', self::getSetting('smtp_port'));
761
        \Config::set('mail.username', self::getSetting('smtp_username'));
762
        \Config::set('mail.password', self::getSetting('smtp_password'));
763
764
        $to = $config['to'];
765
        $data = $config['data'];
766
        $template = $config['template'];
767
768
        $template = CRUDBooster::first('cms_email_templates', ['slug' => $template]);
769
        $html = $template->content;
770
        foreach ($data as $key => $val) {
771
            $html = str_replace('['.$key.']', $val, $html);
772
            $template->subject = str_replace('['.$key.']', $val, $template->subject);
773
        }
774
        $subject = $template->subject;
775
        $attachments = ($config['attachments']) ?: [];
776
777
        if ($config['send_at'] != null) {
778
            $a = [];
779
            $a['send_at'] = $config['send_at'];
780
            $a['email_recipient'] = $to;
781
            $a['email_from_email'] = $template->from_email ?: CRUDBooster::getSetting('email_sender');
782
            $a['email_from_name'] = $template->from_name ?: CRUDBooster::getSetting('appname');
783
            $a['email_cc_email'] = $template->cc_email;
784
            $a['email_subject'] = $subject;
785
            $a['email_content'] = $html;
786
            $a['email_attachments'] = serialize($attachments);
787
            $a['is_sent'] = 0;
788
            DB::table('cms_email_queues')->insert($a);
789
790
            return true;
791
        }
792
793
        \Mail::send("crudbooster::emails.blank", ['content' => $html], function ($message) use ($to, $subject, $template, $attachments) {
794
            $message->priority(1);
795
            $message->to($to);
796
797
            if ($template->from_email) {
798
                $from_name = ($template->from_name) ?: CRUDBooster::getSetting('appname');
799
                $message->from($template->from_email, $from_name);
800
            }
801
802
            if ($template->cc_email) {
803
                $message->cc($template->cc_email);
804
            }
805
806
            if (count($attachments)) {
807
                foreach ($attachments as $attachment) {
808
                    $message->attach($attachment);
809
                }
810
            }
811
812
            $message->subject($subject);
813
        });
814
    }
815
816
    public static function valid($arr = [], $type = 'json')
817
    {
818
        $input_arr = Request::all();
819
820
        foreach ($arr as $a => $b) {
821
            if (is_int($a)) {
822
                $arr[$b] = 'required';
823
            } else {
824
                $arr[$a] = $b;
825
            }
826
        }
827
828
        $validator = Validator::make($input_arr, $arr);
829
830
        if ($validator->fails()) {
831
            $message = $validator->errors()->all();
832
833
            if ($type == 'json') {
834
                $result = [];
835
                $result['api_status'] = 0;
836
                $result['api_message'] = implode(', ', $message);
837
                $res = response()->json($result, 200);
838
                $res->send();
839
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
840
            } else {
841
                $res = redirect()->back()->with(['message' => implode('<br/>', $message), 'message_type' => 'warning'])->withInput();
842
                \Session::driver()->save();
843
                $res->send();
844
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
845
            }
846
        }
847
    }
848
849
    public static function parseSqlTable($table)
850
    {
851
852
        $f = explode('.', $table);
853
854
        if (count($f) == 1) {
855
            return ["table" => $f[0], "database" => config('crudbooster.MAIN_DB_DATABASE')];
856
        } elseif (count($f) == 2) {
857
            return ["database" => $f[0], "table" => $f[1]];
858
        } elseif (count($f) == 3) {
859
            return ["table" => $f[0], "schema" => $f[1], "table" => $f[2]];
860
        }
861
862
        return false;
863
    }
864
865
    public static function putCache($section, $cache_name, $cache_value)
866
    {
867
        if (Cache::has($section)) {
868
            $cache_open = Cache::get($section);
869
        } else {
870
            Cache::forever($section, []);
871
            $cache_open = Cache::get($section);
872
        }
873
        $cache_open[$cache_name] = $cache_value;
874
        Cache::forever($section, $cache_open);
875
876
        return true;
877
    }
878
879
    public static function getCache($section, $cache_name)
880
    {
881
882
        if (Cache::has($section)) {
883
            $cache_open = Cache::get($section);
884
885
            return $cache_open[$cache_name];
886
        } else {
887
            return false;
888
        }
889
    }
890
891
    public static function flushCache()
892
    {
893
        Cache::flush();
894
    }
895
896
    public static function forgetCache($section, $cache_name)
897
    {
898
        if (Cache::has($section)) {
899
            $open = Cache::get($section);
900
            unset($open[$cache_name]);
901
            Cache::forever($section, $open);
902
903
            return true;
904
        } else {
905
            return false;
906
        }
907
    }
908
909
    public static function pk($table)
910
    {
911
        return self::findPrimaryKey($table);
912
    }
913
914
//     public static function findPrimaryKey($table)
915
//     {
916
//         if (! $table) {
917
//             return 'id';
918
//         }
919
920
//         if (self::getCache('table_'.$table, 'primary_key')) {
921
//             return self::getCache('table_'.$table, 'primary_key');
922
//         }
923
//         $table = CRUDBooster::parseSqlTable($table);
924
925
//         if (! $table['table']) {
926
//             throw new \Exception("parseSqlTable can't determine the table");
927
//         }
928
//         $query = config('database.connections.'.config('database.default').'.driver') == 'pgsql' ? "select * from information_schema.key_column_usage WHERE TABLE_NAME = '$table[table]'" : "select * from information_schema.COLUMNS where TABLE_SCHEMA = '$table[database]' and TABLE_NAME = '$table[table]' and COLUMN_KEY = 'PRI'";
929
//         $keys = DB::select($query);
930
//         $primary_key = $keys[0]->COLUMN_NAME;
931
//         if ($primary_key) {
932
//             self::putCache('table_'.$table, 'primary_key', $primary_key);
933
934
//             return $primary_key;
935
//         } else {
936
//             return 'id';
937
//         }
938
//     }
939
940
	public static function findPrimaryKey($table)
941
	{
942
		if(!$table)
943
		{
944
			return 'id';
945
		}
946
		
947
		$pk = DB::getDoctrineSchemaManager()->listTableDetails($table)->getPrimaryKey();
948
		if(!$pk) {
949
		    return null;
950
		}
951
		return $pk->getColumns()[0];	
952
	}
953
954
    public static function newId($table)
955
    {
956
        $key = CRUDBooster::findPrimaryKey($table);
957
        $id = DB::table($table)->max($key) + 1;
958
959
        return $id;
960
    }
961
962
    public static function isColumnExists($table, $field)
963
    {
964
965
        if (! $table) {
966
            throw new Exception("\$table is empty !", 1);
0 ignored issues
show
Bug introduced by
The type crocodicstudio\crudbooster\helpers\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
967
        }
968
        if (! $field) {
969
            throw new Exception("\$field is empty !", 1);
970
        }
971
972
        $table = CRUDBooster::parseSqlTable($table);
973
974
        // if(self::getCache('table_'.$table,'column_'.$field)) {
975
        // 	return self::getCache('table_'.$table,'column_'.$field);
976
        // }
977
978
        if (Schema::hasColumn($table['table'], $field)) {
979
            // self::putCache('table_'.$table,'column_'.$field,1);
980
            return true;
981
        } else {
982
            // self::putCache('table_'.$table,'column_'.$field,0);
983
            return false;
984
        }
985
    }
986
987
    public static function getForeignKey($parent_table, $child_table)
988
    {
989
        $parent_table = CRUDBooster::parseSqlTable($parent_table)['table'];
990
        $child_table = CRUDBooster::parseSqlTable($child_table)['table'];
991
        if (Schema::hasColumn($child_table, 'id_'.$parent_table)) {
992
            return 'id_'.$parent_table;
993
        } else {
994
            return $parent_table.'_id';
995
        }
996
    }
997
998
    public static function getTableForeignKey($fieldName)
999
    {
1000
        $table = null;
1001
        if (substr($fieldName, 0, 3) == 'id_') {
1002
            $table = substr($fieldName, 3);
1003
        } elseif (substr($fieldName, -3) == '_id') {
1004
            $table = substr($fieldName, 0, (strlen($fieldName) - 3));
1005
        }
1006
1007
        return $table;
1008
    }
1009
1010
    public static function isForeignKey($fieldName)
1011
    {
1012
        if (substr($fieldName, 0, 3) == 'id_') {
1013
            $table = substr($fieldName, 3);
1014
        } elseif (substr($fieldName, -3) == '_id') {
1015
            $table = substr($fieldName, 0, (strlen($fieldName) - 3));
1016
        }
1017
1018
        if (Cache::has('isForeignKey_'.$fieldName)) {
1019
            return Cache::get('isForeignKey_'.$fieldName);
1020
        } else {
1021
            if ($table) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $table does not seem to be defined for all execution paths leading up to this point.
Loading history...
1022
                $hasTable = Schema::hasTable($table);
1023
                if ($hasTable) {
1024
                    Cache::forever('isForeignKey_'.$fieldName, true);
1025
1026
                    return true;
1027
                } else {
1028
                    Cache::forever('isForeignKey_'.$fieldName, false);
1029
1030
                    return false;
1031
                }
1032
            } else {
1033
                return false;
1034
            }
1035
        }
1036
    }
1037
1038
    public static function urlFilterColumn($key, $type, $value = '', $singleSorting = true)
1039
    {
1040
        $params = Request::all();
1041
        $mainpath = trim(self::mainpath(), '/');
1042
1043
        if ($params['filter_column'] && $singleSorting) {
1044
            foreach ($params['filter_column'] as $k => $filter) {
1045
                foreach ($filter as $t => $val) {
1046
                    if ($t == 'sorting') {
1047
                        unset($params['filter_column'][$k]['sorting']);
1048
                    }
1049
                }
1050
            }
1051
        }
1052
1053
        $params['filter_column'][$key][$type] = $value;
1054
1055
        if (isset($params)) {
1056
            return $mainpath.'?'.http_build_query($params);
1057
        } else {
1058
            return $mainpath.'?filter_column['.$key.']['.$type.']='.$value;
1059
        }
1060
    }
1061
1062
    public static function insertLog($description, $details = '')
1063
    {
1064
        if (CRUDBooster::getSetting('api_debug_mode')) {
1065
            $a = [];
1066
            $a['created_at'] = date('Y-m-d H:i:s');
1067
            $a['ipaddress'] = $_SERVER['REMOTE_ADDR'];
1068
            $a['useragent'] = $_SERVER['HTTP_USER_AGENT'];
1069
            $a['url'] = Request::url();
1070
            $a['description'] = $description;
1071
            $a['details'] = $details;
1072
            $a['id_cms_users'] = self::myId();
1073
            DB::table('cms_logs')->insert($a);
1074
        }
1075
    }
1076
1077
    public static function referer()
1078
    {
1079
        return Request::server('HTTP_REFERER');
1080
    }
1081
1082
    public static function listTables()
1083
    {
1084
        $tables = [];
1085
        $multiple_db = config('crudbooster.MULTIPLE_DATABASE_MODULE');
1086
        $multiple_db = ($multiple_db) ? $multiple_db : [];
1087
        $db_database = config('crudbooster.MAIN_DB_DATABASE');
1088
1089
        if ($multiple_db) {
1090
            try {
1091
                $multiple_db[] = config('crudbooster.MAIN_DB_DATABASE');
1092
                $query_table_schema = implode("','", $multiple_db);
1093
                $tables = DB::select("SELECT CONCAT(TABLE_SCHEMA,'.',TABLE_NAME) FROM INFORMATION_SCHEMA.Tables WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA != 'mysql' AND TABLE_SCHEMA != 'performance_schema' AND TABLE_SCHEMA != 'information_schema' AND TABLE_SCHEMA != 'phpmyadmin' AND TABLE_SCHEMA IN ('$query_table_schema')");
1094
            } catch (\Exception $e) {
1095
                $tables = [];
1096
            }
1097
        } else {
1098
            try {
1099
                $tables = DB::select("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.Tables WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = '".$db_database."'");
1100
            } catch (\Exception $e) {
1101
                $tables = [];
1102
            }
1103
        }
1104
1105
        return $tables;
1106
    }
1107
1108
    public static function getUrlParameters($exception = null)
1109
    {
1110
        @$get = $_GET;
1111
        $inputhtml = '';
1112
1113
        if ($get) {
1114
1115
            if (is_array($exception)) {
1116
                foreach ($exception as $e) {
1117
                    unset($get[$e]);
1118
                }
1119
            }
1120
1121
            $string_parameters = http_build_query($get);
1122
            $string_parameters_array = explode('&', $string_parameters);
1123
            foreach ($string_parameters_array as $s) {
1124
                $part = explode('=', $s);
1125
                $name = urldecode($part[0]);
1126
                $value = urldecode($part[1]);
1127
                if ($name) {
1128
                    $inputhtml .= "<input type='hidden' name='$name' value='$value'/>\n";
1129
                }
1130
            }
1131
        }
1132
1133
        return $inputhtml;
1134
    }
1135
1136
    public static function authAPI()
1137
    {
1138
1139
        $allowedUserAgent = config('crudbooster.API_USER_AGENT_ALLOWED');
1140
        $user_agent = Request::header('User-Agent');
1141
        $time = Request::header('X-Authorization-Time');
1142
1143
        if ($allowedUserAgent && count($allowedUserAgent)) {
1144
            $userAgentValid = false;
1145
            foreach ($allowedUserAgent as $a) {
1146
                if (stripos($user_agent, $a) !== false) {
0 ignored issues
show
Bug introduced by
It seems like $user_agent can also be of type array; however, parameter $haystack of stripos() does only seem to accept string, 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

1146
                if (stripos(/** @scrutinizer ignore-type */ $user_agent, $a) !== false) {
Loading history...
1147
                    $userAgentValid = true;
1148
                    break;
1149
                }
1150
            }
1151
            if ($userAgentValid == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1152
                $result['api_status'] = false;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = array(); before regardless.
Loading history...
1153
                $result['api_message'] = "THE DEVICE AGENT IS INVALID";
1154
                $res = response()->json($result, 200);
1155
                $res->send();
1156
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1157
            }
1158
        }
1159
1160
        if (self::getSetting('api_debug_mode') == 'false') {
1161
1162
            $result = [];
1163
            $validator = Validator::make([
1164
1165
                'X-Authorization-Token' => Request::header('X-Authorization-Token'),
1166
                'X-Authorization-Time' => Request::header('X-Authorization-Time'),
1167
                'useragent' => Request::header('User-Agent'),
1168
            ], [
1169
1170
                    'X-Authorization-Token' => 'required',
1171
                    'X-Authorization-Time' => 'required',
1172
                    'useragent' => 'required',
1173
                ]);
1174
1175
            if ($validator->fails()) {
1176
                $message = $validator->errors()->all();
1177
                $result['api_status'] = 0;
1178
                $result['api_message'] = implode(', ', $message);
1179
                $res = response()->json($result, 200);
1180
                $res->send();
1181
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1182
            }
1183
1184
            $keys = DB::table('cms_apikey')->where('status', 'active')->pluck('screetkey');
1185
            $server_token = [];
1186
            $server_token_screet = [];
1187
            foreach ($keys as $key) {
1188
                $server_token[] = md5($key.$time.$user_agent);
0 ignored issues
show
Bug introduced by
Are you sure $user_agent of type array|null|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

1188
                $server_token[] = md5($key.$time./** @scrutinizer ignore-type */ $user_agent);
Loading history...
Bug introduced by
Are you sure $time of type array|null|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

1188
                $server_token[] = md5($key./** @scrutinizer ignore-type */ $time.$user_agent);
Loading history...
1189
                $server_token_screet[] = $key;
1190
            }
1191
1192
            $sender_token = Request::header('X-Authorization-Token');
1193
1194
            if (! Cache::has($sender_token)) {
0 ignored issues
show
Bug introduced by
It seems like $sender_token can also be of type array; however, parameter $key of Illuminate\Support\Facades\Cache::has() does only seem to accept string, 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

1194
            if (! Cache::has(/** @scrutinizer ignore-type */ $sender_token)) {
Loading history...
1195
                if (! in_array($sender_token, $server_token)) {
1196
                    $result['api_status'] = false;
1197
                    $result['api_message'] = "THE TOKEN IS NOT MATCH WITH SERVER TOKEN";
1198
                    $res = response()->json($result, 200);
1199
                    $res->send();
1200
                    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1201
                }
1202
            } else {
1203
                if (Cache::get($sender_token) != $user_agent) {
0 ignored issues
show
Bug introduced by
It seems like $sender_token can also be of type array; however, parameter $key of Illuminate\Support\Facades\Cache::get() does only seem to accept string, 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

1203
                if (Cache::get(/** @scrutinizer ignore-type */ $sender_token) != $user_agent) {
Loading history...
1204
                    $result['api_status'] = false;
1205
                    $result['api_message'] = "THE TOKEN IS ALREADY BUT NOT MATCH WITH YOUR DEVICE";
1206
                    $res = response()->json($result, 200);
1207
                    $res->send();
1208
                    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1209
                }
1210
            }
1211
1212
            $id = array_search($sender_token, $server_token);
1213
            $server_screet = $server_token_screet[$id];
1214
            DB::table('cms_apikey')->where('screetkey', $server_screet)->increment('hit');
1215
1216
            $expired_token = date('Y-m-d H:i:s', strtotime('+5 seconds'));
1217
            Cache::put($sender_token, $user_agent, $expired_token);
0 ignored issues
show
Bug introduced by
It seems like $sender_token can also be of type array; however, parameter $key of Illuminate\Support\Facades\Cache::put() does only seem to accept string, 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

1217
            Cache::put(/** @scrutinizer ignore-type */ $sender_token, $user_agent, $expired_token);
Loading history...
Bug introduced by
$expired_token of type string is incompatible with the type DateInterval|DateTimeInterface|integer expected by parameter $ttl of Illuminate\Support\Facades\Cache::put(). ( Ignorable by Annotation )

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

1217
            Cache::put($sender_token, $user_agent, /** @scrutinizer ignore-type */ $expired_token);
Loading history...
1218
        }
1219
    }
1220
1221
    public static function sendNotification($config = [])
1222
    {
1223
        $content = $config['content'];
1224
        $to = $config['to'];
1225
        $id_cms_users = $config['id_cms_users'];
1226
        $id_cms_users = ($id_cms_users) ?: [CRUDBooster::myId()];
1227
        foreach ($id_cms_users as $id) {
1228
            $a = [];
1229
            $a['created_at'] = date('Y-m-d H:i:s');
1230
            $a['id_cms_users'] = $id;
1231
            $a['content'] = $content;
1232
            $a['is_read'] = 0;
1233
            $a['url'] = $to;
1234
            DB::table('cms_notifications')->insert($a);
1235
        }
1236
1237
        return true;
1238
    }
1239
1240
    public static function sendFCM($regID = [], $data)
1241
    {
1242
        if (! $data['title'] || ! $data['content']) {
1243
            return 'title , content null !';
1244
        }
1245
1246
        $apikey = CRUDBooster::getSetting('google_fcm_key');
1247
        $url = 'https://fcm.googleapis.com/fcm/send';
1248
        $fields = [
1249
            'registration_ids' => $regID,
1250
            'data' => $data,
1251
            'content_available' => true,
1252
            'notification' => [
1253
                'sound' => 'default',
1254
                'badge' => 0,
1255
                'title' => trim(strip_tags($data['title'])),
1256
                'body' => trim(strip_tags($data['content'])),
1257
            ],
1258
            'priority' => 'high',
1259
        ];
1260
        $headers = [
1261
            'Authorization:key='.$apikey,
1262
            'Content-Type:application/json',
1263
        ];
1264
1265
        $ch = curl_init($url);
1266
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_setopt() does only seem to accept resource, 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

1266
        curl_setopt(/** @scrutinizer ignore-type */ $ch, CURLOPT_HTTPHEADER, $headers);
Loading history...
1267
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
1268
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
1269
        curl_setopt($ch, CURLOPT_POST, 1);
1270
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
1271
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1272
        $chresult = curl_exec($ch);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, 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

1272
        $chresult = curl_exec(/** @scrutinizer ignore-type */ $ch);
Loading history...
1273
        curl_close($ch);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, 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

1273
        curl_close(/** @scrutinizer ignore-type */ $ch);
Loading history...
1274
1275
        return $chresult;
1276
    }
1277
1278
    public static function getTableColumns($table)
1279
    {
1280
        //$cols = DB::getSchemaBuilder()->getColumnListing($table);
1281
        $table = CRUDBooster::parseSqlTable($table);
1282
        $cols = collect(DB::select('SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = :database AND TABLE_NAME = :table', [
1283
            'database' => $table['database'],
1284
            'table' => $table['table'],
1285
        ]))->map(function ($x) {
1286
            return (array) $x;
1287
        })->toArray();
1288
1289
        $result = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
1290
        $result = $cols;
1291
1292
        $new_result = [];
1293
        foreach ($result as $ro) {
1294
            $new_result[] = $ro['COLUMN_NAME'];
1295
        }
1296
1297
        return $new_result;
1298
    }
1299
1300
    public static function getNameTable($columns)
1301
    {
1302
        $name_col_candidate = config('crudbooster.NAME_FIELDS_CANDIDATE');
1303
        $name_col_candidate = explode(',', $name_col_candidate);
1304
        $name_col = '';
1305
        foreach ($columns as $c) {
1306
            foreach ($name_col_candidate as $cc) {
1307
                if (strpos($c, $cc) !== false) {
1308
                    $name_col = $c;
1309
                    break;
1310
                }
1311
            }
1312
            if ($name_col) {
1313
                break;
1314
            }
1315
        }
1316
        if ($name_col == '') {
1317
            $name_col = 'id';
1318
        }
1319
1320
        return $name_col;
1321
    }
1322
1323
    public static function isExistsController($table)
1324
    {
1325
        $controllername = ucwords(str_replace('_', ' ', $table));
1326
        $controllername = str_replace(' ', '', $controllername).'Controller';
1327
        $path = base_path("app/Http/Controllers/");
1328
        $path2 = base_path("app/Http/Controllers/ControllerMaster/");
1329
        if (file_exists($path.'Admin'.$controllername.'.php') || file_exists($path2.'Admin'.$controllername.'.php') || file_exists($path2.$controllername.'.php')) {
1330
            return true;
1331
        } else {
1332
            return false;
1333
        }
1334
    }
1335
1336
    public static function generateAPI($controller_name, $table_name, $permalink, $method_type = 'post')
1337
    {
1338
        $php = '
1339
		<?php namespace App\Http\Controllers;
1340
1341
		use Session;
1342
		use Request;
1343
		use DB;
1344
		use CRUDBooster;
1345
1346
		class Api'.$controller_name.'Controller extends \crocodicstudio\crudbooster\controllers\ApiController {
1347
1348
		    function __construct() {    
1349
				$this->table       = "'.$table_name.'";        
1350
				$this->permalink   = "'.$permalink.'";    
1351
				$this->method_type = "'.$method_type.'";    
1352
		    }
1353
		';
1354
1355
        $php .= "\n".'
1356
		    public function hook_before(&$postdata) {
1357
		        //This method will be execute before run the main process
1358
1359
		    }';
1360
1361
        $php .= "\n".'
1362
		    public function hook_query(&$query) {
1363
		        //This method is to customize the sql query
1364
1365
		    }';
1366
1367
        $php .= "\n".'
1368
		    public function hook_after($postdata,&$result) {
1369
		        //This method will be execute after run the main process
1370
1371
		    }';
1372
1373
        $php .= "\n".'
1374
		}
1375
		';
1376
1377
        $php = trim($php);
1378
        $path = base_path("app/Http/Controllers/");
1379
        file_put_contents($path.'Api'.$controller_name.'Controller.php', $php);
1380
    }
1381
1382
    public static function generateController($table, $name = null)
1383
    {
1384
1385
        $exception = ['id', 'created_at', 'updated_at', 'deleted_at'];
1386
        $image_candidate = explode(',', config('crudbooster.IMAGE_FIELDS_CANDIDATE'));
1387
        $password_candidate = explode(',', config('crudbooster.PASSWORD_FIELDS_CANDIDATE'));
1388
        $phone_candidate = explode(',', config('crudbooster.PHONE_FIELDS_CANDIDATE'));
1389
        $email_candidate = explode(',', config('crudbooster.EMAIL_FIELDS_CANDIDATE'));
1390
        $name_candidate = explode(',', config('crudbooster.NAME_FIELDS_CANDIDATE'));
1391
        $url_candidate = explode(',', config("crudbooster.URL_FIELDS_CANDIDATE"));
1392
1393
        $controllername = ucwords(str_replace('_', ' ', $table));
1394
        $controllername = str_replace(' ', '', $controllername).'Controller';
1395
        if ($name) {
1396
            $controllername = ucwords(str_replace(['_', '-'], ' ', $name));
1397
            $controllername = str_replace(' ', '', $controllername).'Controller';
1398
        }
1399
1400
        $path = base_path("app/Http/Controllers/");
1401
        $countSameFile = count(glob($path.'Admin'.$controllername.'.php'));
0 ignored issues
show
Bug introduced by
It seems like glob($path . 'Admin' . $controllername . '.php') can also be of type false; however, parameter $var of count() does only seem to accept Countable|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

1401
        $countSameFile = count(/** @scrutinizer ignore-type */ glob($path.'Admin'.$controllername.'.php'));
Loading history...
1402
1403
        if ($countSameFile != 0) {
1404
            $suffix = $countSameFile;
1405
            $controllername = ucwords(str_replace(['_', '-'], ' ', $name)).$suffix;
1406
            $controllername = str_replace(' ', '', $controllername).'Controller';
1407
        }
1408
1409
        $coloms = CRUDBooster::getTableColumns($table);
1410
        $name_col = CRUDBooster::getNameTable($coloms);
1411
        $pk = CB::pk($table);
1412
1413
        $button_table_action = 'TRUE';
1414
        $button_action_style = "button_icon";
1415
        $button_add = 'TRUE';
1416
        $button_edit = 'TRUE';
1417
        $button_delete = 'TRUE';
1418
        $button_show = 'TRUE';
1419
        $button_detail = 'TRUE';
1420
        $button_filter = 'TRUE';
1421
        $button_export = 'FALSE';
1422
        $button_import = 'FALSE';
1423
        $button_bulk_action = 'TRUE';
1424
        $global_privilege = 'FALSE';
1425
1426
        $php = '
1427
<?php namespace App\Http\Controllers;
1428
1429
	use Session;
1430
	use Request;
1431
	use DB;
1432
	use CRUDBooster;
1433
1434
	class Admin'.$controllername.' extends \crocodicstudio\crudbooster\controllers\CBController {
1435
1436
	    public function cbInit() {
1437
	    	# START CONFIGURATION DO NOT REMOVE THIS LINE
1438
			$this->table 			   = "'.$table.'";	        
1439
			$this->title_field         = "'.$name_col.'";
1440
			$this->limit               = 20;
1441
			$this->orderby             = "'.$pk.',desc";
1442
			$this->show_numbering      = FALSE;
1443
			$this->global_privilege    = '.$global_privilege.';	        
1444
			$this->button_table_action = '.$button_table_action.';   
1445
			$this->button_action_style = "'.$button_action_style.'";     
1446
			$this->button_add          = '.$button_add.';
1447
			$this->button_delete       = '.$button_delete.';
1448
			$this->button_edit         = '.$button_edit.';
1449
			$this->button_detail       = '.$button_detail.';
1450
			$this->button_show         = '.$button_show.';
1451
			$this->button_filter       = '.$button_filter.';        
1452
			$this->button_export       = '.$button_export.';	        
1453
			$this->button_import       = '.$button_import.';
1454
			$this->button_bulk_action  = '.$button_bulk_action.';	
1455
			$this->sidebar_mode		   = "normal"; //normal,mini,collapse,collapse-mini
1456
			# END CONFIGURATION DO NOT REMOVE THIS LINE						      
1457
1458
			# START COLUMNS DO NOT REMOVE THIS LINE
1459
	        $this->col = [];
1460
	';
1461
        $coloms_col = array_slice($coloms, 0, 8);
1462
        foreach ($coloms_col as $c) {
1463
            $label = str_replace("id_", "", $c);
1464
            $label = ucwords(str_replace("_", " ", $label));
1465
            $label = str_replace('Cms ', '', $label);
1466
            $field = $c;
1467
1468
            if (in_array($field, $exception)) {
1469
                continue;
1470
            }
1471
1472
            if (array_search($field, $password_candidate) !== false) {
1473
                continue;
1474
            }
1475
1476
            if (substr($field, 0, 3) == 'id_') {
1477
                $jointable = str_replace('id_', '', $field);
1478
                $joincols = CRUDBooster::getTableColumns($jointable);
1479
                $joinname = CRUDBooster::getNameTable($joincols);
1480
                $php .= "\t\t".'$this->col[] = array("label"=>"'.$label.'","name"=>"'.$field.'","join"=>"'.$jointable.','.$joinname.'");'."\n";
1481
            } elseif (substr($field, -3) == '_id') {
1482
                $jointable = substr($field, 0, (strlen($field) - 3));
1483
                $joincols = CRUDBooster::getTableColumns($jointable);
1484
                $joinname = CRUDBooster::getNameTable($joincols);
1485
                $php .= "\t\t".'$this->col[] = array("label"=>"'.$label.'","name"=>"'.$field.'","join"=>"'.$jointable.','.$joinname.'");'."\n";
1486
            } else {
1487
                $image = '';
1488
                if (in_array($field, $image_candidate)) {
1489
                    $image = ',"image"=>true';
1490
                }
1491
                $php .= "\t\t".'$this->col[] = array("label"=>"'.$label.'","name"=>"'.$field.'" '.$image.');'."\n";
1492
            }
1493
        }
1494
1495
        $php .= "\n\t\t\t# END COLUMNS DO NOT REMOVE THIS LINE";
1496
1497
        $php .= "\n\t\t\t# START FORM DO NOT REMOVE THIS LINE";
1498
        $php .= "\n\t\t".'$this->form = [];'."\n";
1499
1500
        foreach ($coloms as $c) {
1501
            $attribute = [];
1502
            $validation = [];
1503
            $validation[] = 'required';
1504
            $placeholder = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $placeholder is dead and can be removed.
Loading history...
1505
            $help = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $help is dead and can be removed.
Loading history...
1506
1507
            $label = str_replace("id_", "", $c);
1508
            $label = ucwords(str_replace("_", " ", $label));
1509
            $field = $c;
1510
1511
            if (in_array($field, $exception)) {
1512
                continue;
1513
            }
1514
1515
            $typedata = CRUDBooster::getFieldType($table, $field);
1516
1517
            switch ($typedata) {
1518
                default:
1519
                case 'varchar':
1520
                case 'char':
1521
                    $type = "text";
1522
                    $validation[] = "min:1|max:255";
1523
                    break;
1524
                case 'text':
1525
                case 'longtext':
1526
                    $type = 'textarea';
1527
                    $validation[] = "string|min:5|max:5000";
1528
                    break;
1529
                case 'date':
1530
                    $type = 'date';
1531
                    $validation[] = "date";
1532
                    break;
1533
                case 'datetime':
1534
                case 'timestamp':
1535
                    $type = 'datetime';
1536
                    $validation[] = "date_format:Y-m-d H:i:s";
1537
                    break;
1538
                case 'time':
1539
                    $type = 'time';
1540
                    $validation[] = 'date_format:H:i:s';
1541
                    break;
1542
                case 'double':
1543
                    $type = 'money';
1544
                    $validation[] = "integer|min:0";
1545
                    break;
1546
                case 'int':
1547
                case 'integer':
1548
                    $type = 'number';
1549
                    $validation[] = 'integer|min:0';
1550
                    break;
1551
            }
1552
1553
            if (substr($field, 0, 3) == 'id_') {
1554
                $jointable = str_replace('id_', '', $field);
1555
                $joincols = CRUDBooster::getTableColumns($jointable);
1556
                $joinname = CRUDBooster::getNameTable($joincols);
1557
                $attribute['datatable'] = $jointable.','.$joinname;
1558
                $type = 'select2';
1559
            }
1560
1561
            if (substr($field, -3) == '_id') {
1562
                $jointable = str_replace('_id', '', $field);
1563
                $joincols = CRUDBooster::getTableColumns($jointable);
1564
                $joinname = CRUDBooster::getNameTable($joincols);
1565
                $attribute['datatable'] = $jointable.','.$joinname;
1566
                $type = 'select2';
1567
            }
1568
1569
            if (substr($field, 0, 3) == 'is_') {
1570
                $type = 'radio';
1571
                $label_field = ucwords(substr($field, 3));
1572
                $validation = ['required|integer'];
1573
                $attribute['dataenum'] = ['1|'.$label_field, '0|Un-'.$label_field];
1574
            }
1575
1576
            if (in_array($field, $password_candidate)) {
1577
                $type = 'password';
1578
                $validation = ['min:3', 'max:32'];
1579
                $attribute['help'] = trans("crudbooster.text_default_help_password");
1580
            }
1581
1582
            if (in_array($field, $image_candidate)) {
1583
                $type = 'upload';
1584
                $attribute['help'] = trans('crudbooster.text_default_help_upload');
1585
                $validation = ['required|image|max:3000'];
1586
            }
1587
1588
            if ($field == 'latitude') {
1589
                $type = 'hidden';
1590
            }
1591
            if ($field == 'longitude') {
1592
                $type = 'hidden';
1593
            }
1594
1595
            if (in_array($field, $phone_candidate)) {
1596
                $type = 'number';
1597
                $validation = ['required', 'numeric'];
1598
                $attribute['placeholder'] = trans('crudbooster.text_default_help_number');
1599
            }
1600
1601
            if (in_array($field, $email_candidate)) {
1602
                $type = 'email';
1603
                $validation[] = 'email|unique:'.$table;
1604
                $attribute['placeholder'] = trans('crudbooster.text_default_help_email');
1605
            }
1606
1607
            if ($type == 'text' && in_array($field, $name_candidate)) {
1608
                $attribute['placeholder'] = trans('crudbooster.text_default_help_text');
1609
                $validation = ['required', 'string', 'min:3', 'max:70'];
1610
            }
1611
1612
            if ($type == 'text' && in_array($field, $url_candidate)) {
1613
                $validation = ['required', 'url'];
1614
                $attribute['placeholder'] = trans('crudbooster.text_default_help_url');
1615
            }
1616
1617
            $validation = implode('|', $validation);
1618
1619
            $php .= "\t\t";
1620
            $php .= '$this->form[] = ["label"=>"'.$label.'","name"=>"'.$field.'","type"=>"'.$type.'","required"=>TRUE';
1621
1622
            if ($validation) {
1623
                $php .= ',"validation"=>"'.$validation.'"';
1624
            }
1625
1626
            if ($attribute) {
1627
                foreach ($attribute as $key => $val) {
1628
                    if (is_bool($val)) {
1629
                        $val = ($val) ? "TRUE" : "FALSE";
1630
                    } else {
1631
                        $val = '"'.$val.'"';
1632
                    }
1633
                    $php .= ',"'.$key.'"=>'.$val;
1634
                }
1635
            }
1636
1637
            $php .= "];\n";
1638
        }
1639
1640
        $php .= "\n\t\t\t# END FORM DO NOT REMOVE THIS LINE";
1641
1642
        $php .= '     
1643
1644
			/* 
1645
	        | ---------------------------------------------------------------------- 
1646
	        | Sub Module
1647
	        | ----------------------------------------------------------------------     
1648
			| @label          = Label of action 
1649
			| @path           = Path of sub module
1650
			| @foreign_key 	  = foreign key of sub table/module
1651
			| @button_color   = Bootstrap Class (primary,success,warning,danger)
1652
			| @button_icon    = Font Awesome Class  
1653
			| @parent_columns = Sparate with comma, e.g : name,created_at
1654
	        | 
1655
	        */
1656
	        $this->sub_module = array();
1657
1658
1659
	        /* 
1660
	        | ---------------------------------------------------------------------- 
1661
	        | Add More Action Button / Menu
1662
	        | ----------------------------------------------------------------------     
1663
	        | @label       = Label of action 
1664
	        | @url         = Target URL, you can use field alias. e.g : [id], [name], [title], etc
1665
	        | @icon        = Font awesome class icon. e.g : fa fa-bars
1666
	        | @color 	   = Default is primary. (primary, warning, succecss, info)     
1667
	        | @showIf 	   = If condition when action show. Use field alias. e.g : [id] == 1
1668
	        | 
1669
	        */
1670
	        $this->addaction = array();
1671
1672
1673
	        /* 
1674
	        | ---------------------------------------------------------------------- 
1675
	        | Add More Button Selected
1676
	        | ----------------------------------------------------------------------     
1677
	        | @label       = Label of action 
1678
	        | @icon 	   = Icon from fontawesome
1679
	        | @name 	   = Name of button 
1680
	        | Then about the action, you should code at actionButtonSelected method 
1681
	        | 
1682
	        */
1683
	        $this->button_selected = array();
1684
1685
	                
1686
	        /* 
1687
	        | ---------------------------------------------------------------------- 
1688
	        | Add alert message to this module at overheader
1689
	        | ----------------------------------------------------------------------     
1690
	        | @message = Text of message 
1691
	        | @type    = warning,success,danger,info        
1692
	        | 
1693
	        */
1694
	        $this->alert        = array();
1695
	                
1696
1697
	        
1698
	        /* 
1699
	        | ---------------------------------------------------------------------- 
1700
	        | Add more button to header button 
1701
	        | ----------------------------------------------------------------------     
1702
	        | @label = Name of button 
1703
	        | @url   = URL Target
1704
	        | @icon  = Icon from Awesome.
1705
	        | 
1706
	        */
1707
	        $this->index_button = array();
1708
1709
1710
1711
	        /* 
1712
	        | ---------------------------------------------------------------------- 
1713
	        | Customize Table Row Color
1714
	        | ----------------------------------------------------------------------     
1715
	        | @condition = If condition. You may use field alias. E.g : [id] == 1
1716
	        | @color = Default is none. You can use bootstrap success,info,warning,danger,primary.        
1717
	        | 
1718
	        */
1719
	        $this->table_row_color = array();     	          
1720
1721
	        
1722
	        /*
1723
	        | ---------------------------------------------------------------------- 
1724
	        | You may use this bellow array to add statistic at dashboard 
1725
	        | ---------------------------------------------------------------------- 
1726
	        | @label, @count, @icon, @color 
1727
	        |
1728
	        */
1729
	        $this->index_statistic = array();
1730
1731
1732
1733
	        /*
1734
	        | ---------------------------------------------------------------------- 
1735
	        | Add javascript at body 
1736
	        | ---------------------------------------------------------------------- 
1737
	        | javascript code in the variable 
1738
	        | $this->script_js = "function() { ... }";
1739
	        |
1740
	        */
1741
	        $this->script_js = NULL;
1742
1743
1744
            /*
1745
	        | ---------------------------------------------------------------------- 
1746
	        | Include HTML Code before index table 
1747
	        | ---------------------------------------------------------------------- 
1748
	        | html code to display it before index table
1749
	        | $this->pre_index_html = "<p>test</p>";
1750
	        |
1751
	        */
1752
	        $this->pre_index_html = null;
1753
	        
1754
	        
1755
	        
1756
	        /*
1757
	        | ---------------------------------------------------------------------- 
1758
	        | Include HTML Code after index table 
1759
	        | ---------------------------------------------------------------------- 
1760
	        | html code to display it after index table
1761
	        | $this->post_index_html = "<p>test</p>";
1762
	        |
1763
	        */
1764
	        $this->post_index_html = null;
1765
	        
1766
	        
1767
	        
1768
	        /*
1769
	        | ---------------------------------------------------------------------- 
1770
	        | Include Javascript File 
1771
	        | ---------------------------------------------------------------------- 
1772
	        | URL of your javascript each array 
1773
	        | $this->load_js[] = asset("myfile.js");
1774
	        |
1775
	        */
1776
	        $this->load_js = array();
1777
	        
1778
	        
1779
	        
1780
	        /*
1781
	        | ---------------------------------------------------------------------- 
1782
	        | Add css style at body 
1783
	        | ---------------------------------------------------------------------- 
1784
	        | css code in the variable 
1785
	        | $this->style_css = ".style{....}";
1786
	        |
1787
	        */
1788
	        $this->style_css = NULL;
1789
	        
1790
	        
1791
	        
1792
	        /*
1793
	        | ---------------------------------------------------------------------- 
1794
	        | Include css File 
1795
	        | ---------------------------------------------------------------------- 
1796
	        | URL of your css each array 
1797
	        | $this->load_css[] = asset("myfile.css");
1798
	        |
1799
	        */
1800
	        $this->load_css = array();
1801
	        
1802
	        
1803
	    }
1804
1805
1806
	    /*
1807
	    | ---------------------------------------------------------------------- 
1808
	    | Hook for button selected
1809
	    | ---------------------------------------------------------------------- 
1810
	    | @id_selected = the id selected
1811
	    | @button_name = the name of button
1812
	    |
1813
	    */
1814
	    public function actionButtonSelected($id_selected,$button_name) {
1815
	        //Your code here
1816
	            
1817
	    }
1818
1819
1820
	    /*
1821
	    | ---------------------------------------------------------------------- 
1822
	    | Hook for manipulate query of index result 
1823
	    | ---------------------------------------------------------------------- 
1824
	    | @query = current sql query 
1825
	    |
1826
	    */
1827
	    public function hook_query_index(&$query) {
1828
	        //Your code here
1829
	            
1830
	    }
1831
1832
	    /*
1833
	    | ---------------------------------------------------------------------- 
1834
	    | Hook for manipulate row of index table html 
1835
	    | ---------------------------------------------------------------------- 
1836
	    |
1837
	    */    
1838
	    public function hook_row_index($column_index,&$column_value) {	        
1839
	    	//Your code here
1840
	    }
1841
1842
	    /*
1843
	    | ---------------------------------------------------------------------- 
1844
	    | Hook for manipulate data input before add data is execute
1845
	    | ---------------------------------------------------------------------- 
1846
	    | @arr
1847
	    |
1848
	    */
1849
	    public function hook_before_add(&$postdata) {        
1850
	        //Your code here
1851
1852
	    }
1853
1854
	    /* 
1855
	    | ---------------------------------------------------------------------- 
1856
	    | Hook for execute command after add public static function called 
1857
	    | ---------------------------------------------------------------------- 
1858
	    | @id = last insert id
1859
	    | 
1860
	    */
1861
	    public function hook_after_add($id) {        
1862
	        //Your code here
1863
1864
	    }
1865
1866
	    /* 
1867
	    | ---------------------------------------------------------------------- 
1868
	    | Hook for manipulate data input before update data is execute
1869
	    | ---------------------------------------------------------------------- 
1870
	    | @postdata = input post data 
1871
	    | @id       = current id 
1872
	    | 
1873
	    */
1874
	    public function hook_before_edit(&$postdata,$id) {        
1875
	        //Your code here
1876
1877
	    }
1878
1879
	    /* 
1880
	    | ---------------------------------------------------------------------- 
1881
	    | Hook for execute command after edit public static function called
1882
	    | ----------------------------------------------------------------------     
1883
	    | @id       = current id 
1884
	    | 
1885
	    */
1886
	    public function hook_after_edit($id) {
1887
	        //Your code here 
1888
1889
	    }
1890
1891
	    /* 
1892
	    | ---------------------------------------------------------------------- 
1893
	    | Hook for execute command before delete public static function called
1894
	    | ----------------------------------------------------------------------     
1895
	    | @id       = current id 
1896
	    | 
1897
	    */
1898
	    public function hook_before_delete($id) {
1899
	        //Your code here
1900
1901
	    }
1902
1903
	    /* 
1904
	    | ---------------------------------------------------------------------- 
1905
	    | Hook for execute command after delete public static function called
1906
	    | ----------------------------------------------------------------------     
1907
	    | @id       = current id 
1908
	    | 
1909
	    */
1910
	    public function hook_after_delete($id) {
1911
	        //Your code here
1912
1913
	    }
1914
1915
1916
1917
	    //By the way, you can still create your own method in here... :) 
1918
1919
1920
	}
1921
	        ';
1922
1923
        $php = trim($php);
1924
1925
        //create file controller
1926
        file_put_contents($path.'Admin'.$controllername.'.php', $php);
1927
1928
        return 'Admin'.$controllername;
1929
    }
1930
1931
    /*
1932
    | --------------------------------------------------------------------------------------------------------------
1933
    | Alternate route for Laravel Route::controller
1934
    | --------------------------------------------------------------------------------------------------------------
1935
    | $prefix       = path of route
1936
    | $controller   = controller name
1937
    | $namespace    = namespace of controller (optional)
1938
    |
1939
    */
1940
    public static function routeController($prefix, $controller, $namespace = null)
1941
    {
1942
1943
        $prefix = trim($prefix, '/').'/';
1944
1945
        $namespace = ($namespace) ?: 'App\Http\Controllers';
1946
1947
        try {
1948
            Route::get($prefix, ['uses' => $controller.'@getIndex', 'as' => $controller.'GetIndex']);
1949
1950
            $controller_class = new \ReflectionClass($namespace.'\\'.$controller);
1951
            $controller_methods = $controller_class->getMethods(\ReflectionMethod::IS_PUBLIC);
1952
            $wildcards = '/{one?}/{two?}/{three?}/{four?}/{five?}';
1953
            foreach ($controller_methods as $method) {
1954
1955
                if ($method->class != 'Illuminate\Routing\Controller' && $method->name != 'getIndex') {
1956
                    if (substr($method->name, 0, 3) == 'get') {
1957
                        $method_name = substr($method->name, 3);
1958
                        $slug = array_filter(preg_split('/(?=[A-Z])/', $method_name));
0 ignored issues
show
Bug introduced by
It seems like preg_split('/(?=[A-Z])/', $method_name) can also be of type false; however, parameter $input of array_filter() 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

1958
                        $slug = array_filter(/** @scrutinizer ignore-type */ preg_split('/(?=[A-Z])/', $method_name));
Loading history...
1959
                        $slug = strtolower(implode('-', $slug));
1960
                        $slug = ($slug == 'index') ? '' : $slug;
1961
                        Route::get($prefix.$slug.$wildcards, ['uses' => $controller.'@'.$method->name, 'as' => $controller.'Get'.$method_name]);
1962
                    } elseif (substr($method->name, 0, 4) == 'post') {
1963
                        $method_name = substr($method->name, 4);
1964
                        $slug = array_filter(preg_split('/(?=[A-Z])/', $method_name));
1965
                        Route::post($prefix.strtolower(implode('-', $slug)).$wildcards, [
1966
                            'uses' => $controller.'@'.$method->name,
1967
                            'as' => $controller.'Post'.$method_name,
1968
                        ]);
1969
                    }
1970
                }
1971
            }
1972
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
1973
1974
        }
1975
    }
1976
}
1977