public function onActivation(&$controller) { CakePlugin::load('Sites'); App::import('Model', 'CakeSchema'); App::import('Model', 'ConnectionManager'); App::uses('Sites', 'Sites.Lib'); include_once APP . 'Plugin' . DS . 'Sites' . DS . 'Config' . DS . 'Schema' . DS . 'schema.php'; $db = ConnectionManager::getDataSource('default'); //Get all available tables $tables = $db->listSources(); $CakeSchema = new CakeSchema(); $SiteSchema = new SiteSchema(); foreach ($SiteSchema->tables as $table => $config) { if (!in_array($table, $tables)) { $db->execute($db->createSchema($SiteSchema, $table)); } } //Ignore the cache since the tables wont be inside the cache at this point //$db->cacheSources = false; @unlink(TMP . 'cache' . DS . 'models/cake_model_' . ConnectionManager::getSourceName($db) . '_' . $db->config["database"] . '_list'); $db->listSources(); //Insert "ALL SITES" $controller->loadModel('Sites.Site'); $controller->Site->create(); $data = array('Site' => array('id' => Sites::ALL_SITES, 'title' => 'All Sites', 'tagline' => Configure::read('Site.tagline'), 'email' => Configure::read('Site.email'), 'locale' => Configure::read('Site.locale'), 'status' => Configure::read('Site.status'), 'timezone' => Configure::read('Site.timezone'), 'theme' => Configure::read('Site.theme'), 'default' => 1), 'SiteDomain' => array(0 => array('site_id' => Sites::ALL_SITES, 'domain' => $_SERVER["HTTP_HOST"]))); $controller->Site->id = Sites::ALL_SITES; if ($controller->Site->exists()) { $count = $controller->Site->SiteDomain->find('count', array('conditions' => array('SiteDomain.site_id' => Sites::ALL_SITES))); if ($count > 0) { unset($data['SiteDomain']); } } $controller->Site->saveAll($data); }
/** * Cache the DataSource description * * @param string $object The name of the object (model) to cache * @param mixed $data The description of the model, usually a string or array * @return mixed */ protected function _cacheDescription($object, $data = null) { if ($this->cacheSources === false) { return null; } if ($data !== null) { $this->_descriptions[$object] =& $data; } $key = ConnectionManager::getSourceName($this) . '_' . $object; $cache = Cache::read($key, '_cake_model_'); if (empty($cache)) { $cache = $data; Cache::write($key, $cache, '_cake_model_'); } return $cache; }
/** * testCreateDataSource method * * @return void */ public function testCreateDataSourceWithIntegrationTests() { $name = 'test_created_connection'; $connections = ConnectionManager::enumConnectionObjects(); $this->assertTrue((bool) count(array_keys($connections) >= 1)); $source = ConnectionManager::getDataSource('test'); $this->assertTrue(is_object($source)); $config = $source->config; $connection = ConnectionManager::create($name, $config); $this->assertTrue(is_object($connection)); $this->assertEquals($name, $connection->configKeyName); $this->assertEquals($name, ConnectionManager::getSourceName($connection)); $source = ConnectionManager::create(null, array()); $this->assertEquals(null, $source); $source = ConnectionManager::create('another_test', array()); $this->assertEquals(null, $source); $config = array('classname' => 'DboMysql', 'filename' => 'dbo' . DS . 'dbo_mysql'); $source = ConnectionManager::create(null, $config); $this->assertEquals(null, $source); }
/** * Cache the DataSource description * * @param string $object The name of the object (model) to cache * @param mixed $data The description of the model, usually a string or array * @return void */ function __cacheDescription($object, $data = null) { if (Configure::read() > 0) { $expires = "+15 seconds"; } else { $expires = "+999 days"; } if ($data !== null) { $this->__descriptions[$object] =& $data; $cache = serialize($data); } else { $cache = null; } $new = cache('models' . DS . ConnectionManager::getSourceName($this) . '_' . $object, $cache, $expires); if ($new != null) { $new = unserialize($new); } return $new; }
/** * Generates the fields list of an SQL query. * * @param Model $Model The model to get fields for. * @param string $alias Alias table name * @param mixed $fields The provided list of fields. * @param bool $quote If false, returns fields array unquoted * @return array */ public function fields(Model $Model, $alias = null, $fields = array(), $quote = true) { if (empty($alias)) { $alias = $Model->alias; } $virtualFields = $Model->getVirtualField(); $cacheKey = array($alias, get_class($Model), $Model->alias, $virtualFields, $fields, $quote, ConnectionManager::getSourceName($this), $Model->schemaName, $Model->table); $cacheKey = md5(serialize($cacheKey)); if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) { return $return; } $allFields = empty($fields); if ($allFields) { $fields = array_keys($Model->schema()); } elseif (!is_array($fields)) { $fields = CakeText::tokenize($fields); } $fields = array_values(array_filter($fields)); $allFields = $allFields || in_array('*', $fields) || in_array($Model->alias . '.*', $fields); $virtual = array(); if (!empty($virtualFields)) { $virtualKeys = array_keys($virtualFields); foreach ($virtualKeys as $field) { $virtualKeys[] = $Model->alias . '.' . $field; } $virtual = $allFields ? $virtualKeys : array_intersect($virtualKeys, $fields); foreach ($virtual as $i => $field) { if (strpos($field, '.') !== false) { $virtual[$i] = str_replace($Model->alias . '.', '', $field); } $fields = array_diff($fields, array($field)); } $fields = array_values($fields); } if (!$quote) { if (!empty($virtual)) { $fields = array_merge($fields, $this->_constructVirtualFields($Model, $alias, $virtual)); } return $fields; } $count = count($fields); if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) { for ($i = 0; $i < $count; $i++) { if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) { unset($fields[$i]); continue; } if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') { $fields[$i] = $fields[$i]->value; } elseif (preg_match('/^\\(.*\\)\\s' . $this->alias . '.*/i', $fields[$i])) { continue; } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) { $prepend = ''; if (strpos($fields[$i], 'DISTINCT') !== false) { $prepend = 'DISTINCT '; $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i])); } $dot = strpos($fields[$i], '.'); if ($dot === false) { $prefix = !(strpos($fields[$i], ' ') !== false || strpos($fields[$i], '(') !== false); $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]); } else { if (strpos($fields[$i], ',') === false) { $build = explode('.', $fields[$i]); if (!Hash::numeric($build)) { $fields[$i] = $this->name(implode('.', $build)); } } } $fields[$i] = $prepend . $fields[$i]; } elseif (preg_match('/\\(([\\.\\w]+)\\)/', $fields[$i], $field)) { if (isset($field[1])) { if (strpos($field[1], '.') === false) { $field[1] = $this->name($alias . '.' . $field[1]); } else { $field[0] = explode('.', $field[1]); if (!Hash::numeric($field[0])) { $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0])); $fields[$i] = preg_replace('/\\(' . $field[1] . '\\)/', '(' . $field[0] . ')', $fields[$i], 1); } } } } } } if (!empty($virtual)) { $fields = array_merge($fields, $this->_constructVirtualFields($Model, $alias, $virtual)); } return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields)); }
/** * Caches/returns cached results for child instances * * @return array */ function listSources($data = null) { if ($this->cacheSources === false) { return null; } if ($this->_sources != null) { return $this->_sources; } if (Configure::read() > 0) { $expires = "+30 seconds"; } else { $expires = "+999 days"; } if ($data != null) { $data = serialize($data); } $filename = ConnectionManager::getSourceName($this) . '_' . preg_replace("/[^A-Za-z0-9_-]/", "_", $this->config['database']) . '_list'; $new = cache('models' . DS . $filename, $data, $expires); if ($new != null) { $new = unserialize($new); $this->_sources = $new; } return $new; }
/** * Cache the DataSource description * * @param string $object The name of the object (model) to cache * @param mixed $data The description of the model, usually a string or array */ function __cacheDescription($object, $data = null) { if ($this->cacheSources === false) { return null; } if (Configure::read() > 0) { $expires = "+15 seconds"; } else { $expires = "+999 days"; } if ($data !== null) { $this->__descriptions[$object] =& $data; } $key = ConnectionManager::getSourceName($this) . '_' . $object; $cache = Cache::read($key, '_cake_model_'); if (empty($cache)) { $cache = $data; Cache::write($key, $cache, array('duration' => $expires, 'config' => '_cake_model_')); } return $cache; }
protected function _buildListable($tableName) { $cacheKey = ConnectionManager::getSourceName($this) . '_listable_' . $tableName; $list = Cache::read($cacheKey, '_cake_model_'); if (!$list) { $path = Inflector::singularize($tableName) . '/' . 'list'; $rawList = $this->_request($path); foreach ($rawList[$tableName] as $row) { $list[$row['id']] = $row; } Cache::write($cacheKey, $list, '_cake_model_'); } return $list; }
/** * Tests that cached table descriptions are saved under the sanitized key name * * @access public */ function testCacheKeyName() { Configure::write('Cache.disable', false); $dbName = 'db' . rand() . '$(*%&).db'; $this->assertFalse(file_exists(TMP . $dbName)); $config = $this->db->config; $db = new DboSqlite3(array_merge($this->db->config, array('database' => TMP . $dbName))); $this->assertTrue(file_exists(TMP . $dbName)); $db->execute("CREATE TABLE test_list (id VARCHAR(255));"); $db->cacheSources = true; $this->assertEqual($db->listSources(), array('test_list')); $db->cacheSources = false; $fileName = '_' . preg_replace('/[^A-Za-z0-9_\\-+]/', '_', TMP . $dbName) . '_list'; $key = ConnectionManager::getSourceName($db) . '_' . $db->config['database'] . '_list'; $key = preg_replace('/[^A-Za-z0-9_\\-.+]/', '_', $key); $result = Cache::read($fileName, '_cake_model_'); $this->assertEqual($result, array('test_list')); //Cache::delete($fileName, '_cake_model_'); Configure::write('Cache.disable', true); }
public function after($event = array()) { static $createdTables = 0; // tracks number of created tables // determines how many tables are in this schema class $totalTables = 0; $refclass = new ReflectionClass($this); foreach ($refclass->getProperties() as $property) { if ($property->class === $refclass->name) { ++$totalTables; } } // when called from the console schema utility, the connection parameter is // a string, but when it's called from the web installer it's an object if (is_string($this->connection)) { $dataSourceName = $this->connection; } else { $dataSourceName = ConnectionManager::getSourceName($this->connection); } $db = ConnectionManager::getDataSource($dataSourceName); $db->cacheSources = false; // must be disabled to populate the tables // handle create table events if (isset($event['create'])) { ++$createdTables; switch ($event['create']) { case 'roles': // Create hierarchical roles $role = ClassRegistry::init('Role'); $role->setDataSource($dataSourceName); $parent_id = null; $role_names = $role->getRoleNames(); foreach ($role_names as $role_name) { $role->create(); $role->save(array('name' => $role_name, 'display_name' => $role->getDisplayNameFor($role_name), 'parent_id' => $parent_id)); $parent_id = $role->id; } break; case 'users': // Create default user $user = ClassRegistry::init('User'); $user->setDataSource($dataSourceName); $user->create(); $user->save(array('name' => 'Admin')); break; case 'aros': // Create ARO root node for users and collection memberships $aro = ClassRegistry::init('Aro'); $aro->setDataSource($dataSourceName); $aro->create(); $aro->save(array('alias' => 'users')); break; case 'acos': // Create ACO root node for the role hierarchy $aco = ClassRegistry::init('Aco'); $aco->setDataSource($dataSourceName); $aco->create(); $aco->save(array('alias' => 'role')); break; case 'aros_acos': break; } // final step -- requires all tables to be created if ($createdTables === $totalTables) { $acl = new DbAcl(); // component object $acl->allow('users', 'role/super/admin/mod/user'); $acl->allow(array('model' => 'User', 'foreign_key' => 1), 'role/super'); } } return true; }
protected function _factoryEndpointClient($type, $domain) { $var = sprintf('_%sClient', $type); $this->{$var} = false; $key = sprintf('%s_%s_%s_endpoint', ConnectionManager::getSourceName($this), $domain, $type); $key = preg_replace('/[^A-Za-z0-9_\\-.+]/', '_', $key); $endpoint = Cache::read($key, '_cake_model_'); if (empty($endpoint) && ($client = $this->_factoryClient())) { $result = $client->describeDomains(['DomainNames' => [$domain]]); $service = Inflector::camelize($type) . 'Service'; $endpoint = $result['DomainStatusList'][0][$service]['Endpoint']; Cache::write($key, $endpoint, '_cake_model_'); } if (!empty($endpoint)) { $this->{$var} = CloudSearchDomainClient::factory(['base_url' => $endpoint]); } return $this->{$var}; }
/** * Resets the model's datasource to the original * * @param Model $Model The model * @return boolean */ protected function _resetSource($Model) { if (isset($Model->_useDbConfig)) { $this->source = ConnectionManager::getDataSource($Model->_useDbConfig); } return $Model->setDataSource(ConnectionManager::getSourceName($this->source)); }
/** * Reads from cache if it exists. If not, it falls back to the original * datasource to retrieve the data and cache it for later * * @param Model $model * @param array $query * @param int $recursive * @return array Results * @see DataSource::read() */ public function read(Model $model, $query = array(), $recursive = null) { // Resets the model's datasource to the original $model->setDataSource(ConnectionManager::getSourceName($this->source)); $key = $this->_key($model, $query); $results = Cache::read($key, $this->config['config']); if ($results === false) { $results = $this->source->read($model, $query, $recursive); // compress before storing if ($this->_useGzip()) { Cache::write($key, gzcompress(serialize($results)), $this->config['config']); } else { Cache::write($key, $results, $this->config['config']); } $this->_map($model, $key); } else { // uncompress data from cache if ($this->_useGzip()) { $results = unserialize(gzuncompress($results)); } } Cache::set(null, $this->config['config']); return $results; }