Creates a new context instance.
public static createInstance ( sfApplicationConfiguration $configuration, string $name = null, string $class = __CLASS__ ) : sfContext | ||
$configuration | sfApplicationConfiguration | An sfApplicationConfiguration instance |
$name | string | A name for this context (application name by default) |
$class | string | The context class to use (sfContext by default) |
Résultat | sfContext | An sfContext instance |
/** * {@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; }
protected function execute($arguments = array(), $options = array()) { parent::execute($arguments, $options); sfContext::createInstance($this->createConfiguration('pc_frontend', 'prod'), 'pc_frontend'); $pcGadgets = Doctrine::getTable('Gadget')->retrieveGadgetsByTypesName('dailyNews'); $mobileGadgets = Doctrine::getTable('Gadget')->retrieveGadgetsByTypesName('mobileDailyNews'); $targetMembers = Doctrine::getTable('Member')->findAll(); foreach ($targetMembers as $member) { if (!$member->getConfig('daily_news')) { continue; } if (1 == $member->getConfig('daily_news') && !$this->isDailyNewsDay()) { continue; } $address = $member->getEmailAddress(); $gadgets = $pcGadgets['dailyNewsContents']; if (opToolkit::isMobileEmailAddress($address)) { $gadgets = $mobileGadgets['mobileDailyNewsContents']; } $filteredGadgets = array(); if ($gadgets) { foreach ($gadgets as $gadget) { if ($gadget->isEnabled()) { $filteredGadgets[] = array('component' => array('module' => $gadget->getComponentModule(), 'action' => $gadget->getComponentAction()), 'gadget' => $gadget, 'member' => $member); } } } $context = $this->getContextByEmailAddress($address); $params = array('member' => $member, 'gadgets' => $filteredGadgets, 'subject' => $context->getI18N()->__('デイリーニュース'), 'today' => time()); opMailSend::sendTemplateMail('dailyNews', $address, opConfig::get('admin_mail_address'), $params, $context); } }
/** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { sfContext::createInstance($this->configuration); $blast = Doctrine::getTable('Blast')->find(1); $response = Doctrine::getTable('BlastResponse')->find(1); BlastManager::createTextResponse($response); }
protected function execute($arguments = array(), $options = array()) { // Memory usage is a bit high here because we look at every page, and the Rackspace Cloud // environment has a very low default memory limit for their ersatz "cron jobs." // TODO: prioritize a low-memory solution for rebuild-search-index, which will be // necessary for large sites anyway ini_set('memory_limit', '256M'); // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection(); // Initialize the context, which loading use of helpers, notably url_for // First set config vars so that reasonable siteless-but-rooted URLs can be generated // TODO: think about ways to make this work for people who like frontend_dev.php etc., although // we're doing rather well with an index.php that suits each environment sfConfig::set('sf_no_script_name', true); $_SERVER['PHP_SELF'] = ''; $_SERVER['SCRIPT_NAME'] = ''; $context = sfContext::createInstance($this->configuration); if (isset($options['table'])) { $indexes = array($options['table']); } else { $indexes = sfConfig::get('app_aToolkit_indexes', array()); } $count = 0; foreach ($indexes as $index) { $table = Doctrine::getTable($index); if ($index === 'aPage') { aZendSearch::purgeLuceneIndex($table); // We're about to request updates of all page/culture combinations. Don't // add that to an existing workload which could result in a huge pileup of // repeat requests if someone starts interrupting this task and trying again, etc. $this->query('DELETE FROM a_lucene_update'); $pages = Doctrine::getTable('aPage')->createQuery('p')->innerJoin('p.Areas a')->execute(array(), Doctrine::HYDRATE_ARRAY); foreach ($pages as $page) { $cultures = array(); foreach ($page['Areas'] as $area) { $cultures[$area['culture']] = true; } $cultures = array_keys($cultures); foreach ($cultures as $culture) { $this->query('INSERT INTO a_lucene_update (page_id, culture) VALUES (:page_id, :culture)', array('page_id' => $page['id'], 'culture' => $culture)); } } while (true) { $result = $this->query('SELECT COUNT(id) AS total FROM a_lucene_update'); $count = $result[0]['total']; if ($count == 0) { break; } $this->logSection('toolkit', "{$count} pages remain to be indexed, starting another update pass..."); $this->update(); } } else { // We don't have a deferred update feature for other tables, // so we'll have to get them done in the memory available $table->rebuildLuceneIndex(); } $this->logSection('toolkit', sprintf('Index for "%s" rebuilt', $index)); } }
/** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { $data = array(); $modules = $this->findModules(); $target = sfConfig::get('sf_cache_dir') . '/' . $arguments['application'] . '/' . $arguments['env'] . '/config/configuration.php'; // remove existing optimization file if (file_exists($target)) { $this->getFilesystem()->remove($target); } // recreate configuration without the cache $this->setConfiguration($this->createConfiguration($this->configuration->getApplication(), $this->configuration->getEnvironment())); // initialize the context sfContext::createInstance($this->configuration); // force cache generation for generated modules foreach ($modules as $module) { $this->configuration->getConfigCache()->import('modules/' . $module . '/config/generator.yml', false, true); } $templates = $this->findTemplates($modules); $data['getTemplateDir'] = $this->optimizeGetTemplateDir($modules, $templates); $data['getControllerDirs'] = $this->optimizeGetControllerDirs($modules); $data['getPluginPaths'] = $this->configuration->getPluginPaths(); $data['loadHelpers'] = $this->optimizeLoadHelpers($modules); if (!file_exists($directory = dirname($target))) { $this->getFilesystem()->mkdirs($directory); } $this->logSection('file+', $target); file_put_contents($target, '<?php return ' . var_export($data, true) . ';'); }
protected function execute($arguments = array(), $options = array()) { $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection(); $context = sfContext::createInstance($this->configuration); sfProjectConfiguration::getActive()->loadHelpers('Partial', 'I18N', 'Url'); $serverUrl = $options['setenvironment'] == '' ? $serverUrl = $options['host'] : $serverUrl = $options['host'] . '/' . $options['setenvironment']; $workflows = WorkflowVersionTable::instance()->getWorkflowsToStart(time())->toArray(); foreach($workflows as $workflow) { $sender = WorkflowTemplateTable::instance()->getWorkflowTemplateById($workflow['workflowtemplate_id'])->toArray(); $userSettings = new UserMailSettings($sender[0]['sender_id']); $sendMail = new SendStartWorkflowEmail($userSettings, $context, $workflow, $sender, $serverUrl); $workflowTemplate = WorkflowTemplateTable::instance()->getWorkflowTemplateByVersionId($workflow['id']); WorkflowVersionTable::instance()->startWorkflowInFuture($workflow['id']); $sendToAllSlotsAtOnce = $workflowTemplate[0]->getMailinglistVersion()->toArray(); if($sendToAllSlotsAtOnce[0]['sendtoallslotsatonce'] == 1) { $calc = new CreateWorkflow($workflow['id']); $calc->setServerUrl($serverUrl); $calc->setContext($context); $calc->addAllSlots(); } else { $calc = new CreateWorkflow($workflow['id']); $calc->setServerUrl($serverUrl); $calc->setContext($context); $calc->addSingleSlot(); } } }
protected function execute($args = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection(); // So we can play with app.yml settings from the application $context = sfContext::createInstance($this->configuration); $admin = Doctrine::getTable('sfGuardUser')->findOneByUsername('admin'); for ($i = 0; $i < $options['amount']; $i++) { echo "Creating event " . ($i + 1) . " of " . $options['amount'] . "...\n"; $post = new aEvent(); $post->author_id = $admin->id; $post->status = 'published'; $post->start_date = aDate::mysql(strtotime($i + 1 . ' days')); $post->start_time = date('H:i:s', rand(0, time())); $post->end_date = aDate::mysql(strtotime($i + rand(1, 14) . ' days')); $post->end_time = date('H:i:s', rand(0, time())); $post->excerpt = ''; $post->location = "1168 E. Passyunk Avenue\nPhiladelphia PA 19147"; $post->published_at = aDate::mysql(strtotime('-' . ($i + 1) . ' days')); $title = implode(' ', $this->getWords(mt_rand(5, 10), $options)); $body = implode(' ', $this->getWords(mt_rand(20, 100), $options)); $post->setTitle($title); $post->save(); $slot = $post->Page->createSlot('aRichText'); $slot->value = $body; $slot->save(); $post->Page->newAreaVersion('blog-body', 'update', array('permid' => 1, 'slot' => $slot)); } }
/** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { sfContext::createInstance($this->configuration); $displayName = $this->ask("Enter a minyan display name (Darchei Noam Glenbrook)"); $identifier = $this->ask("Enter minyan identifier (dng)"); $email = $this->ask("Enter username for minyan admin"); $user = Doctrine::getTable('SfGuardUser')->findOneByUsername(trim(strtolower($email))); if (!$user) { throw new Exception("User with email {$email} does not exist"); } try { $con = Doctrine::getConnectionByTableName("SfGuardUser"); $con->beginTransaction(); $minyan = new Minyan(); $minyan->setName($displayName); $minyan->setIdentifier(Utils::formatPermalink($identifier)); $minyan->save(); $minyanUser = new MinyanUser(); $minyanUser->setIsAdmin(true); $minyanUser->setUserId($user->getId()); $minyanUser->setMinyanId($minyan->getId()); $minyanUser->save(); $this->logSection('mam', "Minyan {$identifier} created successfully!"); $con->commit(); } catch (Exception $e) { $con->rollback(); throw $e; } }
protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); $this->context = sfContext::createInstance($this->configuration); $this->context->getConfiguration()->loadHelpers(array('Parse', 'Text', 'Tag')); ini_set('memory_limit', '2048M'); Doctrine::getTable('Post')->createQuery()->update()->set('text_original', 'text')->where('text_original is NULL')->execute(); Doctrine::getTable('PostComment')->createQuery()->update()->set('comment_original', 'comment')->where('comment_original is NULL')->execute(); $offset = 0; do { $posts = Doctrine::getTable('Post')->createQuery()->limit(100)->offset($offset)->execute(); $this->ParsePosts($posts); $offset += 100; echo "Offset: " . $offset . "\n"; } while (count($posts)); $offset = 0; do { $comments = Doctrine::getTable('PostComment')->createQuery()->limit(100)->offset($offset)->execute(); $this->ParsetComments($comments); $offset += 100; echo "Comments Offset: " . $offset . "\n"; } while (count($comments)); }
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()) { sfContext::createInstance($this->configuration); sfContext::getInstance(); $this->logLevel = $options['verbose'] ? Resque_Worker::LOG_NORMAL : 0; $this->logLevel = $options['vverbose'] ? Resque_Worker::LOG_VERBOSE : $this->logLevel; $queues = explode(',', $arguments['queues']); if ($options['count'] == 1) { $worker = $this->createWorker($queues, $options); $this->logSection('worker', 'Starting worker ' . $worker); $worker->work($options['interval']); } else { if ($options['count'] > 1) { if (!function_exists('pcntl_fork')) { throw new Exception('PHP installation lakcs PCNTL. Recompile with `--enable-pcntl` configuration option.'); } for ($i = 0; $i < $options['count']; ++$i) { $pid = pcntl_fork(); if ($pid == -1) { $this->logBlock('Could not fork worker ' . $i, 'ERROR'); return; } else { if (!$pid) { $worker = $this->createWorker($queues, $options); $this->logSection('worker', 'Starting worker ' . $worker); $worker->work($options['interval']); break; } } } } } }
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); // Go to the Subreddit and obtain the past few keys. $reddit_location = $options['subreddit']; $reddit = new RedditObject($reddit_location); $quiet = (bool) $options['quiet']; if (!$quiet) { echo "Obtaining the most recent comments from {$reddit_location}..."; } $reddit->appendData(); $found_keys = count($reddit->getComments()); if (!$quiet) { echo "\nFound {$found_keys} keys. Updating keys in the database..."; } ValidationTable::getInstance()->storeNewKeys($reddit->getComments()); // Now that new keys are stored in the database we need to update all applicable users $users = sfGuardUserTable::getInstance()->getUsersToBeValidated(); $updated = sfGuardUserTable::getInstance()->validateUsers($users); if (!$quiet) { echo "\nSending emails..."; } foreach ($users as $user_id) { $sf_user = $context->getUser(); $sf_user->setApiUserId($user_id); $sf_user->sendMail('RedditValidationSucceeded'); } if (!$quiet) { echo "\n{$updated} users validated and email sent.\n"; } }
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; }
protected function execute($arguments = array(), $options = array()) { $context = sfContext::createInstance($this->configuration); // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); $table = PetitionTable::getInstance(); $con = $table->getConnection(); $silent = $options['silent']; $utc_hour = $options['utc-hour']; if ($utc_hour !== '') { if (gmdate('H') !== $utc_hour) { if (!$silent) { echo "exiting, it is not the right hour.\n"; } return; } } $petitions = $table->fetchScheduleNeed(); foreach ($petitions as $petition) { /* @var $petition Petition */ if (!$silent) { echo $petition->getId() . "\t" . $petition->getName() . "\n"; } // $petition->state(Doctrine_Record::STATE_DIRTY); // with cachetagging this does not help, we have to change something $kind = $petition->getKind(); $petition->setKind(0); $petition->setKind($kind); $petition->save(); } if (!$silent) { echo "done.\n"; } }
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 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; }
/** * 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()); } }
/** * 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(); $context = sfContext::createInstance($this->configuration); if (isset($options['table'])) { $indexes = array($options['table']); } else { $indexes = sfConfig::get('app_aToolkit_indexes', array()); } $count = 0; foreach ($indexes as $index) { $table = Doctrine::getTable($index); if ($options['verbose']) { echo "Optimizing {$index}\n"; } aZendSearch::optimizeLuceneIndex($table); } if ($options['verbose']) { echo "Success!\n"; } }
protected function execute($arguments = array(), $options = array()) { $context = sfContext::createInstance(sfProjectConfiguration::getApplicationConfiguration('app', $options['env'], true)); parent::execute($arguments, $options); // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); // add your code here $options_task_server_backup = array('location' => $arguments['location'], 'filepath' => $arguments['filepath']); if ($arguments['snapshot']) { $options_task_server_backup['snapshot'] = $arguments['snapshot']; } if ($arguments['newsnapshot']) { $options_task_server_backup['newsnapshot'] = $arguments['newsnapshot']; } if ($arguments['delete']) { $options_task_server_backup['deletesnapshot'] = $arguments['delete']; } if ($arguments['location']) { if ($arguments['do_not_generate_tar'] && $arguments['do_not_generate_tar'] != 'false') { $options_task_server_backup['do_not_generate_tar'] = true; } } $task_server_backup = new serverBackupTask($this->dispatcher, new sfFormatter()); return $task_server_backup->run(array('serverid' => $arguments['serverid']), $options_task_server_backup); }
protected function execute($arguments = array(), $options = array()) { $context = sfContext::createInstance(sfProjectConfiguration::getApplicationConfiguration('app', $options['env'], true)); // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); // add your code here $nid = $arguments['id']; $this->log("[INFO] node check id={$nid}"); if (!($etva_node = EtvaNodePeer::retrieveByPK($nid))) { $msg_i18n = $context->getI18N()->__(EtvaNodePeer::_ERR_NOTFOUND_ID_, array('%id%' => $nid)); $error = array('success' => false, 'agent' => sfConfig::get('config_acronym'), 'error' => $msg_i18n, 'info' => $msg_i18n); $this->log("[ERROR] " . $error['error']); return $error; } else { $etva_node_va = new EtvaNode_VA($etva_node); $response = $etva_node_va->checkState(); if (!$response['success']) { $this->log("[ERROR] " . $response['error']); } else { $this->log("[INFO] " . $response['response']); } return $response; } }
protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); // need a scriptname otherwise it uses the symfony file if ($arguments['env'] != 'prod') { $_SERVER['SCRIPT_NAME'] = '/' . $arguments['application'] . '_' . $arguments['env'] . '.php'; } else { $_SERVER['SCRIPT_NAME'] = '/index.php'; } sfContext::createInstance(sfProjectConfiguration::getApplicationConfiguration($arguments['application'], $arguments['env'], true)); $searchIndex = new zsSearchIndex($arguments['index']); //optimize to increase speed $searchIndex->optimize(); //loop thru all models specified in this index and update all entries foreach ($searchIndex->getModels() as $model => $config) { $this->logSection('update', 'model: ' . $model); foreach (Doctrine::getTable($model)->findAll() as $object) { $searchIndex->updateIndex($object); echo '.'; } echo "\n"; } //re-optimize index $searchIndex->optimize(); }
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); }
/** * 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; }
/** * @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."); }
protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $con = $databaseManager->getDatabase($options['connection'])->getConnection(); $context = sfContext::createInstance(sfProjectConfiguration::getApplicationConfiguration('app', 'dev', true)); if ($options['server'] !== null) { EtvaSettingPeer::updateSetting(EtvaSettingPeer::_SMTP_SERVER_, $options['server']); } if ($options['port'] !== null) { EtvaSettingPeer::updateSetting(EtvaSettingPeer::_SMTP_PORT_, $options['port']); } if ($options['security-type'] !== null) { EtvaSettingPeer::updateSetting(EtvaSettingPeer::_SMTP_SECURITY_, $options['security-type']); } if ($options['use-auth'] !== null) { EtvaSettingPeer::updateSetting(EtvaSettingPeer::_SMTP_USE_AUTH_, $options['use-auth']); } if ($options['username'] !== null) { EtvaSettingPeer::updateSetting(EtvaSettingPeer::_SMTP_USERNAME_, $options['username']); } if ($options['password'] !== null) { EtvaSettingPeer::updateSetting(EtvaSettingPeer::_SMTP_KEY_, $options['password']); } return; }
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); $one_day_users = sfGuardUserTable::getInstance()->getOneDayEmailReminders(); $one_week_users = sfGuardUserTable::getInstance()->getOneWeekEmailReminders(); $quiet = (bool) $options['quiet']; if (!$quiet) { echo "Sending one-day reminder emails to " . count($one_day_users) . " users..."; } foreach ($one_day_users as $user) { $sf_user = $context->getUser(); $sf_user->setApiUserId($user->getIncremented()); $sf_user->sendMail('RegisterOneDay'); } if (!$quiet) { echo "\nSending one-week reminder emails to " . count($one_week_users) . " users..."; } foreach ($one_week_users as $user) { $sf_user = $context->getUser(); $sf_user->setApiUserId($user->getIncremented()); $sf_user->sendMail('RegisterOneWeek'); } if (!$quiet) { echo "\n"; } }
/** * Main task function. * * @var $configuration sfProjectConfiguration * @see sfTask */ protected function execute($arguments = array(), $options = array()) { // Initialize the context sfContext::createInstance($this->configuration); // Record start time $this->startedAt = $this->getMicroTime(); // Get current config $this->config = $this->checkAndGetConfig($options['config']); switch ($options['type']) { case paProject::TYPE_SYMFONY: $this->project = new paSfProject($this->config, $options['config'], $this->getFilesystem()); break; case paProject::TYPE_CAKE_PHP: throw new RuntimeException('Are you OK ? :)'); break; case paProject::TYPE_PHP: case paProject::TYPE_JAVA: default: throw new RuntimeException(sprintf('The analysis of this type of project (%s) is not implemented yet; available: type=1 for a symfony project (This is the default option)', $options['type'])); break; } $this->project->analyse($arguments, $options); $this->endedAt = $this->getMicroTime(); $this->outputStats($arguments, $options); $returnCode = $this->getReturnCode($arguments, $options); return $returnCode; }
/** * To be able to create routes to Symfony 1 from Symfony 2, * you can create a Symfony 2 routing rule like this: * sf1: * path: /{module}/{action}/{params} * defaults: { action: index, params: '', _controller: "kernel.listener.symfony1_fallback:fallbackToSymfony1" } * requirements: * params: "[a-zA-Z0-9_\/]+" * @return Response */ public function fallbackToSymfony1() { $configuration = $this->kernel->getConfiguration(); $context = \sfContext::createInstance($configuration); try { $context->dispatch(); } catch (\sfStopException $e) { } $code = 0; $response = new Response(); if ($context->getResponse() instanceof \sfWebResponse) { $web_response = $context->getResponse(); /* @var $web_response \sfWebResponse */ $code = $web_response->getStatusCode(); // If we're trying to redirect to another location, set the statuscode and header in the symfony2 response // properly, because this response is overwriting the sf1 response if the content of the body is less than // 4kb large due to output buffering. if ($code === 302 || $code === 304) { $response->setStatusCode($code, Response::$statusTexts[$code]); $response->headers->set('Location', $web_response->getHttpHeader('Location')); } } // Symfony1 will usually send headers for us //Check if found response code is a known SF2 response code if (!isset(Response::$statusTexts[$code])) { // But for some reason it appears not to be, lets keep Symfony2 // busy with an empty response :p // For some ajax requests it doesn't, dunno why, but thats why the // 200 status code. $code = 200; } $response->headers->set('X-Status-Code', $code); return $response; }
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()) { require_once realpath(dirname(__FILE__) . '/../../../../lib/vendor/OAuth/OAuth.php'); new sfDatabaseManager($this->configuration); sfContext::createInstance($this->createConfiguration('pc_frontend', 'prod'), 'pc_frontend'); $consumerKey = isset($options['consumer-key']) && $options['consumer-key'] ? $options['consumer-key'] : opOpenSocialToolKit::getOAuthConsumerKey(); $consumer = new OAuthConsumer($consumerKey, null, null); $signatureMethod = new OAuthSignatureMethod_RSA_SHA1_opOpenSocialPlugin(); $httpOptions = opOpenSocialToolKit::getHttpOptions(); $queueGroups = Doctrine::getTable('ApplicationLifecycleEventQueue')->getQueueGroups(); $limitRequest = (int) $options['limit-request']; $limitRequestApp = (int) $options['limit-request-app']; $allRequest = 0; foreach ($queueGroups as $group) { $application = Doctrine::getTable('Application')->find($group[0]); $links = $application->getLinks(); $linkHash = array(); foreach ($links as $link) { if (isset($link['rel']) && isset($link['href'])) { $method = isset($link['method']) ? strtolower($link['method']) : ''; $method = 'post' !== $method ? 'get' : 'post'; $linkHash[$link['rel']] = array('href' => $link['href'], 'method' => $method); } } $queues = Doctrine::getTable('ApplicationLifecycleEventQueue')->getQueuesByApplicationId($group[0], $limitRequestApp); foreach ($queues as $queue) { if (!isset($linkHash[$queue->getName()])) { $queue->delete(); continue; } $href = $linkHash[$queue->getName()]['href']; $method = $linkHash[$queue->getName()]['method']; $oauthRequest = OAuthRequest::from_consumer_and_token($consumer, null, $method, $href, $queue->getParams()); $oauthRequest->sign_request($signatureMethod, $consumer, null); $client = new Zend_Http_Client(); if ('post' !== $method) { $method = 'get'; $client->setMethod(Zend_Http_Client::GET); $href .= '?' . $oauthRequest->to_postdata(); } else { $client->setMethod(Zend_Http_Client::POST); $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED); $client->setRawData($oauthRequest->to_postdata()); } $client->setConfig($httpOptions); $client->setUri($href); $client->setHeaders($oauthRequest->to_header()); $response = $client->request(); if ($response->isSuccessful()) { $queue->delete(); } $allRequest++; if ($limitRequest && $limitRequest <= $allRequest) { break 2; } } $application->free(true); $queues->free(true); } }