Completed
Push — development ( d3ce46...64eb7f )
by Ashutosh
10:50
created

SettingsController::settingsActivity()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 3
nop 1
1
<?php
2
3
namespace App\Http\Controllers\Common;
4
5
use App\ApiKey;
6
use App\Model\Common\Setting;
7
use App\Model\Common\Template;
8
use App\Model\Plugin;
9
use App\User;
10
use Bugsnag;
11
use GrahamCampbell\Markdown\Facades\Markdown;
12
use Illuminate\Http\Request;
13
use Illuminate\Support\Facades\Input;
14
use Spatie\Activitylog\Models\Activity;
15
16
class SettingsController extends BaseSettingsController
17
{
18
    public function __construct()
19
    {
20
        $this->middleware('auth', ['except' => 'checkPaymentGateway']);
21
        $this->middleware('admin', ['except' => 'checkPaymentGateway']);
22
    }
23
24
    public function settings(Setting $settings)
25
    {
26
        if (!$settings->where('id', '1')->first()) {
27
            $settings->create(['company' => '']);
28
        }
29
30
        return view('themes.default1.common.admin-settings');
31
        //return view('themes.default1.common.settings', compact('setting', 'template'));
32
    }
33
34
    public function plugins()
35
    {
36
        return view('themes.default1.common.plugins');
37
    }
38
39
    public function getPlugin()
40
    {
41
        $plugins = $this->fetchConfig();
42
43
        //dd($result);
44
        return \DataTables::of(new Collection($plugins))
45
                        // ->searchColumns('name')
46
                        ->addColumn('name', function ($model) {
47
                            if (array_has($model, 'path')) {
48
                                if ($model['status'] == 0) {
49
                                    $activate = '<a href='.url('plugin/status/'.$model['path']).'>Activate</a>';
50
                                    $settings = ' ';
51
                                } else {
52
                                    $settings = '<a href='.url($model['settings']).'>Settings</a> | ';
53
                                    $activate = '<a href='.url('plugin/status/'.$model['path']).'>Deactivate</a>';
54
                                }
55
56
                                $delete = '<a href=  id=delete'.$model['path'].' data-toggle=modal data-target=#del'.$model['path']."><span style='color:red'>Delete</span></a>"
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 176 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
57
                                        ."<div class='modal fade' id=del".$model['path'].">
58
                                            <div class='modal-dialog'>
59
                                                <div class=modal-content>  
60
                                                    <div class=modal-header>
61
                                                        <h4 class=modal-title>Delete</h4>
62
                                                    </div>
63
                                                    <div class=modal-body>
64
                                                       <p>Are you Sure ?</p>
65
                                                        <div class=modal-footer>
66
                                                            <button type=button class='btn btn-default pull-left' data-dismiss=modal id=dismis>".\Lang::get('lang.close').'</button>
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 180 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
67
                                                            <a href='.url('plugin/delete/'.$model['path'])."><button class='btn btn-danger'>Delete</button></a>
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 159 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
68
                                                        </div>
69
70
71
                                                    </div>
72
                                                </div>
73
                                            </div>
74
                                        </div>";
75
                                $action = '<br><br>'.$delete.' | '.$settings.$activate;
76
                            } else {
77
                                $action = '';
78
                            }
79
80
                            return ucfirst($model['name']).$action;
81
                        })
82
                        ->addColumn('description', function ($model) {
83
                            return $model['description'];
84
                        })
85
                        ->addColumn('author', function ($model) {
86
                            return ucfirst($model['author']);
87
                        })
88
                        ->addColumn('website', function ($model) {
89
                            return '<a href='.$model['website'].' target=_blank>'.$model['website'].'</a>';
90
                        })
91
                        ->addColumn('version', function ($model) {
92
                            return $model['version'];
93
                        })
94
                      ->rawColumns(['name', 'description', 'author', 'website', 'version'])
95
                            ->make(true);
96
    }
97
98
    /**
99
     * Reading the Filedirectory.
100
     *
101
     * @return type
102
     */
103
    public function readPlugins()
104
    {
105
        $dir = app_path().DIRECTORY_SEPARATOR.'Plugins';
106
        $plugins = array_diff(scandir($dir), ['.', '..']);
107
108
        return $plugins;
109
    }
110
111
    /**
112
     * After plugin post.
113
     *
114
     * @param Request $request
115
     *
116
     * @return type
117
     */
118
    public function postPlugins(Request $request)
119
    {
120
        $v = $this->validate($request, ['plugin' => 'required|mimes:application/zip,zip,Zip']);
121
        $plug = new Plugin();
122
        $file = $request->file('plugin');
123
        //dd($file);
124
        $destination = app_path().DIRECTORY_SEPARATOR.'Plugins';
125
        $zipfile = $file->getRealPath();
126
        /*
127
         * get the file name and remove .zip
128
         */
129
        $filename2 = $file->getClientOriginalName();
130
        $filename2 = str_replace('.zip', '', $filename2);
131
        $filename1 = ucfirst($file->getClientOriginalName());
132
        $filename = str_replace('.zip', '', $filename1);
133
        mkdir($destination.DIRECTORY_SEPARATOR.$filename);
134
        /*
135
         * extract the zip file using zipper
136
         */
137
        \Zipper::make($zipfile)->folder($filename2)->extractTo($destination.DIRECTORY_SEPARATOR.$filename);
138
139
        $file = app_path().DIRECTORY_SEPARATOR.'Plugins'.DIRECTORY_SEPARATOR.$filename; // Plugin file path
140
141
        if (file_exists($file)) {
142
            $seviceporvider = $file.DIRECTORY_SEPARATOR.'ServiceProvider.php';
143
            $config = $file.DIRECTORY_SEPARATOR.'config.php';
144
            if (file_exists($seviceporvider) && file_exists($config)) {
145
                /*
146
                 * move to faveo config
147
                 */
148
                $faveoconfig = config_path().DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$filename.'.php';
149
                if ($faveoconfig) {
150
                    //copy($config, $faveoconfig);
151
                    /*
152
                     * write provider list in app.php line 128
153
                     */
154
                    $app = base_path().DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'app.php';
155
                    $str = "\n\n\t\t\t'App\\Plugins\\$filename"."\\ServiceProvider',";
156
                    $line_i_am_looking_for = 102;
157
                    $lines = file($app, FILE_IGNORE_NEW_LINES);
158
                    $lines[$line_i_am_looking_for] = $str;
159
                    file_put_contents($app, implode("\n", $lines));
160
                    $plug->create(['name' => $filename, 'path' => $filename, 'status' => 1]);
161
162
                    return redirect()->back()->with('success', 'Installed SuccessFully');
163
                } else {
164
                    /*
165
                     * delete if the plugin hasn't config.php and ServiceProvider.php
166
                     */
167
                    $this->deleteDirectory($file);
168
169
                    return redirect()->back()->with('fails', 'Their is no '.$file);
170
                }
171
            } else {
172
                /*
173
                 * delete if the plugin hasn't config.php and ServiceProvider.php
174
                 */
175
                $this->deleteDirectory($file);
176
177
                return redirect()->back()->with('fails', 'Their is no <b>config.php or ServiceProvider.php</b>  '.$file);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
178
            }
179
        } else {
180
            /*
181
             * delete if the plugin Name is not equal to the folder name
182
             */
183
            $this->deleteDirectory($file);
184
185
            return redirect()->back()->with('fails', '<b>Plugin File Path is not exist</b>  '.$file);
186
        }
187
    }
188
189
190
    public function getActivity()
191
    {
192
        try {
193
            $activity_log = Activity::select('id', 'log_name', 'description',
194
                'subject_id', 'subject_type', 'causer_id', 'properties', 'created_at')->get();
195
196
            return\ DataTables::of($activity_log)
197
             ->addColumn('checkbox', function ($model) {
198
                 return "<input type='checkbox' class='activity' value=".$model->id.' name=select[] id=check>';
199
             })
200
                           ->addColumn('name', function ($model) {
201
                               return ucfirst($model->log_name);
202
                           })
203
                             ->addColumn('description', function ($model) {
204
                                 return ucfirst($model->description);
205
                             })
206
                          ->addColumn('username', function ($model) {
207
                              $causer_id = $model->causer_id;
208
                              $names = User::where('id', $causer_id)->pluck('last_name', 'first_name');
209
                              foreach ($names as $key => $value) {
210
                                  $fullName = $key.' '.$value;
211
212
                                  return $fullName;
213
                              }
214
                          })
215
                              ->addColumn('role', function ($model) {
216
                                  $causer_id = $model->causer_id;
217
                                  $role = User::where('id', $causer_id)->pluck('role');
218
219
                                  return json_decode($role);
220
                              })
221
                               ->addColumn('new', function ($model) {
222
                                   $properties = ($model->properties);
223
                                   $newEntry = $this->getNewEntry($properties, $model);
224
225
                                   return $newEntry;
226
                               })
227
                                ->addColumn('old', function ($model) {
228
                                    $data = ($model->properties);
229
                                    $oldEntry = $this->getOldEntry($data, $model);
230
231
                                    return $oldEntry;
232
                                })
233
                                ->addColumn('created_at', function ($model) {
234
                                    $newDate = $this->getDate($model->created_at);
235
236
                                    return $newDate;
237
                                })
238
239
                            ->rawColumns(['checkbox', 'name', 'description',
240
                                'username', 'role', 'new', 'old', 'created_at', ])
241
                            ->make(true);
242
        } catch (\Exception $e) {
243
            Bugsnag::notifyException($e);
244
245
            return redirect()->back()->with('fails', $e->getMessage());
246
        }
247
    }
248
249
    /**
250
     * Delete the directory.
251
     *
252
     * @param type $dir
253
     *
254
     * @return bool
255
     */
256
    public function deleteDirectory($dir)
257
    {
258
        if (!file_exists($dir)) {
259
            return true;
260
        }
261
        if (!is_dir($dir)) {
262
            return unlink($dir);
263
        }
264
        foreach (scandir($dir) as $item) {
265
            if ($item == '.' || $item == '..') {
266
                continue;
267
            }
268
            chmod($dir.DIRECTORY_SEPARATOR.$item, 0777);
269
            if (!$this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) {
270
                return false;
271
            }
272
        }
273
        chmod($dir, 0777);
274
275
        return rmdir($dir);
276
    }
277
278
    public function readConfigs()
279
    {
280
        $dir = app_path().DIRECTORY_SEPARATOR.'Plugins'.DIRECTORY_SEPARATOR;
281
        $directories = scandir($dir);
282
        $files = [];
283
        foreach ($directories as $key => $file) {
284
            if ($file === '.' or $file === '..') {
285
                continue;
286
            }
287
288
            if (is_dir($dir.DIRECTORY_SEPARATOR.$file)) {
289
                $files[$key] = $file;
290
            }
291
        }
292
        //dd($files);
293
        $config = [];
294
        $plugins = [];
295
        if (count($files) > 0) {
296
            foreach ($files as $key => $file) {
297
                $plugin = $dir.$file;
298
                $plugins[$key] = array_diff(scandir($plugin), ['.', '..', 'ServiceProvider.php']);
299
                $plugins[$key]['file'] = $plugin;
300
            }
301
            foreach ($plugins as $plugin) {
302
                $dir = $plugin['file'];
303
                //opendir($dir);
304
                if ($dh = opendir($dir)) {
305
                    while (($file = readdir($dh)) !== false) {
306
                        if ($file == 'config.php') {
307
                            $config[] = $dir.DIRECTORY_SEPARATOR.$file;
308
                        }
309
                    }
310
                    closedir($dh);
311
                }
312
            }
313
314
            return $config;
315
        } else {
316
            return 'null';
317
        }
318
    }
319
320
    public function fetchConfig()
321
    {
322
        $configs = $this->readConfigs();
323
        //dd($configs);
324
        $plugs = new Plugin();
325
        $fields = [];
326
        $attributes = [];
327
        if ($configs != 'null') {
328
            foreach ($configs as $key => $config) {
329
                $fields[$key] = include $config;
330
            }
331
        }
332
        //dd($fields);
333
        if (count($fields) > 0) {
334
            foreach ($fields as $key => $field) {
335
                $plug = $plugs->where('name', $field['name'])->select('path', 'status')->orderBy('name')->get()->toArray();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
336
                if ($plug) {
337
                    foreach ($plug as $i => $value) {
338
                        $attributes[$key]['path'] = $plug[$i]['path'];
339
                        $attributes[$key]['status'] = $plug[$i]['status'];
340
                    }
341
                } else {
342
                    $attributes[$key]['path'] = $field['name'];
343
                    $attributes[$key]['status'] = 0;
344
                }
345
                $attributes[$key]['name'] = $field['name'];
346
                $attributes[$key]['settings'] = $field['settings'];
347
                $attributes[$key]['description'] = $field['description'];
348
                $attributes[$key]['website'] = $field['website'];
349
                $attributes[$key]['version'] = $field['version'];
350
                $attributes[$key]['author'] = $field['author'];
351
            }
352
        }
353
        //dd($attributes);
354
        return $attributes;
355
    }
356
357
    public function deletePlugin($slug)
358
    {
359
        $dir = app_path().DIRECTORY_SEPARATOR.'Plugins'.DIRECTORY_SEPARATOR.$slug;
360
        $this->deleteDirectory($dir);
361
        /*
362
         * remove service provider from app.php
363
         */
364
        $str = "'App\\Plugins\\$slug"."\\ServiceProvider',";
365
        $path_to_file = base_path().DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'app.php';
366
        $file_contents = file_get_contents($path_to_file);
367
        $file_contents = str_replace($str, '//', $file_contents);
368
        file_put_contents($path_to_file, $file_contents);
369
        $plugin = new Plugin();
370
        $plugin = $plugin->where('path', $slug)->first();
371
        if ($plugin) {
372
            $plugin->delete();
373
        }
374
375
        return redirect()->back()->with('success', 'Deleted Successfully');
376
    }
377
378
    public function statusPlugin($slug)
379
    {
380
        $plugs = new Plugin();
381
        $plug = $plugs->where('name', $slug)->first();
382
        if (!$plug) {
383
            $app = base_path().DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'app.php';
384
            $str = "\n'App\\Plugins\\$slug"."\\ServiceProvider',";
385
            $line_i_am_looking_for = 102;
386
            $lines = file($app, FILE_IGNORE_NEW_LINES);
387
            $lines[$line_i_am_looking_for] = $str;
388
            file_put_contents($app, implode("\n", $lines));
389
            $plugs->create(['name' => $slug, 'path' => $slug, 'status' => 1]);
390
391
            return redirect()->back()->with('success', 'Status has changed');
392
        }
393
        $status = $plug->status;
394
        if ($status == 0) {
395
            $plug->status = 1;
396
397
            $app = base_path().DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'app.php';
398
            $str = "\n'App\\Plugins\\$slug"."\\ServiceProvider',";
399
            $line_i_am_looking_for = 102;
400
            $lines = file($app, FILE_IGNORE_NEW_LINES);
401
            $lines[$line_i_am_looking_for] = $str;
402
            file_put_contents($app, implode("\n", $lines));
403
        }
404
        if ($status == 1) {
405
            $plug->status = 0;
406
            /*
407
             * remove service provider from app.php
408
             */
409
            $str = "\n'App\\Plugins\\$slug"."\\ServiceProvider',";
410
            $path_to_file = base_path().DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'app.php';
411
412
            $file_contents = file_get_contents($path_to_file);
413
            $file_contents = str_replace($str, '//', $file_contents);
414
            file_put_contents($path_to_file, $file_contents);
415
        }
416
        $plug->save();
417
418
        return redirect()->back()->with('success', 'Status has changed');
419
    }
420
421
    public static function checkPaymentGateway($currency)
422
    {
423
        try {
424
            $plugins = new Plugin();
425
            $models = [];
426
            $gateways = 'Razorpay';
427
            // $active_plugins = $plugins->where('status', 1)->get();
428
            // if ($active_plugins->count() > 0) {
429
            //     foreach ($active_plugins as $plugin) {
430
            //         array_push($models, \DB::table(strtolower($plugin->name)));
431
            //     }
432
            //     if (count($models) > 0) {
433
            //         foreach ($models as $model) {
434
            //             if ($model->first()) {
435
            //                 $currencies = explode(',', $model->first()->currencies);
436
            //                 if (in_array($currency, $currencies)) {
437
            //                     array_push($gateways, $model);
438
            //                 }
439
            //             }
440
            //         }
441
            //     }
442
            // }
443
444
            return $gateways;
445
        } catch (\Exception $ex) {
446
            dd($ex);
447
        }
448
    }
449
450
    public function settingsSystem(Setting $settings)
451
    {
452
        try {
453
            $set = $settings->find(1);
454
455
            return view('themes.default1.common.setting.system', compact('set'));
456
        } catch (\Exception $ex) {
457
            return redirect()->back()->with('fails', $ex->getMessage());
458
        }
459
    }
460
461
    public function postSettingsSystem(Setting $settings, Request $request)
462
    {
463
        try {
464
            $setting = $settings->find(1);
465
            if ($request->hasFile('logo')) {
466
                $name = $request->file('logo')->getClientOriginalName();
467
                $destinationPath = public_path('cart/img/logo');
468
                $request->file('logo')->move($destinationPath, $name);
469
                $setting->logo = $name;
470
            }
471
            $setting->fill($request->except('password', 'logo'))->save();
472
473
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
474
        } catch (\Exception $ex) {
475
            return redirect()->back()->with('fails', $ex->getMessage());
476
        }
477
    }
478
479
    public function settingsEmail(Setting $settings)
480
    {
481
        try {
482
            $set = $settings->find(1);
483
484
            return view('themes.default1.common.setting.email', compact('set'));
485
        } catch (\Exception $ex) {
486
            return redirect()->back()->with('fails', $ex->getMessage());
487
        }
488
    }
489
490
    public function postSettingsEmail(Setting $settings, Request $request)
491
    {
492
        $this->validate($request, [
493
                'email'     => 'required',
494
                'password'  => 'required',
495
                'driver'    => 'required',
496
                'port'      => 'required',
497
                'encryption'=> 'required',
498
499
            ]);
500
501
        try {
502
            $setting = $settings->find(1);
503
            $setting->fill($request->input())->save();
504
505
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
506
        } catch (\Exception $ex) {
507
            return redirect()->back()->with('fails', $ex->getMessage());
508
        }
509
    }
510
511
    public function settingsTemplate(Setting $settings)
512
    {
513
        try {
514
            $set = $settings->find(1);
515
            $template = new Template();
516
            //$templates = $template->lists('name', 'id')->toArray();
517
            return view('themes.default1.common.setting.template', compact('set', 'template'));
518
        } catch (\Exception $ex) {
519
            return redirect()->back()->with('fails', $ex->getMessage());
520
        }
521
    }
522
523
    public function settingsActivity(Activity $activities)
524
    {
525
        try {
526
            $activity = $activities->all();
527
528
            return view('themes.default1.common.Activity-Log', compact('activity'));
529
        } catch (\Exception $ex) {
530
            return redirect()->back()->with('fails', $ex->getMessage());
531
        }
532
    }
533
534
    public function postSettingsTemplate(Setting $settings, Request $request)
535
    {
536
        try {
537
            $setting = $settings->find(1);
538
            $setting->fill($request->input())->save();
539
540
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
541
        } catch (\Exception $ex) {
542
            return redirect()->back()->with('fails', $ex->getMessage());
543
        }
544
    }
545
546
    public function settingsError(Setting $settings)
547
    {
548
        try {
549
            $set = $settings->find(1);
550
551
            return view('themes.default1.common.setting.error-log', compact('set'));
552
        } catch (\Exception $ex) {
553
            return redirect()->back()->with('fails', $ex->getMessage());
554
        }
555
    }
556
557
    public function settingsBugsnag(Setting $settings)
558
    {
559
        try {
560
            $set = $settings->find(1);
561
562
            return view('themes.default1.common.setting.bugsnag', compact('set'));
563
        } catch (\Exception $ex) {
564
            return redirect()->back()->with('fails', $ex->getMessage());
565
        }
566
    }
567
568
    public function postSettingsError(Setting $settings, Request $request)
569
    {
570
        try {
571
            $setting = $settings->find(1);
572
            $setting->fill($request->input())->save();
573
574
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
575
        } catch (\Exception $ex) {
576
            return redirect()->back()->with('fails', $ex->getMessage());
577
        }
578
    }
579
}
580