UpgradeController   C
last analyzed

Complexity

Total Complexity 66

Size/Duplication

Total Lines 412
Duplicated Lines 11.41 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
dl 47
loc 412
rs 5.7474
c 0
b 0
f 0
wmc 66
lcom 1
cbo 7

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
C getLatestVersion() 0 41 7
A downloadLatestCode() 0 16 2
B saveLatestCodeAtTemp() 0 24 3
C doUpdate() 0 73 10
B copyToActualDirectory() 0 29 3
A deleteBarNotification() 0 12 3
A fileUpdate() 0 15 3
B fileUpgrading() 0 22 4
A testScroll() 0 9 2
C fileUpgrading1() 0 50 10
A getCurl() 0 21 4
B postDownloadCurl() 23 23 4
B postCurl() 24 24 4
A databaseUpdate() 0 14 3
A databaseUpgrade() 0 14 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like UpgradeController 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 UpgradeController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers\Update;
4
5
use App\Http\Controllers\Controller;
6
use App\Http\Controllers\Utility\LibraryController as Utility;
7
use App\Model\Update\BarNotification;
8
use Artisan;
9
use Exception;
10
use Illuminate\Http\Request;
11
12
class UpgradeController extends Controller
13
{
14
    public $dir;
15
16
    public function __construct()
17
    {
18
        $dir = base_path();
19
        $this->dir = $dir;
20
    }
21
22
    public function getLatestVersion()
23
    {
24
        try {
25
            $name = \Config::get('app.name');
26
            //dd($name);
27
            //serial key should be encrypted data
28
            $serial_key = '64JAHF9WVJA4GCUZ';
29
            //order number should be encrypted data
30
            $order_number = '44596328';
31
            $url = env('APP_URL');
32
            $data = [
33
                'serial_key'   => $serial_key,
34
                'order_number' => $order_number,
35
                'name'         => $name,
36
                'version'      => Utility::getFileVersion(),
37
                'request_type' => 'check_update',
38
                'url'          => $url,
39
            ];
40
            $data = Utility::encryptByFaveoPublicKey(json_encode($data));
41
            //dd($data);
42
            $post_data = [
43
                'data' => $data,
44
            ];
45
            $url = 'http://faveohelpdesk.com/billing/public/verification';
46
            if (str_contains($url, ' ')) {
47
                $url = str_replace(' ', '%20', $url);
48
            }
49
            $curl = $this->postCurl($url, $post_data);
50
            if (is_array($curl)) {
51
                if (array_key_exists('status', $curl)) {
52
                    if ($curl['status'] == 'success') {
53
                        if (array_key_exists('version', $curl)) {
54
                            return $curl['version'];
55
                        }
56
                    }
57
                }
58
            }
59
        } catch (\Exception $ex) {
60
            return redirect()->back()->with('fails', $ex->getMessage());
61
        }
62
    }
63
64
    public function downloadLatestCode()
65
    {
66
        $name = \Config::get('app.name');
67
        $durl = 'http://www.faveohelpdesk.com/billing/public/download-url';
68
        if (str_contains($durl, ' ')) {
69
            $durl = str_replace(' ', '%20', $durl);
70
        }
71
        $data = [
72
            'name' => $name,
73
        ];
74
        $download = $this->postDownloadCurl($durl, $data);
75
76
        $download_url = $download['zipball_url'];
77
78
        return $download_url;
79
    }
80
81
    public function saveLatestCodeAtTemp($download_url)
82
    {
83
        echo '<p>Downloading New Update</p>';
84
        $context = stream_context_create(
85
                [
86
                    'http' => [
87
                        'header' => 'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
88
                    ],
89
                ]
90
        );
91
92
        $newUpdate = file_get_contents($download_url, false, $context);
93
        if (!is_dir("$this->dir/UPDATES/")) {
94
            \File::makeDirectory($this->dir.'/UPDATES/', 0777);
95
        }
96
97
        $dlHandler = fopen($this->dir.'/UPDATES/'.'/faveo-helpdesk-master.zip', 'w');
98
        if (!fwrite($dlHandler, $newUpdate)) {
99
            echo '<p>Could not save new update. Operation aborted.</p>';
100
            exit();
101
        }
102
        fclose($dlHandler);
103
        echo '<p>Update Downloaded And Saved</p>';
104
    }
105
106
    public function doUpdate()
107
    {
108
        try {
109
            $memory_limit = ini_get('memory_limit');
110
            if ($memory_limit < 256) {
111
                echo '<ul class=list-unstyled>';
112
                echo "<li style='color:red;'>Sorry we can not process your request because of limited memory! You have only  $memory_limit. For this you need atleast 256 MB</li>";
113
                echo '</ul>';
114
115
                return 0;
116
            }
117
            if (!extension_loaded('zip')) {
118
                echo '<ul class=list-unstyled>';
119
                echo "<li style='color:red;'>Sorry we can not process your request because you don't have ZIP extension contact your system admin</li>";
120
                echo '</ul>';
121
122
                return 0;
123
            }
124
            //Artisan::call('down');
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
125
            $update = $this->dir.'/UPDATES';
126
            //Open The File And Do Stuff
127
            $zipHandle = zip_open($update.'/faveo-helpdesk-master.zip');
128
            //dd($update . '/faveo-' . $aV . '.zip');
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
129
130
            echo '<ul class=list-unstyled>';
131
            while ($aF = zip_read($zipHandle)) {
132
                $thisFileName = zip_entry_name($aF);
133
                $thisFileDir = dirname($thisFileName);
134
135
                //Continue if its not a file
136
                if (substr($thisFileName, -1, 1) == '/') {
137
                    continue;
138
                }
139
140
                //Make the directory if we need to...
141
                if (!is_dir($update.'/'.$thisFileDir.'/')) {
142
                    \File::makeDirectory($update.'/'.$thisFileDir, 0775, true, true);
143
                    // mkdir($update.'/'. $thisFileDir, 0775);
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
144
                    echo '<li style="color:white;">Created Directory '.$thisFileDir.'</li>';
145
                }
146
147
                //Overwrite the file
148
                if (!is_dir($update.'/'.$thisFileName)) {
149
                    echo '<li style="color:white;">'.$thisFileName.'...........';
150
                    $contents = zip_entry_read($aF, zip_entry_filesize($aF));
151
                    $contents = str_replace("\r\n", "\n", $contents);
152
                    $updateThis = '';
153
154
                    //If we need to run commands, then do it.
155
                    if ($thisFileName == $thisFileDir.'/.env') {
156
                        if (is_file($update.'/'.$thisFileDir.'/.env')) {
157
                            unlink($update.'/'.$thisFileDir.'/.env');
158
                            unlink($update.'/'.$thisFileDir.'/config/database.php');
159
                        }
160
                        echo' EXECUTED</li>';
161
                    } else {
162
                        $updateThis = fopen($update.'/'.$thisFileName, 'w');
163
                        fwrite($updateThis, $contents);
164
                        fclose($updateThis);
165
                        unset($contents);
166
                        echo' UPDATED</li>';
167
                    }
168
                }
169
            }
170
            echo '</ul>';
171
            //Artisan::call('migrate', ['--force' => true]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
172
            return true;
173
        } catch (Exception $ex) {
174
            echo '<ul class=list-unstyled>';
175
            echo "<li style='color:red;'>".$ex->getMessage().'</li>';
176
            echo '</ul>';
177
        }
178
    }
179
180
    public function copyToActualDirectory($latest_version)
0 ignored issues
show
Unused Code introduced by
The parameter $latest_version is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
181
    {
182
        try {
183
            echo '<ul class=list-unstyled>';
184
            $directory = "$this->dir/UPDATES";
185
            $destination = $this->dir;
186
//        $destination = "/Applications/AMPPS/www/test/new";
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
187
            $directories = \File::directories($directory);
188
189
//        echo "current directory => $directory <br>";
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
190
//        echo "Destination Directory => $destination <br>";
191
            foreach ($directories as $source) {
192
                $success = \File::copyDirectory($source, $destination);
0 ignored issues
show
Unused Code introduced by
$success is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
193
                echo '<li class="success">&raquo; </li>';
194
            }
195
196
            \File::deleteDirectory($directory);
197
198
            $this->deleteBarNotification('new-version');
199
200
            echo "<li style='color:green;'>&raquo; Faveo Updated to v".Utility::getFileVersion().'</li>';
201
            echo '</ul>';
202
        } catch (Exception $ex) {
203
            echo '<ul class=list-unstyled>';
204
            echo "<li style='color:red;'>".$ex->getMessage().'</li>';
205
            echo '</ul>';
206
        }
207
        exit();
208
    }
209
210
    public function deleteBarNotification($key)
211
    {
212
        try {
213
            $noti = new BarNotification();
214
            $notifications = $noti->where('key', $key)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\Update\BarNotification>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
215
            foreach ($notifications as $notify) {
216
                $notify->delete();
217
            }
218
        } catch (Exception $ex) {
219
            throw new Exception($ex->getMessage());
220
        }
221
    }
222
223
    public function fileUpdate()
224
    {
225
        try {
226
            $latest_version = $this->getLatestVersion();
227
            if (Utility::getFileVersion() < $latest_version) {
228
                $url = url('file-upgrade');
229
230
                return view('themes.default1.update.file', compact('url'));
231
            }
232
233
            return redirect('dashboard')->with('fails', 'Could not find latest realeases from repository.');
234
        } catch (Exception $ex) {
235
            return redirect()->back()->with('fails', $ex->getMessage());
236
        }
237
    }
238
239
    public function fileUpgrading(Request $request)
240
    {
241
        try {
242
            //
243
            $latest_version = $this->getLatestVersion();
244
245
            $current_version = Utility::getFileVersion();
246
            if ($latest_version != '') {
247
                if (Utility::getFileVersion() < $latest_version) {
248
                    return view('themes.default1.update.update', compact('latest_version', 'current_version', 'request'));
249
                }
250
            }
251
252
            return redirect('dashboard')->with('fails', 'Could not find latest realeases from repository.');
253
254
//            else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
255
//                return redirect()->back();
256
//            }
257
        } catch (Exception $ex) {
258
            return redirect()->back()->with('fails', $ex->getMessage());
259
        }
260
    }
261
262
    public function testScroll()
263
    {
264
        $ex = 1000;
265
        echo '<ul style=list-unstyled>';
266
        for ($i = 0; $i < $ex; $i++) {
267
            echo "<li style='color:white;'>updated</li>";
268
        }
269
        echo '</ul>';
270
    }
271
272
    public function fileUpgrading1(Request $request)
273
    {
274
        if (Utility::getFileVersion() < Utility::getDatabaseVersion()) {
275
            $latest_version = $this->getLatestVersion();
276
//            dd($latest_version);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
277
            $current_version = Utility::getFileVersion();
278
            //dd($current_version);
279
            if ($latest_version != '') {
280
                echo "<p>CURRENT VERSION: $current_version</p>";
281
                echo '<p>Reading Current Releases List</p>';
282
                if ($latest_version > $current_version) {
283
                    echo '<p>New Update Found: v'.$latest_version.'</p>';
284
                    $found = true;
285
                    if (!is_file("$this->dir/UPDATES/faveo-helpdesk-master.zip")) {
286
                        if ($request->get('dodownload') == true) {
287
                            $download_url = $this->downloadLatestCode();
288
                            if ($download_url != null) {
289
                                $this->saveLatestCodeAtTemp($download_url);
290
                            } else {
291
                                echo '<p>Error in you network connection.</p>';
292
                            }
293
                        } else {
294
                            echo '<p>Latest code found. <a href='.url('file-upgrade?dodownload=true').'>&raquo; Download Now?</a></p>';
295
                            exit();
296
                        }
297
                    } else {
298
                        echo '<p>Update already downloaded.</p>';
299
                    }
300
                    if ($request->get('doUpdate') == true) {
301
                        $updated = $this->doUpdate();
302
                    } else {
303
                        echo '<p>Update ready. <a href='.url('file-upgrade?doUpdate=true').'>&raquo; Install Now?</a></p>';
304
                        exit();
305
                    }
306
307
                    if ($updated == true) {
308
                        $this->copyToActualDirectory($latest_version);
309
                    } elseif ($found != true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison !== instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
310
                        echo '<p>&raquo; No update is available.</p>';
311
                    }
312
                } else {
313
                    echo '<p>Could not find latest realeases.</p>';
314
                }
315
            } else {
316
                echo '<p>Could not find latest realeases from repository.</p>';
317
            }
318
        } else {
319
            return redirect()->back();
320
        }
321
    }
322
323
    public function getCurl($url)
324
    {
325
        try {
326
            $curl = Utility::_isCurl();
327
            if (!$curl) {
328
                throw new Exception('Please enable your curl function to check latest update');
329
            }
330
            $ch = curl_init();
331
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
332
            curl_setopt($ch, CURLOPT_URL, $url);
333
            if (curl_exec($ch) === false) {
334
                echo 'Curl error: '.curl_error($ch);
335
            }
336
            $data = curl_exec($ch);
337
            curl_close($ch);
338
339
            return $data;
340
        } catch (Exception $ex) {
341
            return redirect()->back()->with('fails', $ex->getMessage());
342
        }
343
    }
344
345 View Code Duplication
    public function postDownloadCurl($url, $data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
346
    {
347
        try {
348
            $curl = Utility::_isCurl();
349
            if (!$curl) {
350
                throw new Exception('Please enable your curl function to check latest update');
351
            }
352
            $ch = curl_init();
353
            curl_setopt($ch, CURLOPT_POST, 1);
354
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
355
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
356
            curl_setopt($ch, CURLOPT_URL, $url);
357
            if (curl_exec($ch) === false) {
358
                echo 'Curl error: '.curl_error($ch);
359
            }
360
            $data = curl_exec($ch);
361
            curl_close($ch);
362
363
            return json_decode($data, true);
364
        } catch (Exception $ex) {
365
            return redirect()->back()->with('fails', $ex->getMessage());
366
        }
367
    }
368
369 View Code Duplication
    public function postCurl($url, $data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
370
    {
371
        try {
372
            $curl = Utility::_isCurl();
373
            if (!$curl) {
374
                throw new Exception('Please enable your curl function to check latest update');
375
            }
376
            $ch = curl_init();
377
            curl_setopt($ch, CURLOPT_POST, 1);
378
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
379
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
380
            curl_setopt($ch, CURLOPT_URL, $url);
381
            if (curl_exec($ch) === false) {
382
                echo 'Curl error: '.curl_error($ch);
383
            }
384
            $data = curl_exec($ch);
385
            curl_close($ch);
386
            $data = Utility::decryptByFaveoPrivateKey($data);
387
388
            return json_decode($data, true);
389
        } catch (Exception $ex) {
390
            return redirect()->back()->with('fails', $ex->getMessage());
391
        }
392
    }
393
394
    public function databaseUpdate()
395
    {
396
        try {
397
            if (Utility::getFileVersion() > Utility::getDatabaseVersion()) {
398
                $url = url('database-upgrade');
399
                //$string = "Your Database is outdated please upgrade <a href=$url>Now !</a>";
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
400
                return view('themes.default1.update.database', compact('url'));
401
            } else {
402
                return redirect()->back();
403
            }
404
        } catch (Exception $ex) {
405
            return redirect()->back()->with('fails', $ex->getMessage());
406
        }
407
    }
408
409
    public function databaseUpgrade()
410
    {
411
        try {
412
            if (Utility::getFileVersion() > Utility::getDatabaseVersion()) {
413
                Artisan::call('migrate', ['--force' => true]);
414
415
                return redirect('dashboard')->with('success', 'Database updated');
416
            } else {
417
                return redirect()->back();
418
            }
419
        } catch (Exception $ex) {
420
            return redirect()->back()->with('fails', $ex->getMessage());
421
        }
422
    }
423
}
424