Passed
Push — master ( 25ce53...efc233 )
by Ferry
02:55
created

postRequestBuyPlugin()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 17
c 0
b 0
f 0
nc 3
nop 0
dl 0
loc 22
rs 9.7

1 Method

Rating   Name   Duplication   Size   Complexity  
A DeveloperPluginStoreController::recursiveCopy() 0 14 5
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\ComposerHelper;
13
use crocodicstudio\crudbooster\helpers\CurlHelper;
14
use crocodicstudio\crudbooster\helpers\ModuleGenerator;
15
use Illuminate\Support\Facades\Artisan;
16
use Illuminate\Support\Facades\Cache;
17
use Illuminate\Support\Facades\DB;
18
use Illuminate\Support\Facades\Hash;
19
use Illuminate\Support\Facades\Log;
20
21
class DeveloperPluginStoreController extends Controller
22
{
23
24
    private $view = "crudbooster::dev_layouts.modules.plugin";
25
26
    public function __construct()
27
    {
28
        view()->share(['page_title'=>'Plugin Store']);
29
    }
30
31
32
    public function getIndex() {
33
34
        if(request("refresh")) {
35
            $this->fetchPluginData(false );
36
            return cb()->redirectBack("Plugin list has been refreshed!","success");
37
        }
38
39
        $data = [];
40
        $data['result'] = $this->fetchPluginData();
41
        return view($this->view.'.index',$data);
42
    }
43
44
    public function getUninstall($key)
45
    {
46
        $pluginData = $this->fetchPluginData();
47
48
        if(isset($pluginData[$key])) {
49
            if(file_exists(app_path("CBPlugins/".$key))) {
50
51
                if(isset($pluginData['source']) && $pluginData['source'] == 'composer') {
52
                    if(isset($pluginData['package'])) {
53
                        ComposerHelper::composerRemove($pluginData['package']);
54
                    }
55
                }
56
57
                rrmdir(app_path("CBPlugins/".$key));
58
59
                return response()->json(['status'=>true, 'message'=>'Plugin has been uninstalled!']);
60
            }else{
61
                return response()->json(['status'=>false,'message'=>'Failed to uninstall, plugin is not found']);
62
            }
63
        }else {
64
            return response()->json(['status'=>false,'message'=>'Failed to uninstall, plugin key is not found']);
65
        }
66
    }
67
68
    private function recursiveCopy($src,$dst) {
69
        $dir = opendir($src);
70
        @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

70
        /** @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...
71
        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

71
        while(false !== ( $file = readdir(/** @scrutinizer ignore-type */ $dir)) ) {
Loading history...
72
            if (( $file != '.' ) && ( $file != '..' )) {
73
                if ( is_dir($src . '/' . $file) ) {
74
                    $this->recursiveCopy($src . '/' . $file,$dst . '/' . $file);
75
                }
76
                else {
77
                    copy($src . '/' . $file,$dst . '/' . $file);
78
                }
79
            }
80
        }
81
        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

81
        closedir(/** @scrutinizer ignore-type */ $dir);
Loading history...
82
    }
83
84
    public function getInstall($key)
85
    {
86
        ini_set("memory_limit","192M");
87
        set_time_limit(500);
88
89
        $pluginData = $this->fetchPluginData();
90
91
        try {
92
            if(isset($pluginData[$key])) {
93
                $plugin = $pluginData[$key];
94
95
                if(isset($plugin['source']) && $plugin['source'] == "composer") {
96
97
                    if(isset($plugin['package']) && isset($plugin['service_provider'])) {
98
                        // Make a composer
99
                        $output = ComposerHelper::composerRequire($plugin['package'], $plugin['service_provider']);
100
101
                        Artisan::call("migrate");
102
103
                        return response()->json(['status'=>true,'message'=>$output]);
104
                    } else {
105
                        return response()->json(['status'=>true,'message'=>'Installation is failed, there is no package and or service provider']);
106
                    }
107
108
                } else {
109
                    // Create temp file of zip plugin
110
                    $temp = tmpfile();
111
                    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

111
                    fwrite(/** @scrutinizer ignore-type */ $temp, file_get_contents($plugin['url_download']));
Loading history...
112
                    $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

112
                    $filename = stream_get_meta_data(/** @scrutinizer ignore-type */ $temp)['uri'];
Loading history...
113
114
                    // Extract zip plugin
115
                    $zip = new \ZipArchive;
116
                    $res = $zip->open($filename);
117
                    if ($res === TRUE) {
118
                        $zip->extractTo(app_path('CBPlugins'));
119
                        $dirName = $zip->getNameIndex(0);
120
                        $zip->close();
121
                        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

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