protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     $visiteurs_dir = sfConfig::get('sf_root_dir') . '/web/visiteur/';
     $interactifs_dir = sfConfig::get('sf_root_dir') . '/web/interactif';
     $finder = new sfFinder();
     $fileSystem = new sfFilesystem();
     foreach ($finder->in($visiteurs_dir) as $file) {
         //echo 'search in '. $file;
         if (is_file($file) && basename($file) != '.DS_Store') {
             $realpath = str_replace($visiteurs_dir, "", $file);
             $split = explode('/', $realpath);
             if (count($split) > 2) {
                 //print_r($split);
                 //exit;
                 $visiteur_id = $split[0];
                 $interactif_id = $split[1];
                 $filename = basename($file);
                 //  check if symlink exist
                 if (Doctrine::getTable('Interactif')->symlinkDocument($interactif_id, $visiteur_id, $filename, $file)) {
                     $this->logSection("INFO", "Symlink " . $interactifs_dir . '/' . $interactif_id . '/' . $visiteur_id . '/' . $filename);
                 }
             }
         }
     }
     $this->logSection("INFO", "END Symlink interactif directory");
 }
  protected function execute($arguments = array(), $options = array())
  {
    $databaseManager = new sfDatabaseManager($this->configuration);
    $this->conn = $databaseManager->getDatabase('doctrine')->getDoctrineConnection();

    $sql = 'SELECT id FROM member WHERE is_active != 0';
    $where = array();
    if ( $options['min'] && $options['max']  && $options['min'] <= $options['max'])
    {
        $sql .= ' AND id BETWEEN ? AND ?';
        $where = array(intval($options['min']),intval($options['max']));
    }
    $memberIds = $this->conn->fetchColumn($sql, $where);

    $this->setContents();
    foreach ($memberIds as $memberid)
    {
      $randomtime = $this->makeRandomTime($options['date'],$options['number']);
      for ($i=0; $i<$options['number']; ++$i)
      {
        $title=$this->makeRandomContents('title',$options['titlecount']);
        $body=$this->makeRandomContents('body',$options['bodycount']);
        $diary = new Diary();
        $diary->setMemberId($memberid);
        $diary->setTitle($title);
        $diary->setBody($body);
        $diary->setPublicFlag(1);
        $diary->setCreatedAt($randomtime[$i]);
        $diary->setUpdatedAt($randomtime[$i]);
        $diary->save();
        $diary->free();
        $this->logSection('posted a diary', sprintf('%s %s', $memberid, $randomtime[$i]));
      }
    }
  }
Exemplo n.º 3
0
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     $this->logSection('Create directory', "Visiteur");
     $q = Doctrine_Query::create()->from('Visiteur v');
     $visiteurs = $q->execute();
     foreach ($visiteurs as $visiteur) {
         $visiteur->createDataFolder();
     }
     $this->logSection('Create directory', "Interactif");
     $q = Doctrine_Query::create()->from('Interactif i');
     $interactifs = $q->execute();
     foreach ($interactifs as $interactif) {
         $interactif->createDataFolder();
     }
     $this->logSection('Create directory', "Exposition");
     $q = Doctrine_Query::create()->from('Exposition v');
     $expositions = $q->execute();
     foreach ($expositions as $exposition) {
         $exposition->createDataFolder();
     }
     $this->logSection('Create directory', "Medaille");
     $fileSystem = new sfFilesystem();
     $fileSystem->mkdirs(sfConfig::get('sf_web_dir') . "/medaille");
     $this->logSection('Create directory', "MedailleType");
     $fileSystem = new sfFilesystem();
     $fileSystem->mkdirs(sfConfig::get('sf_web_dir') . "/medaille_type");
 }
 protected function execute($arguments = array(), $options = array())
 {
     $app = $options['app'];
     $env = $options['env'];
     $this->bootstrapSymfony($app, $env, true);
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase('doctrine')->getConnection();
     $this->logSection('import', 'initializing...');
     $plugins = SymfonyPluginApi::getPlugins();
     $count = 0;
     foreach ($plugins as $plugin) {
         $new = Doctrine::getTable('SymfonyPlugin')->findOneByTitle($plugin['id']);
         // if plugin exists update info.  Otherwise, create it
         if ($new) {
             // Nothing Yet
         } elseif ($plugin['id']) {
             $new = new SymfonyPlugin();
             $new['title'] = (string) $plugin['id'];
             $new['description'] = (string) $plugin->description;
             $new['repository'] = (string) $plugin->scm;
             $new['image'] = (string) $plugin->image;
             $new['homepage'] = (string) $plugin->homepage;
             $new['ticketing'] = (string) $plugin->ticketing;
             $new->saveNoIndex();
             $this->logSection('import', "added '{$new->title}'");
             $count++;
         }
     }
     $this->logSection('import', "Running Lucene Cleanup");
     $this->runLuceneRebuild();
     $this->logSection('import', "Completed.  Added {$count} new plugins(s)");
 }
Exemplo n.º 5
0
 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();
     $table = Doctrine::getTable('sfGuardUser');
     $users = $table->createQuery('u')->innerJoin('u.Profile p')->execute();
     $first = true;
     foreach ($users as $user) {
         if (preg_match("/[^\\w]/", $user->username)) {
             $user->username = preg_replace("/[^\\w]/", "_", $user->username);
             while ($table->findOneByUsername($user->username)) {
                 $user->username .= rand(0, 9);
                 echo $user->username;
             }
             $user->save();
             $profile->save();
             if ($first) {
                 echo "The following usernames required change, contact them if they are legitimate users and\nlet them know their new username.\n";
                 echo "The report below shows the NEW username only.\n\n";
                 $first = false;
             }
             echo "Username: "******"\n";
         }
         $profile = $user->getProfile();
         if (preg_match("/[\\<\\>\\&\\|]/", $profile->fullname)) {
             // No need for a big announcement because we don't log in by our full names
             $profile->fullname = preg_replace("/[\\<\\>\\&\\|]/", "_", $profile->fullname);
             $profile->save();
         }
     }
 }
 public function setup()
 {
     $db = $this->databasemanager->getDatabase('doctrine');
     /* @var $db sfDoctrineDatabase */
     // Special Handling for postgre, since droping even when closing the connection, fails with
     // SQLSTATE[55006]: Object in use: 7 ERROR:  database "cs_doctrine_act_as_sortable_test" is being accessed by other users DETAIL:  There are 1 other session(s) using the database.
     if ($db->getDoctrineConnection() instanceof Doctrine_Connection_Pgsql) {
         try {
             $db->getDoctrineConnection()->createDatabase();
         } catch (Exception $e) {
         }
         $export = new Doctrine_Export_Pgsql($db->getDoctrineConnection());
         $import = new Doctrine_Import_Pgsql($db->getDoctrineConnection());
         $tablenames = array(SortableArticleTable::getInstance()->getTableName(), SortableArticleUniqueByTable::getInstance()->getTableName(), SortableArticleCategoryTable::getInstance()->getTableName());
         foreach ($tablenames as $tablename) {
             if ($import->tableExists($tablename)) {
                 $export->dropTable($tablename);
             }
         }
     } else {
         try {
             // ignore error if database does not yet exist (clean CI-env)
             $db->getDoctrineConnection()->dropDatabase();
         } catch (Exception $e) {
         }
         $db->getDoctrineConnection()->createDatabase();
     }
     // Using Doctrine instead of Doctrine_Core keeps it symfony 1.2 compatible, which uses
     Doctrine::loadModels(dirname(__FILE__) . '/../fixtures/project/lib/model/doctrine', Doctrine::MODEL_LOADING_CONSERVATIVE);
     Doctrine::createTablesFromArray(Doctrine::getLoadedModels());
     Doctrine::loadData(dirname(__FILE__) . '/../fixtures/project/data/fixtures/categories.yml');
 }
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     // add your code here
 }
 protected function execute($arguments = array(), $options = array())
 {
     if (!$this->safeToRun()) {
         print "Process already running!\n";
         die;
     }
     $timer = sfTimerManager::getTimer('execute');
     $databaseManager = new sfDatabaseManager($this->configuration);
     $databaseManager->initialize($this->configuration);
     //set up index
     $index = EntityTable::getLuceneIndex();
     //delete deleted entities
     $q = LsDoctrineQuery::create()->from('Entity e')->where('e.is_deleted = ?', true)->setHydrationMode(Doctrine::HYDRATE_ARRAY);
     foreach ($q->execute() as $entity) {
         if ($hits = $index->find('key:' . $entity['id'])) {
             if ($options['debug_mode']) {
                 printf("Deleting index for Entity %s\n", $entity['id']);
             }
             foreach ($hits as $hit) {
                 $index->delete($hit->id);
             }
         }
     }
     printf("Memory used: %s\n", LsNumber::makeBytesReadable(memory_get_usage()));
     printf("Index size: %s\n", $index->count());
     $timer->addTime();
     printf("Run time: %s\n", $timer->getElapsedTime());
     sfTimerManager::clearTimers();
 }
Exemplo n.º 9
0
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     /*
     if($options['include'] != "" && $options['exclude'] != "")
     {
       throw new Exception("Only one option is authorized");
     }
     */
     if ($options['include'] != "") {
         $to_replace = split(",", $options['include']);
         sfConfig::set('app_sync_tables', $to_replace);
     }
     if ($options['exclude'] != "") {
         $tables = sfConfig::get('app_sync_tables');
         $excludes = split(",", $options['exclude']);
         foreach ($excludes as $exclude) {
             if (($key = array_search($exclude, $tables)) !== false) {
                 unset($tables[$key]);
             }
         }
         sfConfig::set('app_sync_tables', $tables);
     }
     $sync = new ServerVipSync($this->configuration);
     $sync->startSync();
 }
 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()) {
        $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($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     $MODEL_CLASS_NAME = $arguments['classname'];
     if ('doctrine' === sfConfig::get('sf_orm')) {
         $table = Doctrine_Core::getTable($MODEL_CLASS_NAME);
         $fieldNames = $table->getColumnNames();
         $this->log(sprintf('%s', $MODEL_CLASS_NAME));
         $this->log(sprintf('  %s_data', $MODEL_CLASS_NAME));
         foreach ($fieldNames as $fieldName) {
             $this->log(sprintf('    %-20s %s', $fieldName . ':', $table->getTypeOf($fieldName)));
         }
     } else {
         $MODEL_CLASS_NAME_PEER = $MODEL_CLASS_NAME . 'Peer';
         $peerClass = new $MODEL_CLASS_NAME_PEER();
         $fieldNames = $peer_class->getFieldNames(BasePeer::TYPE_FIELDNAME);
         $this->log(sprintf('%s', $MODEL_CLASS_NAME));
         $this->log(sprintf('  %s_data', $MODEL_CLASS_NAME));
         foreach ($fieldNames as $fieldName) {
             $this->log(sprintf('    %-20s', $fieldName . ':'));
         }
     }
 }
  protected function execute($arguments = array(), $options = array())
  {
    $databaseManager = new sfDatabaseManager($this->configuration);
    $this->conn = $databaseManager->getDatabase('doctrine')->getDoctrineConnection();

    $sql = 'SELECT id FROM community';
    $where = array();
    if ( $options['cmin'] && $options['cmax']  && $options['cmin'] <= $options['cmax'])
    {
        $sql .= ' WHERE id BETWEEN ? AND ?';
        $where = array(intval($options['cmin']),intval($options['cmax']));
    }
    $commuIds = $this->conn->fetchColumn($sql, $where);
    foreach ($commuIds as $cid)
    {
      for ($i=0; $i < $options['number']; ++$i)
      {
        $ct = new CommunityTopic();
        $ct->setCommunity(Doctrine::getTable('community')->find($cid));
        $ct->setMemberId(self::fetchRandomMemberId($cid));
        $ct->setName('name');
        $ct->setBody('body');
        $ct->save();
        $ct->free();
        $this->logSection('created a community topic', sprintf("%s", $cid));
      }
    }
  }
Exemplo n.º 14
0
 /**
  * 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();
         }
     }
 }
 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 execute($arguments = array(), $options = array())
  {
    $databaseManager = new sfDatabaseManager($this->configuration);
    $this->conn = $databaseManager->getDatabase('doctrine')->getDoctrineConnection();

    $communityIds = $this->getCommunityIds();
    for ($i=0; $i < $options['communitynumber']; ++$i)
    {
      $communityId = $this->fetchRandomCommunityId($communityIds);
      $topicIds = $this->getTopicIds($communityId);
      $memberIds = $this->getMemberIds($communityId);
      for ($j=0; $j < $options['topicnumber']; ++$j)
      {
        for ($k=0; $k < $options['number']; ++$k)
        {
          $ctc = new CommunityTopicComment();
          $ctc->setMemberId(self::fetchRandomMemberId($memberIds));
          $ctc->setCommunityTopicId(self::fetchRandomTopicId($topicIds));
          $ctc->setBody('body');
          $ctc->save();
          $ctc->free();
          $this->logSection('created a community topic comment', sprintf("%s", $communityId));
        }
      }
    }
  }
Exemplo n.º 17
0
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     // load the scanner
     switch ($options['source']) {
         case 'amazon':
             require_once dirname(__FILE__) . '/scanners/artworkScanAmazon.php';
             break;
         case 'meta':
             require_once dirname(__FILE__) . '/scanners/artworkScanMeta.php';
             break;
         case 'folders':
             require_once dirname(__FILE__) . '/scanners/artworkScanFolders.php';
             break;
         case 'service':
             //reserved for future album art services: unused at the moment
             throw new Exception('Not Ready: This is a reserved block for future album art sources.');
             break;
     }
     // resync the database's has_art flag with the users art cache
     if ($options['resync']) {
         require_once dirname(__FILE__) . '/scanners/artworkScanResync.php';
     }
     echo "\r\n";
 }
 /**
  * @param   array   $arguments    (optional)
  * @param   array   $options      (optional)
  */
 public function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     afPortalStatePeer::deleteAllByIdXml($arguments['idxml']);
     return 0;
 }
 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();
 }
 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));
     }
 }
Exemplo n.º 21
0
 public static function getDatabaseParams($configuration, $dbname = false)
 {
     $dbManager = new sfDatabaseManager($configuration);
     $names = $dbManager->getNames();
     $db = $dbManager->getDatabase($dbname ? $dbname : $names[0]);
     if (!$db) {
         throw new sfException("No database connection called {$db} is defined");
     }
     $username = $db->getParameter('username');
     //root
     $dsn = $db->getParameter('dsn');
     //mysql:dbname=mydbtest;host=localhost because it's test config
     $password = $db->getParameter('password');
     //password
     if (!preg_match('/^mysql:(.*)\\s*$/', $dsn, $matches)) {
         throw new sfException("I don't understand the DSN {$dsn}, sorry");
     }
     $pairs = explode(';', $matches[1]);
     $data = array();
     foreach ($pairs as $pair) {
         list($key, $val) = explode('=', $pair);
         $data[$key] = $val;
     }
     $data['username'] = $username;
     $data['password'] = $password;
     return $data;
 }
 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 execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     // add your code here
     $n = $options['n'];
     $tags = $this->createTags($n);
     if (!empty($options['models'])) {
         $modelClasses = explode(',', $options['models']);
         foreach ($modelClasses as $class) {
             try {
                 $models = Doctrine::getTable($class)->createQuery()->execute();
                 foreach ($models as $model) {
                     $modelTags = array();
                     while (count($modelTags) < $options['tags-per-model']) {
                         $tag = $tags[rand(0, $n - 1)];
                         $modelTags[$tag] = $tag;
                     }
                     $modelTags = array_values($modelTags);
                     $model->addTag($modelTags);
                     $model->save();
                 }
             } catch (Exception $e) {
                 echo $e->getMessage() . "\n";
             }
         }
     }
 }
 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));
     }
 }
Exemplo n.º 25
0
  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'])->getConnection();

    $this->logSection('rdvz', "Retrieving users...") ;

    $ldap = new uapvLdap() ;
    $users = Doctrine::getTable('user')->retrieveLdapUsers() ;

    $this->logSection('rdvz', "Updating information...") ;

    foreach($users as $user)
    {
      $us = $ldap->searchOne(sfConfig::get('app_profile_var_translation_uid')."=".$user->getLdapId()) ;

      $user->setName($us[sfConfig::get('app_profile_var_translation_name')]) ;
      $user->setSurname($us[sfConfig::get('app_profile_var_translation_surname')]) ;
      $user->setMail($us[sfConfig::get('app_profile_var_translation_mail')]) ;
      $user->save();
    }

    $this->logSection('rdvz', "Done.") ;
  }
Exemplo n.º 26
0
 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;
 }
Exemplo n.º 27
0
 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();
 }
 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";
 }
Exemplo n.º 29
0
function run_propel_build_sql_diff($task, $args)
{
    if (!count($args)) {
        throw new Exception('You must provide the application.');
    }
    $app = $args[0];
    if (!is_dir(sfConfig::get('sf_app_dir') . DIRECTORY_SEPARATOR . $app)) {
        throw new Exception(sprintf('The app "%s" does not exist.', $app));
    }
    run_propel_build_sql($task, $args);
    pake_echo_action('propel-sql-diff', "building database patch");
    define('SF_ROOT_DIR', realpath(dirname(__FILE__) . '/../../../..'));
    define('SF_APP', $app);
    define('SF_ENVIRONMENT', isset($args[1]) ? $args[1] : 'dev');
    define('SF_DEBUG', 1);
    require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . SF_APP . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
    $databaseManager = new sfDatabaseManager();
    $databaseManager->initialize();
    $i = new dbInfo();
    $i->loadFromDb();
    $i2 = new dbInfo();
    $i2->loadAllFilesInDir(sfConfig::get('sf_data_dir') . '/sql');
    $diff = $i->getDiffWith($i2);
    $filename = sfConfig::get('sf_data_dir') . '/sql/diff.sql';
    if ($diff == '') {
        pake_echo_comment("no difference found");
    }
    pake_echo_action('propel-sql-diff', "writing file {$filename}");
    file_put_contents($filename, $diff);
}
 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();
     $this->createContextInstance();
     $c1 = new Criteria();
     $career_school_year = CareerSchoolYearPeer::retrieveBySchoolYear();
     $c1->add(StudentCareerSchoolYearPeer::CAREER_SCHOOL_YEAR_ID, $career_school_year[0]->getId());
     $c1->add(StudentCareerSchoolYearPeer::STATUS, StudentCareerSchoolYearStatus::LAST_YEAR_REPPROVED);
     $students_career_school_year = StudentCareerSchoolYearPeer::doSelectJoinCareerSchoolYear($c1);
     foreach ($students_career_school_year as $student_career_school_year) {
         $this->logSection('STUDENT CAREER SCHOOL YEAR ID', $student_career_school_year->getId());
         $previous_school_year = SchoolYearPeer::retrieveLastYearSchoolYear($student_career_school_year->getCareerSchoolYear()->getSchoolYear());
         if (is_null($previous_school_year)) {
             $this->logSection('action', 'continue');
             continue;
         }
         $c = new Criteria();
         $c->add(StudentCareerSchoolYearPeer::STUDENT_ID, $student_career_school_year->getStudent()->getId());
         $c->addJoin(StudentCareerSchoolYearPeer::CAREER_SCHOOL_YEAR_ID, CareerSchoolYearPeer::ID, Criteria::INNER_JOIN);
         $c->addJoin(CareerSchoolYearPeer::CAREER_ID, CareerPeer::ID, Criteria::INNER_JOIN);
         $c->add(CareerSchoolYearPeer::SCHOOL_YEAR_ID, $previous_school_year->getId());
         $c->add(StudentCareerSchoolYearPeer::STATUS, StudentCareerSchoolYearStatus::APPROVED);
         if (StudentCareerSchoolYearPeer::doCount($c)) {
             $this->logSection('action', 'fix');
             $student_career_school_year->setStatus(StudentCareerSchoolYearStatus::IN_COURSE);
             $student_career_school_year->save();
         }
     }
 }