/ tests / RoleModelTest.php
<?php
/**
 * SeekQuarry/Yioop --
 * Open Source Pure PHP Search Engine, Crawler, and Indexer
 *
 * Copyright (C) 2009 - 2026  Chris Pollett chris@pollett.org
 *
 * LICENSE:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see
 * <https://www.gnu.org/licenses/>.
 *
 * END LICENSE
 *
 * @author Chris Pollett chris@pollett.org
 * @license https://www.gnu.org/licenses/ GPL3
 * @link https://www.seekquarry.com/
 * @copyright 2009 - 2026
 * @package seek_quarry\test
 */
namespace seekquarry\yioop\tests;

use seekquarry\yioop\configs as C;
use seekquarry\yioop\library\UnitTest;
use seekquarry\yioop\models\RoleModel;
use seekquarry\yioop\models\ProfileModel;
use seekquarry\yioop\models\datasources\Sqlite3Manager;
use seekquarry\yioop\models\UserModel;

/**
 * Checks how RoleModel stores per-role group limits and how it resolves the
 * effective limit for a user account across the roles that account holds.
 * The core rule under test is that the most generous role wins, unlimited
 * (-1) beats any finite cap, and a role with no stored limits row, or an
 * account with no roles at all, counts as unlimited.
 *
 * @author Chris Pollett
 */
class RoleModelTest extends UnitTest
{
    /**
     * The RoleModel instance under test, pointed at a throwaway database.
     * @var RoleModel
     */
    public $model;
    /**
     * $db stores the database manager the cases run their own statements
     * through, pointed at the same throwaway database as the model.
     * Declaring it here rather than making it as the case runs is what
     * PHP asks for from version 8.2 onward.
     * @var Sqlite3Manager
     */
    public $db;
    /**
     * File path of the throwaway SQLite database this test stands up.
     * @var string
     */
    public $public_db_path;
    /**
     * Stands up a throwaway SQLite database with the ROLE, ROLE_LIMITS, and
     * USER_ROLE tables, seeds three roles (Admin unlimited, User and Editor
     * with finite caps) plus a fourth role with no limits row, and assigns a
     * handful of test accounts to those roles.
     */
    public function setUp()
    {
        $tag = getmypid() . "_" . random_int(1000, 9999);
        $this->public_db_path = C\WORK_DIRECTORY . "/temp/" .
            "role_limits_test_public_$tag.db";
        $public_db = new Sqlite3Manager();
        $public_db->connect("", "", "", $this->public_db_path);
        /* Stand up the ROLE, ROLE_LIMITS, and USER_ROLE tables from the same
           definitions the live database uses, borrowed from ProfileModel, so
           this test tracks any schema change automatically rather than
           carrying a hand-copied version that could drift. */
        $dbinfo = ["DBMS" => "Sqlite3", "DB_HOST" => ""];
        $profile = new ProfileModel(C\DB_NAME, false);
        $profile->initializeSql($public_db, $dbinfo);
        foreach (['ROLE', 'ROLE_LIMITS', 'USER_ROLE'] as $table) {
            $public_db->execute($profile->create_statements[$table]);
        }
        $public_db->execute("INSERT INTO ROLE VALUES (1, 'Admin'), " .
            "(2, 'User'), (3, 'Editor'), (4, 'Guest')");
        $this->model = new RoleModel(C\DB_NAME, false);
        $this->model->db = $public_db;
        $this->model->setRoleLimits(1,
            $this->makeCaps(-1, -1, -1, -1, -1, -1, -1));
        $this->model->setRoleLimits(2,
            $this->makeCaps(3, 50, 500, 26214400, 500, 25, 5000));
        $this->model->setRoleLimits(3,
            $this->makeCaps(10, 100, 500, 26214400, 5000, 100, 50000));
        /* role 4 (Guest) is left with no ROLE_LIMITS row on purpose */
        $public_db->execute("INSERT INTO USER_ROLE (USER_ID, ROLE_ID) " .
            "VALUES (10, 2), (11, 1), (11, 2), (12, 2), (12, 3), " .
            "(14, 2), (14, 4)");
        /* A second database of its own, for the cases about roles that
           are sold and run out: they need tables and rows the ones
           above would collide with. */
        $tag = uniqid();
        $this->db_path = C\WORK_DIRECTORY . "/temp/role_sub_$tag.db";
        $this->db = new Sqlite3Manager();
        $this->db->connect("", "", "", $this->db_path);
        $dbinfo = ["DBMS" => "Sqlite3", "DB_HOST" => ""];
        $profile = new ProfileModel(C\DB_NAME, false);
        $profile->initializeSql($this->db, $dbinfo);
        foreach (['ROLE', 'ROLE_LIMITS', 'USER_ROLE', 'ACTIVITY',
            'ROLE_ACTIVITY'] as $table) {
            $this->db->execute($profile->create_statements[$table]);
        }
        $this->role_model = new RoleModel(C\DB_NAME, false);
        $this->role_model->db = $this->db;
        $this->user_model = new UserModel(C\DB_NAME, false);
        $this->user_model->db = $this->db;
        /* role 10 free, role 11 one-time buy, role 12 monthly
           subscription; price and frequency live on ROLE_LIMITS */
        $roles = [[10, 'Free'], [11, 'Lifetime'], [12, 'Monthly']];
        foreach ($roles as $role) {
            $this->db->execute(
                "INSERT INTO ROLE (ROLE_ID, NAME) VALUES (?, ?)", $role);
        }
        $limits = [[10, 0, 'never'], [11, 100, 'once'],
            [12, 50, 'monthly']];
        foreach ($limits as $limit) {
            $this->db->execute("INSERT INTO ROLE_LIMITS " .
                "(ROLE_ID, ROLE_COST, CHARGE_FREQUENCY) " .
                "VALUES (?, ?, ?)", $limit);
        }
        /* one activity that role 12 grants */
        $this->db->execute("INSERT INTO ACTIVITY " .
            "(ACTIVITY_ID, TRANSLATION_ID, METHOD_NAME) " .
            "VALUES (1, 1, 'testActivity')");
        $this->db->execute("INSERT INTO ROLE_ACTIVITY " .
            "(ROLE_ID, ACTIVITY_ID, ALLOWED_ARGUMENTS) " .
            "VALUES (12, 1, 'all')");
        /* user 5 lapsed, user 6 never lapses, user 7 still in future */
        $this->role_model->addUserRole(5, 12, time() - 100);
        $this->role_model->addUserRole(6, 12, C\FOREVER);
        $this->role_model->addUserRole(7, 12, time() + 100000);
    }
    /**
     * Disconnects and removes the throwaway database, and evicts this test's
     * own handle from the data-source layer's process-wide connection cache
     * so a later test reusing the same scratch name gets a fresh handle.
     */
    public function tearDown()
    {
        if (!empty($this->db)) {
            $this->db->disconnect();
        }
        if (!empty($this->db_path) && file_exists($this->db_path)) {
            unlink($this->db_path);
        }
        if ($this->model && $this->model->db) {
            $this->model->db->disconnect();
            unset(Sqlite3Manager::$active_connections[
                $this->model->db->connect_string]);
        }
        if ($this->public_db_path &&
                file_exists($this->public_db_path)) {
            unlink($this->public_db_path);
        }
    }
    /**
     * Builds a caps array in the shape setRoleLimits expects.
     *
     * @param int $groups groups a role may own
     * @param int $members members allowed per group
     * @param int $wiki wiki pages allowed per group
     * @param int $memory resource memory per page, in bytes
     * @param int $threads threads or chats allowed per group
     * @param int $thread_resources resources allowed per thread
     * @param int $thread_posts posts allowed per thread
     * @param int $cost cost of the role in credits
     * @param string $frequency how often the cost is charged
     * @return array cap column name => value
     */
    public function makeCaps($groups, $members, $wiki, $memory, $threads,
        $thread_resources, $thread_posts, $cost = 0, $frequency = 'never')
    {
        return ['MAX_GROUPS_OWNED' => $groups,
            'MAX_GROUP_MEMBERS' => $members,
            'MAX_GROUP_WIKI_PAGES' => $wiki,
            'MAX_PAGE_RESOURCE_MEMORY' => $memory,
            'MAX_GROUP_THREADS' => $threads,
            'MAX_THREAD_RESOURCES' => $thread_resources,
            'MAX_THREAD_POSTS' => $thread_posts,
            'ROLE_COST' => $cost,
            'CHARGE_FREQUENCY' => $frequency];
    }
    /**
     * Storing a role's caps and reading them back returns the same values,
     * and writing again for the same role replaces rather than duplicates.
     */
    public function setAndGetRoleLimitsTestCase()
    {
        $limits = $this->model->getRoleLimits();
        $this->assertEqual(50, (int)$limits[2]['MAX_GROUP_MEMBERS'],
            "stored User members cap reads back");
        $this->assertEqual(26214400,
            (int)$limits[2]['MAX_PAGE_RESOURCE_MEMORY'],
            "stored User memory cap reads back");
        $this->model->setRoleLimits(2,
            $this->makeCaps(1, 250, 100, 5242880, 50, 5, 100));
        $limits = $this->model->getRoleLimits();
        $this->assertEqual(250, (int)$limits[2]['MAX_GROUP_MEMBERS'],
            "rewriting a role's caps replaces the old value");
    }
    /**
     * An account holding an unlimited role and a finite role is unlimited on
     * that cap, because unlimited is the most generous value.
     */
    public function unlimitedWinsTestCase()
    {
        $effective = $this->model->getUserGroupLimits(11);
        $this->assertEqual(-1, $effective['MAX_GROUP_MEMBERS'],
            "admin (unlimited) plus user (50) resolves to unlimited");
    }
    /**
     * When every role an account holds is finite, the effective cap is the
     * largest across those roles.
     */
    public function maxOverRolesTestCase()
    {
        $effective = $this->model->getUserGroupLimits(12);
        $this->assertEqual(100, $effective['MAX_GROUP_MEMBERS'],
            "user (50) plus editor (100) resolves to 100");
    }
    /**
     * An account holding a single finite role gets that role's caps.
     */
    public function singleRoleTestCase()
    {
        $effective = $this->model->getUserGroupLimits(10);
        $this->assertEqual(50, $effective['MAX_GROUP_MEMBERS'],
            "user-only account gets the user members cap");
        $this->assertEqual(500, $effective['MAX_GROUP_WIKI_PAGES'],
            "user-only account gets the user wiki cap");
    }
    /**
     * An account with no roles at all is unlimited on every cap.
     */
    public function noRolesUnlimitedTestCase()
    {
        $effective = $this->model->getUserGroupLimits(13);
        $this->assertEqual(-1, $effective['MAX_GROUP_MEMBERS'],
            "account with no roles is unlimited");
    }
    /**
     * A role with no stored limits row counts as unlimited, so an account
     * holding such a role alongside a finite role is unlimited on that cap.
     */
    public function missingLimitsRowTestCase()
    {
        $effective = $this->model->getUserGroupLimits(14);
        $this->assertEqual(-1, $effective['MAX_GROUP_MEMBERS'],
            "a role with no limits row lifts the cap to unlimited");
    }
    /**
     * A role's cost and charge frequency round-trip through storage, and a
     * later write replaces them in place rather than adding a second row.
     */
    public function costAndFrequencyTestCase()
    {
        $this->model->setRoleLimits(2,
            $this->makeCaps(3, 50, 500, 26214400, 500, 10, 5000, 25,
            'monthly'));
        $limits = $this->model->getRoleLimits();
        $this->assertEqual(25, (int)$limits[2]['ROLE_COST'],
            "stored role cost reads back");
        $this->assertEqual('monthly', $limits[2]['CHARGE_FREQUENCY'],
            "stored charge frequency reads back");
    }
    /**
     * File path of the throwaway database.
     * @var string
     */
    public $db_path;
    /**
     * RoleModel wired to the throwaway database.
     * @var object
     */
    public $role_model;
    /**
     * UserModel wired to the throwaway database.
     * @var object
     */
    public $user_model;
    /**
     * Only roles with a price above zero are listed as sellable.
     */
    public function getSellableRolesTestCase()
    {
        $sellable = $this->role_model->getSellableRoles();
        $ids = [];
        foreach ($sellable as $role) {
            $ids[] = (int)$role['ROLE_ID'];
        }
        sort($ids);
        $this->assertEqual([11, 12], $ids,
            "free role is excluded, priced roles are listed");
    }
    /**
     * A granted role stores the expiry it was given.
     */
    public function addUserRoleStoresExpiryTestCase()
    {
        $result = $this->db->execute("SELECT EXPIRES FROM USER_ROLE " .
            "WHERE USER_ID = 6 AND ROLE_ID = 12");
        $row = $this->db->fetchArray($result);
        $this->assertEqual(C\FOREVER, (int)$row['EXPIRES'],
            "a forever grant records the forever sentinel");
    }
    /**
     * A lapsed grant stops conferring the role's activity, while a
     * forever grant and a future-dated grant still confer it.
     */
    public function lapsedRoleLosesActivityTestCase()
    {
        $this->assertFalse(
            $this->user_model->isAllowedUserActivity(5, 'testActivity'),
            "expired grant no longer confers the activity");
        $this->assertTrue(
            $this->user_model->isAllowedUserActivity(6, 'testActivity'),
            "forever grant still confers the activity");
        $this->assertTrue(
            $this->user_model->isAllowedUserActivity(7, 'testActivity'),
            "future-dated grant still confers the activity");
    }
    /**
     * A user's held sellable roles come back with their cost, frequency,
     * and expiry; a user holding no sellable role gets an empty list.
     */
    public function getUserSellableRolesTestCase()
    {
        $held = $this->role_model->getUserSellableRoles(6);
        $this->assertEqual(1, count($held),
            "user 6 holds one sellable role");
        $this->assertEqual(12, (int)$held[0]['ROLE_ID'],
            "the held sellable role is the monthly one");
        $this->assertEqual(50, (int)$held[0]['ROLE_COST'],
            "its cost comes from ROLE_LIMITS");
        $this->assertEqual('monthly', $held[0]['CHARGE_FREQUENCY'],
            "its frequency comes from ROLE_LIMITS");
        $this->assertEqual([],
            $this->role_model->getUserSellableRoles(99),
            "a user with no sellable role gets an empty list");
    }
    /**
     * Moving a grant's expiry forward updates the stored value.
     */
    public function updateUserRoleExpiresTestCase()
    {
        $this->role_model->updateUserRoleExpires(6, 12, 12345);
        $result = $this->db->execute("SELECT EXPIRES FROM USER_ROLE " .
            "WHERE USER_ID = 6 AND ROLE_ID = 12");
        $row = $this->db->fetchArray($result);
        $this->assertEqual(12345, (int)$row['EXPIRES'],
            "expiry was moved to the new value");
    }
    /**
     * A new grant renews by default, and setUserRoleRenew can turn that
     * off so a cancelled subscription is later removed rather than
     * renewed.
     */
    public function willRenewDefaultAndSetTestCase()
    {
        $held = $this->role_model->getUserSellableRoles(7);
        $this->assertEqual(1, (int)$held[0]['WILL_RENEW'],
            "a fresh grant renews by default");
        $this->role_model->setUserRoleRenew(7, 12, 0);
        $held = $this->role_model->getUserSellableRoles(7);
        $this->assertEqual(0, (int)$held[0]['WILL_RENEW'],
            "cancelling turns renewing off");
        $this->role_model->setUserRoleRenew(7, 12, 1);
        $held = $this->role_model->getUserSellableRoles(7);
        $this->assertEqual(1, (int)$held[0]['WILL_RENEW'],
            "resubscribing turns renewing back on");
    }
    /**
     * A grant added with the renew flag off keeps that flag, so a caller
     * can grant a role that will not auto-renew.
     */
    public function addUserRoleStoresRenewTestCase()
    {
        $this->role_model->addUserRole(8, 12, time() + 100000, 0);
        $held = $this->role_model->getUserSellableRoles(8);
        $this->assertEqual(1, count($held),
            "user 8 now holds the monthly role");
        $this->assertEqual(0, (int)$held[0]['WILL_RENEW'],
            "the grant kept the renew-off flag it was added with");
    }
}
X