Passed
Push — master ( 95e7d1...09ce37 )
by Ferry
04:01
created

DeveloperPluginStoreController::recursiveCopy()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 9
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 14
rs 9.6111
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: User
5
 * Date: 4/25/2019
6
 * Time: 9:28 PM
7
 */
8
9
namespace crocodicstudio\crudbooster\controllers;
10
11
use crocodicstudio\crudbooster\exceptions\CBValidationException;
12
use crocodicstudio\crudbooster\helpers\CurlHelper;
13
use crocodicstudio\crudbooster\helpers\ModuleGenerator;
14
use Illuminate\Support\Facades\Cache;
15
use Illuminate\Support\Facades\DB;
16
use Illuminate\Support\Facades\Hash;
17
18
class DeveloperPluginStoreController extends Controller
19
{
20
21
    private $view = "crudbooster::dev_layouts.modules.plugin";
22
23
    public function __construct()
24
    {
25
        view()->share(['page_title'=>'Plugin Store']);
26
    }
27
28
29
    public function getIndex() {
30
31
        if(request("refresh")) {
32
            $this->fetchPluginData(false );
33
            return cb()->redirectBack("Plugin list has been refreshed!","success");
34
        }
35
36
        $data = [];
37
        $data['result'] = $this->fetchPluginData();
38
        return view($this->view.'.index',$data);
39
    }
40
41
    public function postLoginAccount() {
42
        $curl = new CurlHelper("http://crudbooster.com/api/login_member");
43
        $curl->headers([
44
            "Access-Token"=>"bVc/ZnpYNSZrMVZYOHE5U2tqcSU=",
45
            "User-Agent"=>"CRUDBooster-Bot-Client"
46
        ]);
47
        $curl->data([
48
            "email"=>request("email"),
49
            "password"=>request("password")
50
        ]);
51
        $response = $curl->send();
52
53
        if($respArray = json_decode($response, true)) {
54
            if($respArray['status'] && isset($respArray['token'])) {
55
                session(['account_token'=>$respArray['token']]);
56
            }
57
            return response()->make($response,200,["Content-Type"=>"application/json"]);
58
        } else {
59
            return response()->json(['status'=>false,'message'=>'failed']);
60
        }
61
    }
62
63
    public function postRequestBuyPlugin() {
64
        $curl = new CurlHelper("http://crudbooster.com/api/request_buy_plugin");
65
        $curl->headers([
66
            "Access-Token"=>"bVc/ZnpYNSZrMVZYOHE5U2tqcSU=",
67
            "User-Agent"=>"CRUDBooster-Bot-Client"
68
        ]);
69
        $curl->data([
70
            "key"=>base64_encode(request("key")),
0 ignored issues
show
Bug introduced by
It seems like request('key') can also be of type array; however, parameter $data of base64_encode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

70
            "key"=>base64_encode(/** @scrutinizer ignore-type */ request("key")),
Loading history...
71
            "token"=>base64_encode(request("token")),
72
            "ref"=>base64_encode(cb()->getDeveloperUrl("plugins"))
73
        ]);
74
        $response = $curl->send();
75
76
        if($respArray = json_decode($response, true)) {
77
            if($respArray['status']) {
78
                $form = base64_decode($respArray['payment']);
79
                return response()->json(['status'=>true,'form'=>$form]);
80
            } else {
81
                return response()->json($respArray);
82
            }
83
        } else {
84
            return response()->json(['status'=>false,'message'=>'failed','raw'=>$response]);
85
        }
86
    }
87
88
    public function getUninstall($key)
89
    {
90
        $pluginData = $this->fetchPluginData();
91
92
        if(isset($pluginData[$key])) {
93
            if(file_exists(app_path("CBPlugins/".$key))) {
94
                rrmdir(app_path("CBPlugins/".$key));
95
                return response()->json(['status'=>true, 'message'=>'Plugin has been uninstalled!']);
96
            }else{
97
                return response()->json(['status'=>false,'message'=>'Failed to uninstall, plugin is not found']);
98
            }
99
        }else {
100
            return response()->json(['status'=>false,'message'=>'Failed to uninstall, plugin key is not found']);
101
        }
102
    }
103
104
    private function recursiveCopy($src,$dst) {
105
        $dir = opendir($src);
106
        @mkdir($dst);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

106
        /** @scrutinizer ignore-unhandled */ @mkdir($dst);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
107
        while(false !== ( $file = readdir($dir)) ) {
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type false; however, parameter $dir_handle of readdir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

107
        while(false !== ( $file = readdir(/** @scrutinizer ignore-type */ $dir)) ) {
Loading history...
108
            if (( $file != '.' ) && ( $file != '..' )) {
109
                if ( is_dir($src . '/' . $file) ) {
110
                    $this->recursiveCopy($src . '/' . $file,$dst . '/' . $file);
111
                }
112
                else {
113
                    copy($src . '/' . $file,$dst . '/' . $file);
114
                }
115
            }
116
        }
117
        closedir($dir);
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type false; however, parameter $dir_handle of closedir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

117
        closedir(/** @scrutinizer ignore-type */ $dir);
Loading history...
118
    }
119
120
    public function getInstall($key)
121
    {
122
        $pluginData = $this->fetchPluginData();
123
124
        try {
125
            if(isset($pluginData[$key])) {
126
                $plugin = $pluginData[$key];
127
128
                // Create temp file of zip plugin
129
                $temp = tmpfile();
130
                fwrite($temp, file_get_contents($plugin['url_download']));
0 ignored issues
show
Bug introduced by
It seems like $temp can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

130
                fwrite(/** @scrutinizer ignore-type */ $temp, file_get_contents($plugin['url_download']));
Loading history...
131
                $filename = stream_get_meta_data($temp)['uri'];
0 ignored issues
show
Bug introduced by
It seems like $temp can also be of type false; however, parameter $stream of stream_get_meta_data() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

131
                $filename = stream_get_meta_data(/** @scrutinizer ignore-type */ $temp)['uri'];
Loading history...
132
133
                // Extract zip plugin
134
                $zip = new \ZipArchive;
135
                $res = $zip->open($filename);
136
                if ($res === TRUE) {
137
                    $zip->extractTo(app_path('CBPlugins'));
138
                    $dirName = $zip->getNameIndex(0);
139
                    $zip->close();
140
                    fclose($temp);
0 ignored issues
show
Bug introduced by
It seems like $temp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

140
                    fclose(/** @scrutinizer ignore-type */ $temp);
Loading history...
141
142
                    // Rename
143
                    if(file_exists(app_path("CBPlugins/".$key))) rrmdir(app_path("CBPlugins/".$key));
144
                    rename(app_path("CBPlugins/".$dirName), app_path("CBPlugins/".$key));
145
146
                    // Read Plugin JSON
147
                    $pluginJson = json_decode(file_get_contents(app_path("CBPlugins/".$key."/plugin.json")), true);
148
149
                    // Check if has asset
150
                    if($pluginJson && $pluginJson['asset']) {
151
                        // Check destination folder is ready
152
                        if(file_exists(public_path("cb_asset/".$key))) {
153
                            rrmdir(public_path("cb_asset/".$key));
154
                        }
155
156
                        // Create directory empty
157
                        mkdir(public_path("cb_asset/".$key));
158
159
                        // Copy asset
160
                        $this->recursiveCopy(app_path("CBPlugins/".$key."/".$pluginJson['asset']), public_path("cb_asset/".$key));
161
                    }
162
163
                    return response()->json(['status'=>true,'message'=>'Install / update plugin has been succesfull!']);
164
165
                } else {
166
                    return response()->json(['status'=>false,'message'=>"Failed to install/update, can't open the plugin archive"]);
167
                }
168
            }else{
169
                return response()->json(['status'=>false,'message'=>'Failed to install/update, plugin key is not found']);
170
            }
171
        } catch (\Exception $e) {
172
            return response()->json(['status'=>false,'message'=>'Something went wrong!']);
173
        }
174
    }
175
176
    private function fetchPluginData($cache = true)
177
    {
178
        if($cache === true && $data = Cache::get("plugin_store_data")) {
179
            return $data;
180
        }
181
182
        $result = [];
183
184
        try {
185
            $opts = [
186
                "http" => [
187
                    "method" => "GET",
188
                    "header" => "Access-Token: bVc/ZnpYNSZrMVZYOHE5U2tqcSU=\r\n".
189
                                "User-Agent: CRUDBooster-Bot-Client"
190
                ]
191
            ];
192
            $context = stream_context_create($opts);
193
            $data = file_get_contents(base64_decode("aHR0cDovL2NydWRib29zdGVyLmNvbS9hcGkvcGx1Z2luP2FjY2Vzc190b2tlbj1iVmMvWm5wWU5TWnJNVlpZT0hFNVUydHFjU1U9"), false, $context);
194
195
            if($data) {
196
                $data = json_decode($data, true);
197
                if($data['status']==true) {
198
199
                    foreach($data['data'] as $item) {
200
                        $key = $item['key'];
201
                        $result[ $key ] = $item;
202
                    }
203
204
                    $result = collect($result)->sortBy("name")->all();
205
206
                    Cache::put("plugin_store_data", $result, now()->addDays(3));
207
                }
208
            }
209
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
210
211
        }
212
213
        return $result;
214
    }
215
}