Completed
Push — development ( b504d8...633085 )
by Ashutosh
10:54 queued 10s
created

BaseSettingsController::execEnabled()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 3
nc 4
nop 0
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
68
    public function destroyEmail(Request $request)
69
    {
70
        try {
71
            $ids = $request->input('select');
72
            if (!empty($ids)) {
73
                foreach ($ids as $id) {
74
                    $email = \DB::table('email_log')->where('id', $id)->delete();
75
                    if ($email) {
76
                        // $email->delete();
77
                    } else {
78
                        echo "<div class='alert alert-danger alert-dismissable'>
79
                        <i class='fa fa-ban'></i>
80
81
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
82
                        /* @scrutinizer ignore-type */     \Lang::get('message.failed').'
83
84
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
85
                            './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
86
                    </div>';
87
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
88
                    }
89
                }
90
                echo "<div class='alert alert-success alert-dismissable'>
91
                        <i class='fa fa-ban'></i>
92
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '
93
                        ./* @scrutinizer ignore-type */\Lang::get('message.success').'
94
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
95
                            './* @scrutinizer ignore-type */ \Lang::get('message.deleted-successfully').'
96
                    </div>';
97
            } else {
98
                echo "<div class='alert alert-danger alert-dismissable'>
99
                        <i class='fa fa-ban'></i>
100
                        <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').
101
                        '!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
102
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
103
                            './* @scrutinizer ignore-type */ \Lang::get('message.select-a-row').'
104
                    </div>';
105
                //echo \Lang::get('message.select-a-row');
106
            }
107
        } catch (\Exception $e) {
108
            echo "<div class='alert alert-danger alert-dismissable'>
109
                        <i class='fa fa-ban'></i>
110
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
111
                        /* @scrutinizer ignore-type */\Lang::get('message.failed').'
112
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
113
                            '.$e->getMessage().'
114
                    </div>';
115
        }
116
    }
117
118
    public function advanceSearch($from = '', $till = '', $delFrom = '', $delTill = '')
119
    {
120
        $join = new Activity();
121
        if ($from) {
122
            $from = $this->getDateFormat($from);
123
            $tills = $this->getDateFormat();
124
            $tillDate = (new ExtendedOrderController())->getTillDate($from, $till, $tills);
125
            $join = $join->whereBetween('created_at', [$from, $tillDate]);
126
        }
127
        if ($till) {
128
            $till = $this->getDateFormat($till);
129
            $froms = Activity::first()->created_at;
130
            $fromDate = (new ExtendedOrderController())->getFromDate($from, $froms);
131
            $join = $join->whereBetween('created_at', [$fromDate, $till]);
132
        }
133
        if ($delFrom) {
134
            $from = $this->getDateFormat($delFrom);
135
            $tills = $this->getDateFormat();
136
            $tillDate = (new ExtendedOrderController())->getTillDate($from, $delTill, $tills);
137
            $join->whereBetween('created_at', [$from, $tillDate])->delete();
138
        }
139
        if ($delTill) {
140
            $till = $this->getDateFormat($delTill);
141
            $froms = Activity::first()->created_at;
142
            $fromDate = (new ExtendedOrderController())->getFromDate($delFrom, $froms);
143
            $join->whereBetween('created_at', [$fromDate, $till])->delete();
144
        }
145
        $join = $join->orderBy('created_at', 'desc')
146
        ->select(
147
            'id',
148
            'log_name',
149
            'description',
150
            'subject_id',
151
            'subject_type',
152
            'causer_id',
153
            'properties',
154
            'created_at'
155
        );
156
157
        return $join;
158
    }
159
160
  
161
162
    public function getScheduler(StatusSetting $status)
163
    {
164
        $cronPath = base_path('artisan');
165
        $status = $status->whereId('1')->first();
166
        $execEnabled = $this->execEnabled();
167
        $paths = $this->getPHPBinPath();
168
        // $command = ":- <pre>***** php $cronUrl schedule:run >> /dev/null 2>&1</pre>";
169
        // $shared = ":- <pre>/usr/bin/php-cli -q  $cronUrl schedule:run >> /dev/null 2>&1</pre>";
170
        $warn = '';
171
        $condition = new \App\Model\Mailjob\Condition();
172
173
        $commands = [
174
            'everyMinute'        => 'Every Minute',
175
            'everyFiveMinutes'   => 'Every Five Minute',
176
            'everyTenMinutes'    => 'Every Ten Minute',
177
            'everyThirtyMinutes' => 'Every Thirty Minute',
178
            'hourly'             => 'Every Hour',
179
            'daily'              => 'Every Day',
180
            'dailyAt'            => 'Daily at',
181
            'weekly'             => 'Every Week',
182
183
            'monthly' => 'Monthly',
184
            'yearly'  => 'Yearly',
185
        ];
186
187
        $expiryDays = [
188
            '120'=> '120 Days',
189
            '90' => '90 Days',
190
            '60' => '60 Days',
191
            '30' => '30 Days',
192
            '15' => '15 Days',
193
            '5'  => '5 Days',
194
            '3'  => '3 Days',
195
            '1'  => '1 Day',
196
            '0'  => 'On the Expiry Day',
197
        ];
198
199
        $selectedDays = [];
200
        $daysLists = ExpiryMailDay::get();
201
        if (count($daysLists) > 0) {
202
            foreach ($daysLists as $daysList) {
203
                $selectedDays[] = $daysList;
204
            }
205
        }
206
        $delLogDays = ['720' => '720 Days', '365'=>'365 days', '180'=>'180 Days',
207
        '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...
208
        $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...
209
210
        return view('themes.default1.common.cron.cron', compact(
211
            'cronPath',
212
            'warn',
213
            'commands',
214
            'condition',
215
            'status',
216
            'expiryDays',
217
            'selectedDays',
218
            'delLogDays',
219
            'beforeLogDay',
220
            'execEnabled',
221
            'paths'
222
        ));
223
    }
224
225
    public function postSchedular(StatusSetting $status, Request $request)
226
    {
227
        $allStatus = $status->whereId('1')->first();
228
        if ($request->expiry_cron) {
229
            $allStatus->expiry_mail = $request->expiry_cron;
230
        } else {
231
            $allStatus->expiry_mail = 0;
232
        }
233
        if ($request->activity) {
234
            $allStatus->activity_log_delete = $request->activity;
235
        } else {
236
            $allStatus->activity_log_delete = 0;
237
        }
238
        $allStatus->save();
239
        $this->saveConditions();
240
        /* redirect to Index page with Success Message */
241
        return redirect('job-scheduler')->with('success', \Lang::get('message.updated-successfully'));
242
    }
243
244
    /**
245
     * Check if exec() function is available.
246
     *
247
     * @return bool
248
     */
249
    private function execEnabled()
250
    {
251
        try {
252
            // make a small test
253
            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...
254
        } catch (\Exception $ex) {
255
            return false;
256
        }
257
    }
258
259
    private function getPHPBinPath()
260
    {
261
        $paths = [
262
            '/usr/bin/php',
263
            '/usr/local/bin/php',
264
            '/bin/php',
265
            '/usr/bin/php7',
266
            '/usr/bin/php7.1',
267
            '/usr/bin/php71',
268
            '/opt/plesk/php/7.1/bin/php',
269
        ];
270
        // try to detect system's PHP CLI
271
        if ($this->execEnabled()) {
272
            try {
273
                $paths = array_unique(array_merge($paths, explode(' ', exec('whereis php'))));
274
            } catch (\Exception $e) {
275
                // @todo: system logging here
276
                echo $e->getMessage();
277
            }
278
        }
279
280
        // validate detected / default PHP CLI
281
        // 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...
282
        $paths = array_values(array_filter($paths, function ($path) {
283
            return is_executable($path) && preg_match("/php[0-9\.a-z]{0,3}$/i", $path);
284
        }));
285
286
        return $paths;
287
    }
288
289
    protected function checkPHPExecutablePath(Request $request)
290
    {
291
        $path = $request->get('path');
292
        $version = '5.6';
293
        if (!file_exists($path) || !is_executable($path)) {
294
            return errorResponse(\Lang::get('message.invalid-php-path'));
295
        }
296
297
        if ($this->execEnabled()) {
298
            $exec_script = $path.' '.public_path('cron-test.php');
299
            $version = exec($exec_script, $output);
300
301
            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...
302
        } else {
303
            return successResponse(\Lang::get('message.please_enable_php_exec_for_cronjob_check'));
304
        }
305
    }
306
    
307
    //Save the Cron Days for expiry Mails and Activity Log
308
    public function saveCronDays(Request $request)
309
    {
310
        $daysList = new \App\Model\Mailjob\ExpiryMailDay();
311
        $lists = $daysList->get();
312
        if ($lists->count() > 0) {
313
            foreach ($lists as $list) {
314
                $list->delete();
315
            }
316
        }
317
        if ($request['expiryday'] != null) {
318
            foreach ($request['expiryday'] as $key => $value) {
319
                $daysList->create([
320
                'days'=> $value,
321
                ]);
322
            }
323
        }
324
        ActivityLogDay::findorFail(1)->update(['days'=>$request->logdelday]);
325
326
        return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
327
    }
328
329
    //Save Google recaptch site key and secret in Database
330
    public function captchaDetails(Request $request)
331
    {
332
        $status = $request->input('status');
333
        if ($status == 1) {
334
            $nocaptcha_sitekey = $request->input('nocaptcha_sitekey');
335
            $captcha_secretCheck = $request->input('nocaptcha_secret');
336
            $path_to_file = base_path('.env');
337
            $file_contents = file_get_contents($path_to_file);
338
            $file_contents_sitekey = str_replace(env('NOCAPTCHA_SITEKEY'), $nocaptcha_sitekey, $file_contents);
339
            file_put_contents($path_to_file, $file_contents_sitekey);
340
            $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...
341
            file_put_contents($path_to_file, $file_contents_nocaptcha_secret);
342
        } else {
343
            $nocaptcha_sitekey = '00';
344
            $captcha_secretCheck = '00';
345
            $path_to_file = base_path('.env');
346
            $file_contents = file_get_contents($path_to_file);
347
            $file_contents_sitekey = str_replace(env('NOCAPTCHA_SITEKEY'), $nocaptcha_sitekey, $file_contents);
348
            file_put_contents($path_to_file, $file_contents_sitekey);
349
350
            $file_contents_sitekey = str_replace(env('NOCAPTCHA_SECRET'), $captcha_secretCheck, $file_contents);
351
            file_put_contents($path_to_file, $file_contents_sitekey);
352
        }
353
354
        StatusSetting::where('id', 1)->update(['recaptcha_status'=>$status]);
355
        ApiKey::where('id', 1)->update(['nocaptcha_sitekey'=> $nocaptcha_sitekey,
356
         'captcha_secretCheck'                             => $captcha_secretCheck, ]);
357
358
        return ['message' => 'success', 'update'=>'Recaptcha Settings Updated'];
359
    }
360
}
361