/** * вывод html-карты сайта по шорт-коду [sitemap-html] */ static function viewSitemap() { $sitemap = Storage::get(md5('mgPluginSitemapHtml')); if ($sitemap == null) { $pages = self::getPages(); $catalog = self::getCatalog(); $html = ' <div class="sitemap-html"> <h2 class="new-products-title">Карта сайта</h2> <ul class="js_listSiteMap">'; foreach ($pages as $url => $title) { $partsUrl = URL::getSections($url); $priority = count($partsUrl); if (is_array($title)) { $html .= '<li><a href="' . SITE . '/' . $url . '">' . $title[$url] . '<ul>'; foreach ($title as $suburl => $subtitle) { if ($suburl != $url) { $html .= '<li><a href="' . SITE . '/' . $suburl . '" title="' . $subtitle . '">' . $subtitle . '</a></li>'; } } $html .= '</ul></li>'; } else { $html .= '<li><a href="' . SITE . '/' . $url . '" title="' . $title . '">' . $title . '</a></li>'; if ($url == 'catalog') { $html .= '<ul>' . $catalog . '</ul>'; } } } $sitemap = $html . '</ul></div>'; Storage::save(md5('mgPluginSitemapHtml'), $sitemap); } return $sitemap; }
function handle_uploaded_avatar_pic() { if (isset($_POST['user_filename'])) { $_POST['user_filename'] = Storage::validateFileId($_POST['user_filename']); } if (!empty($_FILES['userfile']['name'])) { // process uploaded image file $myUploadobj = new FileUploader(); $file = $myUploadobj->upload_file(PA::$upload_path, 'userfile', true, true, 'image'); if (!$file) { throw new PAException(FILE_NOT_UPLOADED, $myUploadobj->error); } } else { // download given image url $avatar_url = trim(@$_REQUEST['avatar_url']); if (!empty($avatar_url) && preg_match("|http://(.*?)/(.*)|", $avatar_url, $m)) { list(, $uf_server, $uf_path) = $m; $file = Storage::save($avatar_url, basename($uf_path), "critical", "image"); if (!$file) { throw new PAException(FILE_NOT_UPLOADED, sprintf(__("Could not retrieve file from URL: %s"), $avatar_url)); } } } if (@$file) { $_POST['user_filename'] = $file; $_POST['avatar_url'] = ''; } }
function __construct() { $model = new Models_Product(); // Требуется только пересчет цены товара. if (!empty($_REQUEST['calcPrice'])) { $model->calcPrice(); exit; } $product = Storage::get(md5('ControllersProduct' . URL::getUrl())); if ($product == null) { $settings = MG::get('settings'); $product = $model->getProduct(URL::getQueryParametr('id')); if (empty($product)) { MG::redirect('/404'); exit; } $product['meta_title'] = $product['meta_title'] ? $product['meta_title'] : $product['title']; $product['currency'] = $settings['currency']; $blockVariants = $model->getBlockVariants($product['id']); $blockedProp = $model->noPrintProperty(); $propertyFormData = $model->createPropertyForm($param = array('id' => $product['id'], 'maxCount' => $product['count'], 'productUserFields' => $product['thisUserFields'], 'action' => "/catalog", 'method' => "POST", 'ajax' => true, 'blockedProp' => $blockedProp, 'noneAmount' => false, 'noneButton' => $product['count'] ? false : true, 'titleBtn' => MG::getSetting('buttonBuyName'), 'blockVariants' => $blockVariants, 'currency_iso' => $product['currency_iso'])); // Легкая форма без характеристик. $liteFormData = $model->createPropertyForm($param = array('id' => $product['id'], 'maxCount' => $product['count'], 'productUserFields' => null, 'action' => "/catalog", 'method' => "POST", 'ajax' => true, 'blockedProp' => $blockedProp, 'noneAmount' => false, 'noneButton' => $product['count'] ? false : true, 'titleBtn' => MG::getSetting('buttonBuyName'), 'blockVariants' => $blockVariants)); //echo viewData($propertyFormData['defaultSet']); $product['price_course'] += $propertyFormData['marginPrice']; $currencyRate = MG::getSetting('currencyRate'); $currencyShopIso = MG::getSetting('currencyShopIso'); $product['currency_iso'] = $product['currency_iso'] ? $product['currency_iso'] : $currencyShopIso; $product['old_price'] = $product['old_price'] * $currencyRate[$product['currency_iso']]; $product['old_price'] = $product['old_price'] ? $product['old_price'] : 0; $product['price'] = MG::priceCourse($product['price_course']); $product['propertyForm'] = $propertyFormData['html']; $product['propertyNodummy'] = $propertyFormData['propertyNodummy']; $product['stringsProperties'] = $propertyFormData['stringsProperties']; $product['liteFormData'] = $liteFormData['html']; $product['description'] = MG::inlineEditor(PREFIX . 'product', "description", $product['id'], $product['description']); $product['title'] = MG::modalEditor('catalog', $product['title'], 'edit', $product["id"]); // Информация об отсутствии товара на складе. if (MG::getSetting('printRemInfo') == "true") { $message = 'Здравствуйте, меня интересует товар "' . str_replace("'", """, $product['title']) . '" с артикулом "' . $product['code'] . '", но его нет в наличии. Сообщите, пожалуйста, о поступлении этого товара на склад. '; if ($product['count'] != 0) { $style = 'style="display:none;"'; } $product['remInfo'] = "<span class='rem-info' " . $style . ">Товара временно нет на складе!<br/><a href='" . SITE . "/feedback?message=" . $message . "'>Сообщить когда будет в наличии.</a></span>"; } if ($product['count'] < 0) { $product['count'] = "много"; } $product['related'] = $model->createRelatedForm($product['related']); Storage::save(md5('ControllersProduct' . URL::getUrl()), $product); } // MG::set('propertyNodummy',$product['propertyNodummy']); // $_SESSION['propertyNodummy'] = $product['propertyNodummy']; $this->data = $product; }
static function breadcrumbs() { $breadcrumbs = Storage::get(md5('breadcrumbs' . URL::getUrl())); if ($breadcrumbs == null) { $sections = URL::getSections(); array_splice($sections, 0, 1); if (SHORT_LINK == 1 && MG::get('controller') == 'controllers_product') { $product_url = URL::getLastSection(); $res = DB::query('SELECT CONCAT(c.`parent_url`, c.`url`) as fullurl FROM `' . PREFIX . 'product` p LEFT JOIN `' . PREFIX . 'category` c ON p.cat_id = c.id WHERE p.url = ' . DB::quote($product_url)); $cat = DB::fetchArray($res); $sections = explode('/', $cat['fullurl']); $sections[] = $product_url; } $breadcrumbs = '<a href="' . SITE . '/catalog">Каталог</a>'; $max = count($sections); $i = 0; $par = ''; foreach ($sections as $section) { $url = $section; $cat = 'title'; if ($url != 'catalog') { $data = self::checkURLname('*', 'category', $section, 'url', $par); $url = $data[0]['parent_url'] . $section; $res = $data[0]['title']; $par = $data[0]['id']; if (!$data[0]['title']) { $cat = 'name'; $n = ''; $result = self::checkURLname('*', 'product', $section, 'url', $n); $url = $data[0]['parent_url'] . $sections[1] . '/' . $sections[2]; $categoryRes = self::checkURLname('url, parent_url', 'category', $result[0]['cat_id'], 'id'); $url = $categoryRes[0]['parent_url'] . $categoryRes[0]['url'] . '/' . $result[0]['url']; $res = $result[0]['title']; } } $i++; if ($max == $i) { $breadcrumbs .= ' » <span class="last-crumb">' . $res . '</span>'; } else { $breadcrumbs .= ' » <a href="' . SITE . '/' . $url . '">' . $res . '</a>'; } } $breadcrumbs = "<div class='bread-crumbs'>" . $breadcrumbs . "</div>"; //сохраняем объект в кэш Storage::save(md5('breadcrumbs' . URL::getUrl()), $breadcrumbs); } return $breadcrumbs; }
static function breadcrumbs() { $breadcrumbs = Storage::get(md5('breadcrumbs' . URL::getUrl())); if ($breadcrumbs == null) { $sections = URL::getSections(); array_splice($sections, 0, 1); $breadcrumbs = '<a href="' . SITE . '/catalog">Каталог</a>'; $max = count($sections); $i = 0; $par = ''; foreach ($sections as $section) { $url = $section; $cat = 'title'; if ($url != 'catalog') { $data = self::checkURLname('*', 'category', $section, 'url', $par); $url = $data[0]['parent_url'] . $section; $res = $data[0]['title']; $par = $data[0]['id']; if (!$data[0]['title']) { $cat = 'name'; $n = ''; $result = self::checkURLname('*', 'product', $section, 'url', $n); $url = $data[0]['parent_url'] . $sections[1] . '/' . $sections[2]; $categoryRes = self::checkURLname('url, parent_url', 'category', $result[0]['cat_id'], 'id'); $url = $categoryRes[0]['parent_url'] . $categoryRes[0]['url'] . '/' . $result[0]['url']; $res = $result[0]['title']; } } $i++; if ($max == $i) { $breadcrumbs .= ' » <span class="last-crumb">' . $res . '</span>'; } else { $breadcrumbs .= ' » <a href="' . SITE . '/' . $url . '">' . $res . '</a>'; } } $breadcrumbs = "<div class='bread-crumbs'>" . $breadcrumbs . "</div>"; //сохраняем объект в кэш Storage::save(md5('breadcrumbs' . URL::getUrl()), $breadcrumbs); } return $breadcrumbs; }
if (!$image_file) { $error = $myUploadobj->error; } } catch (Exception $e) { $error = $e->getMessage(); } $img_resized = uihelper_resize_mk_img($image_file, 200, 200, NULL, 'style="margin-left: 10px"'); } echo "{"; echo "error: '" . $error . "',\n"; echo "image: '" . htmlspecialchars($img_resized) . "',\n"; echo "image_file: '" . $image_file . "'\n"; echo "}"; } else { if (preg_match("|http://(.*?)/(.*)|", $img_url, $m)) { try { list(, $uf_server, $uf_path) = $m; $image_file = Storage::save($img_url, basename($uf_path), "critical", "image"); } catch (Exception $e) { $error = $e->getMessage(); } $img_resized = uihelper_resize_mk_img($image_file, 200, 200, NULL, 'style="margin-left: 10px"'); } else { $error = 'Invalid Image URL.'; } echo "{"; echo "error: '" . $error . "',\n"; echo "image: '" . htmlspecialchars($img_resized) . "',\n"; echo "image_file: '" . $image_file . "'\n"; echo "}"; }
public static function resize_img($root_path, $root_url, $output_path, $max_x, $max_y, $picture, $alternate = NULL, $overwrite = FALSE, $resize_type = RESIZE_CROP) { $final_path = NULL; if ($alternate) { if (preg_match("|^http://|", $alternate)) { throw new CNException(BAD_PARAMETER, "Alternate image passed to resizing functions must not be a URL"); } if (!preg_match("#^(files|Themes|images)/#", $alternate)) { throw new CNException(BAD_PARAMETER, "Alternate image passed to resizing functions must be relative to the web directory; {$alternate} is not valid"); } } if ($picture instanceof StoredFile) { $stored_file = $picture; $pic_path = $picture->filename; } else { if (defined("NEW_STORAGE")) { // check for broken or deprecated calling code if (preg_match("|^files/files|", $picture)) { throw new CNException(INVALID_ID, "Broken image ID - starting with files/files!"); } if (preg_match("|^files/pa://|", $picture)) { throw new CNException(INVALID_ID, "Broken image ID - check for code adding 'files/' to the start of a pa:// image URL"); } } $stored_file = NULL; $image_path = NULL; if (getimagesize(PA::$project_dir . "/{$root_path}/{$picture}")) { $image_path = PA::$project_dir . "/{$root_path}"; } else { if (getimagesize(PA::$core_dir . "/{$root_path}/{$picture}")) { $image_path = PA::$core_dir . "/{$root_path}"; } else { if (getimagesize(PA::$project_dir . "/{$root_path}/{$alternate}")) { $image_path = PA::$project_dir . "/{$root_path}"; } else { if (getimagesize(PA::$core_dir . "/{$root_path}/{$alternate}")) { $image_path = PA::$core_dir . "/{$root_path}"; } } } } if ($picture && is_file("{$image_path}/{$picture}") && getimagesize("{$image_path}/{$picture}") !== false) { $pic_path = $picture; } else { if (!$alternate || !is_file("{$image_path}/{$alternate}")) { // we could throw a FILE_NOT_FOUND exception here, but that // breaks things, so instead we output an image tag with the // requested size that refers to the original path. this // way the admin will see 404 errors in the log, and maybe // fix what's wrong. $final_path = $picture; $width = $max_x; $height = $max_y; } else { $pic_path = $alternate; } } } if (!$final_path) { // if it's a png or gif, convert to png - so we don't lose transparency. otherwise jpg. $path_parts = pathinfo($pic_path); $ext = strtolower($path_parts['extension']); switch ($ext) { case 'png': case 'gif': $ext = 'png'; $mime_type = "image/png"; break; default: $ext = 'jpg'; $mime_type = "image/jpeg"; break; } $prefix = ImageResize::$resize_type_prefixes[$resize_type]; if (!$prefix) { throw new CNException(BAD_PARAMETER, "Invalid resize type: {$resize_type}"); } // 'dim' string for file link $file_link_dim = $prefix . "-" . $max_x . "x" . $max_y; if ($stored_file) { // have we resized this already? $link = Storage::find_thumb($stored_file->file_id, $file_link_dim); if ($link) { $thumb_id = $link['file_id']; } else { // nope - we have to resize it now $picture_full_path = $stored_file->getPath(); // temp output filename $resized_fn_tmp = tempnam(ini_get("upload_tmp_dir"), "rsz"); $resized_fn = $resized_fn_tmp . "." . $ext; rename($resized_fn_tmp, $resized_fn); // leaf name, to show to users later on $leaf = $stored_file->filename; Logger::log("Resizing image '{$picture_full_path}' from Storage into {$resized_fn}", LOGGER_ACTION); ImageResize::do_resize_to_max_side($picture_full_path, $resized_fn, $max_x, $max_y, $resize_type); list($w, $h) = getimagesize($resized_fn); // make the new file $thumb_id = Storage::save($resized_fn, $file_link_dim . "-" . $leaf, "throwaway", $mime_type, array("width" => $w, "height" => $h)); unlink($resized_fn); // link it to the original so we can find it again Storage::link($thumb_id, array("role" => "thumb", "dim" => $file_link_dim, "file" => $stored_file->file_id)); } // and return the details $thumb = Storage::get($thumb_id); return array('url' => $thumb->getURL(), 'width' => $thumb->width, 'height' => $thumb->height, 'size_attr' => 'width="' . $thumb->width . '" height="' . $thumb->height . '"'); } else { // relative path to resized file $resized_pic_path = $prefix . "_" . $max_x . "x" . $max_y . "/" . preg_replace("/\\.[A-Za-z]+\$/", "", $pic_path) . ".{$ext}"; // abs path to resized file $resized_fn = PA::$project_dir . "/{$root_path}/{$output_path}/{$resized_pic_path}"; // only overwrite an existing file if it's out of date or we have been told to (via $overwrite) if (!file_exists($resized_fn) || filemtime($resized_fn) < filemtime("{$image_path}/{$pic_path}") || $overwrite) { // make all path parts up to the image if (!is_dir(dirname($resized_fn))) { $mkdir_path = PA::$project_dir . "/{$root_path}/{$output_path}"; ImageResize::try_mkdir($mkdir_path); foreach (explode("/", dirname($resized_pic_path)) as $path_part) { $mkdir_path .= "/{$path_part}"; ImageResize::try_mkdir($mkdir_path); } } ImageResize::do_resize_to_max_side("{$image_path}/{$pic_path}", $resized_fn, $max_x, $max_y, $resize_type); clearstatcache(); } } list($width, $height) = getimagesize($resized_fn); $final_path = "{$output_path}/" . dirname($resized_pic_path) . "/" . rawurlencode(basename($resized_pic_path)); } return array('final_path' => $final_path, 'width' => $width, 'height' => $height, 'size_attr' => 'width="' . $width . '" height="' . $height . '"'); }
/** * Name : start_upload() * @access private * Use : actually uploads the file */ private function start_upload() { if (!isset($this->file_name)) { $this->error = "You must define filename!"; } if ($this->file_size <= 0) { $this->error = "The file size is too small."; } if ($this->file_size > $this->max_filesize && $this->max_filesize != 0) { $this->error = "The file size is too large, upload a file having size less than " . $this->max_filesize / 1000000 . "M"; } if ($this->error != "") { return; } $destination = $this->full_name; if (!defined("NEW_STORAGE")) { // Old style - just throw it in web/files if (!@move_uploaded_file($this->tmp_name, $destination)) { $this->error = "Unable to copy " . $this->file_name . " to {$destination} directory."; return; } } else { if (!is_uploaded_file($this->tmp_name)) { $this->error = sprintf(__("Security error: File %s is not an uploaded file:"), $this->tmp_name); return; } // we now know that $this->tmp_name is a real file and has passed all the security checks, so throw it in storage... $this->file_id = Storage::save($this->tmp_name, $this->raw_file_name); } }
/** * @return bool */ public function createOrNone() { $this->verifyTable(); if (!Storage::model()->findByAttributes(array('key' => $this->hash()))) { $storage = new Storage(); $storage->key = $this->hash(); $storage->value = json_encode($this->generateBrief()); return $storage->save(); } return false; }
/** * Строит sql запрос для поиска всех id товаров удовлетворяющих фильтру по характеристикам * * @param array $properties массив с ключами переданных массивов с характеристиками * @return array массив id товаров. */ public function getProductIdByFilter($properties) { $result = array(); $propertyData = Storage::get(md5('filterProperty' . $_REQUEST['category_id'])); if ($propertyData == null) { $propertyData = $this->getPropertyData(); Storage::save(md5('filterProperty' . $_REQUEST['category_id']), $propertyData); } $sql = ' SELECT p.id FROM `' . PREFIX . 'product` as p'; foreach ($properties as $id => $property) { if (empty($id) || !is_numeric($id)) { continue; } // если указан параметр по умолчанию из выпадающего спи ска "не выбрано" if (count($property) === 1 && empty($property[0])) { continue; } if ($property[0] == "slider") { if (empty($property[1]) || empty($property[2])) { continue; } $arVal = array_unique(explode('|', trim($propertyData[$id]['allValue'], '|'))); $min = (double) $arVal[0]; // Максимальное значение (назначим 1 значение самым маленьким) $max = (double) $arVal[0]; // Минимальное значение (назначим 1 значение самым большим) foreach ($arVal as $value) { if (!empty($value)) { // Проверми,является ли значение числом if (is_numeric($value)) { // Ищем мин и максимальные значения if ($max < $value) { $max = $value; } else { if ($min > $value) { $min = $value; } } } } } if ($property[1] == $min && $property[2] == $max) { continue; } } $sql .= ' JOIN `' . PREFIX . 'product_user_property` as pup' . $id . ' ON '; foreach ($property as $cnt => $value) { //Если мы уже составляли условие для слайдера, то пропускаем шаг. #ДОБАВЛЕНО if ($property[0] == "slider" && $cnt > 0) { continue; } $value = str_replace('+', '[[.plus-sign.]]', $value); $value = str_replace('*', '[[.asterisk.]]', $value); $value = str_replace('(', '[[.left-parenthesis.]]', $value); $value = str_replace(')', '[[.right-parenthesis.]]', $value); $value = str_replace('?', '[[.question-mark.]]', $value); $sql .= '(pup' . $id . '.product_id = p.id AND '; $sql .= '((pup' . $id . '.property_id = ' . DB::quote($id) . ') AND '; //Проверяем, выводится ли тип характеристика слайдером. #ДОБАВЛЕНО if ($property[0] == "slider") { $sql .= '(pup' . $id . '.value BETWEEN ' . $property[1] . ' AND ' . $property[2] . ' OR pup' . $id . '.value = \'\'))) OR '; continue; } $sql .= '(LCASE(concat("|",pup' . $id . '.value,"|")) REGEXP LCASE("[[.vertical-line.]]' . DB::quote(htmlspecialchars_decode($value), true) . '(#.*#)?[[.vertical-line.]]")))) OR '; } $sql = substr($sql, 0, -4); } $res = DB::query($sql); while ($row = DB::fetchAssoc($res)) { $result[] = $row['id']; } $pIds = implode(',', $result); if (!empty($pIds)) { $sql = ' SELECT pup.property_id, pup.value FROM `' . PREFIX . 'product_user_property` as pup WHERE pup.product_id IN (' . DB::quote($pIds, 1) . ') '; $res = DB::query($sql); while ($row = DB::fetchAssoc($res)) { if ($row['value']) { $partVal = explode('|', $row['value']); foreach ($partVal as $value) { $this->accessValues[$row['property_id']][$value] = preg_replace('~(#.*#)~', '', $value); } } } } return $result; }
function __construct() { $settings = MG::get('settings'); // Если нажата кнопка купить. $_REQUEST['category_id'] = URL::getQueryParametr('category_id'); if (!empty($_REQUEST['inCartProductId'])) { $cart = new Models_Cart(); $property = $cart->createProperty($_POST); $cart->addToCart($_REQUEST['inCartProductId'], $_REQUEST['amount_input'], $property); SmalCart::setCartData(); MG::redirect('/cart'); } $countСatalogProduct = $settings['countСatalogProduct']; // Показать первую страницу выбранного раздела. $page = 1; // Запрашиваемая страница. if (isset($_REQUEST['p'])) { $page = $_REQUEST['p']; } $model = new Models_Catalog(); // Получаем список вложенных категорий, для вывода всех продуктов, на страницах текущей категории. $model->categoryId = MG::get('category')->getCategoryList($_REQUEST['category_id']); // В конец списка, добавляем корневую текущую категорию. $model->categoryId[] = $_REQUEST['category_id']; // Передаем номер требуемой страницы, и количество выводимых объектов. $countСatalogProduct = 100; $actionButton = MG::getSetting('actionInCatalog') === "true" ? 'actionBuy' : 'actionView'; $dataGroupProducts = Storage::get(md5('dataGroupProductsIndexConroller')); $currencyRate = MG::getSetting('currencyRate'); $currencyShopIso = MG::getSetting('currencyShopIso'); $randomProdBlock = MG::getSetting('randomProdBlock') == "true" ? true : false; if ($dataGroupProducts == null) { // Формируем список товаров со старой ценой. $sort = $randomProdBlock ? "RAND()" : "sort"; $saleProducts = $model->getListByUserFilter(MG::getSetting('countSaleProduct'), ' (p.old_price>0 || pv.old_price>0) and p.activity=1 ORDER BY ' . $sort . ' ASC'); $recommendProducts = $model->getListByUserFilter(MG::getSetting('countRecomProduct'), ' p.recommend=1 ORDER BY ' . $sort . ' ASC'); $newProducts = $model->getListByUserFilter(MG::getSetting('countNewProduct'), ' p.new=1 ORDER BY ' . $sort . ' ASC'); foreach ($saleProducts['catalogItems'] as &$item) { $imagesUrl = explode("|", $item['image_url']); $item["image_url"] = ""; if (!empty($imagesUrl[0])) { $item["image_url"] = $imagesUrl[0]; } $item['currency_iso'] = $item['currency_iso'] ? $item['currency_iso'] : $currencyShopIso; //$item['price'] *= $currencyRate[$item['currency_iso']]; $item['old_price'] = $item['old_price'] ? MG::priceCourse($item['old_price']) : 0; $item['price'] = MG::priceCourse($item['price_course']); if ($printCompareButton != 'true') { $item['actionCompare'] = ''; } if ($actionButton == 'actionBuy' && $item['count'] == 0) { $item['actionBuy'] = $item['actionView']; } } $dataGroupProducts['recommendProducts'] = $recommendProducts; $dataGroupProducts['newProducts'] = $newProducts; $dataGroupProducts['saleProducts'] = $saleProducts; Storage::save(md5('dataGroupProductsIndexConroller'), $dataGroupProducts); } $recommendProducts = $dataGroupProducts['recommendProducts']; $newProducts = $dataGroupProducts['newProducts']; $saleProducts = $dataGroupProducts['saleProducts']; $html = MG::get('pages')->getPageByUrl('index'); if (!empty($html)) { $html['html_content'] = MG::inlineEditor(PREFIX . 'page', "html_content", $html['id'], $html['html_content']); } else { $html['html_content'] = ''; } $this->data = array('newProducts' => !empty($newProducts['catalogItems']) ? $newProducts['catalogItems'] : array(), 'recommendProducts' => !empty($recommendProducts['catalogItems']) ? $recommendProducts['catalogItems'] : array(), 'saleProducts' => !empty($saleProducts['catalogItems']) ? $saleProducts['catalogItems'] : array(), 'titeCategory' => $html['meta_title'], 'cat_desc' => $html['html_content'], 'meta_title' => $html['meta_title'], 'meta_keywords' => $html['meta_keywords'], 'meta_desc' => $html['meta_desc'], 'currency' => $settings['currency'], 'actionButton' => $actionButton); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionImport() { $model = new Storage(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Storage'])) { if (!empty($_FILES)) { $tempFile = $_FILES['Storage']['tmp_name']['fileImport']; $fileTypes = array('xls', 'xlsx'); // File extensions $fileParts = pathinfo($_FILES['Storage']['name']['fileImport']); if (in_array(@$fileParts['extension'], $fileTypes)) { Yii::import('ext.heart.excel.EHeartExcel', true); EHeartExcel::init(); $inputFileType = PHPExcel_IOFactory::identify($tempFile); $objReader = PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($tempFile); $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true); $baseRow = 2; $inserted = 0; $read_status = false; while (!empty($sheetData[$baseRow]['A'])) { $read_status = true; //$storage_id= $sheetData[$baseRow]['A']; $curDate = $sheetData[$baseRow]['B']; $prod_id = $sheetData[$baseRow]['C']; $curCount = $sheetData[$baseRow]['D']; $model2 = new Storage(); //$model2->storage_id= $storage_id; $model2->curDate = $curDate; $model2->prod_id = $prod_id; $model2->curCount = $curCount; try { if ($model2->save()) { $inserted++; } } catch (Exception $e) { Yii::app()->user->setFlash('error', "{$e->getMessage()}"); //$this->refresh(); } $baseRow++; } Yii::app()->user->setFlash('success', $inserted . ' row inserted'); } else { Yii::app()->user->setFlash('warning', 'Wrong file type (xlsx, xls, and ods only)'); } } $this->render('admin', array('model' => $model)); } else { $this->render('admin', array('model' => $model)); } }
/** * Возвращает список товаров и пейджер для постраничной навигации. * @param int $countRows - количество возвращаемых записей для одной страницы. * @param boolean $mgadmin - откуда вызван метод, из публичной части или панели управления. * @param boolean $onlyActive - учитывать только активные продукты. * @return type */ public function getList($countRows = 20, $mgadmin = false, $onlyActive = false) { // Если не удалось получить текущую категорию. if (!$this->getCurrentCategory()) { echo 'Ошибка получения данных!'; exit; } // только для публичной части строим html для фильтров, а ели уже пришел запрос с нее, то получаем результат if (!$mgadmin) { $onlyInCount = false; // ищем все товары if (MG::getSetting('printProdNullRem') == "true") { $onlyInCount = true; // ищем только среди тех которые есть в наличии } $filterProduct = $this->filterPublic(true, $onlyInCount); MG::set('catalogfilter', $filterProduct['filterBarHtml']); // return array('catalogItems'=>null, 'pager'=>null, 'filterBarHtml'=>$filter->getHtmlFilter(true), 'userFilter' => $userFilter); // если пришел запрос с фильтра со страницы каталога и не используется плагин фильтров if (isset($_REQUEST['applyFilter'])) { $result = array(); if (!empty($filterProduct['userFilter'])) { // если при генерации фильтров был построен запрос // по входящим свойствам товара из гет запроса // то получим все товары именно по данному запросу, учитвая фильтрацию по характеристикам $result = $this->getListByUserFilter($countRows, $filterProduct['userFilter']); $result['filterBarHtml'] = $filterProduct['filterBarHtml']; } $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); } } // Страница. $page = URL::get("page"); $sql .= 'SELECT DISTINCT p.id, CONCAT(c.parent_url,c.url) as category_url, p.url as product_url, p.*, pv.product_id as variant_exist, rate,(p.price_course + p.price_course * (IFNULL(rate,0))) as `price_course` FROM `' . PREFIX . 'product` p LEFT JOIN `' . PREFIX . 'category` c ON c.id = p.cat_id LEFT JOIN `' . PREFIX . 'product_variant` pv ON p.id = pv.product_id LEFT JOIN ( SELECT pv.product_id, SUM( pv.count ) AS varcount FROM `' . PREFIX . 'product_variant` AS pv GROUP BY pv.product_id ) AS temp ON p.id = temp.product_id'; // FIND_IN_SET - учитывает товары, в настройках которых, // указано в каких категориях следует их покзывать. $this->currentCategory['id'] = $this->currentCategory['id'] ? $this->currentCategory['id'] : 0; if (MG::getSetting('productInSubcat') == 'true') { $filter = '(p.cat_id IN (' . DB::quote(implode(',', $this->categoryId), 1) . ') ' . 'or FIND_IN_SET(' . DB::quote($this->currentCategory['id'], 1) . ',p.`inside_cat`))'; } else { $filter = '(c.id IN (' . DB::quote($this->currentCategory['id'], 1) . ') ' . 'or FIND_IN_SET(' . DB::quote($this->currentCategory['id'], 1) . ',p.`inside_cat`))'; } if ($mgadmin) { $filter = ' (p.cat_id IN (' . DB::quote(implode(',', $this->categoryId), 1) . ') ' . 'or FIND_IN_SET(' . DB::quote($this->currentCategory['id'], 1) . ',p.`inside_cat`))'; if ($this->currentCategory['id'] == 0) { $filter = ' 1=1 '; } } // Запрос вернет общее кол-во продуктов в выбранной категории. $sql .= ' WHERE ' . $filter; if ($onlyActive) { $sql .= ' AND p.activity = 1'; } if (MG::getSetting('printProdNullRem') == "true" && !$mgadmin) { $sql .= " AND (temp.`varcount` > 0 OR temp.`varcount` < 0" . " OR p.count>0 OR p.count<0)"; } $orderBy = ' ORDER BY `sort` ASC '; if (FILTER_SORT != 'FILTER_SORT' && !$mgadmin) { $parts = explode('|', FILTER_SORT); $orderBy = ' ORDER BY `' . DB::quote($parts[0], 1) . '` ' . DB::quote($parts[1], 1); } $sql .= $orderBy; // в админке не используем кэш if (!$mgadmin) { $result = Storage::get(md5($sql . $page)); } if ($result == null) { $navigator = new Navigator($sql, $page, $countRows); //определяем класс $this->products = $navigator->getRowsSql(); // добавим к полученым товарам их свойства $this->products = $this->addPropertyToProduct($this->products); if ($mgadmin) { $this->pager = $navigator->getPager('forAjax'); } else { $this->pager = $navigator->getPager(); } $result = array('catalogItems' => $this->products, 'pager' => $this->pager, 'totalCountItems' => $navigator->getNumRowsSql()); Storage::save(md5($sql . $page), array('catalogItems' => $this->products, 'pager' => $this->pager, 'totalCountItems' => $navigator->getNumRowsSql())); } if (!empty($filterProduct['filterBarHtml'])) { $result['filterBarHtml'] = $filterProduct['filterBarHtml']; } $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); }
/** * Возвращает закэшированное горизонтальное меню категорий. */ public function getCategoriesHorHTML() { $result = Storage::get(md5('getCategoriesHorHTML')); if ($result == null) { $category = $this->getHierarchyCategory(); $result = MG::layoutManager('layout_horizontmenu', array('categories' => $category)); if (MG::getSetting("enabledSiteEditor") == "false") { Storage::save(md5('getCategoriesHorHTML'), $result); } } $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); }
// Iterate structure $body = ""; $attachments = array(); foreach ($structure as $structurePart) { $partFile = "{$tmpFile}-{$structurePart}"; $section = mailparse_msg_get_part($mp, $structurePart); $info = mailparse_msg_get_part_data($section); if (!in_array($info['content-type'], array('multipart/mixed', 'multipart/alternative'))) { // Get contents $part = mailparse_msg_get_part($mp, $structurePart); // Use NULL as callback to return as string and not to STDOUT. $contents = mailparse_msg_extract_part_file($part, $tmpFile, NULL); if (isset($info['disposition-filename'])) { // Attachment, store $name = iconv_mime_decode($info['disposition-filename']); $id = Storage::save($name, $contents); $attachments[] = $id; } else { if (!$body && $info['content-type'] == 'text/plain') { // Body part $body = trim(preg_replace('/-- [\\r\\n]+.*/s', '', $contents)); } } } } // Delete tmp file unlink($tmpFile); // Validate picture attachments $pictureAttachments = array(); foreach ($attachments as $storageId) { $finfo = @getimagesize(Storage::localFile($storageId));
function testStorage() { // test Storage - public API // store test.txt echo "saving test.txt with a crazy name\n"; $file_id = Storage::save('test.txt', 'O*Bc3wukygfsT@#($0876)$!@#*+_][.txt'); echo "resulting file_id = {$file_id}\n"; $file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($file_id)); $this->assertEquals($file->link_count, 0); $this->assertEquals($file->last_linked, NULL); $file_path = Storage::getPath($file_id); $file_url = Storage::getURL($file_id); echo "getPath({$file_id}) -> {$file_path}\n"; echo "getURL({$file_id}) -> {$file_url}\n"; $this->assertTrue(strpos($file_path, PA::$path . "/web/files/") === 0); $this->assertTrue(strpos($file_url, PA::$url) === 0); // link it in somewhere $link_id = Storage::link($file_id, array('role' => 'avatar', 'user' => 1)); echo "linked it in as avatar for user 1; link_id = {$link_id}\n"; $link = Dal::query_one_object("SELECT * FROM file_links WHERE link_id=?", array($link_id)); $this->assertEquals($link->file_id, $file_id); $file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($file_id)); $this->assertEquals($file->link_count, 1); $this->assertNotEquals($file->last_linked, NULL); // another file $child_file_id = Storage::save('test2.txt', 'this is the child file.jpg', 'throwaway', 'image/jpeg'); echo "child file: {$child_file_id}\n"; $child_file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($child_file_id)); $child_file_path = Storage::getPath($child_file_id); $child_file_url = Storage::getURL($child_file_id); echo "getPath({$child_file_id}) -> {$child_file_path}\n"; echo "getURL({$child_file_id}) -> {$child_file_url}\n"; $this->assertTrue(strpos($child_file_path, PA::$path . "/web/files/") === 0); $this->assertTrue(strpos($child_file_url, PA::$url) === 0); // link child file in as a thumbnail of first file $child_link_id = Storage::link($child_file_id, array('role' => 'thumb', 'file' => $file_id, 'dim' => '123x123')); echo "child link id: {$child_link_id}\n"; $child_link = Dal::query_one_object("SELECT * FROM file_links WHERE link_id=?", array($child_link_id)); $this->assertEquals($child_link->file_id, $child_file_id); $this->assertEquals($child_link->parent_file_id, $file_id); $child_file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($child_file_id)); $this->assertEquals($child_file->link_count, 1); $this->assertNotEquals($child_file->last_linked, NULL); // this should fail (missing role) try { Storage::link($file_id, array("user" => 1)); $this->fail("Expected exception"); } catch (PAException $e) { $this->assertEquals($e->getCode(), BAD_PARAMETER); } // this should fail (missing network) try { Storage::link($file_id, array("role" => "header", "group" => 42)); $this->fail("Expected exception"); } catch (PAException $e) { $this->assertEquals($e->getCode(), BAD_PARAMETER); } // this should fail (network not valid) try { Storage::link($file_id, array("role" => "thumb", "network" => 1, "file" => $file_id, "dim" => "123x123")); $this->fail("Expected exception"); } catch (PAException $e) { $this->assertEquals($e->getCode(), BAD_PARAMETER); } // this should fail (parent_file_id == file_id) try { $link_id = Storage::link($file_id, array("role" => "thumb", "file" => $file_id, "dim" => "123x123")); $this->fail("Expected exception"); } catch (PAException $e) { $this->assertEquals($e->getCode(), BAD_PARAMETER); } // Now unlink the two files we just created ... // unlink the first - but don't delete it Storage::unlink($file_id, $link_id, FALSE); // make sure it's gone $this->assertEquals(Dal::query_one("SELECT * FROM file_links WHERE link_id=?", array($link_id)), NULL); // the file should still be there, with zero links, though $file = Dal::query_one("SELECT * FROM files WHERE file_id=?", array($file_id)); $this->assertNotEquals($file, NULL); $this->assertEquals($file->link_count, 0); // try a bad unlink operation try { Storage::unlink($file_id, $child_link_id); $this->fail("Expected exception"); } catch (PAException $e) { $this->assertEquals($e->getCode(), FILE_NOT_FOUND); } // unlink and delete the second Storage::unlink($child_file_id, $child_link_id); // make sure it's gone $this->assertEquals(Dal::query_one("SELECT * FROM file_links WHERE link_id=?", array($child_link_id)), NULL); // and make sure the file is gone too $this->assertEquals(Dal::query_one("SELECT * FROM files WHERE file_id=?", array($child_file)), NULL); // reap unlinked files (immediately - no grace period) Storage::cleanupFiles(-1, -1); // make sure the first file is now gone $this->assertEquals(Dal::query_one("SELECT * FROM files WHERE file_id=?", array($file_id)), NULL); }