Exemple #1
1
 public function indexDirectory($dir)
 {
     if (!file_exists($dir)) {
         throw new Doctrine_Search_Indexer_Exception('Unknown directory ' . $dir);
     }
     $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY);
     $files = array();
     foreach ($it as $file) {
         $name = $file->getPathName();
         if (strpos($name, '.svn') === false) {
             $files[] = $name;
         }
     }
     $q = new Doctrine_Query();
     $q->delete()->from('Doctrine_File f')->where('f.url LIKE ?', array($dir . '%'))->execute();
     // clear the index
     $q = new Doctrine_Query();
     $q->delete()->from('Doctrine_File_Index i')->where('i.file_id = ?')->execute();
     $conn = Doctrine_Manager::connection();
     $coll = new Doctrine_Collection('Doctrine_File');
     foreach ($files as $file) {
         $coll[]->url = $file;
     }
     $coll->save();
 }
 /**
  * DOCUMENT ME
  * @param mixed $arguments
  * @param mixed $options
  */
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     // PDO connection not so useful, get the doctrine one
     $conn = Doctrine_Manager::connection();
     if ($options['table'] === 'aPage') {
         $q = Doctrine::getTable('aLuceneUpdate')->createQuery('u');
     } else {
         $q = Doctrine::getTable($options['table'])->createQuery('o')->where('o.lucene_dirty IS TRUE');
     }
     if ($options['limit'] !== false) {
         $q->limit($options['limit'] + 0);
     }
     $updates = $q->execute();
     $i = 0;
     foreach ($updates as $update) {
         $i++;
         if ($options['table'] === 'aPage') {
             $page = aPageTable::retrieveByIdWithSlots($update->page_id, $update->culture);
             // Careful, pages die
             if ($page) {
                 $page->updateLuceneIndex();
             }
             $update->delete();
         } else {
             // The actual object
             $update->updateLuceneIndex();
             $update->lucene_dirty = false;
             $update->save();
         }
     }
 }
 public function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager(sfProjectConfiguration::getApplicationConfiguration('frontend', $options['env'], true));
     $configuration = ProjectConfiguration::getApplicationConfiguration('frontend', $options['env'], true);
     sfContext::createInstance($configuration);
     $conn = Doctrine_Manager::connection();
     // Récupération de toutes les notices.
     $noeuds = $conn->execute("SELECT id, name FROM ei_data_set_structure;");
     $this->log('Récupération des noeuds...OK');
     // Création de la requête permettant
     $this->log('Création de la requête de mise à jour...');
     $requeteToUpdate = "UPDATE ei_data_set_structure SET slug = #{NEW_SLUG} WHERE id = #{NODE_ID};";
     $requeteGlobale = array();
     foreach ($noeuds->fetchAll() as $noeud) {
         // Remplacement SLUG.
         $tmpRequete = str_replace("#{NEW_SLUG}", $conn->quote(MyFunction::sluggifyForXML($noeud["name"])), $requeteToUpdate);
         // Remplacement ID.
         $tmpRequete = str_replace("#{NODE_ID}", $noeud["id"], $tmpRequete);
         // Ajout dans la requête globale.
         $requeteGlobale[] = $tmpRequete;
     }
     // Préparation de la requête.
     $this->log("Préparation de la requête...");
     $requete = implode(" ", $requeteGlobale);
     try {
         // Exécution de la requête.
         $this->log("Exécution de la requête...");
         $conn->execute($requete);
         // Fin.
         $this->log("Processus terminé avec succès.");
     } catch (Exception $exc) {
         $this->log($exc->getMessage());
     }
 }
 protected function copyModel($model)
 {
     $table = dmDb::table($model);
     $tableName = $table->getTableName();
     $vars = array();
     $placeholders = array();
     foreach ($table->getColumns() as $columnName => $column) {
         $fields[] = $columnName;
         $placeholders[] = ':' . $columnName;
     }
     $conn = Doctrine_Manager::connection();
     $stmt = $conn->prepare(sprintf('INSERT INTO %s (%s) VALUES (%s)', $tableName, implode(',', $fields), implode(',', $placeholders)))->getStatement();
     $conn->beginTransaction();
     try {
         foreach ($this->oldDb->getData($tableName) as $array) {
             $values = array();
             foreach ($fields as $field) {
                 $values[':' . $field] = isset($array[$field]) ? $array[$field] : '';
             }
             $stmt->execute($values);
         }
     } catch (Exception $e) {
         dmDebug::show($model, $array);
         throw $e;
     }
     $conn->commit();
 }
 protected function execute($arguments = array(), $options = array())
 {
     $configuration = ProjectConfiguration::getApplicationConfiguration($arguments['application'], $options['env'], true);
     $databaseManager = new sfDatabaseManager($configuration);
     $databaseManager->initialize($configuration);
     $db = Doctrine_Manager::connection();
     //get person entities with all-caps names
     $sql = 'SELECT e.id, e.name FROM entity e ' . 'WHERE e.name <> \'\' AND e.primary_ext = ? AND CAST(UPPER(e.name) AS BINARY) = CAST(e.name AS BINARY)';
     $stmt = $db->execute($sql, array('Person'));
     $names = $stmt->fetchAll(PDO::FETCH_ASSOC);
     foreach ($names as $ary) {
         $new = PersonTable::nameizePersonName($ary['name']);
         if ($new != $ary['name']) {
             $sql = 'UPDATE entity SET name = ? WHERE id = ?';
             $stmt = $db->execute($sql, array($new, $ary['id']));
             print "Changed Entity name " . $ary['name'] . " to " . $new . "\n";
         }
     }
     //get aliases with all-caps names
     $sql = 'SELECT a.id, a.name FROM alias a LEFT JOIN entity e ON (e.id = a.entity_id) ' . 'WHERE a.name <> \'\' AND a.is_primary = 1 AND e.primary_ext = ? AND ' . 'CAST(UPPER(a.name) AS BINARY) = CAST(a.name AS BINARY)';
     $stmt = $db->execute($sql, array('Person'));
     $names = $stmt->fetchAll(PDO::FETCH_ASSOC);
     foreach ($names as $ary) {
         $new = PersonTable::nameizePersonName($ary['name']);
         if ($new != $ary['name']) {
             $sql = 'UPDATE alias SET name = ? WHERE id = ?';
             $stmt = $db->execute($sql, array($new, $ary['id']));
             print "Changed Alias " . $ary['name'] . " to " . $new . "\n";
         }
     }
     //DONE
     LsCli::beep();
 }
 public function deleteProjectParams($project_id, $project_ref, Doctrine_Connection $conn = null)
 {
     if ($conn == null) {
         $conn = Doctrine_Manager::connection();
     }
     $conn->getTable('EiProjectParam')->createQuery('pp')->delete()->where('pp.project_id=? And pp.project_ref=?', array($project_id, $project_ref))->execute();
 }
Exemple #7
0
 public function getDefaultInterventionWithScenarioVersion(EiProjet $ei_project, EiVersion $ei_version, Doctrine_Connection $conn = null)
 {
     if ($conn == null) {
         $conn = Doctrine_Manager::connection();
     }
     return $conn->fetchRow("select s.id as subject_id,s.name as subject_name,sp.ei_version_id as sp_ei_version_id, s.package_id,s.package_ref ,t.name as ticket_name  from ei_subject s " . " inner join ei_ticket t on s.package_id=t.ticket_id and s.package_ref=t.ticket_ref " . " Left join ei_scenario_package sp on sp.package_id=t.ticket_id and sp.package_ref=t.ticket_ref and sp.ei_scenario_id=" . $ei_version->getEiScenarioId() . " inner join ei_user_default_package udp on t.ticket_id=udp.ticket_id and t.ticket_ref=udp.ticket_ref " . " where udp.user_id=" . $this->getUserId() . " and udp.user_ref=" . $this->getRefId() . " and s.project_id=" . $ei_project->getProjectId() . " and s.project_ref=" . $ei_project->getRefId());
 }
 public static function createOrUpdateDistantParams(EiProjet $ei_project, EiProfil $ei_profile, KalFunction $kal_function, $data, Doctrine_Connection $conn = null)
 {
     if ($conn == null) {
         $conn = Doctrine_Manager::connection();
     }
     try {
         $conn->beginTransaction();
         //Début de la transaction
         //Appel du webservice
         $result_update = MyFunction::loadResultOfWebServiceByPostJson(MyFunction::getPrefixPath(null) . "/serviceweb/project/parameter/createOrUpdate.json", array('project_id' => $ei_project->getProjectId(), 'project_ref' => $ei_project->getRefId(), 'profile_id' => $ei_profile->getProfileId(), 'profile_ref' => $ei_profile->getProfileRef(), 'function_id' => $kal_function->getFunctionId(), 'function_ref' => $kal_function->getFunctionRef(), 'data' => $data));
         $array_result = json_decode(html_entity_decode($result_update), true);
         //Récupération du paramètre pour traitement
         if (count($array_result) == 0) {
             return false;
         }
         if (array_key_exists("error", $array_result)) {
             return false;
         }
         if (!$array_result[0]) {
             return false;
         }
         //Rechargement d'un paramètre
         self::reload($array_result, $conn);
         $conn->commit();
         return $array_result[0]['fp_id'];
     } catch (Exception $e) {
         $conn->rollback();
         return false;
         throw $e;
     }
 }
 public function getDefaultInterventionWithScenarioVersion(EiProjet $ei_project, EiVersion $ei_version, Doctrine_Connection $conn = null)
 {
     if ($conn == null) {
         $conn = Doctrine_Manager::connection();
     }
     return $conn->fetchRow("select sp.*, s.id as subject_id ,s.name as subject_name from ei_scenario_package sp\n                                inner join ei_subject s on sp.package_id= s.package_id and sp.package_ref=s.package_ref\n                                where sp.ei_scenario_id= " . $ei_version->getEiScenarioId() . " and sp.ei_version_id=" . $ei_version->getId() . " and s.project_id=" . $ei_project->getProjectId() . " and s.project_ref=" . $ei_project->getRefId());
 }
 /**
  * initialize the library scan by setting a new scan_id for the session
  * @param source str: add a service name for each scanner
  */
 public function __construct($service_name)
 {
     //Since this class services a batch script, stop Doctrine from leaving objects in memory
     Doctrine_Manager::connection()->setAttribute(Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS, true);
     $this->service_name = $service_name;
     $this->scan_id = Doctrine_Core::getTable('Scan')->addScan('playlist');
 }
Exemple #11
0
 /**
  * Setup Doctrine
  *
  * @return void
  */
 public function setup(Zend_Config $config)
 {
     if (is_array($config->path_config)) {
         $this->setPathConfig($config->path_config);
     } elseif ($config->path_config instanceof Zend_Config) {
         $this->setPathConfig($config->path_config->toArray());
     }
     if ($charset = $config->get('charset')) {
         $listener = new Zym_App_Resource_Doctrine_ConnectionListener();
         $listener->setCharset($charset);
         Doctrine_Manager::getInstance()->addListener($listener);
     }
     // determine if config is for a single-db or a multi-db site
     $connections = $config->connection instanceof Zend_Config ? $config->connection->toArray() : (array) $config->connection;
     // add connection(s) to doctrine
     foreach ($connections as $name => $connection) {
         if ($connection instanceof Zend_Config) {
             $connection = $connection->toArray();
         }
         if (is_string($name)) {
             Doctrine_Manager::connection($connection, $name);
         } else {
             Doctrine_Manager::connection($connection);
         }
     }
 }
 public function testTest2()
 {
     $dbh = new Doctrine_Adapter_Mock('mysql');
     $conn = Doctrine_Manager::connection($dbh);
     $sql = $conn->export->exportClassesSql(array('Ticket_255_User'));
     $this->assertEqual($sql[0], 'CREATE TABLE ticket_255__user (id BIGINT AUTO_INCREMENT, username VARCHAR(255), email_address VARCHAR(255), password VARCHAR(255), UNIQUE INDEX username_email_address_unqidx_idx (username, email_address), PRIMARY KEY(id)) ENGINE = INNODB');
 }
 public function insertTmpData($projets, $project_id, $project_ref, Doctrine_Connection $conn = null)
 {
     if ($conn == null) {
         $conn = Doctrine_Manager::connection();
     }
     //On vide la table temporaire avant toute opération
     $conn->execute("TRUNCATE TABLE script_ei_notice");
     $items = $projets->getElementsByTagName("ei_notices");
     if ($items->length != 0) {
         //ya t-il des éléments à traiter?
         $ei_notices = $items->item(0)->getElementsByTagName("ei_notice");
         $stmt = $conn->prepare("INSERT INTO script_ei_notice (notice_id, notice_ref,function_id,function_ref,name) " . "VALUES (:notice_id, :notice_ref,:function_id,:function_ref,:name) " . "ON DUPLICATE KEY UPDATE notice_id=notice_id,notice_ref=notice_ref  ");
         if ($ei_notices->length != 0) {
             foreach ($ei_notices as $ei_notice) {
                 $notice_id = $ei_notice->getAttribute("notice_id");
                 $notice_ref = $ei_notice->getAttribute("notice_ref");
                 //recherche du profil en base
                 if ($notice_id != null && $notice_ref != null) {
                     $stmt->bindValue("notice_id", $notice_id);
                     $stmt->bindValue("notice_ref", $notice_ref);
                     $stmt->bindValue("function_id", $ei_notice->getElementsByTagName("function_id")->item(0)->nodeValue);
                     $stmt->bindValue("function_ref", $ei_notice->getElementsByTagName("function_ref")->item(0)->nodeValue);
                     $stmt->bindValue("name", $ei_notice->getElementsByTagName("name")->item(0)->nodeValue);
                     $stmt->execute(array());
                 }
             }
         }
     }
     return null;
 }
 static function countByEntityId($id)
 {
     $db = Doctrine_Manager::connection();
     $sql = 'SELECT COUNT(*) FROM os_entity_donor WHERE entity_id = ?';
     $stmt = $db->execute($sql, array($id));
     return $stmt->fetch(PDO::FETCH_COLUMN);
 }
Exemple #15
0
 public function postDelete(Doctrine_Event $event)
 {
     //Make sure all linked tables are clean
     //RokGallery_Model_FileTags
     $q = Doctrine_Query::create()->delete('RokGallery_Model_FileTags ft')->andWhere('ft.file_id NOT IN (SELECT f.id from RokGallery_Model_File f)');
     $q->execute();
     $q->free();
     //RokGallery_Model_FileViews
     $q = Doctrine_Query::create()->delete('RokGallery_Model_FileViews fv')->andWhere('fv.file_id NOT IN (SELECT f.id from RokGallery_Model_File f)');
     $q->execute();
     $q->free();
     //RokGallery_Model_FileLoves
     $q = Doctrine_Query::create()->delete('RokGallery_Model_FileLoves fl')->andWhere('fl.file_id NOT IN (SELECT f.id from RokGallery_Model_File f)');
     $q->execute();
     $q->free();
     //rokgallery_files_index
     $conn =& Doctrine_Manager::connection();
     $dbh =& $conn->getDbh();
     $stmt = $dbh->prepare('delete from ' . RokCommon_Doctrine::getPlatformInstance()->setTableName('rokgallery_files_index') . ' where id NOT IN (SELECT f.id from ' . RokGallery_Model_FileTable::getInstance()->getTableName() . ' f)');
     $stmt->execute();
     //RokGallery_Model_Slice
     $q = Doctrine_Query::create()->delete('RokGallery_Model_Slice s')->andWhere('s.file_id NOT IN (SELECT f.id from RokGallery_Model_File f)');
     $q->execute();
     $q->free();
 }
 public function __construct(array $options = array())
 {
     $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $options);
     if (!isset($this->_options['connection'])) {
         $this->_options['connection'] = Doctrine_Manager::connection();
     }
 }
 protected function execute($arguments = array(), $options = array())
 {
     $configuration = ProjectConfiguration::getApplicationConfiguration($arguments['application'], $options['env'], true);
     $databaseManager = new sfDatabaseManager($configuration);
     $databaseManager->initialize($configuration);
     $this->db = Doctrine_Manager::connection();
     $this->s3 = new S3(sfConfig::get('app_amazon_access_key'), sfConfig::get('app_amazon_secret_key'));
     // hide strict errors
     error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
     $sql = "SELECT DISTINCT(r.source) FROM reference r ORDER BY id ASC LIMIT " . $options["limit"] . " OFFSET " . $options["offset"];
     $stmt = $this->db->execute($sql);
     $sources = $stmt->fetchAll(PDO::FETCH_COLUMN);
     foreach ($sources as $source) {
         if (!$options["localdir"]) {
             $s3path = ReferenceTable::generateS3path($source);
             if (!$options["overwrite"] && $this->s3->getObjectInfo(sfConfig::get('app_amazon_s3_bucket'), $s3path) !== false) {
                 print "ALREADY UPLOADED: " . $s3path . "\n";
                 continue;
             }
         }
         $this->writeTmpFile($source, $options["debug_mode"], $options["localdir"]);
         if (!$options["localdir"]) {
             $this->uploadTmpFile($source, $options["overwrite"], $options["debug_mode"]);
             if (unlink($this->getLocalPath($source, $options["local_dir"])) && $options["debug_mode"]) {
                 print "REMOVED LOCAL: " . $source . " [" . sha1($source) . "]\n";
             }
         }
         print "----------------------------------------------------------------\n";
     }
     //DONE
     LsCli::beep();
 }
 public function executeGuardar(sfWebRequest $request)
 {
     $this->datos = $request->getParameter('datos');
     $unidadeducativa = Doctrine::getTable('SdatRueUnidadEducativa')->find(array($this->datos['codue'], $this->datos['subcea'], $this->datos['periodo']));
     if ($unidadeducativa) {
         $conn = Doctrine_Manager::connection();
         $conn->beginTransaction();
         try {
             $unidadeducativa->setTelefono1($this->datos['telefono1']);
             $unidadeducativa->setTelefono2($this->datos['telefono2']);
             $unidadeducativa->setReferenciaTelefono2($this->datos['referenciatelefono2']);
             $unidadeducativa->setFax($this->datos['fax']);
             $unidadeducativa->setEmail($this->datos['email']);
             $unidadeducativa->setCasilla($this->datos['casilla']);
             $unidadeducativa->setCiDirector($this->datos['cidirector']);
             $unidadeducativa->setDirector($this->datos['director']);
             $unidadeducativa->setItemDirector($this->datos['itemdirector']);
             $unidadeducativa->setCodCerradaId($this->datos['cerrada']);
             if ($this->datos['turno'] == '-999') {
                 $unidadeducativa->setTurnoId('0');
             } else {
                 $unidadeducativa->setTurnoId($this->datos['turno']);
             }
             $unidadeducativa->setFechaConsolidacion(date('Y-m-d H:i:s'));
             $unidadeducativa->save();
             $conn->commit();
             $this->getUser()->setFlash('notice_error', "SE CREO CORRECTAMENTE");
             $this->redirect('cea_crear_inicio/index');
         } catch (Doctrine_Exception $e) {
             $conn->rollback();
             $this->getUser()->setFlash('notice_error', "ERROR AL CREAR INICIO DE GESTION DEL CEA");
             $this->redirect('cea_crear_inicio/index');
         }
     }
 }
Exemple #19
0
 function index()
 {
     $category = new Category();
     $category->title = "The CodeIgniter Lounge";
     $forum = new Forum();
     $forum->title = "Introduce Yourself!";
     $forum->description = "Use this forum to introduce yourself to the CodeIgniter community, or to announce your new CI powered site.";
     // add category to the forum
     $forum->Category = $category;
     $forum2 = new Forum();
     $forum2->title = "The Lounge";
     $forum2->description = "CodeIgniter's social forum where you can discuss anything not related to development. No topics off limits... but be civil.";
     // you can also add the other way around
     // add forum to the category
     $category->Forums[] = $forum2;
     // a different syntax (array style)
     $category2 = new Category();
     $category2['title'] = "CodeIgniter Development Forums";
     $forum3 = new Forum();
     $forum3['title'] = "CodeIgniter Discussion";
     $forum3['description'] = "This forum is for general topics related to CodeIgniter";
     $forum4 = new Forum();
     $forum4['title'] = "Code and Application Development";
     $forum4['description'] = "Use the forum to discuss anything related to programming and code development.";
     $category2['Forums'][] = $forum3;
     $category2['Forums'][] = $forum4;
     // flush() saves all unsaved objects
     $conn = Doctrine_Manager::connection();
     $conn->flush();
     echo "Success!";
 }
 public function createSubjectMessageType($project_id, $project_ref, $name, $conn)
 {
     if ($conn == null) {
         $conn = Doctrine_Manager::connection();
     }
     $conn->insert($this->getInstance(), array('name' => $name, 'project_id' => $project_id, 'project_ref' => $project_ref, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')));
 }
 public function testExport()
 {
     $conn = Doctrine_Manager::connection('mysql://root@localhost/test');
     $sql = $conn->export->exportClassesSql(array('Ticket_1604_User', 'Ticket_1604_EmailAdresses'));
     $def = array("CREATE TABLE ticket_1604__user (id BIGINT AUTO_INCREMENT, name VARCHAR(30), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = INNODB", "CREATE TABLE ticket_1604__email_adresses (id BIGINT AUTO_INCREMENT, user_id BIGINT, address VARCHAR(30), INDEX user_id_idx (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = INNODB", "ALTER TABLE ticket_1604__email_adresses ADD CONSTRAINT ticket_1604__email_adresses_user_id_ticket_1604__user_id FOREIGN KEY (user_id) REFERENCES ticket_1604__user(id)");
     $this->assertEqual($sql, $def);
 }
 /**
  * コンストラクタ
  *
  * @param  string  $app  アプリケーションの種類 (ex. front, dev,... )
  */
 public function __construct($app)
 {
     $this->configuration = ProjectConfiguration::getApplicationConfiguration($app, 'test', true);
     new sfDatabaseManager($this->configuration);
     $this->connection = Doctrine_Manager::connection();
     $this->connection->beginTransaction();
 }
Exemple #23
0
 /**
  * Retrieves the connection associated to this expression at creation,
  * or the current connection used if it was not specified. 
  * 
  * @return Doctrine_Connection The connection
  */
 public function getConnection()
 {
     if (!isset($this->_conn)) {
         return Doctrine_Manager::connection();
     }
     return $this->_conn;
 }
 public function getTagsForCategories($categoryIds, $model, $popular = false, $limit = null)
 {
     if (!is_array($categoryIds)) {
         $categoryIds = array($categoryIds);
     }
     $connection = Doctrine_Manager::connection();
     $pdo = $connection->getDbh();
     $innerQuery = "SELECT b.id AS id FROM a_blog_item b\n                   LEFT JOIN a_blog_item_category bic ON b.id = bic.blog_item_id\n                   LEFT JOIN a_blog_category bc ON bic.blog_category_id = bc.id\n                   WHERE  b.status = 'published' AND b.published_at < NOW()";
     if (count($categoryIds)) {
         $innerQuery .= " AND bc.id IN (" . implode(',', $categoryIds) . ") ";
     }
     $innerQuery .= " GROUP BY b.id ";
     $query = "SELECT tg.tag_id, t.name, COUNT(tg.id) AS t_count FROM (\n              {$innerQuery}\n              ) as b\n              LEFT JOIN tagging tg ON tg.taggable_id = b.id\n              LEFT JOIN tag t ON t.id = tg.tag_id\n              WHERE tg.taggable_model = '{$model}'";
     $query .= "GROUP BY tg.tag_id ";
     if ($popular) {
         $query .= "ORDER BY t_count DESC ";
     } else {
         $query .= "ORDER BY t.name ASC ";
     }
     if (!is_null($limit)) {
         $query .= "LIMIT {$limit}";
     }
     $rs = $pdo->query($query);
     $tags = array();
     foreach ($rs as $tag) {
         $name = $tag['name'];
         $tags[$name] = $tag['t_count'];
     }
     return $tags;
 }
 public function initialize($context, $parameters = array())
 {
     parent::initialize($context, $parameters);
     $this->db = Doctrine_Manager::connection();
     $this->request = $context->getRequest();
     $this->response = $context->getResponse();
 }
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     echo "\nApostrophe Database Migration Task\n  \nThis task will make any necessary database schema changes to bring your \nMySQL database up to date with the current release of Apostrophe and any additional\nApostrophe plugins that you have installed. For other databases see the source code \nor run './symfony doctrine:build-sql' to obtain the SQL commands you may need.\n  \nBACK UP YOUR DATABASE BEFORE YOU RUN THIS TASK. It works fine in our tests, \nbut why take chances with your data?\n\n";
     if (!$options['force']) {
         if (!$this->askConfirmation("Are you sure you are ready to migrate your project? [y/N]", 'QUESTION_LARGE', false)) {
             die("Operation CANCELLED. No changes made.\n");
         }
     }
     $this->migrate = new aMigrate(Doctrine_Manager::connection()->getDbh());
     // If I needed to I could look for the constraint definition like this.
     // But since we added these in the same migration I don't have to. Keep this
     // comment around as sooner or later we'll probably need to check for this
     // kind of thing
     //
     // $createTable = $data[0]['Create Table'];
     // if (!preg_match('/CONSTRAINT `a_redirect_page_id_a_page_id`/', $createTable))
     // {
     //
     // }
     if (!$this->migrate->tableExists('a_redirect')) {
         $this->migrate->sql(array("CREATE TABLE IF NOT EXISTS a_redirect (id INT AUTO_INCREMENT, page_id INT, slug VARCHAR(255) UNIQUE, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, INDEX slugindex_idx (slug), INDEX page_id_idx (page_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = INNODB;", "ALTER TABLE a_redirect ADD CONSTRAINT a_redirect_page_id_a_page_id FOREIGN KEY (page_id) REFERENCES a_page(id) ON DELETE CASCADE;"));
     }
     if (!$this->migrate->getCommandsRun()) {
         echo "Your database is already up to date.\n\n";
     } else {
         echo $this->migrate->getCommandsRun() . " SQL commands were run.\n\n";
     }
     echo "Done!\n";
 }
 public static function createDistantNoticeLang($version_notice_id, $notice_id, $notice_ref, $lang, Doctrine_Connection $conn = null)
 {
     if ($conn == null) {
         $conn = Doctrine_Manager::connection();
     }
     try {
         $conn->beginTransaction();
         //Début de la transaction
         //Appel du webservice
         $result_service = MyFunction::loadResultOfWebServiceByPostJson(MyFunction::getPrefixPath(null) . "serviceweb/createNoticeVersion.json", array('version_notice_id' => $version_notice_id, 'notice_id' => $notice_id, 'notice_ref' => $notice_ref, 'lang' => $lang));
         //Récupération de la nouvelle langue de notice pour traitement
         $array_result = json_decode(html_entity_decode($result_service), true);
         if (count($array_result) == 0) {
             return array("success" => false, "message" => "Error on transaction");
         }
         if (array_key_exists("error", $array_result)) {
             return array("success" => false, "message" => $array_result["error"]);
         }
         if (!$array_result[0]) {
             return array("success" => false, "message" => "Empty result content");
         }
         self::reload($array_result, $conn);
         $conn->commit();
         return Doctrine_Core::getTable("EiVersionNotice")->findOneByVersionNoticeIdAndNoticeIdAndNoticeRefAndLang($version_notice_id, $notice_id, $notice_ref, $lang);
     } catch (Exception $e) {
         $conn->rollback();
         throw $e;
         return false;
     }
 }
Exemple #28
0
 public function validate($user, $password)
 {
     if (!isset($user)) {
         $user = new CocoasUser();
     }
     $cuenta = 0;
     try {
         $this->connection = Doctrine_Manager::connection();
         $q = Doctrine_Query::create()->from('user u')->where("u.email='" . $user->name . "'");
         $rows = $q->execute();
         $cuenta = count($rows);
     } catch (Exception $e) {
         if ($GLOBALS["debugMode"]) {
             $this->validator->errors->addError(ErrorManager::CANIS_FATAL, $e->getMessage());
         }
     }
     if ($cuenta == 1) {
         $auxUser = $rows[0];
         //Si los hash de la clave coinciden
         if ($password == $auxUser->password) {
             $user->roleName = $auxUser->Role->name;
             $user->locationId = $auxUser->Location->id;
             $user->status = $auxUser->status;
             $user->id = $auxUser->id;
         }
     } else {
         $user = new CocoasUser();
     }
     return $user;
 }
 public function testCachedResultsAreSpecificToDsn()
 {
     $cacheDriver = new Doctrine_Cache_Array();
     $conn1 = Doctrine_Manager::connection('sqlite::memory:', 'conn_1');
     $conn1->setAttribute(Doctrine_Core::ATTR_RESULT_CACHE, $cacheDriver);
     $conn2 = Doctrine_Manager::connection('sqlite::memory:', 'conn_2');
     $conn2->setAttribute(Doctrine_Core::ATTR_RESULT_CACHE, $cacheDriver);
     $this->assertNotEqual($conn1, $conn2);
     $manager = Doctrine_Manager::getInstance();
     $manager->setCurrentConnection('conn_1');
     $this->assertEqual($conn1, Doctrine_Manager::connection());
     Doctrine_Core::createTablesFromArray(array('Ticket_1706_User'));
     $user = new Ticket_1706_User();
     $user->name = 'Allen';
     $user->save();
     $manager->setCurrentConnection('conn_2');
     $this->assertEqual($conn2, Doctrine_Manager::connection());
     Doctrine_Core::createTablesFromArray(array('Ticket_1706_User'));
     $user = new Ticket_1706_User();
     $user->name = 'Bob';
     $user->save();
     $manager->setCurrentConnection('conn_1');
     $u1 = Doctrine_Query::create()->from('Ticket_1706_User u')->useResultCache()->execute();
     $this->assertEqual(1, count($u1));
     $this->assertEqual('Allen', $u1[0]->name);
     $manager->setCurrentConnection('conn_2');
     $u2 = Doctrine_Query::create()->from('Ticket_1706_User u')->useResultCache()->execute();
     $this->assertEqual(1, count($u2));
     $this->assertEqual('Bob', $u2[0]->name);
 }
 public function createAssignmentHistory(EiSubjectAssignment $assignment, $is_assignment = true, Doctrine_Connection $conn = null)
 {
     if ($conn == null) {
         $conn = Doctrine_Manager::connection();
     }
     return $conn->insert($this->getInstance(), array('author_of_assignment' => MyFunction::getGuard()->getId(), 'subject_id' => $assignment->getSubjectId(), 'assign_to' => $assignment->getGuardId(), 'date' => date("Y-m-d H:i:s"), 'is_assignment' => $is_assignment));
 }