• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

visavi / rotor / 28968938134

08 Jul 2026 07:12PM UTC coverage: 32.79% (+0.06%) from 32.729%
28968938134

push

github

visavi
Админ-логи и очистка кеша перенесены в модули, добавлена более лучшая очистка кеша

1 of 16 new or added lines in 7 files covered. (6.25%)

3 existing lines in 1 file now uncovered.

1849 of 5639 relevant lines covered (32.79%)

3.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/app/Http/Controllers/Admin/ModuleController.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace App\Http\Controllers\Admin;
6

7
use App\Models\Module;
8
use App\Models\ModuleRegistry;
9
use App\Providers\ModuleServiceProvider;
10
use Illuminate\Http\RedirectResponse;
11
use Illuminate\Http\Request;
12
use Illuminate\Support\Facades\Artisan;
13
use Illuminate\Support\Facades\Http;
14
use Illuminate\View\View;
15
use ZipArchive;
16

17
class ModuleController extends AdminController
18
{
19
    /**
20
     * Главная страница
21
     */
22
    public function index(): View
×
23
    {
24
        $modules = Module::query()->get();
×
25
        $moduleInstall = [];
×
26
        foreach ($modules as $module) {
×
27
            $moduleInstall[$module->name] = $module;
×
28
        }
29

30
        $moduleNames = [];
×
31
        $modulesLoaded = glob(base_path('modules/*'), GLOB_ONLYDIR);
×
32
        foreach ($modulesLoaded as $module) {
×
33
            if (file_exists($module . '/module.php')) {
×
34
                $moduleNames[basename($module)] = include $module . '/module.php';
×
35
            }
36
        }
37

38
        $installed = array_intersect_key($moduleInstall, $moduleNames);
×
39
        $counts = [
×
40
            'all'           => count($moduleNames),
×
41
            'installed'     => count(array_filter($installed, fn ($m) => $m->active)),
×
42
            'disabled'      => count(array_filter($installed, fn ($m) => ! $m->active)),
×
43
            'not-installed' => count($moduleNames) - count($installed),
×
44
        ];
×
45

46
        $registryModules = ModuleRegistry::getAvailableModules();
×
47
        $failedModules = ModuleServiceProvider::$failed;
×
48

49
        return view('admin/modules/index', compact('moduleInstall', 'moduleNames', 'counts', 'registryModules', 'failedModules'));
×
50
    }
51

52
    /**
53
     * Просмотр модуля
54
     */
55
    public function module(Request $request): View
×
56
    {
57
        $moduleName = (string) $request->input('module');
×
58
        $modulePath = base_path('modules/' . $moduleName);
×
59

60
        if (! preg_match('|^[A-Z][\w\-]+$|', $moduleName) || ! file_exists($modulePath)) {
×
61
            abort(200, __('admin.modules.module_not_found'));
×
62
        }
63

64
        $moduleConfig = include $modulePath . '/module.php';
×
65
        $module = Module::query()->where('name', $moduleName)->first();
×
66

67
        if (file_exists($modulePath . '/screenshots')) {
×
68
            $moduleConfig['screenshots'] = glob($modulePath . '/screenshots/*.{gif,png,jpg,jpeg,webp}', GLOB_BRACE);
×
69
        }
70

71
        if (file_exists($modulePath . '/database/migrations')) {
×
72
            $migrations = [];
×
73
            foreach (glob($modulePath . '/database/migrations/*.php') as $migration) {
×
74
                $migrations[basename($migration)] = file_get_contents($migration);
×
75
            }
76
            $moduleConfig['migrations'] = $migrations;
×
77
        }
78

79
        if (file_exists($modulePath . '/resources/assets')) {
×
80
            $moduleConfig['symlink'] = Module::getLinkNameByPath($modulePath);
×
81
        }
82

83
        if (file_exists($modulePath . '/config.php')) {
×
84
            $moduleConfig['config'] = file_get_contents($modulePath . '/config.php');
×
85
        }
86

87
        if (file_exists($modulePath . '/routes.php')) {
×
88
            $moduleConfig['routes'] = file_get_contents($modulePath . '/routes.php');
×
89
        }
90

91
        if (file_exists($modulePath . '/hooks.php')) {
×
92
            $moduleConfig['hooks'] = file_get_contents($modulePath . '/hooks.php');
×
93
        }
94

95
        if (file_exists($modulePath . '/helpers.php')) {
×
96
            $moduleConfig['helpers'] = file_get_contents($modulePath . '/helpers.php');
×
97
        }
98

99
        if (file_exists($modulePath . '/middleware.php')) {
×
100
            $moduleConfig['middleware'] = file_get_contents($modulePath . '/middleware.php');
×
101
        }
102

103
        foreach (['changelog.md', 'CHANGELOG.md'] as $changelog) {
×
104
            if (file_exists($modulePath . '/' . $changelog)) {
×
105
                $moduleConfig['changelog'] = file_get_contents($modulePath . '/' . $changelog);
×
106
                break;
×
107
            }
108
        }
109

110
        $registryInfo = ModuleRegistry::getAvailableModules()[$moduleName] ?? null;
×
111

112
        return view('admin/modules/module', compact('module', 'moduleConfig', 'moduleName', 'registryInfo'));
×
113
    }
114

115
    /**
116
     * Установка модуля
117
     */
118
    public function install(Request $request): RedirectResponse
×
119
    {
120
        $moduleName = $request->input('module');
×
121
        $enable = int($request->input('enable'));
×
122
        $update = int($request->input('update'));
×
123
        $modulePath = base_path('modules/' . $moduleName);
×
124

125
        if (! preg_match('|^[A-Z][\w\-]+$|', $moduleName) || ! file_exists($modulePath)) {
×
126
            abort(200, __('admin.modules.module_not_found'));
×
127
        }
128

129
        $module = Module::query()->firstOrNew(['name' => $moduleName]);
×
130

131
        $moduleConfig = include $modulePath . '/module.php';
×
132

133
        $requires = $moduleConfig['requires'] ?? null;
×
134
        if ($requires && version_compare(ROTOR_VERSION, $requires, '<')) {
×
135
            setFlash('danger', __('admin.modules.requires') . ' ' . $requires . '!');
×
136

137
            return redirect('admin/modules/module?module=' . $moduleName);
×
138
        }
139

140
        // Файлы на диск кладём только для активного модуля: свежая установка,
141
        // включение или обновление уже активного. Обновление выключенного модуля
142
        // лишь повышает версию — его файлы не должны возвращаться на диск.
143
        if (! $module->exists || $enable || $module->active) {
×
144
            $module->createSymlink();
×
145
            $module->publish();
×
146
            $module->migrate();
×
147
        }
148

149
        $result = __('admin.modules.module_success_installed');
×
150

151
        if ($module->exists) {
×
152
            if ($update) {
×
153
                $module->update([
×
154
                    'version' => $moduleConfig['version'],
×
155
                ]);
×
156
                $result = __('admin.modules.module_success_updated');
×
157
            }
158

159
            if ($enable) {
×
160
                $module->update([
×
161
                    'active' => true,
×
162
                ]);
×
163
                $result = __('admin.modules.module_success_enabled');
×
164
            }
165
        } else {
166
            $module->fill([
×
167
                'version' => $moduleConfig['version'],
×
168
            ])->save();
×
169
        }
170

171
        // Полная синхронизация активных модулей: порядок установки перестаёт
172
        // иметь значение (напр. перевод модуля-языка подмешается в Форум,
173
        // даже если Форум поставили позже). Сама сбрасывает кэш модулей.
174
        Module::syncAll();
×
175

176
        // После syncAll — пересборка увидит роуты нового модуля
NEW
177
        refreshCaches();
×
178

UNCOV
179
        setFlash('success', $result);
×
180

181
        return redirect('admin/modules/module?module=' . $moduleName);
×
182
    }
183

184
    /**
185
     * Каталог модулей из реестров
186
     */
187
    public function marketplace(Request $request): View
×
188
    {
189
        $force = (bool) $request->input('refresh');
×
190
        $available = ModuleRegistry::getAvailableModules($force);
×
191

192
        $modules = Module::query()->get()->keyBy('name');
×
193
        $moduleNames = [];
×
194

195
        $modulesLoaded = glob(base_path('modules/*'), GLOB_ONLYDIR);
×
196
        foreach ($modulesLoaded as $module) {
×
197
            $moduleNames[] = basename($module);
×
198
        }
199

200
        $counts = ['all' => count($available), 'installed' => 0, 'disabled' => 0, 'not-installed' => 0];
×
201
        foreach ($available as $name => $info) {
×
202
            $localExists = in_array($name, $moduleNames, true);
×
203
            $installed = $modules->has($name) && $localExists;
×
204

205
            if ($installed) {
×
206
                $counts[$modules[$name]->active ? 'installed' : 'disabled']++;
×
207
            } else {
208
                $counts['not-installed']++;
×
209
            }
210
        }
211

212
        return view('admin/modules/marketplace', compact('available', 'modules', 'moduleNames', 'counts'));
×
213
    }
214

215
    /**
216
     * Форма загрузки модуля
217
     */
218
    public function upload(): View
×
219
    {
220
        return view('admin/modules/upload');
×
221
    }
222

223
    /**
224
     * Установка модуля из ZIP-файла
225
     */
226
    public function uploadZip(Request $request): RedirectResponse
×
227
    {
228
        if (! $request->hasFile('zip') || ! $request->file('zip')->isValid()) {
×
229
            setFlash('danger', __('admin.modules.upload_invalid_file'));
×
230

231
            return redirect()->route('admin.modules.upload');
×
232
        }
233

234
        try {
235
            $moduleName = $this->extractZip($request->file('zip')->getPathname());
×
236
        } catch (\Exception $e) {
×
237
            setFlash('danger', $e->getMessage());
×
238

239
            return redirect()->route('admin.modules.upload');
×
240
        }
241

242
        return redirect('/admin/modules/module?module=' . $moduleName)
×
243
            ->with('success', __('admin.modules.upload_success_extracted'));
×
244
    }
245

246
    /**
247
     * Установка модуля по URL
248
     */
249
    public function download(Request $request): RedirectResponse
×
250
    {
251
        $url = trim($request->input('url', ''));
×
252

253
        if (! filter_var($url, FILTER_VALIDATE_URL) || ! in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'], true)) {
×
254
            setFlash('danger', __('admin.modules.download_invalid_url'));
×
255

256
            return redirect()->back();
×
257
        }
258

259
        $maxSize = (int) config('modules.download_max_size') * 1024 * 1024;
×
260

261
        $tempDir = storage_path('app/temp');
×
262
        if (! is_dir($tempDir)) {
×
263
            mkdir($tempDir, 0755, true);
×
264
        }
265
        $tempFile = $tempDir . '/rotor_module_' . uniqid() . '.zip';
×
266

267
        try {
268
            // Потоковая запись: лимит проверяется по мере чтения, тело не держим в памяти
269
            $response = Http::timeout(30)->withOptions(['stream' => true])->get($url);
×
270

271
            if (! $response->ok()) {
×
272
                setFlash('danger', __('admin.modules.download_failed'));
×
273

274
                return redirect()->back();
×
275
            }
276

277
            $stream = $response->toPsrResponse()->getBody();
×
278
            $handle = fopen($tempFile, 'wb');
×
279

280
            if ($handle === false) {
×
281
                setFlash('danger', __('admin.modules.download_failed'));
×
282

283
                return redirect()->back();
×
284
            }
285
            $written = 0;
×
286
            $tooLarge = false;
×
287

288
            while (! $stream->eof()) {
×
289
                $chunk = $stream->read(8192);
×
290
                $written += strlen($chunk);
×
291

292
                if ($written > $maxSize) {
×
293
                    $tooLarge = true;
×
294
                    break;
×
295
                }
296

297
                fwrite($handle, $chunk);
×
298
            }
299

300
            fclose($handle);
×
301

302
            if ($tooLarge) {
×
303
                @unlink($tempFile);
×
304
                setFlash('danger', __('admin.modules.download_too_large', ['size' => formatSize($maxSize)]));
×
305

306
                return redirect()->back();
×
307
            }
308

309
            if (file_get_contents($tempFile, false, null, 0, 4) !== "PK\x03\x04") {
×
310
                @unlink($tempFile);
×
311
                setFlash('danger', __('admin.modules.download_not_zip'));
×
312

313
                return redirect()->back();
×
314
            }
315

316
            try {
317
                $moduleName = $this->extractZip($tempFile);
×
318
            } finally {
319
                @unlink($tempFile);
×
320
            }
321
        } catch (\Exception $e) {
×
322
            @unlink($tempFile);
×
323
            setFlash('danger', $e->getMessage());
×
324

325
            return redirect()->back();
×
326
        }
327

328
        // Для уже установленного модуля распаковка — лишь первый шаг обновления:
329
        // подсказываем, что версия применится по кнопке «Применить обновление»
330
        $extracted = Module::query()->where('name', $moduleName)->exists()
×
331
            ? __('admin.modules.update_extracted')
×
332
            : __('admin.modules.upload_success_extracted');
×
333

334
        return redirect('/admin/modules/module?module=' . $moduleName)
×
335
            ->with('success', $extracted);
×
336
    }
337

338
    /**
339
     * Распаковка ZIP-архива модуля
340
     */
341
    private function extractZip(string $zipPath): string
×
342
    {
343
        $zip = new ZipArchive();
×
344

345
        if ($zip->open($zipPath) !== true) {
×
346
            throw new \RuntimeException(__('admin.modules.zip_open_failed'));
×
347
        }
348

349
        $topDirs = [];
×
350
        for ($i = 0; $i < $zip->numFiles; $i++) {
×
351
            $name = $zip->getNameIndex($i);
×
352

353
            if (str_contains($name, '..')) {
×
354
                $zip->close();
×
355
                throw new \RuntimeException(__('admin.modules.zip_invalid_path'));
×
356
            }
357

358
            $parts = explode('/', $name);
×
359
            if ($parts[0] !== '') {
×
360
                $topDirs[$parts[0]] = true;
×
361
            }
362
        }
363

364
        if (count($topDirs) !== 1) {
×
365
            $zip->close();
×
366
            throw new \RuntimeException(__('admin.modules.zip_invalid_structure'));
×
367
        }
368

369
        $moduleName = array_key_first($topDirs);
×
370

371
        if (! preg_match('/^[A-Z][A-Za-z0-9]+$/', $moduleName)) {
×
372
            $zip->close();
×
373
            throw new \RuntimeException(__('admin.modules.zip_invalid_name'));
×
374
        }
375

376
        $targetPath = base_path('modules/' . $moduleName);
×
377

378
        // Существующий модуль уводим в резервную копию, чтобы чистая распаковка
379
        // не оставила старых файлов и можно было откатиться при сбое
380
        $backupPath = null;
×
381
        if (is_dir($targetPath)) {
×
382
            $backupPath = base_path('modules/.backup_' . $moduleName . '_' . time());
×
383
            if (! rename($targetPath, $backupPath)) {
×
384
                $zip->close();
×
385
                throw new \RuntimeException(__('admin.modules.zip_backup_failed'));
×
386
            }
387
        }
388

389
        if (! $zip->extractTo(base_path('modules/'))) {
×
390
            $zip->close();
×
391
            $this->restoreBackup($targetPath, $backupPath);
×
392
            throw new \RuntimeException(__('admin.modules.zip_extract_failed'));
×
393
        }
394
        $zip->close();
×
395

396
        $this->chmodRecursive($targetPath);
×
397

398
        if (! file_exists($targetPath . '/module.php')) {
×
399
            $this->restoreBackup($targetPath, $backupPath);
×
400
            throw new \RuntimeException(__('admin.modules.zip_no_module_file'));
×
401
        }
402

403
        if ($backupPath) {
×
404
            $this->deleteDirectory($backupPath);
×
405
        }
406

407
        // Файлы перезаписаны на диске, но opcache (revalidate_freq) ещё держит
408
        // старый module.php — без сброса кнопка обновления и новый код модуля
409
        // подхватятся только со следующим запросом после ревалидации
410
        if (function_exists('opcache_reset')) {
×
411
            opcache_reset();
×
412
        }
413

414
        return $moduleName;
×
415
    }
416

417
    /**
418
     * Удаление файлов модуля с диска
419
     */
420
    public function deleteFiles(Request $request): RedirectResponse
×
421
    {
422
        $moduleName = $request->input('module');
×
423
        $modulePath = base_path('modules/' . $moduleName);
×
424

425
        if (! preg_match('|^[A-Z][\w\-]+$|', $moduleName) || ! file_exists($modulePath)) {
×
426
            abort(200, __('admin.modules.module_not_found'));
×
427
        }
428

429
        if (Module::query()->where('name', $moduleName)->exists()) {
×
430
            abort(200, __('admin.modules.delete_files_not_uninstalled'));
×
431
        }
432

433
        $this->deleteDirectory($modulePath);
×
434

NEW
435
        refreshCaches();
×
436
        setFlash('success', __('admin.modules.module_files_deleted'));
×
437

438
        return redirect()->route('admin.modules.index');
×
439
    }
440

441
    /**
442
     * Откат распаковки: удалить частично распакованное и вернуть резервную копию
443
     */
444
    private function restoreBackup(string $targetPath, ?string $backupPath): void
×
445
    {
446
        $this->deleteDirectory($targetPath);
×
447

448
        if ($backupPath && is_dir($backupPath)) {
×
449
            rename($backupPath, $targetPath);
×
450
        }
451
    }
452

453
    /**
454
     * Рекурсивно устанавливает права доступа (755 для директорий, 644 для файлов)
455
     */
456
    private function chmodRecursive(string $path): void
×
457
    {
458
        chmod($path, 0755);
×
459

460
        foreach (scandir($path) as $item) {
×
461
            if ($item === '.' || $item === '..') {
×
462
                continue;
×
463
            }
464

465
            $full = $path . '/' . $item;
×
466
            if (is_dir($full)) {
×
467
                $this->chmodRecursive($full);
×
468
            } else {
469
                chmod($full, 0644);
×
470
            }
471
        }
472
    }
473

474
    /**
475
     * Рекурсивно удаляет директорию, включая симлинки
476
     */
477
    private function deleteDirectory(string $path): void
×
478
    {
479
        if (is_link($path)) {
×
480
            unlink($path);
×
481

482
            return;
×
483
        }
484

485
        if (! is_dir($path)) {
×
486
            return;
×
487
        }
488

489
        foreach (scandir($path) as $item) {
×
490
            if ($item === '.' || $item === '..') {
×
491
                continue;
×
492
            }
493

494
            $full = $path . '/' . $item;
×
495
            is_dir($full) && ! is_link($full) ? $this->deleteDirectory($full) : unlink($full);
×
496
        }
497

498
        rmdir($path);
×
499
    }
500

501
    /**
502
     * Удаление/Выключение модуля
503
     */
504
    public function uninstall(Request $request): RedirectResponse
×
505
    {
506
        $moduleName = $request->input('module');
×
507
        $disable = int($request->input('disable'));
×
508
        $modulePath = base_path('modules/' . $moduleName);
×
509

510
        if (! preg_match('|^[A-Z][\w\-]+$|', $moduleName) || ! file_exists($modulePath)) {
×
511
            abort(200, __('admin.modules.module_not_found'));
×
512
        }
513

514
        $module = Module::query()->where('name', $moduleName)->first();
×
515
        if (! $module) {
×
516
            abort(200, __('admin.modules.module_not_found'));
×
517
        }
518

519
        $module->deleteSymlink();
×
520
        $module->unpublish();
×
521

UNCOV
522
        if ($disable) {
×
523
            $module->update([
×
524
                'active' => false,
×
525
            ]);
×
526
            $result = __('admin.modules.module_success_disabled');
×
527
        } else {
528
            if (config('modules.safe_mode')) {
×
529
                setFlash('danger', __('admin.modules.safe_mode_enabled'));
×
530

531
                return redirect('admin/modules/module?module=' . $moduleName);
×
532
            }
533

534
            $module->rollback();
×
535
            $module->delete();
×
536
            $result = __('admin.modules.module_success_deleted');
×
537
        }
538

539
        clearCache(['modules', 'settings']);
×
540

541
        // После смены статуса модуля — пересборка соберёт роуты без него
NEW
542
        refreshCaches();
×
543

UNCOV
544
        setFlash('success', $result);
×
545

546
        return redirect('admin/modules/module?module=' . $moduleName);
×
547
    }
548
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc