Completed
Pull Request — development (#635)
by Ashutosh
09:42
created

BaseSettingsController::checkPHPExecutablePath()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 15
rs 9.6111
c 0
b 0
f 0
cc 5
nc 4
nop 1
1
<?php
2
3
namespace App\Http\Controllers\Common;
4
5
use App\ApiKey;
6
use App\Http\Controllers\Controller;
7
use App\Http\Controllers\Order\ExtendedOrderController;
8
use App\Model\Common\StatusSetting;
9
use App\Model\Mailjob\ActivityLogDay;
10
use App\Model\Mailjob\ExpiryMailDay;
11
use DateTime;
12
use DateTimeZone;
13
use Illuminate\Http\Request;
14
use Spatie\Activitylog\Models\Activity;
15
16
class BaseSettingsController extends Controller
17
{
18
    /**
19
     * Get the logged activity.
20
     */
21
    public function getNewEntry($properties, $model)
22
    {
23
        $properties = (array_key_exists('attributes', $properties->toArray()))
24
        ? ($model->properties['attributes']) : null;
25
26
        $display = [];
27
28
        if ($properties != null) {
29
            if (array_key_exists('parent', $properties)) {
30
                unset($properties['parent']);
31
            }
32
            foreach ($properties as $key => $value) {
33
                $display[] = '<strong>'.'ucfirst'($key).'</strong>'.' : '.$value.'<br/>';
34
            }
35
            $updated = (count($properties) > 0) ? implode('', $display) : '--';
36
37
            return $updated;
38
        } else {
39
            return '--';
40
        }
41
    }
42
43
    /**
44
     * Get the older Entries.
45
     */
46
    public function getOldEntry($data, $model)
47
    {
48
        $oldData = '';
49
        $oldData = (array_key_exists('old', $data->toArray())) ? ($model->properties['old']) : null;
50
        if ($oldData != null) {
51
            if ((count($oldData) > 0)) {
52
                foreach ($oldData as $key => $value) {
53
                    $display[] = '<strong>'.'ucfirst'($key).'</strong>'.' : '.$value.'<br/>';
54
                }
55
            }
56
            $old = (count($oldData) > 0) ? implode('', $display) : '--';
57
58
            return $old;
59
        } else {
60
            return '--';
61
        }
62
    }
63
64
    /**
65
     * Get Date.
66
     */
67
    public function getDate($dbdate)
68
    {
69
        $created = new DateTime($dbdate);
70
        $tz = \Auth::user()->timezone()->first()->name;
71
        $created->setTimezone(new DateTimeZone($tz));
72
        $date = $created->format('M j, Y, g:i a '); //5th October, 2018, 11:17PM
73
        $newDate = $date;
74
75
        return $newDate;
76
    }
77
78
    public function destroyEmail(Request $request)
79
    {
80
        try {
81
            $ids = $request->input('select');
82
            if (!empty($ids)) {
83
                foreach ($ids as $id) {
84
                    $email = \DB::table('email_log')->where('id', $id)->delete();
85
                    if ($email) {
86
                        // $email->delete();
87
                    } else {
88
                        echo "<div class='alert alert-danger alert-dismissable'>
89
                        <i class='fa fa-ban'></i>
90
91
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
92
                        /* @scrutinizer ignore-type */     \Lang::get('message.failed').'
93
94
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
95
                            './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
96
                    </div>';
97
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
98
                    }
99
                }
100
                echo "<div class='alert alert-success alert-dismissable'>
101
                        <i class='fa fa-ban'></i>
102
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '
103
                        ./* @scrutinizer ignore-type */\Lang::get('message.success').'
104
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
105
                            './* @scrutinizer ignore-type */ \Lang::get('message.deleted-successfully').'
106
                    </div>';
107
            } else {
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').
111
                        '!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
112
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
113
                            './* @scrutinizer ignore-type */ \Lang::get('message.select-a-row').'
114
                    </div>';
115
                //echo \Lang::get('message.select-a-row');
116
            }
117
        } catch (\Exception $e) {
118
            echo "<div class='alert alert-danger alert-dismissable'>
119
                        <i class='fa fa-ban'></i>
120
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
121
                        /* @scrutinizer ignore-type */\Lang::get('message.failed').'
122
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
123
                            '.$e->getMessage().'
124
                    </div>';
125
        }
126
    }
127
128
    public function advanceSearch($from = '', $till = '', $delFrom = '', $delTill = '')
129
    {
130
        $join = new Activity();
131
        if ($from) {
132
            $from = $this->getDateFormat($from);
133
            $tills = $this->getDateFormat();
134
            $tillDate = (new ExtendedOrderController())->getTillDate($from, $till, $tills);
135
            $join = $join->whereBetween('created_at', [$from, $tillDate]);
136
        }
137
        if ($till) {
138
            $till = $this->getDateFormat($till);
139
            $froms = Activity::first()->created_at;
140
            $fromDate = (new ExtendedOrderController())->getFromDate($from, $froms);
141
            $join = $join->whereBetween('created_at', [$fromDate, $till]);
142
        }
143
        if ($delFrom) {
144
            $from = $this->getDateFormat($delFrom);
145
            $tills = $this->getDateFormat();
146
            $tillDate = (new ExtendedOrderController())->getTillDate($from, $delTill, $tills);
147
            $join->whereBetween('created_at', [$from, $tillDate])->delete();
148
        }
149
        if ($delTill) {
150
            $till = $this->getDateFormat($delTill);
151
            $froms = Activity::first()->created_at;
152
            $fromDate = (new ExtendedOrderController())->getFromDate($delFrom, $froms);
153
            $join->whereBetween('created_at', [$fromDate, $till])->delete();
154
        }
155
        $join = $join->orderBy('created_at', 'desc')
156
        ->select('id', 'log_name', 'description',
157
                'subject_id', 'subject_type', 'causer_id', 'properties', 'created_at');
158
159
        return $join;
160
    }
161
162
    public function getDateFormat($dbdate = '')
163
    {
164
        $created = new DateTime($dbdate);
165
        $tz = \Auth::user()->timezone()->first()->name;
166
        $created->setTimezone(new DateTimeZone($tz));
167
        $date = $created->format('Y-m-d H:m:i');
168
169
        return $date;
170
    }
171
172
    public function getScheduler(StatusSetting $status)
173
    {
174
        $cronPath = base_path('artisan');
175
        $status = $status->whereId('1')->first();
176
        $execEnabled = $this->execEnabled();
177
        $paths = $this->getPHPBinPath();
178
        // $command = ":- <pre>***** php $cronUrl schedule:run >> /dev/null 2>&1</pre>";
179
        // $shared = ":- <pre>/usr/bin/php-cli -q  $cronUrl schedule:run >> /dev/null 2>&1</pre>";
180
        $warn = '';
181
        $condition = new \App\Model\Mailjob\Condition();
182
183
        // $job = $condition->checkActiveJob();
184
        $commands = [
185
            'everyMinute'        => 'Every Minute',
186
            'everyFiveMinutes'   => 'Every Five Minute',
187
            'everyTenMinutes'    => 'Every Ten Minute',
188
            'everyThirtyMinutes' => 'Every Thirty Minute',
189
            'hourly'             => 'Every Hour',
190
            'daily'              => 'Every Day',
191
            'dailyAt'            => 'Daily at',
192
            'weekly'             => 'Every Week',
193
194
            'monthly' => 'Monthly',
195
            'yearly'  => 'Yearly',
196
        ];
197
198
        $expiryDays = [
199
            '120'=> '120 Days',
200
            '90' => '90 Days',
201
            '60' => '60 Days',
202
            '30' => '30 Days',
203
            '15' => '15 Days',
204
            '5'  => '5 Days',
205
            '3'  => '3 Days',
206
            '1'  => '1 Day',
207
            '0'  => 'On the Expiry Day',
208
        ];
209
210
        $selectedDays = [];
211
        $daysLists = ExpiryMailDay::get();
212
        if (count($daysLists) > 0) {
213
            foreach ($daysLists as $daysList) {
214
                $selectedDays[] = $daysList;
215
            }
216
        }
217
        $delLogDays = ['720'=> '720 Days', '365'=>'365 days', '180'=>'180 Days',
218
       '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 150 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...
219
        $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...
220
221
        return view('themes.default1.common.cron.cron', compact('cronPath','warn', 'commands', 'condition',
222
             'status', 'expiryDays', 'selectedDays', 'delLogDays', 'beforeLogDay', 'execEnabled', 'paths'));
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
    public function saveConditions()
308
    {
309
        if (\Input::get('expiry-commands') && \Input::get('activity-commands')) {
310
            $expiry_commands = \Input::get('expiry-commands');
311
            $expiry_dailyAt = \Input::get('expiry-dailyAt');
312
            $activity_commands = \Input::get('activity-commands');
313
            $activity_dailyAt = \Input::get('activity-dailyAt');
314
            $activity_command = $this->getCommand($activity_commands, $activity_dailyAt);
315
            $expiry_command = $this->getCommand($expiry_commands, $expiry_dailyAt);
316
            $jobs = ['expiryMail' => $expiry_command, 'deleteLogs' =>  $activity_command];
317
            $this->storeCommand($jobs);
318
        }
319
    }
320
321
    public function getCommand($command, $daily_at)
322
    {
323
        if ($command == 'dailyAt') {
324
            $command = "dailyAt,$daily_at";
325
        }
326
327
        return $command;
328
    }
329
330
    public function storeCommand($array = [])
331
    {
332
        $command = new \App\Model\Mailjob\Condition();
333
        $commands = $command->get();
334
        if ($commands->count() > 0) {
335
            foreach ($commands as $condition) {
336
                $condition->delete();
337
            }
338
        }
339
        if (count($array) > 0) {
340
            foreach ($array as $key => $save) {
341
                $command->create([
342
                    'job'   => $key,
343
                    'value' => $save,
344
                ]);
345
            }
346
        }
347
    }
348
349
    //Save the Cron Days for expiry Mails and Activity Log
350
    public function saveCronDays(Request $request)
351
    {
352
        $daysList = new \App\Model\Mailjob\ExpiryMailDay();
353
        $lists = $daysList->get();
354
        if ($lists->count() > 0) {
355
            foreach ($lists  as $list) {
356
                $list->delete();
357
            }
358
        }
359
        if ($request['expiryday'] != null) {
360
            foreach ($request['expiryday'] as $key => $value) {
361
                $daysList->create([
362
          'days'=> $value,
363
           ]);
364
            }
365
        }
366
        ActivityLogDay::findorFail(1)->update(['days'=>$request->logdelday]);
367
368
        return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
369
    }
370
371
    public function licenseDetails(Request $request)
372
    {
373
        $status = $request->input('status');
374
        $licenseApiSecret = $request->input('license_api_secret');
375
        $licenseApiUrl = $request->input('license_api_url');
376
        StatusSetting::where('id', 1)->update(['license_status'=>$status]);
377
        ApiKey::where('id', 1)->update(['license_api_secret'=>$licenseApiSecret, 'license_api_url'=>$licenseApiUrl]);
378
379
        return ['message' => 'success', 'update'=>'Licensing Settings Updated'];
380
    }
381
382
    //Save Google recaptch site key and secret in Database
383
    public function captchaDetails(Request $request)
384
    {
385
        $status = $request->input('status');
386
        if ($status == 1) {
387
            $nocaptcha_sitekey = $request->input('nocaptcha_sitekey');
388
            $captcha_secretCheck = $request->input('nocaptcha_secret');
389
            $path_to_file = base_path('.env');
390
            $file_contents = file_get_contents($path_to_file);
391
            $file_contents_sitekey = str_replace(env('NOCAPTCHA_SITEKEY'), $nocaptcha_sitekey, $file_contents);
392
            file_put_contents($path_to_file, $file_contents_sitekey);
393
            $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...
394
            file_put_contents($path_to_file, $file_contents_nocaptcha_secret);
395
        } else {
396
            $nocaptcha_sitekey = '00';
397
            $captcha_secretCheck = '00';
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
403
            $file_contents_sitekey = str_replace(env('NOCAPTCHA_SECRET'), $captcha_secretCheck, $file_contents);
404
            file_put_contents($path_to_file, $file_contents_sitekey);
405
        }
406
407
        StatusSetting::where('id', 1)->update(['recaptcha_status'=>$status]);
408
        ApiKey::where('id', 1)->update(['nocaptcha_sitekey'=> $nocaptcha_sitekey,
409
         'captcha_secretCheck'                             => $captcha_secretCheck, ]);
410
411
        return ['message' => 'success', 'update'=>'Recaptcha Settings Updated'];
412
    }
413
}
414