Passed
Push — master ( 14a327...e5b44f )
by Paul
20:18 queued 10:35
created

NoticeController::renderPremiumNotice()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 12
ccs 0
cts 9
cp 0
rs 8.8333
cc 7
nc 5
nop 0
crap 56
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Controllers;
4
5
use GeminiLabs\SiteReviews\Addons\Updater;
6
use GeminiLabs\SiteReviews\Database;
7
use GeminiLabs\SiteReviews\Database\OptionManager;
8
use GeminiLabs\SiteReviews\Helper;
9
use GeminiLabs\SiteReviews\Helpers\Arr;
10
use GeminiLabs\SiteReviews\Helpers\Str;
11
use GeminiLabs\SiteReviews\Modules\Html\Builder;
12
use GeminiLabs\SiteReviews\Modules\Migrate;
13
use GeminiLabs\SiteReviews\Modules\Queue;
14
use GeminiLabs\SiteReviews\Modules\Sanitizer;
15
use GeminiLabs\SiteReviews\Request;
16
17
class NoticeController extends Controller
18
{
19
    const USER_META_KEY = '_glsr_notices';
20
21
    /**
22
     * @var array
23
     */
24
    protected $dismissValuesMap;
25
26
    public function __construct()
27
    {
28
        $this->dismissValuesMap = [
29
            'premium' => glsr()->version('minor'),
30
            'welcome' => glsr()->version('minor'),
31
        ];
32
    }
33
34
    /**
35
     * @return void
36
     * @filter admin_notices
37
     */
38
    public function adminNotices()
39
    {
40
        // order is intentional!
41
        $this->renderWelcomeNotice();
42
        $this->renderPremiumNotice();
43
        $this->renderMigrationNotice();
44
    }
45
46
    /**
47
     * @return void
48
     * @action site-reviews/route/admin/dismiss-notice
49
     */
50
    public function dismissNotice(Request $request)
51
    {
52
        $notice = glsr(Sanitizer::class)->sanitizeText($request->notice);
53
        if ($notice) {
54
            $this->setUserMeta($notice, $this->getVersionFor($notice));
55
        }
56
    }
57
58
    /**
59
     * @return void
60
     * @action site-reviews/route/ajax/dismiss-notice
61
     */
62
    public function dismissNoticeAjax(Request $request)
63
    {
64
        $this->dismissNotice($request);
65
        wp_send_json_success();
66
    }
67
68
    protected function licensing()
69
    {
70
        $isFree = true; // priority 1
71
        $isValid = true; // priority 2
72
        $isSaved = true; // priority 3
73
        foreach (glsr()->updated as $addonId => $addon) {
74
            if (!$addon['licensed']) {
75
                continue; // this is a free add-on
76
            }
77
            $isFree = false; // there are premium add-ons installed
78
            if (empty(glsr_get_option('licenses.'.$addonId))) {
79
                $isSaved = false;
80
                continue; // the license has not been saved in the settings
81
            }
82
            $licenseStatus = get_option(glsr()->prefix.$addonId);
83
            if (empty($licenseStatus)) { // the license status has not been stored
84
                $license = glsr_get_option('licenses.'.$addonId);
85
                $updater = new Updater($addon['updateUrl'], $addon['file'], $addonId, compact('license'));
86
                $licenseStatus = $updater->isLicenseValid() ? 'valid' : 'invalid';
87
            }
88
            if ('valid' !== $licenseStatus) {
89
                $isValid = false;
90
                break;
91
            }
92
        }
93
        return compact('isFree', 'isSaved', 'isValid');
94
    }
95
96
    /**
97
     * @param string $key
98
     * @param mixed $fallback
99
     * @return mixed
100
     */
101
    protected function getUserMeta($key, $fallback)
102
    {
103
        $meta = get_user_meta(get_current_user_id(), static::USER_META_KEY, true);
104
        return Arr::get($meta, $key, $fallback);
105
    }
106
107
    /**
108
     * @param string $noticeKey
109
     * @return string
110
     */
111
    protected function getVersionFor($noticeKey)
112
    {
113
        return Arr::get($this->dismissValuesMap, $noticeKey, glsr()->version('major'));
114
    }
115
116
    /**
117
     * @return void
118
     */
119
    protected function renderPremiumNotice()
120
    {
121
        if (!Str::startsWith(glsr()->post_type, glsr_current_screen()->post_type)) {
122
            return;
123
        }
124
        $licensing = $this->licensing();
125
        if ($licensing['isFree']) {
126
            if (Helper::isGreaterThan($this->getVersionFor('premium'), $this->getUserMeta('premium', 0))) {
127
                glsr()->render('partials/notices/premium', $licensing);
128
            }
129
        } elseif ((glsr()->can('edit_others_posts') && !$licensing['isSaved']) || !$licensing['isValid']) {
130
            glsr()->render('partials/notices/premium', $licensing); // always show this notice!
131
        }
132
    }
133
134
    /**
135
     * @return void
136
     */
137
    protected function renderMigrationNotice()
138
    {
139
        if ($this->isReviewAdminScreen() && glsr()->hasPermission('tools', 'general')) {
140
            $args = [];
141
            if (glsr(Database::class)->isMigrationNeeded()) {
142
                $args['database'] = true;
143
            }
144
            if (glsr(Migrate::class)->isMigrationNeeded()) {
145
                $args['migrations'] = glsr(Migrate::class)->pendingVersions();
146
            }
147
            if (empty($args)) {
148
                return;
149
            }
150
            if (!glsr(Queue::class)->isPending('queue/migration')) {
151
                // The $args are informational only
152
                glsr(Queue::class)->once(time() + MINUTE_IN_SECONDS, 'queue/migration', $args);
153
            }
154
            glsr()->render('partials/notices/migrate', [
155
                'action' => glsr(Builder::class)->a([
156
                    'data-expand' => '#support-common-problems-and-solutions',
157
                    'href' => glsr_admin_url('documentation', 'support'),
158
                    'text' => _x('Common Problems and Solutions', 'admin-text', 'site-reviews'),
159
                ]),
160
            ]);
161
        }
162
    }
163
164
    /**
165
     * @return void
166
     */
167
    protected function renderWelcomeNotice()
168
    {
169
        if ($this->isReviewAdminScreen()
170
            && Helper::isGreaterThan($this->getVersionFor('welcome'), $this->getUserMeta('welcome', 0))
171
            && glsr()->can('edit_others_posts')) {
172
            $welcomeText = '0.0.0' == glsr(OptionManager::class)->get('version_upgraded_from')
173
                ? _x('Thanks for installing Site Reviews v%s, we hope you love it!', 'admin-text', 'site-reviews')
174
                : _x('Thanks for updating to Site Reviews v%s, we hope you love the changes!', 'admin-text', 'site-reviews');
175
            glsr()->render('partials/notices/welcome', [
176
                'text' => sprintf($welcomeText, glsr()->version),
177
            ]);
178
        }
179
    }
180
181
    /**
182
     * @param string $key
183
     * @param mixed $value
184
     * @return mixed
185
     */
186
    protected function setUserMeta($key, $value)
187
    {
188
        $userId = get_current_user_id();
189
        $meta = (array) get_user_meta($userId, static::USER_META_KEY, true);
190
        $meta = array_filter(wp_parse_args($meta, []));
191
        $meta[$key] = $value;
192
        update_user_meta($userId, static::USER_META_KEY, $meta);
193
    }
194
}
195