AbstractUserGroup.php 20.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
<?php
/**
 * AbstractUserGroup.php
 *
 * The AbstractUserGroup class file.
 *
 * PHP versions 5
 *
 * @author    Alexander Schneider <alexanderschneider85@gmail.com>
 * @copyright 2008-2017 Alexander Schneider
 * @license   http://www.gnu.org/licenses/gpl-2.0.html  GNU General Public License, version 2
 * @version   SVN: $id$
 * @link      http://wordpress.org/extend/plugins/user-access-manager/
 */

declare(strict_types=1);

namespace UserAccessManager\UserGroup;

use Exception;
use UserAccessManager\Config\MainConfig;
use UserAccessManager\Database\Database;
use UserAccessManager\Object\ObjectHandler;
use UserAccessManager\ObjectMembership\MissingObjectMembershipHandlerException;
use UserAccessManager\Util\Util;
use UserAccessManager\Wrapper\Php;
use UserAccessManager\Wrapper\Wordpress;

/**
 * Class AbstractUserGroup
 *
 * @package UserAccessManager\UserGroup
 */
abstract class AbstractUserGroup
{
    const NONE_ROLE = '_none-role_';

    /**
     * @var Php
     */
    protected $php;

    /**
     * @var Wordpress
     */
    protected $wordpress;

    /**
     * @var Database
     */
    protected $database;

    /**
     * @var MainConfig
     */
    protected $config;

    /**
     * @var Util
     */
    protected $util;

    /**
     * @var ObjectHandler
     */
    protected $objectHandler;

    /**
     * @var AssignmentInformationFactory
     */
    protected $assignmentInformationFactory;

    /**
     * @var string
     */
    protected $id = null;

    /**
     * @var string
     */
    protected $type = null;

    /**
     * @var string
     */
    protected $name = null;

    /**
     * @var string
     */
    protected $description = null;

    /**
     * @var string
     */
    protected $readAccess = 'group';

    /**
     * @var string
     */
    protected $writeAccess = 'group';

    /**
     * @var bool
     */
    protected $ignoreDates = false;

    /**
     * @var array
     */
    protected $assignedObjects = [];

    /**
     * @var array
     */
    protected $objectMembership = [];

    /**
     * @var array
     */
    protected $fullObjectMembership = [];

    /**
     * @var array|null
     */
    protected $defaultTypes = null;

    /**
     * AbstractUserGroup constructor.
     * @param Php $php
     * @param Wordpress $wordpress
     * @param Database $database
     * @param MainConfig $config
     * @param Util $util
     * @param ObjectHandler $objectHandler
     * @param AssignmentInformationFactory $assignmentInformationFactory
     * @param null|int|string $id
     * @throws UserGroupTypeException
     */
    public function __construct(
        Php $php,
        Wordpress $wordpress,
        Database $database,
        MainConfig $config,
        Util $util,
        ObjectHandler $objectHandler,
        AssignmentInformationFactory $assignmentInformationFactory,
        $id = null
    ) {
        if ($this->type === null) {
            throw new UserGroupTypeException('User group type must not null.');
        }

        $this->php = $php;
        $this->wordpress = $wordpress;
        $this->database = $database;
        $this->config = $config;
        $this->util = $util;
        $this->objectHandler = $objectHandler;
        $this->assignmentInformationFactory = $assignmentInformationFactory;
        $this->id = $id;
    }

    /*
     * Primary values.
     */

    /**
     * Returns the group id.
     * @return int|string|null
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Returns the user group type.
     * @return string
     */
    public function getType(): ?string
    {
        return $this->type;
    }

    /**
     * Returns the group name.
     * @return string
     */
    public function getName(): ?string
    {
        return $this->name;
    }

    /**
     * Sets the group name.
     * @param string $name The new group name.
     */
    public function setName(string $name)
    {
        $this->name = $name;
    }

    /**
     * Returns the group description.
     * @return string
     */
    public function getDescription(): ?string
    {
        return $this->description;
    }

    /**
     * Sets the group description.
     * @param string $description The new group description.
     */
    public function setDescription(string $description)
    {
        $this->description = $description;
    }

    /**
     * Returns the read access.
     * @return string
     */
    public function getReadAccess(): string
    {
        return $this->readAccess;
    }

    /**
     * Sets the read access.
     * @param string $readAccess The read access.
     */
    public function setReadAccess(string $readAccess)
    {
        $this->readAccess = $readAccess;
    }

    /**
     * Returns the write access.
     * @return string
     */
    public function getWriteAccess(): string
    {
        return $this->writeAccess;
    }

    /**
     * Sets the write access.
     * @param string $writeAccess The write access.
     */
    public function setWriteAccess(string $writeAccess)
    {
        $this->writeAccess = $writeAccess;
    }

    /**
     * Sets the ignore dates flag.
     * @param bool $ignoreDates
     */
    public function setIgnoreDates(bool $ignoreDates)
    {
        if ($this->ignoreDates !== $ignoreDates) {
            $this->resetObjects();
        }

        $this->ignoreDates = $ignoreDates;
    }

    /**
     * Return the ignore dates flag.
     * @return bool
     */
    public function getIgnoreDates(): bool
    {
        return $this->ignoreDates;
    }

    /**
     * Resets the objects
     */
    protected function resetObjects()
    {
        $this->assignedObjects = [];
        $this->objectMembership = [];
        $this->fullObjectMembership = [];
    }

    /**
     * Deletes the user group.
     * @return bool
     * @throws Exception
     */
    public function delete(): bool
    {
        $allObjectTypes = $this->objectHandler->getAllObjectTypes();

        foreach ($allObjectTypes as $objectType) {
            $this->removeObject($objectType);
        }

        return true;
    }

    /**
     * Adds a object of the given type.
     * @param string $objectType The object type.
     * @param int|string $objectId The object id.
     * @param null $fromDate From date.
     * @param null $toDate To date.
     * @return bool
     * @throws Exception
     */
    public function addObject(string $objectType, $objectId, $fromDate = null, $toDate = null): bool
    {
        $generalObjectType = $this->objectHandler->getGeneralObjectType($objectType);

        if ($generalObjectType === null
            || $this->objectHandler->isValidObjectType($objectType) === false
        ) {
            return false;
        }

        $return = $this->database->replace(
            $this->database->getUserGroupToObjectTable(),
            [
                'group_id' => $this->id,
                'group_type' => $this->type,
                'object_id' => $objectId,
                'general_object_type' => $generalObjectType,
                'object_type' => $objectType,
                'from_date' => $fromDate,
                'to_date' => $toDate
            ],
            [
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s'
            ]
        );

        if ($return !== false) {
            $this->resetObjects();
            return true;
        }

        return false;
    }

    /**
     * Removes a object of the given type.
     * @param string $objectType The object type.
     * @param null $objectId The object id.
     * @param bool $ignoreGeneralType
     * @return bool
     * @throws Exception
     */
    public function removeObject(string $objectType, $objectId = null, $ignoreGeneralType = false): bool
    {
        $generalObjectType = $this->objectHandler->getGeneralObjectType($objectType);

        if ($generalObjectType === null
            || $this->objectHandler->isValidObjectType($objectType) === false
        ) {
            return false;
        }

        $objectTypeQuery = " AND object_type = '%s' ";
        $values = [
            $this->id,
            $this->type,
            $objectType
        ];

        if ($ignoreGeneralType === false) {
            $objectTypeQuery = " AND (object_type = '%s' OR general_object_type = '%s') ";
            $values[] = $generalObjectType;
        }

        $query = "DELETE FROM {$this->database->getUserGroupToObjectTable()}
            WHERE group_id = %d
              AND group_type = '%s'
              {$objectTypeQuery}";

        if ($objectId !== null) {
            $query .= ' AND object_id = %d';
            $values[] = $objectId;
        }

        $query = $this->database->prepare($query, $values);
        $success = ($this->database->query($query) !== false);

        if ($success === true) {
            $this->resetObjects();
        }

        return $success;
    }

    /**
     * Returns the assigned objects.
     * @param string $objectType The object type.
     * @return AssignmentInformation[]
     */
    public function getAssignedObjects(string $objectType): array
    {
        if (isset($this->assignedObjects[$objectType]) === false) {
            $query = "SELECT object_id AS id, object_type AS objectType, from_date AS fromDate, to_date AS toDate
                FROM {$this->database->getUserGroupToObjectTable()}
                WHERE group_id = '%s'
                  AND group_type = '%s'
                  AND object_id != ''
                  AND (general_object_type = '%s' OR object_type = '%s')";

            $parameters = [
                $this->id,
                $this->type,
                $objectType,
                $objectType
            ];

            if ($this->ignoreDates === false) {
                $query .= " AND (from_date IS NULL OR from_date <= '%s') AND (to_date IS NULL OR to_date >= '%s')";
                $time = $this->wordpress->currentTime('mysql');
                $parameters = array_merge($parameters, [$time, $time]);
            }

            $query = $this->database->prepare($query, $parameters);
            $results = (array) $this->database->getResults($query);
            $this->assignedObjects[$objectType] = [];

            foreach ($results as $result) {
                $this->assignedObjects[$objectType][$result->id] = $this->assignmentInformationFactory
                    ->createAssignmentInformation($result->objectType, $result->fromDate, $result->toDate);
            }
        }

        return $this->assignedObjects[$objectType];
    }

    /**
     * Marks the group as default for the object type.
     * @param string $objectType
     * @param null|int $fromTime
     * @param null|int $toTime
     * @return bool
     * @throws Exception
     */
    public function addDefaultType(string $objectType, $fromTime = null, $toTime = null): bool
    {
        $fromDate = ($fromTime !== null) ? gmdate('Y-m-d H:i:s', $fromTime) : null;
        $toTime = ($toTime !== null && $toTime <= $fromTime) ? $fromTime + 1 : $toTime;
        $toDate = ($toTime !== null) ? gmdate('Y-m-d H:i:s', $toTime) : null;

        return $this->addObject($objectType, '', $fromDate, $toDate);
    }

    /**
     * Removes the group as default for object type.
     * @param string $objectType
     * @return bool
     * @throws Exception
     */
    public function removeDefaultType(string $objectType): bool
    {
        return $this->removeObject($objectType, '', true);
    }

    /**
     * Returns the object type for which the user group is the default group.
     * @return array
     */
    public function getDefaultGroupForObjectTypes(): ?array
    {
        if ($this->defaultTypes === null) {
            $this->defaultTypes = [];

            $query = "SELECT object_type AS objectType, from_date AS fromDate, to_date AS toDate
                FROM {$this->database->getUserGroupToObjectTable()}
                WHERE group_id = '%s'
                  AND group_type = '%s'
                  AND object_id = ''";

            $parameters = [
                $this->id,
                $this->type
            ];

            $query = $this->database->prepare($query, $parameters);
            $results = (array) $this->database->getResults($query);

            foreach ($results as $result) {
                $this->defaultTypes[$result->objectType] = [
                    ($result->fromDate !== null) ? strtotime($result->fromDate) : null,
                    ($result->toDate !== null) ? strtotime($result->toDate) : null
                ];
            }
        }

        return $this->defaultTypes;
    }

    /**
     * Checks if the group is the default one for the given object type.
     * @param string $objectType
     * @param null|int $fromTime
     * @param null|int $toTime
     * @return bool
     */
    public function isDefaultGroupForObjectType(string $objectType, &$fromTime = null, &$toTime = null): bool
    {
        $defaultGroupForObjectTypes = $this->getDefaultGroupForObjectTypes();

        // Reset reference values anyway
        $fromTime = null;
        $toTime = null;

        if (isset($defaultGroupForObjectTypes[$objectType])) {
            $fromTime = $defaultGroupForObjectTypes[$objectType][0] !== null ?
                (int) $defaultGroupForObjectTypes[$objectType][0] : null;
            $toTime = $defaultGroupForObjectTypes[$objectType][1] !== null ?
                (int) $defaultGroupForObjectTypes[$objectType][1] : null;

            return true;
        }

        return false;
    }

    /**
     * Checks if the object is assigned to the group.
     * @param string $objectType The object type.
     * @param int|string $objectId The object id.
     * @param AssignmentInformation|null $assignmentInformation The assignment information object.
     * @return bool
     */
    public function isObjectAssignedToGroup(
        string $objectType,
        $objectId,
        &$assignmentInformation = null
    ): bool {
        $assignmentInformation = null;
        $assignedObjects = $this->getAssignedObjects($objectType);

        if (isset($assignedObjects[$objectId]) === true) {
            $assignmentInformation = $assignedObjects[$objectId];
            return true;
        }

        return false;
    }

    /**
     * Returns a single object.
     * @param string $objectType The object type.
     * @param int|string $objectId The id of the object which should be checked.
     * @param null|AssignmentInformation $assignmentInformation The assignment information
     * @return bool
     * @throws Exception
     */
    public function isObjectMember(
        string $objectType,
        $objectId,
        &$assignmentInformation = null
    ): bool {
        if (isset($this->objectMembership[$objectType][$objectId]) === false) {
            try {
                $isMember = $this->objectHandler->getObjectMembershipHandler($objectType)->isMember(
                    $this,
                    $this->config->lockRecursive(),
                    $objectId,
                    $assignmentInformation
                );
            } catch (MissingObjectMembershipHandlerException $exception) {
                $isMember = false;
            }

            $this->objectMembership[$objectType][$objectId] = ($isMember === true) ?
                $assignmentInformation : false;
        }

        $assignmentInformation = ($this->objectMembership[$objectType][$objectId] instanceof AssignmentInformation) ?
            $this->objectMembership[$objectType][$objectId] : null;

        return ($this->objectMembership[$objectType][$objectId] !== false);
    }

    /**
     * Checks if the role is a group member.
     * @param int|string $roleId
     * @param null $assignmentInformation
     * @return bool
     * @throws Exception
     */
    public function isRoleMember($roleId, &$assignmentInformation = null): bool
    {
        return $this->isObjectMember(ObjectHandler::GENERAL_ROLE_OBJECT_TYPE, $roleId, $assignmentInformation);
    }

    /**
     * Checks if the user is a group member.
     * @param int|string $userId The user id.
     * @param null|AssignmentInformation $assignmentInformation The assignment information.
     * @return bool
     * @throws Exception
     */
    public function isUserMember($userId, &$assignmentInformation = null): bool
    {
        return $this->isObjectMember(ObjectHandler::GENERAL_USER_OBJECT_TYPE, $userId, $assignmentInformation);
    }

    /**
     * Checks if the term is a group member.
     * @param int|string $termId
     * @param null|AssignmentInformation $assignmentInformation
     * @return bool
     * @throws Exception
     */
    public function isTermMember($termId, &$assignmentInformation = null): bool
    {
        return $this->isObjectMember(ObjectHandler::GENERAL_TERM_OBJECT_TYPE, $termId, $assignmentInformation);
    }

    /**
     * Checks if the post is a group member
     * @param int|string $postId
     * @param null|AssignmentInformation $assignmentInformation
     * @return bool
     * @throws Exception
     */
    public function isPostMember($postId, &$assignmentInformation = null): bool
    {
        return $this->isObjectMember(ObjectHandler::GENERAL_POST_OBJECT_TYPE, $postId, $assignmentInformation);
    }

    /**
     * Returns the recursive membership.
     * @param string $objectType The object type.
     * @param int|string $objectId The object id.
     * @return array
     * @throws Exception
     */
    public function getRecursiveMembershipForObject(string $objectType, $objectId): array
    {
        /**
         * @var AssignmentInformation $assignmentInformation
         */
        if ($this->isObjectMember($objectType, $objectId, $assignmentInformation) === true) {
            return $assignmentInformation->getRecursiveMembership();
        }

        return [];
    }

    /**
     * Returns true if the requested object is locked recursive.
     * @param string $objectType The object type.
     * @param int|string $objectId The object id.
     * @return bool
     * @throws Exception
     */
    public function isLockedRecursive(string $objectType, $objectId): bool
    {
        /**
         * @var AssignmentInformation $assignmentInformation
         */
        if ($this->isObjectMember($objectType, $objectId, $assignmentInformation) === true) {
            return (count($assignmentInformation->getRecursiveMembership()) > 0);
        }

        return false;
    }

    /**
     * Returns all objects of the given type.
     * @param string $objectType The object type.
     * @return array
     * @throws Exception
     */
    public function getAssignedObjectsByType(string $objectType): array
    {
        if (isset($this->fullObjectMembership[$objectType]) === false) {
            try {
                $handler = $this->objectHandler->getObjectMembershipHandler($objectType);
                $this->fullObjectMembership[$objectType] = $handler->getFullObjects(
                    $this,
                    $this->config->lockRecursive(),
                    ($objectType === $this->objectHandler->getGeneralObjectType($objectType)) ? null : $objectType
                );
            } catch (MissingObjectMembershipHandlerException $exception) {
                $this->fullObjectMembership[$objectType] = [];
            }
        }

        return $this->fullObjectMembership[$objectType];
    }

    /**
     * Returns the roles assigned to the group.
     * @return array
     * @throws Exception
     */
    public function getFullRoles(): array
    {
        return $this->getAssignedObjectsByType(ObjectHandler::GENERAL_ROLE_OBJECT_TYPE);
    }


    /**
     * Returns the users assigned to the group.
     * @return array
     * @throws Exception
     */
    public function getFullUsers(): array
    {
        return $this->getAssignedObjectsByType(ObjectHandler::GENERAL_USER_OBJECT_TYPE);
    }

    /**
     * Returns the terms assigned to the group.
     * @return array
     * @throws Exception
     */
    public function getFullTerms(): array
    {
        return $this->getAssignedObjectsByType(ObjectHandler::GENERAL_TERM_OBJECT_TYPE);
    }

    /**
     * Returns the posts assigned to the group.
     * @return array
     * @throws Exception
     */
    public function getFullPosts(): array
    {
        return $this->getAssignedObjectsByType(ObjectHandler::GENERAL_POST_OBJECT_TYPE);
    }
}