static function getDataFromQuery($query, $queryMultiLanguage) { $fallback = array_keys(Configure::read('MultiLanguage.fallback')); $model = new AppModel(); $model->useTable = false; $dataFallback = $model->query($query); $exportData = array(); foreach ($dataFallback[0] as $data) { foreach ($data as $key => $val) { $exportData[$key][$fallback[0]] = $val; } } $dataLanguages = $model->query($queryMultiLanguage); foreach ($dataLanguages as $data) { foreach ($data['dataMultiLanguage'] as $key => $val) { if (isset($exportData[$key])) { $exportData[$key][$data['dataMultiLanguage']['lang_code']] = $val; } } } $arrData = array(); $listLanguage = array_keys(Configure::read('MultiLanguage.fallback') + Configure::read('MultiLanguage.list')); $arrData[] = MultiLanguageLib::getHeader4Export(); foreach ($exportData as $key => $language) { $row = array(); $row[] = $key; foreach ($listLanguage as $lang) { $row[] .= isset($language[$lang]) ? $language[$lang] : ''; } $arrData[] = $row; } return $arrData; }
function query($sql = null) { if (!empty($sql)) { return parent::query($sql); } else { return parent::query($this->sql); } }
public function afterFind(Model $Model, $results, $primary = false) { if (isset($this->langConfig['query']['multiLanguageIsUsed']) && $this->langConfig['query']['multiLanguageIsUsed'] == false) { return $results; } $this->langModels[get_class($Model)] = $Model; $this->initRelatedObjects($Model); $this->getDataResults($results); foreach ($this->langData as $className => $data) { if (!isset($this->langModels[$className]) || count($data) == 0) { continue; } $mod = $this->langModels[$className]; if (!isset($mod->multiLanguage['columns'])) { continue; } $appModel = new AppModel(); $appModel->useTable = false; $sql = 'SELECT * FROM multilanguage_' . $mod->useTable . ' multilanguage ' . 'WHERE lang_code = "' . Configure::read('Config.language') . '" AND object_id IN (' . implode(',', array_keys($data)) . ')'; $languageData = Hash::combine($appModel->query($sql), '{n}.multilanguage.object_id', '{n}.multilanguage'); foreach ($data as $objectId => $val) { foreach ($mod->multiLanguage['columns'] as $column) { if (isset($languageData[$objectId][$column]) && isset($val[$column]) && !empty($languageData[$objectId][$column])) { $this->langData[$className][$objectId][$column] = $languageData[$objectId][$column]; } } } } $this->fillDataResults($results); return $results; }
/** * Placeholder. Output multigrouped * * A means of putting mptt data in a select box (using groups?) is needed. Must still be possible to select * (intermediary) parents. * * @since 1.2 * @param AppModel $model * @param mixed $conditions SQL conditions as a string or as an array('field' =>'value',...) * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") * @param int $limit SQL LIMIT clause, for calculating items per page * @param string $keyPath A string path to the key, i.e. "{n}.Post.id" * @param string $valuePath A string path to the value, i.e. "{n}.Post.title" * @param string $groupPath A string path to a value to group the elements by, i.e. "{n}.Post.category_id" * @return array An associative array of records, where the id is the key, and the display field is the value * @access public */ function generate_tree_list(&$model, $conditions = null, $order = null, $limit = null, $keyPath = null, $valuePath = null, $groupPath = null) { extract($this->settings[$model->name]); /* $model->bindModel( array('hasOne'=> array('TreeParent'=> array( 'className'=>$model->name, 'foreignKey'=>'parent_id', 'conditions'=>'OR 1=1 AND '.$model->escapeField($left).' BETWEEN TreeParent.'.$left.' AND TreeParent.'.$right ) ) ) ); $recursive = $model->recursive; $model->recursive = 0; .... $this->recursive = $recursive; */ $result = $model->query('SELECT Node.id AS id, CONCAT( REPEAT(\'.....\', COUNT(Parent.name)-1), Node.name) AS name ' . 'FROM ' . $model->tablePrefix . $model->table . ' As Node, ' . $model->tablePrefix . $model->table . ' As Parent ' . 'WHERE Node.' . $left . ' BETWEEN Parent.' . $left . ' AND Parent.' . $right . ' ' . 'GROUP BY Node.' . $model->displayField . ' ' . 'ORDER BY Node.' . $left); uses('Set'); $keys = Set::extract($result, '{n}.Node.id'); $vals = Set::extract($result, '{n}.0.name'); if (!empty($keys) && !empty($vals)) { $out = array(); if ($groupPath != null) { $group = Set::extract($result, $groupPath); if (!empty($group)) { $c = count($keys); for ($i = 0; $i < $c; $i++) { if (!isset($group[$i])) { $group[$i] = 0; } if (!isset($out[$group[$i]])) { $out[$group[$i]] = array(); } $out[$group[$i]][$keys[$i]] = $vals[$i]; } return $out; } } $return = array_combine($keys, $vals); return $return; } return null; }
public function restore() { $path = $this->path; $tmpath = APP_DIR . DS . 'tmp'; $backupFolder = new Folder($path); // Get the list of files list($dirs, $files) = $backupFolder->read(); // Remove any un related files foreach ($files as $i => $file) { if (!preg_match('/\\.sql/', $file)) { unset($files[$i]); } } // Sort, explode the files to an array and list files sort($files, SORT_NUMERIC); foreach ($files as $i => $file) { $fileParts = explode(".", $file); $backupDate = strtotime(str_replace("_", "", $fileParts[0])); $this->out("[" . $i . "]: " . date("F j, Y, g:i:s a", $backupDate)); } App::import('Model', 'AppModel'); $model = new AppModel(false, false); // Prompt for the file to restore to $this->hr(); $uResponse = $this->in('Type Backup File Number? [or press enter to skip]'); if ($uResponse == "") { $this->out('Exiting'); } else { $zipfile = $path . $files[$uResponse]; if (array_key_exists($uResponse, $files)) { $this->out('Restoring file: ' . $zipfile); $fileParts = explode(".", $files[$uResponse]); if (isset($fileParts[2]) && $fileParts[2] == 'zip') { $this->out('Unzipping File'); if (class_exists('ZipArchive')) { $zip = new ZipArchive(); if ($zip->open($zipfile) === true) { $zip->extractTo($tmpath); $unzippedFile = $tmpath . DS . $zip->getNameIndex(0); $zip->close(); $this->out('Successfully Unzipped'); } else { $this->out('Unzip Failed'); $this->_stop(); } } else { $this->out('ZipArchive not found, cannot Unzip File!'); $this->_stop(); } } if (($sqlContent = file_get_contents($filename = $unzippedFile)) !== false) { $this->out('Restoring Database'); $sql = explode($this->separador, $sqlContent); foreach ($sql as $key => $s) { debug($s); if (trim($s)) { $result = $model->query($s); } } unlink($unzippedFile); } else { $this->out("Couldn't load contents of file {$unzippedFile}, aborting..."); unlink($unzippedFile); $this->_stop(); } } else { $this->out("Invalid File Number"); $this->_stop(); } } }
/** * Perform a query against the CyberSourceSource DataSource. * * @param string $method name of CyberSourceSource DataSource method to request * @param array $data underscore-delineated array of request data * @return mixed result array on success, false on failure * @access public */ public function query($method, $data) { $result = false; $this->data = $data; if ($this->validates()) { $options = $this->__dataToOptions(); if ($options) { $result = parent::query($method, array($options)); if (!$result['success']) { $this->validateLastResult(); $result = false; } } } return $result; }
public static function runTests() { /** * TODO: * 1. Auto-create table * 2. Handle expiration date */ $sql = "DROP TABLE IF EXISTS `%1\$s`;\nCREATE TABLE `%1\$s` (\n `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n `created` datetime NOT NULL,\n `modified` datetime DEFAULT NULL,\n `expires` datetime DEFAULT NULL,\n `hash` varchar(40) NOT NULL,\n `key` text,\n `value` longtext,\n `used` int(11) unsigned NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `hash` (`hash`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;"; $model = new AppModel(0, false); $model->query(sprintf($sql, 'cache_test')); $model->query(sprintf($sql, 'cache_test2')); $cache = new AppModel(0, 'cache_test'); $cache2 = new AppModel(0, 'cache_test2'); Cache::config('default', array('engine' => 'DbTable', 'duration' => '+1 days', 'storage' => 'cache_test', 'lock' => false, 'serialize' => true)); Cache::config('testcache2', array('engine' => 'DbTable', 'duration' => false, 'storage' => 'cache_test2', 'lock' => false, 'serialize' => true)); App::uses('Test', 'Vendor'); $key1 = 'testkey1'; $key2 = 'testkey_2'; $key3 = 'sometestkey3'; $value1 = 'some value1'; $value2 = 2; $value3 = array('key1' => 'value1', 'key2' => 'value_2'); // Test 1 - read empty cache Test::assertEqual('Test1', array(null, null), array(Cache::read($key1), Cache::read($key3, 'testcache2'))); // Test 2 - write cache on diff.configs $time = time(); $dt = date('Y-m-d H:i:s', $time); $dt2 = date('Y-m-d H:i:s', $time + DAY); // Cache::write($key1, $value1); Cache::write($key2, $value2, 'testcache2'); // Cache::write($key3, $value3); $trueRes = array(array(array('AppModel' => array('id' => '1', 'created' => $dt, 'modified' => $dt, 'expires' => $dt2, 'hash' => sha1($key1), 'key' => $key1, 'value' => serialize($value1), 'used' => '0')), array('AppModel' => array('id' => '2', 'created' => $dt, 'modified' => $dt, 'expires' => $dt2, 'hash' => sha1($key3), 'key' => $key3, 'value' => serialize($value3), 'used' => '0'))), array(array('AppModel' => array('id' => '1', 'created' => $dt, 'modified' => $dt, 'expires' => null, 'hash' => sha1($key2), 'key' => $key2, 'value' => serialize($value2), 'used' => '0')))); Test::assertEqual('Test2', $trueRes, array($cache->find('all'), $cache2->find('all'))); /* $sql = 'DROP TABLE IF EXISTS `%s`'; $model->query(sprintf($sql, 'cache_test')); $model->query(sprintf($sql, 'cache_test2')); */ }
static function FetchPassword($email) { return array_pop(mysql_fetch_row(AppModel::query(AppModel::Prepare("SELECT `password` FROM `user` WHERE `email`='%s' LIMIT 1", $email)))); }
/** * Check DB table for localized fields and define them if needed * * @param AppModel $model * @return bool (true if no changes were made) */ protected function _checkSchema($model) { if (empty($this->_ready[$model->alias])) { $this->_ready[$model->alias] = true; } else { return; } $fields = $this->settings[$model->alias]; if (empty($fields)) { return true; } $locales = SlConfigure::read('I18n.locales'); if (empty($locales)) { trigger_error('I18n didn\'t initilialize properly.', E_USER_ERROR); return false; } $db =& ConnectionManager::getDataSource($model->useDbConfig); $schema = $model->schema(); $alterTable = array(); // add all localized missing fields in this model foreach ($fields as $field) { foreach ($locales as $locale) { $field_lang = $field . '_' . $locale; if (empty($schema[$field_lang])) { if (empty($schema[$field])) { trigger_error("Table for {$model->alias} Model doesn't have a field named '{$field}'!", E_USER_ERROR); } $alterTable[$model->table]['add'][$field_lang] = $schema[$field]; } } } foreach ($locales as $locale) { $field_lang = '_' . $locale; if (empty($schema[$field_lang])) { $alterTable[$model->table]['add'][$field_lang] = array('type' => 'boolean', 'null' => false); } } if ($alterTable) { if (!method_exists($db, 'alterSchema')) { trigger_error("Table configuration for {$model->alias} Model could not be changed to reflect your latest language settings because its DataSource does not support altering schemas.", E_USER_ERROR); } $model->cacheSources = false; $model->cacheQueries = false; // delete cached model file clearCache("{$model->useDbConfig}_{$model->table}", 'models', ''); // execute alter table and update schema $model->query($db->alterSchema($alterTable)); $model->schema(true); // output a notice about updated DB table trigger_error("Table configuration for {$model->alias} Model has changed to reflect your latest language settings.", E_USER_NOTICE); return false; } return true; }