예제 #1
0
파일: news.php 프로젝트: WinGood/24karcher
 /**
  * Добавляет новость в базу данных.
  *
  * @param array $array массив с данными о новости.
  * @return bool|int в случае успеха возвращает id добавленной новости.
  */
 public function addNews($array)
 {
     unset($array['id']);
     $result = array();
     $array['url'] = empty($array['url']) ? MG::translitIt($array['title']) : $array['url'];
     if (strlen($array['url']) > 60) {
         $array['url'] = substr($array['url'], 0, 60);
     }
     // Исключает дублирование.
     $dublicatUrl = false;
     $tempArray = $this->getNewsByUrl($array['url']);
     if (!empty($tempArray)) {
         $dublicatUrl = true;
     }
     if (DB::buildQuery('INSERT INTO `mpl_news` SET add_date=now(), ', $array)) {
         $id = DB::insertId();
         // Если url дублируется, то дописываем к нему id новости.
         if ($dublicatUrl) {
             $this->updateNews(array('id' => $id, 'url' => $array['url'] . '_' . $id));
         }
         $array['id'] = $id;
         $result = $array;
     }
     return $result;
 }
예제 #2
0
파일: import.php 프로젝트: nellka/mebel
 /**
  * Парсит путь категории возвращает набор категорий.
  * @param type $path - список категорий через /
  */
 public function parseCategoryPath($path)
 {
     $i = 1;
     $categories = array();
     if (!$path) {
         return $categories;
     }
     $parent = $path;
     $parentTranslit = MG::translitIt($parent, 1);
     $parentTranslit = URL::prepareUrl($parentTranslit);
     $categories[$parent]['title'] = URL::parsePageUrl($parent);
     $categories[$parent]['url'] = URL::parsePageUrl($parentTranslit);
     $categories[$parent]['parent_url'] = URL::parseParentUrl($parentTranslit);
     $categories[$parent]['parent'] = 0;
     while ($parent != '/') {
         $parent = URL::parseParentUrl($parent);
         $parentTranslit = MG::translitIt($parent, 1);
         $parentTranslit = URL::prepareUrl($parentTranslit);
         if ($parent != '/') {
             $categories[$parent]['title'] = URL::parsePageUrl($parent);
             $categories[$parent]['url'] = URL::parsePageUrl($parentTranslit);
             $categories[$parent]['parent_url'] = URL::parseParentUrl($parentTranslit);
             $categories[$parent]['parent_url'] = $categories[$parent]['parent_url'] != '/' ? $categories[$parent]['parent_url'] : '';
             $categories[$parent]['parent'] = 0;
         }
     }
     $categories = array_reverse($categories);
     return $categories;
 }
예제 #3
0
파일: product.php 프로젝트: nellka/mebel
 /**
  * Добавляет товар в базу данных. 
  * @param array $array массив с данными о товаре.
  * @return bool|int в случае успеха возвращает id добавленного товара.
  */
 public function addProduct($array, $clone = false)
 {
     if (empty($array['title'])) {
         return false;
     }
     $userProperty = $array['userProperty'];
     $variants = !empty($array['variants']) ? $array['variants'] : array();
     // варианты товара
     unset($array['userProperty']);
     unset($array['variants']);
     unset($array['id']);
     $result = array();
     $array['url'] = empty($array['url']) ? MG::translitIt($array['title']) : $array['url'];
     $maskField = array('title', 'meta_title', 'meta_keywords', 'meta_desc', 'image_title', 'image_alt');
     foreach ($array as $k => $v) {
         if (in_array($k, $maskField)) {
             $v = htmlspecialchars_decode($v);
             $array[$k] = htmlspecialchars($v);
         }
     }
     if (!empty($array['url'])) {
         $array['url'] = URL::prepareUrl($array['url']);
     }
     // Исключает дублирование.
     $dublicatUrl = false;
     $tempArray = $this->getProductByUrl($array['url']);
     if (!empty($tempArray)) {
         $dublicatUrl = true;
     }
     if (DB::buildQuery('INSERT INTO `' . PREFIX . 'product` SET ', $array)) {
         $id = DB::insertId();
         // Если url дублируется, то дописываем к нему id продукта.
         if ($dublicatUrl) {
             $this->updateProduct(array('id' => $id, 'url' => $array['url'] . '_' . $id, 'sort' => $id));
         } else {
             $this->updateProduct(array('id' => $id, 'url' => $array['url'], 'sort' => $id));
         }
         $array['id'] = $id;
         $array['userProperty'] = $userProperty;
         $userProp = array();
         if ($clone) {
             if (!empty($userProperty)) {
                 foreach ($userProperty as $property) {
                     $userProp[$property['property_id']] = $property['value'];
                     if (!empty($property['product_margin'])) {
                         $userProp["margin_" . $property['property_id']] = $property['product_margin'];
                     }
                 }
                 $userProperty = $userProp;
             }
         }
         if (!empty($userProperty)) {
             $this->saveUserProperty($userProperty, $id);
         }
         // Обновляем и добавляем варианты продукта.
         $this->saveVariants($variants, $id);
         $variants = $this->getVariants($id);
         foreach ($variants as $variant) {
             $array['variants'][] = $variant;
         }
         $tempProd = $this->getProduct($id);
         $array['category_url'] = $tempProd['category_url'];
         $array['product_url'] = $tempProd['product_url'];
         $result = $array;
     }
     $this->updatePriceCourse($currencyShopIso, array($result['id']));
     $args = func_get_args();
     return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args);
 }
예제 #4
0
 /**
  * Создание новой категории.
  * @param $category - категория.
  */
 function newCategory($category)
 {
     $url = URL::prepareUrl(MG::translitIt($category['name'], 1));
     $parent_url = MG::get('category')->getParentUrl($category['parent_id']);
     $parent = URL::prepareUrl(MG::translitIt($category['parentname'], 1));
     $data = array('title' => $category['name'], 'url' => str_replace(array('/', '\\'), '-', $url), 'parent' => $category['parent_id'], 'html_content' => $category['description'], 'meta_title' => $category['name'], 'meta_keywords' => $category['name'], 'meta_desc' => MG::textMore($category['description'], 157), 'invisible' => 0, 'parent_url' => $parent_url, '1c_id' => $category['1c_id']);
     $res = DB::query('SELECT *
   FROM `' . PREFIX . 'category`
   WHERE `1c_id`=' . DB::quote($category['1c_id']));
     if ($row = DB::fetchAssoc($res)) {
         DB::query('
     UPDATE `' . PREFIX . 'category`
     SET ' . DB::buildPartQuery($data) . '
     WHERE `1c_id`=' . DB::quote($category['1c_id']));
         return $row['id'];
     } else {
         $data = MG::get('category')->addCategory($data);
         return $data['id'];
     }
     return 0;
 }
예제 #5
0
파일: upload.php 프로젝트: nellka/mebel
 /**
  * Загружает картинку от пользователей с публичной части сайта на сервер 
  * @param string $subDir - имя каталога куда будет загружено изображение 
  * @return boolean
  */
 public function uploadImage($subDir = '')
 {
     $validFormats = array('jpeg', 'jpg', 'png', 'gif');
     if (isset($_POST) && 'POST' == $_SERVER['REQUEST_METHOD']) {
         if (!empty($_FILES['upload'])) {
             $imageinfo = getimagesize($_FILES['upload']['tmp_name']);
             $file_array = $_FILES['upload'];
         } elseif (!empty($_FILES['logo'])) {
             $imageinfo = getimagesize($_FILES['logo']['tmp_name']);
             $file_array = $_FILES['logo'];
         }
         $name = $file_array['name'];
         $size = $file_array['size'];
         $type = $file_array['type'];
         if (strlen($name)) {
             $fullName = explode('.', $name);
             $ext = array_pop($fullName);
             $name = implode('.', $fullName);
             // проверка соответствмя расширения с разрешенными,
             if (in_array(strtolower($ext), $validFormats)) {
                 // проверка типа файла и  на количество типов
                 if (strpos($type, 'image') !== false) {
                     if ($imageinfo['mime'] == 'image/gif' || $imageinfo['mime'] == 'image/jpeg' || $imageinfo['mime'] == 'image/jpg' || $imageinfo['mime'] == 'image/png') {
                         if (substr_count($type, '/') <= 1) {
                             // проверка на установелнный размер файла и переименование латинским написанием
                             if ($size < 1024 * 2 * 1024 && !empty($file_array['tmp_name'])) {
                                 //$file_array['tmp_name'] будет пустым если размер загруженного файла превышает размер установленный параметром upload_max_filesize в php.ini
                                 $name = str_replace(" ", "-", $name);
                                 $name = MG::translitIt($name);
                                 $actualImageName = $name . "." . $ext;
                                 if (file_exists('uploads/' . $subDir . $name . "." . $ext)) {
                                     $actualImageName = $name . time() . "." . $ext;
                                 }
                                 $tmp = $file_array['tmp_name'];
                                 // пересохранение с помощью GD
                                 if ($this->resavingImageFromPublic($actualImageName, $tmp, $dirUpload = 'uploads/' . $subDir)) {
                                     return SITE . '/' . $dirUpload . $actualImageName;
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return false;
 }
예제 #6
0
 /**
  * Save uploaded files
  *
  * @param  array
  * @return array
  * @author Dmitry (dio) Levashov
  **/
 protected function upload($args)
 {
     $target = $args['target'];
     $volume = $this->volume($target);
     $files = isset($args['FILES']['upload']) && is_array($args['FILES']['upload']) ? $args['FILES']['upload'] : array();
     $result = array('added' => array(), 'header' => empty($args['html']) ? false : 'Content-Type: text/html; charset=utf-8');
     $paths = $args['upload_path'] ? $args['upload_path'] : array();
     if (!$volume) {
         return array('error' => $this->error(self::ERROR_UPLOAD, self::ERROR_TRGDIR_NOT_FOUND, '#' . $target), 'header' => $header);
     }
     $non_uploads = array();
     if (empty($files)) {
         if (isset($args['upload']) && is_array($args['upload'])) {
             foreach ($args['upload'] as $i => $url) {
                 // check is data:
                 if (substr($url, 0, 5) === 'data:') {
                     list($data, $args['name'][$i]) = $this->parse_data_scheme($url, $volume->getMimeTable());
                 } else {
                     $data = $this->get_remote_contents($url);
                 }
                 if ($data) {
                     $_name = isset($args['name'][$i]) ? $args['name'][$i] : preg_replace('~^.*?([^/#?]+)(?:\\?.*)?(?:#.*)?$~', '$1', rawurldecode($url));
                     if ($_name) {
                         $_ext = '';
                         if (preg_match('/(\\.[a-z0-9]{1,7})$/', $_name, $_match)) {
                             $_ext = $_match[1];
                         }
                         $tmpfname = DIRECTORY_SEPARATOR . 'ELF_FATCH_' . md5($url . microtime()) . $_ext;
                         $tmpPath = sys_get_temp_dir();
                         if (!@touch($tmpPath . $tmpfname)) {
                             if ($tmpPath = $volume->getTempPath()) {
                                 $tmpfname = $tmpPath . $tmpfname;
                             } else {
                                 $tmpfname = '';
                             }
                         } else {
                             $tmpfname = $tmpPath . $tmpfname;
                         }
                         if ($tmpfname) {
                             if (file_put_contents($tmpfname, $data)) {
                                 $non_uploads[$tmpfname] = true;
                                 $files['tmp_name'][$i] = $tmpfname;
                                 $files['name'][$i] = preg_replace('/[\\/\\?*:|"<>]/', '_', $_name);
                                 $files['error'][$i] = 0;
                             } else {
                                 @unlink($tmpfname);
                             }
                         }
                     }
                 }
             }
         }
         if (empty($files)) {
             return array('error' => $this->error(self::ERROR_UPLOAD, self::ERROR_UPLOAD_NO_FILES), 'header' => $header);
         }
     }
     foreach ($files['name'] as $i => $name) {
         $name = MG::translitIt($name);
         if (($error = $files['error'][$i]) > 0) {
             $result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $name, $error == UPLOAD_ERR_INI_SIZE || $error == UPLOAD_ERR_FORM_SIZE ? self::ERROR_UPLOAD_FILE_SIZE : self::ERROR_UPLOAD_TRANSFER);
             $this->uploadDebug = 'Upload error code: ' . $error;
             break;
         }
         $tmpname = $files['tmp_name'][$i];
         $path = $paths && !empty($paths[$i]) ? $paths[$i] : '';
         // do hook function 'upload.presave'
         if (!empty($this->listeners['upload.presave'])) {
             foreach ($this->listeners['upload.presave'] as $handler) {
                 call_user_func_array($handler, array(&$path, &$name, $tmpname, $this, $volume));
             }
         }
         if (($fp = fopen($tmpname, 'rb')) == false) {
             $result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $name, self::ERROR_UPLOAD_TRANSFER);
             $this->uploadDebug = 'Upload error: unable open tmp file';
             if (!is_uploaded_file($tmpname)) {
                 if (@unlink($tmpname)) {
                     unset($non_uploads[$tmpfname]);
                 }
                 continue;
             }
             break;
         }
         if ($path) {
             $_target = $volume->getUploadTaget($target, $path, $result);
         } else {
             $_target = $target;
         }
         if (!$_target || ($file = $volume->upload($fp, $_target, $name, $tmpname)) === false) {
             $result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $name, $volume->error());
             fclose($fp);
             if (!is_uploaded_file($tmpname)) {
                 if (@unlink($tmpname)) {
                     unset($non_uploads[$tmpfname]);
                 }
                 continue;
             }
             break;
         }
         fclose($fp);
         if (!is_uploaded_file($tmpname) && @unlink($tmpname)) {
             unset($non_uploads[$tmpfname]);
         }
         $result['added'][] = $file;
     }
     if ($non_uploads) {
         foreach (array_keys($non_uploads) as $_temp) {
             @unlink($_temp);
         }
     }
     return $result;
 }