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

gammerce / sklep-sms / 31443529012

10 Aug 2026 11:45PM UTC coverage: 82.238% (-0.08%) from 82.321%
31443529012

Pull #446

github

web-flow
Merge 5c4a22180 into 4128e69c6
Pull Request #446: Bump nanoid from 3.3.3 to 3.3.18

11936 of 14514 relevant lines covered (82.24%)

37.62 hits per line

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

84.73
/includes/ServiceModules/MybbExtraGroups/MybbExtraGroupsServiceModule.php
1
<?php
2
namespace App\ServiceModules\MybbExtraGroups;
3

4
use App\Exceptions\InvalidConfigException;
5
use App\Http\Validation\Rules\EmailRule;
6
use App\Http\Validation\Rules\IntegerCommaSeparatedListRule;
7
use App\Http\Validation\Rules\IntegerRule;
8
use App\Http\Validation\Rules\MinValueRule;
9
use App\Http\Validation\Rules\MybbUserExistsRule;
10
use App\Http\Validation\Rules\NumberRule;
11
use App\Http\Validation\Rules\RequiredRule;
12
use App\Http\Validation\Rules\UserExistsRule;
13
use App\Http\Validation\Rules\YesNoRule;
14
use App\Http\Validation\Validator;
15
use App\Loggers\DatabaseLogger;
16
use App\Managers\UserManager;
17
use App\Models\MybbUser;
18
use App\Models\Purchase;
19
use App\Models\QuantityPrice;
20
use App\Models\Service;
21
use App\Models\Transaction;
22
use App\Models\UserService;
23
use App\Payment\Admin\AdminPaymentService;
24
use App\Payment\General\BoughtServiceService;
25
use App\Payment\General\PaymentMethod;
26
use App\Payment\General\PaymentOption;
27
use App\Payment\General\PurchasePriceService;
28
use App\ServiceModules\Interfaces\IServiceAdminManage;
29
use App\ServiceModules\Interfaces\IServiceCreate;
30
use App\ServiceModules\Interfaces\IServicePromoCode;
31
use App\ServiceModules\Interfaces\IServicePurchaseWeb;
32
use App\ServiceModules\Interfaces\IServiceUserOwnServices;
33
use App\ServiceModules\Interfaces\IServiceUserServiceAdminAdd;
34
use App\ServiceModules\Interfaces\IServiceUserServiceAdminDisplay;
35
use App\ServiceModules\ServiceModule;
36
use App\Support\Database;
37
use App\Support\PriceTextService;
38
use App\Support\QueryParticle;
39
use App\System\Auth;
40
use App\Theme\Template;
41
use App\Translation\TranslationManager;
42
use App\Translation\Translator;
43
use App\User\Permission;
44
use App\View\Html\BodyRow;
45
use App\View\Html\Cell;
46
use App\View\Html\ExpirationCell;
47
use App\View\Html\HeadCell;
48
use App\View\Html\NoneText;
49
use App\View\Html\PreWrapCell;
50
use App\View\Html\Structure;
51
use App\View\Html\UserRef;
52
use App\View\Html\Wrapper;
53
use App\View\Pagination\PaginationFactory;
54
use App\View\Renders\PurchasePriceRenderer;
55
use Exception;
56
use PDOException;
57
use Symfony\Component\HttpFoundation\Request;
58

59
class MybbExtraGroupsServiceModule extends ServiceModule implements
60
    IServiceAdminManage,
61
    IServiceCreate,
62
    IServiceUserServiceAdminDisplay,
63
    IServicePurchaseWeb,
64
    IServiceUserServiceAdminAdd,
65
    IServiceUserOwnServices,
66
    IServicePromoCode
67
{
68
    const MODULE_ID = "mybb_extra_groups";
69
    const USER_SERVICE_TABLE = "ss_user_service_mybb_extra_groups";
70

71
    /** @var string[] */
72
    private array $groups = [];
73

74
    private string $dbHost;
75
    private int $dbPort;
76
    private string $dbUser;
77
    private string $dbPassword;
78
    private string $dbName;
79

80
    private Auth $auth;
81
    private UserManager $userManager;
82
    private Translator $lang;
83
    private BoughtServiceService $boughtServiceService;
84
    private AdminPaymentService $adminPaymentService;
85
    private PurchasePriceService $purchasePriceService;
86
    private PurchasePriceRenderer $purchasePriceRenderer;
87
    private PriceTextService $priceTextService;
88
    private MybbRepository $mybbRepository;
89
    private MybbUserGroupRepository $mybbUserGroupRepository;
90
    private MybbUserServiceRepository $mybbUserServiceRepository;
91
    private DatabaseLogger $logger;
92
    private PaginationFactory $paginationFactory;
93
    private Database $db;
94

95
    public function __construct(
78✔
96
        AdminPaymentService $adminPaymentService,
97
        Auth $auth,
98
        BoughtServiceService $boughtServiceService,
99
        Database $db,
100
        DatabaseLogger $logger,
101
        MybbRepositoryFactory $mybbRepositoryFactory,
102
        MybbUserGroupRepository $mybbUserGroupRepository,
103
        MybbUserServiceRepository $mybbUserServiceRepository,
104
        PaginationFactory $paginationFactory,
105
        PriceTextService $priceTextService,
106
        PurchasePriceRenderer $purchasePriceRenderer,
107
        PurchasePriceService $purchasePriceService,
108
        Template $template,
109
        TranslationManager $translationManager,
110
        UserManager $userManager,
111
        ?Service $service = null
112
    ) {
113
        parent::__construct($template, $service);
78✔
114
        $this->adminPaymentService = $adminPaymentService;
78✔
115
        $this->auth = $auth;
78✔
116
        $this->boughtServiceService = $boughtServiceService;
78✔
117
        $this->db = $db;
78✔
118
        $this->logger = $logger;
78✔
119
        $this->mybbUserGroupRepository = $mybbUserGroupRepository;
78✔
120
        $this->mybbUserServiceRepository = $mybbUserServiceRepository;
78✔
121
        $this->paginationFactory = $paginationFactory;
78✔
122
        $this->priceTextService = $priceTextService;
78✔
123
        $this->purchasePriceRenderer = $purchasePriceRenderer;
78✔
124
        $this->purchasePriceService = $purchasePriceService;
78✔
125
        $this->userManager = $userManager;
78✔
126
        $this->lang = $translationManager->user();
78✔
127

128
        $this->readServiceData();
78✔
129

130
        $this->mybbRepository = $mybbRepositoryFactory->create(
78✔
131
            $this->dbHost,
78✔
132
            $this->dbPort,
78✔
133
            $this->dbUser,
78✔
134
            $this->dbPassword,
78✔
135
            $this->dbName
78✔
136
        );
78✔
137
    }
138

139
    private function readServiceData()
78✔
140
    {
141
        $serviceData = $this->service ? $this->service->getData() : null;
78✔
142
        if (isset($serviceData["mybb_groups"])) {
78✔
143
            $this->groups = explode(",", $serviceData["mybb_groups"]);
10✔
144
        }
145
        $this->dbHost = array_get($serviceData, "db_host", "");
78✔
146
        $this->dbPort = array_get($serviceData, "db_port", 3306);
78✔
147
        $this->dbUser = array_get($serviceData, "db_user", "");
78✔
148
        $this->dbPassword = array_get($serviceData, "db_password", "");
78✔
149
        $this->dbName = array_get($serviceData, "db_name", "");
78✔
150
    }
151

152
    public function mapToUserService(array $data): MybbUserService
2✔
153
    {
154
        return $this->mybbUserServiceRepository->mapToModel($data);
2✔
155
    }
156

157
    public function serviceAdminExtraFieldsGet(): string
1✔
158
    {
159
        if ($this->showOnWeb()) {
1✔
160
            $webSelYes = "selected";
×
161
            $webSelNo = "";
×
162
        } else {
163
            $webSelYes = "";
1✔
164
            $webSelNo = "selected";
1✔
165
        }
166

167
        return $this->template->renderNoComments("admin/services/mybb_extra_groups/extra_fields", [
1✔
168
            "moduleId" => $this->getModuleId(),
1✔
169
            "webSelYes" => $webSelYes,
1✔
170
            "webSelNo" => $webSelNo,
1✔
171
            "mybbGroups" => implode(",", $this->groups),
1✔
172
            "dbHost" => $this->dbHost,
1✔
173
            "dbUser" => $this->dbUser,
1✔
174
            "dbPassword" => strlen($this->dbPassword) ? "********" : "",
1✔
175
            "dbName" => $this->dbName,
1✔
176
        ]);
1✔
177
    }
178

179
    public function serviceAdminManagePre(Validator $validator): void
1✔
180
    {
181
        $validator->extendRules([
1✔
182
            "db_host" => [new RequiredRule()],
1✔
183
            "db_user" => [new RequiredRule()],
1✔
184
            "db_password" => [],
1✔
185
            "db_name" => [new RequiredRule()],
1✔
186
            "mybb_groups" => [new RequiredRule(), new IntegerCommaSeparatedListRule()],
1✔
187
            "web" => [new RequiredRule(), new YesNoRule()],
1✔
188
        ]);
1✔
189
    }
190

191
    public function serviceAdminManagePost(array $body): array
1✔
192
    {
193
        $mybbGroups = explode(",", $body["mybb_groups"]);
1✔
194
        foreach ($mybbGroups as $key => $group) {
1✔
195
            $mybbGroups[$key] = trim($group);
1✔
196
            if (!strlen($mybbGroups[$key])) {
1✔
197
                unset($mybbGroups[$key]);
×
198
            }
199
        }
200

201
        $extraData = [
1✔
202
            "mybb_groups" => implode(",", $mybbGroups),
1✔
203
            "web" => $body["web"],
1✔
204
            "db_host" => $body["db_host"],
1✔
205
            "db_user" => $body["db_user"],
1✔
206
            "db_password" => array_get($body, "db_password", $this->dbPassword),
1✔
207
            "db_name" => $body["db_name"],
1✔
208
        ];
1✔
209

210
        return [
1✔
211
            "data" => $extraData,
1✔
212
        ];
1✔
213
    }
214

215
    public function userServiceAdminDisplayTitleGet(): string
1✔
216
    {
217
        return $this->lang->t("mybb_groups");
1✔
218
    }
219

220
    public function userServiceAdminDisplayGet(Request $request): Wrapper
1✔
221
    {
222
        $pagination = $this->paginationFactory->create($request);
1✔
223
        $queryParticle = new QueryParticle();
1✔
224

225
        if ($request->query->has("search")) {
1✔
226
            $queryParticle->extend(
1✔
227
                create_search_query(
1✔
228
                    ["us.id", "us.user_id", "u.username", "s.name", "usmeg.mybb_uid"],
1✔
229
                    $request->query->get("search")
1✔
230
                )
1✔
231
            );
1✔
232
        }
233

234
        $where = $queryParticle->isEmpty() ? "" : "WHERE {$queryParticle} ";
1✔
235

236
        $statement = $this->db->statement(
1✔
237
            <<<EOF
1✔
238
SELECT 
1✔
239
SQL_CALC_FOUND_ROWS 
240
us.id,
241
us.user_id,
242
us.comment,
243
u.username, 
244
s.id AS `service_id`,
245
s.name AS `service`,
246
us.expire,
247
usmeg.mybb_uid 
248
FROM `ss_user_service` AS us 
249
INNER JOIN `{$this->getUserServiceTable()}` AS usmeg ON usmeg.us_id = us.id 
1✔
250
LEFT JOIN `ss_services` AS s ON s.id = usmeg.service_id 
251
LEFT JOIN `ss_users` AS u ON u.uid = us.user_id 
252
{$where}
1✔
253
ORDER BY us.id DESC 
254
LIMIT ?, ?
255
EOF
1✔
256
        );
1✔
257
        $statement->bindAndExecute(
1✔
258
            array_merge($queryParticle->params(), $pagination->getSqlLimit())
1✔
259
        );
1✔
260
        $rowsCount = $this->db->query("SELECT FOUND_ROWS()")->fetchColumn();
1✔
261

262
        $bodyRows = collect($statement)
1✔
263
            ->map(function (array $row) {
1✔
264
                $userEntry = $row["user_id"]
×
265
                    ? new UserRef($row["user_id"], $row["username"])
×
266
                    : new NoneText();
×
267

268
                return (new BodyRow())
×
269
                    ->setDbId($row["id"])
×
270
                    ->addCell(new Cell($userEntry))
×
271
                    ->addCell(new Cell($row["service"]))
×
272
                    ->addCell(new Cell($row["mybb_uid"]))
×
273
                    ->addCell(new ExpirationCell($row["expire"]))
×
274
                    ->addCell(new PreWrapCell($row["comment"]))
×
275
                    ->setDeleteAction(can(Permission::USER_SERVICES_MANAGEMENT()))
×
276
                    ->setEditAction(false);
×
277
            })
1✔
278
            ->all();
1✔
279

280
        $table = (new Structure())
1✔
281
            ->addHeadCell(new HeadCell($this->lang->t("id"), "id"))
1✔
282
            ->addHeadCell(new HeadCell($this->lang->t("user")))
1✔
283
            ->addHeadCell(new HeadCell($this->lang->t("service")))
1✔
284
            ->addHeadCell(new HeadCell($this->lang->t("mybb_user")))
1✔
285
            ->addHeadCell(new HeadCell($this->lang->t("expires")))
1✔
286
            ->addHeadCell(new HeadCell($this->lang->t("comment")))
1✔
287
            ->addBodyRows($bodyRows)
1✔
288
            ->enablePagination("/admin/user_service", $pagination, $rowsCount);
1✔
289

290
        return (new Wrapper())->enableSearch()->setTable($table);
1✔
291
    }
292

293
    public function purchaseFormGet(array $query): string
1✔
294
    {
295
        $quantities = collect($this->purchasePriceService->getServicePrices($this->service))
1✔
296
            ->map(
1✔
297
                fn(QuantityPrice $price) => $this->purchasePriceRenderer->render(
1✔
298
                    $price,
1✔
299
                    $this->service
1✔
300
                )
1✔
301
            )
1✔
302
            ->join();
1✔
303

304
        $costBox = $this->template->render("shop/components/purchase/cost_box");
1✔
305

306
        return $this->template->render("shop/services/mybb_extra_groups/purchase_form", [
1✔
307
            "costBox" => $costBox,
1✔
308
            "quantities" => $quantities,
1✔
309
            "serviceId" => $this->service->getId(),
1✔
310
            "user" => $this->auth->user(),
1✔
311
        ]);
1✔
312
    }
313

314
    public function purchaseFormValidate(Purchase $purchase, array $body): void
3✔
315
    {
316
        $validator = new Validator(
3✔
317
            [
3✔
318
                "email" => array_get($body, "email"),
3✔
319
                "quantity" => as_int(array_get($body, "quantity")),
3✔
320
                "username" => array_get($body, "username"),
3✔
321
            ],
3✔
322
            [
3✔
323
                "email" => [new RequiredRule(), new EmailRule()],
3✔
324
                "quantity" => [new IntegerRule()],
3✔
325
                "username" => [new RequiredRule(), new MybbUserExistsRule($this->mybbRepository)],
3✔
326
            ]
3✔
327
        );
3✔
328

329
        $validated = $validator->validateOrFail();
3✔
330
        $quantity = $validated["quantity"] === -1 ? null : $validated["quantity"];
2✔
331

332
        $purchase->setOrder([
2✔
333
            "username" => $validated["username"],
2✔
334
        ]);
2✔
335
        $purchase->setEmail($validated["email"]);
2✔
336

337
        $quantityPrice = $this->purchasePriceService->getServicePriceByQuantity(
2✔
338
            $quantity,
2✔
339
            $this->service
2✔
340
        );
2✔
341

342
        if ($quantityPrice) {
2✔
343
            $purchase->setPayment([
2✔
344
                Purchase::PAYMENT_PRICE_SMS => as_int($quantityPrice->smsPrice),
2✔
345
                Purchase::PAYMENT_PRICE_TRANSFER => as_int($quantityPrice->transferPrice),
2✔
346
                Purchase::PAYMENT_PRICE_DIRECT_BILLING => as_int(
2✔
347
                    $quantityPrice->directBillingPrice
2✔
348
                ),
2✔
349
            ]);
2✔
350
        }
351
    }
352

353
    public function orderDetails(Purchase $purchase): string
1✔
354
    {
355
        $email = $purchase->getEmail() ?: $this->lang->t("none");
1✔
356
        $username = $purchase->getOrder("username");
1✔
357
        $serviceName = $this->service->getNameI18n();
1✔
358
        $quantity =
1✔
359
            $purchase->getOrder(Purchase::ORDER_QUANTITY) === null
1✔
360
                ? $this->lang->t("forever")
1✔
361
                : $purchase->getOrder(Purchase::ORDER_QUANTITY) . " " . $this->service->getTag();
×
362

363
        return $this->template->renderNoComments(
1✔
364
            "shop/services/mybb_extra_groups/order_details",
1✔
365
            compact("quantity", "username", "email", "serviceName")
1✔
366
        );
1✔
367
    }
368

369
    public function purchase(Purchase $purchase): int
5✔
370
    {
371
        $mybbUser = $this->findMybbUser($purchase->getOrder("username"));
5✔
372

373
        if (!$mybbUser) {
5✔
374
            $this->logger->log(
×
375
                "log_mybb_purchase_no_user",
×
376
                json_encode($purchase->getPaymentList())
×
377
            );
×
378
            throw new Exception("User was deleted from MyBB db during the purchase.");
×
379
        }
380

381
        $quantity = multiply($purchase->getOrder(Purchase::ORDER_QUANTITY), 24 * 60 * 60);
5✔
382

383
        $this->mybbUserServiceRepository->create(
5✔
384
            $this->service->getId(),
5✔
385
            $purchase->user->getId(),
5✔
386
            $quantity,
5✔
387
            $mybbUser->getUid(),
5✔
388
            $purchase->getComment()
5✔
389
        );
5✔
390

391
        foreach ($this->groups as $group) {
5✔
392
            $mybbUser->prolongShopGroup($group, $quantity);
5✔
393
        }
394
        $this->saveMybbUser($mybbUser);
5✔
395

396
        $promoCode = $purchase->getPromoCode();
5✔
397

398
        return $this->boughtServiceService->create(
5✔
399
            $purchase->user->getId(),
5✔
400
            $purchase->user->getUsername(),
5✔
401
            $purchase->getAddressIp(),
5✔
402
            (string) $purchase->getPaymentOption()->getPaymentMethod(),
5✔
403
            $purchase->getPayment(Purchase::PAYMENT_PAYMENT_ID),
5✔
404
            $purchase->getPayment(Purchase::PAYMENT_INVOICE_ID),
5✔
405
            $this->service->getId(),
5✔
406
            0,
5✔
407
            $purchase->getOrder(Purchase::ORDER_QUANTITY),
5✔
408
            $purchase->getOrder("username") . " ({$mybbUser->getUid()})",
5✔
409
            $purchase->getEmail(),
5✔
410
            $promoCode ? $promoCode->getCode() : null,
5✔
411
            [
5✔
412
                "uid" => $mybbUser->getUid(),
5✔
413
                "groups" => implode(",", $this->groups),
5✔
414
            ]
5✔
415
        );
5✔
416
    }
417

418
    public function purchaseInfo($action, Transaction $transaction)
2✔
419
    {
420
        $username = $transaction->getAuthData();
2✔
421
        $quantity = $transaction->isForever()
2✔
422
            ? $this->lang->t("forever")
×
423
            : $transaction->getQuantity() . " " . $this->service->getTag();
2✔
424
        $cost =
2✔
425
            $this->priceTextService->getPriceText($transaction->getCost()) ?:
2✔
426
            $this->lang->t("none");
×
427

428
        if ($action === "email") {
2✔
429
            return $this->template->renderNoComments(
2✔
430
                "shop/services/mybb_extra_groups/purchase_info_email",
2✔
431
                [
2✔
432
                    "cost" => $cost,
2✔
433
                    "quantity" => $quantity,
2✔
434
                    "serviceName" => $this->service->getNameI18n(),
2✔
435
                    "username" => $username,
2✔
436
                ]
2✔
437
            );
2✔
438
        }
439

440
        if ($action === "web") {
1✔
441
            return $this->template->renderNoComments(
1✔
442
                "shop/services/mybb_extra_groups/purchase_info_web",
1✔
443
                compact("cost", "username", "quantity") + [
1✔
444
                    "email" => $transaction->getEmail(),
1✔
445
                    "serviceName" => $this->service->getNameI18n(),
1✔
446
                ]
1✔
447
            );
1✔
448
        }
449

450
        if ($action === "payment_log") {
×
451
            return [
×
452
                "text" => $this->lang->t(
×
453
                    "mybb_group_bought",
×
454
                    $this->service->getNameI18n(),
×
455
                    $username
×
456
                ),
×
457
                "class" => "outcome",
×
458
            ];
×
459
        }
460

461
        return "";
×
462
    }
463

464
    public function userServiceDelete(UserService $userService, $who): bool
1✔
465
    {
466
        try {
467
            $this->mybbRepository->connectDb();
1✔
468
            return true;
1✔
469
        } catch (PDOException $e) {
×
470
            if ($who === "admin") {
×
471
                throw new InvalidConfigException($e->getMessage());
×
472
            }
473

474
            return false;
×
475
        }
476
    }
477

478
    public function userServiceDeletePost(UserService $userService): void
1✔
479
    {
480
        assert($userService instanceof MybbUserService);
481

482
        $mybbUser = $this->findMybbUser($userService->getMybbUid());
1✔
483

484
        // Usuwamy wszystkie shopGroups oraz z mybbGroups te grupy, które maja was_before = false
485
        foreach ($mybbUser->getShopGroup() as $gid => $groupData) {
1✔
486
            if (!$groupData["was_before"]) {
×
487
                $mybbUser->removeMybbAddGroup($gid);
×
488
            }
489
        }
490
        $mybbUser->removeShopGroup();
1✔
491

492
        // Dodajemy uzytkownikowi grupy na podstawie USER_SERVICE_TABLE
493
        $statement = $this->db->statement(
1✔
494
            "SELECT us.expire - UNIX_TIMESTAMP() AS `expire`, s.data AS `extra_data` FROM `ss_user_service` AS us " .
1✔
495
                "INNER JOIN `{$this->getUserServiceTable()}` AS m ON us.id = m.us_id " .
1✔
496
                "INNER JOIN `ss_services` AS s ON us.service_id = s.id " .
1✔
497
                "WHERE m.mybb_uid = ?"
1✔
498
        );
1✔
499
        $statement->bindAndExecute([$userService->getMybbUid()]);
1✔
500

501
        foreach ($statement as $row) {
1✔
502
            $row["extra_data"] = json_decode($row["extra_data"], true);
×
503
            foreach (explode(",", $row["extra_data"]["mybb_groups"]) as $groupId) {
×
504
                $mybbUser->prolongShopGroup($groupId, $row["expire"]);
×
505
            }
506
        }
507

508
        // Użytkownik nie może mieć takiej displaygroup
509
        if (
510
            !in_array(
1✔
511
                $mybbUser->getMybbDisplayGroup(),
1✔
512
                array_unique(
1✔
513
                    array_merge(
1✔
514
                        array_keys($mybbUser->getShopGroup()),
1✔
515
                        $mybbUser->getMybbAddGroups(),
1✔
516
                        [$mybbUser->getMybbUserGroup()]
1✔
517
                    )
1✔
518
                )
1✔
519
            )
1✔
520
        ) {
521
            $mybbUser->setMybbDisplayGroup(0);
×
522
        }
523

524
        $this->saveMybbUser($mybbUser);
1✔
525
    }
526

527
    public function userServiceAdminAddFormGet(): string
1✔
528
    {
529
        return $this->template->renderNoComments(
1✔
530
            "admin/services/mybb_extra_groups/user_service_admin_add",
1✔
531
            ["moduleId" => $this->getModuleId()]
1✔
532
        );
1✔
533
    }
534

535
    public function userServiceAdminAdd(Request $request): int
1✔
536
    {
537
        $admin = $this->auth->user();
1✔
538
        $forever = (bool) $request->request->get("forever");
1✔
539

540
        $validator = new Validator(
1✔
541
            array_merge($request->request->all(), [
1✔
542
                "quantity" => as_int($request->request->get("quantity")),
1✔
543
            ]),
1✔
544
            [
1✔
545
                "comment" => [],
1✔
546
                "quantity" => $forever
1✔
547
                    ? []
548
                    : [new RequiredRule(), new NumberRule(), new MinValueRule(0)],
1✔
549
                "user_id" => [new UserExistsRule()],
1✔
550
                "mybb_username" => [
1✔
551
                    new RequiredRule(),
1✔
552
                    new MybbUserExistsRule($this->mybbRepository),
1✔
553
                ],
1✔
554
                "email" => [new EmailRule()],
1✔
555
            ]
1✔
556
        );
1✔
557

558
        $validated = $validator->validateOrFail();
1✔
559
        $user = $this->userManager->get($validated["user_id"]);
1✔
560

561
        // Add payment info
562
        $paymentId = $this->adminPaymentService->payByAdmin(
1✔
563
            $admin,
1✔
564
            get_ip($request),
1✔
565
            get_platform($request)
1✔
566
        );
1✔
567

568
        $purchase = (new Purchase($user, get_ip($request), get_platform($request)))
1✔
569
            ->setService($this->service->getId(), $this->service->getName())
1✔
570
            ->setPaymentOption(new PaymentOption(PaymentMethod::ADMIN()))
1✔
571
            ->setPayment([
1✔
572
                Purchase::PAYMENT_PAYMENT_ID => $paymentId,
1✔
573
            ])
1✔
574
            ->setOrder([
1✔
575
                "username" => $validated["mybb_username"],
1✔
576
                Purchase::ORDER_QUANTITY => $forever ? null : $validated["quantity"],
1✔
577
            ])
1✔
578
            ->setEmail($validated["email"])
1✔
579
            ->setComment($validated["comment"]);
1✔
580

581
        return $this->purchase($purchase);
1✔
582
    }
583

584
    public function userOwnServiceInfoGet(UserService $userService, $buttonEdit): string
×
585
    {
586
        assert($userService instanceof MybbUserService);
587

588
        $username = $this->mybbRepository->findUsernameByUid($userService->getMybbUid());
×
589

590
        return $this->template->render(
×
591
            "shop/services/mybb_extra_groups/user_own_service",
×
592
            compact("mybbUid", "expire") + [
×
593
                "expire" => as_expiration_datetime_string($userService->getExpire()),
×
594
                "moduleId" => $this->getModuleId(),
×
595
                "mybbUid" => "$username ({$userService->getMybbUid()})",
×
596
                "serviceName" => $this->service->getNameI18n(),
×
597
                "userServiceId" => $userService->getId(),
×
598
            ]
×
599
        );
×
600
    }
601

602
    /**
603
     * @param string|int $userId Int - by uid, String - by username
604
     * @return MybbUser|null
605
     */
606
    private function findMybbUser($userId): ?MybbUser
6✔
607
    {
608
        if (is_integer($userId)) {
6✔
609
            $rawMybbUser = $this->mybbRepository->getUserByUid($userId);
1✔
610
        } else {
611
            $rawMybbUser = $this->mybbRepository->getUserByUsername($userId);
5✔
612
        }
613

614
        if (!$rawMybbUser) {
6✔
615
            return null;
×
616
        }
617

618
        $mybbUser = new MybbUser($rawMybbUser["uid"], $rawMybbUser["usergroup"]);
6✔
619
        $mybbUser->setMybbAddGroups(explode(",", $rawMybbUser["additionalgroups"]));
6✔
620
        $mybbUser->setMybbDisplayGroup($rawMybbUser["displaygroup"]);
6✔
621

622
        $rows = $this->mybbUserGroupRepository->findGroupsExpiration($rawMybbUser["uid"]);
6✔
623

624
        foreach ($rows as $row) {
6✔
625
            $mybbUser->setShopGroup($row["gid"], [
×
626
                "expire" => $row["expire"],
×
627
                "was_before" => $row["was_before"],
×
628
            ]);
×
629
        }
630

631
        return $mybbUser;
6✔
632
    }
633

634
    /**
635
     * Zapisuje dane o użytkowniku
636
     *
637
     * @param MybbUser $mybbUser
638
     */
639
    private function saveMybbUser(MybbUser $mybbUser)
6✔
640
    {
641
        $this->mybbRepository->connectDb();
6✔
642

643
        $this->mybbUserGroupRepository->delete($mybbUser->getUid());
6✔
644

645
        $this->mybbUserGroupRepository->createMany(
6✔
646
            collect($mybbUser->getShopGroup())
6✔
647
                ->map(
6✔
648
                    fn(array $groupData, $groupId) => [
6✔
649
                        "uid" => $mybbUser->getUid(),
5✔
650
                        "gid" => $groupId,
5✔
651
                        "expire" => $groupData["expire"],
5✔
652
                        "was_before" => $groupData["was_before"],
5✔
653
                    ]
5✔
654
                )
6✔
655
                ->all()
6✔
656
        );
6✔
657

658
        $additionalGroups = collect($mybbUser->getMybbAddGroups())
6✔
659
            ->extend(array_keys($mybbUser->getShopGroup()))
6✔
660
            ->unique()
6✔
661
            ->values()
6✔
662
            ->sort()
6✔
663
            ->all();
6✔
664

665
        $this->mybbRepository->updateGroups(
6✔
666
            $mybbUser->getUid(),
6✔
667
            $additionalGroups,
6✔
668
            $mybbUser->getMybbDisplayGroup()
6✔
669
        );
6✔
670
    }
671
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc