Completed
Branch feature-dynamic-fields (3b03cc)
by Ashutosh
09:05
created

BaseSettingsController   D

Complexity

Total Complexity 59

Size/Duplication

Total Lines 405
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 59
eloc 237
dl 0
loc 405
rs 4.08
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A getDate() 0 9 1
A getCommand() 0 7 2
A getNewEntry() 0 19 6
A destroyEmail() 0 46 5
A getOldEntry() 0 15 6
A storeCommand() 0 14 5
A postSchedular() 0 17 3
A checkPHPExecutablePath() 0 15 5
A captchaDetails() 0 29 2
A advanceSearch() 0 40 5
A getDateFormat() 0 8 1
A getPHPBinPath() 0 28 4
A getScheduler() 0 60 3
A saveConditions() 0 11 3
A execEnabled() 0 7 3
A saveCronDays() 0 19 5

How to fix   Complexity   

Complex Class

Complex classes like BaseSettingsController 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 BaseSettingsController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers\Common;
4
5
use App\ApiKey;
6
use App\Http\Controllers\Order\ExtendedOrderController;
7
use App\Model\Common\StatusSetting;
8
use App\Model\Mailjob\ActivityLogDay;
9
use App\Model\Mailjob\ExpiryMailDay;
10
use App\Traits\ApiKeySettings;
11
use DateTime;
12
use DateTimeZone;
13
use Illuminate\Http\Request;
14
use Spatie\Activitylog\Models\Activity;
15
16
class BaseSettingsController extends PaymentSettingsController
17
{
18
    use ApiKeySettings;
19
20
    /**
21
     * Get the logged activity.
22
     */
23
    public function getNewEntry($properties, $model)
24
    {
25
        $properties = (array_key_exists('attributes', $properties->toArray()))
26
        ? ($model->properties['attributes']) : null;
27
28
        $display = [];
29
30
        if ($properties != null) {
31
            if (array_key_exists('parent', $properties)) {
32
                unset($properties['parent']);
33
            }
34
            foreach ($properties as $key => $value) {
35
                $display[] = '<strong>'.'ucfirst'($key).'</strong>'.' : '.$value.'<br/>';
36
            }
37
            $updated = (count($properties) > 0) ? implode('', $display) : '--';
38
39
            return $updated;
40
        } else {
41
            return '--';
42
        }
43
    }
44
45
    /**
46
     * Get the older Entries.
47
     */
48
    public function getOldEntry($data, $model)
49
    {
50
        $oldData = '';
51
        $oldData = (array_key_exists('old', $data->toArray())) ? ($model->properties['old']) : null;
52
        if ($oldData != null) {
53
            if ((count($oldData) > 0)) {
54
                foreach ($oldData as $key => $value) {
55
                    $display[] = '<strong>'.'ucfirst'($key).'</strong>'.' : '.$value.'<br/>';
56
                }
57
            }
58
            $old = (count($oldData) > 0) ? implode('', $display) : '--';
59
60
            return $old;
61
        } else {
62
            return '--';
63
        }
64
    }
65
66
    /**
67
     * Get Date.
68
     */
69
    public function getDate($dbdate)
70
    {
71
        $created = new DateTime($dbdate);
72
        $tz = \Auth::user()->timezone()->first()->name;
73
        $created->setTimezone(new DateTimeZone($tz));
74
        $date = $created->format('M j, Y, g:i a '); //5th October, 2018, 11:17PM
75
        $newDate = $date;
76
77
        return $newDate;
78
    }
79
80
    public function destroyEmail(Request $request)
81
    {
82
        try {
83
            $ids = $request->input('select');
84
            if (!empty($ids)) {
85
                foreach ($ids as $id) {
86
                    $email = \DB::table('email_log')->where('id', $id)->delete();
87
                    if ($email) {
88
                        // $email->delete();
89
                    } else {
90
                        echo "<div class='alert alert-danger alert-dismissable'>
91
                        <i class='fa fa-ban'></i>
92
93
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
94
                        /* @scrutinizer ignore-type */     \Lang::get('message.failed').'
95
96
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
97
                            './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
98
                    </div>';
99
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
100
                    }
101
                }
102
                echo "<div class='alert alert-success alert-dismissable'>
103
                        <i class='fa fa-ban'></i>
104
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '
105
                        ./* @scrutinizer ignore-type */\Lang::get('message.success').'
106
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
107
                            './* @scrutinizer ignore-type */ \Lang::get('message.deleted-successfully').'
108
                    </div>';
109
            } else {
110
                echo "<div class='alert alert-danger alert-dismissable'>
111
                        <i class='fa fa-ban'></i>
112
                        <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').
113
                        '!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
114
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
115
                            './* @scrutinizer ignore-type */ \Lang::get('message.select-a-row').'
116
                    </div>';
117
                //echo \Lang::get('message.select-a-row');
118
            }
119
        } catch (\Exception $e) {
120
            echo "<div class='alert alert-danger alert-dismissable'>
121
                        <i class='fa fa-ban'></i>
122
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
123
                        /* @scrutinizer ignore-type */\Lang::get('message.failed').'
124
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
125
                            '.$e->getMessage().'
126
                    </div>';
127
        }
128
    }
129
130
    public function advanceSearch($from = '', $till = '', $delFrom = '', $delTill = '')
131
    {
132
        $join = new Activity();
133
        if ($from) {
134
            $from = $this->getDateFormat($from);
135
            $tills = $this->getDateFormat();
136
            $tillDate = (new ExtendedOrderController())->getTillDate($from, $till, $tills);
137
            $join = $join->whereBetween('created_at', [$from, $tillDate]);
138
        }
139
        if ($till) {
140
            $till = $this->getDateFormat($till);
141
            $froms = Activity::first()->created_at;
142
            $fromDate = (new ExtendedOrderController())->getFromDate($from, $froms);
143
            $join = $join->whereBetween('created_at', [$fromDate, $till]);
144
        }
145
        if ($delFrom) {
146
            $from = $this->getDateFormat($delFrom);
147
            $tills = $this->getDateFormat();
148
            $tillDate = (new ExtendedOrderController())->getTillDate($from, $delTill, $tills);
149
            $join->whereBetween('created_at', [$from, $tillDate])->delete();
150
        }
151
        if ($delTill) {
152
            $till = $this->getDateFormat($delTill);
153
            $froms = Activity::first()->created_at;
154
            $fromDate = (new ExtendedOrderController())->getFromDate($delFrom, $froms);
155
            $join->whereBetween('created_at', [$fromDate, $till])->delete();
156
        }
157
        $join = $join->orderBy('created_at', 'desc')
158
        ->select(
159
            'id',
160
            'log_name',
161
            'description',
162
            'subject_id',
163
            'subject_type',
164
            'causer_id',
165
            'properties',
166
            'created_at'
167
        );
168
169
        return $join;
170
    }
171
172
    public function getDateFormat($dbdate = '')
173
    {
174
        $created = new DateTime($dbdate);
175
        $tz = \Auth::user()->timezone()->first()->name;
176
        $created->setTimezone(new DateTimeZone($tz));
177
        $date = $created->format('Y-m-d H:m:i');
178
179
        return $date;
180
    }
181
182
    public function getScheduler(StatusSetting $status)
183
    {
184
        $cronPath = base_path('artisan');
185
        $status = $status->whereId('1')->first();
186
        $execEnabled = $this->execEnabled();
187
        $paths = $this->getPHPBinPath();
188
        // $command = ":- <pre>***** php $cronUrl schedule:run >> /dev/null 2>&1</pre>";
189
        // $shared = ":- <pre>/usr/bin/php-cli -q  $cronUrl schedule:run >> /dev/null 2>&1</pre>";
190
        $warn = '';
191
        $condition = new \App\Model\Mailjob\Condition();
192
193
        $commands = [
194
            'everyMinute'        => 'Every Minute',
195
            'everyFiveMinutes'   => 'Every Five Minute',
196
            'everyTenMinutes'    => 'Every Ten Minute',
197
            'everyThirtyMinutes' => 'Every Thirty Minute',
198
            'hourly'             => 'Every Hour',
199
            'daily'              => 'Every Day',
200
            'dailyAt'            => 'Daily at',
201
            'weekly'             => 'Every Week',
202
203
            'monthly' => 'Monthly',
204
            'yearly'  => 'Yearly',
205
        ];
206
207
        $expiryDays = [
208
            '120'=> '120 Days',
209
            '90' => '90 Days',
210
            '60' => '60 Days',
211
            '30' => '30 Days',
212
            '15' => '15 Days',
213
            '5'  => '5 Days',
214
            '3'  => '3 Days',
215
            '1'  => '1 Day',
216
            '0'  => 'On the Expiry Day',
217
        ];
218
219
        $selectedDays = [];
220
        $daysLists = ExpiryMailDay::get();
221
        if (count($daysLists) > 0) {
222
            foreach ($daysLists as $daysList) {
223
                $selectedDays[] = $daysList;
224
            }
225
        }
226
        $delLogDays = ['720' => '720 Days', '365'=>'365 days', '180'=>'180 Days',
227
        '150'                => '150 Days', '60'=>'60 Days', '30'=>'30 Days', '15'=>'15 Days', '5'=>'5 Days', '2'=>'2 Days', '0'=>'Delete All Logs', ];
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 151 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...
228
        $beforeLogDay[] = ActivityLogDay::first()->days;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$beforeLogDay was never initialized. Although not strictly required by PHP, it is generally a good practice to add $beforeLogDay = array(); before regardless.
Loading history...
229
230
        return view('themes.default1.common.cron.cron', compact(
231
            'cronPath',
232
            'warn',
233
            'commands',
234
            'condition',
235
            'status',
236
            'expiryDays',
237
            'selectedDays',
238
            'delLogDays',
239
            'beforeLogDay',
240
            'execEnabled',
241
            'paths'
242
        ));
243
    }
244
245
    public function postSchedular(StatusSetting $status, Request $request)
246
    {
247
        $allStatus = $status->whereId('1')->first();
248
        if ($request->expiry_cron) {
249
            $allStatus->expiry_mail = $request->expiry_cron;
250
        } else {
251
            $allStatus->expiry_mail = 0;
252
        }
253
        if ($request->activity) {
254
            $allStatus->activity_log_delete = $request->activity;
255
        } else {
256
            $allStatus->activity_log_delete = 0;
257
        }
258
        $allStatus->save();
259
        $this->saveConditions();
260
        /* redirect to Index page with Success Message */
261
        return redirect('job-scheduler')->with('success', \Lang::get('message.updated-successfully'));
262
    }
263
264
    /**
265
     * Check if exec() function is available.
266
     *
267
     * @return bool
268
     */
269
    private function execEnabled()
270
    {
271
        try {
272
            // make a small test
273
            return function_exists('exec') && !in_array('exec', array_map('trim', explode(', ', ini_get('disable_functions'))));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 128 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...
274
        } catch (\Exception $ex) {
275
            return false;
276
        }
277
    }
278
279
    private function getPHPBinPath()
280
    {
281
        $paths = [
282
            '/usr/bin/php',
283
            '/usr/local/bin/php',
284
            '/bin/php',
285
            '/usr/bin/php7',
286
            '/usr/bin/php7.1',
287
            '/usr/bin/php71',
288
            '/opt/plesk/php/7.1/bin/php',
289
        ];
290
        // try to detect system's PHP CLI
291
        if ($this->execEnabled()) {
292
            try {
293
                $paths = array_unique(array_merge($paths, explode(' ', exec('whereis php'))));
294
            } catch (\Exception $e) {
295
                // @todo: system logging here
296
                echo $e->getMessage();
297
            }
298
        }
299
300
        // validate detected / default PHP CLI
301
        // Because array_filter() preserves keys, you should consider the resulting array to be an associative array even if the original array had integer keys for there may be holes in your sequence of keys. This means that, for example, json_encode() will convert your result array into an object instead of an array. Call array_values() on the result array to guarantee json_encode() gives you an array.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 407 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...
302
        $paths = array_values(array_filter($paths, function ($path) {
303
            return is_executable($path) && preg_match("/php[0-9\.a-z]{0,3}$/i", $path);
304
        }));
305
306
        return $paths;
307
    }
308
309
    protected function checkPHPExecutablePath(Request $request)
310
    {
311
        $path = $request->get('path');
312
        $version = '5.6';
313
        if (!file_exists($path) || !is_executable($path)) {
314
            return errorResponse(\Lang::get('message.invalid-php-path'));
315
        }
316
317
        if ($this->execEnabled()) {
318
            $exec_script = $path.' '.public_path('cron-test.php');
319
            $version = exec($exec_script, $output);
320
321
            return (version_compare($version, '7.1.3', '>=') == 1) ? successResponse(\Lang::get('message.valid-php-path')) : errorResponse(\Lang::get('message.invalid-php-version-or-path'));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 190 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...
322
        } else {
323
            return successResponse(\Lang::get('message.please_enable_php_exec_for_cronjob_check'));
324
        }
325
    }
326
327
    public function saveConditions()
328
    {
329
        if (\Input::get('expiry-commands') && \Input::get('activity-commands')) {
330
            $expiry_commands = \Input::get('expiry-commands');
331
            $expiry_dailyAt = \Input::get('expiry-dailyAt');
332
            $activity_commands = \Input::get('activity-commands');
333
            $activity_dailyAt = \Input::get('activity-dailyAt');
334
            $activity_command = $this->getCommand($activity_commands, $activity_dailyAt);
335
            $expiry_command = $this->getCommand($expiry_commands, $expiry_dailyAt);
336
            $jobs = ['expiryMail' => $expiry_command, 'deleteLogs' =>  $activity_command];
337
            $this->storeCommand($jobs);
338
        }
339
    }
340
341
    public function getCommand($command, $daily_at)
342
    {
343
        if ($command == 'dailyAt') {
344
            $command = "dailyAt,$daily_at";
345
        }
346
347
        return $command;
348
    }
349
350
    public function storeCommand($array = [])
351
    {
352
        $command = new \App\Model\Mailjob\Condition();
353
        $commands = $command->get();
354
        if ($commands->count() > 0) {
355
            foreach ($commands as $condition) {
356
                $condition->delete();
357
            }
358
        }
359
        if (count($array) > 0) {
360
            foreach ($array as $key => $save) {
361
                $command->create([
362
                    'job'   => $key,
363
                    'value' => $save,
364
                ]);
365
            }
366
        }
367
    }
368
369
    //Save the Cron Days for expiry Mails and Activity Log
370
    public function saveCronDays(Request $request)
371
    {
372
        $daysList = new \App\Model\Mailjob\ExpiryMailDay();
373
        $lists = $daysList->get();
374
        if ($lists->count() > 0) {
375
            foreach ($lists as $list) {
376
                $list->delete();
377
            }
378
        }
379
        if ($request['expiryday'] != null) {
380
            foreach ($request['expiryday'] as $key => $value) {
381
                $daysList->create([
382
                'days'=> $value,
383
                ]);
384
            }
385
        }
386
        ActivityLogDay::findorFail(1)->update(['days'=>$request->logdelday]);
387
388
        return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
389
    }
390
391
    //Save Google recaptch site key and secret in Database
392
    public function captchaDetails(Request $request)
393
    {
394
        $status = $request->input('status');
395
        if ($status == 1) {
396
            $nocaptcha_sitekey = $request->input('nocaptcha_sitekey');
397
            $captcha_secretCheck = $request->input('nocaptcha_secret');
398
            $path_to_file = base_path('.env');
399
            $file_contents = file_get_contents($path_to_file);
400
            $file_contents_sitekey = str_replace(env('NOCAPTCHA_SITEKEY'), $nocaptcha_sitekey, $file_contents);
401
            file_put_contents($path_to_file, $file_contents_sitekey);
402
            $file_contents_nocaptcha_secret = str_replace(env('NOCAPTCHA_SECRET'), $captcha_secretCheck, $file_contents);
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...
403
            file_put_contents($path_to_file, $file_contents_nocaptcha_secret);
404
        } else {
405
            $nocaptcha_sitekey = '00';
406
            $captcha_secretCheck = '00';
407
            $path_to_file = base_path('.env');
408
            $file_contents = file_get_contents($path_to_file);
409
            $file_contents_sitekey = str_replace(env('NOCAPTCHA_SITEKEY'), $nocaptcha_sitekey, $file_contents);
410
            file_put_contents($path_to_file, $file_contents_sitekey);
411
412
            $file_contents_sitekey = str_replace(env('NOCAPTCHA_SECRET'), $captcha_secretCheck, $file_contents);
413
            file_put_contents($path_to_file, $file_contents_sitekey);
414
        }
415
416
        StatusSetting::where('id', 1)->update(['recaptcha_status'=>$status]);
417
        ApiKey::where('id', 1)->update(['nocaptcha_sitekey'=> $nocaptcha_sitekey,
418
         'captcha_secretCheck'                             => $captcha_secretCheck, ]);
419
420
        return ['message' => 'success', 'update'=>'Recaptcha Settings Updated'];
421
    }
422
}
423