H5pController::show()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 1
eloc 10
c 3
b 1
f 0
nc 1
nop 2
dl 0
loc 16
rs 9.9332
1
<?php
2
3
namespace Djoudi\LaravelH5p\Http\Controllers;
4
5
use App\Http\Controllers\Controller;
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\Controller was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Djoudi\LaravelH5p\Eloquents\H5pContent;
7
use Djoudi\LaravelH5p\Events\H5pEvent;
8
use H5pCore;
9
use Illuminate\Http\Request;
10
use Illuminate\Support\Facades\App;
11
use Illuminate\Support\Facades\Auth;
12
13
class H5pController extends Controller
14
{
15
    public function index(Request $request)
16
    {
17
        $where = H5pContent::orderBy('h5p_contents.id', 'desc');
18
19
        if ($request->query('sf') && $request->query('s')) {
20
            if ($request->query('sf') == 'title') {
21
                $where->where('h5p_contents.title', $request->query('s'));
22
            }
23
            if ($request->query('sf') == 'creator') {
24
                $where->leftJoin('users', 'users.id', 'h5p_contents.user_id')->where('users.name', 'like', '%'.$request->query('s').'%');
0 ignored issues
show
Bug introduced by
Are you sure $request->query('s') of type array|null|string can be used in concatenation? ( Ignorable by Annotation )

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

24
                $where->leftJoin('users', 'users.id', 'h5p_contents.user_id')->where('users.name', 'like', '%'./** @scrutinizer ignore-type */ $request->query('s').'%');
Loading history...
25
            }
26
        }
27
28
        $search_fields = [
29
            'title'   => trans('laravel-h5p.content.title'),
30
            'creator' => trans('laravel-h5p.content.creator'),
31
        ];
32
        $entrys = $where->paginate(10);
33
        $entrys->appends(['sf' => $request->query('sf'), 's' => $request->query('s')]);
34
35
        return view('h5p.content.index', compact('entrys', 'request', 'search_fields'));
36
    }
37
38
    public function create(Request $request)
39
    {
40
        $h5p = App::make('LaravelH5p');
41
        $core = $h5p::$core;
42
43
        // Prepare form
44
        $library = 0;
45
        $parameters = '{}';
46
47
        $display_options = $core->getDisplayOptionsForEdit(null);
48
49
        // view Get the file and settings to print from
50
        $settings = $h5p::get_editor();
51
52
        // create event dispatch
53
        event(new H5pEvent('content', 'new'));
54
55
        $user = Auth::user();
56
57
        return view('h5p.content.create', compact('settings', 'user', 'library', 'parameters', 'display_options'));
58
    }
59
60
    public function store(Request $request)
61
    {
62
        $h5p = App::make('LaravelH5p');
63
        $core = $h5p::$core;
64
        $editor = $h5p::$h5peditor;
65
66
        $this->validate($request, [
67
            'title'  => 'required|max:250',
68
            'action' => 'required',
69
        ], [], [
70
            'title'  => trans('laravel-h5p.content.title'),
71
            'action' => trans('laravel-h5p.content.action'),
72
        ]);
73
74
        $oldLibrary = null;
75
        $oldParams = null;
76
        $event_type = 'create';
77
        $content = [
78
            'disable'    => H5PCore::DISABLE_NONE,
79
            'user_id'    => Auth::id(),
80
            'title'      => $request->get('title'),
81
            'embed_type' => 'div',
82
            'filtered'   => '',
83
            'slug'       => config('laravel-h5p.slug'),
84
        ];
85
86
        $content['filtered'] = '';
87
88
        try {
89
            if ($request->get('action') === 'create') {
90
                $content['library'] = $core->libraryFromString($request->get('library'));
91
                if (!$content['library']) {
92
                    throw new H5PException('Invalid library.');
0 ignored issues
show
Bug introduced by
The type Djoudi\LaravelH5p\Http\Controllers\H5PException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
93
                }
94
95
                // Check if library exists.
96
                $content['library']['libraryId'] = $core->h5pF->getLibraryId($content['library']['machineName'], $content['library']['majorVersion'], $content['library']['minorVersion']);
97
                if (!$content['library']['libraryId']) {
98
                    throw new H5PException('No such library');
99
                }
100
                //old
101
                // $content['params'] = $request->get('parameters');
102
                // $params = json_decode($content['params']);
103
104
                //new
105
                $params = json_decode($request->get('parameters'));
106
                $content['params'] = json_encode($params->params);
107
                if ($params === null) {
108
                    throw new H5PException('Invalid parameters');
109
                }
110
111
                // Set disabled features
112
                $this->get_disabled_content_features($core, $content);
113
114
                // Save new content
115
                $content['id'] = $core->saveContent($content);
116
117
                // Move images and find all content dependencies
118
                $editor->processParameters($content['id'], $content['library'], $params, $oldLibrary, $oldParams);
119
120
                event(new H5pEvent('content', $event_type, $content['id'], $content['title'], $content['library']['machineName'], $content['library']['majorVersion'], $content['library']['minorVersion']));
0 ignored issues
show
Unused Code introduced by
The call to Djoudi\LaravelH5p\Events\H5pEvent::__construct() has too many arguments starting with $content['library']['minorVersion']. ( Ignorable by Annotation )

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

120
                event(/** @scrutinizer ignore-call */ new H5pEvent('content', $event_type, $content['id'], $content['title'], $content['library']['machineName'], $content['library']['majorVersion'], $content['library']['minorVersion']));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
121
122
                $return_id = $content['id'];
123
            } elseif ($request->get('action') === 'upload') {
124
                $content['uploaded'] = true;
125
126
                $this->get_disabled_content_features($core, $content);
127
128
                // Handle file upload
129
                $return_id = $this->handle_upload($content);
130
            }
131
132
            if ($return_id) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $return_id does not seem to be defined for all execution paths leading up to this point.
Loading history...
133
                return redirect()
134
                    ->route('h5p.edit', $return_id)
135
                    ->with('success', trans('laravel-h5p.content.created'));
136
            } else {
137
                return redirect()
138
                    ->route('h5p.create')
139
                    ->with('fail', trans('laravel-h5p.content.can_not_created'));
140
            }
141
        } catch (H5PException $ex) {
142
            return redirect()
143
                ->route('h5p.create')
144
                ->with('fail', trans('laravel-h5p.content.can_not_created'));
145
        }
146
    }
147
148
    public function edit(Request $request, $id)
149
    {
150
        $h5p = App::make('LaravelH5p');
151
        $core = $h5p::$core;
152
        $editor = $h5p::$h5peditor;
0 ignored issues
show
Unused Code introduced by
The assignment to $editor is dead and can be removed.
Loading history...
153
154
        $settings = $h5p::get_core();
155
        $content = $h5p->get_content($id);
156
        $embed = $h5p->get_embed($content, $settings);
157
        $embed_code = $embed['embed'];
0 ignored issues
show
Unused Code introduced by
The assignment to $embed_code is dead and can be removed.
Loading history...
158
        $settings = $embed['settings'];
0 ignored issues
show
Unused Code introduced by
The assignment to $settings is dead and can be removed.
Loading history...
159
160
        // Prepare form
161
        $library = $content['library'] ? H5PCore::libraryToString($content['library']) : 0;
162
        $parameters = $content['params'] ? $content['params'] : '{}';
163
        $display_options = $core->getDisplayOptionsForEdit($content['disable']);
164
165
        // view Get the file and settings to print from
166
        $settings = $h5p::get_editor($content);
167
168
        // create event dispatch
169
        event(new H5pEvent('content', 'edit', $content['id'], $content['title'], $content['library']['name'], $content['library']['majorVersion'].'.'.$content['library']['minorVersion']));
170
171
        $user = Auth::user();
172
173
        return view('h5p.content.edit', compact('settings', 'user', 'id', 'content', 'library', 'parameters', 'display_options'));
174
    }
175
176
    public function update(Request $request, $id)
177
    {
178
        $h5p = App::make('LaravelH5p');
179
        $core = $h5p::$core;
180
        $editor = $h5p::$h5peditor;
181
182
        $this->validate($request, [
183
            'title'  => 'required|max:250',
184
            'action' => 'required',
185
        ], [], [
186
            'title'  => trans('laravel-h5p.content.title'),
187
            'action' => trans('laravel-h5p.content.action'),
188
        ]);
189
190
        $event_type = 'update';
191
        $content = $h5p::get_content($id);
192
        $content['embed_type'] = 'div';
193
        $content['user_id'] = Auth::id();
194
        $content['disable'] = $request->get('disable') ? $request->get('disable') : false;
195
        $content['title'] = $request->get('title');
196
        $content['filtered'] = '';
197
198
        $oldLibrary = $content['library'];
199
        $oldParams = json_decode($content['params']);
200
201
        try {
202
            if ($request->get('action') === 'create') {
203
                $content['library'] = $core->libraryFromString($request->get('library'));
204
                if (!$content['library']) {
205
                    throw new H5PException('Invalid library.');
206
                }
207
208
                // Check if library exists.
209
                $content['library']['libraryId'] = $core->h5pF->getLibraryId($content['library']['machineName'], $content['library']['majorVersion'], $content['library']['minorVersion']);
210
                if (!$content['library']['libraryId']) {
211
                    throw new H5PException('No such library');
212
                }
213
214
                //                $content['parameters'] = $request->get('parameters');
215
                //old
216
                //$content['params'] = $request->get('parameters');
217
                //$params = json_decode($content['params']);
218
219
                //new
220
                $params = json_decode($request->get('parameters'));
221
                $content['params'] = json_encode($params->params);
222
                if ($params === null) {
223
                    throw new H5PException('Invalid parameters');
224
                }
225
226
                // Set disabled features
227
                $this->get_disabled_content_features($core, $content);
228
229
                // Save new content
230
                $core->saveContent($content);
231
232
                // Move images and find all content dependencies
233
                $editor->processParameters($content['id'], $content['library'], $params, $oldLibrary, $oldParams);
234
235
                event(new H5pEvent('content', $event_type, $content['id'], $content['title'], $content['library']['machineName'], $content['library']['majorVersion'], $content['library']['minorVersion']));
0 ignored issues
show
Unused Code introduced by
The call to Djoudi\LaravelH5p\Events\H5pEvent::__construct() has too many arguments starting with $content['library']['minorVersion']. ( Ignorable by Annotation )

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

235
                event(/** @scrutinizer ignore-call */ new H5pEvent('content', $event_type, $content['id'], $content['title'], $content['library']['machineName'], $content['library']['majorVersion'], $content['library']['minorVersion']));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
236
237
                $return_id = $content['id'];
238
            } elseif ($request->get('action') === 'upload') {
239
                $content['uploaded'] = true;
240
241
                $this->get_disabled_content_features($core, $content);
242
243
                // Handle file upload
244
                $return_id = $this->handle_upload($content);
245
            }
246
247
            if ($return_id) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $return_id does not seem to be defined for all execution paths leading up to this point.
Loading history...
248
                return redirect()
249
                    ->route('h5p.edit', $return_id)
250
                    ->with('success', trans('laravel-h5p.content.updated'));
251
            } else {
252
                return redirect()
253
                    ->back()
254
                    ->with('fail', trans('laravel-h5p.content.can_not_updated'));
255
            }
256
        } catch (H5PException $ex) {
257
            return redirect()
258
                ->back()
259
                ->with('fail', trans('laravel-h5p.content.can_not_updated'));
260
        }
261
    }
262
263
    public function show(Request $request, $id)
264
    {
265
        $h5p = App::make('LaravelH5p');
266
        $core = $h5p::$core;
0 ignored issues
show
Unused Code introduced by
The assignment to $core is dead and can be removed.
Loading history...
267
        $settings = $h5p::get_editor();
268
        $content = $h5p->get_content($id);
269
        $embed = $h5p->get_embed($content, $settings);
270
        $embed_code = $embed['embed'];
271
        $settings = $embed['settings'];
272
        $title = $content['title'];
273
274
        // create event dispatch
275
        event(new H5pEvent('content', null, $content['id'], $content['title'], $content['library']['name'], $content['library']['majorVersion'], $content['library']['minorVersion']));
0 ignored issues
show
Unused Code introduced by
The call to Djoudi\LaravelH5p\Events\H5pEvent::__construct() has too many arguments starting with $content['library']['minorVersion']. ( Ignorable by Annotation )

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

275
        event(/** @scrutinizer ignore-call */ new H5pEvent('content', null, $content['id'], $content['title'], $content['library']['name'], $content['library']['majorVersion'], $content['library']['minorVersion']));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
276
277
        //     return view('h5p.content.edit', compact("settings", 'user', 'id', 'content', 'library', 'parameters', 'display_options'));
278
        return view('h5p.content.show', compact('settings', 'user', 'embed_code', 'title'));
279
    }
280
281
    public function destroy(Request $request, $id)
282
    {
283
        try {
284
            $content = H5pContent::findOrFail($id);
285
            $content->delete();
286
        } catch (Exception $ex) {
0 ignored issues
show
Bug introduced by
The type Djoudi\LaravelH5p\Http\Controllers\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
287
            return trans('laravel-h5p.content.can_not_delete');
288
        }
289
    }
290
291
    private function get_disabled_content_features($core, &$content)
292
    {
293
        $set = [
294
            H5PCore::DISPLAY_OPTION_FRAME     => filter_input(INPUT_POST, 'frame', FILTER_VALIDATE_BOOLEAN),
295
            H5PCore::DISPLAY_OPTION_DOWNLOAD  => filter_input(INPUT_POST, 'download', FILTER_VALIDATE_BOOLEAN),
296
            H5PCore::DISPLAY_OPTION_EMBED     => filter_input(INPUT_POST, 'embed', FILTER_VALIDATE_BOOLEAN),
297
            H5PCore::DISPLAY_OPTION_COPYRIGHT => filter_input(INPUT_POST, 'copyright', FILTER_VALIDATE_BOOLEAN),
298
        ];
299
        $content['disable'] = $core->getStorableDisplayOptions($set, $content['disable']);
300
    }
301
302
    private function handle_upload($content = null, $only_upgrade = null, $disable_h5p_security = false)
303
    {
304
        $h5p = App::make('LaravelH5p');
305
        $core = $h5p::$core;
306
        $validator = $h5p::$validator;
307
        $interface = $h5p::$interface;
308
        $storage = $h5p::$storage;
309
310
        if ($disable_h5p_security) {
311
            // Make it possible to disable file extension check
312
            $core->disableFileCheck = (filter_input(INPUT_POST, 'h5p_disable_file_check', FILTER_VALIDATE_BOOLEAN) ? true : false);
313
        }
314
315
        // Move so core can validate the file extension.
316
        rename($_FILES['h5p_file']['tmp_name'], $interface->getUploadedH5pPath());
317
318
        $skipContent = ($content === null);
319
320
        if ($validator->isValidPackage($skipContent, $only_upgrade) && ($skipContent || $content['title'] !== null)) {
321
            if (function_exists('check_upload_size')) {
322
                // Check file sizes before continuing!
323
                $tmpDir = $interface->getUploadedH5pFolderPath();
324
                $error = self::check_upload_sizes($tmpDir);
325
                if ($error !== null) {
326
                    // Didn't meet space requirements, cleanup tmp dir.
327
                    $interface->setErrorMessage($error);
328
                    H5PCore::deleteFileTree($tmpDir);
329
330
                    return false;
331
                }
332
            }
333
            // No file size check errors
334
            if (isset($content['id'])) {
335
                $interface->deleteLibraryUsage($content['id']);
336
            }
337
338
            $storage->savePackage($content, null, $skipContent);
339
340
            // Clear cached value for dirsize.
341
            return $storage->contentId;
342
        }
343
        // The uploaded file was not a valid H5P package
344
        @unlink($interface->getUploadedH5pPath());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). 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

344
        /** @scrutinizer ignore-unhandled */ @unlink($interface->getUploadedH5pPath());

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...
345
346
        return false;
347
    }
348
}
349