Passed
Push — main ( db602c...8b7c2e )
by Paul
06:19
created

AdminController::searchAuthorsAjax()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 9
ccs 0
cts 8
cp 0
rs 10
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\Commands\ToggleVerified;
13
use GeminiLabs\SiteReviews\Database;
14
use GeminiLabs\SiteReviews\Defaults\ColumnFilterbyDefaults;
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 Controller
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() && $this->execute(new ApproveReview($review))) {
37
            glsr(Notice::class)->store(); // because of the redirect
38
        }
39
        wp_redirect(glsr_admin_url());
40
        exit;
41
    }
42
43
    /**
44
     * @param array $data
45
     * @action in_plugin_update_message-{plugin_basename}
46
     */
47
    public function displayUpdateWarning($data): void
48
    {
49
        $version = Arr::get($data, 'new_version');
50
        $parts = explode('.', $version);
51
        $newVersion = Arr::getAs('int', $parts, 0, 0);
52
        if ($newVersion > (int) glsr()->version('major')) {
53
            glsr()->render('views/partials/update-warning');
54
        }
55
    }
56
57
    /**
58
     * @return void
59
     * @action admin_enqueue_scripts
60
     */
61
    public function enqueueAssets()
62
    {
63
        $this->execute(new EnqueueAdminAssets());
64
    }
65
66
    /**
67
     * @return array
68
     * @filter plugin_action_links_site-reviews/site-reviews.php
69
     */
70
    public function filterActionLinks(array $links)
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
     * @param array $items
89
     * @return array
90
     * @filter dashboard_glance_items
91
     */
92
    public function filterDashboardGlanceItems($items)
93
    {
94
        $postCount = wp_count_posts(glsr()->post_type);
95
        if (empty($postCount->publish)) {
96
            return $items;
97
        }
98
        $text = _nx('%s Review', '%s Reviews', $postCount->publish, 'admin-text', 'site-reviews');
99
        $text = sprintf($text, number_format_i18n($postCount->publish));
100
        $items = Arr::consolidate($items);
101
        if (glsr()->can('edit_posts')) {
102
            $items[] = glsr(Builder::class)->a($text, [
103
                'class' => 'glsr-review-count',
104
                'href' => glsr_admin_url(),
105
            ]);
106
        } else {
107
            $items[] = glsr(Builder::class)->span($text, [
108
                'class' => 'glsr-review-count',
109
            ]);
110
        }
111
        return $items;
112
    }
113
114
    /**
115
     * @param array $args
116
     * @return array
117
     * @filter export_args
118
     */
119
    public function filterExportArgs($args)
120
    {
121
        if (in_array(Arr::get($args, 'content'), ['all', glsr()->post_type])) {
122
            $this->execute(new ExportRatings(glsr()->args($args)));
123
        }
124
        return $args;
125
    }
126
127
    /**
128
     * @param bool $showButton
129
     * @return bool
130
     * @filter screen_options_show_submit
131
     */
132
    public function filterScreenOptionsButton($showButton)
133
    {
134
        global $post_type_object, $title, $typenow;
135
        if (!Str::startsWith($typenow, glsr()->post_type)) {
136
            return $showButton;
137
        }
138
        $submit = get_submit_button(_x('Apply', 'admin-text', 'site-reviews'), 'primary', 'screen-options-apply', false);
139
        $close = glsr(Builder::class)->button([
140
            'aria-controls' => 'screen-options-wrap',
141
            'class' => 'button button-secondary glsr-screen-meta-toggle',
142
            'text' => _x('Close Panel', 'admin-text', 'site-reviews'),
143
            'type' => 'button',
144
        ]);
145
        echo glsr(Builder::class)->p([
146
            'style' => 'display:inline-flex;gap:6px;',
147
            'text' => $submit.$close,
148
        ]);
149
        return false; // don't display the default submit button
150
    }
151
152
    /**
153
     * @param array $plugins
154
     * @return array
155
     * @filter mce_external_plugins
156
     */
157
    public function filterTinymcePlugins($plugins)
158
    {
159
        if (glsr()->can('edit_posts')) {
160
            $plugins = Arr::consolidate($plugins);
161
            $plugins['glsr_shortcode'] = glsr()->url('assets/scripts/mce-plugin.js');
162
        }
163
        return $plugins;
164
    }
165
166
    /**
167
     * @return void
168
     * @action admin_init
169
     */
170 8
    public function onActivation()
171
    {
172 8
        if (empty(get_option(glsr()->prefix.'activated'))) {
173 8
            glsr(Install::class)->run();
174 8
            glsr(Migrate::class)->run();
175 8
            update_option(glsr()->prefix.'activated', true);
176
        }
177
    }
178
179
    /**
180
     * @return void
181
     * @action import_end
182
     */
183
    public function onImportEnd()
184
    {
185
        $this->execute(new ImportRatings());
186
    }
187
188
    /**
189
     * @return void
190
     * @action admin_head
191
     */
192
    public function printInlineStyle()
193
    {
194
        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:#F6E05E!important;}</style>';
195
    }
196
197
    /**
198
     * @return void
199
     * @action admin_init
200
     */
201 8
    public function registerTinymcePopups()
202
    {
203 8
        $this->execute(new RegisterTinymcePopups([
204 8
            'site_reviews' => _x('Latest Reviews', 'admin-text', 'site-reviews'),
205 8
            'site_review' => _x('Single Review', 'admin-text', 'site-reviews'),
206 8
            'site_reviews_form' => _x('Review Form', 'admin-text', 'site-reviews'),
207 8
            'site_reviews_summary' => _x('Rating Summary', 'admin-text', 'site-reviews'),
208 8
        ]));
209
    }
210
211
    /**
212
     * @return void
213
     * @action in_admin_header
214
     */
215
    public function renderPageHeader()
216
    {
217
        global $post_type_object, $title, $typenow;
218
        if (!Str::startsWith($typenow, glsr()->post_type)) {
219
            return;
220
        }
221
        $screen = glsr_current_screen();
222
        glsr()->render('views/partials/page-header', [
223
            'hasNewButton' => in_array($screen->base, ['edit', 'post']),
224
            'hasPremiumButton' => !glsr(License::class)->isLicensed(),
225
            'hasScreenOptions' => in_array($screen->base, ['edit', 'edit-tags']),
226
            'logo' => file_get_contents(glsr()->path('assets/images/mascot.svg')),
227
            'newText' => Arr::get($post_type_object, 'labels.add_new'),
228
            'newUrl' => admin_url('post-new.php?post_type='.$typenow),
229
            'title' => esc_html($title),
230
        ]);
231
    }
232
233
    /**
234
     * @param string $editorId
235
     * @return void
236
     * @action media_buttons
237
     */
238
    public function renderTinymceButton($editorId)
239
    {
240
        $allowedEditors = glsr()->filterArray('tinymce/editor-ids', ['content'], $editorId);
241
        if ('post' !== glsr_current_screen()->base || !in_array($editorId, $allowedEditors)) {
242
            return;
243
        }
244
        $shortcodes = [];
245
        foreach (glsr()->retrieveAs('array', 'mce', []) as $shortcode => $values) {
246
            $shortcodes[$shortcode] = $values;
247
        }
248
        if (!empty($shortcodes)) {
249
            $shortcodes = wp_list_sort($shortcodes, 'label', 'ASC', true); // preserve keys
250
            glsr()->render('partials/editor/tinymce', [
251
                'shortcodes' => $shortcodes,
252
            ]);
253
        }
254
    }
255
256
    /**
257
     * @return void
258
     * @action admin_init
259
     */
260 8
    public function scheduleMigration()
261
    {
262 8
        if ($this->isReviewAdminScreen()
263 8
            && !defined('GLSR_UNIT_TESTS')
264 8
            && !glsr(Queue::class)->isPending('queue/migration')) {
265
            if (glsr(Migrate::class)->isMigrationNeeded() || glsr(Database::class)->isMigrationNeeded()) {
266
                glsr(Queue::class)->once(time() + MINUTE_IN_SECONDS, 'queue/migration');
267
            }
268
        }
269
    }
270
271
    /**
272
     * @return void
273
     * @action site-reviews/route/ajax/filter-assigned_post
274
     */
275
    public function searchAssignedPostsAjax(Request $request)
276
    {
277
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
278
        $results = glsr(Database::class)->searchAssignedPosts($search)->results();
279
        wp_send_json_success([
280
            'items' => $results,
281
        ]);
282
    }
283
284
    /**
285
     * @return void
286
     * @action site-reviews/route/ajax/filter-assigned_user
287
     */
288
    public function searchAssignedUsersAjax(Request $request)
289
    {
290
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
291
        $results = glsr(Database::class)->searchAssignedUsers($search)->results();
292
        array_walk($results, function ($user) {
293
            $user->name = glsr(Sanitizer::class)->sanitizeUserName($user->name);
294
        });
295
        wp_send_json_success([
296
            'items' => $results,
297
        ]);
298
    }
299
300
    /**
301
     * @return void
302
     * @action site-reviews/route/ajax/filter-author
303
     */
304
    public function searchAuthorsAjax(Request $request)
305
    {
306
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
307
        $results = glsr(Database::class)->searchUsers($search)->results();
308
        array_walk($results, function ($user) {
309
            $user->name = glsr(Sanitizer::class)->sanitizeUserName($user->name);
310
        });
311
        wp_send_json_success([
312
            'items' => $results,
313
        ]);
314
    }
315
316
    /**
317
     * @return void
318
     * @action site-reviews/route/ajax/search-posts
319
     */
320
    public function searchPostsAjax(Request $request)
321
    {
322
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
323
        $results = glsr(Database::class)->searchPosts($search)->render();
324
        wp_send_json_success([
325
            'empty' => '<div>'._x('Nothing found.', 'admin-text', 'site-reviews').'</div>',
326
            'items' => $results,
327
        ]);
328
    }
329
330
    /**
331
     * @return void
332
     * @action site-reviews/route/ajax/search-strings
333
     */
334
    public function searchStringsAjax(Request $request)
335
    {
336
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
337
        $exclude = Arr::consolidate($request->exclude);
338
        $results = glsr(Translation::class)
339
            ->search($search)
340
            ->exclude()
341
            ->exclude($exclude)
342
            ->renderResults();
343
        wp_send_json_success([
344
            'empty' => '<div>'._x('Nothing found.', 'admin-text', 'site-reviews').'</div>',
345
            'items' => $results,
346
        ]);
347
    }
348
349
    /**
350
     * @return void
351
     * @action site-reviews/route/ajax/search-users
352
     */
353
    public function searchUsersAjax(Request $request)
354
    {
355
        $search = glsr(Sanitizer::class)->sanitizeText($request->search);
356
        $results = glsr(Database::class)->searchUsers($search)->render();
357
        wp_send_json_success([
358
            'empty' => '<div>'._x('Nothing found.', 'admin-text', 'site-reviews').'</div>',
359
            'items' => $results,
360
        ]);
361
    }
362
363
    /**
364
     * @return void
365
     * @action site-reviews/route/ajax/toggle-filters
366
     */
367
    public function toggleFiltersAjax(Request $request)
368
    {
369
        if ($userId = get_current_user_id()) {
370
            $filters = array_keys(glsr(ColumnFilterbyDefaults::class)->defaults());
371
            $enabled = glsr(Sanitizer::class)->sanitizeArrayString($request->enabled);
372
            $enabled = array_intersect($filters, $enabled);
373
            update_user_meta($userId, 'edit_'.glsr()->post_type.'_filters', $enabled);
374
        }
375
        wp_send_json_success();
376
    }
377
378
    /**
379
     * @return void
380
     * @action site-reviews/route/ajax/toggle-pinned
381
     */
382
    public function togglePinnedAjax(Request $request)
383
    {
384
        $command = new TogglePinned($request->toArray());
385
        $result = $this->execute($command);
386
        glsr()->action('cache/flush', $command->review);
387
        wp_send_json_success([
388
            'notices' => glsr(Notice::class)->get(),
389
            'pinned' => $result,
390
        ]);
391
    }
392
393
    /**
394
     * @return void
395
     * @action site-reviews/route/ajax/toggle-status
396
     */
397
    public function toggleStatusAjax(Request $request)
398
    {
399
        $result = $this->execute(new ToggleStatus($request->toArray()));
400
        wp_send_json_success($result);
401
    }
402
403
    /**
404
     * @return void
405
     * @action site-reviews/route/ajax/toggle-verified
406
     */
407
    public function toggleVerifiedAjax(Request $request)
408
    {
409
        $command = new ToggleVerified($request->toArray());
410
        $result = $this->execute($command);
411
        glsr()->action('cache/flush', $command->review);
412
        wp_send_json_success([
413
            'notices' => glsr(Notice::class)->get(),
414
            'verified' => $result,
415
        ]);
416
    }
417
}
418