diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7605abbbc..13531c4f9 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1351,1002 +1351,144 @@ lb_copy_files: ### Фаза 0: Подготовка ✅ -1. ✅ Автозагрузчик `src/autoload.php` — карта классов + fallback spl_autoload -2. ✅ Скелет директорий (98 каталогов) -3. ✅ `bootstrap.php` — XC_Bootstrap с 4 контекстами -4. ✅ `core/Container/ServiceContainer.php` — DI-контейнер -5. ✅ Разбиение `www/constants.php` → 7 core-файлов + тонкий фасад (74 строки) - - ✅ `core/Config/Paths.php`, `AppConfig.php`, `Binaries.php`, `ConfigLoader.php` - - ✅ `core/Error/ErrorCodes.php`, `ErrorHandler.php` - - ✅ `core/Http/RequestGuard.php` - - ✅ `www/stream/init.php` → подключён autoload.php +Autoload, скелет директорий, bootstrap.php, ServiceContainer, разбиение constants.php → 7 core-файлов. --- -### Фаза 1: Извлечение core/ (базовые компоненты) +### Фаза 1: Извлечение core/ ✅ -#### 1.1 ✅ Database -- ✅ `core/Database/DatabaseHandler.php` (530 стр.) ← `includes/Database.php` -- ✅ `core/Database/Database.php` (299 стр.) — перемещён из `includes/` -- ✅ Все 20 файлов переключены на DatabaseHandler +Database, Cache, Http/Request, Auth, Process, Util — все базовые компоненты извлечены из god-объектов. -#### 1.2 ✅ Cache -- ✅ `core/Cache/CacheInterface.php` (84 стр.) -- ✅ `core/Cache/FileCache.php` (229 стр.) ← `CoreUtilities::getCache/setCache` -- ✅ `core/Cache/RedisCache.php` (262 стр.) +### Фаза 1.7: Оставшиеся извлечения core/ ✅ -#### 1.3 ✅ Http / Request -- ✅ `core/Http/Request.php` (449 стр.) ← `cleanGlobals()` + `parseIncomingRecursively()` -- ✅ `core/Http/Response.php` (139 стр.) - -#### 1.4 ✅ Auth -- ✅ `core/Auth/SessionManager.php` (305 стр.) ← из двух `session.php` - -#### 1.5 ✅ Process -- ✅ `core/Process/ProcessManager.php` (366 стр.) ← shell_exec/posix_kill - -#### 1.6 ✅ Util -- ✅ `core/Util/GeoIP.php` (159 стр.) ← `CoreUtilities` -- ✅ `core/Util/Encryption.php` (137 стр.) ← `CoreUtilities` -- ✅ `core/Util/TimeUtils.php` (114 стр.) ← `CoreUtilities` + `admin.php::secondsToTime()` -- ✅ `core/Util/NetworkUtils.php` (129 стр.) ← IP/CIDR/subnet из `CoreUtilities` - ---- - -### Фаза 1.7: Оставшиеся извлечения core/ - -**Из `CoreUtilities.php` (4847 строк) → новые классы:** - -#### Шаг 1.7.1 — Логирование ✅ -- ✅ Извлечь `saveLog()` (стр. 489–504) → `FileLogger::log()` -- ✅ Извлечь `clientLog()` (StUtil стр. 1169–1177) → `DatabaseLogger::log()` -- ✅ Написать `LoggerInterface` с методом `log($type, $message, $extra)` -- ✅ Proxy: `CoreUtilities::saveLog()` → `FileLogger::log()` -- ✅ Proxy: `StreamingUtilities::clientLog()` → `DatabaseLogger::log()` - -#### Шаг 1.7.2 — Системная информация ✅ -- ✅ Извлечь 9 методов (стр. 534–671, 827–852, 1338–1344, 4621–4665) → `SystemInfo` -- ✅ Proxy: каждый вызов `CoreUtilities::getStats()` → `SystemInfo::getStats()` - -#### Шаг 1.7.3 — Защита от брутфорса (Flood/Bruteforce) ✅ -- ✅ Извлечь 4 метода из CoreUtilities (стр. 709–826) → `BruteforceGuard` -- ✅ 4 дублированных метода в StreamingUtilities (стр. 215–394) → proxy на тот же `BruteforceGuard` -- ✅ Первая дедупликация CoreUtilities ↔ StreamingUtilities - -#### Шаг 1.7.4 — HTTP-клиент (cURL) ✅ -- ✅ Извлечь 3 метода (стр. 373–428, 1408–1442, 3568–3578) → `CurlClient` - -#### Шаг 1.7.5 — Событийная система ✅ -- ✅ Написать простой EventDispatcher (publish/subscribe) -- ✅ Пока без подписчиков — подготовка к модульной системе - -#### Шаг 1.7.6 — RBAC / Авторизация ✅ -- ✅ Извлечь `hasPermissions()` (стр. 582–619) и `hasResellerPermissions()` (стр. 575–581) -- ✅ Массив `$rAdvPermissions` → `resources/data/admin_constants.php` -- ✅ Proxy: глобальные функции в `admin.php` → `Authorization::check()` - -#### Шаг 1.7.7 — Аутентификация ✅ -- ✅ Извлечь `processLogin()` из `admin_api.php` (стр. 1399–1478) → `Authenticator::login()` -- ✅ Извлечь `processLogin()` из `reseller_api.php` → `Authenticator::resellerLogin()` -- ✅ Proxy: `API::processLogin()` → `Authenticator::login()` - -#### Шаг 1.7.8 — Утилиты изображений ✅ -- ✅ Извлечь методы работы с изображениями (resize, thumbnail, URL-валидация) -- ✅ `StreamingUtilities::validateImage()` (стр. 1355) → `ImageUtils::validateURL()` -- ✅ `admin.php::getAdminImage()` (стр. 871–883) → `ImageUtils::resize()` +Логирование, SystemInfo, BruteforceGuard, CurlClient, EventDispatcher, Authorization, Authenticator, ImageUtils — 8 шагов завершены. --- ### Фаза 2: Дедупликация CoreUtilities ↔ StreamingUtilities ✅ -Форк устранён. 53 дублированных метода дедуплицированы. - -#### Шаг 2.1 — Инвентаризация дубликатов ✅ - -Инвентаризация выполнена: **53 общих метода** между CoreUtilities и StreamingUtilities. -Все методы распределены по шагам 2.2–2.5 и успешно дедуплицированы. - -#### Шаг 2.2 — Redis и сигналы ✅ -- ✅ Извлечь Redis-подключение в `RedisManager` (единый для обоих) -- ✅ Proxy: оба класса вызывают `RedisManager::connect()` -- ✅ `getDomainName()` → `DomainResolver::resolve()` (чистая утилита конфигурации) - -#### Шаг 2.3 — Трекинг подключений (Redis) ✅ -- ✅ ~17 методов вынесены в `ConnectionTracker` (работа с Redis-ключами подключений) -- ✅ Proxy: оба god-объекта делегируют в `ConnectionTracker` - -#### Шаг 2.4 — Справочные данные и сортировки ✅ -- ✅ Сортировки и форматирование вынесены в `StreamSorter` -- ✅ Данные-справочники вынесены в `BouquetMapper` / `CategoryRepository` / `BouquetRepository` / `ServerRepository` / `SettingsRepository` - -#### Шаг 2.5 — Дедупликация init() ✅ -- ✅ Оба `init()` стали тонкими обёртками -- ✅ Общая логика вынесена в `core/Init/LegacyInitializer.php` -- ✅ Состояние init синхронизируется через `ServiceContainer` +53 дублированных метода дедуплицированы: Redis/сигналы, трекинг подключений, справочные данные, init(). --- ### Фаза 3: Извлечение domain/ — бизнес-логика ✅ -Все entity/repository/service извлечены из god-объектов. Proxy-методы оставлены в исходных файлах. - -#### Шаг 3.1 — domain/Stream/ ✅ -- `StreamService.php` — processStream, massEdit, massDelete, move, replaceDNS ← admin_api.php -- `ChannelService.php` — processChannel, massEdit, setOrder ← admin_api.php -- `CategoryService.php` — processCategory, orderCategories ← admin_api.php -- `StreamRepository.php` — getStream, getStreamStats, getStreamErrors, getStreamPIDs, getStreamOptions, getStreamSys, getNextOrder ← admin.php -- `CategoryRepository.php` — getCategories ← admin.php -- `M3UParser.php` — parseM3U ← admin.php -- `StreamProcess.php` — startMonitor, stopStream, startProxy, startThumbnail, queueChannel, createChannel, updateStream(s), createChannelItem, startMovie, stopMovie, startLoopback, queueMovie(s), refreshMovies, startStream, startLLOD ← CoreUtilities - -#### Шаг 3.2 — domain/Vod/ ✅ -- `MovieService.php` — process, massEdit, massDelete, import ← admin_api.php -- `SeriesService.php` — process, massEdit, massDelete, import ← admin_api.php -- `EpisodeService.php` — process, massEdit, massDelete ← admin_api.php -- `SeriesRepository.php` — getList, updateFromTMDB, queueRefresh, getSimilar, generatePlaylist ← admin.php -- `MovieRepository.php` — getSimilar, deleteFile ← admin.php - -#### Шаг 3.3 — domain/Line/ ✅ -- `LineService.php` — process, massEdit, massDelete, delete, update (одиночные и массовые) ← admin_api.php + CoreUtilities -- `LineRepository.php` — deleteMany ← admin.php - -#### Шаг 3.4 — domain/User/ ✅ -- `UserService.php` — process, massEdit, massDelete ← admin_api.php -- `GroupService.php` — process ← admin_api.php -- `ProfileService.php` — editAdminProfile ← admin_api.php -- `UserRepository.php` — getUserInfo, getUser, getRegisteredUser(s), getResellers, getDirectReports, getSubUsers, getParent, getStreamingUserInfo ← admin.php + StreamingUtilities -- `GroupRepository.php` — getAll, getById, deleteById ← admin.php - -#### Шаг 3.5 — domain/Device/ ✅ -- `MagService.php` — process, massEdit, massDelete ← admin_api.php -- `EnigmaService.php` — process, massEdit, massDelete ← admin_api.php -- `DeviceSync.php` — syncLineDevices ← admin.php - -#### Шаг 3.6 — domain/Server/ ✅ -- `ServerService.php` — process, processProxy, install, reorder ← admin_api.php -- `ServerRepository.php` — getAllSimple, getStreamingSimple, getProxySimple, getFreeSpace, getStreamsRamdisk, killPID, getRTMPStats, deleteById, probeSource, getSSLLog, checkSource, freeTemp, freeStreams ← admin.php - -#### Шаг 3.7 — domain/Bouquet/ ✅ -- `BouquetService.php` — process, reorder, sort, scan, scanOne ← admin_api.php + admin.php -- `BouquetRepository.php` — getAllSimple, getOrder, getUserBouquets ← admin.php - -#### Шаг 3.8 — domain/Epg/ ✅ -- `EpgService.php` — process, getChannelEpg ← admin_api.php + admin.php -- `EpgRepository.php` — getById, findByName, getStreamEpg, getStreamsEpg, getProgramme, search ← admin.php + CoreUtilities - -#### Шаг 3.9 — domain/Settings/ + domain/Ticket/ ✅ -- `SettingsService.php` — edit, editBackup, editCacheCron ← admin_api.php -- `TicketService.php` — submit ← admin_api.php - -#### Шаг 3.10 — domain/Security/ ✅ -- `BlocklistService.php` — processISP, processUA, blockIP, processRTMPIP, checkBlockedUAs, checkISP, checkServer ← admin_api.php + StreamingUtilities -- `BlocklistRepository.php` — getBlockedIPsSimple, getRTMPIPsSimple, getBlockedUA, getBlockedIPs, getBlockedISP, getBlockedServers, getProxyIPs ← admin.php + CoreUtilities - -#### Шаг 3.11 — domain/Auth/ ✅ -- `CodeService.php` — process ← admin_api.php -- `HMACService.php` — process ← admin_api.php -- `PackageService.php` — process ← admin_api.php (в domain/Line/) -- `CodeRepository.php` — getActiveCodes, updateCodes, getCurrentCode ← admin.php -- `HMACRepository.php` — getAll, getById ← admin.php -- `PackageRepository.php` — deleteById ← admin.php (в domain/Line/) -- `HMACValidator.php` — validate ← StreamingUtilities - -#### Шаг 3.12 — Playlist-генератор ✅ -- `PlaylistGenerator.php` — generate ← CoreUtilities (самый длинный метод, live/vod/series/radio) -- `CronGenerator.php` — generate ← CoreUtilities +12 доменных контекстов: Stream, Vod, Line, User, Device, Server, Bouquet, Epg, Settings/Ticket, Security, Auth, Playlist. Все entity/repository/service извлечены. --- ### Фаза 4: Извлечение streaming/ (hot path) ✅ -#### Шаг 4.1 — streaming/Auth/ ✅ -- `StreamAuth.php` — checkAccess, validateConnections ← auth.php + StreamingUtilities -- `TokenAuth.php` — парсинг токенов -- `DeviceLock.php` — привязка к устройству -- `ConnectionLimiter.php` — closeConnections, closeRTMP → Protection/ - -#### Шаг 4.2 — streaming/Delivery/ ✅ -- `LiveDelivery.php` ← www/stream/live.php -- `StreamRedirector.php` — redirectStream, showVideoServer -- `OffAirHandler.php` — getOffAirVideo -- `HLSGenerator.php` — generateHLS -- `SegmentReader.php` — getLLODSegments -- `SignalSender.php` — sendSignal -- `ProxySelector.php` → Balancer/ - -#### Шаг 4.3 — streaming/Codec/ ✅ -- `FFprobeRunner.php` — probeStream, parseFFProbe -- `FFmpegCommand.php` — сборка FFmpeg-команд -- `SubtitleExtractor.php` — extractSubtitle - -#### Шаг 4.4 — streaming/Protection/ + Health/ ✅ -- `ConnectionLimiter.php` — closeConnections -- `HealthChecker.php` — isRunning -- `ProcessChecker.php` — isPIDRunning, isPIDsRunning, checkPID -- `WatchdogMonitor.php` — getWatchdog - -#### Шаг 4.5 — streaming/StreamingBootstrap.php ✅ -- Лёгкий bootstrap заменяет `www/stream/init.php` -- Загружает: autoload → constants → Database → Redis +streaming/Auth, Delivery, Codec, Protection/Health, StreamingBootstrap — лёгкий bootstrap для hot path. --- -### Фаза 5: Вынесение модулей +### Фаза 5: Вынесение модулей ✅ -Каждый модуль извлекается атомарно — система продолжает работать без него. +6 модулей извлечены атомарно: plex, watch, tmdb, ministra, fingerprint/theft-detection/magscan. ModuleInterface + ModuleLoader. Thread/Multithread дедуплицированы в `core/Process/`. -#### Шаг 5.1 — modules/plex/ ⚡ (в процессе) - -**Завершено:** -- ✅ `PlexAuth.php` — аутентификация (getPlexToken, checkPlexToken, cachePlexToken и др.) -- ✅ `PlexRepository.php` — данные (getPlexServers, getPlexSections) -- ✅ `PlexService.php` — бизнес-логика (editPlexSettings, processPlexSync, forcePlex) -- ✅ `PlexCron.php` — крон синхронизации (Thread, Multithread, PlexCron::run()) -- ✅ `PlexItem.php` — CLI обработка элементов (PlexItem::run()) -- ✅ `crons/plex.php` — тонкая обёртка → PlexCron::run() -- ✅ `includes/cli/plex_item.php` — тонкая обёртка → PlexItem::run() -- ✅ Все 5 классов зарегистрированы в autoload.php -- ✅ `admin/settings_plex.php` → modules/plex/views/ (контроллер + вынесенный view/scripts) -- ✅ `admin/plex_add.php` → modules/plex/views/ (контроллер + общие view/scripts) -- ✅ `admin/plex.php` → modules/plex/views/ (контроллер + список вынесен в view) -- ✅ `config/plex/` → modules/plex/config/ - -**Осталось:** — - -#### Шаг 5.2 — modules/watch/ -- ✅ `API::editWatchSettings()` → modules/watch/WatchService.php -- ✅ `API::processWatchFolder()` → modules/watch/WatchService.php -- ✅ `API::scheduleRecording()` → modules/watch/RecordingService.php -- ✅ `admin.php::getWatchFolders()` → modules/watch/WatchController.php -- ✅ `admin.php::getWatchCategories()` → modules/watch/WatchController.php -- ✅ `admin.php::forceWatch()` → modules/watch/WatchController.php -- ✅ `admin.php::getRecordings()` → modules/watch/WatchController.php -- ✅ `admin.php::deleteRecording()` → modules/watch/WatchController.php -- ✅ `admin/settings_watch.php` → modules/watch/views/ (thin wrapper + view/scripts) -- ✅ `admin/watch.php` → modules/watch/views/ (thin wrapper + view/scripts) -- ✅ `admin/watch_add.php` → modules/watch/views/ (thin wrapper + view/scripts) -- ✅ `admin/watch_output.php` → modules/watch/views/ (thin wrapper + view/scripts) -- ✅ `admin/record.php` → modules/watch/views/ (thin wrapper + view/scripts) -- ✅ `crons/watch.php` → modules/watch/WatchCron.php (entry point + extracted class) -- ✅ `includes/cli/watch_item.php` → modules/watch/WatchItem.php (entry point + extracted class) -- ✅ `WatchModule::registerCrons()` wired to WatchCron - -**Осталось:** — - -#### Шаг 5.3 — modules/tmdb/ -- ✅ `admin/api.php::tmdb_search` → modules/tmdb/TmdbService.php (search) -- ✅ `admin/api.php::tmdb` → modules/tmdb/TmdbService.php (getDetails) -- ✅ `crons/tmdb.php` → modules/tmdb/TmdbCron.php (entry point + extracted class) -- ✅ `crons/tmdb_popular.php` → modules/tmdb/TmdbPopularCron.php (entry point + extracted class) -- ✅ `TmdbModule.php` — registerCrons() wired (TmdbCron + TmdbPopularCron) -- ✅ `includes/libs/TMDb/` → modules/tmdb/lib.php (proxy loader, lib stays in place) - -**Осталось:** — - -#### Шаг 5.4 — modules/ministra/ -- ✅ `ministra/portal.php` (2156 строк) → PortalHandler.php (15 статических обработчиков, ~1345 строк) -- ✅ `ministra/portal.php` helper functions → PortalHelpers.php (19 статических методов, ~860 строк) -- ✅ `MinistraModule.php` — точка входа модуля (standalone endpoint, без cron/routes) -- ✅ `ministra/portal.php` → тонкая обёртка: init/auth → PortalHandler (269 строк + хелперы + комментированный оригинал) - 🔲 `ministra/*.js` → modules/ministra/assets/ (JS-файлы портала — отложено) -**Осталось:** JS-ассеты (отложено до Фазы 6) - -#### Шаг 5.5 — modules/fingerprint/ + modules/theft-detection/ + modules/magscan/ -- ✅ `FingerprintModule.php` — модуль Fingerprint Stream (выбор потока + наложение текста + таблица активности) -- ✅ `TheftDetectionModule.php` — модуль обнаружения кражи VOD (таблица просмотров, данные из cache_engine) -- ✅ `MagscanModule.php` — модуль настроек MAGSCAN (белые/чёрные списки MAC + IP) -- ✅ `module.json` × 3 — метаданные модулей -- ✅ `config/modules.php` — все 3 модуля раскомментированы и включены - -**Источники:** -``` -admin/fingerprint.php (330 стр.) — UI-страница, API: fingerprint + line_activity -admin/theft_detection.php (239 стр.) — UI-страница, данные: CACHE_TMP_PATH/theft_detection -admin/magscan_settings.php (301 стр.) — UI-страница, POST: submit_magscan -``` - -#### Шаг 5.6 — ModuleInterface + загрузчик модулей -- ✅ `core/Module/ModuleInterface.php` — контракт модуля (111 строк): getName, getVersion, boot, registerRoutes, registerCrons, getEventSubscribers -- ✅ `core/Module/ModuleLoader.php` — загрузчик модулей (243 строки): loadAll, load, checkDependencies, isLoaded, getModule -- ✅ `config/modules.php` — конфигурация модулей: plex, watch, fingerprint, theft-detection, magscan (enabled), tmdb, ministra (commented) - --- -#### Аудит Фазы 5 ✅ -Проведена полная проверка всех файлов Фазы 5. Найдено и исправлено: -- **КРИТИЧЕСКОЕ**: `Thread`/`Multithread` дублировались в 3 файлах (PlexCron, WatchCron, cache_engine) → вынесены в `core/Process/Thread.php` + `core/Process/Multithread.php`, все 3 файла переведены на `require_once` -- **autoload.php**: добавлены 14 отсутствующих записей (WatchCron, WatchItem, Tmdb*, Ministra*, Fingerprint*, TheftDetection*, Magscan*, Thread, Multithread) -- **module.json**: созданы для `tmdb` и `ministra` (отсутствовали) -- **config/modules.php**: `tmdb` и `ministra` раскомментированы и включены (были `enabled => false`) +### Фаза 6: Контроллеры и Views (admin/reseller) ✅ ---- +#### Шаг 6.1 — Единый layout ✅ -### Фаза 6: Контроллеры и Views (admin/reseller) ⚡ (в процессе) - -Выполняется ПОСЛЕ извлечения domain/ — контроллеры вызывают сервисы. - -#### Шаг 6.1 — Единый layout -``` -admin/header.php (675 стр.) + reseller/header.php (284 стр.) - → public/Views/layouts/admin.php - -admin/footer.php (804 стр.) + reseller/footer.php (719 стр.) - → public/Views/layouts/footer.php - + assets/admin/js/*.js (вынесенный inline JS) -``` - -**Сделано (старт шага 6.1):** -- ✅ Создан `public/Views/layouts/admin.php` — unified header wrapper (`renderUnifiedLayoutHeader`) -- ✅ Создан `public/Views/layouts/footer.php` — unified footer wrapper (`renderUnifiedLayoutFooter`) -- ✅ Удалён `public/Views/layouts/.gitkeep` -- ✅ Переведены на unified wrappers (пилот): - - `admin/fingerprint.php` - - `admin/magscan_settings.php` - - `admin/theft_detection.php` -- ✅ Переведены на unified wrappers (группа F — настройки): - - `admin/settings.php` - - `admin/profile.php` - - `admin/edit_profile.php` -- ✅ Переведены на unified wrappers (группа E — букеты): - - `admin/bouquets.php` - - `admin/bouquet.php` - - `admin/bouquet_order.php` - - `admin/bouquet_sort.php` -- ✅ Переведены на unified wrappers (группа D — серверы): - - `admin/servers.php` - - `admin/server.php` - - `admin/server_view.php` - - `admin/server_install.php` -- ✅ Переведены на unified wrappers (группа C — линии/устройства): - - `admin/lines.php` - - `admin/line.php` - - `admin/mags.php` - - `admin/mag.php` - - `admin/enigmas.php` - - `admin/enigma.php` -- ✅ Переведены на unified wrappers (группа B — VOD): - - `admin/movies.php` - - `admin/movie.php` - - `admin/series.php` - - `admin/serie.php` - - `admin/episodes.php` - - `admin/episode.php` -- ✅ Переведены на unified wrappers (группа A — потоки): - - `admin/streams.php` - - `admin/stream.php` - - `admin/stream_view.php` - - `admin/created_channel.php` - - `admin/created_channels.php` -- ✅ Переведены на unified wrappers (группа G — остальное, пакет 1): - - `admin/archive.php` - - `admin/dashboard.php` - - `admin/epg.php` - - `admin/epgs.php` - - `admin/group.php` - - `admin/groups.php` -- ✅ Переведены на unified wrappers (группа G — остальное, пакет 2): - - `admin/providers.php` - - `admin/provider.php` - - `admin/packages.php` - - `admin/package.php` - - `admin/profiles.php` - - `admin/proxies.php` - -**Дальше в 6.1:** -- 🔄 Перенос общих CSS/JS-блоков из `admin|reseller` в единые partials -- 🔄 Подключение `partials/header.php` + `partials/footer.php` к layout system (сейчас не используются) -- ✅ ~~Постраничное переключение include `header.php/footer.php` → unified layout wrappers~~ — завершено - -**Reseller миграция на unified wrappers:** -- ✅ Переведены (ранее): `dashboard.php`, `streams.php`, `live_connections.php`, `user.php`, `users.php`, `user_logs.php` -- ✅ Переведены (batch 2): `movies.php`, `enigma.php` (footer fix), `epg_view.php`, `enigmas.php`, `tickets.php`, `ticket_view.php`, `ticket.php`, `radios.php`, `mags.php`, `mag.php`, `line_activity.php`, `lines.php`, `line.php`, `episodes.php`, `created_channels.php`, `edit_profile.php` -- ℹ️ Не требуют миграции (utility/support): `header.php`, `footer.php`, `functions.php`, `session.php`, `api.php`, `table.php`, `post.php`, `topbar.php`, `modals.php`, `resize.php`, `index.php`, `logout.php` -- ℹ️ Отдельная страница (свой HTML): `login.php` +Unified wrappers: `public/Views/layouts/admin.php` + `footer.php`. - **Admin: 112/112 page-файлов — 100% мигрированы** - **Reseller: 22/22 page-файлов — 100% мигрированы** +- ⏭️ CSS/JS partials — **отложено** (footer.php: ~800 стр. page-specific inline JS) -#### Шаг 6.2 — Router + Front Controller -``` -Новый → core/Http/Router.php -Новый → public/index.php (front controller) -Новый → public/routes/admin.php (admin route definitions) -Новый → public/routes/api.php (API route definitions) -``` +#### Шаг 6.2 — Router + Front Controller ✅ -**Статус 6.2:** ✅ Завершён -- ✅ `core/Http/Router.php` — полная реализация (450 стр.): GET/POST/API routes, group(), middleware, permissions, dispatch(), dispatchApi(), singleton - - **Fix: normalizePage()** — `buildRoute()` теперь вызывает `normalizePage()` на результате, чтобы ключи регистрации совпадали с ключами dispatch (rtmp_ips → rtmp/ips) - - **Fix: ServiceContainer DI** — `callHandler()` теперь использует `ServiceContainer::getInstance()->get($class)` с fallback на `new $class()` при ошибке -- ✅ `core/Http/Request.php` — HTTP request wrapper (450 стр.): capture(), input access, sanitization, backward compat -- ✅ `core/Http/Response.php` — HTTP response helper: json(), redirect(), notFound(), cors(), noCache() -- ✅ `core/Http/RequestGuard.php` — flood protection, host verification, Logger init -- ✅ `public/index.php` — Front Controller: - - Трёхрежимный парсинг URL → scope + pageName + accessCode: - - **Режим A** (Access Code + XC_SCOPE): nginx передаёт scope через `fastcgi_param XC_SCOPE` - - **Режим B** (Direct URL): URL содержит `/admin/...` или `/reseller/...` - - **Режим C** (Access Code без XC_SCOPE): fallback через `PHP_SELF` (как `CodeRepository::getCurrentCode`) - - Маппинг `#TYPE#` → scope: admin, reseller, ministra, includes/api/admin → admin, и т.д. - - Bootstrap через legacy chain (session.php → functions.php) - - Загрузка маршрутов из routes/{scope}.php + routes/api.php - - Dispatch через Router → fallback в legacy include - - Поддержка API action dispatch (/admin/api?action=xxx) -- ✅ `public/routes/admin.php` — шаблон маршрутов admin (заглушки для Step 6.3) -- ✅ `public/routes/api.php` — шаблон API маршрутов (заглушки для Step 6.3) +`core/Http/Router.php` (450 стр.), `public/index.php` (Front Controller), `Request.php`, `Response.php`, `RequestGuard.php`. Трёхрежимный URL-парсинг (Access Code + XC_SCOPE / Direct URL / fallback). Access Codes поддержаны. -**Access Codes (`bin/nginx/conf/codes/`):** +#### Шаг 6.3 — Конвертация admin-страниц (Controller/View) ✅ -Панель доступна не по `/admin/`, а по `/RANDOMCODE/`. Коды генерируются из шаблона: -- Шаблон: `bin/nginx/conf/codes/template` -- Генератор: `domain/Auth/CodeRepository.php` → `updateCodes()` -- URL: `http://host/MYCODE/dashboard` → nginx alias → `/home/xc_vm/admin/dashboard.php` -- Типы кодов (field `type` в таблице): - -| type | #TYPE# (alias path) | scope (Router) | -|------|--------------------------|----------------| -| 0 | admin | admin | -| 1 | reseller | reseller | -| 2 | ministra | ministra | -| 3 | includes/api/admin | admin | -| 4 | includes/api/reseller | reseller | -| 5 | ministra/new | ministra | -| 6 | player | player | - -**Активация — два варианта:** - -1) **Прямой доступ** (dev/test, без access codes): -```nginx -location ~ ^/(admin|reseller)(/.*)?$ { - try_files $uri /public/index.php?$args; -} -``` - -2) **Access codes** (production) — обновлённый шаблон `bin/nginx/conf/codes/template`: -```nginx -location ^~ /#CODE# { - alias /home/xc_vm/#TYPE#; - index index.php; - # Статика и legacy PHP отдаются напрямую - try_files $uri $uri.html $uri/ @fc_#CODE#; - - location ~ \.php$ { - fastcgi_split_path_info ^(.+\.php)(/.+)$; - fastcgi_pass php; - include fastcgi_params; - fastcgi_param SCRIPT_FILENAME $request_filename; - } -} - -# Front Controller fallback для access code #CODE# -location @fc_#CODE# { - fastcgi_param XC_SCOPE #TYPE#; - fastcgi_param XC_CODE #CODE#; - fastcgi_param SCRIPT_FILENAME /home/xc_vm/public/index.php; - fastcgi_pass php; - include fastcgi_params; -} -``` - -Пока nginx шаблон не обновлён — legacy URL через access codes (`/MYCODE/dashboard` → `admin/dashboard.php`) работают как раньше. Front Controller активируется только после обновления template. - -#### Шаг 6.3 — Конвертация admin-страниц (Controller/View) - -**Паттерн: Thin Controller + View файл** - -Каждая legacy admin-страница разделяется на: -- **Controller** (`public/Controllers/Admin/XxxController.php`) — подготовка данных, редиректы, проверка прав -- **View** (`public/Views/admin/xxx.php`) — только HTML-контент (между header и footer) -- **Scripts** (`public/Views/admin/xxx.scripts.php`) — page-specific JS (DataTables, api(), etc.) - -**✅ `public/Controllers/Admin/BaseAdminController.php` — render(), redirect(), json(), setTitle(), requirePermission(), requireAdvPermission(), input(), getStatus() -- ✅ `public/Views/admin/_scripts_init.php` — общий JS-бойлерплейт (ResizeObserver, Switchery, DataTable errMode, bindHref, inputFilter, js_navigate и т.д.) -- ✅ `public/Views/layout.php` — мёртвый код, помечен `@deprecated` (актуальный layout: `Views/layouts/admin.php` + `footer.php`) -- ✅ `public/Views/partials/header.php` + `footer.php` — мёртвый код, помечены `@deprecated` - -**Render flow:** `renderUnifiedLayoutHeader('admin')` → `view.php` → `renderUnifiedLayoutFooter('admin')` → `scripts.php` (включает `_scripts_init.php`) → `` - -**Инфраструктурные исправления перед Phase 6.3:** -- ✅ Router `buildRoute()` — нормализация ключей при регистрации (rtmp_ips → rtmp/ips) -- ✅ Router `callHandler()` — DI через ServiceContainer с fallback -- ✅ Autoloader — раскомментированы `domain/`, `streaming/`, `modules/`, добавлен `public/` -- ✅ Autoloader — `MAIN_HOME` fallback: `__DIR__ . '/'` вместо `/home/xc_vm/` -- ✅ Мёртвый Layout код (layout.php + partials/header.php + partials/footer.php) помечен `@deprecated` - -**Пилотная группа (простые листинги, no POST, inline DataTables):** -- ✅ `IpController.php` + `Views/admin/ips.php` + `ips.scripts.php` — Blocked IPs, flush action, getBlockedIPs() -- ✅ `IspController.php` + `Views/admin/isps.php` + `isps.scripts.php` — Blocked ISPs, getISPs() -- ✅ `HmacController.php` + `Views/admin/hmacs.php` + `hmacs.scripts.php` — HMAC Keys, getHMACTokens() -- ✅ `GroupController.php` + `Views/admin/groups.php` + `groups.scripts.php` — Member Groups, getMemberGroups(), adv:edit_group -- ✅ `CodeController.php` + `Views/admin/codes.php` + `codes.scripts.php` — Access Codes, getcodes(), type mapping -- ✅ `PackageController.php` + `Views/admin/packages.php` + `packages.scripts.php` — Packages (filtered !is_addon), getPackages() -- ✅ `RtmpIpController.php` + `Views/admin/rtmp_ips.php` + `rtmp_ips.scripts.php` — RTMP IPs, getRTMPIPs(), push/pull icons -- ✅ `ProfileController.php` + `Views/admin/profiles.php` + `profiles.scripts.php` — Transcode Profiles, getTranscodeProfiles(), JSON profile_options -- ✅ `ProviderController.php` + `Views/admin/providers.php` + `providers.scripts.php` — Stream Providers, getStreamProviders(), reload action, JSON data -- ✅ `TheftDetectionController.php` + `Views/admin/theft_detection.php` + `theft_detection.scripts.php` — VOD Theft Detection, igbinary cache, range filter, custom search -- ✅ Маршруты в `public/routes/admin.php` — 10 GET-маршрутов зарегистрированы - -**Статус 6.3:** ✅ Завершён — **111/111 admin-страниц мигрировано** - -| Артефакт | Кол-во | Статус | -|---|---|---| -| Контроллеры (`Controllers/Admin/`) | 111 + BaseAdminController | ✅ | -| View-прокси (`Views/admin/`) | 111 | ✅ | -| Маршруты (`routes/admin.php`) | 111 | ✅ | -| Legacy-обёртки (`$__viewMode`) | 111 (108 std + 1 settings variant + 2 module bypass) | ✅ | - -**Группы миграции (все завершены):** -- ✅ **Pilot** (10): ips, isps, hmacs, groups, codes, packages, rtmp_ips, profiles, providers, theft_detection -- ✅ **A** (19): streams, stream, stream_view, stream_mass, stream_categories, stream_category, stream_errors, stream_rank, stream_review, stream_tools, channel_order, created_channel, created_channels, created_channel_mass, live_connections, rtmp_monitor, radio, radios, radio_mass -- ✅ **B** (10): movies, movie, movie_mass, series, serie, series_mass, episodes, episode, episodes_mass, ondemand -- ✅ **C** (6): lines, line, line_mass, line_activity, line_ips, mass_delete -- ✅ **D** (4): server_order, server_install, server, server_view -- ✅ **E** (4): bouquets, bouquet, bouquet_order, bouquet_sort -- ✅ **F** (4): settings, settings_plex, settings_watch, quick_tools -- ✅ **G** (6): login_logs, mysql_syslog, mag_events, restream_logs, panel_logs, epgs -- ✅ **H** (9): dashboard, cache, queue, process_monitor, backups, client_logs, user_logs, useragent, useragents -- ✅ **I** (6): mags, mag, mag_mass, enigmas, enigma, enigma_mass -- ✅ **J** (6): epg, epg_view, code, hmac, ip, isp -- ✅ **K** (5): group, package, profile, provider, rtmp_ip -- ✅ **L** (5): users, user, user_mass, plex, plex_add -- ✅ **M** (8): tickets, ticket, ticket_view, serie, watch, watch_add, watch_output, magscan_settings -- ✅ **N** (9): credit_logs, edit_profile, fingerprint, proxies, proxy, record, review, archive, asns - -**16 non-page файлов** (миграция не требуется): header.php, footer.php, topbar.php, modals.php, functions.php, session.php, post.php, login.php, logout.php, setup.php, database.php, index.php, resize.php, player.php, api.php, table.php +**111/111 admin-страниц** мигрированы: Controller + View + Scripts + routes. Паттерн: Thin Controller → Service → View. `BaseAdminController` + `_scripts_init.php`. #### Шаг 6.4 — Объединение admin/reseller ✅ -**Статус:** Завершён — 22 reseller-страницы мигрированы. - -**Артефакты:** -- ✅ `BaseResellerController` — расширяет BaseAdminController, `$scope = 'reseller'`, переопределяет `requirePermission()` → `checkResellerPermissions()` -- ✅ 22 контроллера (`Reseller*Controller`) в `public/Controllers/Reseller/` -- ✅ 22 view proxy в `public/Views/reseller/` -- ✅ 22 legacy файла обёрнуты `$__viewMode` гардами -- ✅ `public/routes/reseller.php` — 22 маршрута - -**Reseller-страницы (22):** -Dashboard & Profile: dashboard, edit_profile -Lines: lines, line, line_activity, live_connections -Devices: mags, mag, enigmas, enigma -Content: streams, movies, radios, episodes, created_channels, epg_view -Tickets: tickets, ticket, ticket_view -Users: users, user, user_logs - -**Ключевые отличия от admin:** -- Контроллеры с префиксом `Reseller` (ResellerDashboardController и т.д.) для избежания конфликтов с admin-контроллерами в безнеймспейсном автозагрузчике -- `checkResellerPermissions()` вместо `checkPermissions()` -- `$_SESSION['reseller']` вместо `$_SESSION['hash']` - -``` -reseller/table.php (1836 стр.) → переиспользует admin-контроллеры с RBAC-фильтром -reseller/api.php (997 стр.) → ResellerApiController (ограниченный AdminApiController) -``` +22 reseller-страницы мигрированы. `BaseResellerController` + 22 контроллера/view/маршрута. #### Шаг 6.5 — Стабилизация Controller/View контракта ✅ -**Статус:** Завершён (первый стабилизационный проход после 6.3/6.4). +Два прохода стабилизации: viewGlobals расширен, nullable-guards для foreach/in_array/count. -**Сделано:** -- ✅ Расширен базовый контракт `BaseAdminController::$viewGlobals`: - - добавлены `rTMDBLanguages`, `rGeoCountries`, `rMAGs`, `rTimezones` - - ранее добавлен `allowedLangs` -- ✅ Исправлен рендер update-уведомления/changelog в `admin/settings.php`: - - защита `foreach` по `changelog` через `is_array` - - защита вложенного `changes` через безопасный fallback на `[]` -- ✅ Исправлен `modules/watch/views/watch_add.php`: - - защита `foreach` по `$rTMDBLanguages` при отсутствии/некорректном типе -- ✅ Второй стабилизационный проход (расширенный, 14 файлов): - - контроллеры `watch/plex/settings_*` теперь нормализуют массивы (`[]` fallback) - - в `watch/plex/profile` view добавлены безопасные `foreach` и `in_array/count` с `(array)`/`is_array` guard - - закрыты риски `foreach(null)` и `Undefined variable` для страниц `watch_output`, `watch_add`, `settings_watch`, `record`, `plex/index`, `plex/settings`, `plex/library_edit`, `admin/edit_profile` +#### Шаг 6.5b — Reseller view nullable audit ✅ -**Цель шага:** -- убрать class-runtime регрессий «Undefined variable / foreach() argument must be array|object» -- зафиксировать единый контракт данных для legacy view в controller-режиме - -**Дальше (следующий проход 6.5):** -- 🔄 точечный аудит `Reseller`-view (особенно echo-сгенерированные файлы) на `foreach/in_array` с nullable-данными -- 🔄 выборочно перенести оставшиеся high-risk случаи в контроллерный data-contract вместо локальных view-guard +Source-level fixes: `getPermissions()` → `[]` fallback, defensive defaults в `functions.php`/`table.php` для `direct_reports`, `all_reports`, `stream_ids`, `category_ids`, `series_ids`, `subresellers`. P0/P1 точечные исправления в 10 файлах. --- ### Фаза 7: Миграция admin.php bootstrap -`admin.php` (4448 стр.) — после извлечения всех функций в domain/. #### Шаг 7.1 — Вынос inline-данных ✅ -- ✅ Данные bootstrap (`rMAGs`, `rCountryCodes`, `rCountries`, `rAdvPermissions`) консолидированы в `resources/data/admin_constants.php` -- ✅ Отдельный `resources/data/permissions.php` удалён +Данные bootstrap консолидированы в `resources/data/admin_constants.php`. -#### Шаг 7.2 — Замена процедурного bootstrap 🔄 -``` -admin.php::initDatabase() → ServiceContainer::get('db') -admin.php::CoreUtilities::init() → bootstrap.php -admin.php::session_start() → SessionManager::start() -admin.php::$rPermissions → Authorization::getPermissions() -admin.php::Translator init → ServiceContainer::get('translator') -``` - -- ✅ Первый инкремент: инициализация runtime в `includes/admin.php` вынесена в `bootstrapAdminRuntime()` (поведение сохранено) -- ✅ Второй инкремент: session/runtime-логика вынесена в `includes/bootstrap/admin_session.php` и `includes/bootstrap/admin_runtime.php` (без изменения поведения) -- ✅ Третий инкремент: `includes/bootstrap/admin_runtime.php` переключён на `XC_Bootstrap::boot(XC_Bootstrap::CONTEXT_ADMIN)` с legacy fallback -- ✅ Четвёртый инкремент: прямые `require_once` зависимостей (`DatabaseHandler/CoreUtilities/API/Translator/MobileDetect`) удалены из `includes/admin.php` и централизованы в `includes/bootstrap/admin_runtime.php` -- ✅ Пятый инкремент: `includes/admin.php` больше не подключает `www/constants.php` напрямую — инициализация идёт через bootstrap-поток -- ✅ Шестой инкремент: убрана двойная `shutdown`-регистрация — в bootstrap-ветке используется `XC_Bootstrap`, в legacy fallback регистрируется локальный close-db shutdown callback -- ✅ Седьмой инкремент: `STATUS_*` константы удалены из `includes/admin.php` и централизованы через `bootstrapAdminStatusConstants()` (`XC_Bootstrap::defineStatusConstants()` + fallback) -- ✅ Восьмой инкремент: bootstrap-цепочка в `includes/admin.php` сведена к фасаду `includes/bootstrap/admin_bootstrap.php` (`bootstrapAdminInclude()`) +#### Шаг 7.2 — Замена процедурного bootstrap ✅ +8 инкрементов: runtime → `bootstrapAdminRuntime()` → `admin_session.php` + `admin_runtime.php` → `XC_Bootstrap::boot(CONTEXT_ADMIN)` → фасад `admin_bootstrap.php`. #### Шаг 7.3 — Удаление proxy-обёрток из admin.php ✅ -- Все функции уже в domain/ (proxy-вызовы) -- Все данные в resources/data/ -- Bootstrap через `bootstrap.php` -- `admin.php` — сокращён с ~4448 до ~3070 строк (удалено 40 proxy-определений) +40 proxy-определений удалены, 560+ call-sites заменены на прямые вызовы domain-сервисов. `admin.php` сокращён с ~4448 до ~3050 строк. -**Статус (7.3 завершён):** -- ✅ Первый инкремент: пакет простых proxy-обёрток вынесен из `includes/admin.php` в `includes/bootstrap/admin_proxies.php` -- ✅ Второй инкремент: вынесены proxy/report/permission-обёртки (`getStreamArguments`, `getTranscodeProfiles`, `getResellers`, `getDirectReports`, `hasPermissions` и связанный блок) в `includes/bootstrap/admin_proxies.php` -- ✅ Третий инкремент: начат прямой отказ от proxy-call-site — HMAC-ветка переведена на прямые вызовы `AuthRepository::*`, proxy `getHMACTokens/getHMACToken` удалены -- ✅ Четвёртый инкремент: массовая замена всех внешних call-site (560+) для proxy-функций: - - `getBouquets()` → `BouquetService::getAllSimple()` (47 call-sites) - - `getStreamingServers()` → `ServerRepository::getStreamingSimple($rPermissions, $type)` (29 call-sites) - - `getStream()` → `StreamRepository::getById($rID)` (~30 call-sites) - - `getUser()` → `UserRepository::getLineById($rID)` (~34 call-sites) - - `getRegisteredUser()` → `UserRepository::getRegisteredUserById($rID)` (~48 call-sites) - - `getBouquetOrder()` → `BouquetService::getOrder()` (6 call-sites) - - `getMemberGroup()` → `GroupService::getById($rID)` (4 call-sites) - - `getBlockedIPs()` → `BlocklistService::getBlockedIPsSimple()` (2 call-sites) - - `getRTMPIPs()` → `BlocklistService::getRTMPIPsSimple()` (2 call-sites) - - `getSSLLog()` → `ServerRepository::getSSLLog(...)` (1 call-site) - - `getWatchdog()` → `WatchdogMonitor::getWatchdog(...)` (1 call-site) - - `getIP()` → `CoreUtilities::getUserIP()` (2 call-sites) - - `getFPMStatus()` → `systemapirequest(...)` inline (1 call-site) - - И ещё ~20 proxy-функций с 0 внешних вызовов -- ✅ Пятый инкремент: все 40 proxy-определений удалены из `admin.php` -- ✅ Рефакторинг: `PackageService::process()` — удалены callback-параметры `getBouquetOrder`/`sortArrayByArray`, заменены прямыми вызовами `BouquetService::getOrder()` -- ⚠️ Оставлены: `getCategories()` (~15 внешних вызовов, не чистый proxy — трансформирует ключи), `getOutputs()` (3 внешних вызова, собственная SQL-логика) +#### Шаг 7.3.1 — Миграция getCategories/getOutputs ✅ +`getCategories()` → `CategoryService::getAllByType()` (~75+ call-sites). `getOutputs()` → `OutputFormatRepository::getAll()` (3 call-sites). Создан `domain/Line/OutputFormatRepository.php`. + +#### Шаг 6.5b — Reseller view nullable audit ✅ +Source-level: `getPermissions()` → `[]` fallback, defensive defaults в `functions.php`/`table.php`. P0 fixes в 8 файлах (foreach/count/in_array guards). P1 в 2 файлах. P2/P3 покрыты source-level defaults. + +#### Шаг 7.4 — Устранение параметра `$db` из Domain-классов ✅ +28 классов (100 методов) → `global $db` внутри. ~357 call-sites обновлены. --- -### Шаг 7.4 — Устранение параметра `$db` из Domain-классов (global $db) +### Фаза 8: Ликвидация god-объектов ✅ -**Суть:** Все 28 Domain-классов (Service/Repository) принимали `$db` как параметр метода. Рефакторинг: убрать `$db` из сигнатур, внутри каждого метода объявить `global $db;`. +**Цель:** Удалить три файла-монолита (`CoreUtilities.php`, `StreamingUtilities.php`, `admin_api.php`), заменив ~7 400 внешних вызовов на прямые обращения к целевым классам. -**Затронутые классы (100 методов):** -- `StreamRepository` (7), `StreamService` (4), `StreamProcess` (13), `ChannelService` (3) -- `SeriesService` (3), `MovieService` (3), `EpisodeService` (2), `PlaylistGenerator` (1) -- `CronGenerator` (1), `ConnectionTracker` (2), `ConnectionLimiter` (3), `CategoryService` (3) -- `UserService` (2), `UserRepository` (5), `GroupService` (2), `PackageService` (2) -- `LineRepository` (1), `LineService` (4), `SettingsService` (3), `ServerRepository` (5) -- `ServerService` (4), `BlocklistService` (10), `EpgService` (3), `AuthService` (3) -- `BouquetService` (8), `TokenAuth` (1), `FFmpegCommand` (1), `WatchdogMonitor` (1) +| Файл | Было строк | Методов | Внешних вызовов | Статус | +|------|:----------:|:-------:|:---------------:|--------| +| `admin_api.php` | 3 686 | 79 | ~300 | ✅ 8.1 — удалён | +| `StreamingUtilities.php` | 659 | 78 | 1 344 | ✅ 8.2 — удалён | +| `CoreUtilities.php` | 1 971 | 152 | 5 755 | ✅ 8.3–8.11 — удалён | -**Обновлено ~357 call-sites** по всей кодовой базе: -- `src/includes/CoreUtilities.php` — 28 вызовов -- `src/includes/admin_api.php` — 60 вызовов -- `src/includes/reseller_api.php` — 15 вызовов -- `src/includes/admin.php` — 16 вызовов -- `src/includes/StreamingUtilities.php` — 6 вызовов -- `src/includes/bootstrap/admin_runtime.php` — 3 вызова -- `src/includes/api/admin/` — 20 вызовов -- `src/includes/api/reseller/` — 11 вызовов -- `src/admin/*.php` — ~100 вызовов -- `src/reseller/*.php` — 18 вызовов -- `src/public/Controllers/Admin/` — 37 вызовов -- `src/domain/` (кросс-вызовы) — 15 вызовов -- `src/modules/` + `src/crons/` — 11 вызовов +#### Шаг 8.1 — admin_api.php ✅ +60 PROXY + 18 OWN методов мигрированы в domain-сервисы. Файл удалён. -**Паттерн (до/после):** -```php -// Было: -public static function getById($db, $rID) { ... } -StreamRepository::getById($db, $rStreamID); +#### Шаг 8.2 — StreamingUtilities.php ✅ +42 PROXY + 33 OWN методов, 18 свойств. ~314 ссылок заменены в 10 батчах. Файл удалён. -// Стало: -public static function getById($rID) { - global $db; - ... -} -StreamRepository::getById($rStreamID); -``` +#### Шаг 8.3 — CoreUtilities методы ✅ +81 PROXY + 69 OWN методов извлечены в целевые классы (17 батчей). CU сокращён с 1 971 до 40 строк. -**Статус:** ✅ Завершено +#### Шаги 8.4–8.6 — Свойства (blocklist, FFmpeg, light) ✅ +- **8.4** 7 blocklist/allowlist свойств → `BlocklistService` lazy getters (FileCache) +- **8.5** 3 FFmpeg свойства → value-object `FfmpegPaths::resolve()` +- **8.6** 3 свойства ($rCategories, $rBouquets, $rSegmentSettings) → сервисные геттеры ---- +#### Шаги 8.7–8.10 — Инфраструктурные свойства → singletons ✅ +- **8.7** `$rCached` → `FileCache`, `$rConfig` → `ConfigReader`, `$rServers` (184 refs) → `ServerRepository::getAll()` +- **8.8** `$db` (30 refs) → `DatabaseFactory::set()/get()`, `$redis` (62 refs) → `RedisManager::instance()` +- **8.9** `$rSettings` (819 refs, 221 файл) → `SettingsManager::set()/getAll()/get()/update()` +- **8.10** `$rRequest` (3863 refs, 166 файлов) → `RequestManager::set()/getAll()/get()/update()` -### Фаза 8: Ликвидация god-объектов +#### Шаг 8.11 — Удаление CoreUtilities.php ✅ +6 call-sites `CoreUtilities::init()` → `LegacyInitializer::initCore()`. Файл физически удалён. -**Цель:** Удалить три файла-монолита (`CoreUtilities.php`, `StreamingUtilities.php`, `admin_api.php`), заменив все ~7 100 внешних вызовов на прямые обращения к целевым классам в `domain/`, `core/`, `streaming/`. +**Эволюция CU:** -#### Аудит перед началом (28.02.2026) +| Фаза | Строк | Методов | Свойств | +|------|------:|--------:|--------:| +| До рефакторинга | 1 971 | 152 | 21 | +| После 8.3 | 40 | 3 | 21 | +| После 8.4–8.6 | 19 | 2 | 8 | +| После 8.7–8.8 | 9 | 1 | 2 | +| После 8.9–8.10 | 5 | 1 | 0 | +| **8.11 — УДАЛЁН** | **0** | **0** | **0** | -| Файл | Строк | Методов | PROXY | OWN | Внешних вызовов | Файлов-потребителей | -|------|--------|---------|-------|-----|-----------------|---------------------| -| `CoreUtilities.php` | 1 971 | 152 | 81 | 69 | 5 755 | 303 | -| `StreamingUtilities.php` | 659 | 78 | 42 | 33 | 1 344 | 20 | -| `admin_api.php` | 3 686 | 79 | 60 | 18 | ~300 | ~40 | -| **Итого** | **6 316** | **309** | **183** | **120** | **~7 400** | — | - -**Распределение вызовов CoreUtilities по типу:** -- `$rRequest` — 3 863 обращений (67%) — глобальный request-контейнер -- `$rSettings` — 769 обращений — настройки панели -- `$rServers` — 201 обращение — массив серверов -- Методы-вызовы — ~920 обращений - -**Распределение StreamingUtilities по директориям:** -- `www/` — 769 | `ministra/` — 266 | `modules/` — 229 | `core/` — 76 | `streaming/` — 4 - -**Дублирование:** ~25 методов идентичны в обоих классах (`encryptData`, `base64url_*`, `cleanGlobals`, `getUserIP`, `getISP`, `getIPInfo`, `getPublicURL`, `isMonitorRunning`, `isStreamRunning`, `isProcessRunning`, `validateImage`, `generateString`, `getDiffTimezone`, `getAdultCategories`, `writeOfflineActivity`, `getPlaylistSegments`, `checkISP`, `checkServer`, `setSignal`, `matchCIDR` и др.) - ---- - -#### Шаг 8.1 — admin_api.php (LOW RISK) - -**Объём:** 3 686 строк, 79 методов (60 PROXY + 18 OWN + 1 INIT), ~300 внешних вызовов в ~40 файлах. - -**8.1.1 — Удаление PROXY-методов** (60 шт.) -Каждый PROXY-метод просто делегирует в сервис: -```php -// Было (admin_api.php): -public static function processBouquet() { return BouquetService::process(self::$db, ...); } -// Вызов: -ipTV_lib::processBouquet(); - -// Стало (прямой вызов): -BouquetService::process($db, ...); -``` - -Целевые классы-делегаты (все уже существуют в `domain/`): -`BouquetService`(3), `AuthService`(2), `UserService`(4), `BlocklistService`(3), `ChannelService`(3), -`EpgService`(1), `EpisodeService`(3), `GroupService`(1), `StreamService`(4), `MovieService`(3), -`SeriesService`(3), `LineService`(3), `MagService`(3), `EnigmaService`(3), `PackageService`(1), -`ServerService`(3), `SettingsService`(3), `CategoryService`(2), `PlexService`(2), `WatchService`(2), -`RecordingService`(1), `Authenticator`(1) - -**8.1.2 — Извлечение OWN-методов** (18 шт.) -Legacy-методы с прямым SQL, которые не были перенесены в сервисы: - -| Метод | Строк | Целевой класс | -|-------|-------|--------------| -| `processProvider()` | ~55 | → `domain/Stream/ProviderService.php` (новый) | -| `processGroupLegacy()` | ~90 | → `domain/User/GroupService.php` | -| `processMovieLegacy()` | ~465 | → `domain/Vod/MovieService.php` | -| `processMAGLegacy()` | ~195 | → `domain/Device/MagService.php` | -| `processEnigmaLegacy()` | ~193 | → `domain/Device/EnigmaService.php` | -| `processProfile()` | ~320 | → `domain/Stream/ProfileService.php` (новый) | -| `processRadio()` | ~248 | → `domain/Stream/RadioService.php` (новый) | -| `massEditRadios()` | ~185 | → `domain/Stream/RadioService.php` | -| `processUserLegacy()` | ~92 | → `domain/User/UserService.php` | -| `processLineLegacy()` | ~108 | → `domain/Line/LineService.php` | -| `processSeriesLegacy()` | ~100 | → `domain/Vod/SeriesService.php` | -| `importSeriesLegacy()` | ~205 | → `domain/Vod/SeriesService.php` | -| `importMoviesLegacy()` | ~200 | → `domain/Vod/MovieService.php` | -| `massEditLinesLegacy()` | ~120 | → `domain/Line/LineService.php` | -| `massEditMagsLegacy()` | ~187 | → `domain/Device/MagService.php` | -| `massEditEnigmasLegacy()` | ~156 | → `domain/Device/EnigmaService.php` | -| `massEditUsersLegacy()` | ~86 | → `domain/User/UserService.php` | -| `massDeleteStations()` | ~16 | → `domain/Stream/StreamService.php` | - -**8.1.3 — Удаление `init()` и статических свойств** -- `$db`, `$rSettings`, `$rServers`, `$rProxyServers`, `$rUserInfo` — уже доступны через `CoreUtilities` или `$GLOBALS` -- `checkMinimumRequirements()` (приватный валидатор) → `core/Validation/InputValidator.php` -- Удалить файл `includes/admin_api.php` - -**Статус 8.1:** ✅ Завершён -- `admin_api.php` (класс `API`) — файл удалён, все proxy/OWN методы мигрированы в domain-сервисы -- Осиротевшие ссылки `API::processUser()` в `src/tools` → заменены на `UserService::process()` -- `API::$db`/`API::init()` в `src/tools` → удалены -- Запись `'API'` в `autoload.php` → удалена -- `reseller_api.php` (класс `ResellerAPI`): `self::$db` → `global $db` (42 вхождения) -- Удалено свойство `public static $db = null` из `ResellerAPI` -- Удалены внешние присвоения `ResellerAPI::$db` из `bootstrap.php`, `admin_runtime.php`, `api/reseller/index.php` - ---- - -#### Шаг 8.2 — StreamingUtilities.php (MEDIUM RISK) - -**Объём:** 659 строк, 78 методов (42 PROXY + 33 OWN + 1 INIT + 2 PROPERTY), 1 344 внешних вызовов в 20 файлах. - -**8.2.1 — Удаление PROXY-методов** (42 шт.) -Все прямые делегаты → заменить call sites на целевой класс: -`ConnectionTracker`(8), `BruteforceGuard`(4), `StreamSorter`(4), `BlocklistService`(3), -`ConnectionLimiter`(3), `StreamRedirector`(2), `OffAirHandler`(2), `RedisManager`(2), -`StreamAuth`(2), `ProxySelector`(1), `SignalSender`(1), `AuthService`(1), `ImageUtils`(1), -`HealthChecker`(1), `CategoryService`(1), `SegmentReader`(1), `HLSGenerator`(1), -`BouquetService`(1), `DomainResolver`(1), `UserRepository`(1), `LegacyInitializer`(1) - -**8.2.2 — Извлечение OWN-методов** (33 шт.) -Группировка по целевому модулю: - -| Группа | Методы | Целевой класс | -|--------|--------|--------------| -| Кеш | `getCache()` | → `core/Cache/FileCache.php` (объединить с `CoreUtilities::getCache/setCache`) | -| Криптография | `encryptData()`, `decryptData()`, `base64url_encode/decode()`, `mc_decrypt()` | → `core/Crypto/DataEncryptor.php` (новый, общий) | -| HTTP/Input | `cleanGlobals()`, `parseIncomingRecursively()`, `parseCleanKey()`, `parseCleanValue()` | → `core/Http/InputSanitizer.php` (новый, общий) | -| Networking | `getUserIP()`, `getISP()`, `getIPInfo()`, `matchCIDR()`, `getDomainName()` | → `core/Network/IpUtils.php` (новый) | -| Process | `isMonitorRunning()`, `isStreamRunning()`, `isProcessRunning()`, `startMonitor()`, `startProxy()` | → `streaming/Process/ProcessManager.php` (объединить из обоих) | -| Streaming | `getPublicURL()`, `getStreamData()`, `getPlaylistSegments()`, `getAllowedRTMP()`, `canWatch()`, `writeOfflineActivity()`, `setSignal()`, `generateString()` | → `streaming/` соответствующие классы | -| UI | `getDiffTimezone()`, `getAdultCategories()` | → `core/Util/DateUtils.php`, `domain/Stream/CategoryService.php` | -| DB | `connectDatabase()`, `closeDatabase()` | → оставить в `LegacyInitializer` или `core/Database/` | -| Init | `isCacheEnabledAndComplete()` | → `core/Cache/CacheStatus.php` | - -**8.2.3 — Замена статических свойств** -`StreamingUtilities::$rRequest` (369), `$rSettings` (366), `$rServers` (105), `$db` (83) — всего **923 обращения** в 20 файлах. -→ Заменить на `$GLOBALS['rRequest']` / `$GLOBALS['rSettings']` / `$GLOBALS['db']` (промежуточный шаг) -→ Или инжектировать через параметры функций (целевой вариант) - -**8.2.4 — Удаление файла** -После переноса всех методов и свойств — удалить `includes/StreamingUtilities.php`. - -**Статус 8.2:** ✅ **ЗАВЕРШЕНО** (2026-03-03) - -**Итого:** ~314 внешних ссылок заменены в 10 батчах (Batch 1–10d). -Файл `includes/StreamingUtilities.php` удалён (676 строк мёртвого кода). - -**Ключевые результаты:** -- 8.2.3 — все 18 статических свойств удалены → `global $var` / `$GLOBALS['var']` -- 8.2.1 — все 42 PROXY-метода мигрированы → прямые вызовы сервисов -- 8.2.2 — все 33 OWN-метода перенесены в целевые классы -- 8.2.4 — файл удалён, require/autoload записи убраны, bootstrap.php очищен - -**Батчи миграции внешних вызовов:** - -| Батч | Методы | Замен | Файлов | -|------|--------|-------|--------| -| 1 | Crypto (encrypt/decrypt/base64url) | 42 | 5 | -| 2 | validateImage | 22 | 3 | -| 3–5 | Простые proxy (sort, categories, health, signal, cache, etc.) | ~60 | 12 | -| 6 | DB lifecycle (connect/close) | 26 | 8 | -| 7 | Redis + Connection (get/create/updateConnection, redisSignal, etc.) | 57 | 6 | -| 8 | Process + Proxy + Queue | 17 | 5 | -| 9 | Process + GeoIP (isMonitorRunning, getIPInfo, etc.) | 24 | 5 | -| 10a | getUserInfo | 18 | 6 | -| 10b | showVideoServer + availableProxy | 26 | 2 | -| 10c | redirectStream, validateConnections, validateHMAC, generateHLS, etc. | 20 | 8 | -| 10d | getAllowedRTMP + getPlaylistSegments | 2 | 2 | - -**Рефакторинг callback-цепочек (Batch 10):** -9 сервисных классов избавлены от callback-параметров → прямые service-to-service вызовы: -`UserRepository`, `OffAirHandler`, `StreamAuth`, `ProxySelector`, `StreamRedirector`, -`ConnectionLimiter`, `HLSGenerator`, `AuthService`, `DomainResolver` - -**Новые методы/классы добавленные при миграции:** -- `GeoIPService::getIPInfo()`, `getISP()`, `matchCIDR()` -- `BlocklistService::getAllowedRTMP()` -- `SegmentReader::getPlaylistSegments()` -- `ConnectionLimiter::writeOfflineActivity()` -- `StreamRedirector::getStreamData()` (private) -- `ProcessManager::isStreamAlive()`, `isMonitorAlive()`, `startMonitor()`, `startProxy()` -- `RedisManager::instance()` (singleton для прямого доступа) - ---- - -#### Шаг 8.3 — CoreUtilities.php (HIGH RISK, поэтапно) - -**Объём:** 1 971 строк, 152 метода (81 PROXY + 69 OWN + 1 INIT + 1 PROPERTY), 5 755 внешних вызовов в 303 файлах. - -**Главная сложность:** `CoreUtilities::$rRequest` — 3 863 обращения в 303 файлах. Это глобальный массив POST/GET-данных, используемый как `CoreUtilities::$rRequest['page']`, `CoreUtilities::$rRequest['id']` и т.д. Аналогично `$rSettings` (769 обращений) и `$rServers` (201). - -**8.3.1 — Удаление PROXY-методов** (81 шт.) -Прямая замена вызовов на целевые классы. Топ делегатов: -`StreamProcess`(16), `ConnectionTracker`(14), `PlexAuth`(6), `BlocklistService`(5), -`BruteforceGuard`(4), `StreamSorter`(4), `LineService`(4), `EpgService`(4), -`ProcessChecker`(3), `CurlClient`(3), `FFprobeRunner`(2), `BouquetService`(2), -`ImageUtils`(2), `RedisManager`(2), остальные по 1 - -**Топ-10 вызываемых PROXY-методов** (количество call sites): - -| Метод | Вызовов | Делегат | -|-------|---------|---------| -| `closeConnection()` | 48 | → `ConnectionLimiter::closeConnection()` | -| `validateImage()` | 40 | → `ImageUtils::validateURL()` | -| `downloadImage()` | 32 | → `ImageUtils::download()` (новый целевой) | -| `getUserIP()` | 30 | → `core/Network/IpUtils::getUserIP()` | -| `updateStream()` | 29 | → `StreamProcess::updateStream()` | -| `getUserConnections()` | 29 | → `ConnectionTracker::getUserConnections()` | -| `updateLine()` | 26 | → `LineService::updateLineSignal()` | -| `checkCron()` | 22 | → метод остаётся (OWN) | -| `getStreamConnections()` | 20 | → `ConnectionTracker::getStreamConnections()` | -| `getRedisConnections()` | 20 | → `ConnectionTracker::getRedisConnections()` | - -**8.3.2 — Извлечение OWN-методов** (69 шт.) - -| Группа | Методы (шт.) | Целевой класс | -|--------|-------------|--------------| -| User/Auth | `getUserInfo()`(170 стр.), `getMAGInfo()`, `getE2Info()`, `getAllowedIPs()`, `getAllowedDomains()` | → `domain/Line/UserInfoResolver.php` (новый) | -| Connection | `closeConnection()`(96 стр.), `writeOfflineActivity()`, `streamLog()` | → `streaming/Connection/ConnectionManager.php` | -| Process | `isMonitorRunning()`, `isThumbnailRunning()`, `isArchiveRunning()`, `isDelayRunning()`, `isStreamRunning()`, `isProcessRunning()`, `isRunning()` | → `streaming/Process/ProcessManager.php` | -| Streaming | `getPlaylistSegments()`, `generateAdminHLS()`, `getStreamBitrate()`, `isValidStream()`, `findKeyframe()`, `parseStreamURL()`, `detectXC_VM()`, `parseTranscode()`, `getArguments()`, `customOrder()`, `getRTMPStats()` | → распределить по `streaming/` классам | -| Cache | `setCache()`, `getCache()` | → `core/Cache/FileCache.php` | -| Crypto | `encryptData()`, `decryptData()`, `base64url_encode/decode()` | → `core/Crypto/DataEncryptor.php` | -| Network | `getUserIP()`, `getISP()`, `checkISP()`, `checkServer()`, `getIPInfo()`, `getCertificateInfo()`, `getApiIP()` | → `core/Network/IpUtils.php` | -| HTTP/Input | `cleanGlobals()`, `parseIncoming*()`, `parseCleanKey/Value()` | → `core/Http/InputSanitizer.php` | -| Image | `downloadImage()`, `getImageSizeKeepAspectRatio()`, `isAbsoluteUrl()` | → `core/Media/ImageUtils.php` (расширить) | -| URL | `getPublicURL()`(45 стр.), `getProxyFor()` | → `core/Network/UrlBuilder.php` | -| Download | `startDownload()`, `stopDownload()` | → `streaming/Download/DownloadManager.php` | -| Backup | `createBackup()`, `restoreBackup()`, `grantPrivileges()`, `revokePrivileges()` | → `domain/Server/BackupService.php` (новый) | -| System | `checkCompatibility()`, `confirmIDs()`, `downloadPanelLogs()`, `submitPanelLogs()` | → `core/System/SystemCheck.php` (новый) | -| Misc | `generateString()`, `secondsToTime()`, `mergeRecursive()`, `checkCron()`, `fixCookie()`, `unserialize_php()`, `getTSInfo()`, `getDiffTimezone()` | → `core/Util/Helpers.php` (новый) | - -**8.3.3 — Замена статических свойств** (наибольшая работа) - -| Свойство | Обращений | Стратегия замены | -|----------|-----------|-----------------| -| `$rRequest` | 3 863 | **Этап A:** глобальная переменная `$rRequest` (через `$GLOBALS['rRequest']` или `global $rRequest`). **Этап B:** `Request::input()` в контроллерах, прямой `$_POST/$_GET` в legacy. | -| `$rSettings` | 769 | **Этап A:** `$GLOBALS['rSettings']`. **Этап B:** `SettingsRepository::getCached()` статический singleton. | -| `$rServers` | 201 | **Этап A:** `$GLOBALS['rServers']`. **Этап B:** `ServerRepository::getCached()`. | -| `$db` | 20 | `$GLOBALS['db']` или `global $db` (уже используется в большинстве мест) | -| `$redis` | 60 | `RedisManager::getInstance()` | -| Остальные | ~40 | Через соответствующие Repository/Service с кешем | - -**Порядок замены `$rRequest` (3 863 вызова):** -1. `admin/` (2 307 из них — уже обёрнуты `$__viewMode` guard, контроллеры используют `$this->input()`) -2. `includes/` (1 455 — через `global $rRequest`) -3. `reseller/` (678), `www/` (373), `crons/` (260), `player/` (170) -4. `core/` (164), `public/` (161), `modules/` (112), `domain/` (76) - -**8.3.4 — Удаление `init()` и `LegacyInitializer`** -- `CoreUtilities::init()` → `LegacyInitializer::initCore()` → вызывается внешними `www/init.php`, `bootstrap.php` -- Заменить инициализацию на `XC_Bootstrap::boot()` (уже существует) -- Удалить `LegacyInitializer.php` после полного перехода - -**8.3.5 — Удаление файла** -После переноса ВСЕХ методов и свойств — удалить `includes/CoreUtilities.php`. - -**Статус 8.3:** ⏳ Не начат - ---- - -#### Шаг 8.4 — Ревизия архитектуры - -- Убедиться: `core/` не содержит бизнес-логики (только инфраструктура) -- Убедиться: `domain/` не знает об `public/` (однонаправленные зависимости) -- Убедиться: удаление любого модуля не ломает систему -- Рефакторинг `cli/monitor.php` — убрать goto-лейблы, вынести в `cli/Commands/MonitorCommand.php` - -**Статус 8.4:** ⏳ Не начат - ---- - -#### Новые целевые файлы (создаются в Фазе 8) - -| Файл | Откуда | Назначение | -|------|--------|-----------| -| `core/Cache/FileCache.php` | CU::getCache/setCache + SU::getCache | Файловый кеш с igbinary | -| `core/Crypto/DataEncryptor.php` | CU+SU::encryptData/decryptData/base64url_* | Шифрование/кодирование | -| `core/Http/InputSanitizer.php` | CU+SU::cleanGlobals/parseIncoming*/parseClean* | Очистка входных данных | -| `core/Network/IpUtils.php` | CU+SU::getUserIP/getISP/getIPInfo/checkISP/matchCIDR | IP-утилиты | -| `core/Network/UrlBuilder.php` | CU+SU::getPublicURL/getProxyFor | Построение URL | -| `core/Media/ImageUtils.php` | CU::downloadImage/getImageSize* (расширить имеющийся) | Работа с изображениями | -| `core/Util/Helpers.php` | CU::generateString/secondsToTime/mergeRecursive/etc. | Общие утилиты | -| `core/Util/DateUtils.php` | CU+SU::getDiffTimezone | Дата/время | -| `core/System/SystemCheck.php` | CU::checkCompatibility/downloadPanelLogs/submitPanelLogs | Системные проверки | -| `core/Validation/InputValidator.php` | admin_api::checkMinimumRequirements | Валидация входных данных | -| `streaming/Process/ProcessManager.php` | CU+SU::isMonitor/isStream/isProcess/isRunning | Управление процессами | -| `streaming/Connection/ConnectionManager.php` | CU::closeConnection/writeOfflineActivity/streamLog | Управление соединениями | -| `streaming/Download/DownloadManager.php` | CU::startDownload/stopDownload | Управление скачиваниями | -| `domain/Line/UserInfoResolver.php` | CU::getUserInfo/getMAGInfo/getE2Info | Получение инфо о юзере/устройстве | -| `domain/Server/BackupService.php` | CU::createBackup/restoreBackup/grant/revokePrivileges | Управление бэкапами | -| `domain/Stream/ProviderService.php` | admin_api::processProvider | CRUD провайдеров | -| `domain/Stream/ProfileService.php` | admin_api::processProfile | CRUD профилей транскодирования | -| `domain/Stream/RadioService.php` | admin_api::processRadio/massEditRadios | CRUD радиостанций | - ---- - -### Рекомендуемый порядок выполнения Фазы 8 - -``` -8.1 admin_api.php ──→ 8.2 StreamingUtilities ──→ 8.3 CoreUtilities -(~300 вызовов, ~40 файлов) (1 344 вызовов, 20 файлов) (5 755 вызовов, 303 файла) - LOW RISK MEDIUM RISK HIGH RISK - -Внутри каждого шага: - .1 Удалить PROXY (поиск-замена call sites) - .2 Извлечь OWN (создать целевые классы + перенести логику) - .3 Заменить свойства (static → global/DI) - .4 Удалить файл -``` - -Каждый подшаг (8.1.1, 8.1.2, ...) — одна рабочая сессия. -После каждого подшага система полностью работоспособна (proxy и legacy продолжают работать). +**Новые singleton/service классы (Phase 8):** `SettingsManager`, `RequestManager`, `ConfigReader`, `DatabaseFactory` (singleton), `RedisManager` (singleton), `FfmpegPaths`, `FileCache`, `DataEncryptor`, `InputSanitizer`, `IpUtils`, `UrlBuilder`, `ImageUtils`, `Helpers`, `ProcessManager`, `ConnectionManager`, `BackupService`, `ProviderService`, `ProfileService`, `RadioService`, `SystemCheck`, `InputValidator`. --- diff --git a/src/admin/api.php b/src/admin/api.php index 58ff7cb77..422d1ff00 100644 --- a/src/admin/api.php +++ b/src/admin/api.php @@ -10,16 +10,16 @@ if (!PHP_ERRORS) { } if (isset($_SESSION['hash'])) { - if (CoreUtilities::$rSettings['redis_handler']) { - CoreUtilities::connectRedis(); + if (SettingsManager::getAll()['redis_handler']) { + RedisManager::ensureConnected(); } - if (isset(CoreUtilities::$rRequest['action'])) { - if (CoreUtilities::$rRequest['action'] == 'stream') { + if (isset(RequestManager::getAll()['action'])) { + if (RequestManager::getAll()['action'] == 'stream') { if (Authorization::check('adv', 'edit_stream')) { - $rStreamID = intval(CoreUtilities::$rRequest['stream_id']); - $rServerID = intval(CoreUtilities::$rRequest['server_id']); - $rSub = CoreUtilities::$rRequest['sub']; + $rStreamID = intval(RequestManager::getAll()['stream_id']); + $rServerID = intval(RequestManager::getAll()['server_id']); + $rSub = RequestManager::getAll()['sub']; if (in_array($rSub, array('start', 'stop', 'restart'))) { if ($rSub == 'restart') { @@ -46,7 +46,7 @@ if (isset($_SESSION['hash'])) { } } else { if ($rSub == 'force') { - $rForceID = intval(CoreUtilities::$rRequest['force_id']); + $rForceID = intval(RequestManager::getAll()['force_id']); $rServerIDs = array_keys(StreamRepository::getSystemRows($rStreamID)); if (0 >= count($rServerIDs)) { @@ -69,16 +69,16 @@ if (isset($_SESSION['hash'])) { } if ($rSub == 'kill') { - CoreUtilities::closeConnection(CoreUtilities::$rRequest['stream_id']); + ConnectionTracker::closeConnection(RequestManager::getAll()['stream_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'purge') { - if (CoreUtilities::$rSettings['redis_handler']) { - foreach (CoreUtilities::getRedisConnections(null, ($rServerID == -1 ? null : $rServerID), $rStreamID, true, false, false) as $rConnection) { - CoreUtilities::closeConnection($rConnection); + if (SettingsManager::getAll()['redis_handler']) { + foreach (ConnectionTracker::getRedisConnections(null, ($rServerID == -1 ? null : $rServerID), $rStreamID, true, false, false) as $rConnection) { + ConnectionTracker::closeConnection($rConnection); } } else { if ($rServerID == -1) { @@ -88,7 +88,7 @@ if (isset($_SESSION['hash'])) { } foreach ($db->get_rows() as $rRow) { - CoreUtilities::closeConnection($rRow); + ConnectionTracker::closeConnection($rRow); } } @@ -107,11 +107,11 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'movie') { + if (RequestManager::getAll()['action'] == 'movie') { if (Authorization::check('adv', 'edit_movie')) { - $rStreamID = intval(CoreUtilities::$rRequest['stream_id']); - $rServerID = intval(CoreUtilities::$rRequest['server_id']); - $rSub = CoreUtilities::$rRequest['sub']; + $rStreamID = intval(RequestManager::getAll()['stream_id']); + $rServerID = intval(RequestManager::getAll()['server_id']); + $rSub = RequestManager::getAll()['sub']; if (in_array($rSub, array('start', 'stop'))) { if ($rServerID == -1) { @@ -142,16 +142,16 @@ if (isset($_SESSION['hash'])) { } if ($rSub == 'kill') { - CoreUtilities::closeConnection(CoreUtilities::$rRequest['stream_id']); + ConnectionTracker::closeConnection(RequestManager::getAll()['stream_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'purge') { - if (CoreUtilities::$rSettings['redis_handler']) { - foreach (CoreUtilities::getRedisConnections(null, ($rServerID == -1 ? null : $rServerID), $rStreamID, true, false, false) as $rConnection) { - CoreUtilities::closeConnection($rConnection); + if (SettingsManager::getAll()['redis_handler']) { + foreach (ConnectionTracker::getRedisConnections(null, ($rServerID == -1 ? null : $rServerID), $rStreamID, true, false, false) as $rConnection) { + ConnectionTracker::closeConnection($rConnection); } } else { if ($rServerID == -1) { @@ -161,7 +161,7 @@ if (isset($_SESSION['hash'])) { } foreach ($db->get_rows() as $rRow) { - CoreUtilities::closeConnection($rRow); + ConnectionTracker::closeConnection($rRow); } } @@ -180,11 +180,11 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'episode') { + if (RequestManager::getAll()['action'] == 'episode') { if (Authorization::check('adv', 'edit_episode')) { - $rStreamID = intval(CoreUtilities::$rRequest['stream_id']); - $rServerID = intval(CoreUtilities::$rRequest['server_id']); - $rSub = CoreUtilities::$rRequest['sub']; + $rStreamID = intval(RequestManager::getAll()['stream_id']); + $rServerID = intval(RequestManager::getAll()['server_id']); + $rSub = RequestManager::getAll()['sub']; if (in_array($rSub, array('start', 'stop'))) { if ($rServerID == -1) { @@ -215,16 +215,16 @@ if (isset($_SESSION['hash'])) { } if ($rSub == 'kill') { - CoreUtilities::closeConnection(CoreUtilities::$rRequest['stream_id']); + ConnectionTracker::closeConnection(RequestManager::getAll()['stream_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'purge') { - if (CoreUtilities::$rSettings['redis_handler']) { - foreach (CoreUtilities::getRedisConnections(null, ($rServerID == -1 ? null : $rServerID), $rStreamID, true, false, false) as $rConnection) { - CoreUtilities::closeConnection($rConnection); + if (SettingsManager::getAll()['redis_handler']) { + foreach (ConnectionTracker::getRedisConnections(null, ($rServerID == -1 ? null : $rServerID), $rStreamID, true, false, false) as $rConnection) { + ConnectionTracker::closeConnection($rConnection); } } else { if ($rServerID == -1) { @@ -234,7 +234,7 @@ if (isset($_SESSION['hash'])) { } foreach ($db->get_rows() as $rRow) { - CoreUtilities::closeConnection($rRow); + ConnectionTracker::closeConnection($rRow); } } @@ -253,10 +253,10 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'line') { + if (RequestManager::getAll()['action'] == 'line') { if (Authorization::check('adv', 'edit_user')) { - $rUserID = intval(CoreUtilities::$rRequest['user_id']); - $rSub = CoreUtilities::$rRequest['sub']; + $rUserID = intval(RequestManager::getAll()['user_id']); + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { deleteLine($rUserID); @@ -267,7 +267,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'enable') { $db->query('UPDATE `lines` SET `enabled` = 1 WHERE `id` = ?;', $rUserID); - CoreUtilities::updateLine($rUserID); + LineService::updateLineSignal($rUserID); echo json_encode(array('result' => true)); exit(); @@ -275,7 +275,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'disable') { $db->query('UPDATE `lines` SET `enabled` = 0 WHERE `id` = ?;', $rUserID); - CoreUtilities::updateLine($rUserID); + LineService::updateLineSignal($rUserID); echo json_encode(array('result' => true)); exit(); @@ -283,7 +283,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'ban') { $db->query('UPDATE `lines` SET `admin_enabled` = 0 WHERE `id` = ?;', $rUserID); - CoreUtilities::updateLine($rUserID); + LineService::updateLineSignal($rUserID); echo json_encode(array('result' => true)); exit(); @@ -291,22 +291,22 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'unban') { $db->query('UPDATE `lines` SET `admin_enabled` = 1 WHERE `id` = ?;', $rUserID); - CoreUtilities::updateLine($rUserID); + LineService::updateLineSignal($rUserID); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'kill') { - if (CoreUtilities::$rSettings['redis_handler']) { - foreach (CoreUtilities::getRedisConnections($rUserID, null, null, true, false, false) as $rConnection) { - CoreUtilities::closeConnection($rConnection); + if (SettingsManager::getAll()['redis_handler']) { + foreach (ConnectionTracker::getRedisConnections($rUserID, null, null, true, false, false) as $rConnection) { + ConnectionTracker::closeConnection($rConnection); } } else { $db->query('SELECT * FROM `lines_live` WHERE `user_id` = ?;', $rUserID); foreach ($db->get_rows() as $rRow) { - CoreUtilities::closeConnection($rRow); + ConnectionTracker::closeConnection($rRow); } } @@ -324,9 +324,9 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'line_activity') { + if (RequestManager::getAll()['action'] == 'line_activity') { if (Authorization::check('adv', 'connection_logs')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub != 'kill') { echo json_encode(array('result' => false)); @@ -334,7 +334,7 @@ if (isset($_SESSION['hash'])) { exit(); } - CoreUtilities::closeConnection(CoreUtilities::$rRequest['pid']); + ConnectionTracker::closeConnection(RequestManager::getAll()['pid']); echo json_encode(array('result' => true)); exit(); @@ -344,9 +344,9 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'process') { + if (RequestManager::getAll()['action'] == 'process') { if (Authorization::check('adv', 'process_monitor')) { - systemapirequest(CoreUtilities::$rRequest['server'], array('action' => 'kill_pid', 'pid' => intval(CoreUtilities::$rRequest['pid']))); + systemapirequest(RequestManager::getAll()['server'], array('action' => 'kill_pid', 'pid' => intval(RequestManager::getAll()['pid']))); echo json_encode(array('result' => true)); exit(); @@ -356,16 +356,16 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'adjust_credits') { + if (RequestManager::getAll()['action'] == 'adjust_credits') { if (Authorization::check('adv', 'edit_reguser')) { - $rUser = UserRepository::getRegisteredUserById(CoreUtilities::$rRequest['id']); + $rUser = UserRepository::getRegisteredUserById(RequestManager::getAll()['id']); - if ($rUser && is_numeric(CoreUtilities::$rRequest['credits'])) { - $rCredits = intval($rUser['credits']) + intval(CoreUtilities::$rRequest['credits']); + if ($rUser && is_numeric(RequestManager::getAll()['credits'])) { + $rCredits = intval($rUser['credits']) + intval(RequestManager::getAll()['credits']); if (0 <= $rCredits) { $db->query('UPDATE `users` SET `credits` = ? WHERE `id` = ?;', $rCredits, $rUser['id']); - $db->query('INSERT INTO `users_credits_logs`(`target_id`, `admin_id`, `amount`, `date`, `reason`) VALUES(?, ?, ?, ?, ?);', $rUser['id'], $rUserInfo['id'], CoreUtilities::$rRequest['credits'], time(), CoreUtilities::$rRequest['reason']); + $db->query('INSERT INTO `users_credits_logs`(`target_id`, `admin_id`, `amount`, `date`, `reason`) VALUES(?, ?, ?, ?, ?);', $rUser['id'], $rUserInfo['id'], RequestManager::getAll()['credits'], time(), RequestManager::getAll()['reason']); echo json_encode(array('result' => true)); exit(); @@ -385,26 +385,26 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'reg_user') { + if (RequestManager::getAll()['action'] == 'reg_user') { if (Authorization::check('adv', 'edit_reguser')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteUser(CoreUtilities::$rRequest['user_id'], false, false, $rUserInfo['id']); + deleteUser(RequestManager::getAll()['user_id'], false, false, $rUserInfo['id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'enable') { - $db->query('UPDATE `users` SET `status` = 1 WHERE `id` = ?;', CoreUtilities::$rRequest['user_id']); + $db->query('UPDATE `users` SET `status` = 1 WHERE `id` = ?;', RequestManager::getAll()['user_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'disable') { - $db->query('UPDATE `users` SET `status` = 0 WHERE `id` = ?;', CoreUtilities::$rRequest['user_id']); + $db->query('UPDATE `users` SET `status` = 0 WHERE `id` = ?;', RequestManager::getAll()['user_id']); echo json_encode(array('result' => true)); exit(); @@ -419,26 +419,26 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'ticket') { + if (RequestManager::getAll()['action'] == 'ticket') { if (Authorization::check('adv', 'ticket')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteTicket(CoreUtilities::$rRequest['ticket_id']); + deleteTicket(RequestManager::getAll()['ticket_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'close') { - $db->query('UPDATE `tickets` SET `status` = 0 WHERE `id` = ?;', CoreUtilities::$rRequest['ticket_id']); + $db->query('UPDATE `tickets` SET `status` = 0 WHERE `id` = ?;', RequestManager::getAll()['ticket_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'reopen') { - $db->query('UPDATE `tickets` SET `status` = 1 WHERE `id` = ?;', CoreUtilities::$rRequest['ticket_id']); + $db->query('UPDATE `tickets` SET `status` = 1 WHERE `id` = ?;', RequestManager::getAll()['ticket_id']); echo json_encode(array('result' => true)); exit(); @@ -453,13 +453,13 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'mag') { + if (RequestManager::getAll()['action'] == 'mag') { if (Authorization::check('adv', 'edit_mag')) { - $rSub = CoreUtilities::$rRequest['sub']; - $rMagDetails = getMag(intval(CoreUtilities::$rRequest['mag_id'])); + $rSub = RequestManager::getAll()['sub']; + $rMagDetails = getMag(intval(RequestManager::getAll()['mag_id'])); if ($rSub == 'delete') { - deleteMAG(CoreUtilities::$rRequest['mag_id']); + deleteMAG(RequestManager::getAll()['mag_id']); echo json_encode(array('result' => true)); exit(); @@ -467,7 +467,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'enable') { $db->query('UPDATE `lines` SET `enabled` = 1 WHERE `id` = ?;', $rMagDetails['user_id']); - CoreUtilities::updateLine($rMagDetails['user_id']); + LineService::updateLineSignal($rMagDetails['user_id']); echo json_encode(array('result' => true)); exit(); @@ -475,7 +475,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'disable') { $db->query('UPDATE `lines` SET `enabled` = 0 WHERE `id` = ?;', $rMagDetails['user_id']); - CoreUtilities::updateLine($rMagDetails['user_id']); + LineService::updateLineSignal($rMagDetails['user_id']); echo json_encode(array('result' => true)); exit(); @@ -483,7 +483,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'ban') { $db->query('UPDATE `lines` SET `admin_enabled` = 0 WHERE `id` = ?;', $rMagDetails['user_id']); - CoreUtilities::updateLine($rMagDetails['user_id']); + LineService::updateLineSignal($rMagDetails['user_id']); echo json_encode(array('result' => true)); exit(); @@ -491,29 +491,29 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'unban') { $db->query('UPDATE `lines` SET `admin_enabled` = 1 WHERE `id` = ?;', $rMagDetails['user_id']); - CoreUtilities::updateLine($rMagDetails['user_id']); + LineService::updateLineSignal($rMagDetails['user_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'convert') { - deleteMAG(CoreUtilities::$rRequest['mag_id'], false, false, true); + deleteMAG(RequestManager::getAll()['mag_id'], false, false, true); echo json_encode(array('result' => true, 'line_id' => $rMagDetails['user']['id'])); exit(); } if ($rSub == 'kill') { - if (CoreUtilities::$rSettings['redis_handler']) { - foreach (CoreUtilities::getRedisConnections($rMagDetails['user_id'], null, null, true, false, false) as $rConnection) { - CoreUtilities::closeConnection($rConnection); + if (SettingsManager::getAll()['redis_handler']) { + foreach (ConnectionTracker::getRedisConnections($rMagDetails['user_id'], null, null, true, false, false) as $rConnection) { + ConnectionTracker::closeConnection($rConnection); } } else { $db->query('SELECT * FROM `lines_live` WHERE `user_id` = ?;', $rMagDetails['user_id']); foreach ($db->get_rows() as $rRow) { - CoreUtilities::closeConnection($rRow); + ConnectionTracker::closeConnection($rRow); } } @@ -531,13 +531,13 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'enigma') { + if (RequestManager::getAll()['action'] == 'enigma') { if (Authorization::check('adv', 'edit_e2')) { - $rSub = CoreUtilities::$rRequest['sub']; - $rE2Details = getEnigma(intval(CoreUtilities::$rRequest['e2_id'])); + $rSub = RequestManager::getAll()['sub']; + $rE2Details = getEnigma(intval(RequestManager::getAll()['e2_id'])); if ($rSub == 'delete') { - deleteEnigma(CoreUtilities::$rRequest['e2_id']); + deleteEnigma(RequestManager::getAll()['e2_id']); echo json_encode(array('result' => true)); exit(); @@ -545,7 +545,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'enable') { $db->query('UPDATE `lines` SET `enabled` = 1 WHERE `id` = ?;', $rE2Details['user_id']); - CoreUtilities::updateLine($rE2Details['user_id']); + LineService::updateLineSignal($rE2Details['user_id']); echo json_encode(array('result' => true)); exit(); @@ -553,7 +553,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'disable') { $db->query('UPDATE `lines` SET `enabled` = 0 WHERE `id` = ?;', $rE2Details['user_id']); - CoreUtilities::updateLine($rE2Details['user_id']); + LineService::updateLineSignal($rE2Details['user_id']); echo json_encode(array('result' => true)); exit(); @@ -561,7 +561,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'ban') { $db->query('UPDATE `lines` SET `admin_enabled` = 0 WHERE `id` = ?;', $rE2Details['user_id']); - CoreUtilities::updateLine($rE2Details['user_id']); + LineService::updateLineSignal($rE2Details['user_id']); echo json_encode(array('result' => true)); exit(); @@ -569,29 +569,29 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'unban') { $db->query('UPDATE `lines` SET `admin_enabled` = 1 WHERE `id` = ?;', $rE2Details['user_id']); - CoreUtilities::updateLine($rE2Details['user_id']); + LineService::updateLineSignal($rE2Details['user_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'convert') { - deleteEnigma(CoreUtilities::$rRequest['e2_id'], false, false, true); + deleteEnigma(RequestManager::getAll()['e2_id'], false, false, true); echo json_encode(array('result' => true, 'line_id' => $rE2Details['user']['id'])); exit(); } if ($rSub == 'kill') { - if (CoreUtilities::$rSettings['redis_handler']) { - foreach (CoreUtilities::getRedisConnections($rE2Details['user_id'], null, null, true, false, false) as $rConnection) { - CoreUtilities::closeConnection($rConnection); + if (SettingsManager::getAll()['redis_handler']) { + foreach (ConnectionTracker::getRedisConnections($rE2Details['user_id'], null, null, true, false, false) as $rConnection) { + ConnectionTracker::closeConnection($rConnection); } } else { $db->query('SELECT * FROM `lines_live` WHERE `user_id` = ?;', $rE2Details['user_id']); foreach ($db->get_rows() as $rRow) { - CoreUtilities::closeConnection($rRow); + ConnectionTracker::closeConnection($rRow); } } @@ -609,12 +609,12 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'mag_event') { + if (RequestManager::getAll()['action'] == 'mag_event') { if (Authorization::check('adv', 'manage_events')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - $db->query('DELETE FROM `mag_events` WHERE `id` = ?;', CoreUtilities::$rRequest['mag_id']); + $db->query('DELETE FROM `mag_events` WHERE `id` = ?;', RequestManager::getAll()['mag_id']); echo json_encode(array('result' => true)); exit(); @@ -629,7 +629,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'regenerate_cache') { + if (RequestManager::getAll()['action'] == 'regenerate_cache') { if (Authorization::check('adv', 'backups')) { shell_exec(PHP_BIN . ' ' . CRON_PATH . 'cache_engine.php "force"'); echo json_encode(array('result' => true)); @@ -641,7 +641,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'enable_cache') { + if (RequestManager::getAll()['action'] == 'enable_cache') { if (Authorization::check('adv', 'backups')) { $db->query('UPDATE `settings` SET `enable_cache` = 1;'); @@ -667,7 +667,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'disable_cache') { + if (RequestManager::getAll()['action'] == 'disable_cache') { if (Authorization::check('adv', 'backups')) { $db->query('UPDATE `settings` SET `enable_cache` = 0;'); @@ -686,19 +686,19 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'epg') { + if (RequestManager::getAll()['action'] == 'epg') { if (Authorization::check('adv', 'epg_edit')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteEPG(CoreUtilities::$rRequest['epg_id']); + deleteEPG(RequestManager::getAll()['epg_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'reload') { - shell_exec(PHP_BIN . ' ' . CRON_PATH . 'epg.php "' . intval(CoreUtilities::$rRequest['epg_id']) . '" > /dev/null 2>/dev/null &'); + shell_exec(PHP_BIN . ' ' . CRON_PATH . 'epg.php "' . intval(RequestManager::getAll()['epg_id']) . '" > /dev/null 2>/dev/null &'); echo json_encode(array('result' => true)); exit(); @@ -713,19 +713,19 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'provider') { + if (RequestManager::getAll()['action'] == 'provider') { if (Authorization::check('adv', 'streams')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteProvider(CoreUtilities::$rRequest['id']); + deleteProvider(RequestManager::getAll()['id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'reload') { - shell_exec(PHP_BIN . ' ' . CRON_PATH . 'providers.php "' . intval(CoreUtilities::$rRequest['id']) . '" > /dev/null 2>/dev/null &'); + shell_exec(PHP_BIN . ' ' . CRON_PATH . 'providers.php "' . intval(RequestManager::getAll()['id']) . '" > /dev/null 2>/dev/null &'); echo json_encode(array('result' => true)); exit(); @@ -740,12 +740,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'profile') { + if (RequestManager::getAll()['action'] == 'profile') { if (Authorization::check('adv', 'tprofiles')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteProfile(CoreUtilities::$rRequest['profile_id']); + deleteProfile(RequestManager::getAll()['profile_id']); echo json_encode(array('result' => true)); exit(); @@ -760,12 +760,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'series') { + if (RequestManager::getAll()['action'] == 'series') { if (Authorization::check('adv', 'edit_series')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteSeries(CoreUtilities::$rRequest['series_id']); + deleteSeries(RequestManager::getAll()['series_id']); echo json_encode(array('result' => true)); exit(); @@ -780,7 +780,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'kill_watch') { + if (RequestManager::getAll()['action'] == 'kill_watch') { if (Authorization::check('adv', 'folder_watch')) { WatchService::killWatch(); echo json_encode(array('result' => true)); @@ -792,7 +792,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'kill_plex') { + if (RequestManager::getAll()['action'] == 'kill_plex') { if (Authorization::check('adv', 'folder_watch')) { killPlexSync(); echo json_encode(array('result' => true)); @@ -804,19 +804,19 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'folder') { + if (RequestManager::getAll()['action'] == 'folder') { if (Authorization::check('adv', 'folder_watch')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteWatchFolder(CoreUtilities::$rRequest['folder_id']); + deleteWatchFolder(RequestManager::getAll()['folder_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'force') { - $rFolder = getWatchFolder(CoreUtilities::$rRequest['folder_id']); + $rFolder = getWatchFolder(RequestManager::getAll()['folder_id']); if ($rFolder) { WatchService::forceWatch($rFolder['server_id'], $rFolder['id']); @@ -839,22 +839,22 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'library') { + if (RequestManager::getAll()['action'] == 'library') { if (Authorization::check('adv', 'folder_watch')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteWatchFolder(CoreUtilities::$rRequest['folder_id']); + deleteWatchFolder(RequestManager::getAll()['folder_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'force') { - $rFolder = getWatchFolder(CoreUtilities::$rRequest['folder_id']); + $rFolder = getWatchFolder(RequestManager::getAll()['folder_id']); if ($rFolder) { - PlexService::forcePlex($rFolder['server_id'], $rFolder['id'], 'systemapirequest'); + PlexService::forcePlex($rFolder['server_id'], $rFolder['id']); echo json_encode(array('result' => true)); exit(); @@ -874,12 +874,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'useragent') { + if (RequestManager::getAll()['action'] == 'useragent') { if (Authorization::check('adv', 'block_uas')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - rdeleteBlockedUA(CoreUtilities::$rRequest['ua_id']); + rdeleteBlockedUA(RequestManager::getAll()['ua_id']); echo json_encode(array('result' => true)); exit(); @@ -894,12 +894,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'isp') { + if (RequestManager::getAll()['action'] == 'isp') { if (Authorization::check('adv', 'block_isps')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - rdeleteBlockedISP(CoreUtilities::$rRequest['isp_id']); + rdeleteBlockedISP(RequestManager::getAll()['isp_id']); echo json_encode(array('result' => true)); exit(); @@ -914,13 +914,13 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'mysql_syslog') { + if (RequestManager::getAll()['action'] == 'mysql_syslog') { if (Authorization::check('adv', 'block_ips')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; - if ($rSub == 'block' && filter_var(CoreUtilities::$rRequest['ip'], FILTER_VALIDATE_IP)) { - $db->query("INSERT INTO `blocked_ips`(`ip`, `notes`, `date`) VALUES(?, 'MySQL Bruteforce', ?);", CoreUtilities::$rRequest['ip'], time()); - touch(FLOOD_TMP_PATH . 'block_' . CoreUtilities::$rRequest['ip']); + if ($rSub == 'block' && filter_var(RequestManager::getAll()['ip'], FILTER_VALIDATE_IP)) { + $db->query("INSERT INTO `blocked_ips`(`ip`, `notes`, `date`) VALUES(?, 'MySQL Bruteforce', ?);", RequestManager::getAll()['ip'], time()); + touch(FLOOD_TMP_PATH . 'block_' . RequestManager::getAll()['ip']); echo json_encode(array('result' => true)); exit(); @@ -935,12 +935,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'ip') { + if (RequestManager::getAll()['action'] == 'ip') { if (Authorization::check('adv', 'block_ips')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - rdeleteBlockedIP(CoreUtilities::$rRequest['ip']); + rdeleteBlockedIP(RequestManager::getAll()['ip']); echo json_encode(array('result' => true)); exit(); @@ -955,12 +955,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'rtmp_ip') { + if (RequestManager::getAll()['action'] == 'rtmp_ip') { if (Authorization::check('adv', 'add_rtmp')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteRTMPIP(CoreUtilities::$rRequest['ip']); + deleteRTMPIP(RequestManager::getAll()['ip']); echo json_encode(array('result' => true)); exit(); @@ -975,12 +975,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'watch_output') { + if (RequestManager::getAll()['action'] == 'watch_output') { if (Authorization::check('adv', 'folder_watch_output')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - $db->query('DELETE FROM `watch_logs` WHERE `id` = ?;', CoreUtilities::$rRequest['result_id']); + $db->query('DELETE FROM `watch_logs` WHERE `id` = ?;', RequestManager::getAll()['result_id']); echo json_encode(array('result' => true)); exit(); @@ -995,13 +995,13 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'server') { + if (RequestManager::getAll()['action'] == 'server') { if (Authorization::check('adv', 'edit_server')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - if ($rServers[CoreUtilities::$rRequest['server_id']]['is_main'] == 0) { - ServerRepository::deleteById(CoreUtilities::$rSettings, 'getStreamingServersByID', CoreUtilities::$rRequest['server_id']); + if ($rServers[RequestManager::getAll()['server_id']]['is_main'] == 0) { + ServerRepository::deleteById(RequestManager::getAll()['server_id']); echo json_encode(array('result' => true)); exit(); @@ -1013,10 +1013,10 @@ if (isset($_SESSION['hash'])) { } if ($rSub == 'update') { - if (!is_numeric(CoreUtilities::$rRequest['server_id'])) { - $rIDs = json_decode(CoreUtilities::$rRequest['server_id'], true); + if (!is_numeric(RequestManager::getAll()['server_id'])) { + $rIDs = json_decode(RequestManager::getAll()['server_id'], true); } else { - $rIDs = array(intval(CoreUtilities::$rRequest['server_id'])); + $rIDs = array(intval(RequestManager::getAll()['server_id'])); } foreach ($rIDs as $rID) { @@ -1028,43 +1028,43 @@ if (isset($_SESSION['hash'])) { } if ($rSub == 'enable') { - $db->query('UPDATE `servers` SET `enabled` = 1 WHERE `id` = ?;', CoreUtilities::$rRequest['server_id']); + $db->query('UPDATE `servers` SET `enabled` = 1 WHERE `id` = ?;', RequestManager::getAll()['server_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'disable') { - $db->query('UPDATE `servers` SET `enabled` = 0 WHERE `id` = ? AND `is_main` = 0;', CoreUtilities::$rRequest['server_id']); + $db->query('UPDATE `servers` SET `enabled` = 0 WHERE `id` = ? AND `is_main` = 0;', RequestManager::getAll()['server_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'enable_proxy') { - $db->query('UPDATE `servers` SET `enable_proxy` = 1 WHERE `id` = ?;', CoreUtilities::$rRequest['server_id']); + $db->query('UPDATE `servers` SET `enable_proxy` = 1 WHERE `id` = ?;', RequestManager::getAll()['server_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'disable_proxy') { - $db->query('UPDATE `servers` SET `enable_proxy` = 0 WHERE `id` = ?;', CoreUtilities::$rRequest['server_id']); + $db->query('UPDATE `servers` SET `enable_proxy` = 0 WHERE `id` = ?;', RequestManager::getAll()['server_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'kill') { - if (CoreUtilities::$rSettings['redis_handler']) { - foreach (CoreUtilities::getRedisConnections(null, CoreUtilities::$rRequest['server_id'], null, true, false, false) as $rConnection) { - CoreUtilities::closeConnection($rConnection); + if (SettingsManager::getAll()['redis_handler']) { + foreach (ConnectionTracker::getRedisConnections(null, RequestManager::getAll()['server_id'], null, true, false, false) as $rConnection) { + ConnectionTracker::closeConnection($rConnection); } } else { - $db->query('SELECT * FROM `lines_live` WHERE `server_id` = ?;', CoreUtilities::$rRequest['server_id']); + $db->query('SELECT * FROM `lines_live` WHERE `server_id` = ?;', RequestManager::getAll()['server_id']); foreach ($db->get_rows() as $rRow) { - CoreUtilities::closeConnection($rRow); + ConnectionTracker::closeConnection($rRow); } } @@ -1075,7 +1075,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'restart') { $rStreamIDs = array(); - $db->query('SELECT `stream_id` FROM `streams_servers` WHERE `server_id` = ? AND `on_demand` = 0 AND `monitor_pid` > 0 AND `pid` > 0 AND `stream_status` = 0;', CoreUtilities::$rRequest['server_id']); + $db->query('SELECT `stream_id` FROM `streams_servers` WHERE `server_id` = ? AND `on_demand` = 0 AND `monitor_pid` > 0 AND `pid` > 0 AND `stream_status` = 0;', RequestManager::getAll()['server_id']); if (0 >= $db->num_rows()) { } else { @@ -1086,7 +1086,7 @@ if (isset($_SESSION['hash'])) { if (0 >= count($rStreamIDs)) { } else { - $rResult = APIRequest(array('action' => 'stream', 'sub' => 'start', 'stream_ids' => array_values($rStreamIDs), 'servers' => array(intval(CoreUtilities::$rRequest['server_id'])))); + $rResult = APIRequest(array('action' => 'stream', 'sub' => 'start', 'stream_ids' => array_values($rStreamIDs), 'servers' => array(intval(RequestManager::getAll()['server_id'])))); } echo json_encode(array('result' => true)); @@ -1096,7 +1096,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'start') { $rStreamIDs = array(); - $db->query('SELECT `stream_id` FROM `streams_servers` WHERE `server_id` = ? AND `on_demand` = 0;', CoreUtilities::$rRequest['server_id']); + $db->query('SELECT `stream_id` FROM `streams_servers` WHERE `server_id` = ? AND `on_demand` = 0;', RequestManager::getAll()['server_id']); if (0 >= $db->num_rows()) { } else { @@ -1107,7 +1107,7 @@ if (isset($_SESSION['hash'])) { if (0 >= count($rStreamIDs)) { } else { - $rResult = APIRequest(array('action' => 'stream', 'sub' => 'start', 'stream_ids' => array_values($rStreamIDs), 'servers' => array(intval(CoreUtilities::$rRequest['server_id'])))); + $rResult = APIRequest(array('action' => 'stream', 'sub' => 'start', 'stream_ids' => array_values($rStreamIDs), 'servers' => array(intval(RequestManager::getAll()['server_id'])))); } echo json_encode(array('result' => true)); @@ -1117,7 +1117,7 @@ if (isset($_SESSION['hash'])) { if ($rSub == 'stop') { $rStreamIDs = array(); - $db->query('SELECT `stream_id` FROM `streams_servers` WHERE `server_id` = ? AND `on_demand` = 0;', CoreUtilities::$rRequest['server_id']); + $db->query('SELECT `stream_id` FROM `streams_servers` WHERE `server_id` = ? AND `on_demand` = 0;', RequestManager::getAll()['server_id']); if (0 >= $db->num_rows()) { } else { @@ -1128,7 +1128,7 @@ if (isset($_SESSION['hash'])) { if (0 >= count($rStreamIDs)) { } else { - $rResult = APIRequest(array('action' => 'stream', 'sub' => 'stop', 'stream_ids' => array_values($rStreamIDs), 'servers' => array(intval(CoreUtilities::$rRequest['server_id'])))); + $rResult = APIRequest(array('action' => 'stream', 'sub' => 'stop', 'stream_ids' => array_values($rStreamIDs), 'servers' => array(intval(RequestManager::getAll()['server_id'])))); } echo json_encode(array('result' => true)); @@ -1143,53 +1143,53 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'proxy') { + if (RequestManager::getAll()['action'] == 'proxy') { if (Authorization::check('adv', 'edit_server')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - ServerRepository::deleteById(CoreUtilities::$rSettings, 'getStreamingServersByID', CoreUtilities::$rRequest['server_id']); + ServerRepository::deleteById(RequestManager::getAll()['server_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'enable') { - $db->query('UPDATE `servers` SET `enabled` = 1 WHERE `id` = ?;', CoreUtilities::$rRequest['server_id']); + $db->query('UPDATE `servers` SET `enabled` = 1 WHERE `id` = ?;', RequestManager::getAll()['server_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'disable') { - $db->query('UPDATE `servers` SET `enabled` = 0 WHERE `id` = ?;', CoreUtilities::$rRequest['server_id']); + $db->query('UPDATE `servers` SET `enabled` = 0 WHERE `id` = ?;', RequestManager::getAll()['server_id']); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'update') { - $db->query('INSERT INTO `signals`(`server_id`, `time`, `custom_data`) VALUES(?, ?, ?);', CoreUtilities::$rRequest['server_id'], time(), json_encode(array('action' => 'update'))); + $db->query('INSERT INTO `signals`(`server_id`, `time`, `custom_data`) VALUES(?, ?, ?);', RequestManager::getAll()['server_id'], time(), json_encode(array('action' => 'update'))); echo json_encode(array('result' => true)); exit(); } if ($rSub == 'kill') { - if (CoreUtilities::$rSettings['redis_handler']) { - foreach (CoreUtilities::$rServers[$rServerID]['parent_id'] as $rParentID) { - foreach (CoreUtilities::getRedisConnections(null, $rParentID, null, true, false, false) as $rConnection) { - if ($rConnection['proxy_id'] != CoreUtilities::$rRequest['server_id']) { + if (SettingsManager::getAll()['redis_handler']) { + foreach (ServerRepository::getAll()[$rServerID]['parent_id'] as $rParentID) { + foreach (ConnectionTracker::getRedisConnections(null, $rParentID, null, true, false, false) as $rConnection) { + if ($rConnection['proxy_id'] != RequestManager::getAll()['server_id']) { } else { - CoreUtilities::closeConnection($rConnection); + ConnectionTracker::closeConnection($rConnection); } } } } else { - $db->query('SELECT * FROM `lines_live` WHERE `proxy_id` = ?;', CoreUtilities::$rRequest['server_id']); + $db->query('SELECT * FROM `lines_live` WHERE `proxy_id` = ?;', RequestManager::getAll()['server_id']); foreach ($db->get_rows() as $rRow) { - CoreUtilities::closeConnection($rRow); + ConnectionTracker::closeConnection($rRow); } } @@ -1207,19 +1207,19 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'package') { + if (RequestManager::getAll()['action'] == 'package') { if (Authorization::check('adv', 'edit_package')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - PackageService::deleteById('getPackage', CoreUtilities::$rRequest['package_id']); + PackageService::deleteById(RequestManager::getAll()['package_id']); echo json_encode(array('result' => true)); exit(); } if (in_array($rSub, array('is_trial', 'is_official', 'can_gen_mag', 'can_gen_e2', 'only_mag', 'only_e2'))) { - $db->query('UPDATE `users_packages` SET ? = ? WHERE `id` = ?;', $rSub, CoreUtilities::$rRequest['value'], CoreUtilities::$rRequest['package_id']); + $db->query('UPDATE `users_packages` SET ? = ? WHERE `id` = ?;', $rSub, RequestManager::getAll()['value'], RequestManager::getAll()['package_id']); echo json_encode(array('result' => true)); exit(); @@ -1234,12 +1234,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'code') { + if (RequestManager::getAll()['action'] == 'code') { if (Authorization::check('adv', 'add_code')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - removeAccessEntry(CoreUtilities::$rRequest['code_id']); + removeAccessEntry(RequestManager::getAll()['code_id']); echo json_encode(array('result' => true)); exit(); @@ -1254,12 +1254,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'hmac') { + if (RequestManager::getAll()['action'] == 'hmac') { if (Authorization::check('adv', 'add_hmac')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - validateHMAC(CoreUtilities::$rRequest['hmac_id']); + validateHMAC(RequestManager::getAll()['hmac_id']); echo json_encode(array('result' => true)); exit(); @@ -1274,19 +1274,19 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'group') { + if (RequestManager::getAll()['action'] == 'group') { if (Authorization::check('adv', 'edit_group')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - GroupService::deleteById(CoreUtilities::$rRequest['group_id']); + GroupService::deleteById(RequestManager::getAll()['group_id']); echo json_encode(array('result' => true)); exit(); } if (in_array($rSub, array('is_admin', 'is_reseller'))) { - $db->query('UPDATE `users_groups` SET ? = ? WHERE `group_id` = ?;', $rSub, CoreUtilities::$rRequest['value'], CoreUtilities::$rRequest['group_id']); + $db->query('UPDATE `users_groups` SET ? = ? WHERE `group_id` = ?;', $rSub, RequestManager::getAll()['value'], RequestManager::getAll()['group_id']); echo json_encode(array('result' => true)); exit(); @@ -1301,12 +1301,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'bouquet') { + if (RequestManager::getAll()['action'] == 'bouquet') { if (Authorization::check('adv', 'edit_bouquet')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteBouquet(CoreUtilities::$rRequest['bouquet_id']); + deleteBouquet(RequestManager::getAll()['bouquet_id']); echo json_encode(array('result' => true)); exit(); @@ -1321,12 +1321,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'category') { + if (RequestManager::getAll()['action'] == 'category') { if (Authorization::check('adv', 'edit_cat')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - deleteCategory(CoreUtilities::$rRequest['category_id']); + deleteCategory(RequestManager::getAll()['category_id']); echo json_encode(array('result' => true)); exit(); @@ -1341,10 +1341,10 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'get_package') { + if (RequestManager::getAll()['action'] == 'get_package') { $rReturn = array(); $rOverride = json_decode($rUserInfo['override_packages'], true); - $db->query('SELECT `id`, `bouquets`, `official_credits` AS `cost_credits`, `official_duration`, `official_duration_in`, `max_connections`, `can_gen_mag`, `can_gen_e2`, `only_mag`, `only_e2` FROM `users_packages` WHERE `id` = ?;', CoreUtilities::$rRequest['package_id']); + $db->query('SELECT `id`, `bouquets`, `official_credits` AS `cost_credits`, `official_duration`, `official_duration_in`, `max_connections`, `can_gen_mag`, `can_gen_e2`, `only_mag`, `only_e2` FROM `users_packages` WHERE `id` = ?;', RequestManager::getAll()['package_id']); if ($db->num_rows() == 1) { $rData = $db->get_row(); @@ -1356,9 +1356,9 @@ if (isset($_SESSION['hash'])) { $rData['exp_date'] = date('Y-m-d', strtotime('+' . intval($rData['official_duration']) . ' ' . $rData['official_duration_in'])); - if (!isset(CoreUtilities::$rRequest['user_id'])) { + if (!isset(RequestManager::getAll()['user_id'])) { } else { - if (!($rUser = UserRepository::getLineById(CoreUtilities::$rRequest['user_id']))) { + if (!($rUser = UserRepository::getLineById(RequestManager::getAll()['user_id']))) { } else { if (time() < $rUser['exp_date']) { $rData['exp_date'] = date('Y-m-d', strtotime('+' . intval($rData['official_duration']) . ' ' . $rData['official_duration_in'], $rUser['exp_date'])); @@ -1384,9 +1384,9 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'get_package_trial') { + if (RequestManager::getAll()['action'] == 'get_package_trial') { $rReturn = array(); - $db->query('SELECT `bouquets`, `trial_credits` AS `cost_credits`, `trial_duration`, `trial_duration_in`, `max_connections`, `can_gen_mag`, `can_gen_e2`, `only_mag`, `only_e2` FROM `users_packages` WHERE `id` = ?;', CoreUtilities::$rRequest['package_id']); + $db->query('SELECT `bouquets`, `trial_credits` AS `cost_credits`, `trial_duration`, `trial_duration_in`, `max_connections`, `can_gen_mag`, `can_gen_e2`, `only_mag`, `only_e2` FROM `users_packages` WHERE `id` = ?;', RequestManager::getAll()['package_id']); if ($db->num_rows() == 1) { $rData = $db->get_row(); @@ -1408,7 +1408,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'graph_stats') { + if (RequestManager::getAll()['action'] == 'graph_stats') { $rLimit = 3600; $rTime = roundUpToAny(time(), 10); $rNearestRange = $rTime - $rLimit; @@ -1420,8 +1420,8 @@ if (isset($_SESSION['hash'])) { } $rServerStats = array(); - if (isset(CoreUtilities::$rRequest['server_id'])) { - $db->query('SELECT `server_id`, `time`, `cpu`, `iostat_info`, `total_mem_used_percent`, `connections`, `streams`, `users`, `total_users`, `bytes_received`, `bytes_sent` FROM `servers_stats` WHERE `time` >= ? AND `server_id` = ? ORDER BY `time` DESC;', $rNearestRange, CoreUtilities::$rRequest['server_id']); + if (isset(RequestManager::getAll()['server_id'])) { + $db->query('SELECT `server_id`, `time`, `cpu`, `iostat_info`, `total_mem_used_percent`, `connections`, `streams`, `users`, `total_users`, `bytes_received`, `bytes_sent` FROM `servers_stats` WHERE `time` >= ? AND `server_id` = ? ORDER BY `time` DESC;', $rNearestRange, RequestManager::getAll()['server_id']); } else { $db->query('SELECT `server_id`, `time`, `cpu`, `iostat_info`, `total_mem_used_percent`, `connections`, `streams`, `users`, `total_users`, `bytes_received`, `bytes_sent` FROM `servers_stats` WHERE `server_id` IN (SELECT `id` FROM `servers` WHERE `server_type` = 0) AND `time` >= ? ORDER BY `time` DESC;', $rNearestRange); } @@ -1456,8 +1456,8 @@ if (isset($_SESSION['hash'])) { $rTotalStreams = 0; $rTotalUsers = 0; - if (isset(CoreUtilities::$rRequest['server_id'])) { - $rTotalUsers = $rServerStats[$rTime][CoreUtilities::$rRequest['server_id']]['users']; + if (isset(RequestManager::getAll()['server_id'])) { + $rTotalUsers = $rServerStats[$rTime][RequestManager::getAll()['server_id']]['users']; } else { $rTotalUsers = $rServerStats[$rTime][SERVER_ID]['total_users']; } @@ -1503,13 +1503,13 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'stats') { + if (RequestManager::getAll()['action'] == 'stats') { if (Authorization::check('adv', 'index')) { - $rServers = CoreUtilities::getServers(true); + $rServers = ServerRepository::getAll(true); $rReturn = array('cpu' => 0, 'mem' => 0, 'io' => 0, 'fs' => 0, 'uptime' => '--', 'bytes_sent' => 0, 'bytes_received' => 0, 'open_connections' => 0, 'total_connections' => 0, 'online_users' => 0, 'total_users' => 0, 'total_streams' => 0, 'total_running_streams' => 0, 'offline_streams' => 0, 'requests_per_second' => 0, 'servers' => array()); - if (CoreUtilities::$rSettings['redis_handler']) { - $rReturn['total_users'] = CoreUtilities::$rSettings['total_users']; + if (SettingsManager::getAll()['redis_handler']) { + $rReturn['total_users'] = SettingsManager::getAll()['total_users']; } else { $db->query('SELECT `activity_id` FROM `lines_live` WHERE `hls_end` = 0 GROUP BY `user_id`;'); @@ -1519,8 +1519,8 @@ if (isset($_SESSION['hash'])) { } } - if (isset(CoreUtilities::$rRequest['server_id'])) { - $rServerID = intval(CoreUtilities::$rRequest['server_id']); + if (isset(RequestManager::getAll()['server_id'])) { + $rServerID = intval(RequestManager::getAll()['server_id']); $rWatchDog = json_decode($rServers[$rServerID]['watchdog_data'], true); if (!is_array($rWatchDog)) { @@ -1545,7 +1545,7 @@ if (isset($_SESSION['hash'])) { $rReturn['requests_per_second'] = $rServers[$rServerID]['requests_per_second']; - if (CoreUtilities::$rSettings['redis_handler']) { + if (SettingsManager::getAll()['redis_handler']) { $rReturn['open_connections'] = $rServers[$rServerID]['connections']; $rReturn['online_users'] = $rServers[$rServerID]['users']; @@ -1603,7 +1603,7 @@ if (isset($_SESSION['hash'])) { } else { $rUptime = 0; - if (!CoreUtilities::$rSettings['redis_handler']) { + if (!SettingsManager::getAll()['redis_handler']) { $db->query('SELECT COUNT(*) AS `count` FROM `lines_live` WHERE `hls_end` = 0;'); if (0 < $db->num_rows()) { @@ -1656,7 +1656,7 @@ if (isset($_SESSION['hash'])) { if ($rServers[$rServerID]['server_online']) { $rArray = array(); - if (CoreUtilities::$rSettings['redis_handler']) { + if (SettingsManager::getAll()['redis_handler']) { $rArray['open_connections'] = $rServers[$rServerID]['connections']; $rReturn['open_connections'] += $rServers[$rServerID]['connections']; $rReturn['total_connections'] += $rServers[$rServerID]['connections']; @@ -1706,7 +1706,7 @@ if (isset($_SESSION['hash'])) { $rReturn['total_running_streams'] += $rServerArray['total_running_streams']; $rReturn['offline_streams'] += $rServerArray['offline_streams']; } - $rReturn['online_users'] = CoreUtilities::$rSettings['total_users']; + $rReturn['online_users'] = SettingsManager::getAll()['total_users']; } echo json_encode($rReturn, JSON_PARTIAL_OUTPUT_ON_ERROR); @@ -1718,11 +1718,11 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'header_stats') { + if (RequestManager::getAll()['action'] == 'header_stats') { if (Authorization::check('adv', 'index')) { $rReturn = array('bytes_sent' => 0, 'bytes_received' => 0, 'total_connections' => 0, 'total_users' => 0, 'total_running_streams' => 0, 'offline_streams' => 0); - if (!CoreUtilities::$rSettings['redis_handler']) { + if (!SettingsManager::getAll()['redis_handler']) { $db->query('SELECT COUNT(*) AS `count` FROM `lines_live` WHERE `hls_end` = 0;'); if (0 >= $db->num_rows()) { @@ -1737,7 +1737,7 @@ if (isset($_SESSION['hash'])) { $rReturn['total_users'] = $db->num_rows(); } } else { - $rReturn['total_users'] = CoreUtilities::$rSettings['total_users']; + $rReturn['total_users'] = SettingsManager::getAll()['total_users']; } $rOnlineCount = $rOfflineCount = array(); @@ -1755,7 +1755,7 @@ if (isset($_SESSION['hash'])) { foreach (array_keys($rServers) as $rServerID) { if (!$rServers[$rServerID]['server_online']) { } else { - if (!CoreUtilities::$rSettings['redis_handler']) { + if (!SettingsManager::getAll()['redis_handler']) { } else { $rReturn['total_connections'] += $rServers[$rServerID]['connections']; } @@ -1780,13 +1780,13 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'review_selection') { + if (RequestManager::getAll()['action'] == 'review_selection') { if (Authorization::check('adv', 'edit_cchannel') || Authorization::check('adv', 'create_channel')) { $rReturn = array('streams' => array(), 'result' => true); - if (!isset(CoreUtilities::$rRequest['data'])) { + if (!isset(RequestManager::getAll()['data'])) { } else { - foreach (CoreUtilities::$rRequest['data'] as $rStreamID) { + foreach (RequestManager::getAll()['data'] as $rStreamID) { $db->query('SELECT `id`, `stream_display_name`, `stream_source` FROM `streams` WHERE `id` = ?;', $rStreamID); if ($db->num_rows() != 1) { @@ -1805,13 +1805,13 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'review_bouquet') { + if (RequestManager::getAll()['action'] == 'review_bouquet') { if (Authorization::check('adv', 'edit_bouquet') || Authorization::check('adv', 'add_bouquet')) { $rReturn = array('streams' => array(), 'movies' => array(), 'series' => array(), 'radios' => array(), 'result' => true); - if (!isset(CoreUtilities::$rRequest['data']['stream'])) { + if (!isset(RequestManager::getAll()['data']['stream'])) { } else { - foreach (CoreUtilities::$rRequest['data']['stream'] as $rStreamID) { + foreach (RequestManager::getAll()['data']['stream'] as $rStreamID) { $db->query('SELECT `id`, `stream_display_name`, `type` FROM `streams` WHERE `id` = ? AND `type` IN (1,3);', $rStreamID); if ($db->num_rows() != 1) { @@ -1822,9 +1822,9 @@ if (isset($_SESSION['hash'])) { } } - if (!isset(CoreUtilities::$rRequest['data']['movies'])) { + if (!isset(RequestManager::getAll()['data']['movies'])) { } else { - foreach (CoreUtilities::$rRequest['data']['movies'] as $rStreamID) { + foreach (RequestManager::getAll()['data']['movies'] as $rStreamID) { $db->query('SELECT `id`, `stream_display_name`, `type` FROM `streams` WHERE `id` = ? AND `type` = 2;', $rStreamID); if ($db->num_rows() != 1) { @@ -1835,9 +1835,9 @@ if (isset($_SESSION['hash'])) { } } - if (!isset(CoreUtilities::$rRequest['data']['radios'])) { + if (!isset(RequestManager::getAll()['data']['radios'])) { } else { - foreach (CoreUtilities::$rRequest['data']['radios'] as $rStreamID) { + foreach (RequestManager::getAll()['data']['radios'] as $rStreamID) { $db->query('SELECT `id`, `stream_display_name`, `type` FROM `streams` WHERE `id` = ? AND `type` = 4;', $rStreamID); if ($db->num_rows() != 1) { @@ -1848,9 +1848,9 @@ if (isset($_SESSION['hash'])) { } } - if (!isset(CoreUtilities::$rRequest['data']['series'])) { + if (!isset(RequestManager::getAll()['data']['series'])) { } else { - foreach (CoreUtilities::$rRequest['data']['series'] as $rSeriesID) { + foreach (RequestManager::getAll()['data']['series'] as $rSeriesID) { $db->query('SELECT `id`, `title` FROM `streams_series` WHERE `id` = ?;', $rSeriesID); if ($db->num_rows() != 1) { @@ -1870,14 +1870,14 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'epglist') { + if (RequestManager::getAll()['action'] == 'epglist') { if (Authorization::check('adv', 'import_streams')) { $rGroups = array(); $rReturn = array('total_count' => 0, 'items' => array(), 'result' => true); - if (isset(CoreUtilities::$rRequest['search'])) { + if (isset(RequestManager::getAll()['search'])) { $rEPGNames = $rEPGMap = array(); - $db->query('SELECT `epg_channels`.`epg_id`, `epg_channels`.`channel_id`, `epg_channels`.`name`, `epg_channels`.`langs`, `epg`.`epg_name` FROM `epg_channels` LEFT JOIN `epg` ON `epg_channels`.`epg_id` = `epg`.`id` WHERE (LOWER(`epg_channels`.`channel_id`) LIKE ? OR LOWER(`epg_channels`.`name`) LIKE ?) ORDER BY `epg_channels`.`name` ASC LIMIT 50;', strtolower(CoreUtilities::$rRequest['search']) . '%', strtolower(CoreUtilities::$rRequest['search']) . '%'); + $db->query('SELECT `epg_channels`.`epg_id`, `epg_channels`.`channel_id`, `epg_channels`.`name`, `epg_channels`.`langs`, `epg`.`epg_name` FROM `epg_channels` LEFT JOIN `epg` ON `epg_channels`.`epg_id` = `epg`.`id` WHERE (LOWER(`epg_channels`.`channel_id`) LIKE ? OR LOWER(`epg_channels`.`name`) LIKE ?) ORDER BY `epg_channels`.`name` ASC LIMIT 50;', strtolower(RequestManager::getAll()['search']) . '%', strtolower(RequestManager::getAll()['search']) . '%'); foreach ($db->get_rows() as $rRow) { if (isset($rEPGNames[$rRow['epg_id']])) { @@ -1904,21 +1904,21 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'serieslist') { + if (RequestManager::getAll()['action'] == 'serieslist') { if (Authorization::check('adv', 'episodes')) { $rReturn = array('total_count' => 0, 'items' => array(), 'result' => true); - if (!isset(CoreUtilities::$rRequest['search'])) { + if (!isset(RequestManager::getAll()['search'])) { } else { - if (isset(CoreUtilities::$rRequest['page'])) { - $rPage = intval(CoreUtilities::$rRequest['page']); + if (isset(RequestManager::getAll()['page'])) { + $rPage = intval(RequestManager::getAll()['page']); } else { $rPage = 1; } - $db->query('SELECT COUNT(`id`) AS `count` FROM `streams_series` WHERE `title` LIKE ?;', '%' . CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT COUNT(`id`) AS `count` FROM `streams_series` WHERE `title` LIKE ?;', '%' . RequestManager::getAll()['search'] . '%'); $rReturn['total_count'] = $db->get_row()['count']; - $db->query('SELECT `id`, `title` FROM `streams_series` WHERE `title` LIKE ? ORDER BY `title` ASC LIMIT ' . ($rPage - 1) * 100 . ', 100;', '%' . CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT `id`, `title` FROM `streams_series` WHERE `title` LIKE ? ORDER BY `title` ASC LIMIT ' . ($rPage - 1) * 100 . ', 100;', '%' . RequestManager::getAll()['search'] . '%'); if (0 >= $db->num_rows()) { } else { @@ -1937,21 +1937,21 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'reguserlist') { + if (RequestManager::getAll()['action'] == 'reguserlist') { if (Authorization::check('adv', 'mng_regusers') || Authorization::check('adv', 'manage_mag') || Authorization::check('adv', 'manage_e2') || Authorization::check('adv', 'edit_e2') || Authorization::check('adv', 'add_e2') || Authorization::check('adv', 'add_mag') || Authorization::check('adv', 'edit_mag')) { $rReturn = array('total_count' => 0, 'items' => array(), 'result' => true); - if (!isset(CoreUtilities::$rRequest['search'])) { + if (!isset(RequestManager::getAll()['search'])) { } else { - if (isset(CoreUtilities::$rRequest['page'])) { - $rPage = intval(CoreUtilities::$rRequest['page']); + if (isset(RequestManager::getAll()['page'])) { + $rPage = intval(RequestManager::getAll()['page']); } else { $rPage = 1; } - $db->query('SELECT COUNT(`id`) AS `id` FROM `users` WHERE `username` LIKE ?;', '%' . CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT COUNT(`id`) AS `id` FROM `users` WHERE `username` LIKE ?;', '%' . RequestManager::getAll()['search'] . '%'); $rReturn['total_count'] = $db->get_row()['id']; - $db->query('SELECT `id`, `username` FROM `users` WHERE `username` LIKE ? ORDER BY `username` ASC LIMIT ' . ($rPage - 1) * 100 . ', 100;', '%' . CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT `id`, `username` FROM `users` WHERE `username` LIKE ? ORDER BY `username` ASC LIMIT ' . ($rPage - 1) * 100 . ', 100;', '%' . RequestManager::getAll()['search'] . '%'); if (0 >= $db->num_rows()) { } else { @@ -1970,25 +1970,25 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'userlist') { + if (RequestManager::getAll()['action'] == 'userlist') { if (Authorization::check('adv', 'edit_e2') || Authorization::check('adv', 'add_e2') || Authorization::check('adv', 'add_mag') || Authorization::check('adv', 'edit_mag')) { $rReturn = array('total_count' => 0, 'items' => array(), 'result' => true); - if (!isset(CoreUtilities::$rRequest['search'])) { + if (!isset(RequestManager::getAll()['search'])) { } else { - if (isset(CoreUtilities::$rRequest['page'])) { - $rPage = intval(CoreUtilities::$rRequest['page']); + if (isset(RequestManager::getAll()['page'])) { + $rPage = intval(RequestManager::getAll()['page']); } else { $rPage = 1; } - $db->query('SELECT COUNT(`id`) AS `id` FROM `lines` WHERE `username` LIKE ? AND `is_e2` = 0 AND `is_mag` = 0;', CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT COUNT(`id`) AS `id` FROM `lines` WHERE `username` LIKE ? AND `is_e2` = 0 AND `is_mag` = 0;', RequestManager::getAll()['search'] . '%'); $rReturn['total_count'] = $db->get_row()['id']; - $db->query('SELECT COUNT(`device_id`) AS `id` FROM `enigma2_devices` WHERE `mac` LIKE ?;', CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT COUNT(`device_id`) AS `id` FROM `enigma2_devices` WHERE `mac` LIKE ?;', RequestManager::getAll()['search'] . '%'); $rReturn['total_count'] += $db->get_row()['id']; - $db->query('SELECT COUNT(`mag_id`) AS `id` FROM `mag_devices` WHERE `mac` LIKE ?;', CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT COUNT(`mag_id`) AS `id` FROM `mag_devices` WHERE `mac` LIKE ?;', RequestManager::getAll()['search'] . '%'); $rReturn['total_count'] += $db->get_row()['id']; - $db->query('SELECT `id`, IF(`lines`.`is_mag`, `mag_devices`.`mac`, IF(`lines`.`is_e2`, `enigma2_devices`.`mac`, `lines`.`username`)) AS `username` FROM `lines` LEFT JOIN `mag_devices` ON `mag_devices`.`user_id` = `lines`.`id` LEFT JOIN `enigma2_devices` ON `enigma2_devices`.`user_id` = `lines`.`id` WHERE `lines`.`username` LIKE ? OR `mag_devices`.`mac` LIKE ? OR `enigma2_devices`.`mac` LIKE ? ORDER BY `username` ASC LIMIT ' . ($rPage - 1) * 100 . ', 100;', CoreUtilities::$rRequest['search'] . '%', CoreUtilities::$rRequest['search'] . '%', CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT `id`, IF(`lines`.`is_mag`, `mag_devices`.`mac`, IF(`lines`.`is_e2`, `enigma2_devices`.`mac`, `lines`.`username`)) AS `username` FROM `lines` LEFT JOIN `mag_devices` ON `mag_devices`.`user_id` = `lines`.`id` LEFT JOIN `enigma2_devices` ON `enigma2_devices`.`user_id` = `lines`.`id` WHERE `lines`.`username` LIKE ? OR `mag_devices`.`mac` LIKE ? OR `enigma2_devices`.`mac` LIKE ? ORDER BY `username` ASC LIMIT ' . ($rPage - 1) * 100 . ', 100;', RequestManager::getAll()['search'] . '%', RequestManager::getAll()['search'] . '%', RequestManager::getAll()['search'] . '%'); if (0 >= $db->num_rows()) { } else { @@ -2007,21 +2007,21 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'streamlist') { + if (RequestManager::getAll()['action'] == 'streamlist') { if (Authorization::check('adv', 'manage_mag')) { $rReturn = array('total_count' => 0, 'items' => array(), 'result' => true); - if (!isset(CoreUtilities::$rRequest['search'])) { + if (!isset(RequestManager::getAll()['search'])) { } else { - if (isset(CoreUtilities::$rRequest['page'])) { - $rPage = intval(CoreUtilities::$rRequest['page']); + if (isset(RequestManager::getAll()['page'])) { + $rPage = intval(RequestManager::getAll()['page']); } else { $rPage = 1; } - $db->query('SELECT COUNT(`id`) AS `id` FROM `streams` WHERE `stream_display_name` LIKE ?;', '%' . CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT COUNT(`id`) AS `id` FROM `streams` WHERE `stream_display_name` LIKE ?;', '%' . RequestManager::getAll()['search'] . '%'); $rReturn['total_count'] = $db->get_row()['id']; - $db->query('SELECT `id`, `stream_display_name` FROM `streams` WHERE `stream_display_name` LIKE ? ORDER BY `stream_display_name` ASC LIMIT ' . ($rPage - 1) * 100 . ', 100;', '%' . CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT `id`, `stream_display_name` FROM `streams` WHERE `stream_display_name` LIKE ? ORDER BY `stream_display_name` ASC LIMIT ' . ($rPage - 1) * 100 . ', 100;', '%' . RequestManager::getAll()['search'] . '%'); if (0 >= $db->num_rows()) { } else { @@ -2040,21 +2040,21 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'adaptivelist') { + if (RequestManager::getAll()['action'] == 'adaptivelist') { if (Authorization::check('adv', 'edit_stream')) { $rReturn = array('total_count' => 0, 'items' => array(), 'result' => true); - if (!isset(CoreUtilities::$rRequest['search'])) { + if (!isset(RequestManager::getAll()['search'])) { } else { - if (isset(CoreUtilities::$rRequest['page'])) { - $rPage = intval(CoreUtilities::$rRequest['page']); + if (isset(RequestManager::getAll()['page'])) { + $rPage = intval(RequestManager::getAll()['page']); } else { $rPage = 1; } - $db->query('SELECT COUNT(`id`) AS `id` FROM `streams` WHERE (`stream_display_name` LIKE ? OR `id` LIKE ?) AND `type` = 1;', '%' . CoreUtilities::$rRequest['search'] . '%', CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT COUNT(`id`) AS `id` FROM `streams` WHERE (`stream_display_name` LIKE ? OR `id` LIKE ?) AND `type` = 1;', '%' . RequestManager::getAll()['search'] . '%', RequestManager::getAll()['search'] . '%'); $rReturn['total_count'] = $db->get_row()['id']; - $db->query('SELECT `id`, `stream_display_name` FROM `streams` WHERE (`stream_display_name` LIKE ? OR `id` LIKE ?) AND `type` = 1 ORDER BY `stream_display_name` ASC LIMIT ' . ($rPage - 1) * 100 . ', 100;', '%' . CoreUtilities::$rRequest['search'] . '%', CoreUtilities::$rRequest['search'] . '%'); + $db->query('SELECT `id`, `stream_display_name` FROM `streams` WHERE (`stream_display_name` LIKE ? OR `id` LIKE ?) AND `type` = 1 ORDER BY `stream_display_name` ASC LIMIT ' . ($rPage - 1) * 100 . ', 100;', '%' . RequestManager::getAll()['search'] . '%', RequestManager::getAll()['search'] . '%'); if (0 >= $db->num_rows()) { } else { @@ -2073,21 +2073,21 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'titlesync') { + if (RequestManager::getAll()['action'] == 'titlesync') { if (Authorization::check('adv', 'edit_stream')) { $rReturn = array('total_count' => 0, 'items' => array(), 'result' => true); - if (!isset(CoreUtilities::$rRequest['search'])) { + if (!isset(RequestManager::getAll()['search'])) { } else { - if (isset(CoreUtilities::$rRequest['page'])) { - $rPage = intval(CoreUtilities::$rRequest['page']); + if (isset(RequestManager::getAll()['page'])) { + $rPage = intval(RequestManager::getAll()['page']); } else { $rPage = 1; } - $db->query("SELECT COUNT(`stream_id`) AS `stream_id` FROM `providers_streams` WHERE `type` = 'live' AND (`stream_display_name` LIKE ? OR `stream_id` LIKE ?);", '%' . CoreUtilities::$rRequest['search'] . '%', CoreUtilities::$rRequest['search'] . '%'); + $db->query("SELECT COUNT(`stream_id`) AS `stream_id` FROM `providers_streams` WHERE `type` = 'live' AND (`stream_display_name` LIKE ? OR `stream_id` LIKE ?);", '%' . RequestManager::getAll()['search'] . '%', RequestManager::getAll()['search'] . '%'); $rReturn['total_count'] = $db->get_row()['stream_id']; - $db->query("SELECT `providers`.`name`, `providers_streams`.`provider_id`, `providers_streams`.`stream_id`, `providers_streams`.`stream_display_name` FROM `providers_streams` LEFT JOIN `providers` ON `providers`.`id` = `providers_streams`.`provider_id` WHERE `providers_streams`.`type` = 'live' AND (`stream_display_name` LIKE ? OR `stream_id` LIKE ?) ORDER BY `stream_display_name` ASC LIMIT " . ($rPage - 1) * 100 . ', 100;', '%' . CoreUtilities::$rRequest['search'] . '%', CoreUtilities::$rRequest['search'] . '%'); + $db->query("SELECT `providers`.`name`, `providers_streams`.`provider_id`, `providers_streams`.`stream_id`, `providers_streams`.`stream_display_name` FROM `providers_streams` LEFT JOIN `providers` ON `providers`.`id` = `providers_streams`.`provider_id` WHERE `providers_streams`.`type` = 'live' AND (`stream_display_name` LIKE ? OR `stream_id` LIKE ?) ORDER BY `stream_display_name` ASC LIMIT " . ($rPage - 1) * 100 . ', 100;', '%' . RequestManager::getAll()['search'] . '%', RequestManager::getAll()['search'] . '%'); $rGroups = array(); if (0 >= $db->num_rows()) { @@ -2116,7 +2116,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'force_epg') { + if (RequestManager::getAll()['action'] == 'force_epg') { if (Authorization::check('adv', 'epg')) { shell_exec(PHP_BIN . ' ' . CRON_PATH . 'epg.php > /dev/null 2>/dev/null &'); echo json_encode(array('result' => true)); @@ -2128,16 +2128,16 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'tmdb_search') { + if (RequestManager::getAll()['action'] == 'tmdb_search') { if (Authorization::check('adv', 'add_series') || Authorization::check('adv', 'edit_series') || Authorization::check('adv', 'add_movie') || Authorization::check('adv', 'edit_movie') || Authorization::check('adv', 'add_episode') || Authorization::check('adv', 'edit_episode')) { - $rTerm = CoreUtilities::$rRequest['term']; + $rTerm = RequestManager::getAll()['term']; if (0 >= strlen($rTerm)) { } else { include MAIN_HOME . 'includes/libs/tmdb.php'; - if (0 < strlen(CoreUtilities::$rRequest['language'])) { - $rTMDB = new TMDB($rSettings['tmdb_api_key'], CoreUtilities::$rRequest['language']); + if (0 < strlen(RequestManager::getAll()['language'])) { + $rTMDB = new TMDB($rSettings['tmdb_api_key'], RequestManager::getAll()['language']); } else { if (0 < strlen($rSettings['tmdb_language'])) { $rTMDB = new TMDB($rSettings['tmdb_api_key'], $rSettings['tmdb_language']); @@ -2146,14 +2146,14 @@ if (isset($_SESSION['hash'])) { } } - if (is_numeric($rTerm) && in_array(CoreUtilities::$rRequest['type'], array('movie', 'series', 'episode'))) { - if (CoreUtilities::$rRequest['type'] == 'movie') { + if (is_numeric($rTerm) && in_array(RequestManager::getAll()['type'], array('movie', 'series', 'episode'))) { + if (RequestManager::getAll()['type'] == 'movie') { $rResult = array(json_decode($rTMDB->getMovie($rTerm)->getJSON(), true)); } else { - if (CoreUtilities::$rRequest['type'] == 'series') { + if (RequestManager::getAll()['type'] == 'series') { $rResult = array(json_decode($rTMDB->getTVShow($rTerm)->getJSON(), true)); } else { - $rResult = json_decode($rTMDB->getSeason($rTerm, intval(CoreUtilities::$rRequest['season']))->getJSON(), true); + $rResult = json_decode($rTMDB->getSeason($rTerm, intval(RequestManager::getAll()['season']))->getJSON(), true); if (isset($rResult['tvshow_id']) && $rResult['tvshow_id'] == 0) { $rResult = null; @@ -2172,14 +2172,14 @@ if (isset($_SESSION['hash'])) { $rTerm = $rRelease['title']; $rJSON = array(); - if (CoreUtilities::$rRequest['type'] == 'movie') { + if (RequestManager::getAll()['type'] == 'movie') { $rResults = $rTMDB->searchMovie($rTerm); foreach ($rResults as $rResult) { $rJSON[] = json_decode($rResult->getJSON(), true); } } else { - if (CoreUtilities::$rRequest['type'] == 'series') { + if (RequestManager::getAll()['type'] == 'series') { $rResults = $rTMDB->searchTVShow($rTerm); foreach ($rResults as $rResult) { @@ -2205,12 +2205,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'tmdb') { + if (RequestManager::getAll()['action'] == 'tmdb') { if (Authorization::check('adv', 'add_series') || Authorization::check('adv', 'edit_series') || Authorization::check('adv', 'add_movie') || Authorization::check('adv', 'edit_movie') || Authorization::check('adv', 'add_episode') || Authorization::check('adv', 'edit_episode')) { include MAIN_HOME . 'includes/libs/tmdb.php'; - if (0 < strlen(CoreUtilities::$rRequest['language'])) { - $rTMDB = new TMDB($rSettings['tmdb_api_key'], CoreUtilities::$rRequest['language']); + if (0 < strlen(RequestManager::getAll()['language'])) { + $rTMDB = new TMDB($rSettings['tmdb_api_key'], RequestManager::getAll()['language']); } else { if (0 < strlen($rSettings['tmdb_language'])) { $rTMDB = new TMDB($rSettings['tmdb_api_key'], $rSettings['tmdb_language']); @@ -2219,18 +2219,18 @@ if (isset($_SESSION['hash'])) { } } - $rID = CoreUtilities::$rRequest['id']; + $rID = RequestManager::getAll()['id']; - if (CoreUtilities::$rRequest['type'] == 'movie') { + if (RequestManager::getAll()['type'] == 'movie') { $rMovie = $rTMDB->getMovie($rID); $rResult = json_decode($rMovie->getJSON(), true); $rResult['trailer'] = $rMovie->getTrailer(); } else { - if (CoreUtilities::$rRequest['type'] != 'series') { + if (RequestManager::getAll()['type'] != 'series') { } else { $rSeries = $rTMDB->getTVShow($rID); $rResult = json_decode($rSeries->getJSON(), true); - $rResult['trailer'] = getSeriesTrailer($rID, (!empty(CoreUtilities::$rRequest['language']) ? CoreUtilities::$rRequest['language'] : $rSettings['tmdb_language'])); + $rResult['trailer'] = getSeriesTrailer($rID, (!empty(RequestManager::getAll()['language']) ? RequestManager::getAll()['language'] : $rSettings['tmdb_language'])); } } @@ -2249,25 +2249,25 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'listdir') { + if (RequestManager::getAll()['action'] == 'listdir') { if (Authorization::check('adv', 'add_episode') || Authorization::check('adv', 'edit_episode') || Authorization::check('adv', 'add_movie') || Authorization::check('adv', 'edit_movie') || Authorization::check('adv', 'create_channel') || Authorization::check('adv', 'edit_cchannel') || Authorization::check('adv', 'folder_watch_add')) { - if (CoreUtilities::$rRequest['filter'] == 'video') { + if (RequestManager::getAll()['filter'] == 'video') { $rFilter = array('mp4', 'mkv', 'avi', 'mpg', 'flv', '3gp', 'm4v', 'wmv', 'mov', 'ts'); } else { - if (CoreUtilities::$rRequest['filter'] == 'subs') { + if (RequestManager::getAll()['filter'] == 'subs') { $rFilter = array('srt', 'sub', 'sbv'); } else { $rFilter = array('mp4', 'mkv', 'avi', 'mpg', 'flv', '3gp', 'm4v', 'wmv', 'mov', 'ts', 'srt', 'sub', 'sbv'); } } - if (!(isset(CoreUtilities::$rRequest['server']) && isset(CoreUtilities::$rRequest['dir']))) { + if (!(isset(RequestManager::getAll()['server']) && isset(RequestManager::getAll()['dir']))) { echo json_encode(array('result' => false)); exit(); } - echo json_encode(array('result' => true, 'data' => listDir(intval(CoreUtilities::$rRequest['server']), CoreUtilities::$rRequest['dir'], $rFilter))); + echo json_encode(array('result' => true, 'data' => listDir(intval(RequestManager::getAll()['server']), RequestManager::getAll()['dir'], $rFilter))); exit(); } @@ -2276,9 +2276,9 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'fingerprint') { + if (RequestManager::getAll()['action'] == 'fingerprint') { if (Authorization::check('adv', 'fingerprint')) { - $rData = json_decode(CoreUtilities::$rRequest['data'], true); + $rData = json_decode(RequestManager::getAll()['data'], true); $rActiveServers = array(); foreach ($rServers as $rServer) { @@ -2296,11 +2296,11 @@ if (isset($_SESSION['hash'])) { if (!(0 < $rData['id'] && 0 < $rData['font_size'] && 0 < strlen($rData['font_color']) && 0 < strlen($rData['xy_offset']) && (0 < strlen($rData['message']) || $rData['type'] < 3))) { } else { - if (CoreUtilities::$rSettings['redis_handler']) { + if (SettingsManager::getAll()['redis_handler']) { if (isset($rData['user'])) { - $rRows = CoreUtilities::getRedisConnections($rData['id'], null, null, true, false, false); + $rRows = ConnectionTracker::getRedisConnections($rData['id'], null, null, true, false, false); } else { - $rRows = CoreUtilities::getRedisConnections(null, null, $rData['id'], true, false, false); + $rRows = ConnectionTracker::getRedisConnections(null, null, $rData['id'], true, false, false); } $rUserMap = $rUserIDs = array(); @@ -2342,7 +2342,7 @@ if (isset($_SESSION['hash'])) { if ($rData['type'] == 1) { $rArray['message'] = $rRow['uuid']; } elseif ($rData['type'] == 2) { - $rArray['message'] = (CoreUtilities::$rSettings['redis_handler'] ? $rUserMap[$rRow['user_id']] : $rRow['username']); + $rArray['message'] = (SettingsManager::getAll()['redis_handler'] ? $rUserMap[$rRow['user_id']] : $rRow['username']); } elseif ($rData['type'] == 3) { $rArray['message'] = $rData['message']; } @@ -2363,7 +2363,7 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'restart_all_services') { + if (RequestManager::getAll()['action'] == 'restart_all_services') { if (Authorization::check('adv', 'servers')) { foreach ($rServers as $rServer) { if (!$rServer['server_online']) { @@ -2380,12 +2380,12 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'restart_services') { + if (RequestManager::getAll()['action'] == 'restart_services') { if (Authorization::check('adv', 'edit_server')) { - if (!is_numeric(CoreUtilities::$rRequest['server_id'])) { - $rIDs = json_decode(CoreUtilities::$rRequest['server_id'], true); + if (!is_numeric(RequestManager::getAll()['server_id'])) { + $rIDs = json_decode(RequestManager::getAll()['server_id'], true); } else { - $rIDs = array(intval(CoreUtilities::$rRequest['server_id'])); + $rIDs = array(intval(RequestManager::getAll()['server_id'])); } foreach ($rIDs as $rID) { @@ -2400,12 +2400,12 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'reboot_server') { + if (RequestManager::getAll()['action'] == 'reboot_server') { if (Authorization::check('adv', 'edit_server')) { - if (!is_numeric(CoreUtilities::$rRequest['server_id'])) { - $rIDs = json_decode(CoreUtilities::$rRequest['server_id'], true); + if (!is_numeric(RequestManager::getAll()['server_id'])) { + $rIDs = json_decode(RequestManager::getAll()['server_id'], true); } else { - $rIDs = array(intval(CoreUtilities::$rRequest['server_id'])); + $rIDs = array(intval(RequestManager::getAll()['server_id'])); } foreach ($rIDs as $rID) { @@ -2420,12 +2420,12 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'update_binaries') { + if (RequestManager::getAll()['action'] == 'update_binaries') { if (Authorization::check('adv', 'edit_server')) { - if (!is_numeric(CoreUtilities::$rRequest['server_id'])) { - $rIDs = json_decode(CoreUtilities::$rRequest['server_id'], true); + if (!is_numeric(RequestManager::getAll()['server_id'])) { + $rIDs = json_decode(RequestManager::getAll()['server_id'], true); } else { - $rIDs = array(intval(CoreUtilities::$rRequest['server_id'])); + $rIDs = array(intval(RequestManager::getAll()['server_id'])); } foreach ($rIDs as $rID) { @@ -2440,32 +2440,32 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'probe_stream') { + if (RequestManager::getAll()['action'] == 'probe_stream') { if (Authorization::check('adv', 'add_stream') || Authorization::check('adv', 'edit_stream')) { - $rAnalyseDuration = abs(intval(CoreUtilities::$rSettings['stream_max_analyze'])); - $rTimeout = intval($rAnalyseDuration / 1000000) + CoreUtilities::$rSettings['probe_extra_wait']; + $rAnalyseDuration = abs(intval(SettingsManager::getAll()['stream_max_analyze'])); + $rTimeout = intval($rAnalyseDuration / 1000000) + SettingsManager::getAll()['probe_extra_wait']; set_time_limit(intval($rTimeout)); ini_set('max_execution_time', intval($rTimeout)); ini_set('default_socket_timeout', intval($rTimeout)); $rServerID = SERVER_ID; - if (empty(CoreUtilities::$rRequest['server']) || !$rServers[intval(CoreUtilities::$rRequest['server'])]['server_online']) { + if (empty(RequestManager::getAll()['server']) || !$rServers[intval(RequestManager::getAll()['server'])]['server_online']) { } else { - $rServerID = intval(CoreUtilities::$rRequest['server']); + $rServerID = intval(RequestManager::getAll()['server']); } $rStreamInfoText = "
Stream probe failed!
"; $rStreamInfo = null; - if (!empty(CoreUtilities::$rRequest['url'])) { - $rURL = CoreUtilities::parseStreamURL(CoreUtilities::$rRequest['url']); + if (!empty(RequestManager::getAll()['url'])) { + $rURL = StreamUtils::parseStreamURL(RequestManager::getAll()['url']); - if (CoreUtilities::detectXC_VM($rURL) && CoreUtilities::$rSettings['api_probe']) { + if (StreamUtils::detectXC_VM($rURL) && SettingsManager::getAll()['api_probe']) { $rURLInfo = parse_url($rURL); $rProbeURL = $rURLInfo['scheme'] . '://' . $rURLInfo['host'] . (($rURLInfo['port'] ? ':' . $rURLInfo['port'] : '')) . '/probe/' . base64_encode($rURLInfo['path']); - if ($rAPIInfo = json_decode(CoreUtilities::getURL($rProbeURL), true)) { + if ($rAPIInfo = json_decode(CurlClient::getURL($rProbeURL), true)) { $rStreamInfo = array(); foreach ($rAPIInfo['codecs'] as $rType => $rCodec) { @@ -2476,12 +2476,12 @@ if (isset($_SESSION['hash'])) { } if (!$rStreamInfo) { - $rStreamInfo = ServerRepository::probeSource('systemapirequest', $rServerID, CoreUtilities::$rRequest['url'], (CoreUtilities::$rRequest['user_agent'] ?: null), (CoreUtilities::$rRequest['http_proxy'] ?: null), (CoreUtilities::$rRequest['cookies'] ?: null), (CoreUtilities::$rRequest['headers'] ?: null))['data']; + $rStreamInfo = ServerRepository::probeSource($rServerID, RequestManager::getAll()['url'], (RequestManager::getAll()['user_agent'] ?: null), (RequestManager::getAll()['http_proxy'] ?: null), (RequestManager::getAll()['cookies'] ?: null), (RequestManager::getAll()['headers'] ?: null))['data']; $rStreamInfo['container'] = $rStreamInfo['format']['format_name']; } } - if (isset(CoreUtilities::$rRequest['map'])) { + if (isset(RequestManager::getAll()['map'])) { echo json_encode($rStreamInfo); exit(); } @@ -2537,31 +2537,31 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'check_stream') { + if (RequestManager::getAll()['action'] == 'check_stream') { if (Authorization::check('adv', 'add_stream') || Authorization::check('adv', 'edit_stream')) { - $rAnalyseDuration = abs(intval(CoreUtilities::$rSettings['stream_max_analyze'])); - $rTimeout = intval($rAnalyseDuration / 1000000) + CoreUtilities::$rSettings['probe_extra_wait']; + $rAnalyseDuration = abs(intval(SettingsManager::getAll()['stream_max_analyze'])); + $rTimeout = intval($rAnalyseDuration / 1000000) + SettingsManager::getAll()['probe_extra_wait']; set_time_limit(intval($rTimeout)); ini_set('max_execution_time', intval($rTimeout)); ini_set('default_socket_timeout', intval($rTimeout)); - if (isset(CoreUtilities::$rRequest['url'])) { - $rURL = CoreUtilities::parseStreamURL(CoreUtilities::$rRequest['url']); + if (isset(RequestManager::getAll()['url'])) { + $rURL = StreamUtils::parseStreamURL(RequestManager::getAll()['url']); - if (isset(CoreUtilities::$rRequest['ua'])) { - $rUA = ' -user_agent ' . escapeshellarg(CoreUtilities::$rRequest['ua']); + if (isset(RequestManager::getAll()['ua'])) { + $rUA = ' -user_agent ' . escapeshellarg(RequestManager::getAll()['ua']); } else { $rUA = ''; } - if (isset(CoreUtilities::$rRequest['cookie'])) { - $rCookie = ' -cookies ' . escapeshellarg(CoreUtilities::fixCookie(CoreUtilities::$rRequest['cookie'])); + if (isset(RequestManager::getAll()['cookie'])) { + $rCookie = ' -cookies ' . escapeshellarg(StreamUtils::fixCookie(RequestManager::getAll()['cookie'])); } else { $rCookie = ''; } } else { - $rStream = StreamRepository::getById(CoreUtilities::$rRequest['stream']); - $rStreamOptions = StreamRepository::getOptions(CoreUtilities::$rRequest['stream']); + $rStream = StreamRepository::getById(RequestManager::getAll()['stream']); + $rStreamOptions = StreamRepository::getOptions(RequestManager::getAll()['stream']); if (0 < strlen($rStreamOptions[1]['value'])) { $rUA = ' -user_agent ' . escapeshellarg($rStreamOptions[1]['value']); @@ -2569,13 +2569,13 @@ if (isset($_SESSION['hash'])) { $rUA = ''; } - if (isset(CoreUtilities::$rRequest['cookie'])) { - $rCookie = ' -cookies ' . escapeshellarg(CoreUtilities::fixCookie($rStreamOptions[17]['value'])); + if (isset(RequestManager::getAll()['cookie'])) { + $rCookie = ' -cookies ' . escapeshellarg(StreamUtils::fixCookie($rStreamOptions[17]['value'])); } else { $rCookie = ''; } - $rURL = CoreUtilities::parseStreamURL(json_decode($rStream['stream_source'], true)[intval(CoreUtilities::$rRequest['id'])]); + $rURL = StreamUtils::parseStreamURL(json_decode($rStream['stream_source'], true)[intval(RequestManager::getAll()['id'])]); } if (0 >= strlen($rURL)) { @@ -2583,12 +2583,12 @@ if (isset($_SESSION['hash'])) { $rStreamInfoText = "
Stream probe failed!
"; $rStreamInfo = null; - if (!(CoreUtilities::detectXC_VM($rURL) && CoreUtilities::$rSettings['api_probe'])) { + if (!(StreamUtils::detectXC_VM($rURL) && SettingsManager::getAll()['api_probe'])) { } else { $rURLInfo = parse_url($rURL); $rProbeURL = $rURLInfo['scheme'] . '://' . $rURLInfo['host'] . (($rURLInfo['port'] ? ':' . $rURLInfo['port'] : '')) . '/probe/' . base64_encode($rURLInfo['path']); - if (!($rAPIInfo = json_decode(CoreUtilities::getURL($rProbeURL), true))) { + if (!($rAPIInfo = json_decode(CurlClient::getURL($rProbeURL), true))) { } else { $rStreamInfo = array(); @@ -2600,7 +2600,7 @@ if (isset($_SESSION['hash'])) { if ($rStreamInfo) { } else { - $rStreamInfo = json_decode(shell_exec('timeout ' . intval($rTimeout) . ' ' . CoreUtilities::$rFFPROBE . $rUA . $rCookie . ' -v quiet -probesize 5000000 -print_format json -show_format -show_streams ' . escapeshellarg($rURL)), true); + $rStreamInfo = json_decode(shell_exec('timeout ' . intval($rTimeout) . ' ' . FfmpegPaths::probe() . $rUA . $rCookie . ' -v quiet -probesize 5000000 -print_format json -show_format -show_streams ' . escapeshellarg($rURL)), true); } if (0 >= count($rStreamInfo['streams'])) { @@ -2658,12 +2658,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'clear_logs') { + if (RequestManager::getAll()['action'] == 'clear_logs') { if (Authorization::check('adv', 'reg_userlog') || Authorization::check('adv', 'client_request_log') || Authorization::check('adv', 'connection_logs') || Authorization::check('adv', 'stream_errors') || Authorization::check('adv', 'credits_log') || Authorization::check('adv', 'folder_watch_settings')) { - if (strlen(CoreUtilities::$rRequest['from']) == 0) { + if (strlen(RequestManager::getAll()['from']) == 0) { $rStartTime = null; } else { - if ($rStartTime = strtotime(CoreUtilities::$rRequest['from'] . ' 00:00:00')) { + if ($rStartTime = strtotime(RequestManager::getAll()['from'] . ' 00:00:00')) { } else { echo json_encode(array('result' => false)); @@ -2671,10 +2671,10 @@ if (isset($_SESSION['hash'])) { } } - if (strlen(CoreUtilities::$rRequest['to']) == 0) { + if (strlen(RequestManager::getAll()['to']) == 0) { $rEndTime = null; } else { - if ($rEndTime = strtotime(CoreUtilities::$rRequest['to'] . ' 23:59:59')) { + if ($rEndTime = strtotime(RequestManager::getAll()['to'] . ' 23:59:59')) { } else { echo json_encode(array('result' => false)); @@ -2682,28 +2682,28 @@ if (isset($_SESSION['hash'])) { } } - if (in_array(CoreUtilities::$rRequest['type'], array('lines_logs', 'streams_errors', 'lines_activity', 'users_credits_logs', 'users_logs', 'panel_logs'))) { - if (CoreUtilities::$rRequest['type'] == 'lines_activity') { + if (in_array(RequestManager::getAll()['type'], array('lines_logs', 'streams_errors', 'lines_activity', 'users_credits_logs', 'users_logs', 'panel_logs'))) { + if (RequestManager::getAll()['type'] == 'lines_activity') { $rColumn = 'date_start'; } else { $rColumn = 'date'; } if ($rStartTime && $rEndTime) { - $db->query('DELETE FROM ' . preparecolumn(CoreUtilities::$rRequest['type']) . ' WHERE `' . $rColumn . '` >= ? AND `' . $rColumn . '` <= ?;', $rStartTime, $rEndTime); + $db->query('DELETE FROM ' . preparecolumn(RequestManager::getAll()['type']) . ' WHERE `' . $rColumn . '` >= ? AND `' . $rColumn . '` <= ?;', $rStartTime, $rEndTime); } else { if ($rStartTime) { - $db->query('DELETE FROM ' . preparecolumn(CoreUtilities::$rRequest['type']) . ' WHERE `' . $rColumn . '` >= ?;', $rStartTime); + $db->query('DELETE FROM ' . preparecolumn(RequestManager::getAll()['type']) . ' WHERE `' . $rColumn . '` >= ?;', $rStartTime); } else { if ($rEndTime) { - $db->query('DELETE FROM ' . preparecolumn(CoreUtilities::$rRequest['type']) . ' WHERE `' . $rColumn . '` <= ?;', $rEndTime); + $db->query('DELETE FROM ' . preparecolumn(RequestManager::getAll()['type']) . ' WHERE `' . $rColumn . '` <= ?;', $rEndTime); } else { - $db->query('TRUNCATE ' . preparecolumn(CoreUtilities::$rRequest['type']) . ';'); + $db->query('TRUNCATE ' . preparecolumn(RequestManager::getAll()['type']) . ';'); } } } } else { - if (CoreUtilities::$rRequest['type'] != 'watch_logs') { + if (RequestManager::getAll()['type'] != 'watch_logs') { } else { if ($rStartTime && $rEndTime) { $db->query('DELETE FROM `watch_logs` WHERE UNIX_TIMESTAMP(`dateadded`) >= ? AND UNIX_TIMESTAMP(`dateadded`) <= ?;', $rStartTime, $rEndTime); @@ -2730,12 +2730,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'backup') { + if (RequestManager::getAll()['action'] == 'backup') { if (Authorization::check('adv', 'database')) { - $rSub = CoreUtilities::$rRequest['sub']; + $rSub = RequestManager::getAll()['sub']; if ($rSub == 'delete') { - $rBackup = pathinfo(CoreUtilities::$rRequest['filename'])['filename']; + $rBackup = pathinfo(RequestManager::getAll()['filename'])['filename']; if (!file_exists(MAIN_HOME . 'backups/' . $rBackup . '.sql')) { } else { @@ -2753,7 +2753,7 @@ if (isset($_SESSION['hash'])) { } if ($rSub == 'restore') { - $rBackup = pathinfo(CoreUtilities::$rRequest['filename'])['filename']; + $rBackup = pathinfo(RequestManager::getAll()['filename'])['filename']; $rFilename = MAIN_HOME . 'backups/' . $rBackup . '.sql'; if (file_exists($rFilename)) { @@ -2774,7 +2774,7 @@ if (isset($_SESSION['hash'])) { } } - CoreUtilities::restoreBackup($rFilename); + BackupService::restore($rFilename, ConfigReader::getAll()); echo json_encode(array('result' => true)); exit(); @@ -2797,9 +2797,9 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'send_event') { + if (RequestManager::getAll()['action'] == 'send_event') { if (Authorization::check('adv', 'manage_events')) { - $rData = json_decode(CoreUtilities::$rRequest['data'], true); + $rData = json_decode(RequestManager::getAll()['data'], true); if (!is_numeric($rData['id'])) { $rIDs = json_decode($rData['id'], true); @@ -2837,8 +2837,8 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'ip_whois') { - $rIP = CoreUtilities::$rRequest['ip']; + if (RequestManager::getAll()['action'] == 'ip_whois') { + $rIP = RequestManager::getAll()['ip']; $rReader = new MaxMind\Db\Reader(GEOLITE2C_BIN); $rResponse = $rReader->get($rIP); @@ -2850,7 +2850,7 @@ if (isset($_SESSION['hash'])) { $rReader->close(); - if (!isset(CoreUtilities::$rRequest['isp'])) { + if (!isset(RequestManager::getAll()['isp'])) { } else { $rReader = new MaxMind\Db\Reader(GEOISP_BIN); $rResponse['isp'] = $rReader->get($rIP); @@ -2900,10 +2900,10 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'asn') { + if (RequestManager::getAll()['action'] == 'asn') { if (Authorization::check('adv', 'block_isps')) { - $rSub = CoreUtilities::$rRequest['sub']; - $rASN = CoreUtilities::$rRequest['id']; + $rSub = RequestManager::getAll()['sub']; + $rASN = RequestManager::getAll()['id']; if ($rSub == 'allow') { $db->query('UPDATE `blocked_asns` SET `blocked` = 0 WHERE `id` = ?;', $rASN); @@ -2939,13 +2939,13 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'server_view') { + if (RequestManager::getAll()['action'] == 'server_view') { if (Authorization::check('adv', 'add_server') || Authorization::check('adv', 'edit_server')) { - if (isset($rServers[CoreUtilities::$rRequest['server_id']])) { - $rServer = $rServers[CoreUtilities::$rRequest['server_id']]; + if (isset($rServers[RequestManager::getAll()['server_id']])) { + $rServer = $rServers[RequestManager::getAll()['server_id']]; } else { - if (isset($rProxyServers[CoreUtilities::$rRequest['server_id']])) { - $rServer = $rProxyServers[CoreUtilities::$rRequest['server_id']]; + if (isset($rProxyServers[RequestManager::getAll()['server_id']])) { + $rServer = $rProxyServers[RequestManager::getAll()['server_id']]; } else { echo json_encode(array('result' => false)); @@ -2969,9 +2969,9 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'server_stats') { + if (RequestManager::getAll()['action'] == 'server_stats') { if (Authorization::check('adv', 'add_server') || Authorization::check('adv', 'edit_server')) { - $rID = intval(CoreUtilities::$rRequest['id']); + $rID = intval(RequestManager::getAll()['id']); if (isset($rServers[$rID])) { $rWatchdog = WatchdogMonitor::getWatchdog($rID); @@ -2994,9 +2994,9 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'rtmp_kill') { + if (RequestManager::getAll()['action'] == 'rtmp_kill') { if (Authorization::check('adv', 'rtmp')) { - echo systemapirequest(intval(CoreUtilities::$rRequest['server']), array('action' => 'rtmp_kill', 'name' => CoreUtilities::$rRequest['name'])); + echo systemapirequest(intval(RequestManager::getAll()['server']), array('action' => 'rtmp_kill', 'name' => RequestManager::getAll()['name'])); exit(); } @@ -3005,14 +3005,14 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'install_status') { + if (RequestManager::getAll()['action'] == 'install_status') { if (Authorization::check('adv', 'add_server') || Authorization::check('adv', 'edit_server')) { - CoreUtilities::$rServers = CoreUtilities::getServers(true); - $rServerID = intval(CoreUtilities::$rRequest['server_id']); + $rServers = ServerRepository::getAll(true); + $rServerID = intval(RequestManager::getAll()['server_id']); $rFilename = BIN_PATH . 'install/' . $rServerID . '.install'; if (file_exists($rFilename)) { - echo json_encode(array('result' => true, 'data' => trim(file_get_contents($rFilename)), 'status' => intval(CoreUtilities::$rServers[$rServerID]['status']))); + echo json_encode(array('result' => true, 'data' => trim(file_get_contents($rFilename)), 'status' => intval($rServers[$rServerID]['status']))); exit(); } @@ -3026,9 +3026,9 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'reinstall_server') { + if (RequestManager::getAll()['action'] == 'reinstall_server') { if (Authorization::check('adv', 'add_server') || Authorization::check('adv', 'edit_server')) { - $rServerID = intval(CoreUtilities::$rRequest['server_id']); + $rServerID = intval(RequestManager::getAll()['server_id']); if ($rServers[$rServerID]['server_type'] == 0) { $rType = 2; @@ -3063,14 +3063,14 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'fpm_status') { + if (RequestManager::getAll()['action'] == 'fpm_status') { if (Authorization::check('adv', 'add_server') || Authorization::check('adv', 'edit_server')) { - $rData = str_replace("\n", '
', systemapirequest(CoreUtilities::$rRequest['server_id'], array('action' => 'fpm_status'))); + $rData = str_replace("\n", '
', systemapirequest(RequestManager::getAll()['server_id'], array('action' => 'fpm_status'))); if (empty($rData)) { $rData = 'No response from status page.'; } else { - $rInstances = intval($rServers[CoreUtilities::$rRequest['server_id']]['total_services']); + $rInstances = intval($rServers[RequestManager::getAll()['server_id']]['total_services']); if (!$rInstances) { } else { @@ -3087,7 +3087,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'update_all_servers') { + if (RequestManager::getAll()['action'] == 'update_all_servers') { if (Authorization::check('adv', 'servers')) { foreach ($rServers as $rServer) { if ($rServer['server_online']) { @@ -3103,7 +3103,7 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'update_all_binaries') { + if (RequestManager::getAll()['action'] == 'update_all_binaries') { if (Authorization::check('adv', 'servers')) { foreach ($rServers as $rServer) { if (!$rServer['server_online']) { @@ -3120,7 +3120,7 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'disable_watch') { + if (RequestManager::getAll()['action'] == 'disable_watch') { if (Authorization::check('adv', 'folder_watch_settings')) { WatchService::disableWatch(); echo json_encode(array('result' => true)); @@ -3132,7 +3132,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'enable_watch') { + if (RequestManager::getAll()['action'] == 'enable_watch') { if (Authorization::check('adv', 'folder_watch_settings')) { WatchService::enableWatch(); echo json_encode(array('result' => true)); @@ -3144,7 +3144,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'disable_plex') { + if (RequestManager::getAll()['action'] == 'disable_plex') { if (Authorization::check('adv', 'folder_watch_settings')) { $db->query("UPDATE `watch_folders` SET `active` = 0 WHERE `type` = 'plex';"); echo json_encode(array('result' => true)); @@ -3156,7 +3156,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'enable_plex') { + if (RequestManager::getAll()['action'] == 'enable_plex') { if (Authorization::check('adv', 'folder_watch_settings')) { $db->query("UPDATE `watch_folders` SET `active` = 1 WHERE `type` = 'plex';"); echo json_encode(array('result' => true)); @@ -3168,10 +3168,10 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'plex_sections') { + if (RequestManager::getAll()['action'] == 'plex_sections') { if (Authorization::check('adv', 'folder_watch_settings')) { - $rToken = CoreUtilities::getPlexToken(CoreUtilities::$rRequest['ip'], CoreUtilities::$rRequest['port'], CoreUtilities::$rRequest['username'], CoreUtilities::$rRequest['password']); - $rSections = PlexRepository::getPlexSections(CoreUtilities::$rRequest['ip'], CoreUtilities::$rRequest['port'], $rToken); + $rToken = PlexAuth::getPlexToken(RequestManager::getAll()['ip'], RequestManager::getAll()['port'], RequestManager::getAll()['username'], RequestManager::getAll()['password']); + $rSections = PlexRepository::getPlexSections(RequestManager::getAll()['ip'], RequestManager::getAll()['port'], $rToken); if ($rSections && 0 < count($rSections)) { echo json_encode(array('result' => true, 'data' => $rSections)); @@ -3185,7 +3185,7 @@ if (isset($_SESSION['hash'])) { echo json_encode(array('result' => false)); exit(); } - if (CoreUtilities::$rRequest['action'] == 'enable_handler') { + if (RequestManager::getAll()['action'] == 'enable_handler') { if (Authorization::check('adv', 'backups')) { $db->query('UPDATE `settings` SET `redis_handler` = 1;'); @@ -3232,7 +3232,7 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'disable_handler') { + if (RequestManager::getAll()['action'] == 'disable_handler') { if (Authorization::check('adv', 'backups')) { $db->query('UPDATE `settings` SET `redis_handler` = 0;'); @@ -3276,9 +3276,9 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'clear_redis') { + if (RequestManager::getAll()['action'] == 'clear_redis') { if (Authorization::check('adv', 'backups')) { - CoreUtilities::$redis->flushAll(); + RedisManager::instance()->flushAll(); echo json_encode(array('result' => true)); exit(); @@ -3288,12 +3288,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'report') { + if (RequestManager::getAll()['action'] == 'report') { if (Authorization::check('adv', 'backups')) { $rURL = pathinfo('http://127.0.0.1:' . $rServers[SERVER_ID]['http_broadcast_port'] . $_SERVER['REQUEST_URI'])['dirname'] . '/table'; set_time_limit(60); ini_set('memory_limit', '-1'); - $rParams = json_decode(CoreUtilities::$rRequest['params'], true); + $rParams = json_decode(RequestManager::getAll()['params'], true); foreach (array() as $rKey) { unset($rParams[$rKey]); @@ -3318,10 +3318,10 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'decrypt_text') { + if (RequestManager::getAll()['action'] == 'decrypt_text') { if (Authorization::check('adv', 'stream_tools')) { $rDecryptedArray = array(); - $rText = (CoreUtilities::$rRequest['text'] ?: null); + $rText = (RequestManager::getAll()['text'] ?: null); if (!$rText) { } else { @@ -3340,7 +3340,7 @@ if (isset($_SESSION['hash'])) { if (!empty($rDecoded)) { try { - $rDecrypted = CoreUtilities::decryptData($rPiece, CoreUtilities::$rSettings['live_streaming_pass'], OPENSSL_EXTRA); + $rDecrypted = Encryption::decrypt($rPiece, SettingsManager::getAll()['live_streaming_pass'], OPENSSL_EXTRA); } catch (Exception $e) { $rDecrypted = null; } @@ -3368,10 +3368,10 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'get_episode_ids') { + if (RequestManager::getAll()['action'] == 'get_episode_ids') { if (Authorization::check('adv', 'add_episode')) { $rReturn = array(); - $rData = json_decode(CoreUtilities::$rRequest['data'], true); + $rData = json_decode(RequestManager::getAll()['data'], true); if (!is_array($rData)) { echo json_encode(array('result' => false)); @@ -3381,7 +3381,7 @@ if (isset($_SESSION['hash'])) { $rInput = array(); - if (CoreUtilities::$rSettings['parse_type'] == 'guessit') { + if (SettingsManager::getAll()['parse_type'] == 'guessit') { foreach ($rData as $rEpisodeID => $rName) { $rInput[$rEpisodeID] = pathinfo($rName)['filename']; } @@ -3414,22 +3414,22 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'download_panel_logs') { - $errors = CoreUtilities::downloadPanelLogs(); + if (RequestManager::getAll()['action'] == 'download_panel_logs') { + $errors = DiagnosticsService::downloadPanelLogs(DatabaseFactory::get()); echo json_encode(array('result' => true, 'data' => $errors)); exit(); } - if (CoreUtilities::$rRequest['action'] == 'get_epg') { + if (RequestManager::getAll()['action'] == 'get_epg') { if (Authorization::check('adv', 'manage_streams')) { - $rTimezone = (CoreUtilities::$rRequest['timezone'] ?: 'Europe/London'); + $rTimezone = (RequestManager::getAll()['timezone'] ?: 'Europe/London'); date_default_timezone_set($rTimezone); $rReturn = array('Channels' => array()); - $rChannels = array_map('intval', explode(',', CoreUtilities::$rRequest['channels'])); + $rChannels = array_map('intval', explode(',', RequestManager::getAll()['channels'])); if (count($rChannels) != 0) { - $rHours = (intval(CoreUtilities::$rRequest['hours']) ?: 3); - $rStartDate = (intval(strtotime(CoreUtilities::$rRequest['startdate'])) ?: time()); + $rHours = (intval(RequestManager::getAll()['hours']) ?: 3); + $rStartDate = (intval(strtotime(RequestManager::getAll()['startdate'])) ?: time()); $rFinishDate = $rStartDate + $rHours * 3600; $rPerUnit = floatval(100 / ($rHours * 60)); $rChannelsSort = $rChannels; @@ -3448,7 +3448,7 @@ if (isset($_SESSION['hash'])) { } } - $rEPG = CoreUtilities::getEPGs($rChannels, $rStartDate, $rFinishDate); + $rEPG = EpgService::getStreamsEpg($rChannels, $rStartDate, $rFinishDate); foreach ($rEPG as $rChannelID => $rEPGData) { $rFullSize = 0; @@ -3496,10 +3496,10 @@ if (isset($_SESSION['hash'])) { $rDefaultArray = $rDefaultEPG; $rDefaultArray['ChannelId'] = $rStream['id']; $rCategoryIDs = json_decode($rStream['category_id'], true); - $rCategories = getCategories('live'); + $rCategories = CategoryService::getAllByType('live'); - if (0 < strlen(CoreUtilities::$rRequest['category'])) { - $rCategory = ($rCategories[intval(CoreUtilities::$rRequest['category'])]['category_name'] ?: 'No Category'); + if (0 < strlen(RequestManager::getAll()['category'])) { + $rCategory = ($rCategories[intval(RequestManager::getAll()['category'])]['category_name'] ?: 'No Category'); } else { $rCategory = ($rCategories[$rCategoryIDs[0]]['category_name'] ?: 'No Category'); } @@ -3509,7 +3509,7 @@ if (isset($_SESSION['hash'])) { $rCategory .= ' (+' . (count($rCategoryIDs) - 1) . ' others)'; } - $rReturn['Channels'][] = array('Id' => $rStream['id'], 'DisplayName' => $rStream['stream_display_name'], 'CategoryName' => $rCategory, 'Archive' => $rArchive, 'Image' => (CoreUtilities::validateImage($rStream['stream_icon']) ?: ''), 'TvListings' => ($rListings[$rStream['id']] ?: array($rDefaultArray))); + $rReturn['Channels'][] = array('Id' => $rStream['id'], 'DisplayName' => $rStream['stream_display_name'], 'CategoryName' => $rCategory, 'Archive' => $rArchive, 'Image' => (ImageUtils::validateURL($rStream['stream_icon']) ?: ''), 'TvListings' => ($rListings[$rStream['id']] ?: array($rDefaultArray))); } echo json_encode($rReturn); @@ -3525,14 +3525,14 @@ if (isset($_SESSION['hash'])) { exit(); } } - if (CoreUtilities::$rRequest['action'] == 'get_programme') { + if (RequestManager::getAll()['action'] == 'get_programme') { if (Authorization::check('adv', 'manage_streams')) { - $rTimezone = (CoreUtilities::$rRequest['timezone'] ?: 'Europe/London'); + $rTimezone = (RequestManager::getAll()['timezone'] ?: 'Europe/London'); date_default_timezone_set($rTimezone); - if (!isset(CoreUtilities::$rRequest['id'])) { + if (!isset(RequestManager::getAll()['id'])) { } else { - $rRow = CoreUtilities::getProgramme(CoreUtilities::$rRequest['stream_id'], CoreUtilities::$rRequest['id']); + $rRow = EpgService::getProgramme(RequestManager::getAll()['stream_id'], RequestManager::getAll()['id']); if (!$rRow) { } else { @@ -3540,7 +3540,7 @@ if (isset($_SESSION['hash'])) { if (time() >= $rRow['end']) { } else { - $db->query('SELECT `server_id`, `direct_source`, `monitor_pid`, `pid`, `stream_status`, `on_demand` FROM `streams` LEFT JOIN `streams_servers` ON `streams_servers`.`stream_id` = `streams`.`id` WHERE `streams`.`id` = ? AND `server_id` IS NOT NULL;', CoreUtilities::$rRequest['stream_id']); + $db->query('SELECT `server_id`, `direct_source`, `monitor_pid`, `pid`, `stream_status`, `on_demand` FROM `streams` LEFT JOIN `streams_servers` ON `streams_servers`.`stream_id` = `streams`.`id` WHERE `streams`.`id` = ? AND `server_id` IS NOT NULL;', RequestManager::getAll()['stream_id']); if (0 >= $db->num_rows()) { } else { @@ -3571,17 +3571,17 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'queue') { + if (RequestManager::getAll()['action'] == 'queue') { if (Authorization::check('adv', 'streams') || Authorization::check('adv', 'series') || Authorization::check('adv', 'episodes')) { - $rSub = CoreUtilities::$rRequest['sub']; - $db->query('SELECT * FROM `queue` WHERE `id` = ?;', CoreUtilities::$rRequest['id']); + $rSub = RequestManager::getAll()['sub']; + $db->query('SELECT * FROM `queue` WHERE `id` = ?;', RequestManager::getAll()['id']); if ($db->num_rows() != 1) { } else { $rRow = $db->get_row(); if ($rSub == 'delete') { - $db->query('DELETE FROM `queue` WHERE `id` = ?;', CoreUtilities::$rRequest['id']); + $db->query('DELETE FROM `queue` WHERE `id` = ?;', RequestManager::getAll()['id']); echo json_encode(array('result' => true)); exit(); @@ -3591,10 +3591,10 @@ if (isset($_SESSION['hash'])) { } else { if (0 >= $rRow['pid']) { } else { - ServerRepository::killPID('systemapirequest', $rRow['server_id'], $rRow['pid']); + ServerRepository::killPID($rRow['server_id'], $rRow['pid']); } - $db->query('DELETE FROM `queue` WHERE `id` = ?;', CoreUtilities::$rRequest['id']); + $db->query('DELETE FROM `queue` WHERE `id` = ?;', RequestManager::getAll()['id']); echo json_encode(array('result' => true)); exit(); @@ -3610,12 +3610,12 @@ if (isset($_SESSION['hash'])) { exit(); } - if (CoreUtilities::$rRequest['action'] == 'search') { + if (RequestManager::getAll()['action'] == 'search') { $rReturn = array('total_count' => 0, 'items' => array(), 'result' => true); $rTables = array('lines' => array('Lines', 'line?id=', '`username`, `admin_notes`, `reseller_notes`, `last_ip`, `contact`', 'id', 'username'), 'mag_devices' => array('MAG Devices', 'mag?id=', '`mac_filter`, `ip`', 'mag_id', 'mac'), 'enigma2_devices' => array('Enigma2 Devices', 'enigma?id=', '`mac_filter`, `public_ip`', 'device_id', 'mac'), 'users' => array('Users', 'user?id=', '`username`, `email`, `ip`, `notes`, `reseller_dns`', 'id', 'username'), 'streams' => array('Streams, Movies & Episodes', 'stream_view?id=', '`stream_display_name`, `stream_source`, `notes`, `channel_id`', 'id', 'stream_display_name'), 'streams_series' => array('TV Series', 'serie?id=', '`title`, `plot`, `cast`, `director`', 'id', 'title')); $rLimit = 100; - $rTerm = strtolower(preg_replace('/[^[:alnum:][:space:]]/u', '', CoreUtilities::$rRequest['search'])); - $rTermSP = strtolower(preg_replace('/[^[:alnum:][:space:]]/u', ' ', CoreUtilities::$rRequest['search'])); + $rTerm = strtolower(preg_replace('/[^[:alnum:][:space:]]/u', '', RequestManager::getAll()['search'])); + $rTermSP = strtolower(preg_replace('/[^[:alnum:][:space:]]/u', ' ', RequestManager::getAll()['search'])); if (!empty($rTermSP)) { $rItems = array(); @@ -3646,7 +3646,7 @@ if (isset($_SESSION['hash'])) { } } array_multisort(array_column($rItems, 'score'), SORT_DESC, $rItems); - $rItems = array_slice($rItems, 0, (intval(CoreUtilities::$rSettings['search_items']) ?: 50)); + $rItems = array_slice($rItems, 0, (intval(SettingsManager::getAll()['search_items']) ?: 50)); $rStreamNameIDs = $rDeviceIDs = $rLineIDs = $rOwnerIDs = $rUserIDs = $rSeriesIDs = $rStreamIDs = array(); foreach ($rItems as $rItem) { @@ -3748,8 +3748,8 @@ if (isset($_SESSION['hash'])) { array_multisort(array_column($rServerItems[$rStreamID], 'priority'), SORT_DESC, $rServerItems[$rStreamID]); } - if (CoreUtilities::$rSettings['redis_handler']) { - $rConnectionCount = CoreUtilities::getStreamConnections($rStreamIDs, true, true); + if (SettingsManager::getAll()['redis_handler']) { + $rConnectionCount = ConnectionTracker::getStreamConnections($rStreamIDs, true, true); } else { $db->query('SELECT `stream_id`, COUNT(*) AS `count` FROM `lines_live` WHERE `stream_id` IN (' . implode(',', $rStreamIDs) . ') AND `hls_end` = 0;'); @@ -3801,9 +3801,9 @@ if (isset($_SESSION['hash'])) { if (0 >= count($rLineIDs)) { } else { - if (CoreUtilities::$rSettings['redis_handler']) { - $rLineConnectionCount = CoreUtilities::getUserConnections($rLineIDs, true); - $rConnectionMap = CoreUtilities::getFirstConnection($rLineIDs); + if (SettingsManager::getAll()['redis_handler']) { + $rLineConnectionCount = ConnectionTracker::getUserConnections($rLineIDs, true); + $rConnectionMap = ConnectionTracker::getFirstConnection($rLineIDs); $rLStreamIDs = array(); foreach ($rConnectionMap as $rUserID => $rConnection) { @@ -3858,7 +3858,7 @@ if (isset($_SESSION['hash'])) { } } - $rCategories = getCategories(null); + $rCategories = CategoryService::getAllByType(null); $rGroups = GroupService::getAll(); foreach ($rItems as $rItem) { @@ -4338,15 +4338,15 @@ if (isset($_SESSION['hash'])) { $rLastInfo['stream_display_name'] = $rStreamNames[$rLastInfo['stream_id']]; if ($rLastInfo['online']) { - $rLastInfoText = "" . $rLastInfo['stream_display_name'] . "
Online: " . CoreUtilities::secondsToTime(time() - $rLastInfo['last_active']) . ''; + $rLastInfoText = "" . $rLastInfo['stream_display_name'] . "
Online: " . TimeUtils::secondsToTime(time() - $rLastInfo['last_active']) . ''; } else { - $rLastInfoText = "Last Active
" . (($rLastInfo['date_end'] ? date(CoreUtilities::$rSettings['date_format'], $rLastInfo['date_end']) . '
' . date('H:i:s', $rLastInfo['date_end']) : 'Never')) . '
'; + $rLastInfoText = "Last Active
" . (($rLastInfo['date_end'] ? date(SettingsManager::getAll()['date_format'], $rLastInfo['date_end']) . '
' . date('H:i:s', $rLastInfo['date_end']) : 'Never')) . '
'; } } else { $rLastInfoText = "Last Active
Never"; } - $rExpires = ($rItem['exp_date'] ? date(CoreUtilities::$rSettings['datetime_format'], $rItem['exp_date']) : null); + $rExpires = ($rItem['exp_date'] ? date(SettingsManager::getAll()['datetime_format'], $rItem['exp_date']) : null); $rHTML = ' - - - - - - + + 'source', 'parent' => '#', 'text' => "Active", 'icon' => 'mdi mdi-play', 'state' => ['opened' => true]], + ['id' => 'offline', 'parent' => '#', 'text' => "Offline", 'icon' => 'mdi mdi-stop', 'state' => ['opened' => true]] + ]; + + foreach ($rServers as $rServer) { + $rServerTree[] = array('id' => $rServer['id'], 'parent' => 'offline', 'text' => $rServer['server_name'], 'icon' => 'mdi mdi-server-network', 'state' => array('opened' => true)); + } + $_TITLE = 'TV Series'; + require_once __DIR__ . '/../public/Views/layouts/admin.php'; + renderUnifiedLayoutHeader('admin'); + ?> + + + + + + + + \ No newline at end of file diff --git a/src/admin/series.php b/src/admin/series.php index 5b4ff5fd0..644b9c26b 100644 --- a/src/admin/series.php +++ b/src/admin/series.php @@ -8,7 +8,7 @@ goHome(); } - $rCategories = getCategories('series'); + $rCategories = CategoryService::getAllByType('series'); $_TITLE = 'TV Series'; require_once __DIR__ . '/../public/Views/layouts/admin.php'; renderUnifiedLayoutHeader('admin'); @@ -51,21 +51,21 @@
@@ -266,12 +266,12 @@ renderUnifiedLayoutFooter('admin'); } echo "\t\t\t\t" . 'order: [[ '; - echo (isset(CoreUtilities::$rRequest['order']) ? intval(CoreUtilities::$rRequest['order']) : 0); + echo (isset(RequestManager::getAll()['order']) ? intval(RequestManager::getAll()['order']) : 0); echo ', "'; - echo (in_array(strtolower(CoreUtilities::$rRequest['dir'] ?? ''), ['asc', 'desc'], true) ? strtolower(CoreUtilities::$rRequest['dir']) : 'desc'); + echo (in_array(strtolower(RequestManager::getAll()['dir'] ?? ''), ['asc', 'desc'], true) ? strtolower(RequestManager::getAll()['dir']) : 'desc'); echo '" ]],' . "\r\n\t\t\t\t" . 'pageLength: parseInt(rEntries),' . "\r\n\t\t\t\t" . 'lengthMenu: [10, 25, 50, 250, 500, 1000],' . "\r\n" . ' displayStart: (parseInt(rPage)-1) * parseInt(rEntries)' . "\r\n\t\t\t" . '});' . "\r\n" . ' function doSearch(rValue) {' . "\r\n" . ' clearTimeout(window.rSearch); window.rSearch = setTimeout(function(){ rTable.search(rValue).draw(); }, 500);' . "\r\n" . ' }' . "\r\n\t\t\t" . '$("#datatable-streampage").css("width", "100%");' . "\r\n\t\t\t" . "\$('#series_search').keyup(function(){" . "\r\n\t\t\t\t" . 'if (!window.rClearing) {' . "\r\n" . ' delParam("page");' . "\r\n" . ' rTable.page(0);' . "\r\n" . ' if ($("#series_search").val()) {' . "\r\n\t\t\t\t\t\t" . 'setParam("search", $("#series_search").val());' . "\r\n\t\t\t\t\t" . '} else {' . "\r\n\t\t\t\t\t\t" . 'delParam("search");' . "\r\n\t\t\t\t\t" . '}' . "\r\n\t\t\t\t\t" . 'checkClear();' . "\r\n\t\t\t\t\t" . 'doSearch($(this).val());' . "\r\n\t\t\t\t" . '}' . "\r\n\t\t\t" . '})' . "\r\n\t\t\t" . "\$('#series_show_entries').change(function(){" . "\r\n\t\t\t\t" . 'if (!window.rClearing) {' . "\r\n" . ' delParam("page");' . "\r\n" . ' rTable.page(0);' . "\r\n" . ' if ($("#series_show_entries").val()) {' . "\r\n\t\t\t\t\t\t" . 'setParam("entries", $("#series_show_entries").val());' . "\r\n\t\t\t\t\t" . '} else {' . "\r\n\t\t\t\t\t\t" . 'delParam("entries");' . "\r\n\t\t\t\t\t" . '}' . "\r\n\t\t\t\t\t" . 'checkClear();' . "\r\n\t\t\t\t\t" . 'rTable.page.len($(this).val()).draw();' . "\r\n\t\t\t\t" . '}' . "\r\n\t\t\t" . '})' . "\r\n\t\t\t" . "\$('#series_category_id').change(function(){" . "\r\n\t\t\t\t" . 'if (!window.rClearing) {' . "\r\n" . ' delParam("page");' . "\r\n" . ' rTable.page(0);' . "\r\n" . ' if ($("#series_category_id").val()) {' . "\r\n\t\t\t\t\t\t" . 'setParam("category", $("#series_category_id").val());' . "\r\n\t\t\t\t\t" . '} else {' . "\r\n\t\t\t\t\t\t" . 'delParam("category");' . "\r\n\t\t\t\t\t" . '}' . "\r\n\t\t\t\t\t" . 'checkClear();' . "\r\n\t\t\t\t\t" . 'rTable.ajax.reload( null, false );' . "\r\n\t\t\t\t" . '}' . "\r\n\t\t\t" . '})' . "\r\n\t\t\t" . "if (\$('#series_search').val()) {" . "\r\n\t\t\t\t" . "rTable.search(\$('#series_search').val()).draw();" . "\r\n\t\t\t" . '}' . "\r\n" . ' $("#btn-export-csv").click(function() {' . "\r\n" . ' $.toast("Generating CSV report...");' . "\r\n" . ' window.location.href = "api?action=report¶ms=" + encodeURIComponent(JSON.stringify($("#datatable-streampage").DataTable().ajax.params()));' . "\r\n\t\t\t" . '});' . "\r\n" . ' checkClear();' . "\r\n\t\t" . '});' . "\r\n" . ' ' . "\r\n\t\t"; ?> - + $(document).ready(function() { initSearch(); }); diff --git a/src/admin/series_mass.php b/src/admin/series_mass.php index 369fe47a1..5dd019796 100644 --- a/src/admin/series_mass.php +++ b/src/admin/series_mass.php @@ -1,359 +1,359 @@ - - - - - +