Inheritance: extends dmProjectConfiguration
 protected function setUp()
 {
     if (!sfContext::hasInstance('frontend')) {
         $configuration = new ProjectConfiguration(dirname(__FILE__) . '/../../fixtures/project');
         sfContext::createInstance($configuration->getApplicationConfiguration('frontend', 'test', true));
     }
     if (in_array('sfImageSource', stream_get_wrappers())) {
         stream_wrapper_unregister('sfImageSource');
     }
     stream_wrapper_register('sfImageSource', 'sfImageSourceMock') or die('Failed to register protocol..');
 }
 public function __construct(ProjectConfiguration $projectConfiguration)
 {
     /*
      * We disable Symfony autoload again feature because it is too slow in dev mode
      * If you introduce a new class when using sympal you just must clear your
      * cache manually
      */
     sfAutoloadAgain::getInstance()->unregister();
     $this->_projectConfiguration = $projectConfiguration;
     $this->_dispatcher = $projectConfiguration->getEventDispatcher();
     $this->_configureDoctrine();
     // Listen to the sympal.load event to perform some context-dependent tasks
     $this->_dispatcher->connect('sympal.load', array($this, 'bootstrapFromContext'));
     $this->_dispatcher->connect('sympal.cache.prime', array($this, 'listenSympalCachePrime'));
 }
 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();
     ProjectConfiguration::setupMailer();
     $queue_table = Doctrine::getTable('MailQueue');
     $queue = $queue_table->getPending($arguments['limit']);
     $done = array();
     $failed = array();
     foreach ($queue as $item) {
         try {
             $mail = new Zend_Mail('utf-8');
             $mail->setSubject($item['subject']);
             $mail->setBodyText($item['body']);
             array_map(array($mail, 'addTo'), explode(',', $item['recipients']));
             $mail->send();
             $done[] = $item['id'];
         } catch (Zend_Exception $e) {
             $failed[] = $item['id'];
         }
     }
     $queue_table->deleteItems($done);
     $queue_table->recordAttemps($failed);
     $this->logSection('mailer', sizeof($done) . ' emails sent');
     $this->logSection('mailer', sizeof($failed) . ' emails failed');
 }
 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 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();
 }
 /**
  * コンストラクタ
  *
  * @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();
 }
    protected function execute($arguments = array(), $options = array())
    {
        $autoloader = sfSimpleAutoload::getInstance();
        $autoloader->addDirectory(sfConfig::get('sf_plugins_dir') . '/sfPropelMigrationsLightPlugin/lib');

        $configuration = ProjectConfiguration::getApplicationConfiguration($arguments['application'],
                        $options['env'], true);

        $databaseManager = new sfDatabaseManager($configuration);

        $migrator = new sfMigrator;

        if (isset($arguments['schema-version']) && ctype_digit($arguments['schema-version'])) {
            $max = $arguments['schema-version'];
        } else {
            $max = $migrator->getMaxVersion();
        }

        $migrations = $migrator->getMigrationsToRunUpTo($max);

        foreach ($migrations as $migration) {
            echo "Marking as Migrated: $migration\n";
            $migrator->markMigration($migration);
        }
    }
 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();
     if ($options['house_senate'] == 'house') {
         $sql = 'select e1.id,e2.id from entity e1 left join political_candidate pc on pc.entity_id = e1.id left join political_candidate pc2 on pc2.house_fec_id = pc.house_fec_id left join entity e2 on e2.id = pc2.entity_id where e1.is_deleted = 0 and e2.is_deleted = 0 and e1.id <> e2.id and pc.id is not null and pc2.id is not null and pc.id <> pc2.id and pc.house_fec_id is not null and pc.house_fec_id <> "" and e1.id < e2.id group by e1.id,e2.id';
     } else {
         if ($options['house_senate'] == 'senate') {
             $sql = 'select e1.id,e2.id from entity e1 left join political_candidate pc on pc.entity_id = e1.id left join political_candidate pc2 on pc2.senate_fec_id = pc.senate_fec_id left join entity e2 on e2.id = pc2.entity_id where e1.is_deleted = 0 and e2.is_deleted = 0 and e1.id <> e2.id and pc.id is not null and pc2.id is not null and pc.id <> pc2.id and pc.senate_fec_id is not null and pc.senate_fec_id <> "" and e1.id < e2.id group by e1.id,e2.id';
         } else {
             echo 'House or Senate not selected...ending script' . "\n";
             die;
         }
     }
     $stmt = $this->db->execute($sql);
     $rows = $stmt->fetchAll();
     foreach ($rows as $row) {
         $e1 = Doctrine::getTable('Entity')->find($row[0]);
         $e2 = Doctrine::getTable('Entity')->find($row[1]);
         $mergedEntity = EntityTable::mergeAll($e1, $e2);
         $e2->setMerge(true);
         $e2->clearRelated();
         $e2->delete();
         echo '  Successfully merged ' . $e2->name . "\n";
         if ($options['test_mode']) {
             die;
         }
     }
 }
 protected function createContextInstance($application = 'frontend', $enviroment = 'dev', $debug = true)
 {
     $configuration = ProjectConfiguration::getApplicationConfiguration($application, $enviroment, $debug);
     sfContext::createInstance($configuration);
     sfContext::switchTo($application);
     $this->context = sfContext::getInstance();
 }
 public function gdata_insert_row()
 {
     ProjectConfiguration::registerZend();
     Zend_Loader::loadClass('Zend_Gdata_AuthSub');
     Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
     Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
     Zend_Loader::loadClass('Zend_Gdata_Docs');
     $username = "******";
     $password = "******";
     //Chave do arquivo
     $key = "0Ak_oCZQf3sTidEJnZGQ4MHdhS0R1NUlSeG1ORkpnalE";
     //Carregando o serviço do arquivo
     $service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
     $client = Zend_Gdata_ClientLogin::getHttpClient($username, $password, $service);
     $spreadSheetService = new Zend_Gdata_Spreadsheets($client);
     //Pegando as planilhas do arquivo
     $query = new Zend_Gdata_Spreadsheets_DocumentQuery();
     $query->setSpreadsheetKey($key);
     $feed = $spreadSheetService->getWorksheetFeed($query);
     //Escolhendo a planilha correta
     foreach ($feed->entries as $entry) {
         if ($entry->getTitle() == 'Disponiveis') {
             $worksheetId = basename($entry->getId());
         }
     }
     //Configura variaveis da nova linha na planilha
     $assoc = $this->getAssociado();
     $matricula = $this->isTitular() ? $assoc->getMatricula() : $assoc->getTitular()->getMatricula();
     $dependenteId = $this->isDependente() ? $assoc->getId() : '0';
     //Monta array para o serviço do arquivo
     $rowData = array("data" => $this->getDateTimeObject('created_at')->format('Y-m-d'), "matricula" => $matricula, "nome" => $assoc->getNome(), "dependenteid" => $dependenteId, "encaminhaid" => $this->getId());
     //Insere na Planilha
     $insertedListEntry = $spreadSheetService->insertRow($rowData, $key, $worksheetId);
 }
Example #11
0
 /**
  * @see sfTask
  */
 protected function doRun(sfCommandManager $commandManager, $options)
 {
     $this->process($commandManager, $options);
     $this->checkProjectExists();
     $application = $commandManager->getArgumentSet()->hasArgument('application') ? $commandManager->getArgumentValue('application') : null;
     $env = $commandManager->getOptionSet()->hasOption('env') ? $commandManager->getOptionValue('env') : 'test';
     if (!is_null($application)) {
         $this->checkAppExists($application);
         require_once sfConfig::get('sf_config_dir') . '/ProjectConfiguration.class.php';
         $isDebug = $commandManager->getOptionSet()->hasOption('debug') ? $commandManager->getOptionValue('debug') : true;
         $this->configuration = ProjectConfiguration::getApplicationConfiguration($application, $env, $isDebug, null, $this->dispatcher);
     } else {
         if (file_exists(sfConfig::get('sf_config_dir') . '/ProjectConfiguration.class.php')) {
             require_once sfConfig::get('sf_config_dir') . '/ProjectConfiguration.class.php';
             $this->configuration = new ProjectConfiguration(null, $this->dispatcher);
         } else {
             $this->configuration = new sfProjectConfiguration(getcwd(), $this->dispatcher);
         }
     }
     $autoloader = sfSimpleAutoload::getInstance();
     foreach ($this->configuration->getModelDirs() as $dir) {
         $autoloader->addDirectory($dir);
     }
     if (!is_null($this->commandApplication) && !$this->commandApplication->withTrace()) {
         sfConfig::set('sf_logging_enabled', false);
     }
     return $this->execute($commandManager->getArgumentValues(), $commandManager->getOptionValues());
 }
Example #12
0
    protected function execute($arguments = array(), $options = array())
    {
        $configuration = ProjectConfiguration::getApplicationConfiguration($options['application'], $options['env'], true);
        $databaseManager = new sfDatabaseManager($this->configuration);
        $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
        $oBilling = new BillingClass();
        $oBilling->puserDailyPayment();
        $q = Doctrine_Query::create()->from('BalanceUser bu')->innerJoin('bu.User u')->where('bu.payable > 0')->andWhere('bu.was_paid = 0')->andWhere('u.active = 1')->andWhere('u.utype = "puser"')->groupBy('bu.id_user')->execute();
        $frontendRouting = new sfPatternRouting(new sfEventDispatcher());
        $config = new sfRoutingConfigHandler();
        $routes = $config->evaluate(array(sfConfig::get('sf_apps_dir') . '/frontend/config/routing.yml'));
        $frontendRouting->setRoutes($routes);
        foreach ($q as $rec) {
            if (!preg_match('/^R[0-9]{12}$/', $rec->getUser()->getAccountNumber())) {
                $email = $rec->getUser()->getEmail();
                $url = 'http://read2read.ru' . $frontendRouting->generate('profile_p_invoice', array(), true);
                $message = $this->getMailer()->compose(sfConfig::get('app_r2r_noreply_email'), $email, 'Read2Read - Напоминание о заполнении номера кошелька', <<<EOF
Вы зарегистрировались на сайте Read2Read.ru и на вашем счету имеется сумма положенная
к выплате в следующем платежном периоде. Для получения этих средств перейдите на сайт
Read2Read.ru и заполните номер кошелька. Ссылка для перехода: {$url}
EOF
);
                $this->getMailer()->send($message);
            }
        }
    }
 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();
     $models = array('Entity', 'Relationship', 'LsList');
     foreach ($models as $model) {
         $modelAlias = strtolower($model);
         $updateAlias = $model == 'LsList' ? 'ls_list' : $modelAlias;
         //get records to update
         $q = LsDoctrineQuery::create()->select('id')->from($model . ' ' . $modelAlias)->where($modelAlias . '.last_user_id IS NULL')->limit($options['limit'])->setHydrationMode(Doctrine::HYDRATE_NONE);
         if (!count($rows = $q->execute())) {
             //nothing to update, go to next model
             continue;
         }
         foreach ($rows as $row) {
             $id = $row[0];
             //get last_user_id
             $result = LsDoctrineQuery::create()->select('m.user_id')->from('Modification m')->where('m.object_model = ? AND m.object_id = ?', array($model, $id))->orderBy('m.id DESC')->setHydrationMode(Doctrine::HYDRATE_NONE)->fetchOne();
             if ($lastUserId = $result[0]) {
                 $query = 'UPDATE ' . $updateAlias . ' SET last_user_id=? WHERE id=?';
                 //use PDO for speed
                 $db->execute($query, array($lastUserId, $id));
             } else {
                 throw new Exception("Couldn't find last_user_id for " . $model . ' #' . $id);
             }
         }
         //only update records of one model at a time
         break;
     }
     //DONE
     LsCli::beep();
 }
Example #14
0
 protected function execute($arguments = array(), $options = array())
 {
     $configuration = ProjectConfiguration::getApplicationConfiguration($arguments['application'], $options['env'], true);
     $databaseManager = new sfDatabaseManager($configuration);
     $databaseManager->initialize($configuration);
     $fh = fopen($options['file_name'], 'a+');
     $start = count(file($options['file_name']));
     $this->db = Doctrine_Manager::connection();
     $this->list = Doctrine::getTable('LsList')->find($options['list_id']);
     $q = $this->list->getListEntitiesByRankQuery();
     $list_entities = $q->execute();
     function func($value)
     {
         return $value['name'];
     }
     for ($i = $start; $i < count($list_entities); $i++) {
         $entity = $list_entities[$i]->Entity;
         $people = $entity->getRelatedEntitiesQuery(array('Person'), array(1, 2, 3, 4, 6, 7, 8, 9, 10))->execute();
         $orgs = $entity->getRelatedEntitiesQuery(array('Org'), array(1, 2, 3, 4, 6, 7, 8, 9, 10))->execute();
         $donations = $entity->getRelatedEntitiesQuery(array('Person'), array(5))->execute();
         $people = implode("; ", array_map("func", $people->toArray()));
         $orgs = implode("; ", array_map("func", $orgs->toArray()));
         $donations = implode("; ", array_map("func", $donations->toArray()));
         $arr = array($entity, $people, $orgs, $donations);
         $str = implode("\t", $arr);
         fwrite($fh, $str . "\n");
     }
 }
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     $applicationConfig = sfProjectConfiguration::getApplicationConfiguration('frontend', 'prod', true);
     $context = sfContext::createInstance($applicationConfig);
     ProjectConfiguration::registerCron();
     $quiet = (bool) $options['quiet'];
     $passed = array();
     $assigned = array();
     if ($arguments['subreddit'] == '%') {
         if (!$quiet) {
             echo "Advancing EpisodeAssignments for all Subreddits...";
         }
         SubredditTable::getInstance()->advanceEpisodeAssignments();
     } else {
         $subreddit = SubredditTable::getInstance()->findOneByName($arguments['subreddit']);
         if ($subreddit) {
             if (!$quiet) {
                 echo "Advancing EpisodeAssignments for {$subreddit} Subreddit...";
             }
             $subreddit->advanceEpisodeAssignments();
         } else {
             throw new sfException('Cannot find Subreddit: ' . $arguments['subreddit']);
         }
     }
     if (!$quiet) {
         echo "\n";
     }
 }
 protected function init($arguments, $options)
 {
     $configuration = ProjectConfiguration::getApplicationConfiguration($arguments['application'], $options['env'], true);
     sfContext::createInstance($configuration, 'default');
     $this->db = LsDb::getDbConnection();
     $this->rawDb = LsDb::getDbConnection('raw');
     /*
     $databaseManager = new sfDatabaseManager($configuration);
     $databaseManager->initialize($configuration);
     $this->db = Doctrine_Manager::connection();
     $rawDb = $databaseManager->getDatabase('raw');
     $this->rawDb = Doctrine_Manager::connection($rawDb->getParameter('dsn'));  
     */
     $this->types = explode(',', $options['types']);
     $this->debugMode = $options['debug_mode'];
     $this->limit = $options['limit'];
     if ($options['expiration_date']) {
         $this->expirationDate = date('Y-m-d H:i:s', strtotime($options['expiration_date']));
     }
     $this->exactNameOverride = $options['exact_name_override'];
     //create insert statement
     $valStr = str_repeat('?, ', 5);
     $valStr = substr($valStr, 0, -2);
     $insertSql = 'INSERT INTO os_entity_category (entity_id, category_id, source, created_at, updated_at) VALUES (' . $valStr . ')';
     $this->insertStmt = $this->db->prepare($insertSql);
     //create lookup statement
     $selectSql = "SELECT category_name FROM os_category WHERE category_id = ?";
     $this->selectStmt = $this->db->prepare($selectSql);
 }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     require_once dirname(__FILE__) . '/../../../config/ProjectConfiguration.class.php';
     $configuration = ProjectConfiguration::getApplicationConfiguration('public', 'prod', true);
     sfContext::createInstance($configuration);
     $liveLang = $arguments['live_lang'];
     $langToDeploy = $arguments['lang_to_deploy'];
     $liveLangs = SfConfig::get('app_site_langs');
     $langsUnderDev = SfConfig::get('app_site_langsUnderDev');
     if (in_array($liveLang, $liveLangs) === false) {
         die("The live lang doesn't seem to be live!");
     }
     if (in_array($langToDeploy, $langsUnderDev) === false) {
         die("You can deploy only a language under development");
     }
     $c = new Criteria();
     $c->add(PcTranslationPeer::LANGUAGE_ID, $langToDeploy);
     $translationsToDeploy = PcTranslationPeer::doSelect($c);
     $i = 0;
     foreach ($translationsToDeploy as $translationToDeploy) {
         $this->log("Deploying the string " . $translationToDeploy->getStringId() . " from {$langToDeploy} to {$liveLang}");
         $liveTranslation = PcTranslationPeer::retrieveByPK($liveLang, $translationToDeploy->getStringId());
         $liveTranslation->setString($translationToDeploy->getString())->save();
         $translationToDeploy->delete();
         $i++;
     }
     $this->log("All done. {$i} strings deployed.");
 }
 public function setPlanning($startDate, $endDate, $title, $content)
 {
     // Parameters for ClientAuth authentication
     ProjectConfiguration::registerZend();
     Zend_Loader::loadClass('Zend_Gdata');
     Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
     Zend_Loader::loadClass('Zend_Gdata_Calendar');
     $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
     $user = sfConfig::get('app_gmail_user');
     $pass = sfConfig::get('app_gmail_pwd');
     // Create an authenticated HTTP client
     $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
     // Create an instance of the Calendar service
     $service = new Zend_Gdata_Calendar($client);
     // Create a new entry using the calendar service's magic factory method
     $event = $service->newEventEntry();
     // Populate the event with the desired information
     // Note that each attribute is crated as an instance of a matching class
     $event->title = $service->newTitle($title);
     $event->where = array($service->newWhere("Paris, France"));
     $event->content = $service->newContent($content);
     // Set the date using RFC 3339 format.
     $tzOffset = "+02";
     $when = $service->newWhen();
     //$when->startTime = "{$start_date}.000{$tzOffset}:00";
     //$when->endTime = "{$end_date}.000{$tzOffset}:00";
     $when->startTime = "{$startDate}:00.000{$tzOffset}:00";
     $when->endTime = "{$endDate}:00.000{$tzOffset}:00";
     $event->when = array($when);
     // Upload the event to the calendar server
     // A copy of the event as it is recorded on the server is returned
     $newEvent = $service->insertEvent($event);
 }
 /**
  * Executes the current task.
  *
  * @param array $arguments An array of arguments
  * @param array $options An array of options
  *
  * @return integer 0 if everything went fine, or an error code
  */
 protected 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();
     /** @var $parametres Récupération des paramètres à charger */
     $parametres = $conn->execute("\n            SELECT *\n            FROM ei_function_has_param, ei_fonction\n            WHERE param_type = 'OUT'\n            AND (param_id, ei_fonction.id) NOT IN (SELECT ei_param_function_id, ei_function_id FROM ei_param_block_function_mapping)\n            AND ei_function_has_param.function_ref = ei_fonction.function_ref\n            AND ei_function_has_param.function_id = ei_fonction.function_id\n        ");
     $this->log('Récupération des paramètres...OK');
     // Création de la requête permettant
     $this->log('Création de la requête d\'insertion...');
     $requeteToInsert = "INSERT INTO ei_param_block_function_mapping (ei_param_function_id, created_at, updated_at, ei_function_id) ";
     $requeteToInsert .= "VALUES(#{PARAM_ID}, now(), now(), #{FONCTION_ID});";
     $pile = array();
     foreach ($parametres->fetchAll() as $parametre) {
         // Remplacement PARAM ID.
         $tmpRequete = str_replace("#{PARAM_ID}", $parametre["param_id"], $requeteToInsert);
         // Remplacement FONCTION ID.
         $tmpRequete = str_replace("#{FONCTION_ID}", $parametre["id"], $tmpRequete);
         // Ajout dans la requête globale.
         $pile[] = $tmpRequete;
     }
     // Préparation de la requête.
     $this->log("Préparation de la requête...");
     $requete = implode(" ", $pile);
     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());
     }
 }
 /**
  * {@inheritdoc}
  */
 public function boot(ContainerInterface $container)
 {
     if (empty($this->options)) {
         throw new \RuntimeException('You must provide options for the Symfony 1.4 kernel.');
     }
     if ($this->isBooted()) {
         return;
     }
     if ($this->classLoader && !$this->classLoader->isAutoloaded()) {
         $this->classLoader->autoload();
     }
     $dispatcher = $container->get('event_dispatcher');
     $event = new LegacyKernelBootEvent($container->get('request'), $this->options);
     $dispatcher->dispatch(LegacyKernelEvents::BOOT, $event);
     $this->options = $event->getOptions();
     require_once $this->rootDir . '/config/ProjectConfiguration.class.php';
     $application = $this->options['application'];
     $environment = $this->options['environment'];
     $debug = $this->options['debug'];
     $this->configuration = \ProjectConfiguration::getApplicationConfiguration($application, $environment, $debug, $this->getRootDir());
     $this->configuration->loadHelpers(array('Url'));
     // Create a context to use with some helpers like Url.
     if (!\sfContext::hasInstance()) {
         $session = $container->get('session');
         if ($session->isStarted()) {
             $session->save();
         }
         ob_start();
         \sfContext::createInstance($this->configuration);
         ob_end_flush();
         $session->migrate();
     }
     $this->isBooted = true;
 }
 /**
  * Returns current sfApplicationConfiguration instance.
  * If no configuration does currently exist, a new one will be created.
  *
  * @return sfApplicationConfiguration
  */
 protected function getApplicationConfiguration()
 {
     if (is_null($this->applicationConfiguration)) {
         $this->applicationConfiguration = ProjectConfiguration::getApplicationConfiguration($this->getApplication(), $this->getEnvironment(), true);
     }
     return $this->applicationConfiguration;
 }
 /**
  * __construct
  *
  * @param string $options 
  * @return void
  */
 public function __construct(array $options = array())
 {
     $dispatcher = ProjectConfiguration::getActive()->getEventDispatcher();
     $dispatcher->connect('commentable.add_commentable_class', array($this, 'getCommentables'));
     $options['generatePath'] = sfConfig::get('sf_lib_dir') . '/model/doctrine/sfCommentsPlugin';
     $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $options);
 }
 public function save(Doctrine_Connection $conn = null)
 {
     $send_message = false;
     if ($this->isNew()) {
         if (!$this->hasVerifiedSender()) {
             $this->deleteWithException("Cannot create Message " . "because sfGuardUser " . $this->getSenderId() . " has not been validated yet.", 406);
         }
         if (!$this->hasVerifiedRecipient()) {
             $this->deleteWithException("Cannot create Message " . "because sfGuardUser " . $this->getSenderId() . " has not been validated yet.", 406);
         }
         $send_message = true;
     }
     /* If the obejct is not new or has passed all rules for saving, we pass
      * it on to the parent save function.
      */
     parent::save($conn);
     if ($send_message) {
         /* The following is for sending an email to the recipient to notify them that they've received a message.
          */
         $recipient = sfGuardUserTable::getInstance()->find($this->getRecipientId());
         if (!$recipient || !$recipient->getReceiveNotificationOfPrivateMessages()) {
             return parent::save($conn);
         }
         $parameters = array('user_id' => $this->getRecipientId(), 'message_id' => $this->getIncremented());
         $prefer_html = $recipient->getPreferHtml();
         $address = $recipient->getEmailAddress();
         $name = $recipient->getPreferredName() ? $recipient->getPreferredName() : $recipient->getFullName();
         $email = EmailTable::getInstance()->getFirstByEmailTypeAndLanguage('NewPrivateMessage', $recipient->getPreferredLanguage());
         $subject = $email->generateSubject($parameters);
         $body = $email->generateBodyText($parameters, $prefer_html);
         $from = sfConfig::get('app_email_address', ProjectConfiguration::getApplicationName() . ' <' . ProjectConfiguration::getApplicationEmailAddress() . '>');
         AppMail::sendMail($address, $from, $subject, $body, $prefer_html ? $body : null);
     }
 }
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     if ($config->get('SymfonyAuthenticator.application_name') == '') {
         die('You should define a SymfonyAuthenticator.application_name name in Moxiemanager config file.');
     }
     if ($config->get('SymfonyAuthenticator.application_env') == '') {
         die('You should define a SymfonyAuthenticator.application_env in Moxiemanager config file.');
     }
     if ($config->get('SymfonyAuthenticator.project_configuration_path') == '') {
         die('You should define a SymfonyAuthenticator.project_configuration_path in Moxiemanager config file.');
     }
     require_once $config->get('SymfonyAuthenticator.project_configuration_path');
     $configuration = ProjectConfiguration::getApplicationConfiguration($config->get('SymfonyAuthenticator.application_name'), $config->get('SymfonyAuthenticator.application_env'), false);
     $context = sfContext::createInstance($configuration);
     // Is the user authenticated ?
     if ($context->getUser()->isAuthenticated()) {
         // Do we need a special role to access to the moxiemanager ?
         if ($config->get('SymfonyAuthenticator.credential') != '') {
             if ($context->getUser()->hasCredential($config->get('SymfonyAuthenticator.credential'))) {
                 return true;
             } else {
                 return false;
             }
         }
         return true;
     }
     return false;
 }
Example #25
0
 /**
  * Returns the current application context.
  *
  * @param  bool $forceReload  true to force context reload, false otherwise
  *
  * @return sfContext
  */
 public function getContext($forceReload = false)
 {
     if (null === $this->context || $forceReload) {
         $isContextEmpty = null === $this->context;
         $context = $isContextEmpty ? sfContext::getInstance() : $this->context;
         // create configuration
         $currentConfiguration = $context->getConfiguration();
         $configuration = ProjectConfiguration::getApplicationConfiguration($currentConfiguration->getApplication(), $currentConfiguration->getEnvironment(), $currentConfiguration->isDebug());
         // connect listeners
         $configuration->getEventDispatcher()->connect('application.throw_exception', array($this, 'listenToException'));
         foreach ($this->listeners as $name => $listener) {
             $configuration->getEventDispatcher()->connect($name, $listener);
         }
         // create context
         $this->context = sfContext::createInstance($configuration);
         unset($currentConfiguration);
         if (!$isContextEmpty) {
             sfConfig::clear();
             sfConfig::add($this->rawConfiguration);
         } else {
             $this->rawConfiguration = sfConfig::getAll();
         }
     }
     return $this->context;
 }
 protected function execute($arguments = array(), $options = array())
 {
     $this->configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'prod', true);
     $this->context = sfContext::createInstance($this->configuration);
     $databaseManager = new sfDatabaseManager($this->configuration);
     $dbdsn = $databaseManager->getDatabase('propel')->getParameter('dsn');
     $dbusername = $databaseManager->getDatabase('propel')->getParameter('username');
     $dbpassword = $databaseManager->getDatabase('propel')->getParameter('password');
     $dbname = preg_replace('/^.*dbname=([^;=]+).*$/', '${1}', $dbdsn);
     ConfigurationHelper::load();
     $backup_method = ConfigurationHelper::getParameter('Backup', 'backup_method');
     $this->logSection('tempos', sprintf('Backup method: %s', $backup_method), 1024);
     if ($backup_method == 'ftp') {
         $backupname = 'tempos-backup.sql';
         $configname = ConfigurationHelper::getDefaultConfigurationFileName();
         $configpath = ConfigurationHelper::getDefaultConfigurationFilePath();
         copy($configpath, '/tmp/' . $configname);
         chdir('/tmp');
         system(sprintf('mysqldump --user=%s --password=%s %s > %s', escapeshellarg($dbusername), escapeshellarg($dbpassword), escapeshellarg($dbname), escapeshellarg($backupname)));
         $tmpfilename = 'tempos-backup-' . date('Y-m-d') . '.tar.gz';
         system(sprintf('tar zcf %s %s %s', escapeshellarg($tmpfilename), escapeshellarg($backupname), escapeshellarg($configname)));
         unlink($backupname);
         unlink($configname);
         try {
             FTPHelper::backupFile($tmpfilename);
         } catch (Exception $ex) {
             unlink($tmpfilename);
             throw $ex;
         }
         unlink($tmpfilename);
     }
 }
 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 setup($options, $parameters = array())
  {
    $this->projectDir = dirname(__FILE__).'/../fixtures';
    $this->cleanup();

    foreach (array('model', 'urlPrefix', 'moduleName', 'singularName', 'pluralName', 'projectDir') as $param)
    {
      if (isset($parameters[$param]))
      {
        $this->$param = $parameters[$param];
      }
    }

    chdir($this->projectDir);
    $task = new sfPropelGenerateModuleTask(new sfEventDispatcher(), new sfFormatter());
    $options[] = 'env=test';
    $options[] = 'singular='.$this->singularName;
    $options[] = 'plural='.$this->pluralName;
    $options[] = '--non-verbose-templates';
    $task->run(array('crud', $this->moduleName, $this->model), $options);

    require_once($this->projectDir.'/config/ProjectConfiguration.class.php');
    sfContext::createInstance(ProjectConfiguration::getApplicationConfiguration('crud', 'test', true, $this->projectDir));

    return $options;
  }
Example #29
0
function sw_combine_debug()
{
    if (ProjectConfiguration::getActive()->isDebug()) {
        $response = sfContext::getInstance()->getResponse();
        echo "<!-- DEBUG MODE - \nCombined files : \n" . var_export($response->getCombinedAssets(), 1) . "\n -->\n";
    }
}
 protected function execute($arguments = array(), $options = array())
 {
     $this->configuration = ProjectConfiguration::getApplicationConfiguration($options['app'], $options['env'], true);
     if (!sfConfig::get('app_sf_amazon_plugin_access_key', false)) {
         throw new sfException(sprintf('You have not set an amazon access key'));
     }
     if (!sfConfig::get('app_sf_amazon_plugin_secret_key', false)) {
         throw new sfException(sprintf('You have not set an amazon secret key'));
     }
     $s3 = new AmazonS3(sfConfig::get('app_sf_amazon_plugin_access_key'), sfConfig::get('app_sf_amazon_plugin_secret_key'));
     $this->s3_response = $s3->create_bucket($arguments['bucket'], $options['region'], $options['acl']);
     if ($this->s3_response->isOk()) {
         $this->log('Bucketed is being created...');
         /* Since AWS follows an "eventual consistency" model, sleep and poll
            until the bucket is available. */
         $exists = $s3->if_bucket_exists($arguments['bucket']);
         while (!$exists) {
             // Not yet? Sleep for 1 second, then check again
             sleep(1);
             $exists = $s3->if_bucket_exists($arguments['bucket']);
         }
         $this->logSection('Bucket+', sprintf('"%s" created successfully', $arguments['bucket']));
     } else {
         throw new sfException($this->s3_response->body->Message);
     }
 }