CBController   F
last analyzed

Complexity

Total Complexity 348

Size/Duplication

Total Lines 1778
Duplicated Lines 0 %

Importance

Changes 29
Bugs 7 Features 0
Metric Value
wmc 348
eloc 1060
dl 0
loc 1778
rs 1.36
c 29
b 7
f 0

36 Methods

Rating   Name   Duplication   Size   Complexity  
A getAdd() 0 13 4
A hook_after_add() 0 2 1
A hook_before_add() 0 2 1
A hook_query_index() 0 2 1
A hook_after_edit() 0 2 1
A getDelete() 0 29 6
A hook_before_edit() 0 2 1
A getDetail() 0 22 4
A postUploadFile() 0 6 2
A postDoneImport() 0 8 1
A getDataTable() 0 19 6
A postExportData() 0 44 5
A hook_after_delete() 0 2 1
A getEdit() 0 19 4
A postDataQuery() 0 6 1
A postUploadSummernote() 0 6 2
A hook_row_index() 0 2 1
A getDeleteImage() 0 31 4
A hook_before_delete() 0 2 1
A actionButtonSelected() 0 2 1
A getUpdateSingle() 0 10 1
A getModalData() 0 34 5
A checkHideForm() 0 6 5
A getExportData() 0 4 1
F postEditSave() 0 129 27
B cbLoader() 0 63 8
F getFindData() 0 93 23
F postAddSave() 0 123 26
A postDoUploadImportData() 0 34 4
F getIndex() 0 419 94
F postDoImportChunk() 0 113 20
A cbView() 0 5 1
F input_assignment() 0 122 38
B getImportData() 0 35 8
B postActionSelected() 0 44 8
F validation() 0 131 31

How to fix   Complexity   

Complex Class

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

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

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

1
<?php namespace crocodicstudio\crudbooster\controllers;
2
3
error_reporting(E_ALL ^ E_NOTICE);
4
5
6
use CB;
7
use CRUDBooster;
0 ignored issues
show
Bug introduced by
The type CRUDBooster was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Illuminate\Support\Facades\App;
9
use Illuminate\Support\Facades\Cache;
10
use Illuminate\Support\Facades\DB;
11
use Illuminate\Support\Facades\Hash;
12
use Illuminate\Support\Facades\PDF;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Facades\PDF was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Illuminate\Support\Facades\Request;
14
use Illuminate\Support\Facades\Route;
15
use Illuminate\Support\Facades\Session;
16
use Illuminate\Support\Facades\Storage;
17
use Illuminate\Support\Facades\Validator;
18
use Maatwebsite\Excel\Facades\Excel;
19
use Schema;
20
21
class CBController extends Controller
22
{
23
    public $data_inputan;
24
25
    public $columns_table;
26
27
    public $module_name;
28
29
    public $table;
30
31
    public $title_field;
32
33
    public $primary_key = 'id';
34
35
    public $arr = [];
36
37
    public $col = [];
38
39
    public $form = [];
40
41
    public $data = [];
42
43
    public $addaction = [];
44
45
    public $orderby = null;
46
47
    public $password_candidate = null;
48
49
    public $date_candidate = null;
50
51
    public $limit = 20;
52
53
    public $global_privilege = false;
54
55
    public $show_numbering = false;
56
57
    public $alert = [];
58
59
    public $index_button = [];
60
61
    public $button_filter = true;
62
63
    public $button_export = true;
64
65
    public $button_import = true;
66
67
    public $button_show = true;
68
69
    public $button_addmore = true;
70
71
    public $button_table_action = true;
72
73
    public $button_bulk_action = true;
74
75
    public $button_add = true;
76
77
    public $button_delete = true;
78
79
    public $button_cancel = true;
80
81
    public $button_save = true;
82
83
    public $button_edit = true;
84
85
    public $button_detail = true;
86
87
    public $button_action_style = 'button_icon';
88
89
    public $button_action_width = null;
90
91
    public $index_statistic = [];
92
93
    public $index_additional_view = [];
94
95
    public $pre_index_html = null;
96
97
    public $post_index_html = null;
98
99
    public $load_js = [];
100
101
    public $load_css = [];
102
103
    public $script_js = null;
104
105
    public $style_css = null;
106
107
    public $sub_module = [];
108
109
    public $show_addaction = true;
110
111
    public $table_row_color = [];
112
113
    public $button_selected = [];
114
115
    public $return_url = null;
116
117
    public $parent_field = null;
118
119
    public $parent_id = null;
120
121
    public $hide_form = [];
122
123
    public $index_return = false; //for export
124
125
    public $sidebar_mode = 'normal';
126
127
    public function cbLoader()
128
    {
129
        $this->cbInit();
0 ignored issues
show
Bug introduced by
The method cbInit() does not exist on crocodicstudio\crudboost...ontrollers\CBController. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

129
        $this->/** @scrutinizer ignore-call */ 
130
               cbInit();
Loading history...
130
131
        $this->checkHideForm();
132
133
        $this->primary_key = CB::pk($this->table);
134
        $this->columns_table = $this->col;
135
        $this->data_inputan = $this->form;
136
        $this->data['pk'] = $this->primary_key;
137
        $this->data['forms'] = $this->data_inputan;
138
        $this->data['hide_form'] = $this->hide_form;
139
        $this->data['addaction'] = ($this->show_addaction) ? $this->addaction : null;
140
        $this->data['table'] = $this->table;
141
        $this->data['title_field'] = $this->title_field;
142
        $this->data['appname'] = CRUDBooster::getSetting('appname');
143
        $this->data['alerts'] = $this->alert;
144
        $this->data['index_button'] = $this->index_button;
145
        $this->data['show_numbering'] = $this->show_numbering;
146
        $this->data['button_detail'] = $this->button_detail;
147
        $this->data['button_edit'] = $this->button_edit;
148
        $this->data['button_show'] = $this->button_show;
149
        $this->data['button_add'] = $this->button_add;
150
        $this->data['button_delete'] = $this->button_delete;
151
        $this->data['button_filter'] = $this->button_filter;
152
        $this->data['button_export'] = $this->button_export;
153
        $this->data['button_addmore'] = $this->button_addmore;
154
        $this->data['button_cancel'] = $this->button_cancel;
155
        $this->data['button_save'] = $this->button_save;
156
        $this->data['button_table_action'] = $this->button_table_action;
157
        $this->data['button_bulk_action'] = $this->button_bulk_action;
158
        $this->data['button_import'] = $this->button_import;
159
        $this->data['button_action_width'] = $this->button_action_width;
160
        $this->data['button_selected'] = $this->button_selected;
161
        $this->data['index_statistic'] = $this->index_statistic;
162
        $this->data['index_additional_view'] = $this->index_additional_view;
163
        $this->data['table_row_color'] = $this->table_row_color;
164
        $this->data['pre_index_html'] = $this->pre_index_html;
165
        $this->data['post_index_html'] = $this->post_index_html;
166
        $this->data['load_js'] = $this->load_js;
167
        $this->data['load_css'] = $this->load_css;
168
        $this->data['script_js'] = $this->script_js;
169
        $this->data['style_css'] = $this->style_css;
170
        $this->data['sub_module'] = $this->sub_module;
171
        $this->data['parent_field'] = (g('parent_field')) ?: $this->parent_field;
172
        $this->data['parent_id'] = (g('parent_id')) ?: $this->parent_id;
173
174
        if ($this->sidebar_mode == 'mini') {
175
            $this->data['sidebar_mode'] = 'sidebar-mini';
176
        } elseif ($this->sidebar_mode == 'collapse') {
177
            $this->data['sidebar_mode'] = 'sidebar-collapse';
178
        } elseif ($this->sidebar_mode == 'collapse-mini') {
179
            $this->data['sidebar_mode'] = 'sidebar-collapse sidebar-mini';
180
        } else {
181
            $this->data['sidebar_mode'] = '';
182
        }
183
184
        if (CRUDBooster::getCurrentMethod() == 'getProfile') {
185
            Session::put('current_row_id', CRUDBooster::myId());
186
            $this->data['return_url'] = Request::fullUrl();
187
        }
188
189
        view()->share($this->data);
190
    }
191
192
    public function cbView($template, $data)
193
    {
194
        header("Content-Type: text/html");
195
        $this->cbLoader();
196
        echo view($template, $data);
197
    }
198
199
    private function checkHideForm()
200
    {
201
        if ($this->hide_form && count($this->hide_form)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->hide_form of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
202
            foreach ($this->form as $i => $f) {
203
                if (in_array($f['name'], $this->hide_form)) {
204
                    unset($this->form[$i]);
205
                }
206
            }
207
        }
208
    }
209
210
    public function getIndex()
211
    {
212
        $this->cbLoader();
213
214
        $module = CRUDBooster::getCurrentModule();
215
216
        if (! CRUDBooster::isView() && $this->global_privilege == false) {
217
            CRUDBooster::insertLog(trans('crudbooster.log_try_view', ['module' => $module->name]));
218
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
219
        }
220
221
        if (Request::get('parent_table')) {
222
            $parentTablePK = CB::pk(g('parent_table'));
223
            $data['parent_table'] = DB::table(Request::get('parent_table'))->where($parentTablePK, Request::get('parent_id'))->first();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
224
            if (Request::get('foreign_key')) {
225
                $data['parent_field'] = Request::get('foreign_key');
226
            } else {
227
                $data['parent_field'] = CB::getTableForeignKey(g('parent_table'), $this->table);
228
            }
229
230
            if ($parent_field) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $parent_field seems to be never defined.
Loading history...
231
                foreach ($this->columns_table as $i => $col) {
232
                    if ($col['name'] == $parent_field) {
233
                        unset($this->columns_table[$i]);
234
                    }
235
                }
236
            }
237
        }
238
239
        $data['table'] = $this->table;
240
        $data['table_pk'] = CB::pk($this->table);
241
        $data['page_title'] = $module->name;
242
        $data['page_description'] = trans('crudbooster.default_module_description');
243
        $data['date_candidate'] = $this->date_candidate;
244
        $data['limit'] = $limit = (Request::get('limit')) ? Request::get('limit') : $this->limit;
245
246
        $tablePK = $data['table_pk'];
247
        $table_columns = CB::getTableColumns($this->table);
248
        $result = DB::table($this->table)->select(DB::raw($this->table.".".$this->primary_key));
249
250
        if (Request::get('parent_id')) {
251
            $table_parent = $this->table;
252
            $table_parent = CRUDBooster::parseSqlTable($table_parent)['table'];
253
            $result->where($table_parent.'.'.Request::get('foreign_key'), Request::get('parent_id'));
254
        }
255
256
        $this->hook_query_index($result);
257
258
        if (in_array('deleted_at', $table_columns)) {
259
            $result->where($this->table.'.deleted_at', null);
260
        }
261
262
        $alias = [];
263
        $join_alias_count = 0;
264
        $join_table_temp = [];
265
        $table = $this->table;
266
        $columns_table = $this->columns_table;
267
        foreach ($columns_table as $index => $coltab) {
268
269
            $join = @$coltab['join'];
270
            $join_where = @$coltab['join_where'];
271
            $join_id = @$coltab['join_id'];
272
            $field = @$coltab['name'];
273
            $join_table_temp[] = $table;
274
275
            if (! $field) {
276
                continue;
277
            }
278
279
            if (strpos($field, ' as ') !== false) {
280
                $field = substr($field, strpos($field, ' as ') + 4);
281
                $field_with = (array_key_exists('join', $coltab)) ? str_replace(",", ".", $coltab['join']) : $field;
282
                $result->addselect(DB::raw($coltab['name']));
283
                $columns_table[$index]['type_data'] = 'varchar';
284
                $columns_table[$index]['field'] = $field;
285
                $columns_table[$index]['field_raw'] = $field;
286
                $columns_table[$index]['field_with'] = $field_with;
287
                $columns_table[$index]['is_subquery'] = true;
288
                continue;
289
            }
290
291
            if (strpos($field, '.') !== false) {
292
                $result->addselect($field);
293
            } else {
294
                $result->addselect($table.'.'.$field);
295
            }
296
297
            $field_array = explode('.', $field);
298
299
            if (isset($field_array[1])) {
300
                $field = $field_array[1];
301
                $table = $field_array[0];
302
            } else {
303
                $table = $this->table;
304
            }
305
306
            if ($join) {
307
308
                $join_exp = explode(',', $join);
309
310
                $join_table = $join_exp[0];
311
                $joinTablePK = CB::pk($join_table);
312
                $join_column = $join_exp[1];
313
                $join_alias = str_replace(".", "_", $join_table);
314
315
                if (in_array($join_table, $join_table_temp)) {
316
                    $join_alias_count += 1;
317
                    $join_alias = $join_table.$join_alias_count;
318
                }
319
                $join_table_temp[] = $join_table;
320
321
                $result->leftjoin($join_table.' as '.$join_alias, $join_alias.(($join_id) ? '.'.$join_id : '.'.$joinTablePK), '=', DB::raw($table.'.'.$field.(($join_where) ? ' AND '.$join_where.' ' : '')));
322
                $result->addselect($join_alias.'.'.$join_column.' as '.$join_alias.'_'.$join_column);
323
324
                $join_table_columns = CRUDBooster::getTableColumns($join_table);
325
                if ($join_table_columns) {
326
                    foreach ($join_table_columns as $jtc) {
327
                        $result->addselect($join_alias.'.'.$jtc.' as '.$join_alias.'_'.$jtc);
328
                    }
329
                }
330
331
                $alias[] = $join_alias;
332
                $columns_table[$index]['type_data'] = CRUDBooster::getFieldType($join_table, $join_column);
333
                $columns_table[$index]['field'] = $join_alias.'_'.$join_column;
334
                $columns_table[$index]['field_with'] = $join_alias.'.'.$join_column;
335
                $columns_table[$index]['field_raw'] = $join_column;
336
337
                @$join_table1 = $join_exp[2];
338
                @$joinTable1PK = CB::pk($join_table1);
339
                @$join_column1 = $join_exp[3];
340
                @$join_alias1 = $join_table1;
341
342
                if ($join_table1 && $join_column1) {
343
344
                    if (in_array($join_table1, $join_table_temp)) {
345
                        $join_alias_count += 1;
346
                        $join_alias1 = $join_table1.$join_alias_count;
347
                    }
348
349
                    $join_table_temp[] = $join_table1;
350
351
                    $result->leftjoin($join_table1.' as '.$join_alias1, $join_alias1.'.'.$joinTable1PK, '=', $join_alias.'.'.$join_column);
352
                    $result->addselect($join_alias1.'.'.$join_column1.' as '.$join_column1.'_'.$join_alias1);
353
                    $alias[] = $join_alias1;
354
                    $columns_table[$index]['type_data'] = CRUDBooster::getFieldType($join_table1, $join_column1);
355
                    $columns_table[$index]['field'] = $join_column1.'_'.$join_alias1;
356
                    $columns_table[$index]['field_with'] = $join_alias1.'.'.$join_column1;
357
                    $columns_table[$index]['field_raw'] = $join_column1;
358
                }
359
            } else {
360
361
                if(isset($field_array[1])) {                    
362
                    $result->addselect($table.'.'.$field.' as '.$table.'_'.$field);
363
                    $columns_table[$index]['type_data'] = CRUDBooster::getFieldType($table, $field);
364
                    $columns_table[$index]['field'] = $table.'_'.$field;
365
                    $columns_table[$index]['field_raw'] = $table.'.'.$field;
366
                }else{
367
                    $result->addselect($table.'.'.$field);
368
                    $columns_table[$index]['type_data'] = CRUDBooster::getFieldType($table, $field);
369
                    $columns_table[$index]['field'] = $field;
370
                    $columns_table[$index]['field_raw'] = $field;
371
                }
372
                
373
                $columns_table[$index]['field_with'] = $table.'.'.$field;
374
            }
375
        }
376
377
        if (Request::get('q')) {
378
            $result->where(function ($w) use ($columns_table, $request) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $request seems to be never defined.
Loading history...
Unused Code introduced by
The import $request 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...
379
                foreach ($columns_table as $col) {
380
                    if (! $col['field_with']) {
381
                        continue;
382
                    }
383
                    if ($col['is_subquery']) {
384
                        continue;
385
                    }
386
                    $w->orwhere($col['field_with'], "like", "%".Request::get("q")."%");
387
                }
388
            });
389
        }
390
391
        if (Request::get('where')) {
392
            foreach (Request::get('where') as $k => $v) {
393
                $result->where($table.'.'.$k, $v);
394
            }
395
        }
396
397
        $filter_is_orderby = false;
398
        if (Request::get('filter_column')) {
399
400
            $filter_column = Request::get('filter_column');
401
            $result->where(function ($w) use ($filter_column, $fc) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fc seems to be never defined.
Loading history...
Unused Code introduced by
The import $fc 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...
402
                foreach ($filter_column as $key => $fc) {
403
404
                    $value = @$fc['value'];
405
                    $type = @$fc['type'];
406
407
                    if ($type == 'empty') {
408
                        $w->whereNull($key)->orWhere($key, '');
409
                        continue;
410
                    }
411
412
                    if ($value == '' || $type == '') {
413
                        continue;
414
                    }
415
416
                    if ($type == 'between') {
417
                        continue;
418
                    }
419
420
                    switch ($type) {
421
                        default:
422
                            if ($key && $type && $value) {
423
                                $w->where($key, $type, $value);
424
                            }
425
                            break;
426
                        case 'like':
427
                        case 'not like':
428
                            $value = '%'.$value.'%';
429
                            if ($key && $type && $value) {
430
                                $w->where($key, $type, $value);
431
                            }
432
                            break;
433
                        case 'in':
434
                        case 'not in':
435
                            if ($value) {
436
                                $value = explode(',', $value);
437
                                if ($key && $value) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $value of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
438
                                    $w->whereIn($key, $value);
439
                                }
440
                            }
441
                            break;
442
                    }
443
                }
444
            });
445
446
            foreach ($filter_column as $key => $fc) {
447
                $value = @$fc['value'];
448
                $type = @$fc['type'];
449
                $sorting = @$fc['sorting'];
450
451
                if ($sorting != '') {
452
                    if ($key) {
453
                        $result->orderby($key, $sorting);
454
                        $filter_is_orderby = true;
455
                    }
456
                }
457
458
                if ($type == 'between') {
459
                    if ($key && $value) {
460
                        $result->whereBetween($key, $value);
461
                    }
462
                } else {
463
                    continue;
464
                }
465
            }
466
        }
467
468
        if ($filter_is_orderby == true) {
469
            $data['result'] = $result->paginate($limit);
470
        } else {
471
            if ($this->orderby) {
472
                if (is_array($this->orderby)) {
473
                    foreach ($this->orderby as $k => $v) {
474
                        if (strpos($k, '.') !== false) {
475
                            $orderby_table = explode(".", $k)[0];
476
                            $k = explode(".", $k)[1];
477
                        } else {
478
                            $orderby_table = $this->table;
479
                        }
480
                        $result->orderby($orderby_table.'.'.$k, $v);
481
                    }
482
                } else {
483
                    $this->orderby = explode(";", $this->orderby);
484
                    foreach ($this->orderby as $o) {
485
                        $o = explode(",", $o);
486
                        $k = $o[0];
487
                        $v = $o[1];
488
                        if (strpos($k, '.') !== false) {
489
                            $orderby_table = explode(".", $k)[0];
490
                        } else {
491
                            $orderby_table = $this->table;
492
                        }
493
                        $result->orderby($orderby_table.'.'.$k, $v);
494
                    }
495
                }
496
                $data['result'] = $result->paginate($limit);
497
            } else {
498
                $data['result'] = $result->orderby($this->table.'.'.$this->primary_key, 'desc')->paginate($limit);
499
            }
500
        }
501
502
        $data['columns'] = $columns_table;
503
504
        if ($this->index_return) {
505
            return $data;
506
        }
507
508
        //LISTING INDEX HTML
509
        $addaction = $this->data['addaction'];
510
511
        if ($this->sub_module) {
512
            foreach ($this->sub_module as $s) {
513
                $table_parent = CRUDBooster::parseSqlTable($this->table)['table'];
514
                $addaction[] = [
515
                    'label' => $s['label'],
516
                    'icon' => $s['button_icon'],
517
                    'url' => CRUDBooster::adminPath($s['path']).'?return_url='.urlencode(Request::fullUrl()).'&parent_table='.$table_parent.'&parent_columns='.$s['parent_columns'].'&parent_columns_alias='.$s['parent_columns_alias'].'&parent_id=['.(! isset($s['custom_parent_id']) ? "id" : $s['custom_parent_id']).']&foreign_key='.$s['foreign_key'].'&label='.urlencode($s['label']),
518
                    'color' => $s['button_color'],
519
                    'showIf' => $s['showIf'],
520
                ];
521
            }
522
        }
523
524
        $mainpath = CRUDBooster::mainpath();
0 ignored issues
show
Unused Code introduced by
The assignment to $mainpath is dead and can be removed.
Loading history...
525
        $orig_mainpath = $this->data['mainpath'];
0 ignored issues
show
Unused Code introduced by
The assignment to $orig_mainpath is dead and can be removed.
Loading history...
526
        $title_field = $this->title_field;
0 ignored issues
show
Unused Code introduced by
The assignment to $title_field is dead and can be removed.
Loading history...
527
        $html_contents = [];
528
        $page = (Request::get('page')) ? Request::get('page') : 1;
529
        $number = ($page - 1) * $limit + 1;
530
        foreach ($data['result'] as $row) {
531
            $html_content = [];
532
533
            if ($this->button_bulk_action) {
534
535
                $html_content[] = "<input type='checkbox' class='checkbox' name='checkbox[]' value='".$row->{$tablePK}."'/>";
536
            }
537
538
            if ($this->show_numbering) {
539
                $html_content[] = $number.'. ';
540
                $number++;
541
            }
542
543
            foreach ($columns_table as $col) {
544
                if ($col['visible'] === false) {
545
                    continue;
546
                }
547
548
                $value = @$row->{$col['field']};
549
                $title = @$row->{$this->title_field};
550
                $label = $col['label'];
551
552
                if (isset($col['image'])) {
553
                    if ($value == '') {
554
                        $value = "<a  data-lightbox='roadtrip' rel='group_{{$table}}' title='$label: $title' href='".asset('vendor/crudbooster/avatar.jpg')."'><img width='40px' height='40px' src='".asset('vendor/crudbooster/avatar.jpg')."'/></a>";
555
                    } else {
556
                        $pic = (strpos($value, 'http://') !== false) ? $value : asset($value);
557
                        $value = "<a data-lightbox='roadtrip'  rel='group_{{$table}}' title='$label: $title' href='".$pic."'><img width='40px' height='40px' src='".$pic."'/></a>";
558
                    }
559
                }
560
561
                if (@$col['download']) {
562
                    $url = (strpos($value, 'http://') !== false) ? $value : asset($value).'?download=1';
563
                    if ($value) {
564
                        $value = "<a class='btn btn-xs btn-primary' href='$url' target='_blank' title='Download File'><i class='fa fa-download'></i> Download</a>";
565
                    } else {
566
                        $value = " - ";
567
                    }
568
                }
569
570
                if ($col['str_limit']) {
571
                    $value = trim(strip_tags($value));
572
                    $value = str_limit($value, $col['str_limit']);
0 ignored issues
show
Deprecated Code introduced by
The function str_limit() has been deprecated: Str::limit() 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

572
                    $value = /** @scrutinizer ignore-deprecated */ str_limit($value, $col['str_limit']);

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...
573
                }
574
575
                if ($col['nl2br']) {
576
                    $value = nl2br($value);
577
                }
578
579
                if ($col['callback_php']) {
580
                    foreach ($row as $k => $v) {
581
                        $col['callback_php'] = str_replace("[".$k."]", $v, $col['callback_php']);
582
                    }
583
                    @eval("\$value = ".$col['callback_php'].";");
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
584
                }
585
586
                //New method for callback
587
                if (isset($col['callback'])) {
588
                    $value = call_user_func($col['callback'], $row);
589
                }
590
591
                $datavalue = @unserialize($value);
592
                if ($datavalue !== false) {
593
                    if ($datavalue) {
594
                        $prevalue = [];
595
                        foreach ($datavalue as $d) {
596
                            if ($d['label']) {
597
                                $prevalue[] = $d['label'];
598
                            }
599
                        }
600
                        if ($prevalue && count($prevalue)) {
601
                            $value = implode(", ", $prevalue);
602
                        }
603
                    }
604
                }
605
606
                $html_content[] = $value;
607
            } //end foreach columns_table
608
609
            if ($this->button_table_action):
610
611
                $button_action_style = $this->button_action_style;
612
                $html_content[] = "<div class='button_action' style='text-align:right'>".view('crudbooster::components.action', compact('addaction', 'row', 'button_action_style', 'parent_field'))->render()."</div>";
613
614
            endif;//button_table_action
615
616
            foreach ($html_content as $i => $v) {
617
                $this->hook_row_index($i, $v);
618
                $html_content[$i] = $v;
619
            }
620
621
            $html_contents[] = $html_content;
622
        } //end foreach data[result]
623
624
        $html_contents = ['html' => $html_contents, 'data' => $data['result']];
625
626
        $data['html_contents'] = $html_contents;
627
628
        return view("crudbooster::default.index", $data);
629
    }
630
631
    public function getExportData()
632
    {
633
634
        return redirect(CRUDBooster::mainpath());
635
    }
636
637
    public function postExportData()
638
    {
639
        ini_set('memory_limit', '1024M');
640
        set_time_limit(180);
641
642
        $this->limit = Request::input('limit');
643
        $this->index_return = true;
644
        $filetype = Request::input('fileformat');
645
        $filename = Request::input('filename');
646
        $papersize = Request::input('page_size');
647
        $paperorientation = Request::input('page_orientation');
648
        $response = $this->getIndex();
649
650
        if (Request::input('default_paper_size')) {
651
            DB::table('cms_settings')->where('name', 'default_paper_size')->update(['content' => $papersize]);
652
        }
653
654
        switch ($filetype) {
655
            case "pdf":
656
                $view = view('crudbooster::export', $response)->render();
657
                $pdf = App::make('dompdf.wrapper');
658
                $pdf->loadHTML($view);
659
                $pdf->setPaper($papersize, $paperorientation);
660
661
                return $pdf->stream($filename.'.pdf');
662
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
663
            case 'xls':
664
                Excel::create($filename, function ($excel) use ($response) {
665
                    $excel->setTitle($filename)->setCreator("crudbooster.com")->setCompany(CRUDBooster::getSetting('appname'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $filename seems to be never defined.
Loading history...
666
                    $excel->sheet($filename, function ($sheet) use ($response) {
667
                        $sheet->setOrientation($paperorientation);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $paperorientation seems to be never defined.
Loading history...
668
                        $sheet->loadview('crudbooster::export', $response);
669
                    });
670
                })->export('xls');
671
                break;
672
            case 'csv':
673
                Excel::create($filename, function ($excel) use ($response) {
674
                    $excel->setTitle($filename)->setCreator("crudbooster.com")->setCompany(CRUDBooster::getSetting('appname'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $filename seems to be never defined.
Loading history...
675
                    $excel->sheet($filename, function ($sheet) use ($response) {
676
                        $sheet->setOrientation($paperorientation);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $paperorientation seems to be never defined.
Loading history...
677
                        $sheet->loadview('crudbooster::export', $response);
678
                    });
679
                })->export('csv');
680
                break;
681
        }
682
    }
683
684
    public function postDataQuery()
685
    {
686
        $query = Request::get('query');
687
        $query = DB::select(DB::raw($query));
688
689
        return response()->json($query);
690
    }
691
692
    public function getDataTable()
693
    {
694
        $table = Request::get('table');
695
        $label = Request::get('label');
696
        $datatableWhere = urldecode(Request::get('datatable_where'));
697
        $foreign_key_name = Request::get('fk_name');
698
        $foreign_key_value = Request::get('fk_value');
699
        if ($table && $label && $foreign_key_name && $foreign_key_value) {
700
            $query = DB::table($table);
701
            if ($datatableWhere) {
702
                $query->whereRaw($datatableWhere);
703
            }
704
            $query->select('id as select_value', $label.' as select_label');
705
            $query->where($foreign_key_name, $foreign_key_value);
706
            $query->orderby($label, 'asc');
707
708
            return response()->json($query->get());
709
        } else {
710
            return response()->json([]);
711
        }
712
    }
713
714
    public function getModalData()
715
    {
716
        $table = Request::get('table');
717
        $where = Request::get('where');
718
        $where = urldecode($where);
719
        $columns = Request::get('columns');
720
        $columns = explode(",", $columns);
721
722
        $table = CRUDBooster::parseSqlTable($table)['table'];
723
        $tablePK = CB::pk($table);
724
        $result = DB::table($table);
725
726
        if (Request::get('q')) {
727
            $result->where(function ($where) use ($columns) {
728
                foreach ($columns as $c => $col) {
729
                    if ($c == 0) {
730
                        $where->where($col, 'like', '%'.Request::get('q').'%');
731
                    } else {
732
                        $where->orWhere($col, 'like', '%'.Request::get('q').'%');
733
                    }
734
                }
735
            });
736
        }
737
738
        if ($where) {
739
            $result->whereraw($where);
740
        }
741
742
        $result->orderby($tablePK, 'desc');
743
744
        $data['result'] = $result->paginate(6);
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
745
        $data['columns'] = $columns;
746
747
        return view('crudbooster::default.type_components.datamodal.browser', $data);
748
    }
749
750
    public function getUpdateSingle()
751
    {
752
        $table = Request::get('table');
753
        $column = Request::get('column');
754
        $value = Request::get('value');
755
        $id = Request::get('id');
756
        $tablePK = CB::pk($table);
757
        DB::table($table)->where($tablePK, $id)->update([$column => $value]);
758
759
        return redirect()->back()->with(['message_type' => 'success', 'message' => trans('crudbooster.alert_delete_data_success')]);
760
    }
761
762
    public function getFindData()
763
    {
764
        $q = Request::get('q');
765
        $id = Request::get('id');
766
        $limit = Request::get('limit') ?: 10;
767
        $format = Request::get('format');
768
769
        $table1 = (Request::get('table1')) ?: $this->table;
770
        $table1PK = CB::pk($table1);
771
        $column1 = (Request::get('column1')) ?: $this->title_field;
772
773
        @$table2 = Request::get('table2');
774
        @$column2 = Request::get('column2');
775
776
        @$table3 = Request::get('table3');
777
        @$column3 = Request::get('column3');
778
779
        $where = Request::get('where');
780
781
        $fk = Request::get('fk');
782
        $fk_value = Request::get('fk_value');
783
784
        if ($q || $id || $table1) {
785
            $rows = DB::table($table1);
786
            $rows->select($table1.'.*');
787
            $rows->take($limit);
788
789
            if (CRUDBooster::isColumnExists($table1, 'deleted_at')) {
790
                $rows->where($table1.'.deleted_at', null);
791
            }
792
793
            if ($fk && $fk_value) {
794
                $rows->where($table1.'.'.$fk, $fk_value);
795
            }
796
797
            if ($table1 && $column1) {
798
799
                $orderby_table = $table1;
800
                $orderby_column = $column1;
801
            }
802
803
            if ($table2 && $column2) {
804
                $table2PK = CB::pk($table2);
805
                $rows->join($table2, $table2.'.'.$table2PK, '=', $table1.'.'.$column1);
806
                $columns = CRUDBooster::getTableColumns($table2);
807
                foreach ($columns as $col) {
808
                    $rows->addselect($table2.".".$col." as ".$table2."_".$col);
809
                }
810
                $orderby_table = $table2;
811
                $orderby_column = $column2;
812
            }
813
814
            if ($table3 && $column3) {
815
                $table3PK = CB::pk($table3);
816
                $rows->join($table3, $table3.'.'.$table3PK, '=', $table2.'.'.$column2);
817
                $columns = CRUDBooster::getTableColumns($table3);
818
                foreach ($columns as $col) {
819
                    $rows->addselect($table3.".".$col." as ".$table3."_".$col);
820
                }
821
                $orderby_table = $table3;
822
                $orderby_column = $column3;
823
            }
824
825
            if ($id) {
826
                $rows->where($table1.".".$table1PK, $id);
827
            }
828
829
            if ($where) {
830
                $rows->whereraw($where);
831
            }
832
833
            if ($format) {
834
                $format = str_replace('&#039;', "'", $format);
835
                $rows->addselect(DB::raw("CONCAT($format) as text"));
836
                if ($q) {
837
                    $rows->whereraw("CONCAT($format) like '%".$q."%'");
838
                }
839
            } else {
840
                $rows->addselect($orderby_table.'.'.$orderby_column.' as text');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $orderby_column does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $orderby_table does not seem to be defined for all execution paths leading up to this point.
Loading history...
841
                if ($q) {
842
                    $rows->where($orderby_table.'.'.$orderby_column, 'like', '%'.$q.'%');
843
                }
844
                $rows->orderBy($orderby_table.'.'.$orderby_column, 'asc');
845
            }
846
847
            $result = [];
848
            $result['items'] = $rows->get();
849
        } else {
850
            $result = [];
851
            $result['items'] = [];
852
        }
853
854
        return response()->json($result);
855
    }
856
857
    public function validation($id = null)
858
    {
859
860
        $request_all = Request::all();
861
        $array_input = [];
862
        foreach ($this->data_inputan as $di) {
863
            $ai = [];
864
            $name = $di['name'];
865
866
            if (! isset($request_all[$name])) {
867
                continue;
868
            }
869
870
            if ($di['type'] != 'upload') {
871
                if (@$di['required']) {
872
                    $ai[] = 'required';
873
                }
874
            }
875
876
            if ($di['type'] == 'upload') {
877
                if ($id) {
878
                    $row = DB::table($this->table)->where($this->primary_key, $id)->first();
879
                    if ($row->{$di['name']} == '') {
880
                        $ai[] = 'required';
881
                    }
882
                }
883
            }
884
885
            if (@$di['min']) {
886
                $ai[] = 'min:'.$di['min'];
887
            }
888
            if (@$di['max']) {
889
                $ai[] = 'max:'.$di['max'];
890
            }
891
            if (@$di['image']) {
892
                $ai[] = 'image';
893
            }
894
            if (@$di['mimes']) {
895
                $ai[] = 'mimes:'.$di['mimes'];
896
            }
897
            $name = $di['name'];
898
            if (! $name) {
899
                continue;
900
            }
901
902
            if ($di['type'] == 'money') {
903
                $request_all[$name] = preg_replace('/[^\d-]+/', '', $request_all[$name]);
904
            }
905
906
            if ($di['type'] == 'child') {
907
                $slug_name = str_slug($di['label'], '');
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

907
                $slug_name = /** @scrutinizer ignore-deprecated */ str_slug($di['label'], '');

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...
908
                foreach ($di['columns'] as $child_col) {
909
                    if (isset($child_col['validation'])) {
910
                        //https://laracasts.com/discuss/channels/general-discussion/array-validation-is-not-working/
911
                        if (strpos($child_col['validation'], 'required') !== false) {
912
                            $array_input[$slug_name.'-'.$child_col['name']] = 'required';
913
914
                            str_replace('required', '', $child_col['validation']);
915
                        }
916
917
                        $array_input[$slug_name.'-'.$child_col['name'].'.*'] = $child_col['validation'];
918
                    }
919
                }
920
            }
921
922
            if (@$di['validation']) {
923
924
                $exp = explode('|', $di['validation']);
925
                if ($exp && count($exp)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $exp of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
926
                    foreach ($exp as &$validationItem) {
927
                        if (substr($validationItem, 0, 6) == 'unique') {
928
                            $parseUnique = explode(',', str_replace('unique:', '', $validationItem));
929
                            $uniqueTable = ($parseUnique[0]) ?: $this->table;
930
                            $uniqueColumn = ($parseUnique[1]) ?: $name;
931
                            $uniqueIgnoreId = ($parseUnique[2]) ?: (($id) ?: '');
932
933
                            //Make sure table name
934
                            $uniqueTable = CB::parseSqlTable($uniqueTable)['table'];
935
936
                            //Rebuild unique rule
937
                            $uniqueRebuild = [];
938
                            $uniqueRebuild[] = $uniqueTable;
939
                            $uniqueRebuild[] = $uniqueColumn;
940
                            if ($uniqueIgnoreId) {
941
                                $uniqueRebuild[] = $uniqueIgnoreId;
942
                            } else {
943
                                $uniqueRebuild[] = 'NULL';
944
                            }
945
946
                            //Check whether deleted_at exists or not
947
                            if (CB::isColumnExists($uniqueTable, 'deleted_at')) {
948
                                $uniqueRebuild[] = CB::findPrimaryKey($uniqueTable);
949
                                $uniqueRebuild[] = 'deleted_at';
950
                                $uniqueRebuild[] = 'NULL';
951
                            }
952
                            $uniqueRebuild = array_filter($uniqueRebuild);
953
                            $validationItem = 'unique:'.implode(',', $uniqueRebuild);
954
                        }
955
                    }
956
                } else {
957
                    $exp = [];
958
                }
959
960
                $validation = implode('|', $exp);
961
962
                $array_input[$name] = $validation;
963
            } else {
964
                $array_input[$name] = implode('|', $ai);
965
            }
966
        }
967
968
        $validator = Validator::make($request_all, $array_input);
969
970
        if ($validator->fails()) {
971
            $message = $validator->messages();
972
            $message_all = $message->all();
973
974
            if (Request::ajax()) {
975
                $res = response()->json([
0 ignored issues
show
Unused Code introduced by
The assignment to $res is dead and can be removed.
Loading history...
976
                    'message' => trans('crudbooster.alert_validation_error', ['error' => implode(', ', $message_all)]),
977
                    'message_type' => 'warning',
978
                ])->send();
979
                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...
980
            } else {
981
                $res = redirect()->back()->with("errors", $message)->with([
982
                    'message' => trans('crudbooster.alert_validation_error', ['error' => implode(', ', $message_all)]),
983
                    'message_type' => 'warning',
984
                ])->withInput();
985
                \Session::driver()->save();
986
                $res->send();
987
                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...
988
            }
989
        }
990
    }
991
992
    public function input_assignment($id = null)
993
    {
994
995
        $hide_form = (Request::get('hide_form')) ? unserialize(Request::get('hide_form')) : [];
996
997
        foreach ($this->data_inputan as $ro) {
998
            $name = $ro['name'];
999
1000
            if (! $name) {
1001
                continue;
1002
            }
1003
1004
            if ($ro['exception']) {
1005
                continue;
1006
            }
1007
1008
            if ($name == 'hide_form') {
1009
                continue;
1010
            }
1011
1012
            if ($hide_form && count($hide_form)) {
1013
                if (in_array($name, $hide_form)) {
1014
                    continue;
1015
                }
1016
            }
1017
1018
            if ($ro['type'] == 'checkbox' && $ro['relationship_table']) {
1019
                continue;
1020
            }
1021
1022
            if ($ro['type'] == 'select2' && $ro['relationship_table']) {
1023
                continue;
1024
            }
1025
1026
            $inputdata = Request::get($name);
1027
1028
            if ($ro['type'] == 'money') {
1029
                $inputdata = preg_replace('/[^\d-]+/', '', $inputdata);
1030
            }
1031
1032
            if ($ro['type'] == 'child') {
1033
                continue;
1034
            }
1035
1036
            if ($name) {
1037
                if ($inputdata != '') {
1038
                    $this->arr[$name] = $inputdata;
1039
                } else {
1040
                    if (CB::isColumnNULL($this->table, $name) && $ro['type'] != 'upload') {
1041
                        continue;
1042
                    } else {
1043
                        $this->arr[$name] = "";
1044
                    }
1045
                }
1046
            }
1047
1048
            $password_candidate = explode(',', config('crudbooster.PASSWORD_FIELDS_CANDIDATE'));
1049
            if (in_array($name, $password_candidate)) {
1050
                if (! empty($this->arr[$name])) {
1051
                    $this->arr[$name] = Hash::make($this->arr[$name]);
1052
                } else {
1053
                    unset($this->arr[$name]);
1054
                }
1055
            }
1056
1057
            if ($ro['type'] == 'checkbox') {
1058
1059
                if (is_array($inputdata)) {
1060
                    if ($ro['datatable'] != '') {
1061
                        $table_checkbox = explode(',', $ro['datatable'])[0];
1062
                        $field_checkbox = explode(',', $ro['datatable'])[1];
1063
                        $table_checkbox_pk = CB::pk($table_checkbox);
1064
                        $data_checkbox = DB::table($table_checkbox)->whereIn($table_checkbox_pk, $inputdata)->pluck($field_checkbox)->toArray();
1065
                        $this->arr[$name] = implode(";", $data_checkbox);
1066
                    } else {
1067
                        $this->arr[$name] = implode(";", $inputdata);
1068
                    }
1069
                }
1070
            }
1071
1072
            //multitext colomn
1073
            if ($ro['type'] == 'multitext') {
1074
                $name = $ro['name'];
1075
                $multitext = "";
1076
                $maxI = ($this->arr[$name])?count($this->arr[$name]):0;
1077
                for ($i = 0; $i <= $maxI - 1; $i++) {
1078
                    $multitext .= $this->arr[$name][$i]."|";
1079
                }
1080
                $multitext = substr($multitext, 0, strlen($multitext) - 1);
1081
                $this->arr[$name] = $multitext;
1082
            }
1083
1084
            if ($ro['type'] == 'googlemaps') {
1085
                if ($ro['latitude'] && $ro['longitude']) {
1086
                    $latitude_name = $ro['latitude'];
1087
                    $longitude_name = $ro['longitude'];
1088
                    $this->arr[$latitude_name] = Request::get('input-latitude-'.$name);
1089
                    $this->arr[$longitude_name] = Request::get('input-longitude-'.$name);
1090
                }
1091
            }
1092
1093
            if ($ro['type'] == 'select' || $ro['type'] == 'select2') {
1094
                if ($ro['datatable']) {
1095
                    if ($inputdata == '') {
1096
                        $this->arr[$name] = 0;
1097
                    }
1098
                }
1099
            }
1100
1101
            if (@$ro['type'] == 'upload') {
1102
1103
                $this->arr[$name] = CRUDBooster::uploadFile($name, $ro['encrypt'] || $ro['upload_encrypt'], $ro['resize_width'], $ro['resize_height'], CB::myId());
1104
1105
                if (! $this->arr[$name]) {
1106
                    $this->arr[$name] = Request::get('_'.$name);
1107
                }
1108
            }
1109
1110
            if (@$ro['type'] == 'filemanager') {
1111
                $filename = str_replace('/'.config('lfm.prefix').'/'.config('lfm.files_folder_name').'/', '', $this->arr[$name]);
1112
                $url = 'uploads/'.$filename;
1113
                $this->arr[$name] = $url;
1114
            }
1115
        }
1116
    }
1117
1118
    public function getAdd()
1119
    {
1120
        $this->cbLoader();
1121
        if (! CRUDBooster::isCreate() && $this->global_privilege == false || $this->button_add == false) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! CRUDBooster::isCreate...is->button_add == false, Probably Intended Meaning: ! CRUDBooster::isCreate(...s->button_add == false)
Loading history...
1122
            CRUDBooster::insertLog(trans('crudbooster.log_try_add', ['module' => CRUDBooster::getCurrentModule()->name]));
1123
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans("crudbooster.denied_access"));
1124
        }
1125
1126
        $page_title = trans("crudbooster.add_data_page_title", ['module' => CRUDBooster::getCurrentModule()->name]);
1127
        $page_menu = Route::getCurrentRoute()->getActionName();
1128
        $command = 'add';
1129
1130
        return view('crudbooster::default.form', compact('page_title', 'page_menu', 'command'));
1131
    }
1132
1133
    public function postAddSave()
1134
    {
1135
        $this->cbLoader();
1136
        if (! CRUDBooster::isCreate() && $this->global_privilege == false) {
1137
            CRUDBooster::insertLog(trans('crudbooster.log_try_add_save', [
1138
                'name' => Request::input($this->title_field),
1139
                'module' => CRUDBooster::getCurrentModule()->name,
1140
            ]));
1141
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans("crudbooster.denied_access"));
1142
        }
1143
1144
        $this->validation();
1145
        $this->input_assignment();
1146
1147
        if (Schema::hasColumn($this->table, 'created_at')) {
1148
            $this->arr['created_at'] = date('Y-m-d H:i:s');
1149
        }
1150
1151
        $this->hook_before_add($this->arr);
1152
1153
//         $this->arr[$this->primary_key] = $id = CRUDBooster::newId($this->table); //error on sql server
1154
        $lastInsertId = $id = DB::table($this->table)->insertGetId($this->arr);
1155
        
1156
        //fix bug if primary key is uuid
1157
        if($this->arr[$this->primary_key]!=$id)
1158
            $id = $this->arr[$this->primary_key];
1159
        
1160
        //Looping Data Input Again After Insert
1161
        foreach ($this->data_inputan as $ro) {
1162
            $name = $ro['name'];
1163
            if (! $name) {
1164
                continue;
1165
            }
1166
1167
            $inputdata = Request::get($name);
1168
1169
            //Insert Data Checkbox if Type Datatable
1170
            if ($ro['type'] == 'checkbox') {
1171
                if ($ro['relationship_table']) {
1172
                    $datatable = explode(",", $ro['datatable'])[0];
1173
                    $foreignKey2 = CRUDBooster::getForeignKey($datatable, $ro['relationship_table']);
1174
                    $foreignKey = CRUDBooster::getForeignKey($this->table, $ro['relationship_table']);
1175
                    DB::table($ro['relationship_table'])->where($foreignKey, $id)->delete();
1176
1177
                    if ($inputdata) {
1178
                        $relationship_table_pk = CB::pk($ro['relationship_table']);
0 ignored issues
show
Unused Code introduced by
The assignment to $relationship_table_pk is dead and can be removed.
Loading history...
1179
                        foreach ($inputdata as $input_id) {
1180
                            DB::table($ro['relationship_table'])->insert([
1181
//                                 $relationship_table_pk => CRUDBooster::newId($ro['relationship_table']),
1182
                                $foreignKey => $id,
1183
                                $foreignKey2 => $input_id,
1184
                            ]);
1185
                        }
1186
                    }
1187
                }
1188
            }
1189
1190
            if ($ro['type'] == 'select2') {
1191
                if ($ro['relationship_table']) {
1192
                    $datatable = explode(",", $ro['datatable'])[0];
1193
                    $foreignKey2 = CRUDBooster::getForeignKey($datatable, $ro['relationship_table']);
1194
                    $foreignKey = CRUDBooster::getForeignKey($this->table, $ro['relationship_table']);
1195
                    DB::table($ro['relationship_table'])->where($foreignKey, $id)->delete();
1196
1197
                    if ($inputdata) {
1198
                        foreach ($inputdata as $input_id) {
1199
                            $relationship_table_pk = CB::pk($row['relationship_table']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $row seems to be never defined.
Loading history...
1200
                            DB::table($ro['relationship_table'])->insert([
1201
//                                 $relationship_table_pk => CRUDBooster::newId($ro['relationship_table']),
1202
                                $foreignKey => $id,
1203
                                $foreignKey2 => $input_id,
1204
                            ]);
1205
                        }
1206
                    }
1207
                }
1208
            }
1209
1210
            if ($ro['type'] == 'child') {
1211
                $name = str_slug($ro['label'], '');
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

1211
                $name = /** @scrutinizer ignore-deprecated */ str_slug($ro['label'], '');

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...
1212
                $columns = $ro['columns'];
1213
                $getColName = Request::get($name.'-'.$columns[0]['name']);
1214
                $count_input_data = ($getColName)?(count($getColName) - 1):0;
1215
                $child_array = [];
1216
                $fk = $ro['foreign_key'];
1217
1218
                for ($i = 0; $i <= $count_input_data; $i++) {
1219
                    $column_data = [];
1220
                    foreach ($columns as $col) {
1221
                        $colname = $col['name'];
1222
                        $colvalue = Request::get($name.'-'.$colname)[$i];
1223
                        if(isset($colvalue) === TRUE) {
1224
                            $column_data[$colname] = $colvalue;
1225
                        }
1226
                    }
1227
                    if(isset($column_data) === TRUE) {
1228
                        $column_data[$fk] = (!empty($id) ? $id : $lastInsertId);
1229
                        $child_array[] = $column_data;
1230
                    }
1231
                }
1232
1233
                $childtable = CRUDBooster::parseSqlTable($ro['table'])['table'];
1234
                DB::table($childtable)->insert($child_array);
1235
            }
1236
        }
1237
1238
        $this->hook_after_add($lastInsertId);
1239
1240
        $this->return_url = ($this->return_url) ? $this->return_url : Request::get('return_url');
1241
1242
        //insert log
1243
        CRUDBooster::insertLog(trans("crudbooster.log_add", ['name' => $this->arr[$this->title_field], 'module' => CRUDBooster::getCurrentModule()->name]));
1244
1245
        if ($this->return_url) {
1246
            if (Request::get('submit') == trans('crudbooster.button_save_more')) {
1247
                CRUDBooster::redirect(Request::server('HTTP_REFERER'), trans("crudbooster.alert_add_data_success"), 'success');
1248
            } else {
1249
                CRUDBooster::redirect($this->return_url, trans("crudbooster.alert_add_data_success"), 'success');
1250
            }
1251
        } else {
1252
            if (Request::get('submit') == trans('crudbooster.button_save_more')) {
1253
                CRUDBooster::redirect(CRUDBooster::mainpath('add'), trans("crudbooster.alert_add_data_success"), 'success');
1254
            } else {
1255
                CRUDBooster::redirect(CRUDBooster::mainpath(), trans("crudbooster.alert_add_data_success"), 'success');
1256
            }
1257
        }
1258
    }
1259
1260
    public function getEdit($id)
1261
    {
1262
        $this->cbLoader();
1263
        $row = DB::table($this->table)->where($this->primary_key, $id)->first();
1264
1265
        if (! CRUDBooster::isRead() && $this->global_privilege == false || $this->button_edit == false) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! CRUDBooster::isRead()...s->button_edit == false, Probably Intended Meaning: ! CRUDBooster::isRead() ...->button_edit == false)
Loading history...
1266
            CRUDBooster::insertLog(trans("crudbooster.log_try_edit", [
1267
                'name' => $row->{$this->title_field},
1268
                'module' => CRUDBooster::getCurrentModule()->name,
1269
            ]));
1270
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
1271
        }
1272
1273
        $page_menu = Route::getCurrentRoute()->getActionName();
1274
        $page_title = trans("crudbooster.edit_data_page_title", ['module' => CRUDBooster::getCurrentModule()->name, 'name' => $row->{$this->title_field}]);
1275
        $command = 'edit';
1276
        Session::put('current_row_id', $id);
1277
1278
        return view('crudbooster::default.form', compact('id', 'row', 'page_menu', 'page_title', 'command'));
1279
    }
1280
1281
    public function postEditSave($id)
1282
    {
1283
        $this->cbLoader();
1284
        $row = DB::table($this->table)->where($this->primary_key, $id)->first();
1285
1286
        if (! CRUDBooster::isUpdate() && $this->global_privilege == false) {
1287
            CRUDBooster::insertLog(trans("crudbooster.log_try_add", ['name' => $row->{$this->title_field}, 'module' => CRUDBooster::getCurrentModule()->name]));
1288
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
1289
        }
1290
1291
        $this->validation($id);
1292
        $this->input_assignment($id);
1293
1294
        if (Schema::hasColumn($this->table, 'updated_at')) {
1295
            $this->arr['updated_at'] = date('Y-m-d H:i:s');
1296
        }
1297
1298
        $this->hook_before_edit($this->arr, $id);
1299
        DB::table($this->table)->where($this->primary_key, $id)->update($this->arr);
1300
1301
        //Looping Data Input Again After Insert
1302
        foreach ($this->data_inputan as $ro) {
1303
            $name = $ro['name'];
1304
            if (! $name) {
1305
                continue;
1306
            }
1307
1308
            $inputdata = Request::get($name);
1309
1310
            //Insert Data Checkbox if Type Datatable
1311
            if ($ro['type'] == 'checkbox') {
1312
                if ($ro['relationship_table']) {
1313
                    $datatable = explode(",", $ro['datatable'])[0];
1314
1315
                    $foreignKey2 = CRUDBooster::getForeignKey($datatable, $ro['relationship_table']);
1316
                    $foreignKey = CRUDBooster::getForeignKey($this->table, $ro['relationship_table']);
1317
                    DB::table($ro['relationship_table'])->where($foreignKey, $id)->delete();
1318
1319
                    if ($inputdata) {
1320
                        foreach ($inputdata as $input_id) {
1321
                            $relationship_table_pk = CB::pk($ro['relationship_table']);
0 ignored issues
show
Unused Code introduced by
The assignment to $relationship_table_pk is dead and can be removed.
Loading history...
1322
                            DB::table($ro['relationship_table'])->insert([
1323
//                                 $relationship_table_pk => CRUDBooster::newId($ro['relationship_table']),
1324
                                $foreignKey => $id,
1325
                                $foreignKey2 => $input_id,
1326
                            ]);
1327
                        }
1328
                    }
1329
                }
1330
            }
1331
1332
            if ($ro['type'] == 'select2') {
1333
                if ($ro['relationship_table'] && $ro["datatable_orig"] == "") {
1334
                    $datatable = explode(",", $ro['datatable'])[0];
1335
1336
                    $foreignKey2 = CRUDBooster::getForeignKey($datatable, $ro['relationship_table']);
1337
                    $foreignKey = CRUDBooster::getForeignKey($this->table, $ro['relationship_table']);
1338
                    DB::table($ro['relationship_table'])->where($foreignKey, $id)->delete();
1339
1340
                    if ($inputdata) {
1341
                        foreach ($inputdata as $input_id) {
1342
                            $relationship_table_pk = CB::pk($ro['relationship_table']);
1343
                            DB::table($ro['relationship_table'])->insert([
1344
//                                 $relationship_table_pk => CRUDBooster::newId($ro['relationship_table']),
1345
                                $foreignKey => $id,
1346
                                $foreignKey2 => $input_id,
1347
                            ]);
1348
                        }
1349
                    }
1350
                }
1351
                if ($ro['relationship_table'] && $ro["datatable_orig"] != "") {
1352
                    $params = explode("|", $ro['datatable_orig']);
1353
                    if(!isset($params[2])) $params[2] = "id";
1354
                    DB::table($params[0])->where($params[2], $id)->update([$params[1] => implode(",",$inputdata)]);
1355
                }
1356
            }
1357
1358
            if ($ro['type'] == 'child') {
1359
                $name = str_slug($ro['label'], '');
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

1359
                $name = /** @scrutinizer ignore-deprecated */ str_slug($ro['label'], '');

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...
1360
                $columns = $ro['columns'];
1361
                $getColName = Request::get($name.'-'.$columns[0]['name']);
1362
                $count_input_data = ($getColName)?(count($getColName) - 1):0;
1363
                $child_array = [];
1364
                $childtable = CRUDBooster::parseSqlTable($ro['table'])['table'];
1365
                $fk = $ro['foreign_key'];
1366
1367
                DB::table($childtable)->where($fk, $id)->delete();
1368
                $lastId = CRUDBooster::newId($childtable);
1369
                $childtablePK = CB::pk($childtable);
1370
1371
                for ($i = 0; $i <= $count_input_data; $i++) {
1372
                    $column_data = [];
1373
                    foreach ($columns as $col) {
1374
                        $colname = $col['name'];
1375
                        $colvalue = Request::get($name.'-'.$colname)[$i];
1376
                        if(isset($colvalue) === TRUE) {
1377
                            $column_data[$colname] = $colvalue;
1378
                        }
1379
                    }
1380
                    if(isset($column_data) === TRUE){
1381
                        $column_data[$childtablePK] = $lastId;
1382
                        $column_data[$fk] = $id;
1383
                        $child_array[] = $column_data;
1384
                        $lastId++;
1385
                    }
1386
                }
1387
                $child_array = array_reverse($child_array);
1388
                DB::table($childtable)->insert($child_array);
1389
            }
1390
        }
1391
1392
        $this->hook_after_edit($id);
1393
1394
        $this->return_url = ($this->return_url) ? $this->return_url : Request::get('return_url');
1395
1396
        //insert log
1397
        $old_values = json_decode(json_encode($row), true);
1398
        CRUDBooster::insertLog(trans("crudbooster.log_update", [
1399
            'name' => $this->arr[$this->title_field],
1400
            'module' => CRUDBooster::getCurrentModule()->name,
1401
        ]), LogsController::displayDiff($old_values, $this->arr));
1402
1403
        if ($this->return_url) {
1404
            CRUDBooster::redirect($this->return_url, trans("crudbooster.alert_update_data_success"), 'success');
1405
        } else {
1406
            if (Request::get('submit') == trans('crudbooster.button_save_more')) {
1407
                CRUDBooster::redirect(CRUDBooster::mainpath('add'), trans("crudbooster.alert_update_data_success"), 'success');
1408
            } else {
1409
                CRUDBooster::redirect(CRUDBooster::mainpath(), trans("crudbooster.alert_update_data_success"), 'success');
1410
            }
1411
        }
1412
    }
1413
1414
    public function getDelete($id)
1415
    {
1416
        $this->cbLoader();
1417
        $row = DB::table($this->table)->where($this->primary_key, $id)->first();
1418
1419
        if (! CRUDBooster::isDelete() && $this->global_privilege == false || $this->button_delete == false) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! CRUDBooster::isDelete...>button_delete == false, Probably Intended Meaning: ! CRUDBooster::isDelete(...button_delete == false)
Loading history...
1420
            CRUDBooster::insertLog(trans("crudbooster.log_try_delete", [
1421
                'name' => $row->{$this->title_field},
1422
                'module' => CRUDBooster::getCurrentModule()->name,
1423
            ]));
1424
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
1425
        }
1426
1427
        //insert log
1428
        CRUDBooster::insertLog(trans("crudbooster.log_delete", ['name' => $row->{$this->title_field}, 'module' => CRUDBooster::getCurrentModule()->name]));
1429
1430
        $this->hook_before_delete($id);
1431
1432
        if (CRUDBooster::isColumnExists($this->table, 'deleted_at')) {
1433
            DB::table($this->table)->where($this->primary_key, $id)->update(['deleted_at' => date('Y-m-d H:i:s')]);
1434
        } else {
1435
            DB::table($this->table)->where($this->primary_key, $id)->delete();
1436
        }
1437
1438
        $this->hook_after_delete($id);
1439
1440
        $url = g('return_url') ?: CRUDBooster::referer();
1441
1442
        CRUDBooster::redirect($url, trans("crudbooster.alert_delete_data_success"), 'success');
1443
    }
1444
1445
    public function getDetail($id)
1446
    {
1447
        $this->cbLoader();
1448
        $row = DB::table($this->table)->where($this->primary_key, $id)->first();
1449
1450
        if (! CRUDBooster::isRead() && $this->global_privilege == false || $this->button_detail == false) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! CRUDBooster::isRead()...>button_detail == false, Probably Intended Meaning: ! CRUDBooster::isRead() ...button_detail == false)
Loading history...
1451
            CRUDBooster::insertLog(trans("crudbooster.log_try_view", [
1452
                'name' => $row->{$this->title_field},
1453
                'module' => CRUDBooster::getCurrentModule()->name,
1454
            ]));
1455
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
1456
        }
1457
1458
        $module = CRUDBooster::getCurrentModule();
1459
1460
        $page_menu = Route::getCurrentRoute()->getActionName();
1461
        $page_title = trans("crudbooster.detail_data_page_title", ['module' => $module->name, 'name' => $row->{$this->title_field}]);
1462
        $command = 'detail';
1463
1464
        Session::put('current_row_id', $id);
1465
1466
        return view('crudbooster::default.form', compact('row', 'page_menu', 'page_title', 'command', 'id'));
1467
    }
1468
1469
    public function getImportData()
1470
    {
1471
        $this->cbLoader();
1472
        $data['page_menu'] = Route::getCurrentRoute()->getActionName();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
1473
        $data['page_title'] = 'Import Data '.$module->name;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $module seems to be never defined.
Loading history...
1474
1475
        if (Request::get('file') && ! Request::get('import')) {
1476
            $file = base64_decode(Request::get('file'));
1477
            $file = storage_path('app/'.$file);
1478
            $rows = Excel::load($file, function ($reader) {
1479
            })->get();
1480
            
1481
            $countRows = ($rows)?count($rows):0;
1482
            
1483
            Session::put('total_data_import', $countRows);
1484
1485
            $data_import_column = [];
1486
            foreach ($rows as $value) {
1487
                $a = [];
1488
                foreach ($value as $k => $v) {
1489
                    $a[] = $k;
1490
                }
1491
                if ($a && count($a)) {
1492
                    $data_import_column = $a;
1493
                }
1494
                break;
1495
            }
1496
1497
            $table_columns = DB::getSchemaBuilder()->getColumnListing($this->table);
1498
1499
            $data['table_columns'] = $table_columns;
1500
            $data['data_import_column'] = $data_import_column;
1501
        }
1502
1503
        return view('crudbooster::import', $data);
1504
    }
1505
1506
    public function postDoneImport()
1507
    {
1508
        $this->cbLoader();
1509
        $data['page_menu'] = Route::getCurrentRoute()->getActionName();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
1510
        $data['page_title'] = trans('crudbooster.import_page_title', ['module' => $module->name]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $module seems to be never defined.
Loading history...
1511
        Session::put('select_column', Request::get('select_column'));
1512
1513
        return view('crudbooster::import', $data);
1514
    }
1515
1516
    public function postDoImportChunk()
1517
    {
1518
        $this->cbLoader();
1519
        $file_md5 = md5(Request::get('file'));
1520
1521
        if (Request::get('file') && Request::get('resume') == 1) {
1522
            $total = Session::get('total_data_import');
1523
            $prog = intval(Cache::get('success_'.$file_md5)) / $total * 100;
1524
            $prog = round($prog, 2);
1525
            if ($prog >= 100) {
1526
                Cache::forget('success_'.$file_md5);
1527
            }
1528
1529
            return response()->json(['progress' => $prog, 'last_error' => Cache::get('error_'.$file_md5)]);
1530
        }
1531
1532
        $select_column = Session::get('select_column');
1533
        $select_column = array_filter($select_column);
1534
        $table_columns = DB::getSchemaBuilder()->getColumnListing($this->table);
1535
1536
        $file = base64_decode(Request::get('file'));
1537
        $file = storage_path('app/'.$file);
1538
1539
        $rows = Excel::load($file, function ($reader) {
1540
        })->get();
1541
1542
        $has_created_at = false;
1543
        if (CRUDBooster::isColumnExists($this->table, 'created_at')) {
1544
            $has_created_at = true;
1545
        }
1546
1547
        $data_import_column = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $data_import_column is dead and can be removed.
Loading history...
1548
        foreach ($rows as $value) {
1549
            $a = [];
1550
            foreach ($select_column as $sk => $s) {
1551
                $colname = $table_columns[$sk];
1552
1553
                if (CRUDBooster::isForeignKey($colname)) {
1554
1555
                    //Skip if value is empty
1556
                    if ($value->$s == '') {
1557
                        continue;
1558
                    }
1559
1560
                    if (intval($value->$s)) {
1561
                        $a[$colname] = $value->$s;
1562
                    } else {
1563
                        $relation_table = CRUDBooster::getTableForeignKey($colname);
1564
                        $relation_moduls = DB::table('cms_moduls')->where('table_name', $relation_table)->first();
1565
1566
                        $relation_class = __NAMESPACE__.'\\'.$relation_moduls->controller;
1567
                        if (! class_exists($relation_class)) {
1568
                            $relation_class = '\App\Http\Controllers\\'.$relation_moduls->controller;
1569
                        }
1570
                        $relation_class = new $relation_class;
1571
                        $relation_class->cbLoader();
1572
1573
                        $title_field = $relation_class->title_field;
1574
1575
                        $relation_insert_data = [];
1576
                        $relation_insert_data[$title_field] = $value->$s;
1577
1578
                        if (CRUDBooster::isColumnExists($relation_table, 'created_at')) {
1579
                            $relation_insert_data['created_at'] = date('Y-m-d H:i:s');
1580
                        }
1581
1582
                        try {
1583
                            $relation_exists = DB::table($relation_table)->where($title_field, $value->$s)->first();
1584
                            if ($relation_exists) {
1585
                                $relation_primary_key = $relation_class->primary_key;
1586
                                $relation_id = $relation_exists->$relation_primary_key;
1587
                            } else {
1588
                                $relation_id = DB::table($relation_table)->insertGetId($relation_insert_data);
1589
                            }
1590
1591
                            $a[$colname] = $relation_id;
1592
                        } catch (\Exception $e) {
1593
                            exit($e);
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...
1594
                        }
1595
                    } //END IS INT
1596
1597
                } else {
1598
                    $a[$colname] = $value->$s;
1599
                }
1600
            }
1601
1602
            $has_title_field = true;
1603
            foreach ($a as $k => $v) {
1604
                if ($k == $this->title_field && $v == '') {
1605
                    $has_title_field = false;
1606
                    break;
1607
                }
1608
            }
1609
1610
            if ($has_title_field == false) {
1611
                continue;
1612
            }
1613
1614
            try {
1615
1616
                if ($has_created_at) {
1617
                    $a['created_at'] = date('Y-m-d H:i:s');
1618
                }
1619
1620
                DB::table($this->table)->insert($a);
1621
                Cache::increment('success_'.$file_md5);
1622
            } catch (\Exception $e) {
1623
                $e = (string) $e;
1624
                Cache::put('error_'.$file_md5, $e, 500);
1625
            }
1626
        }
1627
1628
        return response()->json(['status' => true]);
1629
    }
1630
1631
    public function postDoUploadImportData()
1632
    {
1633
        $this->cbLoader();
1634
        if (Request::hasFile('userfile')) {
1635
            $file = Request::file('userfile');
1636
            $ext = $file->getClientOriginalExtension();
1637
1638
            $validator = Validator::make([
1639
                'extension' => $ext,
1640
            ], [
1641
                'extension' => 'in:xls,xlsx,csv',
1642
            ]);
1643
1644
            if ($validator->fails()) {
1645
                $message = $validator->errors()->all();
1646
1647
                return redirect()->back()->with(['message' => implode('<br/>', $message), 'message_type' => 'warning']);
1648
            }
1649
1650
            //Create Directory Monthly
1651
            $filePath = 'uploads/'.CB::myId().'/'.date('Y-m');
1652
            Storage::makeDirectory($filePath);
1653
1654
            //Move file to storage
1655
            $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

1655
            $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...
1656
            $url_filename = '';
1657
            if (Storage::putFileAs($filePath, $file, $filename)) {
1658
                $url_filename = $filePath.'/'.$filename;
1659
            }
1660
            $url = CRUDBooster::mainpath('import-data').'?file='.base64_encode($url_filename);
1661
1662
            return redirect($url);
1663
        } else {
1664
            return redirect()->back();
1665
        }
1666
    }
1667
1668
    public function postActionSelected()
1669
    {
1670
        $this->cbLoader();
1671
        $id_selected = Request::input('checkbox');
1672
        $button_name = Request::input('button_name');
1673
1674
        if (! $id_selected) {
1675
            CRUDBooster::redirect($_SERVER['HTTP_REFERER'], trans("crudbooster.alert_select_a_data"), 'warning');
1676
        }
1677
1678
        if ($button_name == 'delete') {
1679
            if (! CRUDBooster::isDelete()) {
1680
                CRUDBooster::insertLog(trans("crudbooster.log_try_delete_selected", ['module' => CRUDBooster::getCurrentModule()->name]));
1681
                CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
1682
            }
1683
1684
            $this->hook_before_delete($id_selected);
1685
            $tablePK = CB::pk($this->table);
1686
            if (CRUDBooster::isColumnExists($this->table, 'deleted_at')) {
1687
1688
                DB::table($this->table)->whereIn($tablePK, $id_selected)->update(['deleted_at' => date('Y-m-d H:i:s')]);
1689
            } else {
1690
                DB::table($this->table)->whereIn($tablePK, $id_selected)->delete();
1691
            }
1692
            CRUDBooster::insertLog(trans("crudbooster.log_delete", ['name' => implode(',', $id_selected), 'module' => CRUDBooster::getCurrentModule()->name]));
1693
1694
            $this->hook_after_delete($id_selected);
1695
1696
            $message = trans("crudbooster.alert_delete_selected_success");
1697
1698
            return redirect()->back()->with(['message_type' => 'success', 'message' => $message]);
1699
        }
1700
1701
        $action = str_replace(['-', '_'], ' ', $button_name);
1702
        $action = ucwords($action);
1703
        $type = 'success';
1704
        $message = trans("crudbooster.alert_action", ['action' => $action]);
1705
1706
        if ($this->actionButtonSelected($id_selected, $button_name) === false) {
1707
            $message = ! empty($this->alert['message']) ? $this->alert['message'] : 'Error';
1708
            $type = ! empty($this->alert['type']) ? $this->alert['type'] : 'danger';
1709
        }
1710
1711
        return redirect()->back()->with(['message_type' => $type, 'message' => $message]);
1712
    }
1713
1714
    public function getDeleteImage()
1715
    {
1716
        $this->cbLoader();
1717
        $id = Request::get('id');
1718
        $column = Request::get('column');
1719
1720
        $row = DB::table($this->table)->where($this->primary_key, $id)->first();
1721
1722
        if (! CRUDBooster::isDelete() && $this->global_privilege == false) {
1723
            CRUDBooster::insertLog(trans("crudbooster.log_try_delete_image", [
1724
                'name' => $row->{$this->title_field},
1725
                'module' => CRUDBooster::getCurrentModule()->name,
1726
            ]));
1727
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
1728
        }
1729
1730
        $row = DB::table($this->table)->where($this->primary_key, $id)->first();
1731
1732
        $file = str_replace('uploads/', '', $row->{$column});
1733
        if (Storage::exists($file)) {
1734
            Storage::delete($file);
1735
        }
1736
1737
        DB::table($this->table)->where($this->primary_key, $id)->update([$column => null]);
1738
1739
        CRUDBooster::insertLog(trans("crudbooster.log_delete_image", [
1740
            'name' => $row->{$this->title_field},
1741
            'module' => CRUDBooster::getCurrentModule()->name,
1742
        ]));
1743
1744
        CRUDBooster::redirect(Request::server('HTTP_REFERER'), trans('crudbooster.alert_delete_data_success'), 'success');
1745
    }
1746
1747
    public function postUploadSummernote()
1748
    {
1749
        $this->cbLoader();
1750
        $name = 'userfile';
1751
        if ($file = CRUDBooster::uploadFile($name, true)) {
1752
            echo asset($file);
1753
        }
1754
    }
1755
1756
    public function postUploadFile()
1757
    {
1758
        $this->cbLoader();
1759
        $name = 'userfile';
1760
        if ($file = CRUDBooster::uploadFile($name, true)) {
1761
            echo asset($file);
1762
        }
1763
    }
1764
1765
    public function actionButtonSelected($id_selected, $button_name)
1766
    {
1767
    }
1768
1769
    public function hook_query_index(&$query)
1770
    {
1771
    }
1772
1773
    public function hook_row_index($index, &$value)
1774
    {
1775
    }
1776
1777
    public function hook_before_add(&$arr)
1778
    {
1779
    }
1780
1781
    public function hook_after_add($id)
1782
    {
1783
    }
1784
1785
    public function hook_before_edit(&$arr, $id)
1786
    {
1787
    }
1788
1789
    public function hook_after_edit($id)
1790
    {
1791
    }
1792
1793
    public function hook_before_delete($id)
1794
    {
1795
    }
1796
1797
    public function hook_after_delete($id)
1798
    {
1799
    }
1800
}
1801