Passed
Push — master ( 27e0ff...8f0a74 )
by Nicolaas
07:55
created

DefaultDashboardProvider::sortByCountAndTitle()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 11
rs 10
1
<?php
2
3
namespace Sunnysideup\DashboardWelcomeQuicklinks\Api;
4
5
use SilverStripe\Admin\ModelAdmin;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Admin\ModelAdmin 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 SilverStripe\Assets\File;
7
use SilverStripe\Assets\Folder;
8
use SilverStripe\Assets\Image;
9
use SilverStripe\Assets\Upload;
10
use SilverStripe\CMS\Controllers\CMSSiteTreeFilter_ChangedPages;
0 ignored issues
show
Bug introduced by
The type SilverStripe\CMS\Control...TreeFilter_ChangedPages 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...
11
use SilverStripe\CMS\Controllers\CMSSiteTreeFilter_StatusDraftPages;
0 ignored issues
show
Bug introduced by
The type SilverStripe\CMS\Control...Filter_StatusDraftPages 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...
12
use SilverStripe\CMS\Model\SiteTree;
0 ignored issues
show
Bug introduced by
The type SilverStripe\CMS\Model\SiteTree 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...
13
use SilverStripe\Core\ClassInfo;
14
use SilverStripe\Core\Config\Config;
15
use SilverStripe\Core\Config\Configurable;
16
use SilverStripe\Core\Injector\Injector;
17
use SilverStripe\MFA\Report\EnabledMembers;
0 ignored issues
show
Bug introduced by
The type SilverStripe\MFA\Report\EnabledMembers 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...
18
use SilverStripe\ORM\DataObject;
19
use SilverStripe\Security\DefaultAdminService;
20
use SilverStripe\Security\Group;
21
use SilverStripe\Security\Member;
22
use SilverStripe\Security\Permission;
23
use SilverStripe\Security\PermissionRole;
24
use SilverStripe\VersionedAdmin\ArchiveAdmin;
0 ignored issues
show
Bug introduced by
The type SilverStripe\VersionedAdmin\ArchiveAdmin 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...
25
use Sunnysideup\DashboardWelcomeQuicklinks\Admin\DashboardWelcomeQuicklinks;
26
use Sunnysideup\DashboardWelcomeQuicklinks\Interfaces\DashboardWelcomeQuickLinksProvider;
27
28
class DefaultDashboardProvider implements DashboardWelcomeQuickLinksProvider
29
{
30
    use Configurable;
31
32
    public function provideDashboardWelcomeQuickLinks(): array
33
    {
34
        $this->addPagesLinks();
35
        $this->addFindPages();
36
        $this->addFilesAndImages();
37
        $this->addSiteConfigLinks();
38
        if (Permission::check('ADMIN')) {
39
            $this->addSecurityLinks();
40
        }
41
        $this->addModelAdminLinks();
42
        $this->addMeLinks();
43
        return DashboardWelcomeQuicklinks::get_links();
44
    }
45
46
    private static $model_admins_to_skip = [
0 ignored issues
show
introduced by
The private property $model_admins_to_skip is not used, and could be removed.
Loading history...
47
        ArchiveAdmin::class,
48
    ];
49
50
    private static $pages_to_skip = [
0 ignored issues
show
introduced by
The private property $pages_to_skip is not used, and could be removed.
Loading history...
51
52
    ];
53
54
    protected function addPagesLinks()
55
    {
56
        DashboardWelcomeQuicklinks::add_group('PAGES', 'Pages', 10);
57
        $pagesCount = DataObject::get('Page')->count();
58
        $draftCount = CMSSiteTreeFilter_StatusDraftPages::create()->getFilteredPages()->count();
59
        $revisedCount = CMSSiteTreeFilter_ChangedPages::create()->getFilteredPages()->count();
60
        $add = [
61
            'Title' => DashboardWelcomeQuicklinks::get_base_phrase('add'),
62
            'Link' => '/admin/pages/add'
63
        ];
64
        DashboardWelcomeQuicklinks::add_link(
65
            'PAGES',
66
            DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' Pages (' . $pagesCount . ')',
67
            '/admin/pages',
68
            $add
69
        );
70
        DashboardWelcomeQuicklinks::add_link('PAGES', DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' Unpublished Drafts (' . $draftCount . ')', '/admin/pages?q[FilterClass]=SilverStripe\CMS\Controllers\CMSSiteTreeFilter_StatusDraftPages');
71
        DashboardWelcomeQuicklinks::add_link('PAGES', DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' Unpublished Changes (' . $revisedCount . ')', '/admin/pages?q[FilterClass]=SilverStripe\CMS\Controllers\CMSSiteTreeFilter_ChangedPages');
72
        $pageLastEdited = DataObject::get_one('Page', '', true, 'LastEdited DESC');
73
        if ($pageLastEdited) {
74
            DashboardWelcomeQuicklinks::add_link('PAGES', '✎ Last Edited Page: ' . $pageLastEdited->Title, $pageLastEdited->CMSEditLink());
75
        }
76
        $lastWeekLink = '/admin/pages?q[LastEditedFrom]=' . date('Y-m-d', strtotime('-1 week'));
77
        DashboardWelcomeQuicklinks::add_link('PAGES', DashboardWelcomeQuicklinks::get_base_phrase('review') . ' Recently Modified Pages', $lastWeekLink);
78
        DashboardWelcomeQuicklinks::add_link('PAGES', DashboardWelcomeQuicklinks::get_base_phrase('review') . ' Page Reports', '/admin/reports');
79
    }
80
81
    protected function addFindPages()
82
    {
83
        $pages = [];
84
        $pagesToSkip = (array) $this->Config()->get('pages_to_skip');
85
        foreach (ClassInfo::subclassesFor(SiteTree::class, false) as $className) {
86
            if (in_array($className, $pagesToSkip)) {
87
                continue;
88
            }
89
            $pages[$className] = $className;
90
        }
91
        DashboardWelcomeQuicklinks::add_group('PAGEFILTER', 'Page Types (' . count($pages) . ')', 300);
92
        $pagesArray = [];
93
        foreach ($pages as $pageClassName) {
94
            $pageCount = $pageClassName::get()->filter(['ClassName' => $pageClassName])->count();
95
            if ($pageCount < 1) {
96
                $page = Injector::inst()->get($pageClassName);
97
                if($page->canCreate()) {
98
                    $pageTitle = $page->i18n_singular_name();
99
                    $pagesArray[] = [
100
                        'Title' => DashboardWelcomeQuicklinks::get_base_phrase('add') . ' ' . $pageTitle . ' (0)',
101
                        'Link' => 'admin/pages/add?PageType=' . $pageClassName,
102
                        'Count' => 0,
103
                        'InsideLink' => [],
104
                    ];
105
                }
106
            } elseif ($pageCount === 1) {
107
                $page = DataObject::get_one($pageClassName, ['ClassName' => $pageClassName]);
108
                if($page->canEdit()) {
109
                    $pageTitle = $page->i18n_singular_name();
110
                    $insideLink = [];
111
                    if($page->canCreate()) {
112
                        $insideLink = [
113
                            'Title' => DashboardWelcomeQuicklinks::get_base_phrase('add'),
114
                            'Link' => 'admin/pages/add?PageType=' . $pageClassName,
115
                        ];
116
                    }
117
                    $pagesArray[] = [
118
                        'Title' => DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' ' . $pageTitle . ' (1)',
119
                        'Link' => $page->CMSEditLink(),
120
                        'Count' => 1,
121
                        'InsideLink' => $insideLink,
122
                    ];
123
                }
124
            } else {
125
                $page = Injector::inst()->get($pageClassName);
126
                if($page->canEdit()) {
127
                    $pageTitle = $page->i18n_plural_name();
128
                    $query = 'q[ClassName]=' . $pageClassName;
129
                    $link = 'admin/pages?' . $query;
130
                    $insideLink = [];
131
                    if($page->canCreate()) {
132
                        $insideLink = [
133
                            'Title' => DashboardWelcomeQuicklinks::get_base_phrase('add'),
134
                            'Link' => 'admin/pages/add?PageType=' . $pageClassName,
135
                        ];
136
                    }
137
                    $pagesArray[] = [
138
                        'Title' => DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' ' . $pageTitle . ' (' . $pageCount . ')',
139
                        'Link' => $link,
140
                        'Count' => $pageCount,
141
                        'InsideLink' => $insideLink,
142
                    ];
143
                }
144
            }
145
        }
146
        $pagesArray = $this->sortByCountAndTitle($pagesArray);
147
        foreach($pagesArray as $pageClassName => $pageArray) {
148
            DashboardWelcomeQuicklinks::add_link('PAGEFILTER', $pageArray['Title'], $pageArray['Link'], $pageArray['InsideLink']);
149
        }
150
151
    }
152
153
    protected function addFilesAndImages()
154
    {
155
        // 'Files ('.$filesCount.') and Images ('.$imageCount.')'
156
        DashboardWelcomeQuicklinks::add_group('FILESANDIMAGES', 'Files and Images', 20);
157
        $uploadFolderName = Config::inst()->get(Upload::class, 'uploads_folder');
158
        $uploadFolder = Folder::find_or_make($uploadFolderName);
159
        // all
160
        DashboardWelcomeQuicklinks::add_link('FILESANDIMAGES', DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' Open File Browswer', '/admin/assets');
161
        // per type
162
        $filesCount = File::get()->excludeAny(['ClassName' => [Folder::class, Image::class]])->count();
163
        $imageCount = File::get()->filter(['ClassName' => Image::class])->exclude(['ClassName' => Folder::class])->count();
164
        DashboardWelcomeQuicklinks::add_link('FILESANDIMAGES', DashboardWelcomeQuicklinks::get_base_phrase('review') . ' Files (' . $filesCount . ')', 'admin/assets?filter[appCategory]=DOCUMENT');
165
        DashboardWelcomeQuicklinks::add_link('FILESANDIMAGES', DashboardWelcomeQuicklinks::get_base_phrase('review') . ' Images (' . $imageCount . ')', 'admin/assets?filter[appCategory]=IMAGE');
166
167
        // default upload folder
168
        DashboardWelcomeQuicklinks::add_link('FILESANDIMAGES', DashboardWelcomeQuicklinks::get_base_phrase('review') . ' Open Default Upload Folder', $uploadFolder->CMSEditLink());
169
170
        // recent
171
        $lastWeekLink = '/admin/assets?filter[lastEditedFrom]=' . date('Y-m-d', strtotime('-1 week')) . '&view=tile';
172
        DashboardWelcomeQuicklinks::add_link('FILESANDIMAGES', DashboardWelcomeQuicklinks::get_base_phrase('review') . ' Recently modified Files', $lastWeekLink);
173
    }
174
175
    protected function addSiteConfigLinks()
176
    {
177
        DashboardWelcomeQuicklinks::add_group('SITECONFIG', 'Site Wide Configuration', 20);
178
        DashboardWelcomeQuicklinks::add_link('SITECONFIG', DashboardWelcomeQuicklinks::get_base_phrase('review') . ' Site Settings', '/admin/settings');
179
    }
180
181
    protected function addSecurityLinks()
182
    {
183
        DashboardWelcomeQuicklinks::add_group('SECURITY', 'Security', 30);
184
        $userCount = Member::get()->count();
185
        $add = [
186
            'Title' => DashboardWelcomeQuicklinks::get_base_phrase('add'),
187
            'Link' => '/admin/security/users/EditForm/field/users/item/new'
188
        ];
189
        DashboardWelcomeQuicklinks::add_link(
190
            'SECURITY',
191
            DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' Users (' . $userCount . ')',
192
            '/admin/security',
193
            $add
194
        );
195
        // groups
196
        $groupCount = Group::get()->count();
197
        $add = [
198
            'Title' => DashboardWelcomeQuicklinks::get_base_phrase('add'),
199
            'Link' => '/admin/security/groups/EditForm/field/groups/item/new'
200
        ];
201
        DashboardWelcomeQuicklinks::add_link(
202
            'SECURITY',
203
            DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' Groups  (' . $groupCount . ')',
204
            '/admin/security/groups',
205
            $add
206
        );
207
        DefaultAdminService::singleton()->extend('addSecurityLinks', $this);
208
        $adminGroup = Permission::get_groups_by_permission('ADMIN')->first();
209
        if ($adminGroup) {
210
            $userCount = $adminGroup->Members()->count();
211
            DashboardWelcomeQuicklinks::add_link('SECURITY', DashboardWelcomeQuicklinks::get_base_phrase('review') . ' Administrators (' . $userCount . ')', '/admin/security/groups/EditForm/field/groups/item/' . $adminGroup->ID . '/edit');
212
        }
213
214
        // roles
215
        $roleCount = PermissionRole::get()->count();
216
        $add = [
217
            'Title' => DashboardWelcomeQuicklinks::get_base_phrase('add'),
218
            'Link' => '/admin/security/roles/EditForm/field/roles/item/new'
219
        ];
220
        DashboardWelcomeQuicklinks::add_link(
221
            'SECURITY',
222
            DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' Permission Roles  (' . $roleCount . ')',
223
            '/admin/security/groups',
224
            $add
225
        );
226
        // multi factor
227
        if (class_exists(EnabledMembers::class)) {
228
            $obj = Injector::inst()->get(EnabledMembers::class);
229
            DashboardWelcomeQuicklinks::add_link('SECURITY', DashboardWelcomeQuicklinks::get_base_phrase('review') . ' Multi-Factor Authentication Status', $obj->getLink());
230
        }
231
    }
232
233
    protected function addModelAdminLinks()
234
    {
235
        $modelAdmins = [];
236
        $skips = (array) $this->Config()->get('model_admins_to_skip');
237
        foreach (ClassInfo::subclassesFor(ModelAdmin::class, false) as $className) {
238
            if (in_array($className, $skips)) {
239
                continue;
240
            }
241
            $modelAdmins[$className] = $className;
242
        }
243
        foreach ($modelAdmins as $modelAdminClassName) {
244
            $groupAdded = false;
245
            $ma = Injector::inst()->get($modelAdminClassName);
246
            if ($ma->canView()) {
247
                $mas = $ma->getManagedModels();
248
                if (count($mas) > 0) {
249
                    $numberOfModels = count($mas);
0 ignored issues
show
Unused Code introduced by
The assignment to $numberOfModels is dead and can be removed.
Loading history...
250
                    $groupCode = strtoupper($modelAdminClassName);
251
                    $count = 0;
252
                    foreach ($mas as $model => $title) {
253
                        $count++;
254
                        if (is_array($title)) {
255
                            $title = $title['title'];
256
                            $model = $title['dataClass'] ?? $model;
257
                        }
258
                        if (! class_exists($model)) {
259
                            continue;
260
                        }
261
                        $obj = Injector::inst()->get($model);
262
                        if ($obj && $obj->canView()) {
263
                            if (! $groupAdded) {
264
                                DashboardWelcomeQuicklinks::add_group($groupCode, $ma->menu_title(), 100);
265
                                $groupAdded = true;
266
                            }
267
                            // $classNameList = ClassInfo::subclassesFor($model);
268
                            $ma = ReflectionHelper::allowAccessToProperty(get_class($ma), 'modelClass');
269
                            $ma->modelClass = $model;
270
                            $list = $ma->getList();
271
                            if (! $list) {
272
                                $list = $model::get();
273
                            }
274
                            $objectCount = $list->count();
275
                            if ($objectCount === 1) {
276
                                $baseTable = Injector::inst()->get($model)->baseTable();
277
                                $obj = DataObject::get_one($model, [$baseTable . '.ClassName' => $model]);
278
                                if (! $obj) {
279
                                    $obj = DataObject::get_one($model);
280
                                }
281
                                if ($obj && $obj->hasMethod('CMSEditLink')) {
282
                                    $link = $obj->CMSEditLink();
283
                                    if ($link) {
284
                                        DashboardWelcomeQuicklinks::add_link($groupCode, DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' ' . $model::singleton()->i18n_singular_name(), $link);
285
                                        continue;
286
                                    }
287
                                }
288
                            }
289
290
                            $link = '';
291
                            if ($obj->hasMethod('CMSListLink')) {
292
                                $link = $obj->CMSListLink();
293
                            } if (! $link) {
294
                                $link = $ma->getLinkForModelTab($model);
295
                            }
296
                            $titleContainsObjectCount = strpos($title, ' (' . $objectCount . ')');
297
                            if ($titleContainsObjectCount === false) {
298
                                $title .= ' (' . $objectCount . ')';
299
                            }
300
                            $add = [];
301
                            if ($obj->canCreate()) {
302
                                $classNameEscaped = str_replace('\\', '-', $model);
303
                                $linkNew = $link .= '/EditForm/field/' . $classNameEscaped . '/item/new';
304
                                $add = [
305
                                    'Title' => DashboardWelcomeQuicklinks::get_base_phrase('add'),
306
                                    'Link' => $linkNew
307
                                ];
308
                            }
309
                            DashboardWelcomeQuicklinks::add_link(
310
                                $groupCode,
311
                                DashboardWelcomeQuicklinks::get_base_phrase('edit') . ' ' . $title,
312
                                $link,
313
                                $add
314
                            );
315
                        }
316
                    }
317
                }
318
            }
319
        }
320
    }
321
322
    protected function addMeLinks()
323
    {
324
        DashboardWelcomeQuicklinks::add_group('ME', 'My Account', 200);
325
        DashboardWelcomeQuicklinks::add_link('ME', DashboardWelcomeQuicklinks::get_base_phrase('edit') . '  My Details', '/admin/myprofile');
326
        DashboardWelcomeQuicklinks::add_link('ME', DashboardWelcomeQuicklinks::get_base_phrase('review') . '  Test Password Reset', 'Security/lostpassword');
327
        DashboardWelcomeQuicklinks::add_link('ME', DashboardWelcomeQuicklinks::get_base_phrase('review') . '  Log-out', '/Security/logout');
328
    }
329
330
    protected function sortByCountAndTitle(array $array): array
331
    {
332
        usort($array, function ($a, $b) {
333
            $countComparison = $b['Count'] <=> $a['Count'];
334
            if ($countComparison === 0) {
335
                return $a['Title'] <=> $b['Title'];
336
            }
337
            return $countComparison;
338
        });
339
340
        return $array;
341
    }
342
}
343