function setup()
 {
     global $CC_CONFIG;
     $con = Propel::getConnection();
     // Clear the files table
     $sql = "DELETE FROM " . $CC_CONFIG["filesTable"];
     $con->exec($sql);
     // Add a file
     $values = array("filepath" => dirname(__FILE__) . "/test10001.mp3");
     $this->storedFile = Application_Model_StoredFile::Insert($values, false);
     // Add a file
     $values = array("filepath" => dirname(__FILE__) . "/test10002.mp3");
     $this->storedFile2 = Application_Model_StoredFile::Insert($values, false);
     // Clear the schedule table
     $sql = "DELETE FROM " . $CC_CONFIG["scheduleTable"];
     $con->exec($sql);
     // Create a playlist
     $playlist = new Application_Model_Playlist();
     $playlist->create("Scheduler Unit Test");
     $result = $playlist->addAudioClip($this->storedFile->getId());
     $result = $playlist->addAudioClip($this->storedFile2->getId());
     $result = $playlist->addAudioClip($this->storedFile2->getId());
     // Schedule it
     $i = new Application_Model_ScheduleGroup();
     $this->groupIdCreated = $i->add('2010-11-11 01:30:23', null, $playlist->getId());
 }
Example #2
0
 public static function doUpdateAllModerations($selectCriteria, $values, $con = null)
 {
     if ($con === null) {
         $con = Propel::getConnection(self::DATABASE_NAME);
     }
     return BasePeer::doUpdate($selectCriteria, $values, $con);
 }
Example #3
0
 public static function getPopularTags($max = 30)
 {
     $connection = Propel::getConnection();
     $query = 'SELECT %s as query, COUNT(*) as count
           FROM %s
           INNER JOIN %s ON %s = %s
           INNER JOIN %s ON %s = %s
           WHERE %s = %s
           GROUP BY query
           ORDER BY count DESC';
     $query = sprintf($query, QueryPeer::QUERY, QueryPeer::TABLE_NAME, ReportQueryPeer::TABLE_NAME, QueryPeer::ID, ReportQueryPeer::QUERY_ID, ReportPeer::TABLE_NAME, ReportQueryPeer::REPORT_ID, ReportPeer::ID, ReportPeer::PUBLIC_RECORD, true);
     $statement = $connection->prepareStatement($query);
     $statement->setLimit($max);
     $resultset = $statement->executeQuery();
     $tags = array();
     $max_count = 0;
     while ($resultset->next()) {
         if (!$max_count) {
             $max_count = $resultset->getInt('count');
         }
         $queries[] = array('query' => $resultset->getString('query'), 'rank' => floor($resultset->getInt('count') / $max_count * 9 + 1), 'count' => $resultset->getInt('count'));
     }
     ksort($queries);
     return $queries;
 }
Example #4
0
 /**
  * Update the application delay registry
  * @param array $aData
  * @return string
  **/
 public function update($aData)
 {
     $oConnection = Propel::getConnection(AppDelayPeer::DATABASE_NAME);
     try {
         $oAppDelay = AppDelayPeer::retrieveByPK($aData['APP_DELAY_UID']);
         if (!is_null($oAppDelay)) {
             $oAppDelay->fromArray($aData, BasePeer::TYPE_FIELDNAME);
             if ($oAppDelay->validate()) {
                 $oConnection->begin();
                 $iResult = $oAppDelay->save();
                 $oConnection->commit();
                 return $iResult;
             } else {
                 $sMessage = '';
                 $aValidationFailures = $oAppDelay->getValidationFailures();
                 foreach ($aValidationFailures as $oValidationFailure) {
                     $sMessage .= $oValidationFailure->getMessage() . '<br />';
                 }
                 throw new Exception('The registry cannot be updated!<br />' . $sMessage);
             }
         } else {
             throw new Exception('This row doesn\'t exist!');
         }
     } catch (Exception $oError) {
         $oConnection->rollback();
         throw $oError;
     }
 }
 public function executeSidebar(sfWebRequest $request)
 {
     $route = sfContext::getInstance()->getRouting()->getCurrentRouteName();
     $this->route = $route;
     $id = $request->getParameter('catalogId');
     $stm = Propel::getConnection()->prepare('
         SELECT title,id FROM category WHERE parent_id=4
     ');
     $stm->execute();
     $menu = $stm->fetchAll(PDO::FETCH_OBJ);
     $this->menu = $menu;
     $stm = Propel::getConnection()->prepare('
         SELECT
             title,id
         FROM
             category_has_product
         INNER JOIN product ON product.id = category_has_product.product_id
         WHERE
             category_has_product.category_id = :id
     ');
     $stm->bindParam(':id', $id);
     $stm->execute();
     $product = $stm->fetchAll(PDO::FETCH_OBJ);
     $this->product = $product;
 }
Example #6
0
 public static function abortDbBatchJob(BatchJob $dbBatchJob, $force = false)
 {
     // No need to abort finished job
     if (in_array($dbBatchJob->getStatus(), BatchJobPeer::getClosedStatusList())) {
         if ($force) {
             $dbBatchJob->setExecutionStatus(BatchJobExecutionStatus::ABORTED);
             $dbBatchJob->save();
         }
         return $dbBatchJob;
     }
     $lockObject = $dbBatchJob->getBatchJobLock();
     if (is_null($lockObject)) {
         KalturaLog::err("Batch job [" . $dbBatchJob->getId() . "] doesn't have a lock object and can't be deleted. Status (" . $dbBatchJob->getStatus() . ")");
         return $dbBatchJob;
     }
     // Update status
     $con = Propel::getConnection();
     $update = new Criteria();
     $update->add(BatchJobLockPeer::STATUS, BatchJob::BATCHJOB_STATUS_ABORTED);
     $update->add(BatchJobLockPeer::VERSION, $lockObject->getVersion() + 1);
     $updateCondition = new Criteria();
     $updateCondition->add(BatchJobLockPeer::ID, $lockObject->getId(), Criteria::EQUAL);
     $updateCondition->add(BatchJobLockPeer::VERSION, $lockObject->getVersion(), Criteria::EQUAL);
     $updateCondition->add(BatchJobLockPeer::SCHEDULER_ID, null, Criteria::ISNULL);
     $affectedRows = BasePeer::doUpdate($updateCondition, $update, $con);
     if ($affectedRows) {
         $dbBatchJob->setExecutionStatus(BatchJobExecutionStatus::ABORTED);
         $dbBatchJob = self::updateBatchJob($dbBatchJob, BatchJob::BATCHJOB_STATUS_ABORTED);
     } else {
         $dbBatchJob->setExecutionStatus(BatchJobExecutionStatus::ABORTED);
         $dbBatchJob->save();
     }
     self::abortChildJobs($dbBatchJob);
     return $dbBatchJob;
 }
 /**
  * Inserts the menu links related to the inserted content,
  * into the w3sMenuElements table
  *   
  * @return bool
  * 
  */
 protected function setDefaultRelatedElements()
 {
     $bRollBack = false;
     $con = Propel::getConnection();
     $con = w3sPropelWorkaround::beginTransaction($con);
     for ($i = 1; $i < 4; $i++) {
         $newMenu = new W3sMenuElement();
         $contentValues = array("ContentId" => $this->content->getId(), "PageId" => 0, "Link" => w3sCommonFunctions::toI18n('This is a link'), "ExternalLink" => '', "Image" => '', "RolloverImage" => '', "Position" => $i);
         $newMenu->fromArray($contentValues);
         $result = $newMenu->save();
         if ($newMenu->isModified() && $result == 0) {
             $bRollBack = true;
             break;
         }
     }
     if (!$bRollBack) {
         // Everything was fine so W3StudioCMS commits to database
         $con->commit();
         $result = true;
     } else {
         // Something was wrong so W3StudioCMS aborts the operation and restores to previous status
         w3sPropelWorkaround::rollBack($con);
         $result = false;
     }
 }
Example #8
0
 public function executeSparkline()
 {
     /*
         $c = new Criteria();
       	$c->add(SfReviewTypeEntityPeer::ENTITY_ID, $this->politico->getId());
       	$c->add(SfReviewTypeEntityPeer::VALUE, 1);
       	$c->addAscendingOrderByColumn(SfReviewTypeEntityPeer::DATE);
       	$elements = SfReviewTypeEntityPeer::doSelect( $c );
     
       	$this->sparklineData = "";		
       	$spi = 0;
     foreach ($elements as $element) {
     	$this->sparklineData .= ($spi++>0?",":"").$element->getSum();
     }
     */
     $query = "select entity_id, month(date) as month, max(sum) as sum from sf_review_type_entity where value = 1 and entity_id = ? group by entity_id, month(date) order by month";
     $connection = Propel::getConnection();
     $statement = $connection->prepare($query);
     $statement->bindValue(1, $this->partido->getId());
     $statement->execute();
     $data = $statement->fetchAll(PDO::FETCH_OBJ);
     $this->sparklineData = "0, 0";
     $last = 0;
     foreach ($data as $element) {
         $this->sparklineData .= ", " . ($element->sum - $last);
         $last = $element->sum;
     }
     // select entity_id, month(date), value, sum from sf_review_type_entity where value = 1 group by entity_id, month(date)
 }
 public static function getPopularValidLanguages($max = 10)
 {
     $connection = Propel::getConnection();
     $languages = array_keys(sfConfig::get('app_languages'));
     foreach ($languages as $i => $language) {
         $languages[$i] = "'{$languages[$i]}'";
     }
     $query = 'SELECT %s as language, COUNT(*) as count
           FROM %s
           INNER JOIN %s ON %s = %s
           WHERE %s = false AND %s IN (%s)
           GROUP BY language
           ORDER BY count DESC';
     $query = sprintf($query, SnippetLanguagePeer::NAME, SnippetLanguagePeer::TABLE_NAME, SnippetPeer::TABLE_NAME, SnippetLanguagePeer::SNIPPET_ID, SnippetPeer::ID, SnippetPeer::DRAFT, SnippetLanguagePeer::NAME, implode(', ', $languages));
     $statement = $connection->prepareStatement($query);
     if ($max) {
         $statement->setLimit($max);
     }
     $resultset = $statement->executeQuery();
     $languages = array();
     $max_count = 0;
     while ($resultset->next()) {
         if (!$max_count) {
             $max_count = $resultset->getInt('count');
         }
         $languages[] = array('language' => $resultset->getString('language'), 'rank' => floor($resultset->getInt('count') / $max_count * 9 + 1), 'count' => $resultset->getInt('count'));
     }
     ksort($languages);
     return $languages;
 }
 /**
  * @see Command
  *
  * @throws \InvalidArgumentException When the target directory does not exist
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->writeSection($output, '[Propel] You are running the command: propel:database:drop');
     if ($input->getOption('force')) {
         if ('prod' === $this->getApplication()->getKernel()->getEnvironment()) {
             $this->writeSection($output, 'WARNING: you are about to drop a database in production !', 'bg=red;fg=white');
             if (false === $this->askConfirmation($output, 'Are you sure ? (y/n) ', false)) {
                 $output->writeln('Aborted, nice decision !');
                 return -2;
             }
         }
         list($name, $config) = $this->getConnection($input, $output);
         $dbName = $this->parseDbName($config['connection']['dsn']);
         $query = 'DROP DATABASE ' . $dbName . ';';
         try {
             $connection = \Propel::getConnection($name);
             $statement = $connection->prepare($query);
             $statement->execute();
             $output->writeln(sprintf('<info>Database <comment>%s</comment> has been dropped.</info>', $dbName));
         } catch (\Exception $e) {
             $this->writeSection($output, array('[Propel] Exception catched', '', $e->getMessage()), 'fg=white;bg=red');
         }
     } else {
         $output->writeln('<error>You have to use the "--force" option to drop the database.</error>');
     }
 }
    /**
     * Returns objects of the same class and with similar ratings as the current rateable object.
     * 
     * This implementation is based on the 
     * OpenSlopeOne project by Chaoqun Fu, http://code.google.com/p/openslopeone/.
     *
     * @param BaseObject $object The rateable object for which to return other recommended object
     * @param int $limit The number of recommendation objects which should be returned. Use NULL for returning all recommended objects
     * @return array of sfRecommendationObject objects which wrap the recommended objects
     */
    public function getRecommendations(BaseObject $object, $limit = NULL)
    {
        $parser = new sfPropelSlopeOneSqlParser();
        $slopeQuery = 'SELECT 	item2_id AS id,
    												SUM(rating/times) AS rating
                    FROM sf_slope_one 
                    WHERE item1_id = :item_id AND 
													item1_model = :item_model AND
                          item1_model = item2_model
                    GROUP BY item2_id
                    ORDER BY rating DESC';
        $slopeQuery .= isset($limit) ? ' LIMIT ' . $limit : '';
        $connection = Propel::getConnection();
        $statement = $connection->prepare($parser->parse($slopeQuery));
        $statement->execute(array('item_id' => $object->getId(), 'item_model' => get_class($object)));
        $ratings = array();
        while ($result = $statement->fetch()) {
            $ratings[$result['id']] = $result['rating'];
        }
        $objects = call_user_func(array(get_class($object->getPeer()), 'retrieveByPKs'), array_keys($ratings));
        foreach ($objects as &$object) {
            $object = new sfSlopeOneRecommendation($object, $ratings[$object->getId()]);
        }
        return $objects;
    }
Example #12
0
 public function update($aData)
 {
     $con = Propel::getConnection(AppThreadPeer::DATABASE_NAME);
     try {
         $con->begin();
         $oApp = AppThreadPeer::retrieveByPK($aData['APP_UID'], $aData['APP_THREAD_INDEX']);
         if (is_object($oApp) && get_class($oApp) == 'AppThread') {
             $oApp->fromArray($aData, BasePeer::TYPE_FIELDNAME);
             if ($oApp->validate()) {
                 $res = $oApp->save();
                 $con->commit();
                 return $res;
             } else {
                 $msg = '';
                 foreach ($this->getValidationFailures() as $objValidationFailure) {
                     $msg .= $objValidationFailure->getMessage() . "<br/>";
                 }
                 throw new PropelException('The AppThread row cannot be created!', new PropelException($msg));
             }
         } else {
             $con->rollback();
             throw new Exception("This AppThread row doesn't exist!");
         }
     } catch (Exception $oError) {
         throw $oError;
     }
 }
Example #13
0
 public static function prepareAndExecute($sql, array $paramValueMap, $type = 'all', $fetchType = PDO::FETCH_ASSOC)
 {
     $con = Propel::getConnection();
     $stmt = $con->prepare($sql);
     foreach ($paramValueMap as $param => $v) {
         $stmt->bindValue($param, $v);
     }
     $rows = array();
     if ($stmt->execute()) {
         if ($type == 'single') {
             $rows = $stmt->fetch($fetchType);
         } else {
             if ($type == 'column') {
                 $rows = $stmt->fetchColumn();
             } else {
                 if ($type == 'all') {
                     $rows = $stmt->fetchAll($fetchType);
                 } else {
                     if ($type == 'execute') {
                         $rows = null;
                     } else {
                         $msg = "bad type passed: type({$type})";
                         throw new Exception("Error: {$msg}");
                     }
                 }
             }
         }
     } else {
         $msg = implode(',', $stmt->errorInfo());
         throw new Exception("Error: {$msg}");
     }
     return $rows;
 }
Example #14
0
 private function runQuery(sfWebRequest $request, $databaseName)
 {
     try {
         $e = null;
         $this->getResponse()->setContentType('text/plain');
         $query = $this->getRequestParameter('query');
         if (strlen($query) < 10) {
             // consider the query as bogus
             $e = "The Query seems to be too short. Try something like ?query=select * from smint_user.";
             $result = "";
             return $this->renderPartial('sqlquery/viewResult', array('result' => $result, 'query' => $query, 'exception' => $e));
         } else {
             // open database connection based on filedescpeer settings
             $con = Propel::getConnection($databaseName, Propel::CONNECTION_READ);
             // prepare statement
             $stmt = $con->prepare($query);
             $stmt->execute();
             // fetch the results
             $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
             return $this->renderPartial('sqlquery/viewResult', array('result' => $result, 'query' => $query, 'exception' => $e));
         }
     } catch (Exception $e) {
         $result = null;
         return $this->renderPartial('sqlquery/viewResult', array('result' => $result, 'query' => $query, 'exception' => $e));
     }
 }
Example #15
0
 public static function execute()
 {
     //Check if this is the version to apply the patch
     $count = 0;
     $task = new Task();
     if (patch::$isPathchable && method_exists($task, 'getTasGroupVariable')) {
         $con = Propel::getConnection("workflow");
         $stmt = $con->prepareStatement("select TAS_UID from TASK where TAS_ASSIGN_TYPE = 'SELF_SERVICE';");
         $recordSet = $stmt->executeQuery();
         $recordSet->next();
         $aRow = $recordSet->getRow();
         while ($aRow) {
             $tasUid = $aRow['TAS_UID'];
             $conUser = Propel::getConnection("workflow");
             $stmtUser = $conUser->prepareStatement("select * from TASK_USER where TAS_UID = '" . $tasUid . "';");
             $recordSetTaskUser = $stmtUser->executeQuery();
             if ($recordSetTaskUser->next()) {
                 echo "Patching uid: " . $tasUid . "\n";
                 //Set the values if they match the pattern
                 $conChange = Propel::getConnection("workflow");
                 $stmtChange = $conChange->prepareStatement("update TASK set TAS_GROUP_VARIABLE = '' where TAS_UID = '" . $tasUid . "';");
                 $recordResult = $stmtChange->executeQuery();
                 $count++;
             }
             $recordSet->next();
             $aRow = $recordSet->getRow();
         }
     }
     echo $count . " records where patched to use SELF_SERVICE feature.\n";
 }
 public function save($con = null)
 {
     if (!$this->isValid()) {
         throw $this->getErrorSchema();
     }
     if (is_null($con)) {
         $con = Propel::getConnection(CareerStudentPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
     }
     try {
         $con->beginTransaction();
         $values = $this->getValues();
         $career = CareerPeer::retrieveByPK($values["career_id"]);
         $orientation = OrientationPeer::retrieveByPK($values["orientation_id"]);
         $sub_orientation = SubOrientationPeer::retrieveByPK($values["sub_orientation_id"]);
         $start_year = $values["start_year"];
         unset($values["career_id"]);
         unset($values["orientation_id"]);
         unset($values["sub_orientation_id"]);
         unset($values["start_year"]);
         foreach ($values as $student_id) {
             $student = StudentPeer::retrieveByPk($student_id, $con);
             if (!$student->isRegisteredToCareer($career, $con)) {
                 $student->registerToCareer($career, $orientation, $sub_orientation, $start_year, $con);
             }
         }
         $con->commit();
     } catch (Exception $e) {
         $con->rollBack();
         throw $e;
     }
 }
Example #17
0
 public function executeMenu()
 {
     $this->setLayout(false);
     $con = Propel::getConnection();
     $year = date("Y");
     $years = array();
     $sql = "SELECT DISTINCT MONTH(start_date) AS month FROM m_news WHERE start_date LIKE '" . $year . "%'";
     $stmt = $con->createStatement();
     $rs = $stmt->executeQuery($sql);
     while ($rs->next()) {
         $months[] = $rs->get("month");
     }
     $con = Propel::getConnection();
     $year = date("Y");
     $sql = "SELECT DISTINCT YEAR(start_date) AS year FROM m_news";
     $stmt = $con->createStatement();
     $rs = $stmt->executeQuery($sql);
     while ($rs->next()) {
         $years[$rs->get("year")] = $rs->get("year");
     }
     unset($years[$year]);
     if (!empty($years)) {
         $this->pastYears = $years;
     }
     $this->monthsArr = array(1 => "january", 2 => "february", 3 => "march", 4 => "april", 5 => "may", 6 => "june", 7 => "july", 8 => "august", 9 => "september", 10 => "october", 11 => "november", 12 => "december");
     //UtilsHelper::Date()
     $this->months = $months;
     $this->getRequestParameter("month") ? $this->currentMonth = $this->getRequestParameter("month") : ($this->currentMonth = date("n"));
     $this->currentYear = $year;
 }
Example #18
0
 public static function doSelectByRegPeriod(Criteria $c = null, $rpi = null)
 {
     $tsi = null;
     if ($rpi == null) {
         $tsi = sfContext::getInstance()->getRequest()->getParameter('id');
     }
     if ($rpi == null && $tsi == null) {
         return array();
     }
     $ids = '';
     if ($rpi != null) {
         $c = new Criteria();
         $c->addJoin(RegPeriodPeer::CURRICULUM_ID, CurriculumPeer::ID);
         $c->addJoin(CurriculumPeer::DEPARTMENT_ID, DepartmentPeer::ID);
         $c->add(RegPeriodPeer::ID, $rpi);
         $dept = DepartmentPeer::doSelectOne($c);
         $ids = $dept->getIdRecurs();
     }
     if ($tsi != null) {
         $c = new Criteria();
         $c->addJoin(RegPeriodPeer::CURRICULUM_ID, CurriculumPeer::ID);
         $c->addJoin(CurriculumPeer::DEPARTMENT_ID, DepartmentPeer::ID);
         $c->addJoin(TestSchedulePeer::REG_TEST_PERIOD_ID, RegTestPeriodPeer::ID);
         $c->add(TestSchedulePeer::ID, $tsi);
         $dept = DepartmentPeer::doSelectOne($c);
         $ids = $dept->getIdRecurs();
     }
     $sql = "select * from test_subject where department_id in ({$ids})";
     $connection = Propel::getConnection();
     $statement = $connection->createStatement();
     $result = $statement->executeQuery($sql, ResultSet::FETCHMODE_NUM);
     $objs = TestSubjectPeer::populateObjects($result);
     return $objs;
 }
 /**
  * Copies the menu links for the sourceContent to the targetContent
  *  
  * @parameter  int The id of the source content
  * @parameter  int The id of the target content
  * 
  * @return     bool false - The save operation has failed
  *                  true  - The save operation has correctly done 
  */
 public static function copyRelatedElements($sourceContent, $targetContent)
 {
     $bRollBack = false;
     $con = Propel::getConnection();
     $con = w3sPropelWorkaround::beginTransaction($con);
     // Deletes all the target menus
     $targetMenus = W3sMenuElementPeer::getContentMenu($targetContent);
     foreach ($targetMenus as $targetMenu) {
         $targetMenu->delete();
     }
     // Retrieves the menu rows related to source content
     $sourceMenus = DbFinder::from('W3sMenuElement')->where('contentId', $sourceContent)->orderBy('position')->find();
     foreach ($sourceMenus as $sourceMenu) {
         $oTargetMenu = new W3sMenuElement();
         $contentValues = array("ContentId" => $targetContent, "PageId" => $sourceMenu->getPageId(), "Link" => $sourceMenu->getLink(), "ExternalLink" => $sourceMenu->getExternalLink(), "Image" => $sourceMenu->getImage(), "RolloverImage" => $sourceMenu->getRolloverImage(), "Position" => $sourceMenu->getPosition());
         $oTargetMenu->fromArray($contentValues);
         // Saves
         $result = $oTargetMenu->save();
         if ($oTargetMenu->isModified() && $result == 0) {
             $bRollBack = true;
             break;
         }
     }
     if (!$bRollBack) {
         // Everything was fine so W3StudioCMS commits to database
         $con->commit();
         $result = true;
     } else {
         // Something was wrong so W3StudioCMS aborts the operation and restores to previous status
         w3sPropelWorkaround::rollBack($con);
         $result = false;
     }
     return $result;
 }
 /**
  * legge gli itinera interessanti di un singolo emendamento
  * interessanti sono quelli cui vengono sassegnati dei punti
  *
  * @param string $atto_id 
  * @param string $data 
  * @return void
  * @author Guglielmo Celata
  */
 public function getItineraEmendamentoDataRS($emendamento_id, $data)
 {
     $con = Propel::getConnection(self::DATABASE_NAME);
     $sql = sprintf("select data, em_iter_id from opp_emendamento_has_iter where emendamento_id=%d and data < '%s' and em_iter_id in (1, 2) group by emendamento_id, em_iter_id;", $emendamento_id, $data);
     $stm = $con->createStatement();
     return $stm->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
 }
 public function save($con = null)
 {
     $con = Propel::getConnection();
     try {
         $con->begin();
         $ret = parent::save($con);
         // update vocabulary_has_user table
         $userId = sfContext::getInstance()->getUser()->getSubscriberId();
         $vocabularyId = $this->getId();
         $mode = sfContext::getInstance()->getRequest()->getParameter('action');
         if ($userId && $vocabularyId) {
             //see if there's already an entry in the table and if not, add it
             $criteria = new Criteria();
             $criteria->add(VocabularyHasUserPeer::USER_ID, $userId);
             $VocabularyHasUsersColl = $this->getVocabularyHasUsers($criteria, $con);
             if (!count($VocabularyHasUsersColl)) {
                 $vocabularyUser = new VocabularyHasUser();
                 $vocabularyUser->setVocabularyId($vocabularyId);
                 $vocabularyUser->setUserId($userId);
                 $vocabularyUser->setIsRegistrarFor(true);
                 $vocabularyUser->setIsAdminFor(true);
                 $vocabularyUser->setIsMaintainerFor(true);
                 $vocabularyUser->save($con);
             }
         }
         $con->commit();
         return $ret;
     } catch (Exception $e) {
         $con->rollback();
         throw $e;
     }
 }
 public function execute($request)
 {
     $request->setRequestFormat('xml');
     $this->date = gmdate('Y-m-d\\TH:i:s\\Z');
     $this->title = sfconfig::get('app_siteTitle');
     $this->description = sfconfig::get('app_siteDescription');
     $this->protocolVersion = '2.0';
     list($this->earliestDatestamp) = Propel::getConnection()->query('SELECT MIN(' . QubitObject::UPDATED_AT . ') FROM ' . QubitObject::TABLE_NAME)->fetch();
     $this->granularity = 'YYYY-MM-DDThh:mm:ssZ';
     $this->deletedRecord = 'no';
     $this->compression = 'gzip';
     $this->path = url_for('oai/oaiAction');
     $this->attributes = $this->request->getGetParameters();
     $this->attributesKeys = array_keys($this->attributes);
     $this->requestAttributes = '';
     foreach ($this->attributesKeys as $key) {
         $this->requestAttributes .= ' ' . $key . '="' . $this->attributes[$key] . '"';
     }
     $criteria = new Criteria();
     $criteria->add(QubitAclUserGroup::GROUP_ID, QubitAclGroup::ADMINISTRATOR_ID);
     $criteria->addJoin(QubitAclUserGroup::USER_ID, QubitUser::ID);
     $users = QubitUser::get($criteria);
     $this->adminEmail = array();
     foreach ($users as $user) {
         $this->adminEmail[] = $user->getEmail() . "\n";
     }
 }
Example #23
0
 /**
  * update the current dataset with new values from the database
  *  if posible only with values since our lastUpdated moment
  */
 public function updateDataset()
 {
     if ($this->updated) {
         return;
     }
     $limit = 20000;
     $end = null;
     $start = $this->lastUpdated;
     $con = \Propel::getConnection();
     $table = $this->type == self::TYPE_SELL_LISTING ? 'sell_listing' : 'buy_listing';
     $and = "";
     // only retrieve new ticks since last update
     if ($start) {
         $and = " AND listing_datetime > '{$start->format('Y-m-d H:i:s')}'";
     }
     $stmt = $con->prepare("\n                SELECT\n                listing_datetime AS listingDatetime,\n                MIN(unit_price) AS min_unit_price\n                FROM {$table}\n                WHERE item_id = {$this->itemId}\n                {$and}\n                GROUP BY listing_datetime\n                ORDER BY listing_datetime ASC\n                LIMIT {$limit}");
     $stmt->execute();
     $listings = $stmt->fetchAll(\PDO::FETCH_ASSOC);
     foreach ($listings as $listing) {
         $date = new DateTime("{$listing['listingDatetime']}");
         $rate = intval($listing['min_unit_price']);
         $end = $date;
         $this->processTick($date, $rate);
     }
     if (!($this->uptodate = count($listings) != $limit)) {
         $app = Application::getInstance();
         $app['no_cache'] = true;
     }
     // update for next time
     $this->updated = true;
     if ($end) {
         $this->lastUpdated = $end;
     }
 }
Example #24
0
 public function delete(PropelPDO $con = null)
 {
     if ($con === null) {
         $con = Propel::getConnection(sfGuardGroupPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
     }
     if ($this->isDefaultGroup()) {
         throw new sfException('Cannot remove default group (ID ' . $this->id . ')!');
         return false;
     }
     /*
      * get default group
      *
      */
     $default_group = sfGuardGroupPeer::getDefaultGroup();
     //get default group
     /*
      * check if servers has this group
      * If servers found remove reference to group to be deleted
      */
     $con->beginTransaction();
     try {
         //select from...
         $c1 = new Criteria();
         $c1->add(EtvaServerPeer::SF_GUARD_GROUP_ID, $this->getId());
         //update set
         $c2 = new Criteria();
         $c2->add(EtvaServerPeer::SF_GUARD_GROUP_ID, $default_group->getId());
         BasePeer::doUpdate($c1, $c2, $con);
         parent::delete($con);
         $con->commit();
     } catch (PropelException $e) {
         $con->rollBack();
         throw $e;
     }
 }
 public function loadFixtures($fixtures)
 {
     // initialize database manager
     $databaseManager = new sfDatabaseManager($this);
     // cleanup database
     $db = sfConfig::get('sf_data_dir') . DIRECTORY_SEPARATOR . '/database.sqlite';
     if (file_exists($db)) {
         unlink($db);
     }
     // initialize database
     $sql = file_get_contents(sfConfig::get('sf_data_dir') . DIRECTORY_SEPARATOR . 'sql' . DIRECTORY_SEPARATOR . 'lib.model.schema.sql');
     $sql = preg_replace('/^\\s*\\-\\-.+$/m', '', $sql);
     $sql = preg_replace('/^\\s*DROP TABLE .+?$/m', '', $sql);
     $con = Propel::getConnection();
     $tables = preg_split('/CREATE TABLE/', $sql);
     foreach ($tables as $table) {
         $table = trim($table);
         if (!$table) {
             continue;
         }
         $con->executeQuery('CREATE TABLE ' . $table);
     }
     // load fixtures
     $data = new sfPropelData();
     if (is_array($fixtures)) {
         $data->loadDataFromArray($fixtures);
     } else {
         $data->loadData(sfConfig::get('sf_data_dir') . '/' . $fixtures);
     }
 }
 /**
  * @return \PDO
  */
 private function getConnection()
 {
     if (null === $this->connection) {
         $this->connection = \Propel::getConnection($this->connectionName);
     }
     return $this->connection;
 }
 public function save($con = null)
 {
     if (!$this->isValid()) {
         throw $this->getErrorSchema();
     }
     if (is_null($con)) {
         $con = Propel::getConnection();
     }
     try {
         $con->beginTransaction();
         $values = $this->getValues();
         $school_year = SchoolYearPeer::retrieveByPK($values["school_year_id"]);
         $shift = ShiftPeer::retrieveByPK($values["shift_id"]);
         unset($values["school_year_id"]);
         unset($values["shift_id"]);
         foreach ($values as $student_id) {
             $student = StudentPeer::retrieveByPk($student_id);
             if (!$student->getIsRegistered($school_year)) {
                 $student->registerToSchoolYear($school_year, $shift, $con);
             }
         }
         $con->commit();
     } catch (Exception $e) {
         $con->rollBack();
         throw $e;
     }
 }
 /**
  * @param sfWebRequest $request
  * @return application/json data
  */
 public function execute($request)
 {
     $con = Propel::getConnection();
     $con->beginTransaction();
     $html = '';
     try {
         $type = $request->getParameter('type');
         $this->forward404Unless($type, 'Comment Type Not Found');
         $id = $request->getParameter('id');
         $this->forward404Unless($id, 'Comment ID Not Found');
         $aComment = CommentQuery::create()->filterByType($type)->filterById($id)->findOne();
         $this->forward404Unless($aComment, sprintf('%s Comment Not Found', ucfirst($type)));
         $this->forward404Unless($aComment->getUserId() == $this->getUser()->getId(), 'Your are not authorized to delete this comment');
         // construction of returns array
         switch ($type) {
             case CommentPeer::TYPE_BRANCH:
                 $returns = array('id' => $aComment->getBranchId(), 'type' => $type);
                 break;
             case CommentPeer::TYPE_FILE:
                 $returns = array('id' => $aComment->getFileId(), 'type' => $type);
                 break;
         }
         $aComment->delete($con);
         $html = $this->getComponent('default', 'commentGlobal', $returns);
         $con->commit();
     } catch (Exception $e) {
         $con->rollBack();
         throw $e;
     }
     // returns a json object
     $this->getResponse()->setContentType('application/json');
     return $this->renderText(json_encode(array('html' => $html)));
 }
 public function executeCreate_tree(sfWebRequest $request)
 {
     $request->setRequestFormat('json');
     $title = $request->getParameter('item_title');
     $user = $this->getUser()->getAttribute('s_current_user', null);
     if ($user != null) {
         try {
             $conn = Propel::getConnection();
             $conn->beginTransaction();
             $tree_bean = new TreeSc();
             $tree_bean->setName($title);
             $tree_bean->setUserId($user->getId());
             $tree_bean->setConfigureFlag('');
             $tree_bean->setConfigureDesign('');
             $tree_bean->setFlag(1);
             $tree_bean->save();
             $tree_user_bean = new TreeUser();
             $tree_user_bean->setUserId($tree_bean->getUserId());
             $tree_user_bean->setTreeId($tree_bean->getId());
             $tree_user_bean->save();
             $conn->commit();
             $this->message = 'success';
             $this->treepk = $tree_bean->getId();
             $this->title = $tree_bean->getName();
             return sfView::SUCCESS;
         } catch (Exception $e) {
             $this->message = $e->getMessage();
             return sfView::ERROR;
         }
     } else {
         $this->message = 'session expired';
         return sfView::ERROR;
     }
 }
Example #30
0
 /**
  * @param sfWebRequest $request
  * @return void
  */
 public function execute($request)
 {
     $type = $request->getParameter('type');
     if (null === $type) {
         throw new Exception('Type Not Found');
     }
     $id = $request->getParameter('id');
     if (null === $id) {
         throw new Exception('Id Not Found');
     }
     $status = $request->getParameter('status');
     if (null === $status) {
         throw new Exception('Status Not Found');
     }
     $con = Propel::getConnection();
     $con->beginTransaction();
     try {
         if (self::TYPE_BRANCH === $type) {
             $this->changeBranchStatus($id, $status, $con);
         } else {
             if (self::TYPE_FILE === $type) {
                 $this->changeFileStatus($id, $status, $con);
             } else {
                 throw new Exception(sprintf('Unknow Type `%s`', $type));
             }
         }
         $con->commit();
     } catch (Exception $e) {
         $con->rollBack();
         throw $e;
     }
     $this->getResponse()->setContentType('application/json');
     return $this->renderText(json_encode(array('status' => $status)));
 }