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

visavi / rotor / 27918035804

21 Jun 2026 09:28PM UTC coverage: 16.223% (-0.03%) from 16.253%
27918035804

push

github

visavi
Синхронизация симлинков и публикаций в модулях + проверка пути публикации статики

0 of 17 new or added lines in 3 files covered. (0.0%)

3 existing lines in 3 files now uncovered.

970 of 5979 relevant lines covered (16.22%)

2.37 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
        $module->createSymlink();
×
141
        $module->publish();
×
142
        $module->migrate();
×
143

144
        Artisan::call('route:clear');
×
145
        $result = __('admin.modules.module_success_installed');
×
146

147
        if ($module->exists) {
×
148
            if ($update) {
×
149
                $module->update([
×
150
                    'version'    => $moduleConfig['version'],
×
151
                    'updated_at' => SITETIME,
×
152
                ]);
×
153
                $result = __('admin.modules.module_success_updated');
×
154
            }
155

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

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

UNCOV
176
        setFlash('success', $result);
×
177

178
        return redirect('admin/modules/module?module=' . $moduleName);
×
179
    }
180

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

189
        $modules = Module::query()->get()->keyBy('name');
×
190
        $moduleNames = [];
×
191

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

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

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

209
        return view('admin/modules/marketplace', compact('available', 'modules', 'moduleNames', 'counts'));
×
210
    }
211

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

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

228
            return redirect()->route('admin.modules.upload');
×
229
        }
230

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

236
            return redirect()->route('admin.modules.upload');
×
237
        }
238

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

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

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

253
            return redirect()->back();
×
254
        }
255

256
        $maxSize = (int) config('modules.download_max_size') * 1024 * 1024;
×
257

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

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

268
            if (! $response->ok()) {
×
269
                setFlash('danger', __('admin.modules.download_failed'));
×
270

271
                return redirect()->back();
×
272
            }
273

274
            $stream = $response->toPsrResponse()->getBody();
×
275
            $handle = fopen($tempFile, 'wb');
×
276

277
            if ($handle === false) {
×
278
                setFlash('danger', __('admin.modules.download_failed'));
×
279

280
                return redirect()->back();
×
281
            }
282
            $written = 0;
×
283
            $tooLarge = false;
×
284

285
            while (! $stream->eof()) {
×
286
                $chunk = $stream->read(8192);
×
287
                $written += strlen($chunk);
×
288

289
                if ($written > $maxSize) {
×
290
                    $tooLarge = true;
×
291
                    break;
×
292
                }
293

294
                fwrite($handle, $chunk);
×
295
            }
296

297
            fclose($handle);
×
298

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

303
                return redirect()->back();
×
304
            }
305

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

310
                return redirect()->back();
×
311
            }
312

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

322
            return redirect()->back();
×
323
        }
324

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

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

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

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

346
        $topDirs = [];
×
347
        for ($i = 0; $i < $zip->numFiles; $i++) {
×
348
            $name = $zip->getNameIndex($i);
×
349

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

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

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

366
        $moduleName = array_key_first($topDirs);
×
367

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

373
        $targetPath = base_path('modules/' . $moduleName);
×
374

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

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

393
        $this->chmodRecursive($targetPath);
×
394

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

400
        if ($backupPath) {
×
401
            $this->deleteDirectory($backupPath);
×
402
        }
403

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

411
        return $moduleName;
×
412
    }
413

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

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

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

430
        $this->deleteDirectory($modulePath);
×
431

432
        Artisan::call('route:clear');
×
433
        setFlash('success', __('admin.modules.module_files_deleted'));
×
434

435
        return redirect()->route('admin.modules.index');
×
436
    }
437

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

445
        if ($backupPath && is_dir($backupPath)) {
×
446
            rename($backupPath, $targetPath);
×
447
        }
448
    }
449

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

457
        foreach (scandir($path) as $item) {
×
458
            if ($item === '.' || $item === '..') {
×
459
                continue;
×
460
            }
461

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

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

479
            return;
×
480
        }
481

482
        if (! is_dir($path)) {
×
483
            return;
×
484
        }
485

486
        foreach (scandir($path) as $item) {
×
487
            if ($item === '.' || $item === '..') {
×
488
                continue;
×
489
            }
490

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

495
        rmdir($path);
×
496
    }
497

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

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

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

516
        $module->deleteSymlink();
×
517
        $module->unpublish();
×
518
        Artisan::call('route:clear');
×
519

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

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

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

538
        clearCache(['modules', 'settings']);
×
539
        setFlash('success', $result);
×
540

541
        return redirect('admin/modules/module?module=' . $moduleName);
×
542
    }
543
}
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