Completed
Push — dev ( 0ce36d...e1d2b2 )
by
unknown
15s
created

YupeModule::getAuthItems()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 62
rs 8.829
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * YupeModule файл класса.
4
 * Модуль yupe - основной модуль Юпи!
5
 *
6
 * Модуль yupe содержит в себе все основные компоненты, которые используются другими модулями
7
 * Это наше ядрышко.
8
 *
9
 * @category  YupeMudules
10
 * @package   yupe.modules.yupe
11
 * @author    Andrey Opeykin <[email protected]>
12
 * @copyright 2009-2013 Yupe! Copyright &copy;
13
 * @license   BSD http://ru.wikipedia.org/wiki/%D0%9B%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F_BSD
14
 * @version   0.5.3
15
 * @link      https://yupe.ru
16
 */
17
18
use yupe\components\WebModule;
19
20
/**
21
 * Class YupeModule
22
 */
23
class YupeModule extends WebModule
24
{
25
    /**
26
     *
27
     */
28
    const VERSION = '1.3-dev';
29
30
    /**
31
     * @var
32
     */
33
    public $enableAssets;
34
    /**
35
     * @var
36
     */
37
    public $cache;
38
39
    /**
40
     * @var
41
     */
42
    public $siteDescription;
43
    /**
44
     * @var
45
     */
46
    public $siteName;
47
    /**
48
     * @var
49
     */
50
    public $siteKeyWords;
51
52
    /**
53
     * @var string
54
     */
55
    public $backendLayout = 'column2';
56
    /**
57
     * @var
58
     */
59
    public $backendTheme;
60
    /**
61
     * @var string
62
     */
63
    public $emptyLayout = 'empty';
64
    /**
65
     * @var
66
     */
67
    public $theme;
68
69
    /**
70
     * @var int
71
     */
72
    public $coreCacheTime = 3600;
73
    /**
74
     * @var string
75
     */
76
    public $coreModuleId = 'yupe';
77
78
    /**
79
     * @var string
80
     */
81
    public $uploadPath = 'uploads';
82
    /**
83
     * @var
84
     */
85
    public $email;
86
87
    /**
88
     * @var string
89
     */
90
    public $availableLanguages = 'ru,uk,en,zh';
91
    /**
92
     * @var string
93
     */
94
    public $defaultLanguage = 'ru';
95
    /**
96
     * @var string
97
     */
98
    public $defaultBackendLanguage = 'ru';
99
100
    /**
101
     * @var int
102
     */
103
    public $adminMenuOrder = -1;
104
105
    /**
106
     * @var string
107
     */
108
    public $profileModel = 'User';
109
110
    /**
111
     * @var
112
     */
113
    public $allowedIp;
114
    /**
115
     * @var int
116
     */
117
    public $hidePanelUrls = 0;
118
119
    /**
120
     * @var string
121
     */
122
    public $logo = 'images/logo.png';
123
124
    /**
125
     * @var string
126
     */
127
    public $defaultImage = '/images/nophoto.jpg';
128
129
    /**
130
     * @var array
131
     * @since 0.8
132
     *
133
     * Массив фильтров для контроллеров панели управления
134
     */
135
    protected $backEndFilters = [['yupe\filters\YBackAccessControl - error']];
136
137
    /**
138
     * @return array
139
     * @since 0.8
140
     *
141
     * Вернет массив фильтров для контроллеров панели управления
142
     */
143
    public function getBackendFilters()
144
    {
145
        return $this->backEndFilters;
146
    }
147
148
    /**
149
     * @since 0.8
150
     * @param array $filters
151
     *
152
     * Устанавливает массив фильтров для контроллеров панели управления
153
     */
154
    public function setBackendFilters(array $filters)
155
    {
156
        $this->backEndFilters = $filters;
157
    }
158
159
    /**
160
     * @param $filter
161
     * @since 0.8
162
     *
163
     * Добавить новый фильтр для контроллеров панели управления
164
     */
165
    public function addBackendFilter($filter)
166
    {
167
        $this->backEndFilters[] = $filter;
168
    }
169
170
    /**
171
     * Возвращаем версию:
172
     *
173
     * @return string
174
     **/
175
    public function getVersion()
176
    {
177
        return self::VERSION;
178
    }
179
180
    /**
181
     * @return array
182
     */
183
    public function getAllowedIp()
184
    {
185
        if (strpos($this->allowedIp, ',')) {
186
            return explode(',', trim($this->allowedIp));
187
        }
188
189
        return [];
190
    }
191
192
    /**
193
     * @since 0.7
194
     */
195
    public function getLogo()
196
    {
197
        return Yii::app()->getTheme()->getAssetsUrl().'/'.$this->logo;
198
    }
199
200
    /**
201
     * Проверка модуля на ошибки:
202
     *
203
     * @return bool/mixed - массив сообщений при ошибках или true если всё ок
0 ignored issues
show
Documentation introduced by
The doc-type bool/mixed could not be parsed: Unknown type name "bool/mixed" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
204
     **/
205
    public function checkSelf()
206
    {
207
        $messages = [];
208
209
        if (Yii::app()->hasModule('install')) {
210
            $messages[WebModule::CHECK_ERROR][] = [
211
                'type' => WebModule::CHECK_ERROR,
212
                'message' => Yii::t(
213
                    'YupeModule.yupe',
214
                    'You have active " Install" module, you must disable it after installation! <a href="http://www.yiiframework.com/doc/guide/basics.module">More about Yii modules</a>'
215
                ),
216
            ];
217
        }
218
219
        if (Yii::app()->getDb()->enableProfiling) {
220
            $messages[WebModule::CHECK_ERROR][] = [
221
                'type' => WebModule::CHECK_ERROR,
222
                'message' => Yii::t(
223
                    'YupeModule.yupe',
224
                    'Please, disable profiler (file /protected/config/db.php, parameter "enableProfiling")!'
225
                ),
226
            ];
227
        }
228
229
        if (Yii::app()->getDb()->enableParamLogging) {
230
            $messages[WebModule::CHECK_ERROR][] = [
231
                'type' => WebModule::CHECK_ERROR,
232
                'message' => Yii::t(
233
                    'YupeModule.yupe',
234
                    'Please, disable logging (file /protected/config/db.php, parameter "enableParamLogging")!'
235
                ),
236
            ];
237
        }
238
239
        if (Yii::app()->hasModule('gii')) {
240
            $messages[WebModule::CHECK_ERROR][] = [
241
                'type' => WebModule::CHECK_ERROR,
242
                'message' => Yii::t(
243
                    'YupeModule.yupe',
244
                    'You have active "gii" module. You must disable it after installation! <a href="http://www.yiiframework.com/doc/guide/basics.module">More about Yii modules</a>'
245
                ),
246
            ];
247
        }
248
249
        $uploadPath = Yii::getPathOfAlias('webroot').'/'.$this->uploadPath;
250
251
        if (!is_writable($uploadPath)) {
252
            $messages[WebModule::CHECK_ERROR][] = [
253
                'type' => WebModule::CHECK_ERROR,
254
                'message' => Yii::t(
255
                    'YupeModule.yupe',
256
                    'Directory "{dir}" is not available for write! {link}',
257
                    [
258
                        '{dir}' => $uploadPath,
259
                        '{link}' => CHtml::link(
260
                            Yii::t('YupeModule.yupe', 'Change settings'),
261
                            ['/yupe/backend/modulesettings/', 'module' => 'yupe']
262
                        ),
263
                    ]
264
                ),
265
            ];
266
        }
267
268
        if (!is_writable(Yii::app()->getRuntimePath())) {
269
            $messages[WebModule::CHECK_ERROR][] = [
270
                'type' => WebModule::CHECK_ERROR,
271
                'message' => Yii::t(
272
                    'YupeModule.yupe',
273
                    'Directory "{dir}" is not available for write!',
274
                    ['{dir}' => Yii::app()->runtimePath]
275
                ),
276
            ];
277
        }
278
279
        if (!is_writable(Yii::app()->getAssetManager()->basePath)) {
280
            $messages[WebModule::CHECK_ERROR][] = [
281
                'type' => WebModule::CHECK_ERROR,
282
                'message' => Yii::t(
283
                    'YupeModule.yupe',
284
                    'Directory "{dir}" is not available for write!',
285
                    ['{dir}' => Yii::app()->getAssetManager()->basePath]
286
                ),
287
            ];
288
        }
289
290
        if (defined('YII_DEBUG') && YII_DEBUG) {
291
            $messages[WebModule::CHECK_ERROR][] = [
292
                'type' => WebModule::CHECK_ERROR,
293
                'message' => Yii::t(
294
                    'YupeModule.yupe',
295
                    'Yii is working in debug mode, please, disable it! <br/> <a href="http://www.yiiframework.com/doc/guide/topics.performance">More about Yii performance</a>'
296
                ),
297
            ];
298
        }
299
300
        if (!Yii::app()->getDb()->schemaCachingDuration) {
301
            $messages[WebModule::CHECK_ERROR][] = [
302
                'type' => WebModule::CHECK_ERROR,
303
                'message' => Yii::t(
304
                    'YupeModule.yupe',
305
                    'Please, enable DB caching! <br/> <a href="http://www.yiiframework.com/doc/guide/topics.performance">More about Yii performance</a>'
306
                ),
307
            ];
308
        }
309
310
        return isset($messages[WebModule::CHECK_ERROR]) ? $messages : true;
0 ignored issues
show
Bug Compatibility introduced by
The expression isset($messages[\yupe\co...R]) ? $messages : true; of type array|boolean adds the type array to the return on line 310 which is incompatible with the return type of the parent method yupe\components\WebModule::checkSelf of type boolean.
Loading history...
311
    }
312
313
    /**
314
     * Возвращаем названия параметров:
315
     *
316
     * @return mixed
317
     **/
318
    public function getParamsLabels()
319
    {
320
        return [
321
            'siteDescription' => Yii::t('YupeModule.yupe', 'Site description'),
322
            'siteName' => Yii::t('YupeModule.yupe', 'Site title'),
323
            'siteKeyWords' => Yii::t('YupeModule.yupe', 'Site keywords'),
324
            'backendLayout' => Yii::t('YupeModule.yupe', 'Layout of backend'),
325
            'backendTheme' => Yii::t('YupeModule.yupe', 'Theme of backend'),
326
            'theme' => Yii::t('YupeModule.yupe', 'Frontend theme'),
327
            'coreCacheTime' => Yii::t('YupeModule.yupe', 'Chacing time (sec.)'),
328
            'uploadPath' => Yii::t('YupeModule.yupe', 'File uploads catalog (relative to the site root)'),
329
            'editor' => Yii::t('YupeModule.yupe', 'Visual editor'),
330
            'email' => Yii::t('YupeModule.yupe', 'Admin Email'),
331
            'availableLanguages' => Yii::t(
332
                'YupeModule.yupe',
333
                'List of available languages (for example. ru,en,de)'
334
            ),
335
            'defaultLanguage' => Yii::t('YupeModule.yupe', 'Default language'),
336
            'defaultBackendLanguage' => Yii::t('YupeModule.yupe', 'Default backend language'),
337
            'allowedIp' => Yii::t('YupeModule.yupe', 'Allowed IP'),
338
            'hidePanelUrls' => Yii::t('YupeModule.yupe', 'Hide panel urls'),
339
            'logo' => Yii::t('YupeModule.yupe', 'Logo'),
340
            'allowedExtensions' => Yii::t('YupeModule.yupe', 'Allowed extensions (separated by comma)'),
341
            'mimeTypes' => Yii::t('YupeModule.yupe', 'Mime types'),
342
            'maxSize' => Yii::t('YupeModule.yupe', 'Maximum size (in bytes)'),
343
            'defaultImage' => Yii::t('YupeModule.yupe', 'DefaultImage'),
344
345
        ];
346
    }
347
348
    /**
349
     * Возвращаем редактируемые параметры:
350
     *
351
     * @return mixed
352
     **/
353
    public function getEditableParams()
354
    {
355
        return [
0 ignored issues
show
Best Practice introduced by
The expression return array('coreCacheT...Size', 'defaultImage'); seems to be an array, but some of its elements' types (array) are incompatible with the return type of the parent method yupe\components\WebModule::getEditableParams of type string[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
356
            'coreCacheTime',
357
            'theme' => $this->getThemes(),
358
            'backendTheme' => $this->getThemes(true),
359
            'siteName',
360
            'siteDescription',
361
            'siteKeyWords',
362
            'uploadPath',
363
            'editor' => $this->getEditors(),
364
            'email',
365
            'availableLanguages',
366
            'defaultLanguage' => $this->getLanguagesList(),
367
            'defaultBackendLanguage' => $this->getLanguagesList(),
368
            'allowedIp',
369
            'hidePanelUrls' => $this->getChoice(),
370
            'logo',
371
            'allowedExtensions',
372
            'mimeTypes',
373
            'maxSize',
374
            'defaultImage',
375
        ];
376
    }
377
378
    /**
379
     * массив групп параметров модуля, для группировки параметров на странице настроек
380
     *
381
     * @return array
382
     */
383
    public function getEditableParamsGroups()
384
    {
385
        return [
386
            'site' => [
387
                'label' => Yii::t('YupeModule.yupe', 'Site settings'),
388
                'items' => [
389
                    'logo',
390
                    'siteName',
391
                    'siteDescription',
392
                    'siteKeyWords',
393
                ],
394
            ],
395
            'theme' => [
396
                'label' => Yii::t('YupeModule.yupe', 'Themes'),
397
                'items' => [
398
                    'theme',
399
                    'backendTheme',
400
                ],
401
            ],
402
            'language' => [
403
                'label' => Yii::t('YupeModule.yupe', 'Language settings'),
404
                'items' => [
405
                    'availableLanguages',
406
                    'defaultLanguage',
407
                    'defaultBackendLanguage',
408
                ],
409
            ],
410
            'editors' => [
411
                'label' => Yii::t('YupeModule.yupe', 'Visual editors settings'),
412
                'items' => [
413
                    'editor',
414
                    'uploadPath',
415
                    'allowedExtensions',
416
                    'mimeTypes',
417
                    'maxSize',
418
                    'defaultImage',
419
                ],
420
            ],
421
            'main' => [
422
                'label' => Yii::t('YupeModule.yupe', 'Main settings admin panel'),
423
                'items' => [
424
                    'hidePanelUrls',
425
                    'allowedIp',
426
                    'email',
427
                    'coreCacheTime',
428
                ],
429
            ],
430
        ];
431
    }
432
433
    /**
434
     * Возвращаем правила валидации для параметров модуля
435
     *
436
     * @return array Правила валидации для параметров модуля
437
     */
438
    public function rules()
439
    {
440
        return [
441
            [
442
                'availableLanguages',
443
                'filter',
444
                'filter' => function ($str) {
445
                    return preg_replace('/\s+/', '', $str);
446
                },
447
            ],
448
        ];
449
    }
450
451
    /**
452
     * Возвращаем статус, устанавливать ли галку для установки модуля в инсталяторе по умолчанию:
453
     *
454
     * @return bool
455
     **/
456
    public function getIsInstallDefault()
457
    {
458
        return true;
459
    }
460
461
    /**
462
     * Возвращаем статус, возможно ли модуль отключать:
463
     *
464
     * @return bool
465
     **/
466
    public function getIsNoDisable()
467
    {
468
        return true;
469
    }
470
471
    /**
472
     * Возвращаем массив языков:
473
     *
474
     * @return mixed
475
     **/
476
    public function getLanguagesList()
477
    {
478
        $langs = [];
479
        foreach (explode(',', $this->availableLanguages) as $lang) {
480
            $langs[$lang] = Yii::app()->getLocale()->getLocaleDisplayName(
481
                strpos($lang, '_') !== false ? explode('_', $lang)[0] : $lang
482
            );
483
        }
484
485
        return $langs;
486
    }
487
488
    /**
489
     * Возвращаем линк на админ панель:
490
     *
491
     * @return mixed
492
     **/
493
    public function getAdminPageLink()
494
    {
495
        return '/yupe/backend/settings';
496
    }
497
498
    /**
499
     * Возвращаем массив меню:
500
     *
501
     * @return mixed
502
     **/
503
    public function getNavigation()
504
    {
505
        return [
506
            [
507
                'label' => Yii::t('YupeModule.yupe', 'Clean cache'),
508
                'url' => ['/yupe/backend/ajaxflush', 'method' => 1],
509
                'linkOptions' => [
510
                    'class' => 'flushAction',
511
                    'method' => 'cacheAll',
512
                ],
513
                'icon' => 'fa fa-fw fa-trash-o',
514
                'items' => [
515
                    [
516
                        'icon' => 'fa fa-fw fa-trash-o',
517
                        'label' => Yii::t('YupeModule.yupe', 'Clean cache'),
518
                        'url' => ['/yupe/backend/ajaxflush', 'method' => 1],
519
                        'linkOptions' => [
520
                            'class' => 'flushAction',
521
                            'method' => 'cacheFlush',
522
                        ],
523
                    ],
524
                    [
525
                        'icon' => 'fa fa-fw fa-trash-o',
526
                        'label' => Yii::t('YupeModule.yupe', 'Clean settings cache'),
527
                        'url' => ['/yupe/backend/flushDumpSettings'],
528
                        'linkOptions' => [
529
                            'class' => 'flushAction',
530
                            'method' => 'cacheFlush',
531
                        ],
532
                    ],
533
                    [
534
                        'icon' => 'fa fa-fw fa-trash-o',
535
                        'label' => Yii::t('YupeModule.yupe', 'Clean assets'),
536
                        'url' => ['/yupe/backend/ajaxflush', 'method' => 2],
537
                        'linkOptions' => [
538
                            'class' => 'flushAction',
539
                            'method' => 'assetsFlush',
540
                        ],
541
                        'visible' => !Yii::app()->getAssetManager()->linkAssets,
542
                    ],
543
                    [
544
                        'icon' => 'fa fa-fw fa-trash-o',
545
                        'label' => Yii::t('YupeModule.yupe', 'Clean cache and assets'),
546
                        'url' => ['/yupe/backend/ajaxflush', 'method' => 3],
547
                        'linkOptions' => [
548
                            'class' => 'flushAction',
549
                            'method' => 'cacheAssetsFlush',
550
                        ],
551
                        'visible' => !Yii::app()->getAssetManager()->linkAssets,
552
                    ],
553
                ],
554
            ],
555
            [
556
                'icon' => "fa fa-fw fa-th",
557
                'label' => Yii::t('YupeModule.yupe', 'My modules'),
558
                'url' => ['/yupe/backend/settings'],
559
            ],
560
            [
561
                'icon' => 'fa fa-fw fa-picture-o',
562
                'label' => Yii::t('YupeModule.yupe', 'Theme settings'),
563
                'url' => ['/yupe/backend/themesettings'],
564
            ],
565
            [
566
                'icon' => 'fa fa-fw fa-wrench',
567
                'label' => Yii::t('YupeModule.yupe', 'Site settings'),
568
                'url' => $this->getSettingsUrl(),
569
            ],
570
            [
571
                'icon' => 'fa fa-fw fa-shopping-cart',
572
                'label' => Yii::t('YupeModule.yupe', 'Yupe! store'),
573
                'url' => 'https://yupe.ru/store?from=panel-yupe-store',
574
                'linkOptions' => [
575
                    'target' => '_blank'
576
                ]
577
            ],
578
            [
579
                'icon' => "fa fa-fw fa-question-circle",
580
                'label' => Yii::t('YupeModule.yupe', 'About Yupe!'),
581
                'url' => ['/yupe/backend/help'],
582
                'visible' => Yii::app()->getUser()->checkAccess('Yupe.Backend.index'),
583
            ],
584
        ];
585
    }
586
587
    /**
588
     * Возвращаем название категории модуля:
589
     *
590
     * @return string
591
     **/
592
    public function getCategory()
593
    {
594
        return Yii::t('YupeModule.yupe', 'Yupe!');
595
    }
596
597
    /**
598
     * Возвращаем название модуля:
599
     *
600
     * @return string
601
     **/
602
    public function getName()
603
    {
604
        return Yii::t('YupeModule.yupe', 'Yupe!');
605
    }
606
607
    /**
608
     * Возвращаем описание модуля:
609
     *
610
     * @return string
611
     **/
612
    public function getDescription()
613
    {
614
        return Yii::t('YupeModule.yupe', 'Yupe core!');
615
    }
616
617
    /**
618
     * Возвращаем автора модуля:
619
     *
620
     * @return string
621
     **/
622
    public function getAuthor()
623
    {
624
        return 'yupe team';
625
    }
626
627
    /**
628
     * Возвращаем почту автора модуля:
629
     *
630
     * @return string
631
     **/
632
    public function getAuthorEmail()
633
    {
634
        return Yii::t('YupeModule.yupe', '[email protected]');
635
    }
636
637
    /**
638
     * Возвращаем адрес на сайт автора модуля:
639
     *
640
     * @return string
641
     **/
642
    public function getUrl()
643
    {
644
        return Yii::t('YupeModule.yupe', 'https://yupe.ru');
645
    }
646
647
    /**
648
     * Возвращаем иконка модуля:
649
     *
650
     * @return string
651
     **/
652
    public function getIcon()
653
    {
654
        return "fa fa-fw fa-cog";
655
    }
656
657
    /**
658
     * Получает полный алиас нужного лайаута бэкенда с учетом темы
659
     *
660
     * @param string $layoutName Название лайаута, если не задан - берется по-умолчанию для бекенда
661
     *
662
     * @since 0.4
663
     * @return string Полный путь к лайауту
664
     */
665
    public function getBackendLayoutAlias($layoutName = '')
666
    {
667
        if ($this->backendTheme) {
668
            return 'themes.backend_'.$this->backendTheme.'.views.yupe.layouts.'.($layoutName ? $layoutName : $this->backendLayout);
669
        } else {
670
            return 'application.modules.yupe.views.layouts.'.($layoutName ? $layoutName : $this->backendLayout);
671
        }
672
    }
673
674
    /**
675
     * Метод возвращает доступные темы оформления
676
     *
677
     * Для добавления новой темы необходимо:
678
     * Прочитать http://yiiframework.ru/doc/guide/ru/topics.theming
679
     * Скопировать тему в каталог  WebRoot/themes или аналогичный (настройки themeManager)
680
     * Название каталога с темой для панели управления должно начинаться с префикса "backend_", например "backend_bootstrap"
681
     *
682
     * @param bool $backend - если установлен в true - вернет темы оформления для панели управления, иначе - для публичной части сайта
683
     *
684
     * @return array список доступных тем
685
     * @since 0.4
686
     * @todo возможно, стоит добавить кэширование чтобы каждый раз не ходить по файловой системе
687
     */
688
    public function getThemes($backend = false)
689
    {
690
        $themes = [];
691
692
        if (isset(Yii::app()->themeManager->basePath) && $handler = opendir(Yii::app()->themeManager->basePath)) {
693
            while (($file = readdir($handler))) {
694
                if ($file != '.' && $file != '..' && !is_file($file)) {
695
                    if ("backend_" == substr($file, 0, 8)) {
696
                        if ($backend) {
697
                            $file = str_replace("backend_", "", $file);
698
                            $themes[$file] = $file;
699
                        }
700
                    } else {
701
                        if (!$backend) {
702
                            $themes[$file] = $file;
703
                        }
704
                    }
705
                }
706
            }
707
            closedir($handler);
708
        }
709
710
        return $themes;
711
    }
712
713
    /**
714
     * Метод возвращает пункты, содержащие сабменю для заголовок групп
715
     *
716
     * @param array $menu - список пунктов
717
     *
718
     * @since 0.5
719
     * @return array преобразованный список пунктов
720
     */
721
    public function getSubMenu($menu)
722
    {
723
        $items = [];
724
        $endItemKey = count($menu) ? array_reverse(array_keys($menu))[0] : '';
725
        foreach ($menu as $key => $item) {
726
            if ($key === '') {
727
                continue;
728
            }
729
            if (isset($item['items']) && is_array($item['items']) && !empty($item['items'])) {
730
                $subItems = $item['items'];
731
                unset($item['items'], $item['icon'], $item['url']);
732
                $items[] = $item;
733
                $items = array_merge($items, $subItems);
734
                if ($key != $endItemKey) {
735
                    $items[] = "---";
736
                }
737
            } else {
738
                $items[] = $item;
739
            }
740
        }
741
742
        foreach ($items as $item => $data) {
743
            if (empty($data['items']) && !isset($data['url'])) {
744
                unset($items[$item]);
745
            }
746
        }
747
748
        return $items;
749
    }
750
751
    /**
752
     * Выдает путь к стилям, определяет вкелючена тема или нет
753
     *
754
     * @since 0.5
755
     * @return string путь к директории
756
     */
757
    public function getThemeBaseUrl()
758
    {
759
        return (Yii::app()->theme) ? Yii::app()->theme->baseUrl : Yii::app()->baseUrl;
760
    }
761
762
    /**
763
     * Выдает массив для меню в административной панеле
764
     *
765
     * @since 0.5
766
     * @return array массив меню
767
     */
768
    public function getLanguageSelectorArray()
769
    {
770
        $langs = explode(',', $this->availableLanguages);
771
772
        if (count($langs) <= 1) {
773
            return [];
774
        }
775
776
        if (!Yii::app()->getUrlManager() instanceof \yupe\components\urlManager\LangUrlManager) {
777
            Yii::log(
778
                'For use multi lang, please, enable "yupe\components\urlManager\LangUrlManager" as default UrlManager',
779
                CLogger::LEVEL_WARNING
780
            );
781
782
            return [];
783
        }
784
785
        $items = [];
786
        $currentLanguage = Yii::app()->getLanguage();
787
        $cp = Yii::app()->getRequest()->url;
788
789
        foreach ($langs as $lang) {
790
            $lang = trim($lang);
791
            if ($lang == $currentLanguage) {
792
                continue;
793
            } else {
794
                $items[] = [
795
                    'icon' => 'iconflags iconflags-' . $lang,
796
                    'label' => Yii::t('YupeModule.yupe', $lang),
797
                    'url' => Yii::app()->urlManager->replaceLangInUrl($cp, $lang),
798
                ];
799
            }
800
        }
801
802
        return [
803
            [
804
                'icon' => 'iconflags iconflags-' . $currentLanguage,
805
                'label' => Yii::t('YupeModule.yupe', $currentLanguage),
806
                'items' => $items,
807
                'submenuOptions' => ['style' => 'min-width: 20px;'],
808
            ],
809
        ];
810
    }
811
812
    /**
813
     * Генерация анкора PoweredBy
814
     *
815
     * @param string $color - цвет
816
     * @param string $text - текст
817
     *
818
     * @return string poweredBy
819
     */
820
    public function poweredBy($color = 'yellow', $text = '')
821
    {
822
        if (empty($text)) {
823
            $text = Yii::t('YupeModule.yupe', 'Powered by Yupe!');
824
        }
825
826
        return CHtml::link(
827
            CHtml::image(
828
                Yii::app()->getAssetManager()->publish(
829
                    Yii::getPathOfAlias('application.modules.yupe.views.assets')
830
                )."/img/yupe_{$color}.png",
831
                $text,
832
                ['alt' => CHtml::encode($text)]
833
            ),
834
            'https://yupe.ru?from=pb',
835
            [
836
                'title' => CHtml::encode($text),
837
                'target' => '_blank',
838
            ]
839
        );
840
    }
841
842
    /**
843
     * Получаем массив с именами модулей, от которых зависит работа данного модуля
844
     *
845
     * @return array Массив с именами модулей, от которых зависит работа данного модуля
846
     *
847
     * @since 0.5
848
     */
849
    public function getDependencies()
850
    {
851
        return ['user'];
852
    }
853
854
    /**
855
     * @return array
856
     */
857
    public function getLayoutsList()
858
    {
859
        $data = [];
860
861
        foreach (new GlobIterator(Yii::app()->getTheme()->basePath.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'layouts'.DIRECTORY_SEPARATOR.'*.php') as $item) {
862
            $name = $item->getBaseName('.php');
863
            $data[$name] = $name;
864
        }
865
866
        return $data;
867
    }
868
869
870
    /**
871
     * @return array
872
     */
873
    public function getAuthItems()
874
    {
875
        return [
876
            [
877
                'name' => 'ManageYupeParams',
878
                'description' => Yii::t('YupeModule.yupe', 'Manage Yupe params'),
879
                'type' => AuthItem::TYPE_TASK,
880
                'items' => [
881
                    [
882
                        'type' => AuthItem::TYPE_OPERATION,
883
                        'name' => 'Yupe.Backend.index',
884
                        'description' => Yii::t('YupeModule.yupe', 'Yupe panel'),
885
                    ],
886
                    [
887
                        'type' => AuthItem::TYPE_OPERATION,
888
                        'name' => 'Yupe.Backend.Settings',
889
                        'description' => Yii::t('YupeModule.yupe', 'View modules list'),
890
                    ],
891
                    [
892
                        'type' => AuthItem::TYPE_OPERATION,
893
                        'name' => 'Yupe.Backend.Modupdate',
894
                        'description' => Yii::t('YupeModule.yupe', 'Update module'),
895
                    ],
896
                    [
897
                        'type' => AuthItem::TYPE_OPERATION,
898
                        'name' => 'Yupe.Backend.Modulesettings',
899
                        'description' => Yii::t('YupeModule.yupe', 'View module settings'),
900
                    ],
901
                    [
902
                        'type' => AuthItem::TYPE_OPERATION,
903
                        'name' => 'Yupe.Backend.SaveModulesettings',
904
                        'description' => Yii::t('YupeModule.yupe', 'Update module settings'),
905
                    ],
906
                    [
907
                        'type' => AuthItem::TYPE_OPERATION,
908
                        'name' => 'Yupe.Backend.Themesettings',
909
                        'description' => Yii::t('YupeModule.yupe', 'Update theme settings'),
910
                    ],
911
                    [
912
                        'type' => AuthItem::TYPE_OPERATION,
913
                        'name' => 'Yupe.Backend.FlushDumpSettings',
914
                        'description' => Yii::t('YupeModule.yupe', 'Cleanup settings dump'),
915
                    ],
916
                    [
917
                        'type' => AuthItem::TYPE_OPERATION,
918
                        'name' => 'Yupe.Backend.Ajaxflush',
919
                        'description' => Yii::t('YupeModule.yupe', 'Cleanup cache and assets'),
920
                    ],
921
                    [
922
                        'type' => AuthItem::TYPE_OPERATION,
923
                        'name' => 'Yupe.ModulesBackend.ConfigUpdate',
924
                        'description' => Yii::t('YupeModule.yupe', 'Update module config'),
925
                    ],
926
                    [
927
                        'type' => AuthItem::TYPE_OPERATION,
928
                        'name' => 'Yupe.ModulesBackend.ModuleStatus',
929
                        'description' => Yii::t('YupeModule.yupe', 'Update module status'),
930
                    ],
931
                ],
932
            ],
933
        ];
934
    }
935
}
936