Passed
Push — v3 ( 3d31db...9e8c74 )
by Andrew
29:00 queued 05:41
created

src/controllers/TablesController.php (4 issues)

1
<?php
2
/**
3
 * Retour plugin for Craft CMS 3.x
4
 *
5
 * Retour allows you to intelligently redirect legacy URLs, so that you don't
6
 * lose SEO value when rebuilding & restructuring a website
7
 *
8
 * @link      https://nystudio107.com/
9
 * @copyright Copyright (c) 2018 nystudio107
10
 */
11
12
namespace nystudio107\retour\controllers;
13
14
use nystudio107\retour\helpers\Permission as PermissionHelper;
15
16
use Craft;
17
use craft\db\Query;
18
use craft\helpers\UrlHelper;
19
use craft\web\Controller;
20
21
use yii\web\ForbiddenHttpException;
22
use yii\web\Response;
23
24
/**
25
 * @author    nystudio107
26
 * @package   Retour
27
 * @since     3.0.0
28
 */
29
class TablesController extends Controller
30
{
31
    // Constants
32
    // =========================================================================
33
34
    // Protected Properties
35
    // =========================================================================
36
37
    /**
38
     * @var    bool|array
39
     */
40
    protected $allowAnonymous = [
41
    ];
42
43
    // Public Methods
44
    // =========================================================================
45
46
    /**
47
     * Handle requests for the dashboard statistics table
48
     *
49
     * @param string $sort
50
     * @param int    $page
51
     * @param int    $per_page
52
     * @param string $filter
53
     * @param null   $siteId
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $siteId is correct as it would always require null to be passed?
Loading history...
54
     *
55
     * @return Response
56
     * @throws ForbiddenHttpException
57
     */
58
    public function actionDashboard(
59
        string $sort = 'hitCount|desc',
60
        int $page = 1,
61
        int $per_page = 20,
62
        $filter = '',
63
        $siteId = 0
64
    ): Response {
65
        PermissionHelper::controllerPermissionCheck('retour:dashboard');
66
        $data = [];
67
        $sortField = 'hitCount';
68
        $sortType = 'DESC';
69
        // Figure out the sorting type
70
        if ($sort !== '') {
71
            if (strpos($sort, '|') === false) {
72
                $sortField = $sort;
73
            } else {
74
                list($sortField, $sortType) = explode('|', $sort);
75
            }
76
        }
77
        // Query the db table
78
        $offset = ($page - 1) * $per_page;
79
        $query = (new Query())
80
            ->from(['{{%retour_stats}}'])
81
            ->offset($offset)
82
            ->limit($per_page)
83
            ->orderBy("{$sortField} {$sortType}");
84
        if ((int)$siteId !== 0) {
85
            $query->where(['siteId' => $siteId]);
86
        }
87
        if ($filter !== '') {
88
            $query->where(['like', 'redirectSrcUrl', $filter]);
89
            $query->orWhere(['like', 'referrerUrl', $filter]);
90
        }
91
        $stats = $query->all();
92
        if ($stats) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $stats of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
93
            // Add in the `addLink` field
94
            foreach ($stats as &$stat) {
95
                $stat['addLink'] = '';
96
                if (!$stat['handledByRetour']) {
97
                    $encodedUrl = urlencode('/'.ltrim($stat['redirectSrcUrl'], '/'));
98
                    $stat['addLink'] = UrlHelper::cpUrl('retour/add-redirect', [
99
                        'defaultUrl' => $encodedUrl
100
                    ]);
101
                }
102
            }
103
            // Format the data for the API
104
            $data['data'] = $stats;
105
            $query = (new Query())
106
                ->from(['{{%retour_stats}}']);
107
            if ((int)$siteId !== 0) {
108
                $query->where(['siteId' => $siteId]);
109
            }
110
            if ($filter !== '') {
111
                $query->where(['like', 'redirectSrcUrl', $filter]);
112
                $query->orWhere(['like', 'referrerUrl', $filter]);
113
            }
114
            $count = $query->count();
115
            $data['links']['pagination'] = [
116
                'total' => $count,
117
                'per_page' => $per_page,
118
                'current_page' => $page,
119
                'last_page' => ceil($count / $per_page),
120
                'next_page_url' => null,
121
                'prev_page_url' => null,
122
                'from' => $offset + 1,
123
                'to' => $offset + ($count > $per_page ? $per_page : $count),
124
            ];
125
        }
126
127
        return $this->asJson($data);
128
    }
129
130
    /**
131
     * Handle requests for the dashboard redirects table
132
     *
133
     * @param string $sort
134
     * @param int    $page
135
     * @param int    $per_page
136
     * @param string $filter
137
     * @param null   $siteId
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $siteId is correct as it would always require null to be passed?
Loading history...
138
     *
139
     * @return Response
140
     * @throws ForbiddenHttpException
141
     */
142
    public function actionRedirects(
143
        string $sort = 'hitCount|desc',
144
        int $page = 1,
145
        int $per_page = 20,
146
        $filter = '',
147
        $siteId = 0
148
    ): Response {
149
        PermissionHelper::controllerPermissionCheck('retour:redirects');
150
        $data = [];
151
        $sortField = 'hitCount';
152
        $sortType = 'DESC';
153
        // Figure out the sorting type
154
        if ($sort !== '') {
155
            if (strpos($sort, '|') === false) {
156
                $sortField = $sort;
157
            } else {
158
                list($sortField, $sortType) = explode('|', $sort);
159
            }
160
        }
161
        // Query the db table
162
        $offset = ($page - 1) * $per_page;
163
        $query = (new Query())
164
            ->from(['{{%retour_static_redirects}}'])
165
            ->offset($offset)
166
            ->limit($per_page)
167
            ->orderBy("{$sortField} {$sortType}");
168
        if ((int)$siteId !== 0) {
169
            $query->where(['siteId' => $siteId]);
170
        }
171
        if ($filter !== '') {
172
            $query->where(['like', 'redirectSrcUrl', $filter]);
173
            $query->orWhere(['like', 'redirectDestUrl', $filter]);
174
        }
175
        $redirects = $query->all();
176
        // Add in the `deleteLink` field and clean up the redirects
177
        foreach ($redirects as &$redirect) {
178
            // Make sure the destination URL is not a regex
179
            if ($redirect['redirectMatchType'] !== 'exactmatch') {
180
                if (preg_match("/\$\d+/", $redirect['redirectDestUrl'])) {
181
                    $redirect['redirectDestUrl'] = '';
182
                }
183
            }
184
            // Handle extracting the site name
185
            $redirect['siteName'] = Craft::t('retour', 'All Sites');
186
            if ($redirect['siteId']) {
187
                $sites = Craft::$app->getSites();
188
                $site = $sites->getSiteById($redirect['siteId']);
189
                if ($site) {
190
                    $redirect['siteName'] = $site->name;
191
                }
192
            }
193
194
            $redirect['deleteLink'] = UrlHelper::cpUrl('retour/delete-redirect/'.$redirect['id']);
195
            $redirect['editLink'] = UrlHelper::cpUrl('retour/edit-redirect/'.$redirect['id']);
196
        }
197
        // Format the data for the API
198
        if ($redirects) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $redirects of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
199
            $data['data'] = $redirects;
200
            $query = (new Query())
201
                ->from(['{{%retour_static_redirects}}']);
202
            if ((int)$siteId !== 0) {
203
                $query->where(['siteId' => $siteId]);
204
            }
205
            if ($filter !== '') {
206
                $query->where(['like', 'redirectSrcUrl', $filter]);
207
                $query->orWhere(['like', 'redirectDestUrl', $filter]);
208
            }
209
            $count = $query->count();
210
            $data['links']['pagination'] = [
211
                'total' => $count,
212
                'per_page' => $per_page,
213
                'current_page' => $page,
214
                'last_page' => ceil($count / $per_page),
215
                'next_page_url' => null,
216
                'prev_page_url' => null,
217
                'from' => $offset + 1,
218
                'to' => $offset + ($count > $per_page ? $per_page : $count),
219
            ];
220
        }
221
222
        return $this->asJson($data);
223
    }
224
225
    // Protected Methods
226
    // =========================================================================
227
}
228