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; }
public function __construct() { // automatically define table name (if not defined) if (!isset($this->_name)) { // delete prefix $className = preg_replace('`^.*Model_Table_`', '', get_class($this)); // add slash after upper case letters $name = preg_replace('`[^_]([A-Z])`', '_$1', $className); // table name in lower case $this->_name = strtolower($name); } // load tables structure if (is_null(self::$_structure)) { self::$_structure = Days_Config::load('database')->get(); } // check table definition if (!array_key_exists($this->_name, self::$_structure)) { throw new Days_Exception("Not defined table structure for `{$this->_name}`"); } // set adapter for all tables if (!$this->_db) { $this->_db = Days_Db::factory(); $this->_select = $this->_db->select(); } }
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 getTableDataDump($tableName, $step = 100) { $sql = ''; if ($this->_read) { $quotedTableName = $this->_read->quoteIdentifier($tableName); $colunms = $this->_read->fetchRow('SELECT * FROM ' . $quotedTableName . ' LIMIT 1'); if ($colunms) { $arrSql = array(); $colunms = array_keys($colunms); $quote = $this->_read->getQuoteIdentifierSymbol(); $sql = 'INSERT INTO ' . $quotedTableName . ' (' . $quote . implode($quote . ', ' . $quote, $colunms) . $quote . ')'; $sql .= ' VALUES '; $startRow = 0; $select = $this->_read->select(); $select->from($tableName)->limit($step, $startRow); while ($data = $this->_read->fetchAll($select)) { $dataSql = array(); foreach ($data as $row) { $dataSql[] = $this->_read->quoteInto('(?)', $row); } $arrSql[] = $sql . implode(', ', $dataSql) . ';'; $startRow += $step; $select->limit($step, $startRow); } $sql = implode("\n", $arrSql) . "\n"; } } return $sql; }
function find($parameters) { $select = $this->db->select()->from('user'); foreach ($parameters as $field => $value) { $select->where("{$field}=?", $value); } return $select->query()->fetch(); }
public function setConnection($conn) { if (!$conn instanceof Zend_Db_Adapter_Abstract) { throw new Zend_Exception('dbModel read resource does not implement Zend_Db_Adapter_Abstract'); } $this->_conn = $conn; $this->_select = $this->_conn->select(); }
/** * get version number of a given table * version is stored in database table "applications_tables" * * @param Tinebase_Application application * @return int version number */ public function getTableVersion($_tableName) { $select = $this->_db->select()->from(SQL_TABLE_PREFIX . 'application_tables')->where($this->_db->quoteIdentifier('name') . ' = ?', $_tableName)->orwhere($this->_db->quoteIdentifier('name') . ' = ?', SQL_TABLE_PREFIX . $_tableName); $stmt = $select->query(); $rows = $stmt->fetchAll(); //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $select->__toString()); $result = isset($rows[0]['version']) ? $rows[0]['version'] : 0; return $result; }
/** * Fetch the schema version of the current database * * @return string */ public final function getSchemaVersion() { if (!in_array('schema_info', $this->dbAdapter->listTables())) { $this->createTable('schema_info', array('primary' => false), array(array('version', 'string'))); $this->dbAdapter->insert('schema_info', array('version' => '00000000000000')); return '00000000000000'; } return $this->dbAdapter->fetchOne($this->dbAdapter->select()->from('schema_info', 'version')->limit(1)); }
/** * @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); } }
/** * return device for this user * * @param string $userId * @param string $deviceId * @throws Syncope_Exception_NotFound * @return Syncope_Model_Device */ public function getUserDevice($ownerId, $deviceId) { $select = $this->_db->select()->from($this->_tablePrefix . 'device')->where('owner_id = ?', $ownerId)->where('deviceid = ?', $deviceId); $stmt = $this->_db->query($select); $device = $stmt->fetchObject('Syncope_Model_Device'); if (!$device instanceof Syncope_Model_IDevice) { throw new Syncope_Exception_NotFound('device not found'); } return $device; }
/** * Get all migrated version numbers * * @return array */ public function fetchAll() { $select = $this->adapter->select(); $select->from($this->tableName, 'version'); $select->order('version ASC'); $all = $this->adapter->fetchAll($select); return array_map(function ($v) { return $v['version']; }, $all); }
/** * read syncstate from database * * @param ActiceSync_Model_SyncState $_syncState * @return ActiceSync_Model_SyncState */ public function get(ActiveSync_Model_SyncState $_syncState) { $select = $this->_db->select()->from(SQL_TABLE_PREFIX . 'acsync_synckey')->where('device_id = ?', $_syncState->device_id)->where('type = ?', $_syncState->type)->order('counter DESC')->limit(1); if (!empty($_syncState->counter)) { $select->where('counter = ?', $_syncState->counter); } $row = $this->_db->fetchRow($select); if (!$row) { throw new ActiveSync_Exception_SyncStateNotFound('syncState not found: ' . $select); } $result = new ActiveSync_Model_SyncState($row); return $result; }
/** * Returns true if and only if $value meets the validation requirements * * If $value fails validation, then this method returns false, and * getMessages() will return an array of messages that explain why the * validation failed. * * @param mixed $value * @return boolean * @throws \Zend_Valid_Exception If validation of $value is impossible */ public function isValid($value) { if ($throttleSettings = $this->project->getAskThrottleSettings()) { // Prune the database for (very) old attempts $where = $this->db->quoteInto('gta_datetime < DATE_SUB(NOW(), INTERVAL ? second)', $throttleSettings['period'] * 20); $this->db->delete('gems__token_attempts', $where); // Retrieve the number of failed attempts that occurred within the specified window $select = $this->db->select(); $select->from('gems__token_attempts', array(new \Zend_Db_Expr('COUNT(*) AS attempts'), new \Zend_Db_Expr('UNIX_TIMESTAMP(MAX(gta_datetime)) - UNIX_TIMESTAMP() AS last')))->where('gta_datetime > DATE_SUB(NOW(), INTERVAL ? second)', $throttleSettings['period']); $attemptData = $this->db->fetchRow($select); $remainingDelay = $attemptData['last'] + $throttleSettings['delay']; // \MUtil_Echo::track($throttleSettings, $attemptData, $remainingDelay); if ($attemptData['attempts'] > $throttleSettings['threshold'] && $remainingDelay > 0) { $this->logger->log("Possible token brute force attack, throttling for {$remainingDelay} seconds", \Zend_Log::ERR); $this->_messages = $this->translate->_('The server is currently busy, please wait a while and try again.'); return false; } } // The pure token check if ($this->isValidToken($value)) { return true; } $max_length = $this->tracker->getTokenLibrary()->getLength(); $this->db->insert('gems__token_attempts', array('gta_id_token' => substr($value, 0, $max_length), 'gta_ip_address' => $this->getRequest()->getClientIp())); return false; }
/** * Checks if the user is allowed to login or is blocked * * An adapter authorizes and if the end resultis boolean, string or array * it is converted into a \Zend_Auth_Result. * * @return mixed \Zend_Auth_Adapter_Interface|\Zend_Auth_Result|boolean|string|array */ protected function authorizeBlock() { try { $select = $this->db->select(); $select->from('gems__user_login_attempts', array('UNIX_TIMESTAMP(gula_block_until) - UNIX_TIMESTAMP() AS wait'))->where('gula_block_until is not null')->where('gula_login = ?', $this->getLoginName())->where('gula_id_organization = ?', $this->getCurrentOrganizationId())->limit(1); // Not the first login if ($block = $this->db->fetchOne($select)) { if ($block > 0) { $minutes = intval($block / 60) + 1; // Report all is not well return sprintf($this->plural('Your account is temporarily blocked, please wait a minute.', 'Your account is temporarily blocked, please wait %d minutes.', $minutes), $minutes); } else { // Clean the block once it's past $values['gula_failed_logins'] = 0; $values['gula_last_failed'] = null; $values['gula_block_until'] = null; $where = $this->db->quoteInto('gula_login = ? AND ', $this->getLoginName()); $where .= $this->db->quoteInto('gula_id_organization = ?', $this->getCurrentOrganizationId()); $this->db->update('gems__user_login_attempts', $values, $where); } } } catch (\Zend_Db_Exception $e) { // Fall through as this does not work if the database upgrade did not run // \MUtil_Echo::r($e); } return true; }
/** * Support method for fetching rows. * * @param string|array $where OPTIONAL An SQL WHERE clause. * @param string|array $order OPTIONAL An SQL ORDER clause. * @param int $count OPTIONAL An SQL LIMIT count. * @param int $offset OPTIONAL An SQL LIMIT offset. * @return array The row results, in FETCH_ASSOC mode. */ protected function _fetch($where = null, $order = null, $count = null, $offset = null) { // selection tool $select = $this->_db->select(); // the FROM clause $select->from($this->_name, $this->_cols, $this->_schema); // the WHERE clause $where = (array) $where; foreach ($where as $key => $val) { // is $key an int? if (is_int($key)) { // $val is the full condition $select->where($val); } else { // $key is the condition with placeholder, // and $val is quoted into the condition $select->where($key, $val); } } // the ORDER clause if (!is_array($order)) { $order = array($order); } foreach ($order as $val) { $select->order($val); } // the LIMIT clause $select->limit($count, $offset); // return the results $stmt = $this->_db->query($select); $data = $stmt->fetchAll(Zend_Db::FETCH_ASSOC); return $data; }
/** * get array of ids which got send to the client for a given class * * @param Syncope_Model_IDevice|string $_deviceId * @param Syncope_Model_IFolder|string $_folderId * @return Syncope_Model_SyncState */ public function validate($_deviceId, $_folderId, $_syncKey) { $deviceId = $_deviceId instanceof Syncope_Model_IDevice ? $_deviceId->id : $_deviceId; $folderId = $_folderId instanceof Syncope_Model_IFolder ? $_folderId->id : $_folderId; $select = $this->_db->select()->from($this->_tablePrefix . 'synckey')->where($this->_db->quoteIdentifier('device_id') . ' = ?', $deviceId)->where($this->_db->quoteIdentifier('counter') . ' = ?', $_syncKey)->where($this->_db->quoteIdentifier('type') . ' = ?', $folderId); $stmt = $this->_db->query($select); $state = $stmt->fetchObject('Syncope_Model_SyncState'); $stmt = null; # see https://bugs.php.net/bug.php?id=44081 if (!$state instanceof Syncope_Model_ISyncState) { return false; } $this->_convertFields($state); // check if this was the latest syncKey $select = $this->_db->select()->from($this->_tablePrefix . 'synckey')->where($this->_db->quoteIdentifier('device_id') . ' = ?', $deviceId)->where($this->_db->quoteIdentifier('counter') . ' = ?', $_syncKey + 1)->where($this->_db->quoteIdentifier('type') . ' = ?', $folderId); $stmt = $this->_db->query($select); $moreRecentState = $stmt->fetchObject('Syncope_Model_SyncState'); $stmt = null; # see https://bugs.php.net/bug.php?id=44081 // found more recent synckey => the last sync repsone got not received by the client if ($moreRecentState instanceof Syncope_Model_ISyncState) { // undelete entries marked as deleted in syncope_content table $this->_db->update($this->_tablePrefix . 'content', array('is_deleted' => 0), array('device_id = ?' => $deviceId, 'folder_id = ?' => $folderId, 'creation_synckey = ?' => $state->counter, 'is_deleted = ?' => 1)); // remove entries added during latest sync in syncope_content table $this->_db->delete($this->_tablePrefix . 'content', array('device_id = ?' => $deviceId, 'folder_id = ?' => $folderId, 'creation_synckey > ?' => $state->counter)); } else { // finaly delete all entries marked for removal in syncope_content table $this->_db->delete($this->_tablePrefix . 'content', array('device_id = ?' => $deviceId, 'folder_id = ?' => $folderId, 'is_deleted = ?' => 1)); } // remove all other synckeys $this->_deleteOtherStates($state); return $state; }
public function load($object, $customerId) { $select = $this->_read->select(); $select->from($this->_customerTable, array('login_at', 'logout_at'))->joinInner($this->_visitorTable, $this->_visitorTable . '.visitor_id=' . $this->_customerTable . '.visitor_id', array('last_visit_at'))->joinInner($this->_visitorInfoTable, $this->_visitorTable . '.visitor_id=' . $this->_visitorInfoTable . '.visitor_id', array('http_referer', 'remote_addr'))->joinInner($this->_urlInfoTable, $this->_urlInfoTable . '.url_id=' . $this->_visitorTable . '.last_url_id', array('url'))->where($this->_read->quoteInto($this->_customerTable . '.customer_id=?', $customerId))->order($this->_customerTable . '.login_at desc')->limit(1); $object->setData($this->_read->fetchRow($select)); return $object; }
/** * converts category to tag * * @param int $catId * @return string tagid */ public function getTag($catId) { if (!(isset($this->_tagMapCache[$catId]) || array_key_exists($catId, $this->_tagMapCache))) { $select = $this->_egwDb->select()->from(array('cats' => 'egw_categories'))->where($this->_egwDb->quoteInto($this->_egwDb->quoteIdentifier('cat_id') . ' = ?', $catId)); $cat = $this->_egwDb->fetchAll($select, NULL, Zend_Db::FETCH_ASSOC); $cat = count($cat) === 1 ? $cat[0] : NULL; if (!$cat) { $this->_log->DEBUG(__METHOD__ . '::' . __LINE__ . " category {$catId} not found in egw, skipping tag"); return $this->_tagMapCache[$catId] = NULL; } $tineDb = Tinebase_Core::getDb(); $select = $tineDb->select()->from(array('tags' => $tineDb->table_prefix . 'tags'))->where($tineDb->quoteInto($tineDb->quoteIdentifier('name') . ' LIKE ?', $cat['cat_name'])); $tag = $tineDb->fetchAll($select, NULL, Zend_Db::FETCH_ASSOC); $tag = count($tag) > 0 ? $tag[0] : NULL; if ($tag) { return $this->_tagMapCache[$catId] = $tag['id']; } // create tag $catData = unserialize($cat['cat_data']); $tagId = Tinebase_Record_Abstract::generateUID(); $tagType = $cat['cat_access'] == 'public' ? Tinebase_Model_Tag::TYPE_SHARED : Tinebase_Model_Tag::TYPE_PERSONAL; $tagOwner = $tagType == Tinebase_Model_Tag::TYPE_SHARED ? 0 : $this->mapAccountIdEgw2Tine($cat['cat_owner']); $this->_log->NOTICE(__METHOD__ . '::' . __LINE__ . " creating new {$tagType} tag '{$cat['cat_name']}'"); $tineDb->insert($tineDb->table_prefix . 'tags', array('id' => $tagId, 'type' => $tagType, 'owner' => $tagOwner, 'name' => $cat['cat_name'], 'description' => $cat['cat_description'], 'color' => $catData['color'], 'created_by' => $tagOwner ? $tagOwner : Tinebase_Core::getUser()->getId(), 'creation_time' => $cat['last_mod'] ? $this->convertDate($cat['last_mod']) : Tinebase_DateTime::now())); $right = new Tinebase_Model_TagRight(array('tag_id' => $tagId, 'account_type' => $tagType == Tinebase_Model_Tag::TYPE_SHARED ? Tinebase_Acl_Rights::ACCOUNT_TYPE_ANYONE : Tinebase_Acl_Rights::ACCOUNT_TYPE_USER, 'account_id' => $tagOwner, 'view_right' => true, 'use_right' => true)); Tinebase_Tags::getInstance()->setRights($right); Tinebase_Tags::getInstance()->setContexts(array(0), $tagId); $this->_tagMapCache[$catId] = $tagId; } return $this->_tagMapCache[$catId]; }
/** * update foreign key values * * @param string $_mode create|update * @param Tinebase_Record_Abstract $_record */ protected function _updateForeignKeys($_mode, Tinebase_Record_Abstract $_record) { if (!empty($this->_foreignTables)) { foreach ($this->_foreignTables as $modelName => $join) { if (!array_key_exists('field', $join)) { continue; } $idsToAdd = array(); $idsToRemove = array(); if (!empty($_record->{$modelName})) { $idsToAdd = $this->_getIdsFromMixed($_record->{$modelName}); } $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb()); if ($_mode == 'update') { $select = $this->_db->select(); $select->from(array($join['table'] => $this->_tablePrefix . $join['table']), array($join['field']))->where($this->_db->quoteIdentifier($join['table'] . '.' . $join['joinOn']) . ' = ?', $_record->getId()); $this->_traitGroup($select); $stmt = $this->_db->query($select); $currentIds = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); $stmt->closeCursor(); $idsToRemove = array_diff($currentIds, $idsToAdd); $idsToAdd = array_diff($idsToAdd, $currentIds); } if (!empty($idsToRemove)) { $where = '(' . $this->_db->quoteInto($this->_db->quoteIdentifier($this->_tablePrefix . $join['table'] . '.' . $join['joinOn']) . ' = ?', $_record->getId()) . ' AND ' . $this->_db->quoteInto($this->_db->quoteIdentifier($this->_tablePrefix . $join['table'] . '.' . $join['field']) . ' IN (?)', $idsToRemove) . ')'; $this->_db->delete($this->_tablePrefix . $join['table'], $where); } foreach ($idsToAdd as $id) { $recordArray = array($join['joinOn'] => $_record->getId(), $join['field'] => $id); $this->_db->insert($this->_tablePrefix . $join['table'], $recordArray); } Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId); } } }
/** * @param type $aParams */ public function show($aParams = null) { $aParams = $this->actionController->getRequest()->getParams(); $aDefaultOptions = array('' => 'Not selected'); $aControlsValues = array(); foreach ($this->_aParams['controls'] as $sKey => $aValue) { $aControlsValues[$sKey] = array(); if (isset($aValue['values']) && !is_array($aValue['values'])) { switch ($aValue['values']) { case 'issue': $aQuery = $this->_oDbAdapter->select()->from($aValue['values'], array('id', 'title'))->where('application = ?', $aParams['aid']); $aControlsValues[$sKey] = $this->_oDbAdapter->fetchPairs($aQuery); break; default: break; } } if (!isset($this->_aParams['controls'][$sKey]['values']) || !is_array($aValue['values'])) { is_array($aControlsValues[$sKey]) ? $aControlsValues[$sKey] = $aDefaultOptions + $aControlsValues[$sKey] : $aDefaultOptions; } else { $aControlsValues[$sKey] = $this->_aParams['controls'][$sKey]['values']; } } $this->actionController->view->{$this->getName()} = array('controlsValues' => $aControlsValues); parent::show(); }
/** * Load tree * * @param int|Varien_Data_Tree_Node $parentNode * @return Varien_Data_Tree_Dbp */ public function load($parentNode = null) { $parentPath = ''; if ($parentNode instanceof Varien_Data_Tree_Node) { $parentPath = $parentNode->getData($this->_pathField); } elseif (is_numeric($parentNode)) { $parentNode = null; $select = $this->_conn->select(); $select->from($this->_table, $this->_pathField)->where("{$this->_idField} = ?", $parentNode); $parentPath = $this->_conn->fetchOne($select); } elseif (is_string($parentNode)) { $parentNode = null; $parentPath = $parentNode; } $select = clone $this->_select; $select->order($this->_table . '.' . $this->_orderField . ' ASC'); if ($parentPath) { $condition = $this->_conn->quoteInto("{$this->_table}.{$this->_pathField} like ?", "{$parentPath}/%"); $select->where($condition); } $arrNodes = $this->_conn->fetchAll($select); $childrenItems = array(); foreach ($arrNodes as $nodeInfo) { $pathToParent = explode('/', $nodeInfo[$this->_pathField]); array_pop($pathToParent); $pathToParent = implode('/', $pathToParent); $childrenItems[$pathToParent][] = $nodeInfo; } $this->addChildNodes($childrenItems, $parentPath, $parentNode); return $this; }
protected function _load() { if (null !== $this->_cache) { $data = $this->_cache->load($this->_cacheKey); if (is_string($data)) { $data = unserialize($data); if (!is_array($data)) { $data = null; } } else { $data = null; } $this->_data = $data; } if (null === $this->_data) { $data = $this->_database->select()->from($this->_table)->query()->fetchAll(); $this->_data = array(); if (is_array($data)) { foreach ($data as $row) { $this->_data[$row[$this->_map['key']]] = $row[$this->_map['value']]; } } $this->_saveCache(); } }
/** * Execute a single mail job */ public function executeAction() { $jobId = $this->getParam(\MUtil_Model::REQUEST_ID); $batch = $this->loader->getTaskRunnerBatch('commjob-execute-' . $jobId); $batch->minimalStepDurationMs = 3000; // 3 seconds max before sending feedback if (!$batch->isLoaded() && !is_null($jobId)) { // Check for unprocessed tokens $tracker = $this->loader->getTracker(); $tracker->processCompletedTokens(null, $this->currentUser->getUserId()); // We could skip this, but a check before starting the batch is better $sql = $this->db->select()->from('gems__comm_jobs', array('gcj_id_job'))->where('gcj_active = 1')->where('gcj_id_job = ?', $jobId); $job = $this->db->fetchOne($sql); if (!empty($job)) { $batch->addTask('Mail\\ExecuteMailJobTask', $job); } } if ($batch->isFinished()) { // Add the messages to the view and forward $messages = $batch->getMessages(true); foreach ($messages as $message) { $this->addMessage($message); } $this->_reroute(array('action' => 'show')); } $this->_helper->BatchRunner($batch, $this->_('Execute single mail job'), $this->accesslog); }
/** * Resolve credentials * * Only the first matching username/realm combination in the file is * returned. If the file contains credentials for Digest authentication, * the returned string is the password hash, or h(a1) from RFC 2617. The * returned string is the plain-text password for Basic authentication. * * The expected format of the file is: * username:realm:sharedSecret * * That is, each line consists of the user's username, the applicable * authentication realm, and the password or hash, each delimited by * colons. * * @param string $username Username * @param string $realm Authentication Realm * @throws Zend_Auth_Adapter_Http_Resolver_Exception * @return string|false User's shared secret, if the user is found in the * realm, false otherwise. */ public function resolve($username, $realm) { $exception = null; if ($this->_tableName == '') { $exception = 'A table must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.'; } elseif ($this->_identityColumn == '') { $exception = 'An identity column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.'; } elseif ($this->_credentialColumn == '') { $exception = 'A credential column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.'; } if (null !== $exception) { throw new Zend_Auth_Adapter_Http_Resolver_Exception($exception); } // create result array $authResult = array('code' => Zend_Auth_Result::FAILURE, 'identity' => $username, 'messages' => array()); // get select $select = $this->_zendDb->select(); $select->from($this->_tableName, array('credential' => $this->_credentialColumn))->where($this->_zendDb->quoteIdentifier($this->_identityColumn) . ' = ?', $username); // query for the identity try { $resultIdentities = $this->_zendDb->fetchAll($select->__toString()); } catch (Exception $e) { /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('The supplied parameters to Zend_Auth_Adapter_DbTable failed to ' . 'produce a valid sql statement, please check table and column names ' . 'for validity.'); } if (count($resultIdentities) != 1) { return false; } $resultIdentity = $resultIdentities[0]; return $resultIdentity['credential']; }
/** * Support method for fetching rows. * * @param string $type Whether to fetch 'all' or 'row'. * @param string|array $where OPTIONAL An SQL WHERE clause. * @param string|array $order OPTIONAL An SQL ORDER clause. * @param int $count OPTIONAL An SQL LIMIT count. * @param int $offset OPTIONAL An SQL LIMIT offset. * @return mixed The row results per the Zend_Db_Adapter_Abstract fetch mode. */ protected function _fetch($type, $where = null, $order = null, $count = null, $offset = null) { // selection tool $select = $this->_db->select(); // the FROM clause $select->from($this->_name, array_keys($this->_cols)); // the WHERE clause $where = (array) $where; foreach ($where as $key => $val) { // is $key an int? if (is_int($key)) { // $val is the full condition $select->where($val); } else { // $key is the condition with placeholder, // and $val is quoted into the condition $select->where($key, $val); } } // the ORDER clause $order = (array) $order; foreach ($order as $val) { $select->order($val); } // the LIMIT clause $select->limit($count, $offset); // return the results $method = "fetch{$type}"; return $this->_db->{$method}($select); }
/** * Move tree node * * @todo Use adapter for generate conditions * @param Varien_Data_Tree_Node $node * @param Varien_Data_Tree_Node $newParent * @param Varien_Data_Tree_Node $prevNode */ public function move($node, $newParent, $prevNode = null) { $position = 1; $oldPath = $node->getData($this->_pathField); $newPath = $newParent->getData($this->_pathField); $newPath = $newPath . '/' . $node->getId(); $oldPathLength = strlen($oldPath); $newLevel = $newParent->getLevel() + 1; $levelDisposition = $newLevel - $node->getLevel(); $data = array($this->_levelField => new Zend_Db_Expr("{$this->_levelField} + '{$levelDisposition}'"), $this->_pathField => new Zend_Db_Expr("CONCAT('{$newPath}', RIGHT({$this->_pathField}, LENGTH({$this->_pathField}) - {$oldPathLength}))")); $condition = $this->_conn->quoteInto("{$this->_pathField} REGEXP ?", "^{$oldPath}(/|\$)"); $this->_conn->beginTransaction(); $reorderData = array($this->_orderField => new Zend_Db_Expr("{$this->_orderField} + 1")); try { if ($prevNode && $prevNode->getId()) { $reorderCondition = "{$this->_orderField} > {$prevNode->getData($this->_orderField)}"; $position = $prevNode->getData($this->_orderField) + 1; } else { $reorderCondition = $this->_conn->quoteInto("{$this->_pathField} REGEXP ?", "^{$newParent->getData($this->_pathField)}/[0-9]+\$"); $select = $this->_conn->select()->from($this->_table, new Zend_Db_Expr("MIN({$this->_orderField})"))->where($reorderCondition); $position = (int) $this->_conn->fetchOne($select); } $this->_conn->update($this->_table, $reorderData, $reorderCondition); $this->_conn->update($this->_table, $data, $condition); $this->_conn->update($this->_table, array($this->_orderField => $position, $this->_levelField => $newLevel), $this->_conn->quoteInto("{$this->_idField} = ?", $node->getId())); $this->_conn->commit(); } catch (Exception $e) { $this->_conn->rollBack(); throw new Exception("Can't move tree node due to error: " . $e->getMessage()); } }
/** * import groupmembers from typo3 * * NOTE: in typo3 the user object/dbrow knows the group memberships * * @return void */ public function importGroupMembers() { $select = $this->_t3db->select()->from('be_users'); $usersData = $select->query()->fetchAll(Zend_Db::FETCH_ASSOC); // build a groupMap $userGroup = Tinebase_Group::getInstance()->getDefaultGroup()->getId(); $adminGroup = Tinebase_Group::getInstance()->getDefaultAdminGroup()->getId(); $groupMap = array($userGroup => array(), $adminGroup => array()); foreach ($usersData as $t3user) { $userId = $t3user['uid']; // put user in default user OR admin group $groupMap[$t3user['admin'] == 1 ? $adminGroup : $userGroup][] = $userId; // evaluate typo3 groups if (empty($t3user['usergroup'])) { continue; } $t3userGroups = explode(',', $t3user['usergroup']); foreach ((array) $t3userGroups as $groupId) { if (!(isset($groupMap[$groupId]) || array_key_exists($groupId, $groupMap))) { $groupMap[$groupId] = array(); } $groupMap[$groupId][] = $userId; } } $sqlGroupBackend = new Tinebase_Group_Sql(); foreach ($groupMap as $groupId => $groupMembers) { try { $sqlGroupBackend->setGroupMembers($groupId, $groupMembers); } catch (Exception $e) { // ignore errors Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' could not set groupmembers: ' . $e->getMessage()); } } }
/** * getDbSelect() - Return the preauthentication Db Select object for userland select query modification * * @return Zend_Db_Select */ public function getDbSelect() { if ($this->_dbSelect == null) { $this->_dbSelect = $this->_zendDb->select(); } return $this->_dbSelect; }
public function aggregate($object) { if (!$object->getEntityPkValue() && $object->getId()) { $object->load($object->getReviewId()); } $ratingModel = Mage::getModel('rating/rating'); $ratingSummaries = $ratingModel->getEntitySummary($object->getEntityPkValue(), false); $nonDelete = array(); foreach ($ratingSummaries as $ratingSummaryObject) { if ($ratingSummaryObject->getCount()) { $ratingSummary = round($ratingSummaryObject->getSum() / $ratingSummaryObject->getCount()); } else { $ratingSummary = $ratingSummaryObject->getSum(); } $reviewsCount = $this->getTotalReviews($object->getEntityPkValue(), true, $ratingSummaryObject->getStoreId()); $select = $this->_read->select(); $select->from($this->_aggregateTable)->where("{$this->_aggregateTable}.entity_pk_value = ?", $object->getEntityPkValue())->where("{$this->_aggregateTable}.entity_type = ?", $object->getEntityId())->where("{$this->_aggregateTable}.store_id = ?", $ratingSummaryObject->getStoreId()); $oldData = $this->_read->fetchRow($select); $data = new Varien_Object(); $data->setReviewsCount($reviewsCount)->setEntityPkValue($object->getEntityPkValue())->setEntityType($object->getEntityId())->setRatingSummary($ratingSummary > 0 ? $ratingSummary : 0)->setStoreId($ratingSummaryObject->getStoreId()); $this->_write->beginTransaction(); try { if ($oldData['primary_id'] > 0) { $condition = $this->_write->quoteInto("{$this->_aggregateTable}.primary_id = ?", $oldData['primary_id']); $this->_write->update($this->_aggregateTable, $data->getData(), $condition); } else { $this->_write->insert($this->_aggregateTable, $data->getData()); } $this->_write->commit(); } catch (Exception $e) { $this->_write->rollBack(); } } }