Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- session_start();
- class Content{
- const DB_NAME = "seven"; //name of db
- const DB_USER = "trim";
- const DB_PASS = "12345";
- private static $_db;
- private $_errMsg;
- const FILENAME = 'order.txt'; //order
- const ALL_ITEMS = 'All_db.txt'; //All items of db
- public function __construct(){
- if(!self::$_db){
- self::$_db=mysql_connect("localhost", self::DB_USER, self::DB_PASS);// or die(mysql_error());
- mysql_select_db(self::DB_NAME, self::$_db);
- }else{}
- }
- public function __destruct(){
- $res = mysql_close(self::$_db);
- if(!$res){}//create some err handler
- else{
- self::$_db=NULL;
- }
- }
- public function returnSomeSmallTableInArray($tableName){
- $sql = "SELECT * FROM ".$tableName;
- $res = mysql_query($sql, self::$_db);
- if(!$res){//for this errors I add new table to DB "erors". There will be id, date, userId, msg, and boolian true or false (fixed or no). (1 or 0)
- $_SESSION['msg_date'] = time();
- $this->_errMsg =$this->errorHandler("Some error in sql_query. In public function returnSomeSmallTableInArray class Content "); //sends an error to myAdmin page
- return $this->_errMsg;
- }
- $myrow = mysql_fetch_array($res);
- if(!$myrow){
- $_SESSION['msg_date'] = time();
- $this->_errMsg = $this->errorHandler("Some error in $myrow = mysql_fetch_array. In public function returnSomeSmallTableInArray class Content ");
- //sends an error to myAdmin page
- return $this->_errMsg;
- }else{
- $reorganizedMyrow = array();
- $key=0;
- do{
- $key++;
- $reorganizedMyrow[$key]=$myrow[$tableName];
- }while($myrow = mysql_fetch_array($res));
- return $reorganizedMyrow;
- }
- }// function returnSomeSmallTableInArray
- private function checkFile($date){
- $path_to_90_directory = '../../_images/';//папка, куда будет загружаться начальная картинка и ее сжатая копия
- if($_FILES['file']['size'] <= 2097152 and $_FILES['file']['size'] != 0 and $_FILES['file']['tmp_name'] != NONE){//1M =1024Kb 1Kb = 1024b значит 1M = 1048576b
- if(preg_match('/[.](JPG)|(jpg)|(JPEG)|(jpeg)|(gif)|(GIF)|(png)|(PNG)$/',$_FILES['file']['name'])){ //проверка формата исходного изображения
- $filename = $_FILES['file']['name'];
- $source = $_FILES['file']['tmp_name'];
- $target = $path_to_90_directory . $filename;
- //bytes // in php.ini upload_max_filesize = 2M
- move_uploaded_file($source, $target);//загрузка оригинала в папку $path_to_90_directory
- if(preg_match('/[.](GIF)|(gif)$/', $filename)) {
- $im = imagecreatefromgif($path_to_90_directory.$filename) ; //если оригинал был в формате gif, то создаем изображение в этом же формате.
- }
- if(preg_match('/[.](PNG)|(png)$/', $filename)) {
- $im = imagecreatefrompng($path_to_90_directory.$filename) ;//если оригинал был в формате png, то создаем изображение в этом же формате.
- }
- if(preg_match('/[.](JPG)|(jpg)|(jpeg)|(JPEG)$/', $filename)) {
- $im = imagecreatefromjpeg($path_to_90_directory.$filename); //если оригинал был в формате jpg, то создаем изображение в этом же формате.
- }
- // Создание квадрата 90x90<img src="_User/avatars/net-avatara.jpg" width="44" height="44">
- // dest - результирующее изображение
- // w - ширина изображения
- // ratio - коэффициент пропорциональности
- $w = 135;
- $h = 135; // квадратная 90x90. Можно поставить и другой размер.
- // создаём исходное изображение на основе
- // исходного файла и определяем его размеры
- $w_src = imagesx($im); //вычисляем ширину
- $h_src = imagesy($im); //вычисляем высоту изображения
- // создаём пустую квадратную картинку
- // важно именно truecolor!, иначе будем иметь 8-битный результат
- $dest = imagecreatetruecolor($w,$h);
- // вырезаем квадратную серединку по x, если фото горизонтальное
- if ($w_src>$h_src){
- imagecopyresampled($dest, $im, 0, 0,
- round((max($w_src,$h_src)-min($w_src,$h_src))/2),
- 0, $w, $w, min($w_src,$h_src), min($w_src,$h_src));
- }
- // вырезаем квадратную верхушку по y,
- // если фото вертикальное (хотя можно тоже серединку)
- if ($w_src<$h_src){
- imagecopyresampled($dest, $im, 0, 0, 0, 0, $w, $h,
- min($w_src,$h_src), min($w_src,$h_src));
- }
- // квадратная картинка масштабируется без вырезок
- if ($w_src==$h_src){
- imagecopyresampled($dest, $im, 0, 0, 0, 0, $w, $h, $w_src, $w_src);
- }
- imagejpeg($dest, $path_to_90_directory.$date.".jpg");//сохраняем изображение формата jpg в нужную папку, именем будет текущее время.
- $path_to_90_directory = '_images/';
- $item_img = $path_to_90_directory.$date.".jpg";//заносим в переменную путь до аватара.
- $path_to_90_directory = '../../_images/'; // valid pass from here to file, to unlink it
- $delfull = $path_to_90_directory.$filename;
- unlink ($delfull);//удаляем оригинал загруженного изображения, он нам больше не нужен. Задачей было - получить миниатюру.
- return $item_img; // возврат ссылки на аватар
- }else{//в случае несоответствия формата, выдаем соответствующее сообщение
- $_SESSION['msg_date'] = time();
- $this->_errMsg = "<a href='#'>Image must be in <strong>JPG,GIF or PNG</strong> format</a>";
- return $this->_errMsg;
- }
- }else{
- $this->_errMsg = "<a href='#'>Image size should not exceed 2 MB</a>";
- $_SESSION['msg_date'] = time();
- return $this->_errMsg;
- }
- }
- function saveNewContentItem($type, $brand, $model, $price, $description , $imgLink){
- $date = time();
- $imgLink = $this->checkfile($date);
- if(!preg_match('/[.](jpg)$/',$imgLink)){
- $_SESSION['msg_date'] = time();
- return $imgLink; //will be error msg in
- }
- if(isset($type) and isset($brand) and isset($price) and isset($model) and isset($description) and isset($imgLink)){
- $sql="INSERT INTO content (price, type, brand, model, description, imgLink)
- VALUES ('$price', '$type', '$brand', '$model', '$description', '$imgLink')";
- $res = mysql_query($sql, self::$_db);
- if(!$res){
- $_SESSION['msg_date'] = time();
- $this->_errMsg = $this->errorHandler("Error in Class_content.php / Error adding new file");
- return $this->_errMsg;
- }else{
- $_SESSION['msg_date'] = time();
- $this->_errMsg = "<a href='#'>You have add new file.</a>";
- return $this->_errMsg;
- }
- }else{
- $_SESSION['msg_date'] = time();
- $this->_errMsg = "<a href='#'>Not all of the field was filled.</a>";
- return $this->_errMsg;
- }
- }
- public function getOneItem($id){
- $sql = "SELECT id, type, price, brand, model, description, imgLink FROM content WHERE id='$id'";
- $res=mysql_query($sql, self::$_db);
- if(!$res){
- $this->_errMsg=$this->errorHandler("Error in".__LINE__."Class_content.php", "We did not find anything. Click on this message to let us know about it. ");
- echo $this->_errMsg;
- }else{
- $myrow = mysql_fetch_array($res);
- if(!$myrow){
- $this->_errMsg=$this->errorHandler("Error in".__LINE__."Class_content.php", "We did not find anything. Click on this message to let us know about it. ");
- echo $this->_errMsg;
- }else{
- $type = $myrow['type'];
- $sql_two="SELECT type FROM type WHERE id = '$type'";
- $res_two=mysql_query($sql_two, self::$_db);
- $myrow_two=mysql_fetch_array($res_two);
- $brand=$myrow['brand'];
- $sql_thre="SELECT brand, id FROM brand WHERE id='$brand'";
- $res_thre=mysql_query($sql_thre, self::$_db);
- $myrow_thre=mysql_fetch_array($res_thre);
- printf("","");
- }
- }
- }//public function getOneItem($id){
- public function getItemsForBusket($where){
- $sql = "SELECT id, type, price, brand, model, description, imgLink FROM content WHERE ".$where;
- $res = mysql_query($sql, self::$_db);
- if(!$res){
- echo "Error1";
- exit();
- }else{
- $myrow = mysql_fetch_array($res);
- if(!$myrow){
- echo "Error2";
- exit();
- }
- }
- echo "<div class='th'>
- <span style='width:115px;padding-left:6px;'>Товар </span>
- <span style='width:237px;'>Детали </span>
- <span style='width:78px;'>Кол-во".$_SESSION['count']."</span>
- <span style='width:100px;'>Цена за шт. </span>
- <span style='width:90px;'>Всего </span>
- </div>";
- $total=0;
- $inc=0;
- do{
- $inc++;
- $idy = $myrow['id'];
- $type = $myrow['type'];
- $sql_two="SELECT type FROM type WHERE id = '$type'";
- $res_two=mysql_query($sql_two, self::$_db);
- $myrow_two=mysql_fetch_array($res_two);
- $brand=$myrow['brand'];
- $sql_thre="SELECT brand, id FROM brand WHERE id='$brand'";
- $res_thre=mysql_query($sql_thre, self::$_db);
- $myrow_thre=mysql_fetch_array($res_thre);
- printf("
- <div class='td' >
- <div class='td1' style='background-image:none'><img src='%s' width = '50' height = '50'></div>
- <div class='td2'>
- <div class='b_h'>%s</div>
- <div class='b_t'>Арт.: <span>234355</span> Бренд: <span>%s</span> </div>
- <div class='opus_p'>%s</div>
- </div>
- <div class='td3'><input value='%s' name='' class='in_count' onfocus='this.value = '';' onblur='if (this.value == '' || this.value == ' ') this.value='%s';'></div>
- <div class='td4' id='to%s'>%s</div>
- <div class='td5' id='tt%s'>%s</div>
- <div class='td6'><a class='delete' href='busket1.php?id=%s'> Удалить</a></div>
- <div class='clr'></div>
- </div>
- ",
- $myrow['imgLink'], $myrow['model'], $myrow_thre['brand'], $myrow['description'], $_SESSION['item_ids'][$idy],
- $_SESSION['item_ids'][$idy], $inc, $myrow['price'], $inc, $myrow['price']*$_SESSION['item_ids'][$idy], $idy);
- $total += $myrow['price']*$_SESSION['item_ids'][$idy];
- echo "<div class='busket_price' id='%s'>Общая стоимость <div class='span_busket_price' id='th$inc'>$total</div></div>";
- }while($myrow = mysql_fetch_array($res));
- echo "<p style='display: none' id='hiden_value'>$inc</div>";
- }//public function getItemsForBusket($were){
- function getSortIterator(){
- $sql = "SELECT id, type, price, brand, model, description, imgLink FROM content ORDER BY id DESC";
- $res=mysql_query($sql, self::$_db);
- if(!$res){
- $this->_errMsg=$this->errorHandler("Error in".__LINE__."Class_content.php", "We did not find anything. Click on this message to let us know about it. ");
- echo $this->_errMsg;
- }else{
- $myrow = mysql_fetch_array($res);
- if(!$myrow){
- $this->_errMsg=$this->errorHandler("Error in".__LINE__."Class_content.php", "We did not find anything. Click on this message to let us know about it. ");
- echo $this->_errMsg;
- }else{
- do{
- $type = $myrow['type'];
- $sql_two="SELECT type FROM type WHERE id = '$type'";
- $res_two=mysql_query($sql_two, self::$_db);
- $myrow_two=mysql_fetch_array($res_two);
- $brand=$myrow['brand'];
- $sql_thre="SELECT brand, id FROM brand WHERE id='$brand'";
- $res_thre=mysql_query($sql_thre, self::$_db);
- $myrow_thre=mysql_fetch_array($res_thre);
- if($temp%2==0){
- $temp='pro no_margin_right';
- }else{
- $temp='pro';
- }
- printf("<div class='$temp'>
- <a class='busket'href='%s'>В КОРЗИНУ</a>
- <div class='left_pro'>
- <div class='pro_h'><a href='product.php?id=%s'>%s</a></div>
- <div class='brand_name'>Бренд: <a href='all_brand_items.php?id=%s'>%s</a></div>
- <div class='pro_desc'>%s</div>
- <div class='pro_value'>%s</div>
- </div>
- <div class='pro_img'><a href='product.php?id=%s' style='background-image:none'><img src='%s'></a></div>
- <div class='clr'></div>
- <hr />
- </div>",
- $myrow['id'], $myrow['id'], $myrow_thre['model'], $myrow_thre['id'], $myrow_thre['brand'], $myrow['description'], $myrow['price'], $myrow['id'], $myrow['imgLink']
- );
- }while($myrow = mysql_fetch_array($res));
- }
- }
- }
- function getOrder($query, $text){
- $sql = "SELECT id, type, price, brand, model, description, imgLink FROM content WHERE ".$query;
- $res = mysql_query($sql, self::$_db);
- $myrow = mysql_fetch_array($res);
- // Откроем соединение с файлом
- $f = fopen(self::FILENAME, 'a');
- $str = "Text from user - ".$text . "\r\n";
- fputs($f, $str);
- // в цикле запись всех заказов в файл
- do{
- // Сформируем строку для записи в файл
- $str = 'id of item - '.$myrow['id']. ', ' . 'Model - '. $myrow['model'] . ', ' . 'price - '. $myrow['price'] . "\r\n";
- if(is_resource($f)){
- // Запишем строку в файл и закроем соединение
- fputs($f, $str);
- }
- }while($myrow = mysql_fetch_array($res));
- fclose($f);
- }
- function getAllItemsInFile(){
- $sql = "SELECT id, type, price, brand, model, description, imgLink FROM content";
- $res = mysql_query($sql, self::$_db);
- $myrow = mysql_fetch_array($res);
- $f = fopen(self::ALL_ITEMS, 'a');
- $str = self::DB_NAME." ".self::DB_USER." ".self::DB_PASS. " All items of this db :\r\n";
- fputs($f, $str);
- do{
- $type = $myrow['type'];
- $sql_two="SELECT type FROM type WHERE id = '$type'";
- $res_two=mysql_query($sql_two, self::$_db);
- $myrow_two=mysql_fetch_array($res_two);
- $brand=$myrow['brand'];
- $sql_thre="SELECT brand, id FROM brand WHERE id='$brand'";
- $res_thre=mysql_query($sql_thre, self::$_db);
- $myrow_thre=mysql_fetch_array($res_thre);
- // Сформируем строку для записи в файл
- $str = 'id - '.$myrow['id']. ', '
- . 'price - '. $myrow['price']. ', '
- . 'type - '. $myrow_two['type']. ', '
- . 'brand - '. $myrow_thre['brand']. ', '
- . 'model - '. $myrow['model']. ', '
- . 'description - '. $myrow['description']. ', '
- . 'link to img - '. $myrow['imgLink'] . "\r\n";
- if(is_resource($f)){
- // Запишем строку в файл и закроем соединение
- fputs($f, $str);
- }
- }while($myrow = mysql_fetch_array($res));
- fclose($f);
- }
- function getXmlToDB(){
- $u_xml = $_FILES['xml']['tmp_name']; //get the xml-file adres
- $xml=file_get_contents($u_xml);
- $items = new SimpleXMLElement($xml);
- for($i=0, $count = $items->count(); $i<$count; $i++){ // $count = $items->count() returns the count of items indexes
- $price = $items->item[$i]->price;
- $type = $items->item[$i]->type;
- $brand = $items->item[$i]->brand;
- $model = $items->item[$i]->model;
- $description = $items->item[$i]->description;
- $imgLink = $items->item[$i]->imgLink;
- $res = mysql_query("INSERT INTO content (price, type, brand, model, description, imgLink)
- VALUES ('$price', '$type', '$brand', '$model', '$description', '$imgLink')", self::$_db);
- if(!$res){
- $this->_errMsg = "Error while inserting new items";
- return $this->_errMsg;
- }
- }
- if($this->_errMsg !=="Error while inserting new items from XML file"){
- $this->_errMsg = "Upload was successful";
- return $this->_errMsg;
- }
- }
- function getAll(){
- }
- function deletePost($id){
- }
- function getUserContent($UserId){
- }
- function clearData($data){
- $res = stripslashes(htmlspecialchars(trim($data)));
- return $res;
- }
- public function AddNewErr($msg , $date, $userId, $fixed){
- $sql = "INSERT INTO errors (date, userId, msg, fixed) VALUES ('$date', '$userId', '$msg', '$fixed')";
- if(isset($msg) and isset($date) and isset($userId) and isset($fixed)){
- $res = mysql_query($sql, $this->_db);
- if(!$res){
- $_SESSION['msg_date'] = time();
- $this->_errMsg = $this->errorHandler("Error in Class_content.php / public function AddNewErr($msg , $date, $userId, $fixed)".__LINE__);
- return $this->_errMsg;
- }
- }
- }
- //////////////////////////////////////////////////************privates****************//////////////////////////////////////////////////////////////////
- private function errorHandler($error, $msg=1){ // forms a line with an error
- $date = time();
- $userId = $_SESSION['User_id'];
- $fixed = "no";
- $error = "msg=".$error."&date".$date."&userId".$userId."&fixed=".$fixed;
- if($msg==1){
- $msg = "<a href='../_admin/send_error_from_user.php?".$error."><p id='errorHandlerMsg'>Sorry there are an error during this query . Click on the link to Report it to admin</p></a>";
- return $msg;
- }else{
- $msg = "<a href='../_admin/send_error_from_user.php?".$error."><p id='errorHandlerMsg'>".$msg."</p></a>";
- return $msg;
- }
- }
- }
Add Comment
Please, Sign In to add comment