Test Failed
Push — develop ( db5b9c...b55dd4 )
by Paul
17:52
created

AdminController::toggleStatusAjax()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
rs 10
ccs 0
cts 2
cp 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Controllers;
4
5
use GeminiLabs\SiteReviews\Commands\ApproveReview;
6
use GeminiLabs\SiteReviews\Commands\EnqueueAdminAssets;
7
use GeminiLabs\SiteReviews\Commands\ExportRatings;
8
use GeminiLabs\SiteReviews\Commands\ImportRatings;
9
use GeminiLabs\SiteReviews\Commands\RegisterTinymcePopups;
10
use GeminiLabs\SiteReviews\Commands\TogglePinned;
11
use GeminiLabs\SiteReviews\Commands\ToggleStatus;
12
use GeminiLabs\SiteReviews\Database;
13
use GeminiLabs\SiteReviews\Defaults\ColumnFilterbyDefaults;
14
use GeminiLabs\SiteReviews\Helper;
15
use GeminiLabs\SiteReviews\Helpers\Arr;
16
use GeminiLabs\SiteReviews\Helpers\Str;
17
use GeminiLabs\SiteReviews\Install;
18
use GeminiLabs\SiteReviews\License;
19
use GeminiLabs\SiteReviews\Modules\Html\Builder;
20
use GeminiLabs\SiteReviews\Modules\Migrate;
21
use GeminiLabs\SiteReviews\Modules\Notice;
22
use GeminiLabs\SiteReviews\Modules\Queue;
23
use GeminiLabs\SiteReviews\Modules\Sanitizer;
24
use GeminiLabs\SiteReviews\Modules\Translation;
25
use GeminiLabs\SiteReviews\Request;
26
27
class AdminController extends AbstractController
28
{
29
    /**
30
     * @action site-reviews/route/get/admin/approve
31
     */
32
    public function approveReview(Request $request): void
33
    {
34
        $postId = Arr::get($request->data, 0);
35
        $review = glsr_get_review($postId);
36
        if ($review->isValid()) {
37
            $command = $this->execute(new ApproveReview($review));
38
            if ($command->successful()) {
39
                glsr(Notice::class)->store(); // because of the redirect
40
            }
41
        }
42
        wp_redirect(glsr_admin_url());
43
        exit;
44
    }
45
46
    /**
47
     * @action in_plugin_update_message-{glsr()->basename}
48
     */
49
    public function displayUpdateWarning(array $data): void
50
    {
51
        $version = Arr::get($data, 'new_version');
52
        $parts = explode('.', $version);
53
        $newVersion = Arr::getAs('int', $parts, 0, 0);
54
        if ($newVersion > (int) glsr()->version('major')) {
55
            glsr()->render('views/partials/update-warning');
56
        }
57
    }
58
59
    /**
60
     * @action admin_enqueue_scripts
61
     */
62
    public function enqueueAssets(): void
63
    {
64
        $this->execute(new EnqueueAdminAssets());
65
    }
66
67
    /**
68
     * @filter plugin_action_links_site-reviews/site-reviews.php
69
     */
70
    public function filterActionLinks(array $links): array
71
    {
72
        if (glsr()->hasPermission('settings')) {
73
            $links['settings'] = glsr(Builder::class)->a([
74
                'href' => glsr_admin_url('settings'),
75
                'text' => _x('Settings', 'admin-text', 'site-reviews'),
76
            ]);
77
        }
78
        if (glsr()->hasPermission('documentation')) {
79
            $links['documentation'] = glsr(Builder::class)->a([
80
                'href' => glsr_admin_url('documentation'),
81
                'text' => _x('Help', 'admin-text', 'site-reviews'),
82
            ]);
83
        }
84
        return $links;
85
    }
86
87
    /**
88
     * @filter export_args
89
     */
90
    public function filterExportArgs(array $args): array
91
    {
92
        if (in_array(Arr::get($args, 'content'), ['all', glsr()->post_type])) {
93
            $this->execute(new ExportRatings(glsr()->args($args)));
94
        }
95
        return $args;
96
    }
97
98
    /**
99
     * @filter screen_options_show_submit
100
     */
101
    public function filterScreenOptionsButton(bool $showButton): bool
102
    {
103
        global $post_type_object, $title, $typenow;
104
        if (!str_starts_with($typenow, glsr()->post_type)) {
105
            return $showButton;
106
        }
107
        $submit = get_submit_button(_x('Apply', 'admin-text', 'site-reviews'), 'primary', 'screen-options-apply', false);
108
        $close = glsr(Builder::class)->button([
109
            'aria-controls' => 'screen-options-wrap',
110
            'class' => 'button button-secondary glsr-screen-meta-toggle',
111
            'text' => _x('Close Panel', 'admin-text', 'site-reviews'),
112
            'type' => 'button',
113
        ]);
114
        echo glsr(Builder::class)->p([
115
            'style' => 'display:inline-flex;gap:6px;',
116
            'text' => $submit.$close,
117
        ]);
118
        return false; // don't display the default submit button
119
    }
120
121
    /**
122
     * @filter mce_external_plugins
123
     */
124
    public function filterTinymcePlugins(array $plugins): array
125
    {
126
        if (glsr()->can('edit_posts')) {
127
            $plugins['glsr_shortcode'] = glsr()->url('assets/scripts/mce-plugin.js');
128
        }
129
        return $plugins;
130
    }
131
132
    /**
133
     * @action admin_init
134 8
     */
135
    public function onActivation(): void
136 8
    {
137 8
        if (empty(get_option(glsr()->prefix.'activated'))) {
138 8
            glsr(Install::class)->run(); // this hard-resets role permissions
139 8
            glsr(Migrate::class)->run();
140
            update_option(glsr()->prefix.'activated', true);
141
            glsr()->action('activated');
142
        }
143
    }
144
145
    /**
146
     * @action deactivate_{glsr()->basename}
147
     */
148
    public function onDeactivation(bool $isNetworkDeactivation): void
149
    {
150
        glsr(Install::class)->deactivate($isNetworkDeactivation);
151
    }
152
153
    /**
154
     * @action import_end
155
     */
156
    public function onImportEnd(): void
157
    {
158
        $this->execute(new ImportRatings());
159
    }
160
161
    /**
162
     * @action admin_head
163
     */
164
    public function printInlineStyle(): void
165
    {
166
        echo '<style type="text/css">a[href="edit.php?post_type=site-review&page='.Str::dashCase(glsr()->prefix).'addons"]:not(.current),a[href="edit.php?post_type=site-review&page='.Str::dashCase(glsr()->prefix).'addons"]:focus,a[href="edit.php?post_type=site-review&page='.Str::dashCase(glsr()->prefix).'addons"]:hover{color:#e8ff5e!important;}</style>';
167
    }
168
169
    /**
170 8
     * @action admin_init
171
     */
172 8
    public function registerTinymcePopups(): void
173
    {
174
        $this->execute(new RegisterTinymcePopups());
175
    }
176
177
    /**
178
     * @action in_admin_header
179
     */
180
    public function renderPageHeader(): void
181
    {
182
        global $post_type_object, $title;
183
        if (!$this->isReviewAdminScreen()) {
184
            return;
185
        }
186
        $buttons = [];
187
        $screen = glsr_current_screen();
188
        if (glsr()->post_type === $screen->post_type && !glsr(License::class)->isPremium()) {
189
            $buttons['premium'] = [
190
                'class' => 'components-button is-primary glsr-try-premium',
191
                'href' => 'https://niftyplugins.com/plugins/site-reviews-premium/',
192
                'target' => '_blank',
193
                'text' => _x('Try Premium', 'admin-text', 'site-reviews'),
194
            ];
195
        }
196
        if (glsr()->can('create_posts') && in_array($screen->base, ['edit', 'post'])) {
197
            $buttons['new'] = [
198
                'class' => 'components-button is-secondary glsr-new-post',
199
                'data-new' => '',
200
                'href' => admin_url("post-new.php?post_type={$screen->post_type}"),
201
                'text' => Arr::get($post_type_object, 'labels.add_new'),
202
            ];
203
        }
204
        $buttons = glsr()->filterArray('page-header/buttons', $buttons);
205
        glsr()->render('views/partials/page-header', [
206
            'buttons' => $buttons,
207
            'hasScreenOptions' => in_array($screen->base, ['edit', 'edit-tags', 'post']),
208
            'logo' => Helper::svg('assets/images/icon.svg', false),
209
            'title' => esc_html($title),
210
        ]);
211
    }
212
213
    /**
214
     * @action media_buttons
215
     */
216
    public function renderTinymceButton(string $editorId): void
217
    {
218
        $allowedEditors = glsr()->filterArray('tinymce/editor-ids', ['content'], $editorId);
219
        if ('post' !== glsr_current_screen()->base || !in_array($editorId, $allowedEditors)) {
220
            return;
221
        }
222
        $shortcodes = [];
223
        foreach (glsr()->retrieveAs('array', 'mce', []) as $shortcode => $values) {
224
            $shortcodes[$shortcode] = $values;
225
        }
226
        if (!empty($shortcodes)) {
227
            $shortcodes = wp_list_sort($shortcodes, 'label', 'ASC', true); // preserve keys
228
            glsr()->render('partials/editor/tinymce', [
229
                'shortcodes' => $shortcodes,
230
            ]);
231
        }
232
    }
233
234
    /**
235 8
     * @action admin_init
236
     */
237 8
    public function scheduleMigration(): void
238 8
    {
239
        if (defined('GLSR_UNIT_TESTS')) {
240
            return;
241
        }
242
        if (!$this->isReviewAdminScreen()) {
243
            return;
244
        }
245
        if (glsr(Queue::class)->isPending('queue/migration')) {
246
            return;
247
        }
248
        if (!glsr(Migrate::class)->isMigrationNeeded() && !glsr(Database::class)->isMigrationNeeded()) {
249
            return;
250
        }
251
        glsr(Queue::class)->once(time() + MINUTE_IN_SECONDS, 'queue/migration');
252
    }
253
254
    /**
255
     * @action site-reviews/route/ajax/filter-assigned_post
256
     */
257
    public function searchAssignedPostsAjax(Request $request): void
258
    {
259
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
260
        $results = glsr(Database::class)->searchAssignedPosts($search)->results();
261
        wp_send_json_success([
262
            'items' => $results,
263
        ]);
264
    }
265
266
    /**
267
     * @action site-reviews/route/ajax/filter-assigned_user
268
     */
269
    public function searchAssignedUsersAjax(Request $request): void
270
    {
271
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
272
        $results = glsr(Database::class)->searchAssignedUsers($search)->results();
273
        array_walk($results, function ($user) {
274
            $user->name = glsr(Sanitizer::class)->sanitizeUserName($user->name, $user->nickname);
275
        });
276
        wp_send_json_success([
277
            'items' => $results,
278
        ]);
279
    }
280
281
    /**
282
     * @action site-reviews/route/ajax/filter-author
283
     */
284
    public function searchAuthorsAjax(Request $request): void
285
    {
286
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
287
        $results = glsr(Database::class)->searchUsers($search)->results();
288
        array_walk($results, function ($user) {
289
            $user->name = glsr(Sanitizer::class)->sanitizeUserName($user->name, $user->nickname);
290
        });
291
        wp_send_json_success([
292
            'items' => $results,
293
        ]);
294
    }
295
296
    /**
297
     * @action site-reviews/route/ajax/search-posts
298
     */
299
    public function searchPostsAjax(Request $request): void
300
    {
301
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
302
        $results = glsr(Database::class)->searchPosts($search)->render();
303
        wp_send_json_success([
304
            'empty' => '<div>'._x('Nothing found.', 'admin-text', 'site-reviews').'</div>',
305
            'items' => $results,
306
        ]);
307
    }
308
309
    /**
310
     * @action site-reviews/route/ajax/search-strings
311
     */
312
    public function searchStringsAjax(Request $request): void
313
    {
314
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
315
        $exclude = Arr::consolidate($request->exclude);
316
        $results = glsr(Translation::class)
317
            ->search($search)
318
            ->exclude()
319
            ->exclude($exclude)
320
            ->renderResults();
321
        wp_send_json_success([
322
            'empty' => '<div>'._x('Nothing found.', 'admin-text', 'site-reviews').'</div>',
323
            'items' => $results,
324
        ]);
325
    }
326
327
    /**
328
     * @action site-reviews/route/ajax/search-users
329
     */
330
    public function searchUsersAjax(Request $request): void
331
    {
332
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
333
        $results = glsr(Database::class)->searchUsers($search)->render();
334
        wp_send_json_success([
335
            'empty' => '<div>'._x('Nothing found.', 'admin-text', 'site-reviews').'</div>',
336
            'items' => $results,
337
        ]);
338
    }
339
340
    /**
341
     * @action site-reviews/route/ajax/toggle-filters
342
     */
343
    public function toggleFiltersAjax(Request $request): void
344
    {
345
        if ($userId = get_current_user_id()) {
346
            $filters = array_keys(glsr(ColumnFilterbyDefaults::class)->defaults());
347
            $enabled = glsr(Sanitizer::class)->sanitizeArrayString($request->enabled);
348
            $enabled = array_intersect($filters, $enabled);
349
            update_user_meta($userId, 'edit_'.glsr()->post_type.'_filters', $enabled);
350
        }
351
        wp_send_json_success();
352
    }
353
354
    /**
355
     * @action site-reviews/route/ajax/toggle-pinned
356
     */
357
    public function togglePinnedAjax(Request $request): void
358
    {
359
        $command = $this->execute(new TogglePinned($request));
360
        glsr()->action('cache/flush', $command->review); // @phpstan-ignore-line
361
        wp_send_json_success($command->response());
362
    }
363
364
    /**
365
     * @action site-reviews/route/ajax/toggle-status
366
     */
367
    public function toggleStatusAjax(Request $request): void
368
    {
369
        $command = $this->execute(new ToggleStatus($request));
370
        wp_send_json_success($command->response());
371
    }
372
}
373