public function indexAction() { $this->enableLayout(); // get a list of news objects and order them by date $blogList = new Object\BlogArticle\Listing(); $blogList->setOrderKey("date"); $blogList->setOrder("DESC"); $conditions = []; if ($this->getParam("category")) { $conditions[] = "categories LIKE " . $blogList->quote("%," . (int) $this->getParam("category") . ",%"); } if ($this->getParam("archive")) { $conditions[] = "DATE_FORMAT(FROM_UNIXTIME(date), '%Y-%c') = " . $blogList->quote($this->getParam("archive")); } if (!empty($conditions)) { $blogList->setCondition(implode(" AND ", $conditions)); } $paginator = \Zend_Paginator::factory($blogList); $paginator->setCurrentPageNumber($this->getParam('page')); $paginator->setItemCountPerPage(5); $this->view->articles = $paginator; // get all categories $categories = Object\BlogCategory::getList(); // this is an alternative way to get an object list $this->view->categories = $categories; // archive information, we have to do this in pure SQL $db = \Pimcore\Resource::get(); $ranges = $db->fetchCol("SELECT DATE_FORMAT(FROM_UNIXTIME(date), '%Y-%c') as ranges FROM object_5 GROUP BY DATE_FORMAT(FROM_UNIXTIME(date), '%b-%Y') ORDER BY ranges ASC"); $this->view->archiveRanges = $ranges; }
/** * @param $classId * @param null $idField * @param null $storetable * @param null $querytable * @param null $relationtable */ public function __construct($classId, $idField = null, $storetable = null, $querytable = null, $relationtable = null) { $this->db = \Pimcore\Resource::get(); $this->fields = array(); $this->relations = array(); $this->fieldIds = array(); $this->deletionFieldIds = array(); $this->fieldDefinitions = []; if ($storetable == null) { $this->storetable = self::STORE_TABLE . $classId; } else { $this->storetable = $storetable; } if ($querytable == null) { $this->querytable = self::QUERY_TABLE . $classId; } else { $this->querytable = $querytable; } if ($relationtable == null) { $this->relationtable = self::RELATION_TABLE . $classId; } else { $this->relationtable = $relationtable; } if ($idField == null) { $this->idField = self::ID_FIELD; } else { $this->idField = $idField; } }
/** * */ public function httpErrorLogCleanup() { // keep the history for max. 7 days (=> exactly 144h), according to the privacy policy (EU/German Law) // it's allowed to store the IP for 7 days for security reasons (DoS, ...) $limit = time() - 6 * 86400; $db = \Pimcore\Resource::get(); $db->delete("http_error_log", "date < " . $limit); }
public function executeSQL($fileName) { $db = \Pimcore\Resource::get(); $file = PIMCORE_PLUGINS_PATH . "/CoreShop/install/sql/{$fileName}.sql"; $sql = file_get_contents($file); $mysqli = $db->getConnection(); return $mysqli->multi_query($sql); }
public function __construct(OnlineShop_Framework_IndexService_Tenant_IConfig $tenantConfig) { $this->name = $tenantConfig->getTenantName(); $this->tenantConfig = $tenantConfig; $this->columnConfig = $tenantConfig->getAttributeConfig(); $this->searchColumnConfig = $tenantConfig->getSearchAttributeConfig(); $this->db = \Pimcore\Resource::get(); }
/** * Use the register method to register items with the container via the * protected $this->container property or the `getContainer` method * from the ContainerAwareTrait. * * @return void */ public function register() { $container = $this->getContainer(); $container->singleton(self::SERVICE_DB, function () { /** @var \Pimcore\Resource\Wrapper $resource */ $resource = Resource::get(); return $resource->getResource(); }); }
/** * @return \Zend_Db_Adapter_Abstract */ protected function getDb() { if (!$this->db) { // we're using a new mysql connection here to avoid problems with active (nested) transactions \Logger::debug("Initialize dedicated MySQL connection for the cache adapter"); $this->db = Resource::getConnection(); } return $this->db; }
/** * @return bool|string */ public function getExistingLengths() { $db = \Pimcore\Resource::get(); $query = "\n SELECT length FROM " . OnlineShop_Framework_VoucherService_Token_Resource::TABLE_NAME . "\n WHERE voucherSeriesId = ?\n GROUP BY length"; try { return $db->fetchAssoc($query, $this->getId()); } catch (Exception $e) { return false; } }
public function showAction() { $offset = $this->_getParam("start"); $limit = $this->_getParam("limit"); $orderby = "ORDER BY id DESC"; $sortingSettings = \Pimcore\Admin\Helper\QueryParams::extractSortingSettings($this->getAllParams()); if ($sortingSettings['orderKey']) { $orderby = "ORDER BY " . $sortingSettings['orderKey'] . " " . $sortingSettings['order']; } $queryString = " WHERE 1=1"; if ($this->_getParam("priority") != "-1" && ($this->_getParam("priority") == "0" || $this->_getParam("priority"))) { $queryString .= " AND priority <= " . $this->_getParam("priority"); } else { $queryString .= " AND (priority = 6 OR priority = 5 OR priority = 4 OR priority = 3 OR priority = 2 OR priority = 1 OR priority = 0)"; } if ($this->_getParam("fromDate")) { $datetime = $this->_getParam("fromDate"); if ($this->_getParam("fromTime")) { $datetime = substr($datetime, 0, 11) . $this->_getParam("fromTime") . ":00"; } $queryString .= " AND timestamp >= '" . $datetime . "'"; } if ($this->_getParam("toDate")) { $datetime = $this->_getParam("toDate"); if ($this->_getParam("toTime")) { $datetime = substr($datetime, 0, 11) . $this->_getParam("toTime") . ":00"; } $queryString .= " AND timestamp <= '" . $datetime . "'"; } if ($this->_getParam("component")) { $queryString .= " AND component = '" . $this->_getParam("component") . "'"; } if ($this->_getParam("relatedobject")) { $queryString .= " AND relatedobject = " . $this->_getParam("relatedobject"); } if ($this->_getParam("message")) { $queryString .= " AND message like '%" . $this->_getParam("message") . "%'"; } $db = Resource::get(); $count = $db->fetchCol("SELECT count(*) FROM " . Log\Helper::ERROR_LOG_TABLE_NAME . $queryString); $total = $count[0]; $result = $db->fetchAll("SELECT * FROM " . Log\Helper::ERROR_LOG_TABLE_NAME . $queryString . " {$orderby} LIMIT {$offset}, {$limit}"); $errorDataList = array(); if (!empty($result)) { foreach ($result as $r) { $parts = explode("/", $r['filelink']); $filename = $parts[count($parts) - 1]; $fileobject = str_replace(PIMCORE_DOCUMENT_ROOT, "", $r['fileobject']); $errorData = array("id" => $r['id'], "message" => $r['message'], "timestamp" => $r['timestamp'], "priority" => $this->getPriorityName($r['priority']), "filename" => $filename, "fileobject" => $fileobject, "relatedobject" => $r['relatedobject'], "component" => $r['component'], "source" => $r['source']); $errorDataList[] = $errorData; } } $results = array("p_totalCount" => $total, "p_results" => $errorDataList); $this->_helper->json($results); }
public function updateSubTenantEntries($objectId, $subTenantData, $subObjectId = null) { $db = \Pimcore\Resource::get(); $db->delete($this->getTenantRelationTablename(), "o_id = " . $db->quote($subObjectId ? $subObjectId : $objectId)); if ($subTenantData) { //implementation specific tenant get logic foreach ($subTenantData as $data) { $db->insert($this->getTenantRelationTablename(), $data); } } }
/** * @static * @return string[] */ public static function getPriorities() { $priorities = array(); $priorityNames = array(Zend_Log::DEBUG => "DEBUG", Zend_Log::INFO => "INFO", Zend_Log::NOTICE => "INFO", Zend_Log::WARN => "WARN", Zend_Log::ERR => "ERR", Zend_Log::CRIT => "CRIT", Zend_Log::ALERT => "ALERT", Zend_Log::EMERG => "EMERG"); $db = Resource::get(); $priorityNumbers = $db->fetchCol("SELECT priority FROM " . Log\Helper::ERROR_LOG_TABLE_NAME . " WHERE NOT ISNULL(priority) GROUP BY priority;"); foreach ($priorityNumbers as $priorityNumber) { $priorities[$priorityNumber] = $priorityNames[$priorityNumber]; } return $priorities; }
public function insertOrUpdateVoucherSeries() { $db = \Pimcore\Resource::get(); try { $query = 'INSERT INTO ' . OnlineShop_Framework_VoucherService_Token_Resource::TABLE_NAME . '(token,length,voucherSeriesId) VALUES (?,?,?) ON DUPLICATE KEY UPDATE token = ?, length = ?'; $db->query($query, [trim($this->configuration->getToken()), $this->getFinalTokenLength(), $this->getSeriesId(), trim($this->configuration->getToken()), $this->getFinalTokenLength()]); } catch (Exception $e) { return ['error' => 'Something went wrong.']; //TODO Error } }
/** * @param OnlineShop_Framework_Pricing_IRule $rule * @param string $field * * @return mixed */ private function getData(OnlineShop_Framework_Pricing_IRule $rule, $field) { if (!array_key_exists($rule->getId(), self::$cache)) { $query = <<<'SQL' SELECT 1 , priceRule.ruleId , count(priceRule.o_id) as "soldCount" , sum(orderItem.totalPrice) as "salesAmount" -- DEBUG INFOS , orderItem.oo_id as "orderItem" , `order`.orderdate FROM object_query_%2$d as `order` -- ordered products JOIN object_relations_%2$d as orderItems ON( 1 AND orderItems.fieldname = "items" AND orderItems.src_id = `order`.oo_id ) -- order item JOIN object_%1$d as orderItem ON ( 1 AND orderItem.o_id = orderItems.dest_id ) -- add active price rules JOIN object_collection_PricingRule_%1$d as priceRule ON( 1 AND priceRule.o_id = orderItem.oo_id AND priceRule.fieldname = "PricingRules" AND priceRule.ruleId = %3$d ) WHERE 1 AND `order`.orderState = "committed" LIMIT 1 SQL; try { $query = sprintf($query, \Pimcore\Model\Object\OnlineShopOrderItem::classId(), \Pimcore\Model\Object\OnlineShopOrder::classId(), $rule->getId()); $conn = \Pimcore\Resource::getConnection(); self::$cache[$rule->getId()] = $conn->fetchRow($query); } catch (Exception $e) { Logger::error($e); } } return self::$cache[$rule->getId()][$field]; }
/** * @param \Zend_Controller_Request_Abstract $request * @return bool|void */ public function routeShutdown(\Zend_Controller_Request_Abstract $request) { if (!Tool::useFrontendOutputFilters($request)) { return $this->disable(); } $db = \Pimcore\Resource::get(); $enabled = $db->fetchOne("SELECT id FROM targeting_personas UNION SELECT id FROM targeting_rules LIMIT 1"); if (!$enabled) { return $this->disable(); } if ($request->getParam("document") instanceof Document\Page) { $this->document = $request->getParam("document"); } }
/** * @param int $duration days * @param string|null $seriesId * @return bool */ public static function cleanUpStatistics($duration, $seriesId = null) { $query = "DELETE FROM " . OnlineShop_Framework_VoucherService_Statistic_Resource::TABLE_NAME . " WHERE DAY(DATEDIFF(date, NOW())) >= ?"; $params[] = $duration; if (isset($seriesId)) { $query .= " AND voucherSeriesId = ?"; $params[] = $seriesId; } $db = \Pimcore\Resource::get(); try { $db->query($query, $params); return true; } catch (Exception $e) { return false; } }
/** * @param $key * @param $language * @return \Pimcore\Model\Metadata\Predefined */ public static function getByKeyAndLanguage($key, $language) { $db = \Pimcore\Resource::get(); $list = new self(); $condition = "name = " . $db->quote($key); if ($language) { $condition .= " AND language = " . $db->quote($language); } else { $condition .= " AND (language = '' OR LANGUAGE IS NULL)"; } $list->setCondition($condition); $list = $list->load(); if ($list) { return $list[0]; } return null; }
/** * @param string $token * @param int $usages * @return bool */ public static function isUsedToken($token, $usages = 1) { $db = \Pimcore\Resource::get(); $query = "SELECT usages, seriesId FROM " . self::TABLE_NAME . " WHERE token = ? "; $params[] = $token; try { $usages['usages'] = $db->fetchOne($query, $params); if ($usages > $usages) { return $usages['seriesId']; } else { return false; } // If an Error occurs the token is defined as used. } catch (Exception $e) { return true; } }
/** * */ public function writeLog() { $code = (string) $this->getResponse()->getHttpResponseCode(); $db = \Pimcore\Resource::get(); try { $uri = $this->getRequest()->getScheme() . "://" . $this->getRequest()->getHttpHost() . $this->getRequest()->getRequestUri(); $exists = $db->fetchOne("SELECT date FROM http_error_log WHERE uri = ?", $uri); if ($exists) { $db->query("UPDATE http_error_log SET `count` = `count` + 1, date = ? WHERE uri = ?", [time(), $uri]); } else { $db->insert("http_error_log", array("uri" => $uri, "code" => (int) $code, "parametersGet" => serialize($_GET), "parametersPost" => serialize($_POST), "cookies" => serialize($_COOKIE), "serverVars" => serialize($_SERVER), "date" => time(), "count" => 1)); } } catch (\Exception $e) { \Logger::error("Unable to log http error"); \Logger::error($e); } }
/** * @return OnlineShop_Framework_ICartItem[] */ public function getSubItems() { if ($this->subItems == null) { $this->subItems = array(); $itemClass = get_class($this) . "_List"; $itemList = new $itemClass(); $db = \Pimcore\Resource::get(); $itemList->setCondition("cartId = " . $db->quote($this->getCartId()) . " AND parentItemKey = " . $db->quote($this->getItemKey())); foreach ($itemList->getCartItems() as $item) { if ($item->getProduct() != null) { $this->subItems[] = $item; } else { Logger::warn("product " . $item->getProductId() . " not found"); } } } return $this->subItems; }
/** * @param $file * @throws \Zend_Db_Adapter_Exception */ public function insertDump($file) { $sql = file_get_contents($file); // we have to use the raw connection here otherwise \Zend_Db uses prepared statements, which causes problems with inserts (: placeholders) // and mysqli causes troubles because it doesn't support multiple queries if ($this->db->getResource() instanceof \Zend_Db_Adapter_Mysqli) { $mysqli = $this->db->getConnection(); $mysqli->multi_query($sql); // loop through results, because ->multi_query() is asynchronous do { if ($result = $mysqli->store_result()) { $mysqli->free_result(); } } while ($mysqli->next_result()); } else { if ($this->db->getResource() instanceof \Zend_Db_Adapter_Pdo_Mysql) { $this->db->getConnection()->exec($sql); } } \Pimcore\Resource::reset(); // set the id of the system user to 0 $this->db->update("users", array("id" => 0), $this->db->quoteInto("name = ?", "system")); }
public function getTranslations($type, $params) { if (in_array($type, array('website', 'admin'))) { $listClass = '\\Pimcore\\Model\\Translation\\' . ucfirst($type) . '\\Listing'; /** * @var $list \Pimcore\Model\Translation\Website\Listing */ $list = new $listClass(); if ($key = $params['key']) { $list->addConditionParam(" `key` LIKE " . \Pimcore\Resource::get()->quote("%" . $key . "%"), ''); } $list->addConditionParam(" `creationDate` >= ? ", $params['creationDateFrom']); $list->addConditionParam(" `creationDate` <= ? ", $params['creationDateTill']); $list->addConditionParam(" `modificationDate` >= ? ", $params['modificationDateFrom']); $list->addConditionParam(" `modificationDate` <= ? ", $params['modificationDateTill']); $data = $list->load(); $result = array(); foreach ($data as $obj) { $result[] = $obj->getForWebserviceExport(); } return $result; } else { throw new \Exception("Parameter 'type' has to be 'website' or 'admin'"); } }
* * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.pimcore.org/license * * @copyright Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org) * @license http://www.pimcore.org/license New BSD License */ chdir(__DIR__); include_once "startup.php"; use Pimcore\Model\Search; // clear all data $db = \Pimcore\Resource::get(); $db->query("TRUNCATE `search_backend_data`;"); $elementsPerLoop = 100; $types = array("asset", "document", "object"); foreach ($types as $type) { $listClassName = "\\Pimcore\\Model\\" . ucfirst($type) . "\\Listing"; $list = new $listClassName(); if (method_exists($list, "setUnpublished")) { $list->setUnpublished(true); } $elementsTotal = $list->getTotalCount(); for ($i = 0; $i < ceil($elementsTotal / $elementsPerLoop); $i++) { $list->setLimit($elementsPerLoop); $list->setOffset($i * $elementsPerLoop); echo "Processing " . $type . ": " . ($list->getOffset() + $elementsPerLoop) . "/" . $elementsTotal . "\n"; $elements = $list->load();
/** * @param $code * @return bool */ public static function tokenExists($code) { $db = \Pimcore\Resource::get(); $query = "SELECT EXISTS(SELECT id FROM " . self::TABLE_NAME . " WHERE token = ?)"; $result = $db->fetchOne($query, $code); if ($result == 0) { return false; } return true; }
/** * @param Object\Concrete $object * @return void */ public function delete($object) { $db = Resource::get(); $db->delete("object_metadata_" . $object->getClassId(), $db->quoteInto("o_id = ?", $object->getId()) . " AND " . $db->quoteInto("fieldname = ?", $this->getName())); }
private function inquire($type) { try { $condense = $this->getParam("condense"); $this->checkUserPermission($type . "s"); if ($this->isPost()) { $data = file_get_contents("php://input"); $idList = explode(',', $data); } else { if ($this->getParam("ids")) { $idList = explode(',', $this->getParam("ids")); } else { $idList = array(); } } if ($this->getParam("id")) { $idList[] = $this->getParam("id"); } $resultData = array(); foreach ($idList as $id) { $resultData[$id] = 0; } if ($type == "object") { $col = "o_id"; } else { $col = "id"; } $sql = "select " . $col . " from " . $type . "s where " . $col . " IN (" . implode(',', $idList) . ")"; $result = \Pimcore\Resource::get()->fetchAll($sql); foreach ($result as $item) { $id = $item[$col]; if ($condense) { unset($resultData[$id]); } else { $resultData[$id] = 1; } } $this->encoder->encode(array("success" => true, "data" => $resultData)); } catch (\Exception $e) { $this->encoder->encode(array("success" => false, "msg" => $e->getMessage())); } }
/** * @param $value * @return string */ public function quote($value, $type = null) { $db = Resource::get(); return $db->quote($value, $type); }
/** * @param $tableDefinitions * @param $tableNames */ public static function updateTableDefinitions(&$tableDefinitions, $tableNames) { if (!is_array($tableDefinitions)) { $tableDefinitions = array(); } $db = \Pimcore\Resource::get(); $tmp = array(); foreach ($tableNames as $tableName) { $tmp[$tableName] = $db->fetchAll("show columns from " . $tableName); } foreach ($tmp as $tableName => $columns) { foreach ($columns as $column) { $column["Type"] = strtolower($column["Type"]); if (strtolower($column["Null"]) == "yes") { $column["Null"] = "null"; } // $fieldName = strtolower($column["Field"]); $fieldName = $column["Field"]; $tableDefinitions[$tableName][$fieldName] = $column; } } }
/** * @param $filters * @param $field * @param $drillDownFilters * @return array|mixed */ public function getAvailableOptions($filters, $field, $drillDownFilters) { $db = Resource::get(); $baseQuery = $this->getBaseQuery($filters, array($field), true, $drillDownFilters, $field); $data = array(); if ($baseQuery) { $sql = $baseQuery["data"] . " GROUP BY " . $db->quoteIdentifier($field); $data = $db->fetchAll($sql); } $filteredData = array(); foreach ($data as $d) { if (!empty($d[$field]) || $d[$field] === 0) { $filteredData[] = array("value" => $d[$field]); } } return array("data" => array_merge(array(array("value" => null)), $filteredData)); }
/** * @param null $key * @throws \Exception */ public function initResource($key = null) { $myClass = get_class($this); $resource = null; if (!$key) { // check for a resource in the cache if (array_key_exists($myClass, self::$resourceClassCache)) { $resource = self::$resourceClassCache[$myClass]; } else { $classes = $this->getParentClasses($myClass); foreach ($classes as $class) { $delimiter = "_"; // old prefixed class style if (strpos($class, "\\")) { $delimiter = "\\"; // that's the new with namespaces } $classParts = explode($delimiter, $class); $length = count($classParts); $className = null; for ($i = 0; $i < $length; $i++) { // check for a general DBMS resource adapter $tmpClassName = implode($delimiter, $classParts) . $delimiter . "Resource"; if ($className = $this->determineResourceClass($tmpClassName)) { break; } // this is just for compatibility anymore, this was before the standard way // but as there will not be a specialized implementation anymore eg. Oracle, PostgreSQL, ... // we can move that below the general resource adapter as a fallback $tmpClassName = implode($delimiter, $classParts) . $delimiter . "Resource" . $delimiter . ucfirst(Resource::getType()); if ($className = $this->determineResourceClass($tmpClassName)) { break; } array_pop($classParts); } if ($className && $className != "Pimcore\\Resource") { //\Logger::debug("Found resource implementation " . $className . " for " . $myClass); $resource = $className; self::$resourceClassCache[$myClass] = $resource; break; } } } } else { // check in cache $cacheKey = $myClass . "-" . $key; if (array_key_exists($cacheKey, self::$resourceClassCache)) { $resource = self::$resourceClassCache[$cacheKey]; } else { $delimiter = "_"; // old prefixed class style if (strpos($key, "\\") !== false) { $delimiter = "\\"; // that's the new with namespaces } // check for a specialized resource adapter for the current DBMS $resourceClass = $key . $delimiter . "Resource" . $delimiter . ucfirst(Resource::getType()); if (!($resource = $this->determineResourceClass($resourceClass))) { $resource = $key . $delimiter . "Resource"; } self::$resourceClassCache[$cacheKey] = $resource; } } if (!$resource) { \Logger::critical("No resource implementation found for: " . $myClass); throw new \Exception("No resource implementation found for: " . $myClass); } $resource = "\\" . ltrim($resource, "\\"); $this->resource = new $resource(); $this->resource->setModel($this); $db = Resource::get(); $this->resource->configure($db); if (method_exists($this->resource, "init")) { $this->resource->init(); } }
/** * returns sql query statement to filter according to this data types value(s) * @param $value * @param $operator * @return string * */ public function getFilterCondition($value, $operator) { $db = \Pimcore\Resource::get(); $value = $db->quote($value); $key = $db->quoteIdentifier($this->name, $this->name); return "IFNULL(" . $key . ", 0) = " . $value . " "; }