Guest User

Untitled

a guest
Feb 9th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.65 KB | None | 0 0
  1. <?php
  2. session_start();
  3. class Content{
  4. const DB_NAME = "seven"; //name of db
  5. const DB_USER = "trim";
  6. const DB_PASS = "12345";
  7. private static $_db;
  8. private $_errMsg;
  9. const FILENAME = 'order.txt'; //order
  10. const ALL_ITEMS = 'All_db.txt'; //All items of db
  11.  
  12.  
  13.  
  14.  
  15. public function __construct(){
  16. if(!self::$_db){
  17. self::$_db=mysql_connect("localhost", self::DB_USER, self::DB_PASS);// or die(mysql_error());
  18. mysql_select_db(self::DB_NAME, self::$_db);
  19. }else{}
  20. }
  21.  
  22. public function __destruct(){
  23. $res = mysql_close(self::$_db);
  24. if(!$res){}//create some err handler
  25. else{
  26. self::$_db=NULL;
  27. }
  28. }
  29.  
  30.  
  31. public function returnSomeSmallTableInArray($tableName){
  32. $sql = "SELECT * FROM ".$tableName;
  33. $res = mysql_query($sql, self::$_db);
  34. 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)
  35. $_SESSION['msg_date'] = time();
  36. $this->_errMsg =$this->errorHandler("Some error in sql_query. In public function returnSomeSmallTableInArray class Content "); //sends an error to myAdmin page
  37. return $this->_errMsg;
  38. }
  39. $myrow = mysql_fetch_array($res);
  40. if(!$myrow){
  41. $_SESSION['msg_date'] = time();
  42. $this->_errMsg = $this->errorHandler("Some error in $myrow = mysql_fetch_array. In public function returnSomeSmallTableInArray class Content ");
  43. //sends an error to myAdmin page
  44. return $this->_errMsg;
  45. }else{
  46. $reorganizedMyrow = array();
  47. $key=0;
  48. do{
  49. $key++;
  50. $reorganizedMyrow[$key]=$myrow[$tableName];
  51. }while($myrow = mysql_fetch_array($res));
  52. return $reorganizedMyrow;
  53. }
  54. }// function returnSomeSmallTableInArray
  55.  
  56.  
  57.  
  58. private function checkFile($date){
  59. $path_to_90_directory = '../../_images/';//папка, куда будет загружаться начальная картинка и ее сжатая копия
  60. if($_FILES['file']['size'] <= 2097152 and $_FILES['file']['size'] != 0 and $_FILES['file']['tmp_name'] != NONE){//1M =1024Kb 1Kb = 1024b значит 1M = 1048576b
  61. if(preg_match('/[.](JPG)|(jpg)|(JPEG)|(jpeg)|(gif)|(GIF)|(png)|(PNG)$/',$_FILES['file']['name'])){ //проверка формата исходного изображения
  62. $filename = $_FILES['file']['name'];
  63. $source = $_FILES['file']['tmp_name'];
  64. $target = $path_to_90_directory . $filename;
  65. //bytes // in php.ini upload_max_filesize = 2M
  66.  
  67. move_uploaded_file($source, $target);//загрузка оригинала в папку $path_to_90_directory
  68. if(preg_match('/[.](GIF)|(gif)$/', $filename)) {
  69. $im = imagecreatefromgif($path_to_90_directory.$filename) ; //если оригинал был в формате gif, то создаем изображение в этом же формате.
  70. }
  71. if(preg_match('/[.](PNG)|(png)$/', $filename)) {
  72. $im = imagecreatefrompng($path_to_90_directory.$filename) ;//если оригинал был в формате png, то создаем изображение в этом же формате.
  73. }
  74. if(preg_match('/[.](JPG)|(jpg)|(jpeg)|(JPEG)$/', $filename)) {
  75. $im = imagecreatefromjpeg($path_to_90_directory.$filename); //если оригинал был в формате jpg, то создаем изображение в этом же формате.
  76. }
  77. // Создание квадрата 90x90<img src="_User/avatars/net-avatara.jpg" width="44" height="44">
  78. // dest - результирующее изображение
  79. // w - ширина изображения
  80. // ratio - коэффициент пропорциональности
  81. $w = 135;
  82. $h = 135; // квадратная 90x90. Можно поставить и другой размер.
  83. // создаём исходное изображение на основе
  84. // исходного файла и определяем его размеры
  85. $w_src = imagesx($im); //вычисляем ширину
  86. $h_src = imagesy($im); //вычисляем высоту изображения
  87. // создаём пустую квадратную картинку
  88. // важно именно truecolor!, иначе будем иметь 8-битный результат
  89. $dest = imagecreatetruecolor($w,$h);
  90. // вырезаем квадратную серединку по x, если фото горизонтальное
  91. if ($w_src>$h_src){
  92. imagecopyresampled($dest, $im, 0, 0,
  93. round((max($w_src,$h_src)-min($w_src,$h_src))/2),
  94. 0, $w, $w, min($w_src,$h_src), min($w_src,$h_src));
  95. }
  96. // вырезаем квадратную верхушку по y,
  97. // если фото вертикальное (хотя можно тоже серединку)
  98. if ($w_src<$h_src){
  99. imagecopyresampled($dest, $im, 0, 0, 0, 0, $w, $h,
  100. min($w_src,$h_src), min($w_src,$h_src));
  101. }
  102. // квадратная картинка масштабируется без вырезок
  103. if ($w_src==$h_src){
  104. imagecopyresampled($dest, $im, 0, 0, 0, 0, $w, $h, $w_src, $w_src);
  105. }
  106. imagejpeg($dest, $path_to_90_directory.$date.".jpg");//сохраняем изображение формата jpg в нужную папку, именем будет текущее время.
  107. $path_to_90_directory = '_images/';
  108. $item_img = $path_to_90_directory.$date.".jpg";//заносим в переменную путь до аватара.
  109. $path_to_90_directory = '../../_images/'; // valid pass from here to file, to unlink it
  110. $delfull = $path_to_90_directory.$filename;
  111. unlink ($delfull);//удаляем оригинал загруженного изображения, он нам больше не нужен. Задачей было - получить миниатюру.
  112. return $item_img; // возврат ссылки на аватар
  113. }else{//в случае несоответствия формата, выдаем соответствующее сообщение
  114. $_SESSION['msg_date'] = time();
  115. $this->_errMsg = "<a href='#'>Image must be in <strong>JPG,GIF or PNG</strong> format</a>";
  116. return $this->_errMsg;
  117. }
  118. }else{
  119. $this->_errMsg = "<a href='#'>Image size should not exceed 2 MB</a>";
  120. $_SESSION['msg_date'] = time();
  121. return $this->_errMsg;
  122. }
  123. }
  124. function saveNewContentItem($type, $brand, $model, $price, $description , $imgLink){
  125. $date = time();
  126. $imgLink = $this->checkfile($date);
  127. if(!preg_match('/[.](jpg)$/',$imgLink)){
  128. $_SESSION['msg_date'] = time();
  129. return $imgLink; //will be error msg in
  130. }
  131. if(isset($type) and isset($brand) and isset($price) and isset($model) and isset($description) and isset($imgLink)){
  132. $sql="INSERT INTO content (price, type, brand, model, description, imgLink)
  133. VALUES ('$price', '$type', '$brand', '$model', '$description', '$imgLink')";
  134. $res = mysql_query($sql, self::$_db);
  135. if(!$res){
  136. $_SESSION['msg_date'] = time();
  137. $this->_errMsg = $this->errorHandler("Error in Class_content.php / Error adding new file");
  138. return $this->_errMsg;
  139. }else{
  140. $_SESSION['msg_date'] = time();
  141. $this->_errMsg = "<a href='#'>You have add new file.</a>";
  142. return $this->_errMsg;
  143. }
  144. }else{
  145. $_SESSION['msg_date'] = time();
  146. $this->_errMsg = "<a href='#'>Not all of the field was filled.</a>";
  147. return $this->_errMsg;
  148. }
  149.  
  150. }
  151.  
  152. public function getOneItem($id){
  153. $sql = "SELECT id, type, price, brand, model, description, imgLink FROM content WHERE id='$id'";
  154. $res=mysql_query($sql, self::$_db);
  155. if(!$res){
  156. $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. ");
  157. echo $this->_errMsg;
  158. }else{
  159. $myrow = mysql_fetch_array($res);
  160. if(!$myrow){
  161. $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. ");
  162. echo $this->_errMsg;
  163. }else{
  164. $type = $myrow['type'];
  165. $sql_two="SELECT type FROM type WHERE id = '$type'";
  166. $res_two=mysql_query($sql_two, self::$_db);
  167. $myrow_two=mysql_fetch_array($res_two);
  168.  
  169. $brand=$myrow['brand'];
  170. $sql_thre="SELECT brand, id FROM brand WHERE id='$brand'";
  171. $res_thre=mysql_query($sql_thre, self::$_db);
  172. $myrow_thre=mysql_fetch_array($res_thre);
  173. printf("","");
  174. }
  175. }
  176. }//public function getOneItem($id){
  177.  
  178.  
  179. public function getItemsForBusket($where){
  180. $sql = "SELECT id, type, price, brand, model, description, imgLink FROM content WHERE ".$where;
  181. $res = mysql_query($sql, self::$_db);
  182. if(!$res){
  183. echo "Error1";
  184. exit();
  185. }else{
  186. $myrow = mysql_fetch_array($res);
  187. if(!$myrow){
  188. echo "Error2";
  189. exit();
  190. }
  191. }
  192.  
  193. echo "<div class='th'>
  194. <span style='width:115px;padding-left:6px;'>Товар </span>
  195. <span style='width:237px;'>Детали </span>
  196. <span style='width:78px;'>Кол-во".$_SESSION['count']."</span>
  197. <span style='width:100px;'>Цена за шт. </span>
  198. <span style='width:90px;'>Всего </span>
  199. </div>";
  200. $total=0;
  201. $inc=0;
  202. do{
  203. $inc++;
  204. $idy = $myrow['id'];
  205. $type = $myrow['type'];
  206. $sql_two="SELECT type FROM type WHERE id = '$type'";
  207. $res_two=mysql_query($sql_two, self::$_db);
  208. $myrow_two=mysql_fetch_array($res_two);
  209.  
  210. $brand=$myrow['brand'];
  211. $sql_thre="SELECT brand, id FROM brand WHERE id='$brand'";
  212. $res_thre=mysql_query($sql_thre, self::$_db);
  213. $myrow_thre=mysql_fetch_array($res_thre);
  214. printf("
  215. <div class='td' >
  216. <div class='td1' style='background-image:none'><img src='%s' width = '50' height = '50'></div>
  217.  
  218. <div class='td2'>
  219. <div class='b_h'>%s</div>
  220. <div class='b_t'>Арт.: <span>234355</span> Бренд: <span>%s</span> </div>
  221. <div class='opus_p'>%s</div>
  222. </div>
  223. <div class='td3'><input value='%s' name='' class='in_count' onfocus='this.value = '';' onblur='if (this.value == '' || this.value == ' ') this.value='%s';'></div>
  224.  
  225. <div class='td4' id='to%s'>%s</div>
  226.  
  227. <div class='td5' id='tt%s'>%s</div>
  228.  
  229. <div class='td6'><a class='delete' href='busket1.php?id=%s'> Удалить</a></div>
  230. <div class='clr'></div>
  231. </div>
  232.  
  233. ",
  234. $myrow['imgLink'], $myrow['model'], $myrow_thre['brand'], $myrow['description'], $_SESSION['item_ids'][$idy],
  235. $_SESSION['item_ids'][$idy], $inc, $myrow['price'], $inc, $myrow['price']*$_SESSION['item_ids'][$idy], $idy);
  236. $total += $myrow['price']*$_SESSION['item_ids'][$idy];
  237. echo "<div class='busket_price' id='%s'>Общая стоимость <div class='span_busket_price' id='th$inc'>$total</div></div>";
  238. }while($myrow = mysql_fetch_array($res));
  239. echo "<p style='display: none' id='hiden_value'>$inc</div>";
  240. }//public function getItemsForBusket($were){
  241.  
  242.  
  243.  
  244. function getSortIterator(){
  245. $sql = "SELECT id, type, price, brand, model, description, imgLink FROM content ORDER BY id DESC";
  246. $res=mysql_query($sql, self::$_db);
  247. if(!$res){
  248. $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. ");
  249. echo $this->_errMsg;
  250. }else{
  251. $myrow = mysql_fetch_array($res);
  252. if(!$myrow){
  253. $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. ");
  254. echo $this->_errMsg;
  255. }else{
  256. do{
  257. $type = $myrow['type'];
  258. $sql_two="SELECT type FROM type WHERE id = '$type'";
  259. $res_two=mysql_query($sql_two, self::$_db);
  260. $myrow_two=mysql_fetch_array($res_two);
  261.  
  262. $brand=$myrow['brand'];
  263. $sql_thre="SELECT brand, id FROM brand WHERE id='$brand'";
  264. $res_thre=mysql_query($sql_thre, self::$_db);
  265. $myrow_thre=mysql_fetch_array($res_thre);
  266. if($temp%2==0){
  267. $temp='pro no_margin_right';
  268. }else{
  269. $temp='pro';
  270. }
  271. printf("<div class='$temp'>
  272. <a class='busket'href='%s'>В КОРЗИНУ</a>
  273. <div class='left_pro'>
  274. <div class='pro_h'><a href='product.php?id=%s'>%s</a></div>
  275. <div class='brand_name'>Бренд: <a href='all_brand_items.php?id=%s'>%s</a></div>
  276. <div class='pro_desc'>%s</div>
  277. <div class='pro_value'>%s</div>
  278. </div>
  279. <div class='pro_img'><a href='product.php?id=%s' style='background-image:none'><img src='%s'></a></div>
  280. <div class='clr'></div>
  281. <hr />
  282. </div>",
  283. $myrow['id'], $myrow['id'], $myrow_thre['model'], $myrow_thre['id'], $myrow_thre['brand'], $myrow['description'], $myrow['price'], $myrow['id'], $myrow['imgLink']
  284. );
  285. }while($myrow = mysql_fetch_array($res));
  286. }
  287. }
  288. }
  289.  
  290. function getOrder($query, $text){
  291. $sql = "SELECT id, type, price, brand, model, description, imgLink FROM content WHERE ".$query;
  292. $res = mysql_query($sql, self::$_db);
  293. $myrow = mysql_fetch_array($res);
  294. // Откроем соединение с файлом
  295. $f = fopen(self::FILENAME, 'a');
  296. $str = "Text from user - ".$text . "\r\n";
  297. fputs($f, $str);
  298. // в цикле запись всех заказов в файл
  299. do{
  300. // Сформируем строку для записи в файл
  301. $str = 'id of item - '.$myrow['id']. ', ' . 'Model - '. $myrow['model'] . ', ' . 'price - '. $myrow['price'] . "\r\n";
  302. if(is_resource($f)){
  303. // Запишем строку в файл и закроем соединение
  304. fputs($f, $str);
  305. }
  306. }while($myrow = mysql_fetch_array($res));
  307. fclose($f);
  308. }
  309.  
  310. function getAllItemsInFile(){
  311. $sql = "SELECT id, type, price, brand, model, description, imgLink FROM content";
  312. $res = mysql_query($sql, self::$_db);
  313. $myrow = mysql_fetch_array($res);
  314. $f = fopen(self::ALL_ITEMS, 'a');
  315. $str = self::DB_NAME." ".self::DB_USER." ".self::DB_PASS. " All items of this db :\r\n";
  316. fputs($f, $str);
  317. do{
  318. $type = $myrow['type'];
  319. $sql_two="SELECT type FROM type WHERE id = '$type'";
  320. $res_two=mysql_query($sql_two, self::$_db);
  321. $myrow_two=mysql_fetch_array($res_two);
  322.  
  323. $brand=$myrow['brand'];
  324. $sql_thre="SELECT brand, id FROM brand WHERE id='$brand'";
  325. $res_thre=mysql_query($sql_thre, self::$_db);
  326. $myrow_thre=mysql_fetch_array($res_thre);
  327.  
  328. // Сформируем строку для записи в файл
  329. $str = 'id - '.$myrow['id']. ', '
  330. . 'price - '. $myrow['price']. ', '
  331. . 'type - '. $myrow_two['type']. ', '
  332. . 'brand - '. $myrow_thre['brand']. ', '
  333. . 'model - '. $myrow['model']. ', '
  334. . 'description - '. $myrow['description']. ', '
  335. . 'link to img - '. $myrow['imgLink'] . "\r\n";
  336. if(is_resource($f)){
  337. // Запишем строку в файл и закроем соединение
  338. fputs($f, $str);
  339. }
  340. }while($myrow = mysql_fetch_array($res));
  341. fclose($f);
  342. }
  343.  
  344. function getXmlToDB(){
  345. $u_xml = $_FILES['xml']['tmp_name']; //get the xml-file adres
  346. $xml=file_get_contents($u_xml);
  347. $items = new SimpleXMLElement($xml);
  348. for($i=0, $count = $items->count(); $i<$count; $i++){ // $count = $items->count() returns the count of items indexes
  349. $price = $items->item[$i]->price;
  350. $type = $items->item[$i]->type;
  351. $brand = $items->item[$i]->brand;
  352. $model = $items->item[$i]->model;
  353. $description = $items->item[$i]->description;
  354. $imgLink = $items->item[$i]->imgLink;
  355. $res = mysql_query("INSERT INTO content (price, type, brand, model, description, imgLink)
  356. VALUES ('$price', '$type', '$brand', '$model', '$description', '$imgLink')", self::$_db);
  357. if(!$res){
  358. $this->_errMsg = "Error while inserting new items";
  359. return $this->_errMsg;
  360. }
  361. }
  362. if($this->_errMsg !=="Error while inserting new items from XML file"){
  363. $this->_errMsg = "Upload was successful";
  364. return $this->_errMsg;
  365. }
  366. }
  367.  
  368. function getAll(){
  369. }
  370. function deletePost($id){
  371. }
  372.  
  373. function getUserContent($UserId){
  374. }
  375. function clearData($data){
  376. $res = stripslashes(htmlspecialchars(trim($data)));
  377. return $res;
  378. }
  379.  
  380. public function AddNewErr($msg , $date, $userId, $fixed){
  381. $sql = "INSERT INTO errors (date, userId, msg, fixed) VALUES ('$date', '$userId', '$msg', '$fixed')";
  382. if(isset($msg) and isset($date) and isset($userId) and isset($fixed)){
  383. $res = mysql_query($sql, $this->_db);
  384. if(!$res){
  385. $_SESSION['msg_date'] = time();
  386. $this->_errMsg = $this->errorHandler("Error in Class_content.php / public function AddNewErr($msg , $date, $userId, $fixed)".__LINE__);
  387. return $this->_errMsg;
  388. }
  389. }
  390. }
  391.  
  392.  
  393. //////////////////////////////////////////////////************privates****************//////////////////////////////////////////////////////////////////
  394.  
  395.  
  396.  
  397. private function errorHandler($error, $msg=1){ // forms a line with an error
  398. $date = time();
  399. $userId = $_SESSION['User_id'];
  400. $fixed = "no";
  401. $error = "msg=".$error."&date".$date."&userId".$userId."&fixed=".$fixed;
  402. if($msg==1){
  403. $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>";
  404. return $msg;
  405. }else{
  406. $msg = "<a href='../_admin/send_error_from_user.php?".$error."><p id='errorHandlerMsg'>".$msg."</p></a>";
  407. return $msg;
  408. }
  409. }
  410. }
Add Comment
Please, Sign In to add comment