ACL.php 29.6 KB
Newer Older
totten's avatar
totten committed
1 2 3
<?php
/*
 +--------------------------------------------------------------------+
yashodha's avatar
yashodha committed
4
 | CiviCRM version 4.6                                                |
totten's avatar
totten committed
5
 +--------------------------------------------------------------------+
kurund's avatar
kurund committed
6
 | Copyright CiviCRM LLC (c) 2004-2014                                |
totten's avatar
totten committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the GNU Affero General Public License           |
 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
 |                                                                    |
 | CiviCRM 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 Affero General Public License for more details.        |
 |                                                                    |
 | You should have received a copy of the GNU Affero General Public   |
 | License and the CiviCRM Licensing Exception along                  |
 | with this program; if not, contact CiviCRM LLC                     |
 | at info[AT]civicrm[DOT]org. If you have questions about the        |
 | GNU Affero General Public License or the licensing of CiviCRM,     |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
26
 */
totten's avatar
totten committed
27 28 29 30

/**
 *
 * @package CRM
kurund's avatar
kurund committed
31
 * @copyright CiviCRM LLC (c) 2004-2014
totten's avatar
totten committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45
 * $Id$
 *
 */

/**
 *  Access Control List
 */
class CRM_ACL_BAO_ACL extends CRM_ACL_DAO_ACL {
  static $_entityTable = NULL;
  static $_objectTable = NULL;
  static $_operation = NULL;

  static $_fieldKeys = NULL;

46 47 48
  /**
   * @return array|null
   */
49
  public static function entityTable() {
totten's avatar
totten committed
50 51 52 53 54 55 56 57 58
    if (!self::$_entityTable) {
      self::$_entityTable = array(
        'civicrm_contact' => ts('Contact'),
        'civicrm_acl_role' => ts('ACL Role'),
      );
    }
    return self::$_entityTable;
  }

59 60 61
  /**
   * @return array|null
   */
62
  public static function objectTable() {
totten's avatar
totten committed
63 64 65 66 67 68 69 70 71 72 73
    if (!self::$_objectTable) {
      self::$_objectTable = array(
        'civicrm_contact' => ts('Contact'),
        'civicrm_group' => ts('Group'),
        'civicrm_saved_search' => ts('Contact Group'),
        'civicrm_admin' => ts('Import'),
      );
    }
    return self::$_objectTable;
  }

74 75 76
  /**
   * @return array|null
   */
77
  public static function operation() {
totten's avatar
totten committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    if (!self::$_operation) {
      self::$_operation = array(
        'View' => ts('View'),
        'Edit' => ts('Edit'),
        'Create' => ts('Create'),
        'Delete' => ts('Delete'),
        'Search' => ts('Search'),
        'All' => ts('All'),
      );
    }
    return self::$_operation;
  }

  /**
   * Construct a WHERE clause to handle permissions to $object_*
   *
94 95 96 97 98 99 100 101 102 103 104 105
   * @param array $tables
   *   Any tables that may be needed in the FROM.
   * @param string $operation
   *   The operation being attempted.
   * @param string $object_table
   *   The table of the object in question.
   * @param int $object_id
   *   The ID of the object in question.
   * @param int $acl_id
   *   If it's a grant/revoke operation, the ACL ID.
   * @param bool $acl_role
   *   For grant operations, this flag determines if we're granting a single acl (false) or an entire group.
totten's avatar
totten committed
106
   *
107 108
   * @return string
   *   The WHERE clause, or 0 on failure
totten's avatar
totten committed
109
   */
totten's avatar
totten committed
110 111
  public static function permissionClause(
    &$tables, $operation,
totten's avatar
totten committed
112 113 114
    $object_table = NULL, $object_id = NULL,
    $acl_id = NULL, $acl_role = FALSE
  ) {
pratikshad's avatar
pratikshad committed
115
    $dao = new CRM_ACL_DAO_ACL();
totten's avatar
totten committed
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

    $t = array(
      'ACL' => self::getTableName(),
      'ACLRole' => 'civicrm_acl_role',
      'ACLEntityRole' => CRM_ACL_DAO_EntityRole::getTableName(),
      'Contact' => CRM_Contact_DAO_Contact::getTableName(),
      'Group' => CRM_Contact_DAO_Group::getTableName(),
      'GroupContact' => CRM_Contact_DAO_GroupContact::getTableName(),
    );

    $session = CRM_Core_Session::singleton();
    $contact_id = $session->get('userID');

    $where = " {$t['ACL']}.operation = '" . CRM_Utils_Type::escape($operation, 'String') . "'";

    /* Include clause if we're looking for a specific table/id permission */

    if (!empty($object_table)) {
      $where .= " AND ( {$t['ACL']}.object_table IS null
                         OR ({$t['ACL']}.object_table   = '" . CRM_Utils_Type::escape($object_table, 'String') . "'";
      if (!empty($object_id)) {
        $where .= " AND ({$t['ACL']}.object_id IS null
                            OR {$t['ACL']}.object_id = " . CRM_Utils_Type::escape($object_id, 'Integer') . ')';
      }
      $where .= '))';
    }

    /* Include clause if we're granting an ACL or ACL Role */

    if (!empty($acl_id)) {
      $where .= " AND ({$t['ACL']}.acl_id IS null
                        OR {$t['ACL']}.acl_id   = " . CRM_Utils_Type::escape($acl_id, 'Integer') . ')';
      if ($acl_role) {
        $where .= " AND {$t['ACL']}.acl_table = '{$t['ACLRole']}'";
      }
      else {
        $where .= " AND {$t['ACL']}.acl_table = '{$t['ACL']}'";
      }
    }

    $query = array();

    /* Query for permissions granted to all contacts in the domain */

    $query[] = "SELECT      {$t['ACL']}.*, 0 as override
                    FROM        {$t['ACL']}

                    WHERE       {$t['ACL']}.entity_table    = '{$t['Domain']}'
                            AND ($where)";

    /* Query for permissions granted to all contacts through an ACL group */

    $query[] = "SELECT      {$t['ACL']}.*, 0 as override
                    FROM        {$t['ACL']}

                    INNER JOIN  {$t['ACLEntityRole']}
                            ON  ({$t['ACL']}.entity_table = '{$t['ACLRole']}'
                            AND     {$t['ACL']}.entity_id =
                                    {$t['ACLEntityRole']}.acl_role_id)

                    INNER JOIN  {$t['ACLRole']}
                            ON      {$t['ACL']}.entity_id =
                                    {$t['ACLRole']}.id

                    WHERE       {$t['ACLEntityRole']}.entity_table =
                                    '{$t['Domain']}'
                            AND {$t['ACLRole']}.is_active      = 1
                            AND ($where)";

    /* Query for permissions granted directly to the contact */

    $query[] = "SELECT      {$t['ACL']}.*, 1 as override
                    FROM        {$t['ACL']}

                    INNER JOIN  {$t['Contact']}
                            ON  ({$t['ACL']}.entity_table = '{$t['Contact']}'
                            AND     {$t['ACL']}.entity_id = {$t['Contact']}.id)

                    WHERE       {$t['Contact']}.id          = $contact_id
                            AND ($where)";

    /* Query for permissions granted to the contact through an ACL group */

    $query[] = "SELECT      {$t['ACL']}.*, 1 as override
                    FROM        {$t['ACL']}

                    INNER JOIN  {$t['ACLEntityRole']}
                            ON  ({$t['ACL']}.entity_table = '{$t['ACLRole']}'
                            AND     {$t['ACL']}.entity_id =
                                    {$t['ACLEntityRole']}.acl_role_id)

                    INNER JOIN  {$t['ACLRole']}
                            ON  {$t['ACL']}.entity_id = {$t['ACLRole']}.id

                    WHERE       {$t['ACLEntityRole']}.entity_table =
                                    '{$t['Contact']}'
                        AND     {$t['ACLRole']}.is_active      = 1
                        AND     {$t['ACLEntityRole']}.entity_id  = $contact_id
                        AND     ($where)";

    /* Query for permissions granted to the contact through a group */

    $query[] = "SELECT      {$t['ACL']}.*, 0 as override
                    FROM        {$t['ACL']}

                    INNER JOIN  {$t['GroupContact']}
                            ON  ({$t['ACL']}.entity_table = '{$t['Group']}'
                            AND     {$t['ACL']}.entity_id =
                                    {$t['GroupContact']}.group_id)

                    WHERE       ($where)
                        AND     {$t['GroupContact']}.contact_id = $contact_id
                        AND     {$t['GroupContact']}.status     = 'Added')";

    /* Query for permissions granted through an ACL group to a Contact
         * group */

    $query[] = "SELECT      {$t['ACL']}.*, 0 as override
                    FROM        {$t['ACL']}

                    INNER JOIN  {$t['ACLEntityRole']}
                            ON  ({$t['ACL']}.entity_table = '{$t['ACLRole']}'
                            AND     {$t['ACL']}.entity_id =
                                    {$t['ACLEntityRole']}.acl_role_id)

                    INNER JOIN  {$t['ACLRole']}
                            ON  {$t['ACL']}.entity_id = {$t['ACLRole']}.id

                    INNER JOIN  {$t['GroupContact']}
                            ON  ({$t['ACLEntityRole']}.entity_table =
                                    '{$t['Group']}'
                            AND     {$t['ACLEntityRole']}.entity_id =
                                    {$t['GroupContact']}.group_id)

                    WHERE       ($where)
                        AND     {$t['ACLRole']}.is_active      = 1
                        AND     {$t['GroupContact']}.contact_id = $contact_id
                        AND     {$t['GroupContact']}.status     = 'Added'";

    $union = '(' . implode(') UNION DISTINCT (', $query) . ')';

    $dao->query($union);

totten's avatar
totten committed
259 260
    $allow = array(0);
    $deny = array(0);
totten's avatar
totten committed
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
    $override = array();

    while ($dao->fetch()) {
      /* Instant bypass for the following cases:
             * 1) the rule governs all tables
             * 2) the rule governs all objects in the table in question
             * 3) the rule governs the specific object we want
             */

      if (empty($dao->object_table) ||
        ($dao->object_table == $object_table
          && (empty($dao->object_id)
            || $dao->object_id == $object_id
          )
        )
      ) {
        $clause = 1;
      }
      else {
        /* Otherwise try to generate a clause for this rule */

        $clause = self::getClause(
          $dao->object_table, $dao->object_id, $tables
        );

        /* If the clause returned is null, then the rule is a blanket
                 * (id is null) on a table other than the one we're interested
                 * in.  So skip it. */

        if (empty($clause)) {
          continue;
        }
      }

      /* Now we figure out if this is an allow or deny rule, and possibly
             * a contact-level override */

      if ($dao->deny) {
        $deny[] = $clause;
      }
      else {
        $allow[] = $clause;

        if ($dao->override) {
          $override[] = $clause;
        }
      }
    }

    $allows = '(' . implode(' OR ', $allow) . ')';
    $denies = '(' . implode(' OR ', $deny) . ')';
    if (!empty($override)) {
      $denies = '(NOT (' . implode(' OR ', $override) . ") AND $denies)";
    }

    return "($allows AND NOT $denies)";
  }

  /**
   * Given a table and id pair, return the filter clause
   *
322 323 324 325 326 327
   * @param string $table
   *   The table owning the object.
   * @param int $id
   *   The ID of the object.
   * @param array $tables
   *   Tables that will be needed in the FROM.
totten's avatar
totten committed
328
   *
329 330
   * @return string|null
   *   WHERE-style clause to filter results,
331
   *   or null if $table or $id is null
totten's avatar
totten committed
332 333
   */
  public static function getClause($table, $id, &$tables) {
totten's avatar
totten committed
334 335
    $table = CRM_Utils_Type::escape($table, 'String');
    $id = CRM_Utils_Type::escape($id, 'Integer');
totten's avatar
totten committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    $whereTables = array();

    $ssTable = CRM_Contact_BAO_SavedSearch::getTableName();

    if (empty($table)) {
      return NULL;
    }
    elseif ($table == $ssTable) {
      return CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables);
    }
    elseif (!empty($id)) {
      $tables[$table] = TRUE;
      return "$table.id = $id";
    }
    return NULL;
  }

  /**
   * Construct an associative array of an ACL rule's properties
   *
356 357 358 359
   * @param string $format
   *   Sprintf format for array.
   * @param bool $hideEmpty
   *   Only return elements that have a value set.
totten's avatar
totten committed
360
   *
361 362
   * @return array
   *   Assoc. array of the ACL rule's properties
totten's avatar
totten committed
363
   */
totten's avatar
totten committed
364
  public function toArray($format = '%s', $hideEmpty = FALSE) {
totten's avatar
totten committed
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    $result = array();

    if (!self::$_fieldKeys) {
      $fields = CRM_ACL_DAO_ACL::fields();
      self::$_fieldKeys = array_keys($fields);
    }

    foreach (self::$_fieldKeys as $field) {
      $result[$field] = $this->$field;
    }
    return $result;
  }

  /**
   * Retrieve ACLs for a contact or group.  Note that including a contact id
   * without a group id will return those ACL rules which are granted
   * directly to the contact, but not those granted to the contact through
   * any/all of his group memberships.
   *
384 385 386 387 388 389
   * @param int $contact_id
   *   ID of a contact to search for.
   * @param int $group_id
   *   ID of a group to search for.
   * @param bool $aclRoles
   *   Should we include ACL Roles.
totten's avatar
totten committed
390
   *
391 392
   * @return array
   *   Array of assoc. arrays of ACL rules
totten's avatar
totten committed
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
   */
  public static function &getACLs($contact_id = NULL, $group_id = NULL, $aclRoles = FALSE) {
    $results = array();

    if (empty($contact_id)) {
      return $results;
    }

    $contact_id = CRM_Utils_Type::escape($contact_id, 'Integer');
    if ($group_id) {
      $group_id = CRM_Utils_Type::escape($group_id, 'Integer');
    }

    $rule = new CRM_ACL_BAO_ACL();

totten's avatar
totten committed
408
    $acl = self::getTableName();
totten's avatar
totten committed
409
    $contact = CRM_Contact_BAO_Contact::getTableName();
totten's avatar
totten committed
410 411
    $c2g = CRM_Contact_BAO_GroupContact::getTableName();
    $group = CRM_Contact_BAO_Group::getTableName();
totten's avatar
totten committed
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

    $query = " SELECT      $acl.*
                        FROM        $acl ";

    if (!empty($group_id)) {
      $query .= " INNER JOIN  $c2g
                            ON      $acl.entity_id      = $c2g.group_id
                        WHERE       $acl.entity_table   = '$group'
                            AND     $acl.is_active      = 1
                            AND     $c2g.group_id       = $group_id";

      if (!empty($contact_id)) {
        $query .= " AND     $c2g.contact_id     = $contact_id
                            AND     $c2g.status         = 'Added'";
      }
    }
    else {
      if (!empty($contact_id)) {
        $query .= " WHERE   $acl.entity_table   = '$contact'
                            AND     $acl.entity_id      = $contact_id";
      }
    }

    $rule->query($query);

    while ($rule->fetch()) {
      $results[$rule->id] = $rule->toArray();
    }

    if ($aclRoles) {
      $results += self::getACLRoles($contact_id, $group_id);
    }

    return $results;
  }

  /**
   * Get all of the ACLs through ACL groups
   *
451 452 453 454
   * @param int $contact_id
   *   ID of a contact to search for.
   * @param int $group_id
   *   ID of a group to search for.
totten's avatar
totten committed
455
   *
456 457
   * @return array
   *   Array of assoc. arrays of ACL rules
totten's avatar
totten committed
458 459 460 461 462 463 464 465 466
   */
  public static function &getACLRoles($contact_id = NULL, $group_id = NULL) {
    $contact_id = CRM_Utils_Type::escape($contact_id, 'Integer');
    if ($group_id) {
      $group_id = CRM_Utils_Type::escape($group_id, 'Integer');
    }

    $rule = new CRM_ACL_BAO_ACL();

totten's avatar
totten committed
467 468
    $acl = self::getTableName();
    $aclRole = 'civicrm_acl_role';
totten's avatar
totten committed
469
    $aclRoleJoin = CRM_ACL_DAO_EntityRole::getTableName();
totten's avatar
totten committed
470 471 472
    $contact = CRM_Contact_BAO_Contact::getTableName();
    $c2g = CRM_Contact_BAO_GroupContact::getTableName();
    $group = CRM_Contact_BAO_Group::getTableName();
totten's avatar
totten committed
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

    $query = "   SELECT          $acl.*
                        FROM            $acl
                        INNER JOIN      civicrm_option_group og
                                ON      og.name = 'acl_role'
                        INNER JOIN      civicrm_option_value ov
                                ON      $acl.entity_table   = '$aclRole'
                                AND     ov.option_group_id  = og.id
                                AND     $acl.entity_id      = ov.value";

    if (!empty($group_id)) {
      $query .= " INNER JOIN  $c2g
                            ON      $acl.entity_id     = $c2g.group_id
                        WHERE       $acl.entity_table  = '$group'
                            AND     $acl.is_active     = 1
                            AND     $c2g.group_id           = $group_id";

      if (!empty($contact_id)) {
        $query .= " AND     $c2g.contact_id = $contact_id
                            AND     $c2g.status = 'Added'";
      }
    }
    else {
      if (!empty($contact_id)) {
        $query .= " WHERE   $acl.entity_table  = '$contact'
                                AND $acl.is_active     = 1
                                AND $acl.entity_id     = $contact_id";
      }
    }

    $results = array();

    $rule->query($query);

    while ($rule->fetch()) {
lobo's avatar
lobo committed
508
      $results[$rule->id] = $rule->toArray();
totten's avatar
totten committed
509 510 511 512 513 514 515 516
    }

    return $results;
  }

  /**
   * Get all ACLs granted to a contact through all group memberships
   *
517 518 519 520
   * @param int $contact_id
   *   The contact's ID.
   * @param bool $aclRoles
   *   Include ACL Roles?.
totten's avatar
totten committed
521
   *
522 523
   * @return array
   *   Assoc array of ACL rules
totten's avatar
totten committed
524 525 526 527 528 529
   */
  public static function &getGroupACLs($contact_id, $aclRoles = FALSE) {
    $contact_id = CRM_Utils_Type::escape($contact_id, 'Integer');

    $rule = new CRM_ACL_BAO_ACL();

totten's avatar
totten committed
530 531 532
    $acl = self::getTableName();
    $c2g = CRM_Contact_BAO_GroupContact::getTableName();
    $group = CRM_Contact_BAO_Group::getTableName();
totten's avatar
totten committed
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
    $results = array();

    if ($contact_id) {
      $query = "
SELECT      $acl.*
  FROM      $acl
 INNER JOIN  $c2g
        ON  $acl.entity_id      = $c2g.group_id
     WHERE  $acl.entity_table   = '$group'
       AND  $c2g.contact_id     = $contact_id
       AND  $c2g.status         = 'Added'";

      $rule->query($query);

      while ($rule->fetch()) {
548
        $results[$rule->id] = $rule->toArray();
totten's avatar
totten committed
549 550 551 552 553 554 555 556 557 558 559 560 561 562
      }
    }

    if ($aclRoles) {
      $results += self::getGroupACLRoles($contact_id);
    }

    return $results;
  }

  /**
   * Get all of the ACLs for a contact through ACL groups owned by Contact
   * groups.
   *
563 564
   * @param int $contact_id
   *   ID of a contact to search for.
totten's avatar
totten committed
565
   *
566 567
   * @return array
   *   Array of assoc. arrays of ACL rules
totten's avatar
totten committed
568 569 570 571 572 573 574 575 576 577
   */
  public static function &getGroupACLRoles($contact_id) {
    $contact_id = CRM_Utils_Type::escape($contact_id, 'Integer');

    $rule = new CRM_ACL_BAO_ACL();

    $acl = self::getTableName();
    $aclRole = 'civicrm_acl_role';

    $aclER = CRM_ACL_DAO_EntityRole::getTableName();
totten's avatar
totten committed
578
    $c2g = CRM_Contact_BAO_GroupContact::getTableName();
totten's avatar
totten committed
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
    $group = CRM_Contact_BAO_Group::getTableName();

    $query = "   SELECT          $acl.*
                        FROM            $acl
                        INNER JOIN      civicrm_option_group og
                                ON      og.name = 'acl_role'
                        INNER JOIN      civicrm_option_value ov
                                ON      $acl.entity_table   = '$aclRole'
                                AND     ov.option_group_id  = og.id
                                AND     $acl.entity_id      = ov.value
                                AND     ov.is_active        = 1
                        INNER JOIN      $aclER
                                ON      $aclER.acl_role_id = $acl.entity_id
                                AND     $aclER.is_active    = 1
                        INNER JOIN  $c2g
                                ON      $aclER.entity_id      = $c2g.group_id
                                AND     $aclER.entity_table   = 'civicrm_group'
                        WHERE       $acl.entity_table       = '$aclRole'
                            AND     $acl.is_active          = 1
                            AND     $c2g.contact_id         = $contact_id
                            AND     $c2g.status             = 'Added'";

    $results = array();

    $rule->query($query);

    while ($rule->fetch()) {
lobo's avatar
lobo committed
606
      $results[$rule->id] = $rule->toArray();
totten's avatar
totten committed
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
    }

    // also get all acls for "Any Role" case
    // and authenticated User Role if present
    $roles = "0";
    $session = CRM_Core_Session::singleton();
    if ($session->get('ufID') > 0) {
      $roles .= ",2";
    }

    $query = "
SELECT $acl.*
  FROM $acl
 WHERE $acl.entity_id      IN ( $roles )
   AND $acl.entity_table   = 'civicrm_acl_role'
";

    $rule->query($query);
    while ($rule->fetch()) {
      $results[$rule->id] = $rule->toArray();
    }

    return $results;
  }

  /**
   * Get all ACLs owned by a given contact, including domain and group-level.
   *
635 636
   * @param int $contact_id
   *   The contact ID.
totten's avatar
totten committed
637
   *
638 639
   * @return array
   *   Assoc array of ACL rules
totten's avatar
totten committed
640 641 642 643 644 645 646 647 648 649 650 651 652
   */
  public static function &getAllByContact($contact_id) {
    $result = array();

    /* First, the contact-specific ACLs, including ACL Roles */
    $result += self::getACLs($contact_id, NULL, TRUE);

    /* Then, all ACLs granted through group membership */
    $result += self::getGroupACLs($contact_id, TRUE);

    return $result;
  }

653
  /**
654
   * @param array $params
655 656 657
   *
   * @return CRM_ACL_DAO_ACL
   */
658
  public static function create(&$params) {
totten's avatar
totten committed
659 660 661
    $dao = new CRM_ACL_DAO_ACL();
    $dao->copyValues($params);
    $dao->save();
662
    return $dao;
totten's avatar
totten committed
663 664
  }

665
  /**
666
   * @param array $params
667 668
   * @param $defaults
   */
669
  public static function retrieve(&$params, &$defaults) {
totten's avatar
totten committed
670 671 672 673
    CRM_Core_DAO::commonRetrieve('CRM_ACL_DAO_ACL', $params, $defaults);
  }

  /**
colemanw's avatar
colemanw committed
674
   * Update the is_active flag in the db
totten's avatar
totten committed
675
   *
676 677 678 679
   * @param int $id
   *   Id of the database record.
   * @param bool $is_active
   *   Value we want to set the is_active field.
totten's avatar
totten committed
680
   *
681 682
   * @return Object
   *   DAO object on sucess, null otherwise
totten's avatar
totten committed
683
   */
684
  public static function setIsActive($id, $is_active) {
totten's avatar
totten committed
685 686 687 688 689 690
    // note this also resets any ACL cache
    CRM_Core_BAO_Cache::deleteGroup('contact fields');

    return CRM_Core_DAO::setFieldValue('CRM_ACL_DAO_ACL', $id, 'is_active', $is_active);
  }

691 692
  /**
   * @param $str
colemanw's avatar
colemanw committed
693
   * @param int $contactID
694 695 696
   *
   * @return bool
   */
697
  public static function check($str, $contactID) {
totten's avatar
totten committed
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721

    $acls = CRM_ACL_BAO_Cache::build($contactID);

    $aclKeys = array_keys($acls);
    $aclKeys = implode(',', $aclKeys);

    if (empty($aclKeys)) {
      return FALSE;
    }

    $query = "
SELECT count( a.id )
  FROM civicrm_acl_cache c, civicrm_acl a
 WHERE c.acl_id       =  a.id
   AND a.is_active    =  1
   AND a.object_table =  %1
   AND a.id           IN ( $aclKeys )
";
    $params = array(1 => array($str, 'String'));

    $count = CRM_Core_DAO::singleValueQuery($query, $params);
    return ($count) ? TRUE : FALSE;
  }

722 723 724 725
  /**
   * @param $type
   * @param $tables
   * @param $whereTables
colemanw's avatar
colemanw committed
726
   * @param int $contactID
727 728 729
   *
   * @return null|string
   */
totten's avatar
totten committed
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
  public static function whereClause($type, &$tables, &$whereTables, $contactID = NULL) {
    $acls = CRM_ACL_BAO_Cache::build($contactID);

    $whereClause = NULL;
    $clauses = array();

    if (!empty($acls)) {
      $aclKeys = array_keys($acls);
      $aclKeys = implode(',', $aclKeys);

      $query = "
SELECT   a.operation, a.object_id
  FROM   civicrm_acl_cache c, civicrm_acl a
 WHERE   c.acl_id       =  a.id
   AND   a.is_active    =  1
   AND   a.object_table = 'civicrm_saved_search'
   AND   a.id        IN ( $aclKeys )
ORDER BY a.object_id
";

      $dao = CRM_Core_DAO::executeQuery($query);

      // do an or of all the where clauses u see
      $ids = array();
      while ($dao->fetch()) {
        // make sure operation matches the type TODO
        if (self::matchType($type, $dao->operation)) {
          if (!$dao->object_id) {
            $ids = array();
            $whereClause = ' ( 1 ) ';
            break;
          }
          $ids[] = $dao->object_id;
        }
      }

      if (!empty($ids)) {
        $ids = implode(',', $ids);
        $query = "
SELECT g.*
  FROM civicrm_group g
 WHERE g.id IN ( $ids )
 AND   g.is_active = 1
";
totten's avatar
totten committed
774
        $dao = CRM_Core_DAO::executeQuery($query);
totten's avatar
totten committed
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
        $staticGroupIDs = array();
        $cachedGroupIDs = array();
        while ($dao->fetch()) {
          // currently operation is restrcited to VIEW/EDIT
          if ($dao->where_clause) {
            if ($dao->select_tables) {
              $tmpTables = array();
              foreach (unserialize($dao->select_tables) as $tmpName => $tmpInfo) {
                if ($tmpName == '`civicrm_group_contact-' . $dao->id . '`') {
                  $tmpName = '`civicrm_group_contact-ACL`';
                  $tmpInfo = str_replace('civicrm_group_contact-' . $dao->id, 'civicrm_group_contact-ACL', $tmpInfo);
                }
                elseif ($tmpName == '`civicrm_group_contact_cache_' . $dao->id . '`') {
                  $tmpName = '`civicrm_group_contact_cache-ACL`';
                  $tmpInfo = str_replace('civicrm_group_contact_cache_' . $dao->id, 'civicrm_group_contact_cache-ACL', $tmpInfo);
                }
                $tmpTables[$tmpName] = $tmpInfo;
              }
              $tables = array_merge($tables,
                $tmpTables
              );
            }
            if ($dao->where_tables) {
              $tmpTables = array();
              foreach (unserialize($dao->where_tables) as $tmpName => $tmpInfo) {
                if ($tmpName == '`civicrm_group_contact-' . $dao->id . '`') {
totten's avatar
totten committed
801 802
                  $tmpName = '`civicrm_group_contact-ACL`';
                  $tmpInfo = str_replace('civicrm_group_contact-' . $dao->id, 'civicrm_group_contact-ACL', $tmpInfo);
totten's avatar
totten committed
803 804 805
                  $staticGroupIDs[] = $dao->id;
                }
                elseif ($tmpName == '`civicrm_group_contact_cache_' . $dao->id . '`') {
totten's avatar
totten committed
806 807
                  $tmpName = '`civicrm_group_contact_cache-ACL`';
                  $tmpInfo = str_replace('civicrm_group_contact_cache_' . $dao->id, 'civicrm_group_contact_cache-ACL', $tmpInfo);
totten's avatar
totten committed
808 809 810 811 812 813 814 815 816
                  $cachedGroupIDs[] = $dao->id;
                }
                $tmpTables[$tmpName] = $tmpInfo;
              }
              $whereTables = array_merge($whereTables, $tmpTables);
            }
          }

          if (($dao->saved_search_id || $dao->children || $dao->parents) &&
totten's avatar
totten committed
817 818
            $dao->cache_date == NULL
          ) {
totten's avatar
totten committed
819 820 821 822 823
            CRM_Contact_BAO_GroupContactCache::load($dao);
          }
        }

        if ($staticGroupIDs) {
pratikshad's avatar
pratikshad committed
824
          $clauses[] = '( `civicrm_group_contact-ACL`.group_id IN (' . implode(', ', $staticGroupIDs) . ') AND `civicrm_group_contact-ACL`.status IN ("Added") )';
totten's avatar
totten committed
825 826 827
        }

        if ($cachedGroupIDs) {
pratikshad's avatar
pratikshad committed
828
          $clauses[] = '`civicrm_group_contact_cache-ACL`.group_id IN (' . implode(', ', $cachedGroupIDs) . ')';
totten's avatar
totten committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
        }
      }
    }

    if (!empty($clauses)) {
      $whereClause = ' ( ' . implode(' OR ', $clauses) . ' ) ';
    }

    // call the hook to get additional whereClauses
    CRM_Utils_Hook::aclWhereClause($type, $tables, $whereTables, $contactID, $whereClause);

    if (empty($whereClause)) {
      $whereClause = ' ( 0 ) ';
    }

    return $whereClause;
  }

847
  /**
848
   * @param int $type
colemanw's avatar
colemanw committed
849
   * @param int $contactID
850 851 852 853 854 855
   * @param string $tableName
   * @param null $allGroups
   * @param null $includedGroups
   *
   * @return array
   */
totten's avatar
totten committed
856 857
  public static function group(
    $type,
totten's avatar
totten committed
858 859 860
    $contactID = NULL,
    $tableName = 'civicrm_saved_search',
    $allGroups = NULL,
totten's avatar
totten committed
861 862 863 864 865
    $includedGroups = NULL
  ) {

    $acls = CRM_ACL_BAO_Cache::build($contactID);

Ravish Nair's avatar
Ravish Nair committed
866
    $ids = array();
totten's avatar
totten committed
867 868 869 870
    if (!empty($acls)) {
      $aclKeys = array_keys($acls);
      $aclKeys = implode(',', $aclKeys);

871 872 873 874 875
      $cacheKey = "$tableName-$aclKeys";
      $cache = CRM_Utils_Cache::singleton();
      $ids = $cache->get($cacheKey);
      if (!$ids) {
        $query = "
totten's avatar
totten committed
876 877 878 879 880 881 882 883 884
SELECT   a.operation, a.object_id
  FROM   civicrm_acl_cache c, civicrm_acl a
 WHERE   c.acl_id       =  a.id
   AND   a.is_active    =  1
   AND   a.object_table = %1
   AND   a.id        IN ( $aclKeys )
GROUP BY a.operation,a.object_id
ORDER BY a.object_id
";
885 886 887 888 889 890 891
        $params = array(1 => array($tableName, 'String'));
        $dao = CRM_Core_DAO::executeQuery($query, $params);
        while ($dao->fetch()) {
          if ($dao->object_id) {
            if (self::matchType($type, $dao->operation)) {
              $ids[] = $dao->object_id;
            }
totten's avatar
totten committed
892
          }
893 894 895 896 897 898 899
          else {
            // this user has got the permission for all objects of this type
            // check if the type matches
            if (self::matchType($type, $dao->operation)) {
              foreach ($allGroups as $id => $dontCare) {
                $ids[] = $id;
              }
totten's avatar
totten committed
900
            }
901
            break;
totten's avatar
totten committed
902 903
          }
        }
904
        $cache->set($cacheKey, $ids);
totten's avatar
totten committed
905 906 907
      }
    }

Ravish Nair's avatar
Ravish Nair committed
908 909 910 911 912 913
    if (empty($ids) && !empty($includedGroups) &&
      is_array($includedGroups)
    ) {
      $ids = $includedGroups;
    }

totten's avatar
totten committed
914 915 916 917 918
    CRM_Utils_Hook::aclGroup($type, $contactID, $tableName, $allGroups, $ids);

    return $ids;
  }

919
  /**
920
   * @param int $type
921 922 923 924
   * @param $operation
   *
   * @return bool
   */
925
  public static function matchType($type, $operation) {
totten's avatar
totten committed
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
    $typeCheck = FALSE;
    switch ($operation) {
      case 'All':
        $typeCheck = TRUE;
        break;

      case 'View':
        if ($type == CRM_ACL_API::VIEW) {
          $typeCheck = TRUE;
        }
        break;

      case 'Edit':
        if ($type == CRM_ACL_API::VIEW || $type == CRM_ACL_API::EDIT) {
          $typeCheck = TRUE;
        }
        break;

      case 'Create':
        if ($type == CRM_ACL_API::CREATE) {
          $typeCheck = TRUE;
        }
        break;

      case 'Delete':
        if ($type == CRM_ACL_API::DELETE) {
          $typeCheck = TRUE;
        }
        break;

      case 'Search':
        if ($type == CRM_ACL_API::SEARCH) {
          $typeCheck = TRUE;
        }
        break;
    }
    return $typeCheck;
  }

  /**
colemanw's avatar
colemanw committed
966
   * Delete ACL records
totten's avatar
totten committed
967
   *
968 969
   * @param int $aclId
   *   ID of the ACL record to be deleted.
totten's avatar
totten committed
970 971
   *
   */
972
  public static function del($aclId) {
totten's avatar
totten committed
973 974 975 976 977 978 979
    // delete all entries from the acl cache
    CRM_ACL_BAO_Cache::resetCache();

    $acl = new CRM_ACL_DAO_ACL();
    $acl->id = $aclId;
    $acl->delete();
  }
980

totten's avatar
totten committed
981
}