LibraryController::assets()   A
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
eloc 15
c 1
b 1
f 0
nc 8
nop 2
dl 0
loc 27
rs 9.2222
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 DB;
7
use Djoudi\LaravelH5p\Eloquents\H5pContent;
8
use Djoudi\LaravelH5p\Eloquents\H5pLibrary;
9
use H5PCore;
10
use Illuminate\Http\Request;
11
use Illuminate\Support\Facades\App;
12
use Log;
13
14
class LibraryController extends Controller
15
{
16
    public function index(Request $request)
17
    {
18
        $h5p = App::make('LaravelH5p');
19
        $core = $h5p::$core;
0 ignored issues
show
Unused Code introduced by
The assignment to $core is dead and can be removed.
Loading history...
20
        $interface = $h5p::$interface;
21
        $not_cached = $interface->getNumNotFiltered();
22
23
        $entrys = H5pLibrary::paginate(10);
24
        $settings = $h5p::get_core([
25
            'libraryList' => [
26
                'notCached' => $not_cached,
27
            ],
28
            'containerSelector' => '#h5p-admin-container',
29
            'extraTableClasses' => '',
30
            'l10n'              => [
31
                'NA'             => trans('laravel-h5p.common.na'),
32
                'viewLibrary'    => trans('laravel-h5p.library.viewLibrary'),
33
                'deleteLibrary'  => trans('laravel-h5p.library.deleteLibrary'),
34
                'upgradeLibrary' => trans('laravel-h5p.library.upgradeLibrary'),
35
            ],
36
        ]);
37
38
        foreach ($entrys as $library) {
39
            $usage = $interface->getLibraryUsage($library->id, $not_cached ? true : false);
40
            $settings['libraryList']['listData'][] = (object) [
41
                'id'                     => $library->id,
42
                'title'                  => $library->title.' ('.H5PCore::libraryVersion($library).')',
43
                'restricted'             => ($library->restricted ? true : false),
44
                'numContent'             => $interface->getNumContent($library->id),
45
                'numContentDependencies' => intval($usage['content']),
46
                'numLibraryDependencies' => intval($usage['libraries']),
47
            ];
48
        }
49
50
        $last_update = config('laravel-h5p.h5p_content_type_cache_updated_at');
51
52
        $required_files = $this->assets(['js/h5p-library-list.js']);
53
54
        if ($not_cached) {
55
            $settings['libraryList']['notCached'] = $this->get_not_cached_settings($not_cached);
56
        } else {
57
            $settings['libraryList']['notCached'] = 0;
58
        }
59
60
        return view('h5p.library.index', compact('entrys', 'settings', 'last_update', 'hubOn', 'required_files'));
61
    }
62
63
    public function show(Request $request, $id)
64
    {
65
        $library = $this->get_library($id);
66
67
        // Add settings and translations
68
        $h5p = App::make('LaravelH5p');
69
        $core = $h5p::$core;
0 ignored issues
show
Unused Code introduced by
The assignment to $core is dead and can be removed.
Loading history...
70
        $interface = $h5p::$interface;
71
72
        $settings = [
73
            'containerSelector' => '#h5p-admin-container',
74
        ];
75
76
        // Build the translations needed
77
        $settings['libraryInfo']['translations'] = [
78
            'noContent'             => trans('laravel-h5p.library.noContent'),
79
            'contentHeader'         => trans('laravel-h5p.library.contentHeader'),
80
            'pageSizeSelectorLabel' => trans('laravel-h5p.library.pageSizeSelectorLabel'),
81
            'filterPlaceholder'     => trans('laravel-h5p.library.filterPlaceholder'),
82
            'pageXOfY'              => trans('laravel-h5p.library.pageXOfY'),
83
        ];
84
        $notCached = $interface->getNumNotFiltered();
85
        if ($notCached) {
86
            $settings['libraryInfo']['notCached'] = $this->get_not_cached_settings($notCached);
87
        } else {
88
            // List content which uses this library
89
            $contents = DB::select('SELECT DISTINCT hc.id, hc.title FROM h5p_contents_libraries hcl JOIN h5p_contents hc ON hcl.content_id = hc.id WHERE hcl.library_id = ? ORDER BY hc.title', [$library->id]);
90
91
            foreach ($contents as $content) {
92
                $settings['libraryInfo']['content'][] = [
93
                    'title' => $content->title,
94
                    'url'   => route('h5p.show', ['id' => $content->id]),
95
                ];
96
            }
97
        }
98
        // Build library info
99
        $settings['libraryInfo']['info'] = [
100
            'version'         => H5PCore::libraryVersion($library),
101
            'fullscreen'      => $library->fullscreen ? trans('laravel-h5p.common.yes') : trans('laravel-h5p.common.no'),
102
            'content_library' => $library->runnable ? trans('laravel-h5p.common.yes') : trans('laravel-h5p.common.no'),
103
            'used'            => (isset($contents) ? count($contents) : trans('laravel-h5p.common.na')),
104
        ];
105
106
        $required_files = $this->assets(['js/h5p-library-details.js']);
107
108
        return view('h5p.library.show', compact('settings', 'required_files', 'library'));
109
    }
110
111
    public function store(Request $request)
112
    {
113
        $this->validate($request, [
114
            'h5p_file' => 'required||max:50000',
115
        ]);
116
117
        if ($request->hasFile('h5p_file') && $request->file('h5p_file')->isValid()) {
118
            Log::info('Yes Good ');
119
            $h5p = App::make('LaravelH5p');
120
            $validator = $h5p::$validator;
121
            $interface = $h5p::$interface;
122
123
            // Content update is skipped because it is new registration
124
            $content = null;
125
            $skipContent = true;
126
            $h5p_upgrade_only = ($request->get('h5p_upgrade_only')) ? true : false;
127
128
            rename($request->file('h5p_file')->getPathName(), $interface->getUploadedH5pPath());
129
130
            if ($validator->isValidPackage($skipContent, $h5p_upgrade_only)) {
131
                $storage = $h5p::$storage;
132
                $storage->savePackage($content, null, $skipContent);
133
                Log::info('All is OK ');
134
            }
135
136
//            if ($request->get('sync_hub')) {
137
            //                $h5p::$core->updateContentTypeCache();
138
            //            }
139
            // The uploaded file was not a valid H5P package
140
            @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

140
            /** @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...
141
142
            return redirect()
143
                ->route('h5p.library.index')
144
                ->with('success', trans('laravel-h5p.library.updated'));
145
        }
146
147
        Log::info('Not Good Good ');
148
149
        return redirect()
150
            ->route('h5p.library.index')
151
            ->with('error', trans('laravel-h5p.library.can_not_updated'));
152
    }
153
154
    public function destroy(Request $request)
155
    {
156
        $library = H5pLibrary::findOrFail($request->get('id'));
157
158
        $h5p = App::make('LaravelH5p');
159
        $interface = $h5p::$interface;
160
161
        // Error if in use
162
        $usage = $interface->getLibraryUsage($library);
163
        if ($usage['content'] !== 0 || $usage['libraries'] !== 0) {
164
            return redirect()->route('h5p.library.index')
165
                ->with('error', trans('laravel-h5p.library.used_library_can_not_destoroied'));
166
        }
167
168
        $interface->deleteLibrary($library);
169
170
        return redirect()
171
            ->route('h5p.library.index')
172
            ->with('success', trans('laravel-h5p.library.destroyed'));
173
    }
174
175
    public function clear(Request $request)
176
    {
177
        $h5p = App::make('LaravelH5p');
178
        $core = $h5p::$core;
179
180
        // Do as many as we can in five seconds.
181
        $start = microtime(true);
182
        $contents = H5pContent::where('filtered', '')->get();
183
184
        $done = 0;
185
186
        foreach ($contents as $content) {
187
            $content = $core->loadContent($content->id);
188
            $core->filterParameters($content);
189
            $done++;
190
            if ((microtime(true) - $start) > 5) {
191
                break;
192
            }
193
        }
194
195
        $count = intval(count($contents) - $done);
0 ignored issues
show
Unused Code introduced by
The assignment to $count is dead and can be removed.
Loading history...
196
197
        return redirect()->route('h5p.library.index')
198
            ->with('success', trans('laravel-h5p.library.cleared'));
199
    }
200
201
    public function restrict(Request $request)
202
    {
203
        $entry = H5pLibrary::where('id', $request->get('id'))->first();
204
205
        if ($entry) {
206
            if ($entry->restricted == '1') {
207
                $entry->restricted = '0';
208
            } else {
209
                $entry->restricted = '1';
210
            }
211
            $entry->update();
212
        }
213
214
        return response()->json($entry);
215
    }
216
217
    private function assets($scripts = [], $styles = [])
218
    {
219
        $prefix = 'assets/vendor/h5p/h5p-core/';
220
        $return = [
221
            'scripts' => [],
222
            'styles'  => [],
223
        ];
224
225
        foreach (H5PCore::$adminScripts as $script) {
226
            $return['scripts'][] = $prefix.$script;
227
        }
228
229
        $return['styles'][] = $prefix.'styles/h5p.css';
230
        $return['styles'][] = $prefix.'styles/h5p-admin.css';
231
232
        if ($scripts) {
233
            foreach ($scripts as $script) {
234
                $return['scripts'][] = $prefix.$script;
235
            }
236
        }
237
        if ($styles) {
238
            foreach ($styles as $style) {
239
                $return['styles'][] = $prefix.$style;
240
            }
241
        }
242
243
        return $return;
244
    }
245
246
    //@TODO The following is a feature from the existing WordPress plug-in, but not all features need to be developed.
247
    // Then connect to the new method as needed and implement it
248
    //https://github.com/h5p/h5p-wordpress-plugin/blob/90a7bb4fa3d927eda401470bc599c9f1d7508ffe/admin/class-h5p-library-admin.php
249
    //----------------------------------------------------------------------------------
250
251
    /**
252
     * Load library.
253
     *
254
     * @since 1.1.0
255
     *
256
     * @param int $id optional
257
     */
258
    private function get_library($id = null)
259
    {
260
//        if ($this->library !== NULL) {
261
        //            return $this->library; // Return the current loaded library.
262
        //        }
263
        if ($id === null) {
264
            $id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
265
        }
266
267
        // Try to find content with $id.
268
        return H5pLibrary::findOrFail($id);
269
    }
270
271
    /**
272
     * Display admin interface for managing content libraries.
273
     *
274
     * @since 1.1.0
275
     */
276
    public function display_libraries_page()
277
    {
278
        switch (filter_input(INPUT_GET, 'task', FILTER_SANITIZE_STRING)) {
279
        case null:
280
            $this->display_libraries();
281
282
            return;
283
        case 'show':
284
            $this->display_library_details();
285
286
            return;
287
        case 'delete':
288
            $library = $this->get_library();
289
            H5P_Plugin_Admin::print_messages();
0 ignored issues
show
Bug introduced by
The type Djoudi\LaravelH5p\Http\C...ollers\H5P_Plugin_Admin 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...
290
            if ($library) {
0 ignored issues
show
introduced by
$library is of type Djoudi\LaravelH5p\Eloquents\H5pLibrary, thus it always evaluated to true.
Loading history...
291
                include_once 'views/library-delete.php';
292
            }
293
294
            return;
295
        case 'upgrade':
296
            $library = $this->get_library();
297
            if ($library) {
0 ignored issues
show
introduced by
$library is of type Djoudi\LaravelH5p\Eloquents\H5pLibrary, thus it always evaluated to true.
Loading history...
298
                $settings = $this->display_content_upgrades($library);
299
            }
300
            include_once 'views/library-content-upgrade.php';
301
            if (isset($settings)) {
302
                $h5p = H5P_Plugin::get_instance();
0 ignored issues
show
Bug introduced by
The type Djoudi\LaravelH5p\Http\Controllers\H5P_Plugin 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...
303
                $h5p->print_settings($settings, 'H5PAdminIntegration');
304
            }
305
306
            return;
307
        }
308
        echo '<div class="wrap"><h2>'.esc_html__('Unknown task.').'</h2></div>';
0 ignored issues
show
Bug introduced by
The function esc_html__ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

308
        echo '<div class="wrap"><h2>'./** @scrutinizer ignore-call */ esc_html__('Unknown task.').'</h2></div>';
Loading history...
309
    }
310
311
    /**
312
     * JavaScript settings needed to rebuild content caches.
313
     *
314
     * @since 1.1.0
315
     */
316
    private function get_not_cached_settings($num)
317
    {
318
        return [
319
            'num'      => $num,
320
            'url'      => route('h5p.ajax.rebuild-cache'),
321
            'message'  => __('Not all content has gotten their cache rebuilt. This is required to be able to delete libraries, and to display how many contents that uses the library.'),
322
            'progress' => __('1 content need to get its cache rebuilt. :num contents needs to get their cache rebuilt.', ['num' => $num]),
323
            //            'button' => __('Rebuild cache')
324
        ];
325
    }
326
327
    /*
328
     * Display a list of all h5p content libraries.
329
     *
330
     * @since 1.1.0
331
     */
332
//    private function display_libraries() {
333
    //        $h5p = H5P_Plugin::get_instance();
334
    //        $core = $h5p->get_h5p_instance('core');
335
    //        $interface = $h5p->get_h5p_instance('interface');
336
    //        $not_cached = $interface->getNumNotFiltered();
337
    //        $libraries = $interface->loadLibraries();
338
    //        $settings = array(
339
    //            'containerSelector' => '#h5p-admin-container',
340
    //            'extraTableClasses' => 'wp-list-table widefat fixed',
341
    //            'l10n' => array(
342
    //                'NA' => __('N/A'),
343
    //                'viewLibrary' => __('View library details'),
344
    //                'deleteLibrary' => __('Delete library'),
345
    //                'upgradeLibrary' => __('Upgrade library content')
346
    //            )
347
    //        );
348
    //        // Add settings for each library
349
    //        $i = 0;
350
    //        foreach ($libraries as $versions) {
351
    //            foreach ($versions as $library) {
352
    //                $usage = $interface->getLibraryUsage($library->id, $not_cached ? TRUE : FALSE);
353
    //                if ($library->runnable) {
354
    //                    $upgrades = $core->getUpgrades($library, $versions);
355
    //                    $upgradeUrl = empty($upgrades) ? FALSE : admin_url('admin.php?page=h5p_libraries&task=upgrade&id=' . $library->id . '&destination=' . admin_url('admin.php?page=h5p_libraries'));
356
    //                    $restricted = ($library->restricted ? TRUE : FALSE);
357
    //                    $restricted_url = admin_url('admin-ajax.php?action=h5p_restrict_library' .
358
    //                            '&id=' . $library->id .
359
    //                            '&token=' . wp_create_nonce('h5p_library_' . $i) .
360
    //                            '&token_id=' . $i .
361
    //                            '&restrict=' . ($library->restricted === '1' ? 0 : 1));
362
    //                } else {
363
    //                    $upgradeUrl = NULL;
364
    //                    $restricted = NULL;
365
    //                    $restricted_url = NULL;
366
    //                }
367
    //                $contents_count = $interface->getNumContent($library->id);
368
    //                $settings['libraryList']['listData'][] = array(
369
    //                    'title' => $library->title . ' (' . H5PCore::libraryVersion($library) . ')',
370
    //                    'restricted' => $restricted,
371
    //                    'restrictedUrl' => $restricted_url,
372
    //                    'numContent' => $contents_count === 0 ? '' : $contents_count,
373
    //                    'numContentDependencies' => $usage['content'] < 1 ? '' : $usage['content'],
374
    //                    'numLibraryDependencies' => $usage['libraries'] === 0 ? '' : $usage['libraries'],
375
    //                    'upgradeUrl' => $upgradeUrl,
376
    //                    'detailsUrl' => admin_url('admin.php?page=h5p_libraries&task=show&id=' . $library->id),
377
    //                    'deleteUrl' => admin_url('admin.php?page=h5p_libraries&task=delete&id=' . $library->id)
378
    //                );
379
    //                $i++;
380
    //            }
381
    //        }
382
    //        // Translations
383
    //        $settings['libraryList']['listHeaders'] = array(
384
    //            __('Title'),
385
    //            __('Restricted'),
386
    //            array(
387
    //                'text' => __('Contents'),
388
    //                'class' => 'h5p-admin-center'
389
    //            ),
390
    //            array(
391
    //                'text' => __('Contents using it'),
392
    //                'class' => 'h5p-admin-center'
393
    //            ),
394
    //            array(
395
    //                'text' => __('Libraries using it'),
396
    //                'class' => 'h5p-admin-center'
397
    //            ),
398
    //            __('Actions')
399
    //        );
400
    //
401
    //        // Make it possible to rebuild all caches.
402
    //        if ($not_cached) {
403
    //            $settings['libraryList']['notCached'] = $this->get_not_cached_settings($not_cached);
404
    //        }
405
    //        // Assets
406
    //        $this->add_admin_assets();
407
    //        H5P_Plugin_Admin::add_script('library-list', 'js/h5p-library-list.js');
408
    //        // Load content type cache time
409
    //        $last_update = get_option('h5p_content_type_cache_updated_at', '');
410
    //        $hubOn = config('laravel-h5p.h5p_hub_is_enabled');
411
    //        include_once('views/libraries.php');
412
    //        $h5p->print_settings($settings, 'H5PAdminIntegration');
413
    //    }
414
415
    /*
416
     * Display details for a given content library.
417
     *
418
     * @since 1.1.0
419
     */
420
//    private function display_library_details() {
421
    //        $library = $this->get_library();
422
    //        H5P_Plugin_Admin::print_messages();
423
    //        if (!$library) {
424
    //            return;
425
    //        }
426
    //        // Add settings and translations
427
    //        $h5p = H5P_Plugin::get_instance();
428
    //        $interface = $h5p->get_h5p_instance('interface');
429
    //        $settings = array(
430
    //            'containerSelector' => '#h5p-admin-container',
431
    //        );
432
    //        // Build the translations needed
433
    //        $settings['libraryInfo']['translations'] = array(
434
    //            'noContent' => __('No content is using this library'),
435
    //            'contentHeader' => __('Content using this library'),
436
    //            'pageSizeSelectorLabel' => __('Elements per page'),
437
    //            'filterPlaceholder' => __('Filter content'),
438
    //            'pageXOfY' => __('Page $x of $y'),
439
    //        );
440
    //        $notCached = $interface->getNumNotFiltered();
441
    //        if ($notCached) {
442
    //            $settings['libraryInfo']['notCached'] = $this->get_not_cached_settings($notCached);
443
    //        } else {
444
    //            // List content which uses this library
445
    //            $contents = $wpdb->get_results($wpdb->prepare(
446
    //                            "SELECT DISTINCT hc.id, hc.title
447
    //            FROM h5p_contents_libraries hcl
448
    //            JOIN h5p_contents hc ON hcl.content_id = hc.id
449
    //            WHERE hcl.library_id = %d
450
    //            ORDER BY hc.title", $library->id
451
    //                    )
452
    //            );
453
    //            foreach ($contents as $content) {
454
    //                $settings['libraryInfo']['content'][] = array(
455
    //                    'title' => $content->title,
456
    //                    'url' => admin_url('admin.php?page=h5p&task=show&id=' . $content->id),
457
    //                );
458
    //            }
459
    //        }
460
    //        // Build library info
461
    //        $settings['libraryInfo']['info'] = array(
462
    //            __('Version') => H5PCore::libraryVersion($library),
463
    //            __('Fullscreen') => $library->fullscreen ? __('Yes') : __('No'),
464
    //            __('Content library') => $library->runnable ? __('Yes') : __('No'),
465
    //            __('Used by') => (isset($contents) ? sprintf(_n('1 content', '%d contents', count($contents)), count($contents)) : __('N/A')),
466
    //        );
467
    //        $this->add_admin_assets();
468
    //        H5P_Plugin_Admin::add_script('library-list', 'js/h5p-library-details.js');
469
    //        include_once('views/library-details.php');
470
    //        $h5p->print_settings($settings, 'H5PAdminIntegration');
471
    //    }
472
473
    /*
474
     * Display a list of all h5p content libraries.
475
     *
476
     * @since 1.1.0
477
     */
478
//    private function display_content_upgrades($library) {
479
    //        global $wpdb;
480
    //        $h5p = H5P_Plugin::get_instance();
481
    //        $core = $h5p->get_h5p_instance('core');
482
    //        $interface = $h5p->get_h5p_instance('interface');
483
    //        $versions = $wpdb->get_results($wpdb->prepare(
484
    //                        "SELECT hl2.id, hl2.name, hl2.title, hl2.major_version, hl2.minor_version, hl2.patch_version
485
    //          FROM h5p_libraries hl1
486
    //          JOIN h5p_libraries hl2
487
    //            ON hl2.name = hl1.name
488
    //          WHERE hl1.id = %d
489
    //          ORDER BY hl2.title ASC, hl2.major_version ASC, hl2.minor_version ASC", $library->id
490
    //        ));
491
    //        foreach ($versions as $version) {
492
    //            if ($version->id === $library->id) {
493
    //                $upgrades = $core->getUpgrades($version, $versions);
494
    //                break;
495
    //            }
496
    //        }
497
    //        if (count($versions) < 2) {
498
    //            H5P_Plugin_Admin::set_error(__('There are no available upgrades for this library.'));
499
    //            return NULL;
500
    //        }
501
    //        // Get num of contents that can be upgraded
502
    //        $contents = $interface->getNumContent($library->id);
503
    //        if (!$contents) {
504
    //            H5P_Plugin_Admin::set_error(__("There's no content instances to upgrade."));
505
    //            return NULL;
506
    //        }
507
    //        $contents_plural = sprintf(_n('1 content', '%d contents', $contents), $contents);
508
    //        // Add JavaScript settings
509
    //        $return = filter_input(INPUT_GET, 'destination');
510
    //        $settings = array(
511
    //            'containerSelector' => '#h5p-admin-container',
512
    //            'libraryInfo' => array(
513
    //                'message' => sprintf(__('You are about to upgrade %s. Please select upgrade version.'), $contents_plural),
514
    //                'inProgress' => __('Upgrading to %ver...'),
515
    //                'error' => __('An error occurred while processing parameters:'),
516
    //                'errorData' => __('Could not load data for library %lib.'),
517
    //                'errorContent' => __('Could not upgrade content %id:'),
518
    //                'errorScript' => __('Could not load upgrades script for %lib.'),
519
    //                'errorParamsBroken' => __('Parameters are broken.'),
520
    //                'done' => sprintf(__('You have successfully upgraded %s.'), $contents_plural) . ($return ? '<br/><a href="' . $return . '">' . __('Return') . '</a>' : ''),
521
    //                'library' => array(
522
    //                    'name' => $library->name,
523
    //                    'version' => $library->major_version . '.' . $library->minor_version,
524
    //                ),
525
    //                'libraryBaseUrl' => admin_url('admin-ajax.php?action=h5p_content_upgrade_library&library='),
526
    //                'scriptBaseUrl' => plugins_url('h5p/js'),
527
    //                'buster' => '?ver=' . H5P_Plugin::VERSION,
528
    //                'versions' => $upgrades,
529
    //                'contents' => $contents,
530
    //                'buttonLabel' => __('Upgrade'),
531
    //                'infoUrl' => admin_url('admin-ajax.php?action=h5p_content_upgrade_progress&id=' . $library->id),
532
    //                'total' => $contents,
533
    //                'token' => wp_create_nonce('h5p_content_upgrade')
534
    //            )
535
    //        );
536
    //        $this->add_admin_assets();
537
    //        H5P_Plugin_Admin::add_script('version', 'js/h5p-version.js');
538
    //        H5P_Plugin_Admin::add_script('content-upgrade', 'js/h5p-content-upgrade.js');
539
    //        return $settings;
540
    //    }
541
542
    /*
543
     * Helps rebuild all content caches.
544
     *
545
     * @since 1.1.0
546
     */
547
//    public function ajax_rebuild_cache() {
548
    //        global $wpdb;
549
    //        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
550
    //            exit; // POST is required
551
    //        }
552
    //        $h5p = H5P_Plugin::get_instance();
553
    //        $core = $h5p->get_h5p_instance('core');
554
    //        // Do as many as we can in five seconds.
555
    //        $start = microtime(TRUE);
556
    //        $contents = $wpdb->get_results(
557
    //                "SELECT id
558
    //          FROM h5p_contents
559
    //          WHERE filtered = ''"
560
    //        );
561
    //        $done = 0;
562
    //        foreach ($contents as $content) {
563
    //            $content = $core->loadContent($content->id);
564
    //            $core->filterParameters($content);
565
    //            $done++;
566
    //            if ((microtime(TRUE) - $start) > 5) {
567
    //                break;
568
    //            }
569
    //        }
570
    //        print (count($contents) - $done);
571
    //        exit;
572
    //    }
573
574
    /*
575
     * Add generic admin interface assets.
576
     *
577
     * @since 1.1.0
578
     */
579
//    private function add_admin_assets() {
580
    //        foreach (H5PCore::$adminScripts as $script) {
581
    //            H5P_Plugin_Admin::add_script('admin-' . $script, '' . $script);
582
    //        }
583
    //        H5P_Plugin_Admin::add_style('h5p', 'styles/h5p.css');
584
    //        H5P_Plugin_Admin::add_style('admin', 'styles/h5p-admin.css');
585
    //    }
586
    //
587
    //    /**
588
    //     * JavaScript settings needed to rebuild content caches.
589
    //     *
590
    //     * @since 1.1.0
591
    //     */
592
    //    private function get_not_cached_settings($num) {
593
    //        return array(
594
    //            'num' => $num,
595
    //            'url' => admin_url('admin-ajax.php?action=h5p_rebuild_cache'),
596
    //            'message' => __('Not all content has gotten their cache rebuilt. This is required to be able to delete libraries, and to display how many contents that uses the library.'),
597
    //            'progress' => sprintf(_n('1 content need to get its cache rebuilt.', '%d contents needs to get their cache rebuilt.', $num), $num),
598
    //            'button' => __('Rebuild cache')
599
    //        );
600
    //    }
601
602
    /*
603
     * AJAX processing for content upgrade script.
604
     */
605
//    public function ajax_upgrade_progress() {
606
    //        global $wpdb;
607
    //        header('Cache-Control: no-cache');
608
    //        if (!wp_verify_nonce(filter_input(INPUT_POST, 'token'), 'h5p_content_upgrade')) {
609
    //            print __('Error, invalid security token!');
610
    //            exit;
611
    //        }
612
    //        $library_id = filter_input(INPUT_GET, 'id');
613
    //        if (!$library_id) {
614
    //            print __('Error, missing library!');
615
    //            exit;
616
    //        }
617
    //        // Get the library we're upgrading to
618
    //        $to_library = $wpdb->get_row($wpdb->prepare(
619
    //                        "SELECT id, name, major_version, minor_version
620
    //          FROM h5p_libraries
621
    //          WHERE id = %d", filter_input(INPUT_POST, 'libraryId')
622
    //        ));
623
    //        if (!$to_library) {
624
    //            print __('Error, invalid library!');
625
    //            exit;
626
    //        }
627
    //        // Prepare response
628
    //        $out = new stdClass();
629
    //        $out->params = array();
630
    //        $out->token = wp_create_nonce('h5p_content_upgrade');
631
    //        // Get updated params
632
    //        $params = filter_input(INPUT_POST, 'params');
633
    //        if ($params !== NULL) {
634
    //            // Update params.
635
    //            $params = json_decode($params);
636
    //            foreach ($params as $id => $param) {
637
    //                $wpdb->update(
638
    //                        $wpdb->prefix . 'h5p_contents', array(
639
    //                    'updated_at' => current_time('mysql', 1),
640
    //                    'parameters' => $param,
641
    //                    'library_id' => $to_library->id,
642
    //                    'filtered' => ''
643
    //                        ), array(
644
    //                    'id' => $id
645
    //                        ), array(
646
    //                    '%s',
647
    //                    '%s',
648
    //                    '%d',
649
    //                    '%s'
650
    //                        ), array(
651
    //                    '%d'
652
    //                        )
653
    //                );
654
    //                // Log content upgrade successful
655
    //                new H5pEvent('content', 'upgrade', $id, $wpdb->get_var($wpdb->prepare("SELECT title FROM h5p_contents WHERE id = %d", $id)), $to_library->name, $to_library->major_version . '.' . $to_library->minor_version);
656
    //            }
657
    //        }
658
    //        // Prepare our interface
659
    //        $h5p = H5P_Plugin::get_instance();
660
    //        $interface = $h5p->get_h5p_instance('interface');
661
    //        // Get number of contents for this library
662
    //        $out->left = $interface->getNumContent($library_id);
663
    //        if ($out->left) {
664
    //            // Find the 10 first contents using library and add to params
665
    //            $contents = $wpdb->get_results($wpdb->prepare(
666
    //                            "SELECT id, parameters
667
    //            FROM h5p_contents
668
    //            WHERE library_id = %d
669
    //            LIMIT 40", $library_id
670
    //            ));
671
    //            foreach ($contents as $content) {
672
    //                $out->params[$content->id] = $content->parameters;
673
    //            }
674
    //        }
675
    //        header('Content-type: application/json');
676
    //        print json_encode($out);
677
    //        exit;
678
    //    }
679
    //
680
    //    /**
681
    //     * AJAX loading of libraries for content upgrade script.
682
    //     *
683
    //     * @since 1.1.0
684
    //     * @param string $name
685
    //     * @param int $major
686
    //     * @param int $minor
687
    //     */
688
    //    public function ajax_upgrade_library() {
689
    //        header('Cache-Control: no-cache');
690
    //        $library_string = filter_input(INPUT_GET, 'library');
691
    //        if (!$library_string) {
692
    //            print __('Error, missing library!');
693
    //            exit;
694
    //        }
695
    //        $library_parts = explode('/', $library_string);
696
    //        if (count($library_parts) !== 4) {
697
    //            print __('Error, invalid library!');
698
    //            exit;
699
    //        }
700
    //        $library = (object) array(
701
    //                    'name' => $library_parts[1],
702
    //                    'version' => (object) array(
703
    //                        'major' => $library_parts[2],
704
    //                        'minor' => $library_parts[3]
705
    //                    )
706
    //        );
707
    //        $h5p = H5P_Plugin::get_instance();
708
    //        $core = $h5p->get_h5p_instance('core');
709
    //        $library->semantics = $core->loadLibrarySemantics($library->name, $library->version->major, $library->version->minor);
710
    //        if ($library->semantics === NULL) {
711
    //            print __('Error, could not library semantics!');
712
    //            exit;
713
    //        }
714
    //        // TODO: Library development mode
715
    ////    if ($core->development_mode & H5PDevelopment::MODE_LIBRARY) {
716
    ////      $dev_lib = $core->h5pD->getLibrary($library->name, $library->version->major, $library->version->minor);
717
    ////    }
718
    //        if (isset($dev_lib)) {
719
    //            $upgrades_script_path = $upgrades_script_url = $dev_lib['path'] . '/upgrades.js';
720
    //        } else {
721
    //            $suffix = '/libraries/' . $library->name . '-' . $library->version->major . '.' . $library->version->minor . '/upgrades.js';
722
    //            $upgrades_script_path = $h5p->get_h5p_path() . $suffix;
723
    //            $upgrades_script_url = $h5p->get_h5p_url() . $suffix;
724
    //        }
725
    //        if (file_exists($upgrades_script_path)) {
726
    //            $library->upgradesScript = $upgrades_script_url;
727
    //        }
728
    //        header('Content-type: application/json');
729
    //        print json_encode($library);
730
    //        exit;
731
    //    }
732
}
733