Psr16.php 8.4 KB
Newer Older
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
<?php

/*
 +--------------------------------------------------------------------+
 | CiviCRM version 5                                                  |
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC (c) 2004-2019                                |
 +--------------------------------------------------------------------+
 | 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        |
 +--------------------------------------------------------------------+
 */

/**
 * Class CRM_Core_BAO_Cache_Psr16
 *
 * This optional adapter to help phase-out CRM_Core_BAO_Cache.
 *
 * In effect, it changes the default behavior of legacy cache-consumers
 * (CRM_Core_BAO_Cache) so that they store in the best-available tier
 * (Reds/Memcache or SQL or array) rather than being hard-coded to SQL.
 *
 * It basically just calls "CRM_Utils_Cache::create()" for each $group and
 * maps the getItem/setItem to get()/set().
 */
class CRM_Core_BAO_Cache_Psr16 {

  /**
   * Original BAO behavior did not do expiration. PSR-16 providers have
   * diverse defaults. To provide some consistency, we'll pick a long(ish)
   * TTL for everything that goes through the adapter.
   */
  const TTL = 86400;

  /**
   * @param string $group
   * @return CRM_Utils_Cache_Interface
   */
  protected static function getGroup($group) {
    if (!isset(Civi::$statics[__CLASS__][$group])) {
      if (!in_array($group, self::getLegacyGroups())) {
        Civi::log()
          ->warning('Unrecognized BAO cache group ({group}). This should work generally, but data may not be flushed in some edge-cases. Consider migrating explicitly to PSR-16.', [
            'group' => $group,
          ]);
      }

      $cache = CRM_Utils_Cache::create([
        'name' => "bao_$group",
65
        'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        // We're replacing CRM_Core_BAO_Cache, which traditionally used a front-cache
        // that was not aware of TTLs. So it seems more consistent/performant to
        // use 'fast' here.
        'withArray' => 'fast',
      ]);
      Civi::$statics[__CLASS__][$group] = $cache;
    }
    return Civi::$statics[__CLASS__][$group];
  }

  /**
   * Retrieve an item from the DB cache.
   *
   * @param string $group
   *   (required) The group name of the item.
   * @param string $path
   *   (required) The path under which this item is stored.
   * @param int $componentID
   *   The optional component ID (so componenets can share the same name space).
   *
   * @return object
   *   The data if present in cache, else null
   */
89
  public static function getItem($group, $path, $componentID = NULL) {
90 91 92 93 94 95 96 97
    // TODO: Generate a general deprecation notice.
    if ($componentID) {
      Civi::log()
        ->warning('getItem({group},{path},...) uses unsupported componentID. Consider migrating explicitly to PSR-16.', [
          'group' => $group,
          'path' => $path,
        ]);
    }
98
    return self::getGroup($group)->get(CRM_Utils_Cache::cleanKey($path));
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
  }

  /**
   * Retrieve all items in a group.
   *
   * @param string $group
   *   (required) The group name of the item.
   * @param int $componentID
   *   The optional component ID (so componenets can share the same name space).
   *
   * @throws CRM_Core_Exception
   */
  public static function &getItems($group, $componentID = NULL) {
    // Based on grepping universe, this function is not currently used.
    // Moreover, it's hard to implement in PSR-16. (We'd have to extend the
    // interface.) Let's wait and see if anyone actually needs this...
    throw new \CRM_Core_Exception('Not implemented: CRM_Core_BAO_Cache_Psr16::getItems');
  }

  /**
   * Store an item in the DB cache.
   *
   * @param object $data
   *   (required) A reference to the data that will be serialized and stored.
   * @param string $group
   *   (required) The group name of the item.
   * @param string $path
   *   (required) The path under which this item is stored.
   * @param int $componentID
   *   The optional component ID (so componenets can share the same name space).
   */
  public static function setItem(&$data, $group, $path, $componentID = NULL) {
    // TODO: Generate a general deprecation notice.

    if ($componentID) {
      Civi::log()
        ->warning('setItem({group},{path},...) uses unsupported componentID. Consider migrating explicitly to PSR-16.', [
          'group' => $group,
          'path' => $path,
        ]);
    }
    self::getGroup($group)
141
      ->set(CRM_Utils_Cache::cleanKey($path), $data, self::TTL);
142 143 144 145 146 147 148 149 150 151 152 153 154 155
  }

  /**
   * Delete all the cache elements that belong to a group OR delete the entire cache if group is not specified.
   *
   * @param string $group
   *   The group name of the entries to be deleted.
   * @param string $path
   *   Path of the item that needs to be deleted.
   */
  public static function deleteGroup($group = NULL, $path = NULL) {
    // FIXME: Generate a general deprecation notice.

    if ($path) {
156
      self::getGroup($group)->delete(CRM_Utils_Cache::cleanKey($path));
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
    }
    else {
      self::getGroup($group)->clear();
    }
  }

  /**
   * Cleanup any caches that we've mapped.
   *
   * Traditional SQL-backed caches are cleared as a matter of course during a
   * system flush (by way of "TRUNCATE TABLE civicrm_cache"). This provides
   * a spot where the adapter can
   */
  public static function clearDBCache() {
    foreach (self::getLegacyGroups() as $groupName) {
      $group = self::getGroup($groupName);
      $group->clear();
    }
  }

  /**
   * Get a list of known cache-groups
   *
   * @return array
   */
  public static function getLegacyGroups() {
183
    $groups = [
184 185 186 187 188
      // Core
      'contact fields',
      'custom data',

      // Universe
189 190 191 192 193 194 195 196 197 198

      // be.chiro.civi.atomfeeds
      'dashboard',

      // biz.jmaconsulting.lineitemedit
      'lineitem-editor',

      // civihr/uk.co.compucorp.civicrm.hrcore
      'HRCore_Info',

199
    ];
200 201 202 203 204 205
    // Handle Legacy Multisite caching group.
    $extensions = CRM_Extension_System::singleton()->getManager();
    $multisiteExtensionStatus = $extensions->getStatus('org.civicrm.multisite');
    if ($multisiteExtensionStatus == $extensions::STATUS_INSTALLED) {
      $extension_version = civicrm_api3('Extension', 'get', ['key' => 'org.civicrm.multisite'])['values'][0]['version'];
      if (version_compare($extension_version, '2.7', '<')) {
206 207 208 209
        Civi::log()->warning(
          'CRM_Core_BAO_Cache_PSR is deprecated for multisite extension, you should upgrade to the latest version to avoid this warning, this code will be removed at the end of 2019',
          ['civi.tag' => 'deprecated']
        );
210 211 212
        $groups[] = 'descendant groups for an org';
      }
    }
213 214 215 216 217 218 219 220 221 222 223
    $entitySettingExtensionStatus = $extensions->getStatus('nz.co.fuzion.entitysetting');
    if ($multisiteExtensionStatus == $extensions::STATUS_INSTALLED) {
      $extension_version = civicrm_api3('Extension', 'get', ['key' => 'nz.co.fuzion.entitysetting'])['values'][0]['version'];
      if (version_compare($extension_version, '1.3', '<')) {
        Civi::log()->warning(
          'CRM_Core_BAO_Cache_PSR is deprecated for entity setting extension, you should upgrade to the latest version to avoid this warning, this code will be removed at the end of 2019',
          ['civi.tag' => 'deprecated']
        );
        $groups[] = 'CiviCRM setting Spec';
      }
    }
224
    return $groups;
225 226 227
  }

}