/**
  * Process the data and return the answers that should be changed.
  *
  * Storing the changed values is handled by the calling function.
  *
  * @param \Gems_Tracker_Token $token Gems token object
  * @return array Containing the changed values
  */
 public function processTokenData(\Gems_Tracker_Token $token)
 {
     if (!$token->getReceptionCode()->isSuccess()) {
         return;
     }
     $answers = $token->getRawAnswers();
     if (isset($answers['informedconsent'])) {
         $consent = $this->util->getConsent($answers['informedconsent']);
         if ($consent->exists) {
             // Is existing consent description as answer
             $consentCode = $consent->getDescription();
         } else {
             if ($answers['informedconsent']) {
                 // Uses start of consent description as answer (LS has only 5 chars for an answer option)
                 $consentCode = $this->db->fetchOne("SELECT gco_description FROM gems__consents WHERE gco_description LIKE ? ORDER BY gco_order", $answers['informedconsent'] . '%');
             } else {
                 $consentCode = false;
             }
             if (!$consentCode) {
                 if ($answers['informedconsent']) {
                     // Code not found, use first positive consent
                     $consentCode = $this->db->fetchOne("SELECT gco_description FROM gems__consents WHERE gco_code != ? ORDER BY gco_order", $this->util->getConsentRejected());
                 } else {
                     // Code not found, use first negative consent
                     $consentCode = $this->db->fetchOne("SELECT gco_description FROM gems__consents WHERE gco_code = ? ORDER BY gco_order", $this->util->getConsentRejected());
                 }
             }
         }
         $respondent = $token->getRespondent();
         $values = array('gr2o_patient_nr' => $respondent->getPatientNumber(), 'gr2o_id_organization' => $respondent->getOrganizationId(), 'gr2o_consent' => $consentCode);
         $respondent->getRespondentModel()->save($values);
     }
     return false;
 }
Esempio n. 2
0
 /**
  * Apply filter
  * @param Zend_Db_Adapter_Abstract $db
  * @param Db_Select | Zend_Db_Select $sql
  * @throws Exception
  */
 public function applyTo(Zend_Db_Adapter_Abstract $db, $sql)
 {
     if (!$sql instanceof Db_Select && !$sql instanceof Zend_Db_Select) {
         throw new Exception('Db_Select_Filter::applyTo  $sql must be instance of Db_Select/Zend_Db_Select');
     }
     $quotedField = $db->quoteIdentifier($this->field);
     switch ($this->type) {
         case self::LT:
         case self::GT:
         case self::EQ:
         case self::GT_EQ:
         case self::LT_EQ:
         case self::LIKE:
         case self::NOT:
         case self::NOT_LIKE:
             $sql->where($quotedField . ' ' . $this->type . ' ?', $this->value);
             break;
         case self::IN:
         case self::NOT_IN:
             $sql->where($quotedField . ' ' . $this->type . ' (?)', $this->value);
             break;
         case self::NOT_NULL:
         case self::IS_NULL:
             $sql->where($quotedField . ' ' . $this->type);
             break;
         case self::BETWEEN:
         case self::NOT_BETWEEN:
             $sql->where($quotedField . ' ' . $this->type . ' ' . $db->quote($this->value[0]) . ' AND ' . $db->quote($this->value[1]));
             break;
     }
 }
Esempio n. 3
0
    /**
     * Fetches a single order by its unique Id.
     *
     * @param  int $id
     * @return Order
     */
    public function getById($id)
    {
        try {
            $result = $this->_database->fetchOne(
                'SELECT o.*,c.* FROM order o INNER JOIN customer c ON o.customer_id = c.id WHERE o.id = ?',
                array($id));

            if ($result == null) throw new \Exception("Could not find order with id " . $id);
            $customer = new Customer();
            $customer->setName($result['name']);
            $customer->setAddress1($result['address_1']);
            $customer->setAddress2($result['address_2']);
            $customer->setCity($result['city']);
            $customer->setState($result['state']);
            $customer->setPostalCode($result['postal_code']);
            $customer->setCellphone($result['cell_phone']);
            $customer->setEmail($result['email']);
            $customer->setCallbackUrl($result['callback_url']);
            $order = new Order();
            $order->setId($id);
            $order->setCustomer($customer);

            return $order;
        }
        catch (\Exception $e)
        {
            throw $e;
        }
    }
 /**
  * Should handle execution of the task, taking as much (optional) parameters as needed
  *
  * The parameters should be optional and failing to provide them should be handled by
  * the task
  */
 public function execute($lineNr = null, $organizationData = null)
 {
     $batch = $this->getBatch();
     $import = $batch->getVariable('import');
     if (isset($organizationData['gor_id_organization']) && $organizationData['gor_id_organization']) {
         $oldId = $organizationData['gor_id_organization'];
     } else {
         $oldId = false;
         $batch->addToCounter('import_errors');
         $batch->addMessage(sprintf($this->_('No gor_id_organization not specified for organization at line %d.'), $lineNr));
     }
     if (isset($organizationData['gor_name']) && $organizationData['gor_name']) {
         if ($oldId) {
             $orgId = $this->db->fetchOne("SELECT gor_id_organization FROM gems__organizations WHERE gor_name = ?", $organizationData['gor_name']);
             if ($orgId) {
                 $import['organizationIds'][$oldId] = $orgId;
                 $import['formDefaults']['gtr_organizations'][] = $orgId;
             } else {
                 $import['organizationIds'][$oldId] = false;
             }
         }
     } else {
         $orgId = false;
         $batch->addToCounter('import_errors');
         $batch->addMessage(sprintf($this->_('No gor_name not specified for organization at line %d.'), $lineNr));
     }
 }
 /**
  * Should handle execution of the task, taking as much (optional) parameters as needed
  *
  * The parameters should be optional and failing to provide them should be handled by
  * the task
  *
  * @param array $row Row to save
  */
 public function execute($row = null)
 {
     if ($row) {
         if (!isset($row['grs_id_user']) && isset($row['grs_ssn']) && $this->targetModel instanceof \Gems_Model_RespondentModel && $this->targetModel->hashSsn !== \Gems_Model_RespondentModel::SSN_HIDE) {
             if (\Gems_Model_RespondentModel::SSN_HASH === $this->targetModel->hashSsn) {
                 $search = $this->targetModel->saveSSN($row['grs_ssn']);
             } else {
                 $search = $row['grs_ssn'];
             }
             $sql = 'SELECT grs_id_user FROM gems__respondents WHERE grs_ssn = ?';
             $id = $this->db->fetchOne($sql, $search);
             // Check for change in patient ID
             if ($id) {
                 if (isset($row['gr2o_id_organization']) && $this->targetModel instanceof \MUtil_Model_DatabaseModelAbstract) {
                     $sql = 'SELECT gr2o_patient_nr
                             FROM gems__respondent2org
                             WHERE gr2o_id_user = ? AND gr2o_id_organization = ?';
                     $patientId = $this->db->fetchOne($sql, array($id, $row['gr2o_id_organization']));
                     if ($patientId) {
                         // Change the patient number
                         $copyId = $this->targetModel->getKeyCopyName('gr2o_patient_nr');
                         $row[$copyId] = $patientId;
                     }
                 }
                 $row['grs_id_user'] = $id;
                 $row['gr2o_id_user'] = $id;
             }
         }
         parent::execute($row);
     }
 }
 /**
  * Should handle execution of the task, taking as much (optional) parameters as needed
  *
  * The parameters should be optional and failing to provide them should be handled by
  * the task
  */
 public function execute($sourceId = null, $userId = null)
 {
     $now = new \MUtil_Db_Expr_CurrentTimestamp();
     $values = array('gso_last_synch' => $now, 'gso_changed' => $now, 'gso_changed_by' => $userId);
     $where = $this->db->quoteInto('gso_id_source = ?', $sourceId);
     $this->db->update('gems__sources', $values, $where);
 }
Esempio n. 7
0
 /**
  * Truncate a given table.
  *
  * @param Zend_Db_Adapter_Abstract $db
  * @param string $tableName
  * @return void
  */
 protected function _truncate(Zend_Db_Adapter_Abstract $db, $tableName)
 {
     $tableName = $db->quoteIdentifier($tableName, true);
     if ($db instanceof Zend_Db_Adapter_Pdo_Sqlite) {
         $db->query('DELETE FROM ' . $tableName);
     } else {
         if ($db instanceof Zend_Db_Adapter_Db2) {
             /*if(strstr(PHP_OS, "WIN")) {
                   $file = tempnam(sys_get_temp_dir(), "zendtestdbibm_");
                   file_put_contents($file, "");
                   $db->query('IMPORT FROM '.$file.' OF DEL REPLACE INTO '.$tableName);
                   unlink($file);
               } else {
                   $db->query('IMPORT FROM /dev/null OF DEL REPLACE INTO '.$tableName);
               }*/
             require_once "Zend/Exception.php";
             throw Zend_Exception("IBM Db2 TRUNCATE not supported.");
         } else {
             if ($this->_isMssqlOrOracle($db)) {
                 $db->query('TRUNCATE TABLE ' . $tableName);
             } else {
                 if ($db instanceof Zend_Db_Adapter_Pdo_Pgsql) {
                     $db->query('TRUNCATE ' . $tableName . ' CASCADE');
                 } else {
                     $db->query('TRUNCATE ' . $tableName);
                 }
             }
         }
     }
 }
Esempio n. 8
0
 public function __construct()
 {
     $this->_db = XenForo_Application::getDb();
     $this->_importModel = XenForo_Model::create('XenForo_Model_Import');
     $this->_db->setProfiler(false);
     // this causes lots of memory usage in debug mode, so stop that
 }
Esempio n. 9
0
 public function deleteOther(ActiveSync_Model_SyncState $_syncState)
 {
     // remove all other synckeys
     $where = array($this->_db->quoteInto('device_id = ?', $_syncState->device_id), $this->_db->quoteInto('type = ?', $_syncState->type), $this->_db->quoteInto('counter != ?', $_syncState->counter));
     $this->_db->delete(SQL_TABLE_PREFIX . 'acsync_synckey', $where);
     return true;
 }
Esempio n. 10
0
 public function isValid($value, $context = null)
 {
     $result = true;
     $this->_value = $value;
     $where = array();
     $where[] = $this->dbAdapter->quoteInto("(p.url_id = ? OR pt.url_id = ?)", $value);
     if (isset($this->_data['id'])) {
         $where[] = $this->dbAdapter->quoteInto("(p.id <> ?)", $this->_data['id']);
     }
     if (isset($this->_data['type_id'])) {
         $where[] = $this->dbAdapter->quoteInto("(p.type_id = ?)", $this->_data['type_id']);
     }
     $where = implode(' AND ', $where);
     $sql = "SELECT COUNT(p.id) AS doubles\n                FROM cms_page AS p\n                    LEFT JOIN cms_page_tr AS pt ON (p.id = pt.translation_id AND pt.language = '" . $this->_lang . "')\n                WHERE {$where}";
     //echo "\n\n$sql\n\n"; die();
     $resultSet = $this->dbAdapter->fetchAll($sql);
     if (0 == count($resultSet)) {
         return false;
     }
     $row = $resultSet[0];
     $result = $row['doubles'] == 0;
     if (!$result) {
         $this->_error(self::URLID_EXISTS);
     }
     return $result;
 }
 /**
  * Overrule to implement snippet specific filtering and sorting.
  *
  * @param \MUtil_Model_ModelAbstract $model
  */
 protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model)
 {
     $filter[] = $this->db->quoteInto("gr2t_id_respondent_track IN (\n                    SELECT gr2t2a_id_respondent_track\n                    FROM gems__respondent2track2appointment\n                    WHERE gr2t2a_id_appointment = ?)", $this->request->getParam(\Gems_Model::APPOINTMENT_ID));
     // \MUtil_Model::$verbose = true;
     $model->setFilter($filter);
     $this->processSortOnly($model);
 }
Esempio n. 12
0
 public function loadByName(Mage_Directory_Model_Region $region, $regionName, $countryId)
 {
     $locale = Mage::app()->getLocale()->getLocaleCode();
     $select = $this->_read->select()->from(array('region' => $this->_regionTable))->where('region.country_id=?', $countryId)->where('region.default_name=?', $regionName)->join(array('rname' => $this->_regionNameTable), 'rname.region_id=region.region_id AND rname.locale=\'' . $locale . '\'', array('name'));
     $region->setData($this->_read->fetchRow($select));
     return $this;
 }
 public function load($printQuery = false, $logQuery = false)
 {
     $this->_select = $this->_read->select();
     $entityTable = $this->getEntity()->getEntityTable();
     $paidTable = $this->getAttribute('grand_total')->getBackend()->getTable();
     $idField = $this->getEntity()->getIdFieldName();
     $this->getSelect()->from(array('sales' => $entityTable), array('store_id', 'lifetime' => 'sum(sales.base_grand_total)', 'avgsale' => 'avg(sales.base_grand_total)', 'num_orders' => 'count(sales.base_grand_total)'))->where('sales.entity_type_id=?', $this->getEntity()->getTypeId())->group('sales.store_id');
     if ($this->_customer instanceof Mage_Customer_Model_Customer) {
         $this->getSelect()->where('sales.customer_id=?', $this->_customer->getId());
     }
     $this->printLogQuery($printQuery, $logQuery);
     try {
         $values = $this->_read->fetchAll($this->getSelect()->__toString());
     } catch (Exception $e) {
         $this->printLogQuery(true, true, $this->getSelect()->__toString());
         throw $e;
     }
     $stores = Mage::getResourceModel('core/store_collection')->setWithoutDefaultFilter()->load()->toOptionHash();
     if (!empty($values)) {
         foreach ($values as $v) {
             $obj = new Varien_Object($v);
             $storeName = isset($stores[$obj->getStoreId()]) ? $stores[$obj->getStoreId()] : null;
             $this->_items[$v['store_id']] = $obj;
             $this->_items[$v['store_id']]->setStoreName($storeName);
             $this->_items[$v['store_id']]->setAvgNormalized($obj->getAvgsale() * $obj->getNumOrders());
             foreach ($this->_totals as $key => $value) {
                 $this->_totals[$key] += $obj->getData($key);
             }
         }
         if ($this->_totals['num_orders']) {
             $this->_totals['avgsale'] = $this->_totals['lifetime'] / $this->_totals['num_orders'];
         }
     }
     return $this;
 }
 /**
  * Creates a model for getModel(). Called only for each new $action.
  *
  * The parameters allow you to easily adapt the model to the current action. The $detailed
  * parameter was added, because the most common use of action is a split between detailed
  * and summarized actions.
  *
  * @param boolean $detailed True when the current action is not in $summarizedActions.
  * @param string $action The current action.
  * @return \MUtil_Model_ModelAbstract
  */
 protected function createModel($detailed, $action)
 {
     $fields = array();
     // Export all
     if ('export' === $action) {
         $detailed = true;
     }
     $organizations = $this->util->getDbLookup()->getOrganizations();
     $fields[] = 'gtr_track_name';
     $sql = "CASE WHEN gtr_organizations LIKE '%%|%s|%%' THEN 1 ELSE 0 END";
     foreach ($organizations as $orgId => $orgName) {
         $fields['O' . $orgId] = new \Zend_Db_Expr(sprintf($sql, $orgId));
     }
     $fields['total'] = new \Zend_Db_Expr("(LENGTH(gtr_organizations) - LENGTH(REPLACE(gtr_organizations, '|', ''))-1)");
     $fields[] = 'gtr_id_track';
     $select = $this->db->select();
     $select->from('gems__tracks', $fields);
     $model = new \MUtil_Model_SelectModel($select, 'track-verview');
     $model->setKeys(array('gtr_id_track'));
     $model->resetOrder();
     $model->set('gtr_track_name', 'label', $this->_('Track name'));
     $model->set('total', 'label', $this->_('Total'));
     $model->setOnTextFilter('total', array($this, 'noTextFilter'));
     foreach ($organizations as $orgId => $orgName) {
         $model->set('O' . $orgId, 'label', $orgName, 'tdClass', 'rightAlign', 'thClass', 'rightAlign');
         $model->setOnTextFilter('O' . $orgId, array($this, 'noTextFilter'));
         if ($action !== 'export') {
             $model->set('O' . $orgId, 'formatFunction', array($this, 'formatCheckmark'));
         }
     }
     // \MUtil_Model::$verbose = true;
     return $model;
 }
Esempio n. 15
0
    /**
     * Code to run after deleting an associated attachment.
     *
     * @see XenForo_AttachmentHandler_Abstract::attachmentPostDelete()
     */
    public function attachmentPostDelete(array $attachment, Zend_Db_Adapter_Abstract $db)
    {
        $db->query('
			UPDATE xf_user_profile
			SET about_attach_count = IF(about_attach_count > 0, about_attach_count - 1, 0)
			WHERE user_id = ?
		', $attachment['content_id']);
    }
    /**
     * Code to run after deleting an associated attachment.
     *
     * @see XenForo_AttachmentHandler_Abstract::attachmentPostDelete()
     */
    public function attachmentPostDelete(array $attachment, Zend_Db_Adapter_Abstract $db)
    {
        $db->query('
			UPDATE xf_conversation_message
			SET attach_count = IF(attach_count > 0, attach_count - 1, 0)
			WHERE message_id = ?
		', $attachment['content_id']);
    }
Esempio n. 17
0
 /**
  * Trigger an import run
  *
  * @return int Last import run ID
  */
 public function run()
 {
     if ($this->providesChanges() && !$this->rowsetExists()) {
         $this->storeRowset();
     }
     $this->db->insert('import_run', array('source_id' => $this->source->id, 'rowset_checksum' => $this->rowsetChecksum(), 'start_time' => date('Y-m-d H:i:s'), 'succeeded' => 'y'));
     return $this->db->lastInsertId();
 }
Esempio n. 18
0
 /**
  * setAutocommit
  * 
  * @param Zend_Db_Adapter_Abstract $adapter
  * @param boolean $on
  */
 public static function setAutocommit($adapter, $on)
 {
     if ($on) {
         $adapter->query('SET AUTOCOMMIT=1;');
     } else {
         $adapter->query('SET AUTOCOMMIT=0;');
     }
 }
 /**
  * Should handle execution of the task, taking as much (optional) parameters as needed
  *
  * The parameters should be optional and failing to provide them should be handled by
  * the task
  *
  * @param int $patchLevel Only execute patches for this patchlevel
  */
 public function execute($patchLevel = null)
 {
     //Update the patchlevel only when we have executed at least one patch
     $batch = $this->getBatch();
     if ($batch->getCounter('executed')) {
         $this->db->query('INSERT IGNORE INTO gems__patch_levels (gpl_level, gpl_created) VALUES (?, CURRENT_TIMESTAMP)', $patchLevel);
     }
 }
Esempio n. 20
0
 protected function _getSqlDropSequence(Zend_Db_Adapter_Abstract $db, $sequenceName)
 {
     $seqList = $db->fetchCol('SELECT sequence_name FROM ALL_SEQUENCES');
     if (in_array($sequenceName, $seqList)) {
         return 'DROP SEQUENCE';
     }
     return null;
 }
Esempio n. 21
0
    public function attachmentPostDelete(array $attachment, Zend_Db_Adapter_Abstract $db)
    {
        $db->query('
			UPDATE xf_resource_update
			SET attach_count = IF(attach_count > 0, attach_count - 1, 0)
			WHERE resource_update_id = ?
		', $attachment['content_id']);
    }
Esempio n. 22
0
    /**
     * Gets the discussion from the update marked with "for update" to ensure that position
     * counters are maintained correctly.
     *
     * @param Zend_Db_Adapter_Abstract $db
     * @param integer $id
     *
     * @return array|false Discussion info or false to use what's in the DW already
     */
    public function getDiscussionForUpdate(Zend_Db_Adapter_Abstract $db, $id)
    {
        return $db->fetchRow('
			SELECT *
			FROM xf_thread
			WHERE thread_id = ?
			FOR UPDATE
		', $id);
    }
Esempio n. 23
0
 /**
  * Get the total paid amount by this customer.
  * Replaces: calc_customer_paid()
  * Enter description here ...
  */
 public function getPaidAmount()
 {
     $tbl_prefix = SimpleInvoices_Db_Table_Abstract::getTablePrefix();
     $select = new Zend_Db_Select($this->_db);
     $select->from($tbl_prefix . "payment", array('amount' => new Zend_Db_Expr("COALESCE(SUM(" . $tbl_prefix . "payment.ac_amount), 0)")));
     $select->joinInner($tbl_prefix . "invoices", $tbl_prefix . "payment.ac_inv_id=" . $tbl_prefix . "invoices.id", NULL);
     $select->where($tbl_prefix . "invoices.customer_id=?", $this->_id);
     return $this->_db->fetchOne($select);
 }
 /**
  * get switch case expression with multiple cases
  *
  * @param string $field
  * @param array $cases
  *
  * @return Zend_Db_Expr
  */
 public function getSwitch($field, $cases)
 {
     $case = 'CASE ' . $this->_adapter->quoteIdentifier($field) . ' ';
     foreach ($cases as $when => $then) {
         $case .= $this->_adapter->quoteInto(' WHEN ' . $when . ' THEN ?', $then);
     }
     $case .= ' END';
     return new Zend_Db_Expr($case);
 }
Esempio n. 25
0
 /**
  * Checks if another transaction is running or not
  * 
  * @param  Zend_Db_Adapter_Abstract $dba
  * @return boolean True if another transaction is in progress, false otherwise
  */
 public static function isTransactionRunning(Zend_Db_Adapter_Abstract $dba)
 {
     try {
         $dba->beginTransaction();
     } catch (Exception $e) {
         return true;
     }
     $dba->rollBack();
     return false;
 }
 /**
  * @param $shadowPath
  * @param $newPath
  * @param $oldPath
  * @param $newShadowPath
  * @param $oldShadowPath
  */
 public function copyTreeByShadowPath($shadowPath, $newPath, $oldPath, $newShadowPath, $oldShadowPath)
 {
     $select = $this->_db->select()->from($this->_tablePrefix . $this->_tableName, array('path' => new Zend_Db_Expr($this->_db->quoteInto($this->_db->quoteInto('REPLACE(path, ?', $oldPath) . ', ?)', $newPath)), 'shadow_path' => new Zend_Db_Expr($this->_db->quoteInto($this->_db->quoteInto('REPLACE(shadow_path, ?', $oldShadowPath) . ', ?)', $newShadowPath)), 'record_id' => 'record_id', 'creation_time' => new Zend_Db_Expr('NOW()')))->where($this->_db->quoteInto($this->_db->quoteIdentifier('shadow_path') . ' like ?', $shadowPath . '/%'));
     $stmt = $this->_db->query($select);
     $entries = $stmt->fetchAll(Zend_Db::FETCH_ASSOC);
     foreach ($entries as $entry) {
         $entry['id'] = Tinebase_Record_Abstract::generateUID();
         $this->_db->insert($this->_tablePrefix . $this->_tableName, $entry);
     }
 }
Esempio n. 27
0
 /**
  * Test the connection, and if needed, reconnect.
  *
  * @return void
  */
 protected function _test()
 {
     try {
         $this->_adapter->query('SELECT 1');
     } catch (Exception $e) {
         // there is an error, so we reconnect
         $this->_adapter = null;
         $this->_connect();
     }
 }
Esempio n. 28
0
 public function __construct()
 {
     $this->_oConfig = Zend_Registry::get(REGISTRY_CONFIG);
     $this->_oDBAdapter = Zend_Db::factory($this->_oConfig->db->adapter, $this->_oConfig->db->config->toArray());
     if ($this->_oConfig->db->adapter == 'PDO_MYSQL') {
         $this->_oDBAdapter->query("SET NAMES 'utf8'");
         $this->_oDBAdapter->query("SET CHARACTER SET utf8");
     }
     $this->_sPrefix = $this->_oConfig->db->prefix;
 }
Esempio n. 29
0
 public function __construct(Zend_Db_Adapter_Abstract $adapter, $options = array())
 {
     if (!$adapter->isConnected()) {
         throw new Khcn_Exception('Adapter not connected');
     }
     $this->_adapter = $adapter;
     if (is_array($options)) {
         $this->setOptions($options);
     }
 }
Esempio n. 30
0
 /**
  * import dump in database
  * @param $name
  * @param null $module
  * @throws Zend_Exception
  */
 public function import($name, $module = null)
 {
     $path = $this->getDumpsDirectoryPath($module);
     if (file_exists($path . DIRECTORY_SEPARATOR . $name)) {
         $dump = file_get_contents($path . DIRECTORY_SEPARATOR . $name);
         return $this->_db->query($dump);
     } else {
         throw new Zend_Exception("Dump file not found!");
     }
 }