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

visavi / rotor / 27909067548

21 Jun 2026 03:33PM UTC coverage: 16.253% (-0.09%) from 16.344%
27909067548

push

github

visavi
Добавлено более понятное обновления модулей, кнопки заменены на скачать обновление и применить обновление, на странице обновления в админке есть возможность выбрать апгрейд или скачать полную версиию, добавлена кнопка переустановки ядра, добавлен сброс opcache чтобы кнопка обновления появлялась сразу после скачивания, испавлено экранирование в md

0 of 40 new or added lines in 4 files covered. (0.0%)

3 existing lines in 3 files now uncovered.

970 of 5968 relevant lines covered (16.25%)

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
        clearCache(['modules', 'settings']);
×
172
        setFlash('success', $result);
×
173

174
        return redirect('admin/modules/module?module=' . $moduleName);
×
175
    }
176

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

185
        $modules = Module::query()->get()->keyBy('name');
×
186
        $moduleNames = [];
×
187

188
        $modulesLoaded = glob(base_path('modules/*'), GLOB_ONLYDIR);
×
189
        foreach ($modulesLoaded as $module) {
×
190
            $moduleNames[] = basename($module);
×
191
        }
192

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

198
            if ($installed) {
×
199
                $counts[$modules[$name]->active ? 'installed' : 'disabled']++;
×
200
            } else {
201
                $counts['not-installed']++;
×
202
            }
203
        }
204

205
        return view('admin/modules/marketplace', compact('available', 'modules', 'moduleNames', 'counts'));
×
206
    }
207

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

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

224
            return redirect()->route('admin.modules.upload');
×
225
        }
226

227
        try {
228
            $moduleName = $this->extractZip($request->file('zip')->getPathname());
×
229
        } catch (\Exception $e) {
×
230
            setFlash('danger', $e->getMessage());
×
231

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

235
        return redirect('/admin/modules/module?module=' . $moduleName)
×
236
            ->with('success', __('admin.modules.upload_success_extracted'));
×
237
    }
238

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

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

249
            return redirect()->back();
×
250
        }
251

252
        $maxSize = (int) config('modules.download_max_size') * 1024 * 1024;
×
253

254
        $tempDir = storage_path('app/temp');
×
255
        if (! is_dir($tempDir)) {
×
256
            mkdir($tempDir, 0755, true);
×
257
        }
258
        $tempFile = $tempDir . '/rotor_module_' . uniqid() . '.zip';
×
259

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

264
            if (! $response->ok()) {
×
265
                setFlash('danger', __('admin.modules.download_failed'));
×
266

267
                return redirect()->back();
×
268
            }
269

270
            $stream = $response->toPsrResponse()->getBody();
×
271
            $handle = fopen($tempFile, 'wb');
×
272

273
            if ($handle === false) {
×
274
                setFlash('danger', __('admin.modules.download_failed'));
×
275

276
                return redirect()->back();
×
277
            }
278
            $written = 0;
×
279
            $tooLarge = false;
×
280

281
            while (! $stream->eof()) {
×
282
                $chunk = $stream->read(8192);
×
283
                $written += strlen($chunk);
×
284

285
                if ($written > $maxSize) {
×
286
                    $tooLarge = true;
×
287
                    break;
×
288
                }
289

290
                fwrite($handle, $chunk);
×
291
            }
292

293
            fclose($handle);
×
294

295
            if ($tooLarge) {
×
296
                @unlink($tempFile);
×
297
                setFlash('danger', __('admin.modules.download_too_large', ['size' => formatSize($maxSize)]));
×
298

299
                return redirect()->back();
×
300
            }
301

302
            if (file_get_contents($tempFile, false, null, 0, 4) !== "PK\x03\x04") {
×
303
                @unlink($tempFile);
×
304
                setFlash('danger', __('admin.modules.download_not_zip'));
×
305

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

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

318
            return redirect()->back();
×
319
        }
320

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

327
        return redirect('/admin/modules/module?module=' . $moduleName)
×
NEW
328
            ->with('success', $extracted);
×
329
    }
330

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

338
        if ($zip->open($zipPath) !== true) {
×
339
            throw new \RuntimeException(__('admin.modules.zip_open_failed'));
×
340
        }
341

342
        $topDirs = [];
×
343
        for ($i = 0; $i < $zip->numFiles; $i++) {
×
344
            $name = $zip->getNameIndex($i);
×
345

346
            if (str_contains($name, '..')) {
×
347
                $zip->close();
×
348
                throw new \RuntimeException(__('admin.modules.zip_invalid_path'));
×
349
            }
350

351
            $parts = explode('/', $name);
×
352
            if ($parts[0] !== '') {
×
353
                $topDirs[$parts[0]] = true;
×
354
            }
355
        }
356

357
        if (count($topDirs) !== 1) {
×
358
            $zip->close();
×
359
            throw new \RuntimeException(__('admin.modules.zip_invalid_structure'));
×
360
        }
361

362
        $moduleName = array_key_first($topDirs);
×
363

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

369
        $targetPath = base_path('modules/' . $moduleName);
×
370

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

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

389
        $this->chmodRecursive($targetPath);
×
390

391
        if (! file_exists($targetPath . '/module.php')) {
×
392
            $this->restoreBackup($targetPath, $backupPath);
×
393
            throw new \RuntimeException(__('admin.modules.zip_no_module_file'));
×
394
        }
395

396
        if ($backupPath) {
×
397
            $this->deleteDirectory($backupPath);
×
398
        }
399

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

UNCOV
407
        return $moduleName;
×
408
    }
409

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

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

422
        if (Module::query()->where('name', $moduleName)->exists()) {
×
423
            abort(200, __('admin.modules.delete_files_not_uninstalled'));
×
424
        }
425

426
        $this->deleteDirectory($modulePath);
×
427

428
        Artisan::call('route:clear');
×
429
        setFlash('success', __('admin.modules.module_files_deleted'));
×
430

431
        return redirect()->route('admin.modules.index');
×
432
    }
433

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

441
        if ($backupPath && is_dir($backupPath)) {
×
442
            rename($backupPath, $targetPath);
×
443
        }
444
    }
445

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

453
        foreach (scandir($path) as $item) {
×
454
            if ($item === '.' || $item === '..') {
×
455
                continue;
×
456
            }
457

458
            $full = $path . '/' . $item;
×
459
            if (is_dir($full)) {
×
460
                $this->chmodRecursive($full);
×
461
            } else {
462
                chmod($full, 0644);
×
463
            }
464
        }
465
    }
466

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

475
            return;
×
476
        }
477

478
        if (! is_dir($path)) {
×
479
            return;
×
480
        }
481

482
        foreach (scandir($path) as $item) {
×
483
            if ($item === '.' || $item === '..') {
×
484
                continue;
×
485
            }
486

487
            $full = $path . '/' . $item;
×
488
            is_dir($full) && ! is_link($full) ? $this->deleteDirectory($full) : unlink($full);
×
489
        }
490

491
        rmdir($path);
×
492
    }
493

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

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

507
        $module = Module::query()->where('name', $moduleName)->first();
×
508
        if (! $module) {
×
509
            abort(200, __('admin.modules.module_not_found'));
×
510
        }
511

512
        $module->deleteSymlink();
×
513
        $module->unpublish();
×
514
        Artisan::call('route:clear');
×
515

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

526
                return redirect('admin/modules/module?module=' . $moduleName);
×
527
            }
528

529
            $module->rollback();
×
530
            $module->delete();
×
531
            $result = __('admin.modules.module_success_deleted');
×
532
        }
533

534
        clearCache(['modules', 'settings']);
×
535
        setFlash('success', $result);
×
536

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