Completed
Push — master ( b78da7...95d421 )
by vijay
129:37 queued 84:16
created

HomeController   B

Complexity

Total Complexity 54

Size/Duplication

Total Lines 348
Duplicated Lines 8.33 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 6
Bugs 3 Features 0
Metric Value
c 6
b 3
f 0
dl 29
loc 348
rs 7.0642
wmc 54
lcom 1
cbo 5

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A index() 0 4 1
B version() 0 25 3
A getVersion() 0 14 2
A versionTest() 0 10 1
A versionResult() 0 4 1
B serial() 0 44 4
B decryptByFaveoPrivateKey() 0 33 5
A getEncryptedData() 0 5 1
A createEncryptionKeys() 0 22 2
A checkSerialKey() 0 17 4
A checkOrder() 0 14 3
A checkDomain() 15 15 3
A verifyOrder() 14 14 2
B faveoVerification() 0 26 4
B verificationResult() 0 16 6
B checkUpdate() 0 15 6
B checkFaveoDetails() 0 21 5

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

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Model\Order\Order;
6
use App\Model\Product\Product;
7
use Illuminate\Http\Request;
8
use Exception;
9
10
class HomeController extends Controller
11
{
12
    /*
13
      |--------------------------------------------------------------------------
14
      | Home Controller
15
      |--------------------------------------------------------------------------
16
      |
17
      | This controller renders your application's "dashboard" for users that
18
      | are authenticated. Of course, you are free to change or remove the
19
      | controller as you wish. It is just here to get your app started!
20
      |
21
     */
22
23
    /**
24
     * Create a new controller instance.
25
     *
26
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
27
     */
28
    public function __construct()
29
    {
30
        $this->middleware('auth', ['only' => ['index']]);
31
        $this->middleware('admin', ['only' => ['index']]);
32
    }
33
34
    /**
35
     * Show the application dashboard to the user.
36
     *
37
     * @return Response
38
     */
39
    public function index()
40
    {
41
        return view('themes.default1.layouts.master');
42
    }
43
44
    public function version(Request $request, Product $product)
45
    {
46
        $url = $request->input('response_url');
47
48
        $title = $request->input('title');
49
        //dd($title);
50
        $id = $request->input('id');
51
        if ($id) {
52
            $product = $product->where('id', $id)->first();
53
        } else {
54
            $product = $product->where('name', $title)->first();
55
        }
56
57
        if ($product) {
58
            $version = str_replace('v', '', $product->version);
59
        } else {
60
            $version = 'Not-Available';
61
        }
62
63
        echo "<form action=$url method=post name=redirect >";
64
        echo '<input type=hidden name=_token value='.csrf_token().'>';
65
        echo "<input type=hidden name=value value=$version />";
66
        echo '</form>';
67
        echo"<script language='javascript'>document.redirect.submit();</script>";
68
    }
69
70
    public function getVersion(Request $request, Product $product)
71
    {
72
        $this->validate($request, [
73
            'title' => 'required',
74
        ]);
75
        $title = $request->input('title');
76
        $product = $product->where('name', $title)->first();
77
        if ($product) {
78
            $version = $product->version;
0 ignored issues
show
Unused Code introduced by
$version 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...
79
        } else {
80
            return 0;
81
        }
82
        return str_replace('v', '', $product->version);
83
    }
84
85
    public function versionTest() {
86
        $s = "eyJpdiI6ImFIVDByR29vVzNpcEExM2UyNDVaWXc9PSIsInZhbHVlIjoiODNJS0MxWXFyVEtrYjhZYXFmUFlvOTJYY09NUHhGYTZBemN2eFMzckZCST0iLCJtYWMiOiI2MDdmZTU5YmRjMjQxOWRlZjE3ODUyMWI0OTk5NDM5ZmQxMWE5ZTUyNzQ3YTMyOGQyYmRmNGVkYWQyNDM5ZTNkIn0=";
87
        dd(decrypt($s));
88
        $url = "http://localhost/billings/agorainvoicing/agorainvoicing/public/version";
0 ignored issues
show
Unused Code introduced by
$url 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...
89
        $response = "http://localhost/billings/agorainvoicing/agorainvoicing/public/version-result";
0 ignored issues
show
Unused Code introduced by
$response 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...
90
        $name = "faveo helpdesk community";
0 ignored issues
show
Unused Code introduced by
$name 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...
91
        $version = $product->version;
0 ignored issues
show
Unused Code introduced by
$version 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...
Bug introduced by
The variable $product does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
92
93
        return str_replace('v', '', $product->version);
94
    }
95
96
    
97
98
    public function versionResult(Request $request)
99
    {
100
        dd($request->all());
101
    }
102
103
    public function serial(Request $request, Order $order)
104
    {
105
        $ul = $request->input('url');
106
        $url = str_replace('serial', 'CheckSerial', $ul);
107
        $domain = $request->input('domain');
108
        $first = $request->input('first');
109
        $second = $request->input('second');
110
        $third = $request->input('third');
111
        $forth = $request->input('forth');
112
        $serial = $first.$second.$third.$forth;
113
        //dd($serial);
114
        $order_no = $request->input('order_no');
115
        $order = $order->where('number', $order_no)->first();
116
        if ($order) {
117
            if ($domain === $order->domain) {
118
                $key = $order->serial_key;
119
                if ($key === $serial) {
120
                    $id1 = 'true';
121
                    echo "<form action=$url/$id1 method=post name=redirect>";
122
                    echo '<input type=hidden name=_token value=csrf_token()/>';
123
                    echo '</form>';
124
                    echo"<script language='javascript'>document.redirect.submit();</script>";
125
                } else {
126
                    $id = 'false1';
127
                    echo "<form action=$url/$id method=post name=redirect>";
128
                    echo '<input type=hidden name=_token value=csrf_token()/>';
129
                    echo '</form>';
130
                    echo"<script language='javascript'>document.redirect.submit();</script>";
131
                }
132
            } else {
133
                $id = 'false3';
134
                echo "<form action=$url/$id method=post name=redirect>";
135
                echo '<input type=hidden name=_token value=csrf_token()/>';
136
                echo '</form>';
137
                echo"<script language='javascript'>document.redirect.submit();</script>";
138
            }
139
        } else {
140
            $id = 'false2';
141
            echo "<form action=$url/$id method=post name=redirect>";
142
            echo '<input type=hidden name=_token value=csrf_token()/>';
143
            echo '</form>';
144
            echo"<script language='javascript'>document.redirect.submit();</script>";
145
        }
146
    }
147
148
    public static function decryptByFaveoPrivateKey($encrypted) {
149
        try {
150
            // Get the private Key
151
            $path = storage_path('app/faveo-private.key');
152
            $key_content = file_get_contents($path);
153
            if (!$privateKey = openssl_pkey_get_private($key_content)) {
154
                throw new \Exception('Private Key failed');
155
            }
156
            $a_key = openssl_pkey_get_details($privateKey);
157
158
            // Decrypt the data in the small chunks
159
            $chunkSize = ceil($a_key['bits'] / 8);
160
            $output = '';
161
162
            while ($encrypted) {
163
                $chunk = substr($encrypted, 0, $chunkSize);
164
                $encrypted = substr($encrypted, $chunkSize);
165
                $decrypted = '';
166
                if (!openssl_private_decrypt($chunk, $decrypted, $privateKey)) {
167
                    die('Failed to decrypt data');
168
                }
169
                $output .= $decrypted;
170
            }
171
            openssl_free_key($privateKey);
172
173
            // Uncompress the unencrypted data.
174
            $output = gzuncompress($output);
175
176
            return $output;
177
        } catch (\Exception $ex) {
178
            dd($ex);
179
        }
180
    }
181
182
    public function getEncryptedData(Request $request) {
183
        $enc = $request->input('en');
184
        $result = self::decryptByFaveoPrivateKey($enc);
185
        return response()->json($result);
186
    }
187
188
    public function createEncryptionKeys() {
189
        try {
190
            $privateKey = openssl_pkey_new(array(
191
                'private_key_bits' => 2048, // Size of Key.
192
                'private_key_type' => OPENSSL_KEYTYPE_RSA,
193
            ));
194
            //dd($privateKey);
195
            // Save the private key to private.key file. Never share this file with anyone.
196
            openssl_pkey_export_to_file($privateKey, 'faveo-private-new.key');
197
198
            // Generate the public key for the private key
199
            $a_key = openssl_pkey_get_details($privateKey);
200
            //dd($a_key);
201
            // Save the public key in public.key file. Send this file to anyone who want to send you the encrypted data.
202
            file_put_contents('faveo-public-new.key', $a_key['key']);
203
204
            // Free the private Key.
205
            openssl_free_key($privateKey);
206
        } catch (\Exception $ex) {
207
            dd($ex);
208
        }
209
    }
210
211
    public function checkSerialKey($faveo_encrypted_key,$order_number) {
212
        try {
213
            $order = new Order();
214
            $faveo_decrypted_key = self::decryptByFaveoPrivateKey($faveo_encrypted_key);
215
            $this_order = $order->where('number', $order_number)->first();
216
            if (!$this_order) {
217
                return null;
218
            } else {
219
               if($this_order->serial_key == $faveo_decrypted_key){
220
                   return $this_order->serial_key;
221
               }
222
            }
223
            return null;
224
        } catch (Exception $ex) {
225
            throw new Exception($ex->getMessage());
226
        }
227
    }
228
229
    public function checkOrder($faveo_encrypted_order_number) {
230
        try {
231
            $order = new Order();
232
            $faveo_decrypted_order = self::decryptByFaveoPrivateKey($faveo_encrypted_order_number);
233
            $this_order = $order->where('number', $faveo_decrypted_order)->first();
234
            if (!$this_order) {
235
                return null;
236
            } else {
237
                return $this_order->number;
238
            }
239
        } catch (Exception $ex) {
240
            throw new Exception($ex->getMessage());
241
        }
242
    }
243
244 View Code Duplication
    public function checkDomain($request_url) {
245
        try {
246
//            echo $request_url;
247
//            exit();
248
            $order = new Order();
249
            $this_order = $order->where('domain', $request_url)->first();
250
            if (!$this_order) {
251
                return null;
252
            } else {
253
                return $this_order->domain;
254
            }
255
        } catch (Exception $ex) {
256
            throw new Exception($ex->getMessage());
257
        }
258
    }
259
260 View Code Duplication
    public function verifyOrder($order_number, $serial_key, $domain) {
261
        try {
262
            
263
            $order = new Order();
264
            $this_order = $order
265
                    ->where('number', $order_number)
266
                   // ->where('serial_key', $serial_key)
267
                    ->where('domain', $domain)
268
                    ->first();
269
            return $this_order;
270
        } catch (Exception $ex) {
271
            throw new Exception($ex->getMessage());
272
        }
273
    }
274
275
    public function faveoVerification(Request $request) {
276
        try {
277
            $url = $request->input('url');
278
            $faveo_encrypted_order_number = $request->input('order_number');
279
            $faveo_encrypted_key = $request->input('serial_key');
280
            $request_type = $request->input('request_type');
281
            $faveo_name = $request->input('name');
282
            $faveo_version = $request->input('version');
283
            $order_number = $this->checkOrder($faveo_encrypted_order_number);
284
            $domain = $this->checkDomain($url);
285
            $serial_key = $this->checkSerialKey($faveo_encrypted_key,$order_number);
286
            //return $serial_key;
287
            $result = [];
288
            if ($request_type == 'install') {
289
                $result = $this->verificationResult($order_number, $serial_key, $domain);
290
            }
291
            if ($request_type == 'check_update') {
292
                $result = $this->checkUpdate($order_number, $serial_key, $domain, $faveo_name, $faveo_version);
293
            }
294
           
295
            return response()->json($result);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type null; however, Illuminate\Contracts\Rou...ResponseFactory::json() does only seem to accept string|array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
296
        } catch (Exception $ex) {
297
            $result = ['status' => 'error', 'message' => $ex->getMessage()];
298
            return response()->json($result);
299
        }
300
    }
301
302
    public function verificationResult($order_number, $serial_key, $domain) {
303
        try {
304
305
            if ($order_number && $domain && $serial_key) {
306
                $order = $this->verifyOrder($order_number, $serial_key, $domain);
307
                if ($order) {
308
                    return ['status' => 'success', 'message' => 'This is a valid request'];
309
                }
310
            } else {
311
                return ['status' => 'fails', 'message' => 'This is an invalid request'];
312
            }
313
            
314
        } catch (Exception $ex) {
315
            throw new Exception($ex->getMessage());
316
        }
317
    }
318
319
    public function checkUpdate($order_number, $serial_key, $domain, $faveo_name, $faveo_version) {
320
        try {
321
            if ($order_number && $domain && $serial_key) {
322
                $order = $this->verifyOrder($order_number, $serial_key, $domain);
323
                //var_dump($order);
324
                if ($order) {
325
                    return $this->checkFaveoDetails($order_number, $faveo_name, $faveo_version);
326
                }
327
            } else {
328
                return ['status' => 'fails', 'message' => 'This is an invalid request'];
329
            }
330
        } catch (Exception $ex) {
331
            throw new Exception($ex->getMessage());
332
        }
333
    }
334
335
    public function checkFaveoDetails($order_number, $faveo_name, $faveo_version) {
336
        try {
337
            $order = new Order();
338
            $product = new Product();
339
            $this_order = $order->where('number', $order_number)->first();
340
            if ($this_order) {
341
                $product_id = $this_order->product;
342
                if($product_id){
343
                    $this_product = $product->where('id',$product_id)->first();
344
                    if($this_product){
345
                        $version = str_replace('v', '', $this_product->version);
346
                        return ['status' => 'success', 'message' => 'This is a valid request','version'=>$version];
347
                    }
348
                }
349
            }
350
            return ['status' => 'fails', 'message' => 'This is an invalid request'];
351
            
352
        } catch (Exception $ex) {
353
            throw new Exception($ex->getMessage());
354
        }
355
    }
356
357
}
358