예제 #1
0
 public function registrations($all = false)
 {
     $db = ConnectionManager::getDataSource('default');
     $data = $this->CventAPI->GetRegistrationIds('994C2F8D-98D9-4ADA-98B9-1A1A4F29FAB1');
     $chunks = array_chunk($data, 100);
     $added = 0;
     foreach ($chunks as $chunk) {
         $registrations = $this->CventAPI->RetrieveRegistrations($chunk);
         foreach ($registrations as $registration) {
             $exists = $db->query("select * from cvent where uuid = '{$registration->Id}'");
             if (empty($exists)) {
                 $db->query("INSERT INTO `cvent` (`uuid`, `object`, `parent_object`, `parent_uuid`, `presenter_sequence_id`, `confirmation`, `notes`) VALUES ('{$registration->Id}', 'Registration', 'Event' ,'{$this->eventId}', '{$registration->SourceId}', '{$registration->ConfirmationNumber}', '{$registration->ResponseMethod}');");
                 if (isset($registration->PaymentDetail) && $registration->PaymentDetail instanceof stdClass) {
                     $PaymentDetail = $registration->PaymentDetail;
                     $db->query("INSERT INTO `cvent` (`uuid`, `object`, `parent_object`, `parent_uuid`, `presenter_sequence_id`, `confirmation`, `notes`) VALUES ('{$PaymentDetail->TransactionId}', 'Payment', 'Registration' ,'{$registration->Id}', '{$registration->SourceId}', '{$PaymentDetail->ReferenceNumber}', '{$PaymentDetail->Amount}');");
                 }
                 $added++;
                 $this->out("Added PresenterSequenceId: <info>{$registration->SourceId}</info>");
             }
             if (isset($registration->OrderDetail) && $registration->OrderDetail instanceof stdClass) {
                 $this->addOrderDetails($registration);
             } elseif (count($registration->OrderDetail) > 1) {
                 foreach ($registration->OrderDetail as $key => $value) {
                     $this->addOrderDetails($registration, $key);
                 }
             }
         }
     }
     $this->out("Added: <info>{$added}</info> new registrations.");
 }
 /**
  * Override Model::delete, because it would block deleting when
  * useTable = false and no records exists
  *
  * @param <type> $id
  * @param <type> $cascade
  * @return <type>
  */
 function delete($id = null, $cascade = true)
 {
     if (!empty($id)) {
         $this->id = $id;
     }
     $id = $this->id;
     if ($this->beforeDelete($cascade)) {
         $db =& ConnectionManager::getDataSource($this->useDbConfig);
         if (!$this->Behaviors->trigger($this, 'beforeDelete', array($cascade), array('break' => true, 'breakOn' => false))) {
             return false;
         }
         $this->_deleteDependent($id, $cascade);
         $this->_deleteLinks($id);
         $this->id = $id;
         if (!empty($this->belongsTo)) {
             $keys = $this->find('first', array('fields' => $this->__collectForeignKeys()));
         }
         if ($db->delete($this)) {
             if (!empty($this->belongsTo)) {
                 $this->updateCounterCache($keys[$this->alias]);
             }
             $this->Behaviors->trigger($this, 'afterDelete');
             $this->afterDelete();
             $this->_clearCache();
             $this->id = false;
             $this->__exists = null;
             return true;
         }
     }
     return false;
 }
예제 #3
0
 public function main()
 {
     $db = ConnectionManager::getDataSource('default');
     $db->query($this->migrationsTableSql);
     $results = $db->query("select migrations from __migrations");
     $applied = array();
     foreach ($results as $result) {
         $applied[] = $result['__migrations']['migrations'];
     }
     $migrations = glob(APP . 'Config' . DS . 'Schema' . DS . 'migrations' . DS . '*.sql');
     natsort($migrations);
     $db->begin();
     try {
         foreach ($migrations as $filename) {
             list($migration, $ignore) = explode('.', basename($filename));
             if (in_array($migration, $applied)) {
                 continue;
             }
             $this->out("Migrating to {$migration}.");
             $db->query(file_get_contents($filename));
             $db->query("INSERT INTO `__migrations` VALUES ('{$migration}')");
         }
         $db->commit();
         $this->out('Done.');
     } catch (Exception $e) {
         $this->out("<error>Migration failed. Rolling back.</error>");
         $db->rollback();
         throw $e;
     }
 }
예제 #4
0
 /**
  * Displays information about the system configuration.
  */
 public function status()
 {
     $this->set('core', array('debug' => Configure::read('debug'), 'database' => @ConnectionManager::getDataSource('default')));
     $uploads_path = Configure::read('uploads.path');
     $this->set('uploads', array('url' => Configure::read('uploads.url'), 'path' => $uploads_path, 'exists' => is_dir($uploads_path), 'writable' => is_writable($uploads_path), 'executable' => is_executable($uploads_path)));
     $this->set('dependencies', array('Ghostscript' => is_executable('ghostscript'), 'Imagemagick' => class_exists('Imagick')));
 }
예제 #5
0
 function _importTables($from)
 {
     $defaultDb = ConnectionManager::getDataSource($from);
     foreach ($defaultDb->listSources() as $table) {
         $this->fixtures[] = "app." . Inflector::singularize($table);
     }
 }
예제 #6
0
 /**
  * Run
  *
  * @return void
  */
 public function run()
 {
     $null = null;
     $this->db = ConnectionManager::getDataSource($this->connection);
     $this->db->cacheSources = false;
     $this->db->begin($null);
     if (!isset($this->args[0]) || !in_array($this->args[0], array('insert', 'remove'))) {
         $this->out(__d('SoftDelete', 'Invalid option'));
         return $this->_displayHelp(null);
     }
     if (!isset($this->args[1])) {
         $this->out(__d('SoftDelete', 'You missed field name.'));
         return $this->_displayHelp(null);
     }
     try {
         $this->_run($this->args[0], $this->args[1]);
         $this->_clearCache();
     } catch (Exception $e) {
         $this->db->rollback($null);
         throw $e;
     }
     $this->out(__d('SoftDelete', 'All tables are updated.'));
     $this->out('');
     return $this->db->commit($null);
 }
예제 #7
0
 /**
  * Constructor - checks dependencies and loads the connection
  *
  * @param string $sConnecion The connection from database.php to use. Deafaults to "default"
  * @return void
  */
 function Migrations($sConnection = 'default')
 {
     if (class_exists('Spyc')) {
         $this->bSpycReady = true;
     }
     $this->oDb =& ConnectionManager::getDataSource($sConnection);
 }
예제 #8
0
파일: OracleTest.php 프로젝트: Nervie/Beta
 /**
  * setup method
  *
  * @access public
  * @return void
  */
 public function setUp()
 {
     $this->Dbo = ConnectionManager::getDataSource('test');
     if (!$this->Dbo instanceof Oracle) {
         $this->markTestSkipped('The Oracle extension is not available.');
     }
 }
예제 #9
0
 public function importKeywords()
 {
     $db = ConnectionManager::getDataSource('default');
     $mysqli = new mysqli($db->config['host'], $db->config['login'], $db->config['password'], $db->config['database']);
     $sql = array('links', 'links_keywords');
     foreach (glob('/home/kiang/public_html/news/cache/output/*.json') as $jsonFile) {
         $json = json_decode(file_get_contents($jsonFile), true);
         $newLinkId = String::uuid();
         $json['title'] = $mysqli->real_escape_string(trim($json['title']));
         $json['url'] = $mysqli->real_escape_string($json['url']);
         $json['created'] = date('Y-m-d H:i:s', $json['created_at']);
         $sql['links'][] = "('{$newLinkId}', '{$json['title']}', '{$json['url']}', '{$json['created']}')";
         foreach ($json['keywords'] as $keywordId => $summary) {
             $lkId = String::uuid();
             $summary = $mysqli->real_escape_string(trim($summary));
             $sql['links_keywords'][] = "('{$lkId}', '{$newLinkId}', '{$keywordId}', '{$summary}')";
         }
         unlink($jsonFile);
     }
     if (!empty($sql['links'])) {
         $linksSql = 'INSERT INTO links VALUES ' . implode(',', $sql['links']) . ";\n";
         $lkSql = 'INSERT INTO links_keywords VALUES ' . implode(',', $sql['links_keywords']) . ';';
         file_put_contents(TMP . 'keywords.sql', $linksSql . $lkSql);
     }
 }
예제 #10
0
 /**
  * Called after activating the hook in ExtensionsHooksController::admin_toggle()
  *
  * @param object $controller Controller
  * @return void
  */
 function onActivate(&$controller)
 {
     // ACL: set ACOs with permissions
     $controller->Croogo->addAco('NodeSchema');
     // the controller
     $controller->Croogo->addAco('NodeSchema/admin_index');
     // admin methods
     $controller->Croogo->addAco('NodeSchema/admin_add');
     $controller->Croogo->addAco('NodeSchema/admin_edit');
     $controller->Croogo->addAco('NodeSchema/admin_delete');
     $controller->Croogo->addAco('NodeSchema/admin_add_schema_field');
     $controller->Croogo->addAco('NodeSchema/admin_import');
     $controller->Croogo->addAco('NodeSchema/admin_export');
     // Install the database tables we need
     App::Import('CakeSchema');
     $CakeSchema = new CakeSchema();
     $db =& ConnectionManager::getDataSource('default');
     // TODO: How do we change this for installs?
     // A list of schema files to import for this plugin to work
     $schema_files = array('node_schema_fields.php', 'node_schemas.php', 'node_schemas_types.php');
     foreach ($schema_files as $schema_file) {
         $class_name = Inflector::camelize(substr($schema_file, 0, -4)) . 'Schema';
         $table_name = substr($schema_file, 0, -4);
         // Only build the tables if they don't already exist
         if (!in_array($table_name, $db->_sources)) {
             include_once APP . 'plugins' . DS . 'node_schema' . DS . 'config' . DS . 'schema' . DS . $schema_file;
             // Can app import also work here?
             $ActivateSchema = new $class_name();
             $created = false;
             if (isset($ActivateSchema->tables[$table_name])) {
                 $db->execute($db->createSchema($ActivateSchema, $table_name));
             }
         }
     }
 }
예제 #11
0
 /**
  * Execute installer!
  *
  * @return void
  */
 public function main()
 {
     $this->out();
     $this->out('Plugin: Forum v' . Configure::read('Forum.version'));
     $this->out('Copyright: Miles Johnson, 2010-' . date('Y'));
     $this->out('Help: http://milesj.me/code/cakephp/forum');
     $this->out();
     $this->out('This shell installs the forum plugin by creating the required database tables,');
     $this->out('setting up the admin user, applying necessary table prefixes, and more.');
     $this->hr(1);
     $this->out('Installation Steps:');
     // Begin installation
     $this->db = ConnectionManager::getDataSource(FORUM_DATABASE);
     $this->steps(1);
     if ($this->usersTable()) {
         $this->steps(2);
         if ($this->checkStatus()) {
             $this->steps(3);
             if ($this->setupAcl()) {
                 $this->steps(4);
                 if ($this->createTables()) {
                     $this->steps(5);
                     if ($this->setupAdmin()) {
                         $this->steps(6);
                         $this->finalize();
                     }
                 }
             }
         }
     }
 }
예제 #12
0
파일: sl.php 프로젝트: sandulungu/StarLight
 /**
  * Get or set version info (DB)
  *
  * @param string $extension
  * @param string $newVersion
  */
 public static function version($extension = 'core', $newVersion = null)
 {
     if (SlConfigure::read('Sl.installPending')) {
         return SlConfigure::read('Sl.version');
     }
     if (!SlConfigure::read('Mirror.version')) {
         App::import('Core', 'ConnectionManager');
         $db = @ConnectionManager::getDataSource('default');
         if (!$db->isConnected() || !in_array("{$db->config['prefix']}core_versions", $db->listSources())) {
             if (strpos(Sl::url(false), '/install') === false) {
                 Router::connect(Sl::url(false), array('controller' => 'install'));
             }
             return;
         }
         App::import('Core', 'ClassRegistry');
         ClassRegistry::init('Version')->refreshMirror();
     }
     if ($newVersion) {
         $versionModel = ClassRegistry::init('Version');
         $id = $versionModel->field('Version.id', array('Version.name' => $extension));
         $versionModel->create();
         return $versionModel->save(array('id' => $id, 'name' => $extension, 'version' => $newVersion));
     }
     return SlConfigure::read("Mirror.version.{$extension}");
 }
 function _autenticado($data)
 {
     if (!empty($data)) {
         // Primero buscamos en CENCOS.
         $db =& ConnectionManager::getDataSource($this->Usuario->useDbConfig);
         $usuario = $this->Usuario->find('first', array('fields' => array('Usuario.Usu_cedula', 'Usuario.Usu_nombre'), 'conditions' => array('Usu_login' => $data['SmuqUsuario']['login'], 'Usu_password' => $db->expression("old_password('" . $data['SmuqUsuario']['clave'] . "')"))));
         if (!empty($usuario)) {
             $this->Session->write('Usuario.cedula', $usuario['Usuario']['Usu_cedula']);
             $this->Session->write('Usuario.nombre', mb_convert_case($usuario['Usuario']['Usu_nombre'], MB_CASE_TITLE, "UTF-8"));
             $this->Session->write('Usuario.id_grupo', 3);
             return true;
         } else {
             $usuario = $this->SmuqUsuario->find('first', array('fields' => array('SmuqUsuario.cedula', 'SmuqUsuario.nombre', 'SmuqUsuario.id_grupo'), 'conditions' => array('SmuqUsuario.activo' => 1, 'SmuqUsuario.login' => strtolower($data['SmuqUsuario']['login']), 'SmuqUsuario.clave' => Security::hash($data['SmuqUsuario']['clave'], null, true))));
             if (!empty($usuario)) {
                 $this->Session->write('Usuario.cedula', $usuario['SmuqUsuario']['cedula']);
                 $this->Session->write('Usuario.nombre', $usuario['SmuqUsuario']['nombre']);
                 $this->Session->write('Usuario.id_grupo', $usuario['SmuqUsuario']['id_grupo']);
                 return true;
             } else {
                 $this->Session->delete('Usuario.cedula');
                 $this->Session->delete('Usuario.nombre');
                 $this->Session->delete('Usuario.id_grupo');
             }
         }
     }
     return false;
 }
예제 #14
0
파일: tree_plus.php 프로젝트: hiromi2424/mi
 /**
  * resetDepths method
  *
  * Adding single table update. Typically ~20 times faster than using a loop
  *
  * @param mixed $id
  * @return void
  * @access public
  */
 function resetDepths(&$Model, $id = null)
 {
     if (!$id) {
         $table = $Model->table;
         $Model->query("UPDATE {$table} SET depth = (\n\t\t\t\tSELECT wrapper.parents FROM (\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tthis.id as row,\n\t\t\t\t\t\tCOUNT(parent.id) as parents\n\t\t\t\t\tFROM\n\t\t\t\t\t\t{$table} AS this\n\t\t\t\t\tLEFT JOIN {$table} AS parent ON (\n\t\t\t\t\t\tparent.lft < this.lft AND\n\t\t\t\t\t\tparent.rght > this.rght)\n\t\t\t\t\tGROUP BY\n\t\t\t\t\t\tthis.id\n\t\t\t\t) AS wrapper WHERE wrapper.row = {$table}.id)");
         $db =& ConnectionManager::getDataSource($Model->useDbConfig);
         if (!$db->error) {
             return true;
         }
         $max = ini_get('max_execution_time');
         if ($max) {
             set_time_limit(max($Model->find('count') / 10), 30);
         }
         $Model->updateAll(array('depth' => 0));
         $Model->displayField = 'id';
         $nodes = $Model->find('list', compact('conditions'));
         foreach ($nodes as $id => $_) {
             $Model->resetDepths($id);
         }
         return true;
     }
     $Model->id = $id;
     $path = $Model->getPath($id, array('id'));
     $Model->saveField('depth', count($path));
     return true;
 }
예제 #15
0
 public function run($data)
 {
     if (array_key_exists('search', $data) && !empty($data['search'])) {
         $search = $data['search'];
         $this->Twitter = ConnectionManager::getDataSource('twitter');
         switch ($search) {
             default:
                 $this->getSearchResults($search);
                 $nextUpdate = '+30 Minutes';
                 break;
             case '*global*':
                 $this->getGlobal($search);
                 $nextUpdate = '+5 Minutes';
                 break;
         }
         //check if there is already a task for this term.
         $findConf = array('conditions' => array('fetched' => null, 'data LIKE' => '%' . $search . '%'));
         $alreadyPresent = $this->QueuedTask->find('count', $findConf);
         if ($alreadyPresent == false) {
             if ($this->QueuedTask->createJob('twitterscrape', array('search' => $search), $nextUpdate)) {
                 $this->out('Searchterm update Queued');
             } else {
                 $this->err('Could not create Twitterscrape Job.');
             }
         } else {
             $this->err('There seems to be another job queued for this term, job not requeued.');
         }
         return true;
     } else {
         $this->out('No Search term found, Cancelling');
         // return true so the task does NOT get requeued.
         return true;
     }
 }
예제 #16
0
 /**
  * Truncates all tables and loads fixtures into db
  *
  * @return void
  * @access public
  */
 function main()
 {
     if (!empty($this->args)) {
         if ($this->args[0] == 'chmod') {
             return $this->chmod();
         }
         $fixtures = $this->args;
         foreach ($fixtures as $i => $fixture) {
             $fixtures[$i] = APP . 'tests/fixtures/' . $fixture . '_fixture.php';
         }
     } else {
         App::import('Folder');
         $Folder = new Folder(APP . 'tests/fixtures');
         $fixtures = $Folder->findRecursive('.+_fixture\\.php');
     }
     $db = ConnectionManager::getDataSource('default');
     $records = 0;
     foreach ($fixtures as $path) {
         require_once $path;
         $name = str_replace('_fixture.php', '', basename($path));
         $class = Inflector::camelize($name) . 'Fixture';
         $Fixture =& new $class($db);
         $this->out('-> Truncating table "' . $Fixture->table . '"');
         $db->truncate($Fixture->table);
         $Fixture->insert($db);
         $fixtureRecords = count($Fixture->records);
         $records += $fixtureRecords;
         $this->out('-> Inserting ' . $fixtureRecords . ' records for "' . $Fixture->table . '"');
     }
     $this->out(sprintf('-> Done inserting %d records for %d tables', $records, count($fixtures)));
 }
 public function getRows()
 {
     $data = $this->read();
     $client = $this->Client->find('first', array('fields' => array('Client.id', 'Client.name'), 'conditions' => array('Client.id' => $data['TrainingReport']['client_id'])));
     $moodle_ids = array();
     $users = $this->Client->User->find('all', array('fields' => array('User.id', 'Client.name'), 'conditions' => array('Client.id' => $client['Client']['id'])));
     foreach ($users as $user) {
         $moodle_ids[] = "'n" . $user['User']['id'] . "'";
     }
     $moodle_ids = implode(', ', $moodle_ids);
     $client_name_trunc = substr($client['Client']['name'], 0, 40);
     // mdl_user.institution is only 40 chars
     $moodle = ConnectionManager::getDataSource('moodle');
     $sql = "SELECT mdl_user.firstname, mdl_user.lastname, mdl_quiz_grades.grade, mdl_quiz_grades.timemodified\n                FROM mdl_user, mdl_quiz_grades WHERE mdl_quiz_grades.quiz IN \n                  (SELECT mdl_quiz.id FROM mdl_quiz WHERE mdl_quiz.course = :course_id) \n                AND mdl_quiz_grades.userid = mdl_user.id AND mdl_user.institution = :client_name \n                AND mdl_user.idnumber in ({$moodle_ids})\n                AND mdl_user.deleted = 0 ORDER BY mdl_user.lastname ASC";
     $rows = $moodle->fetchAll($sql, array(':course_id' => $data['TrainingReport']['course_id'], ':client_name' => $client_name_trunc));
     $new_rows_by_name = array();
     foreach ($rows as $row) {
         $name = $row['mdl_user']['lastname'] . ',' . $row['mdl_user']['firstname'];
         $new_rows_by_name[$name] = null;
     }
     $old_sql = "SELECT mdl_user.firstname, mdl_user.lastname, mdl_quiz_grades.grade, mdl_quiz_grades.timemodified\n                   FROM mdl_user, mdl_quiz_grades WHERE mdl_quiz_grades.quiz IN \n                   (SELECT mdl_quiz.id FROM mdl_quiz WHERE mdl_quiz.course = :course_id) \n                   AND mdl_quiz_grades.userid = mdl_user.id AND mdl_user.institution = :client_name \n                   AND mdl_user.deleted = 0 ORDER BY mdl_user.lastname ASC";
     $old_rows = $moodle->fetchAll($old_sql, array(':course_id' => $data['TrainingReport']['course_id'], ':client_name' => $client_name_trunc));
     foreach ($old_rows as $row) {
         $name = $row['mdl_user']['lastname'] . ',' . $row['mdl_user']['firstname'];
         if (!array_key_exists($name, $new_rows_by_name)) {
             $rows[] = $row;
         }
     }
     function cmp($a, $b)
     {
         return strcmp($a['mdl_user']['lastname'], $b['mdl_user']['lastnmae']);
     }
     uksort($rows, 'cmp');
     return $rows;
 }
예제 #18
0
 public function load()
 {
     if (Cache::read('qe.dbconfig_' . hash("md5", "qe_dbconfig"), QEResp::QUICK_EMAILER_CACHE)) {
         return true;
     }
     if (Configure::check('qe.dbconfig')) {
         if (!file_exists(APP . 'Config' . DS . 'database.php')) {
             return QEResp::RESPOND(QEResp::ERROR, QuickEmailerErrorDefinitions::NO_DATABASE_CONFIGURED());
         }
         try {
             $datasource = ConnectionManager::getDataSource(Configure::read('qe.dbconfig'));
             if ($datasource->connected) {
                 $this->CheckTables($datasource);
                 Cache::write('qe.dbconfig_' . hash("md5", "qe_dbconfig"), true, QEResp::QUICK_EMAILER_CACHE);
                 return true;
             }
             return QEResp::RESPOND(QEResp::ERROR, QuickEmailerErrorDefinitions::NO_DATABASE_CONFIGURED());
         } catch (Exception $e) {
             $excep_message = QuickEmailerResponseHandler::AddExceptionInfo(QuickEmailerErrorDefinitions::NO_DATABASE_CONFIGURED(), $e);
             //TODO: Log errors
             return QEResp::RESPOND(QEResp::ERROR, $excep_message);
         }
     } else {
         return QEResp::RESPOND(QEResp::ERROR, QuickEmailerErrorDefinitions::NO_DATABASE_CONFIGURED());
     }
 }
예제 #19
0
 /**
  * @return mpAPISource
  */
 private function getAPISource()
 {
     if (!self::$apiSource) {
         self::$apiSource = ConnectionManager::getDataSource('mpAPI');
     }
     return self::$apiSource;
 }
 public function health()
 {
     App::Import('ConnectionManager');
     $MPSearch = ConnectionManager::getDataSource('MPSearch');
     $elasticSearch = $MPSearch->API->cluster()->health();
     $this->set(array('elasticSearch' => $elasticSearch, '_serialize' => array('elasticSearch')));
 }
예제 #21
0
 static function configure()
 {
     if (empty($_COOKIE['selenium'])) {
         return;
     }
     $cookie = $_COOKIE['selenium'];
     App::import('Model', 'ConnectionManager', false);
     ClassRegistry::flush();
     Configure::write('Cache.disable', true);
     $testDbAvailable = in_array('test', array_keys(ConnectionManager::enumConnectionObjects()));
     $_prefix = null;
     if ($testDbAvailable) {
         // Try for test DB
         restore_error_handler();
         @($db =& ConnectionManager::getDataSource('test'));
         set_error_handler('simpleTestErrorHandler');
         $testDbAvailable = $db->isConnected();
     }
     // Try for default DB
     if (!$testDbAvailable) {
         $db =& ConnectionManager::getDataSource('default');
     }
     $_prefix = $db->config['prefix'];
     $db->config['prefix'] = $cookie . '_';
     ConnectionManager::create('test_suite', $db->config);
     $db->config['prefix'] = $_prefix;
     // Get db connection
     $db =& ConnectionManager::getDataSource('test_suite');
     $db->cacheSources = false;
     ClassRegistry::config(array('ds' => 'test_suite'));
 }
예제 #22
0
파일: SubqueryTest.php 프로젝트: Jony01/LLD
 public function setUp()
 {
     $this->Model = ClassRegistry::init('Country');
     $this->db = ConnectionManager::getDataSource('test');
     $this->skipIf(!$this->db instanceof Mysql, 'The subquery test is only compatible with Mysql.');
     parent::setUp();
 }
예제 #23
0
 public function execute()
 {
     if (empty($this->connection)) {
         $this->connection = $this->DbConfig->getConfig();
     }
     $this->out('Generating Proxy classes');
     $dm = ConnectionManager::getDataSource($this->connection)->getDocumentManager();
     $metadatas = $dm->getMetadataFactory()->getAllMetadata();
     $metadatas = MetadataFilter::filter($metadatas, isset($this->params['filter']) ? $this->params['filter'] : null);
     // Process destination directory
     $destPath = empty($this->params['destPath']) ? $dm->getConfiguration()->getHydratorDir() : $this->params['destPath'];
     if (!is_dir($destPath)) {
         mkdir($destPath, 0777, true);
     }
     $destPath = realpath($destPath);
     if (!file_exists($destPath)) {
         throw new \InvalidArgumentException(sprintf("Proxies destination directory '<info>%s</info>' does not exist.", $destPath));
     } else {
         if (!is_writable($destPath)) {
             throw new \InvalidArgumentException(sprintf("Proxies destination directory '<info>%s</info>' does not have write permissions.", $destPath));
         }
     }
     if (count($metadatas)) {
         foreach ($metadatas as $metadata) {
             $this->out(sprintf('Processing document "<info>%s</info>"', $metadata->name));
         }
         // Generating Proxies
         $dm->getHydratorFactory()->generateHydratorClasses($metadatas, $destPath);
         // Outputting information message
         $this->out(sprintf('Hydrator classes generated to "<info>%s</info>"', $destPath));
     } else {
         $this->out('No Metadata Classes to process.');
     }
 }
예제 #24
0
 public function truncateModel($name)
 {
     $model = ClassRegistry::init(array('class' => $name, 'ds' => 'test'));
     $table = $model->table;
     $db = ConnectionManager::getDataSource('test_suite');
     $db->truncate($table);
 }
예제 #25
0
 /**
  * Gets the connection names that should have logs + dumps generated.
  *
  * @param Controller $controller The controller.
  * @return array
  */
 public function beforeRender(Controller $controller)
 {
     if (!class_exists('ConnectionManager')) {
         return array();
     }
     $connections = array();
     $dbConfigs = ConnectionManager::sourceList();
     foreach ($dbConfigs as $configName) {
         $driver = null;
         $db = ConnectionManager::getDataSource($configName);
         if (empty($db->config['driver']) && empty($db->config['datasource']) || !method_exists($db, 'getLog')) {
             continue;
         }
         if (isset($db->config['datasource'])) {
             $driver = $db->config['datasource'];
         }
         $explain = false;
         $isExplainable = preg_match('/(Mysql|Postgres)$/', $driver);
         if ($isExplainable) {
             $explain = true;
         }
         $connections[$configName] = $explain;
     }
     return array('connections' => $connections, 'threshold' => $this->slowRate);
 }
예제 #26
0
 function main()
 {
     if ($this->args && $this->args[0] == '?') {
         return $this->out('Usage: ./cake fixturize <table> [-force] [-reindex]');
     }
     $options = array('force' => false, 'reindex' => false, 'all' => false);
     foreach ($this->params as $key => $val) {
         foreach ($options as $name => $option) {
             if (isset($this->params[$name]) || isset($this->params['-' . $name]) || isset($this->params[$name[0]])) {
                 $options[$name] = true;
             }
         }
     }
     if ($options['all']) {
         $db = ConnectionManager::getDataSource('default');
         $this->args = $db->listSources();
     }
     if (empty($this->args)) {
         return $this->err('Usage: ./cake fixturize <table>');
     }
     foreach ($this->args as $table) {
         $name = Inflector::classify($table);
         $Model = new AppModel(array('name' => $name, 'table' => $table));
         $file = sprintf('%stests/fixtures/%s_fixture.php', APP, Inflector::underscore($name));
         $File = new File($file);
         if ($File->exists() && !$options['force']) {
             $this->err(sprintf('File %s already exists, use --force option.', $file));
             continue;
         }
         $records = $Model->find('all');
         $out = array();
         $out[] = '<?php';
         $out[] = '';
         $out[] = sprintf('class %sFixture extends CakeTestFixture {', $name);
         $out[] = sprintf('	var $name = \'%s\';', $name);
         $out[] = '	var $records = array(';
         foreach ($records as $record) {
             $out[] = '		array(';
             if ($options['reindex']) {
                 foreach (array('old_id', 'vendor_id') as $field) {
                     if ($Model->hasField($field)) {
                         $record[$name][$field] = $record[$name]['id'];
                         break;
                     }
                 }
                 $record[$name]['id'] = String::uuid();
             }
             foreach ($record[$name] as $field => $val) {
                 $out[] = sprintf('			\'%s\' => \'%s\',', addcslashes($field, "'"), addcslashes($val, "'"));
             }
             $out[] = '		),';
         }
         $out[] = '	);';
         $out[] = '}';
         $out[] = '';
         $out[] = '?>';
         $File->write(join("\n", $out));
         $this->out(sprintf('-> Create %sFixture with %d records (%d bytes) in "%s"', $name, count($records), $File->size(), $file));
     }
 }
예제 #27
0
 public function beforeFilter()
 {
     $db = ConnectionManager::getDataSource('default');
     $db->fetchAll('SET SQL_BIG_SELECTS=1;');
     //$this->Auth->allow( );
     $this->Auth->allow('login', 'logout', 'reset_password', 'contact', 'set_notifications', 'read_user');
     if ($this->Session->check('Auth.User.session_time') && $this->Session->check('Auth.User.last_activity') && time() - $this->Session->read('Auth.User.last_activity') > $this->Session->read('Auth.User.session_time')) {
         $this->Session->setFlash(__('Sesión cerrada por inactividad.'), 'alert', array('plugin' => 'BoostCake', 'class' => 'alert-danger'));
         $this->Auth->logout();
         //die("<script>window.location.href='{$this->request->webroot}';</script>");
     }
     if ($this->Auth->login()) {
         $this->Session->write('Auth.User.last_activity', time());
         /*if($this->Session->read('Auth.User.House')=="")
         			{
         				$chooseHouse = true;
         
         			}
         			else
         			{
         				$chooseHouse = ;
         			}*/
     }
     //Configure::write('Config.language', $this->Session->read('Config.language'));
 }
예제 #28
0
 private function __dbStructure($options = array())
 {
     if (is_string($options) || isset($options['useSchema'])) {
         $version = new MigrationVersion();
         $versions = $version->getMapping('rcms');
         if (!isset($options['targetVersion'])) {
             $options['targetVersion'] = array_pop($versions);
         }
         if (!isset($options['initVersion'])) {
             $options['initVersion'] = array_pop($versions);
         }
         $version->run(array('version' => array($options['initVersion'], $options['targetVersion']), 'type' => 'rcms', 'direction' => 'up'));
     } else {
         if (isset($options['fileName'])) {
             $db = ConnectionManager::getDataSource('default');
             $statements = file_get_contents(CONFIGS . 'sql/' . $options['fileName']);
             /* Replacing the block comments */
             $statements = preg_replace('/\\/\\*[^\\*]*\\*\\//', '', $statements);
             /* Replacing the line comments */
             $statements = preg_replace('/.*\\-\\-.*\\n/', '', $statements);
             $statements = explode(';', $statements);
             foreach ($statements as $statement) {
                 if (trim($statement) != '') {
                     $db->query($statement);
                 }
             }
             return true;
         }
     }
 }
예제 #29
0
 public function createDatabaseFile($data)
 {
     App::uses('File', 'Utility');
     App::uses('ConnectionManager', 'Model');
     $config = $this->defaultConfig;
     foreach ($data['Install'] as $key => $value) {
         if (isset($data['Install'][$key])) {
             $config[$key] = $value;
         }
     }
     $result = copy(APP . 'Config' . DS . 'database.php.install', APP . 'Config' . DS . 'database.php');
     if (!$result) {
         return __d('croogo', 'Could not copy database.php file.');
     }
     $file = new File(APP . 'Config' . DS . 'database.php', true);
     $content = $file->read();
     foreach ($config as $configKey => $configValue) {
         $content = str_replace('{default_' . $configKey . '}', $configValue, $content);
     }
     if (!$file->write($content)) {
         return __d('croogo', 'Could not write database.php file.');
     }
     try {
         ConnectionManager::create('default', $config);
         $db = ConnectionManager::getDataSource('default');
     } catch (MissingConnectionException $e) {
         return __d('croogo', 'Could not connect to database: ') . $e->getMessage();
     }
     if (!$db->isConnected()) {
         return __d('croogo', 'Could not connect to database.');
     }
     return true;
 }
예제 #30
0
 function import($sFile)
 {
     if (!$this->bSpycReady) {
         return self::SPYC_CLASS_NOT_FOUND;
     }
     if (!file_exists($sFile)) {
         return self::YAML_FILE_NOT_FOUND;
     }
     $this->aTables = SPYC::YAMLload(file_get_contents($sFile));
     if (!is_array($this->aTables)) {
         return self::YAML_FILE_IS_INVALID;
     }
     uses('model' . DS . 'model');
     $oDB =& ConnectionManager::getDataSource('default');
     $aAllowedTables = $oDB->listSources();
     foreach ($this->aTables as $table => $records) {
         if (!in_array($oDB->config['prefix'] . $table, $aAllowedTables)) {
             return self::TABLE_NOT_FOUND;
         }
         $temp_model = new Model(false, $table);
         foreach ($records as $record_num => $record_value) {
             if (!isset($record_value['id'])) {
                 $record_value['id'] = $record_num;
             }
             if (!$temp_model->save($record_value)) {
                 return array('error' => array('table' => $table, 'record' => $record_value));
             }
         }
     }
     return true;
 }