admin-page.class.php
582 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Admin page class |
| 4 | * |
| 5 | * @author Alex Kovalev <alex.kovalevv@gmail.com> |
| 6 | * @since 1.0.0 |
| 7 | * @package factory-core |
| 8 | * @copyright (c) 2018, Webcraftic Ltd |
| 9 | * |
| 10 | */ |
| 11 | |
| 12 | // Exit if accessed directly |
| 13 | if( !defined('ABSPATH') ) { |
| 14 | exit; |
| 15 | } |
| 16 | |
| 17 | if( !class_exists('Wbcr_FactoryPages480_AdminPage') ) { |
| 18 | |
| 19 | class Wbcr_FactoryPages480_AdminPage extends Wbcr_FactoryPages480_Page { |
| 20 | |
| 21 | /** |
| 22 | * Visible page title. |
| 23 | * For example: 'License Manager' |
| 24 | * |
| 25 | * @var string |
| 26 | */ |
| 27 | public $page_title; |
| 28 | |
| 29 | /** |
| 30 | * Visible title in menu. |
| 31 | * For example: 'License Manager' |
| 32 | * |
| 33 | * @var string |
| 34 | */ |
| 35 | public $menu_title = null; |
| 36 | |
| 37 | /** |
| 38 | * If set, an extra sub menu will be created with another title. |
| 39 | * |
| 40 | * @var string |
| 41 | */ |
| 42 | public $menu_sub_title = null; |
| 43 | |
| 44 | /** |
| 45 | * Иконка меню в главном меню админ панели |
| 46 | * |
| 47 | * Используется только в том случае, если ссылка на страницу отображается |
| 48 | * в главном меню админ панели (левый сайдбар) и не является элементом подменю. |
| 49 | * |
| 50 | * Пример: '~/assets/img/menu-icon.png', ~/ будет заменен ссылкой на корневую |
| 51 | * директорию плагина. |
| 52 | * Можно использовать dashicons: '\f321' |
| 53 | * |
| 54 | * @var string |
| 55 | */ |
| 56 | public $menu_icon = null; |
| 57 | |
| 58 | /** |
| 59 | * Позиция в главном меню админ панели |
| 60 | * |
| 61 | * Если эта страница была добавлена в главное меню админ панели (левый сайдбар). |
| 62 | * Вы можете установить позицию меню. Подробнее смотрите в Wordpress кодексе. |
| 63 | * |
| 64 | * @link http://codex.wordpress.org/Function_Reference/add_menu_page |
| 65 | * |
| 66 | * Позиция может быть установлена от 0 до 100 и чем больше цифра, тем ниже будет |
| 67 | * расположен пункт меню. |
| 68 | * |
| 69 | * Внимание! Если два пункта используют одинаковую цифру-позицию, один из пунктов |
| 70 | * меню может быть перезаписан и будет показан только один пункт из дву� |
| 71 | . |
| 72 | * Чтобы избежать конфликта, можно использовать десятичные значения, вместо целы� |
| 73 | |
| 74 | * чисел: 63.3 вместо 63. Используйте кавычки: "63.3". |
| 75 | * |
| 76 | * 2 Консоль |
| 77 | * 4 Разделитель |
| 78 | * 5 Посты |
| 79 | * 10 Медиа |
| 80 | * 15 Ссылки |
| 81 | * 20 Страницы |
| 82 | * 25 Комментарии |
| 83 | * 59 Разделитель |
| 84 | * 60 Внешний вид |
| 85 | * 65 Плагины |
| 86 | * 70 Пользователи |
| 87 | * 75 Инструменты |
| 88 | * 80 Настройки |
| 89 | * 99 Разделитель |
| 90 | * |
| 91 | * @var string |
| 92 | */ |
| 93 | public $menu_position = null; |
| 94 | |
| 95 | /** |
| 96 | * Тип записи к меню которой, нужно прикрепить ссылку на страницу |
| 97 | * |
| 98 | * К примеру, если вы установите тип записи "post". В меню "Записи" появится |
| 99 | * ссылка на эту страницу, как элемент подменю. |
| 100 | * |
| 101 | * Пример: 'post' |
| 102 | * |
| 103 | * @var string |
| 104 | */ |
| 105 | public $menu_post_type = null; |
| 106 | |
| 107 | /** |
| 108 | * Название (slug) элемента главного родительского меню в админ панели, в которое будет |
| 109 | * добавлен пункт меню этой страницы, как элемент подменю. |
| 110 | * |
| 111 | * Примеры: |
| 112 | * index.php - Консоль (Dashboard). Или спец. функция: add_dashboard_page(); |
| 113 | * edit.php - Посты (Posts). Или спец. функция: add_posts_page(); |
| 114 | * upload.php - Медиафайлы (Media). Или спец. функция: add_media_page(); |
| 115 | * link-manager.php - Ссылки (Links). Или спец. функция: add_links_page(); |
| 116 | * edit.php?post_type=page - Страницы (Pages). Или спец. функция: add_pages_page(); |
| 117 | * edit-comments.php - Комментарии (Comments). Или спец. функция: add_comments_page(); |
| 118 | * edit.php?post_type=your_post_type - Произвольные типы записей. |
| 119 | * themes.php - Внешний вид (Appearance). Или спец. функция: add_theme_page(); |
| 120 | * plugins.php - Плагины (Plugins). Или спец. функция: add_plugins_page(); |
| 121 | * users.php - Пользователи (Users). Или спец. функция: add_users_page(); |
| 122 | * tools.php - Инструменты (Tools). Или спец. функция: add_management_page(); |
| 123 | * options-general.php - Настройки (Settings). Или спец. функция: add_options_page() |
| 124 | * settings.php - Настройки (Settings) сети сайтов в MU режиме. |
| 125 | * |
| 126 | * @var string |
| 127 | */ |
| 128 | public $menu_target = null; |
| 129 | |
| 130 | /** |
| 131 | * if true, then admin.php is used as a base url. |
| 132 | * |
| 133 | * @var bool |
| 134 | */ |
| 135 | public $custom_target = false; |
| 136 | |
| 137 | /** |
| 138 | * Разрешения пользователя, чтобы иметь доступ к странице. |
| 139 | * |
| 140 | * Этот параметр отвечает и за доступ к странице этого пункта меню. Подробнее |
| 141 | * смотрите в кодексе Wordpress: |
| 142 | * |
| 143 | * @link http://codex.wordpress.org/Roles_and_Capabilities |
| 144 | * |
| 145 | * Указывать массив разрешений, например: |
| 146 | * ['manage_options', 'manage_network'] |
| 147 | * |
| 148 | * @var array |
| 149 | */ |
| 150 | public $capabilitiy = null; |
| 151 | |
| 152 | /** |
| 153 | * Скрыть страницу из главного меню админ панели? |
| 154 | * |
| 155 | * Если true, то закладка на эту страницу не будет добавлена в главное меню |
| 156 | * админ панели. |
| 157 | * |
| 158 | * @var bool |
| 159 | */ |
| 160 | public $internal = false; |
| 161 | |
| 162 | /** |
| 163 | * If true, the page is for network |
| 164 | * |
| 165 | * @var bool |
| 166 | */ |
| 167 | public $network = false; |
| 168 | |
| 169 | /** |
| 170 | * Предотвратить создание страницы? |
| 171 | * |
| 172 | * Если true, то страница не будет создана. Может пригодиться в те� |
| 173 | случая� |
| 174 | , |
| 175 | * когда страница должна быть создана только при выполнении условий. |
| 176 | * |
| 177 | * @since 3.0.6 |
| 178 | * @var bool |
| 179 | */ |
| 180 | public $hidden = false; |
| 181 | |
| 182 | /** |
| 183 | * Сделать доступной страницу в панели управлениям сайтами (панель суперадминистратора) |
| 184 | * |
| 185 | * Если установлено true, в панели управления сайтами появится закладка на эту страницу. |
| 186 | * Также эта страница получить разрешения на просмотр для группы суперадминистраторов. |
| 187 | * |
| 188 | * @var bool |
| 189 | */ |
| 190 | public $available_for_multisite = false; |
| 191 | |
| 192 | /** |
| 193 | * Задать текст ссылки на странице плагинов (рядом с активировать/деактивировать) |
| 194 | * |
| 195 | * Будет работать только, свойство $add_link_to_plugin_actions=true. |
| 196 | * По умолчанию, если текст ссылки не задан, используется заголовок элемента меню |
| 197 | * или заголовок страницы. |
| 198 | * |
| 199 | * @var string |
| 200 | */ |
| 201 | public $title_plugin_action_link; |
| 202 | |
| 203 | /** |
| 204 | * Добавлять ссылку на странице плагинов (рядом с активировать/деактивировать)? |
| 205 | * |
| 206 | * Если true, будет автоматически добавлена ссылка на эту страницу, внутри страницы |
| 207 | * wp-admin/plugins.php (рядом с активировать/деактивировать). Чаще всего требуется |
| 208 | * добавить ссылку на страницу настроек. Если эта страница у вас является главной, |
| 209 | * то вы можете сделать это свойство активным. |
| 210 | * |
| 211 | * @link https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name) |
| 212 | * @var bool |
| 213 | */ |
| 214 | public $add_link_to_plugin_actions = false; |
| 215 | |
| 216 | public function __construct(Wbcr_Factory480_Plugin $plugin) |
| 217 | { |
| 218 | parent::__construct($plugin); |
| 219 | $this->configure(); |
| 220 | |
| 221 | $this->id = empty($this->id) ? str_replace('adminpage', '', strtolower(get_class($this))) : $this->id; |
| 222 | |
| 223 | if( $this->add_link_to_plugin_actions ) { |
| 224 | if( $plugin->isNetworkActive() ) { |
| 225 | // plugin settings link |
| 226 | add_filter("network_admin_plugin_action_links_" . $this->plugin->get_paths()->basename, [ |
| 227 | $this, |
| 228 | 'addLinkToPluginActions' |
| 229 | ]); |
| 230 | } else { |
| 231 | // plugin settings link |
| 232 | add_filter("plugin_action_links_" . $this->plugin->get_paths()->basename, [ |
| 233 | $this, |
| 234 | 'addLinkToPluginActions' |
| 235 | ]); |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | /** |
| 241 | * May be used to configure the page before uts usage. |
| 242 | */ |
| 243 | public function configure() |
| 244 | { |
| 245 | } |
| 246 | |
| 247 | /** |
| 248 | * Includes the Factory Bootstrap assets for a current page. |
| 249 | * |
| 250 | * @param string $hook |
| 251 | * |
| 252 | * @return void |
| 253 | */ |
| 254 | public function actionAdminBootstrapScripts($hook) |
| 255 | { |
| 256 | $this->scripts->connect('bootstrap'); |
| 257 | $this->styles->connect('bootstrap'); |
| 258 | } |
| 259 | |
| 260 | /** |
| 261 | * Includes the assets for a current page (all assets except Factory Bootstrap assets). |
| 262 | * |
| 263 | * @param string $hook |
| 264 | * |
| 265 | * @return void |
| 266 | */ |
| 267 | public function actionAdminScripts($hook) |
| 268 | { |
| 269 | $this->scripts->connect(); |
| 270 | $this->styles->connect(); |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | * @return string |
| 275 | */ |
| 276 | public function getMenuScope() |
| 277 | { |
| 278 | return $this->plugin->getPluginName(); |
| 279 | } |
| 280 | |
| 281 | |
| 282 | /** |
| 283 | * @return string |
| 284 | */ |
| 285 | public function getMenuTitle() |
| 286 | { |
| 287 | $menu_title = !$this->menu_title ? $this->page_title : $this->menu_title; |
| 288 | |
| 289 | /** |
| 290 | * @since 4.0.9 - добавлен |
| 291 | */ |
| 292 | return apply_filters('wbcr/factory/pages/impressive/menu_title', $menu_title, $this->plugin->getPluginName(), $this->id); |
| 293 | } |
| 294 | |
| 295 | /** |
| 296 | * @return string |
| 297 | */ |
| 298 | public function getPageTitle() |
| 299 | { |
| 300 | |
| 301 | $page_title = !$this->page_title ? $this->getMenuTitle() : $this->page_title; |
| 302 | |
| 303 | /** |
| 304 | * @since 4.0.9 - добавлен |
| 305 | */ |
| 306 | return apply_filters('wbcr/factory/pages/impressive/page_title', $page_title, $this->plugin->getPluginName(), $this->id); |
| 307 | } |
| 308 | |
| 309 | /** |
| 310 | * @param null $id |
| 311 | * |
| 312 | * @return mixed|string |
| 313 | */ |
| 314 | public function getResultId($id = null) |
| 315 | { |
| 316 | $id = !empty($id) ? $id : $this->id; |
| 317 | |
| 318 | if( $this->plugin ) { |
| 319 | return $id . '-' . $this->getMenuScope(); |
| 320 | } |
| 321 | |
| 322 | return $id; |
| 323 | } |
| 324 | |
| 325 | /** |
| 326 | * Registers admin page for the admin menu. |
| 327 | */ |
| 328 | public function connect() |
| 329 | { |
| 330 | $result_id = $this->getResultId(); |
| 331 | |
| 332 | $this->hidden = apply_filters('wbcr_factory_480_page_is_hidden_' . $result_id, $this->hidden); |
| 333 | |
| 334 | if( $this->hidden ) { |
| 335 | return; |
| 336 | } |
| 337 | |
| 338 | $this->internal = apply_filters('wbcr_factory_480_page_is_internal_' . $result_id, $this->internal); |
| 339 | |
| 340 | if( $this->internal ) { |
| 341 | $this->menu_target = null; |
| 342 | $this->menu_post_type = null; |
| 343 | } |
| 344 | |
| 345 | // makes redirect to the page |
| 346 | $controller = $this->request->get('fy_page', null, true); |
| 347 | |
| 348 | if( $controller && $controller == $this->id ) { |
| 349 | $plugin = $this->request->get('fy_plugin', null, true); |
| 350 | |
| 351 | if( $this->plugin->getPluginName() == $plugin ) { |
| 352 | |
| 353 | $action = $this->request->get('fy_action', 'index', true); |
| 354 | $is_ajax = $this->request->get('fy_ajax', false); |
| 355 | |
| 356 | if( $is_ajax ) { |
| 357 | $this->executeByName($action); |
| 358 | exit; |
| 359 | } else { |
| 360 | |
| 361 | $params = (array)$this->request->getAll(true); |
| 362 | |
| 363 | unset($params['fy_page']); |
| 364 | unset($params['fy_plugin']); |
| 365 | unset($params['fy_action']); |
| 366 | |
| 367 | $this->redirectToAction($action, $params); |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | // calls scripts and styles, adds pages to menu |
| 373 | if( $this->request->get('page', 'none') == $result_id ) { |
| 374 | $this->assets($this->scripts, $this->styles); |
| 375 | |
| 376 | if( !$this->scripts->isEmpty('bootstrap') || !$this->styles->isEmpty('bootstrap') ) { |
| 377 | add_action('wbcr_factory_480_bootstrap_enqueue_scripts_' . $this->plugin->getPluginName(), [ |
| 378 | $this, |
| 379 | 'actionAdminBootstrapScripts' |
| 380 | ]); |
| 381 | } |
| 382 | |
| 383 | // includes styles and scripts |
| 384 | if( !$this->scripts->isEmpty() || !$this->styles->isEmpty() ) { |
| 385 | add_action('admin_enqueue_scripts', [$this, 'actionAdminScripts']); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | // if this page for a custom menu page |
| 390 | if( $this->menu_post_type ) { |
| 391 | $this->menu_target = 'edit.php?post_type=' . $this->menu_post_type; |
| 392 | |
| 393 | if( empty($this->capabilitiy) ) { |
| 394 | $this->capabilitiy = 'edit_' . $this->menu_post_type; |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | // sets default capabilities |
| 399 | if( empty($this->capabilitiy) ) { |
| 400 | $this->capabilitiy = 'manage_options'; |
| 401 | } |
| 402 | |
| 403 | // submenu |
| 404 | if( $this->menu_target ) { |
| 405 | add_submenu_page($this->menu_target, $this->getPageTitle(), $this->getMenuTitle(), $this->capabilitiy, $result_id, [ |
| 406 | $this, |
| 407 | 'show' |
| 408 | ]); |
| 409 | // global menu |
| 410 | } else { |
| 411 | add_menu_page($this->getPageTitle(), $this->getMenuTitle(), $this->capabilitiy, $result_id, [ |
| 412 | $this, |
| 413 | 'show' |
| 414 | ], null, $this->menu_position); |
| 415 | |
| 416 | if( !empty($this->menu_sub_title) ) { |
| 417 | |
| 418 | add_submenu_page($result_id, $this->menu_sub_title, $this->menu_sub_title, $this->capabilitiy, $result_id, [ |
| 419 | $this, |
| 420 | 'show' |
| 421 | ]); |
| 422 | } |
| 423 | |
| 424 | add_action('admin_head', [$this, 'actionAdminHead']); |
| 425 | } |
| 426 | |
| 427 | // executes an action |
| 428 | if( $this->current() ) { |
| 429 | ob_start(); |
| 430 | $action = $this->request->get('action', 'index', true); |
| 431 | $this->executeByName($action); |
| 432 | $this->result = ob_get_contents(); |
| 433 | ob_end_clean(); |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | protected function current() |
| 438 | { |
| 439 | $result_id = $this->getResultId(); |
| 440 | |
| 441 | if( $result_id == $this->request->get('page', 'none') ) { |
| 442 | return true; |
| 443 | } |
| 444 | |
| 445 | return false; |
| 446 | } |
| 447 | |
| 448 | /** |
| 449 | * @param string $action |
| 450 | * @param array $query_args |
| 451 | */ |
| 452 | public function redirectToAction($action, $query_args = []) |
| 453 | { |
| 454 | |
| 455 | wp_safe_redirect($this->getActionUrl($action, $query_args)); |
| 456 | exit; |
| 457 | } |
| 458 | |
| 459 | /** |
| 460 | * @param string $action |
| 461 | * @param array $query_args |
| 462 | */ |
| 463 | public function actionUrl($action = null, $query_args = []) |
| 464 | { |
| 465 | echo $this->getActionUrl($action, $query_args); |
| 466 | } |
| 467 | |
| 468 | /** |
| 469 | * @param null $action |
| 470 | * @param array $query_args |
| 471 | * |
| 472 | * @return string |
| 473 | */ |
| 474 | public function getActionUrl($action = null, $query_args = []) |
| 475 | { |
| 476 | $url = $this->getBaseUrl(null, $query_args); |
| 477 | |
| 478 | if( !empty($action) ) { |
| 479 | $url = add_query_arg('action', $action, $url); |
| 480 | } |
| 481 | |
| 482 | return $url; |
| 483 | } |
| 484 | |
| 485 | /** |
| 486 | * @return string |
| 487 | */ |
| 488 | public function getBaseUrl($id = null, $query_args = []) |
| 489 | { |
| 490 | $result_id = $this->getResultId($id); |
| 491 | |
| 492 | if( $this->menu_target && !$this->custom_target ) { |
| 493 | $url = $this->network ? network_admin_url($this->menu_target) : admin_url($this->menu_target); |
| 494 | |
| 495 | return add_query_arg(array_merge(['page' => $result_id], $query_args), $url); |
| 496 | } |
| 497 | |
| 498 | $url = $this->network ? network_admin_url('admin.php') : admin_url('admin.php'); |
| 499 | |
| 500 | return add_query_arg(array_merge(['page' => $result_id, $query_args]), $url); |
| 501 | } |
| 502 | |
| 503 | public function actionAdminHead() |
| 504 | { |
| 505 | $result_id = $this->getResultId(); |
| 506 | |
| 507 | if( !empty($this->menu_icon) ) { |
| 508 | |
| 509 | if( preg_match('/\\\f\d{3}/', $this->menu_icon) ) { |
| 510 | $icon_code = $this->menu_icon; |
| 511 | } else { |
| 512 | $icon_url = str_replace('~/', $this->plugin->get_paths()->url . '/', $this->menu_icon); |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | global $wp_version; |
| 517 | |
| 518 | if( version_compare($wp_version, '3.7.3', '>') ) { |
| 519 | ?> |
| 520 | <style type="text/css" media="screen"> |
| 521 | <?php if ( !empty($icon_url) ) { ?> |
| 522 | |
| 523 | a.toplevel_page_<?php echo $result_id ?> .wp-menu-image { |
| 524 | background: url('<?php echo $icon_url ?>') no-repeat 10px -30px !important; |
| 525 | } |
| 526 | |
| 527 | <?php } ?> |
| 528 | |
| 529 | a.toplevel_page_<?php echo $result_id ?> .wp-menu-image:before { |
| 530 | content: "<?php echo !empty($icon_code) ? $icon_code : ''; ?>" !important; |
| 531 | } |
| 532 | |
| 533 | a.toplevel_page_<?php echo $result_id ?>:hover .wp-menu-image, |
| 534 | a.toplevel_page_<?php echo $result_id ?>.wp-has-current-submenu .wp-menu-image, |
| 535 | a.toplevel_page_<?php echo $result_id ?>.current .wp-menu-image { |
| 536 | background-position: 10px 2px !important; |
| 537 | } |
| 538 | </style> |
| 539 | <?php } else { ?> |
| 540 | <style type="text/css" media="screen"> |
| 541 | a.toplevel_page_<?php echo $result_id ?> .wp-menu-image { |
| 542 | background: url('<?php echo $icon_url ?>') no-repeat 6px -33px !important; |
| 543 | } |
| 544 | |
| 545 | a.toplevel_page_<?php echo $result_id ?>:hover .wp-menu-image, |
| 546 | a.toplevel_page_<?php echo $result_id ?>.current .wp-menu-image { |
| 547 | background-position: 6px -1px !important; |
| 548 | } |
| 549 | </style> |
| 550 | <?php |
| 551 | } |
| 552 | |
| 553 | if( $this->internal ) { |
| 554 | ?> |
| 555 | <style type="text/css" media="screen"> |
| 556 | li.toplevel_page_<?php echo $result_id ?> { |
| 557 | display: none; |
| 558 | } |
| 559 | </style> |
| 560 | <?php |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | |
| 565 | /** |
| 566 | * Add settings link in plugins list |
| 567 | * |
| 568 | * @param $links |
| 569 | * |
| 570 | * @return mixed |
| 571 | */ |
| 572 | function addLinkToPluginActions($links) |
| 573 | { |
| 574 | $link_title = !empty($this->title_plugin_action_link) ? $this->title_plugin_action_link : $this->getMenuTitle(); |
| 575 | |
| 576 | $settings_link = '<a href="' . $this->getBaseUrl() . '">' . $link_title . '</a>'; |
| 577 | array_unshift($links, $settings_link); |
| 578 | |
| 579 | return $links; |
| 580 | } |
| 581 | } |
| 582 | } |