PageRenderTime 103ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/storecommander/ead6f6fce09/SC/lib/all/upload/all_upload.php

https://gitlab.com/ptisky/API_prestashop
PHP | 374 lines | 284 code | 19 blank | 71 comment | 50 complexity | 96c2e9255c37addff28cfa9ba656321e MD5 | raw file
  1. <?php
  2. /**
  3. * Store Commander
  4. *
  5. * @category administration
  6. * @author Store Commander - support@storecommander.com
  7. * @version 2015-09-15
  8. * @uses Prestashop modules
  9. * @since 2009
  10. * @copyright Copyright &copy; 2009-2015, Store Commander
  11. * @license commercial
  12. * All rights reserved! Copying, duplication strictly prohibited
  13. *
  14. * *****************************************
  15. * * STORE COMMANDER *
  16. * * http://www.StoreCommander.com *
  17. * * V 2015-09-15 *
  18. * *****************************************
  19. *
  20. * Compatibility: PS version: 1.1 to 1.6.1
  21. *
  22. **/
  23. /**
  24. * upload.php
  25. *
  26. * Copyright 2009, Moxiecode Systems AB
  27. * Released under GPL License.
  28. * Modified for Store Commander
  29. *
  30. * License: http://www.plupload.com/license
  31. * Contributing: http://www.plupload.com/contributing
  32. */
  33. // HTTP headers for no cache etc
  34. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  35. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  36. header("Cache-Control: no-store, no-cache, must-revalidate");
  37. header("Cache-Control: post-check=0, pre-check=0", false);
  38. header("Pragma: no-cache");
  39. // Settings
  40. $obj = Tools::getValue('obj','');
  41. switch($obj)
  42. {
  43. case 'attrtexture':
  44. $targetDir = _PS_COL_IMG_DIR_;
  45. $id_attribute=intval($_GET['id_attribute']);
  46. break;
  47. case 'importcsv':
  48. $targetDir = SC_CSV_IMPORT_DIR;
  49. break;
  50. case 'importcsvcat':
  51. $targetDir = SC_CSV_IMPORT_DIR."category/";
  52. break;
  53. case 'importcsvcus':
  54. $targetDir = SC_CSV_IMPORT_DIR."customers/";
  55. break;
  56. case 'attachment':
  57. $targetDir = _PS_DOWNLOAD_DIR_;
  58. break;
  59. case 'image':
  60. require_once('upload-image.inc.php');
  61. $targetDir = _PS_TMP_IMG_DIR_;
  62. break;
  63. default:
  64. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 100, "message": "Failed to open target directory."}, "id" : "id"}');
  65. }
  66. //$cleanupTargetDir = false; // Remove old files
  67. //$maxFileAge = 60 * 60; // Temp file age in seconds
  68. // 5 minutes execution time
  69. @set_time_limit(5 * 60);
  70. // Uncomment this one to fake upload time
  71. // usleep(5000);
  72. // Get parameters
  73. $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
  74. $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
  75. $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
  76. // Clean the fileName for security reasons
  77. $fileName = preg_replace('/[^\w\._]+/', '', $fileName);
  78. // Make sure the fileName is unique but only if chunking is disabled
  79. if(($obj!='importcsv' && $obj!='importcsvcus' && $obj!='importcsvcat') && $chunks < 2 && file_exists($targetDir . $fileName)){
  80. $ext = strrpos($fileName, '.');
  81. $fileName_a = substr($fileName, 0, $ext);
  82. $fileName_b = substr($fileName, $ext);
  83. $count = 1;
  84. while(file_exists($targetDir . $fileName_a . '_' . $count . $fileName_b))
  85. $count++;
  86. $fileName = $fileName_a . '_' . $count . $fileName_b;
  87. }
  88. if ($obj=='attrtexture')
  89. {
  90. $ext = strrpos($fileName, '.');
  91. $fileName_b = substr($fileName, $ext);
  92. $fileName = $id_attribute . $fileName_b;
  93. }
  94. // Create target dir
  95. if(!file_exists($targetDir))
  96. @mkdir($targetDir);
  97. // Remove old temp files
  98. /* this doesn't really work by now
  99. if(is_dir($targetDir) && ($dir = opendir($targetDir))){
  100. while(($file = readdir($dir)) !== false){
  101. $filePath = $targetDir . DIRECTORY_SEPARATOR . $file;
  102. // Remove temp files if they are older than the max age
  103. if(preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge))
  104. @unlink($filePath);
  105. }
  106. closedir($dir);
  107. }else
  108. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
  109. */
  110. // Look for the content type header
  111. if(isset($_SERVER["HTTP_CONTENT_TYPE"]))
  112. $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
  113. if(isset($_SERVER["CONTENT_TYPE"]))
  114. $contentType = $_SERVER["CONTENT_TYPE"];
  115. // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
  116. if(strpos($contentType, "multipart") !== false){
  117. if(isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])){
  118. // Open temp file
  119. $out = fopen($targetDir . $fileName, $chunk == 0 ? "wb" : "ab");
  120. if($out){
  121. // Read binary input stream and append it to temp file
  122. $in = fopen($_FILES['file']['tmp_name'], "rb");
  123. if($in){
  124. while($buff = fread($in, 4096))
  125. fwrite($out, $buff);
  126. }else
  127. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  128. fclose($in);
  129. fclose($out);
  130. @unlink($_FILES['file']['tmp_name']);
  131. if ($chunks<2 || $chunks==$chunk+1)
  132. getUpload();
  133. }else
  134. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 102, "message": "Failed to open output stream: '.join('/<br/>',explode('/',$targetDir . $fileName)).'<br/>This folder must be writeable."}, "id" : "id"}');
  135. }else
  136. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
  137. }else{
  138. // Open temp file
  139. $out = fopen($targetDir . $fileName, $chunk == 0 ? "wb" : "ab");
  140. if($out){
  141. // Read binary input stream and append it to temp file
  142. $in = fopen("php://input", "rb");
  143. if($in){
  144. while($buff = fread($in, 4096))
  145. fwrite($out, $buff);
  146. }else
  147. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 111, "message": "Failed to open input stream."}, "id" : "id"}');
  148. fclose($in);
  149. fclose($out);
  150. if ($chunks<2 || $chunks==$chunk+1)
  151. getUpload();
  152. }else
  153. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 112, "message": "Failed to open output stream: '.join('/<br/>',explode('/',$targetDir . $fileName)).'<br/>This folder must be writeable."}, "id" : "id"}');
  154. }
  155. // AJOUTER DANS PS
  156. $sql='';
  157. function getUpload()
  158. {
  159. global $targetDir,$fileName,$_FILES,$languages,$obj,$sql;
  160. switch($obj)
  161. {
  162. case 'importcsv':
  163. // nothing to create
  164. break;
  165. case 'attachment':
  166. $name = $_REQUEST["name"];
  167. //$file = substr($fileName,0,-4);
  168. $file = $fileName;
  169. $mime = $_FILES['file']['type'];
  170. if (version_compare(_PS_VERSION_,'1.4.0.3','>=')){
  171. $sql = "INSERT INTO `"._DB_PREFIX_."attachment` (file,file_name,mime) VALUES ('".psql($file)."','".psql($name)."','".psql($mime)."')";
  172. }else{
  173. $sql = "INSERT INTO `"._DB_PREFIX_."attachment` (file,mime) VALUES ('".psql($file)."','".psql($mime)."')";
  174. }
  175. Db::getInstance()->Execute($sql);
  176. $id_attachment = Db::getInstance()->Insert_ID();
  177. $sqlstr = '';
  178. $name = substr($name,0,-4);
  179. foreach($languages AS $lang)
  180. {
  181. $desc = "";
  182. if(_s("CAT_PROD_ATTCH_DESC")=="1")
  183. $desc = psql($name).'_'.psql($lang['iso_code']);
  184. elseif(_s("CAT_PROD_ATTCH_DESC")=="2")
  185. $desc = psql($name);
  186. $sqlstr.='('.intval($id_attachment).','.intval($lang['id_lang']).',\''.psql($name).'\',\''.$desc.'\'),';
  187. }
  188. $sqlstr = trim($sqlstr,',');
  189. $sql2 = "INSERT INTO `"._DB_PREFIX_."attachment_lang` (id_attachment,id_lang,name,description) VALUES ".$sqlstr;
  190. Db::getInstance()->Execute($sql2);
  191. $linktoproduct = Tools::getValue('linktoproduct','0');
  192. $product_list = Tools::getValue('product_list','null');
  193. if($linktoproduct && $product_list!='null')
  194. {
  195. $sql = "DELETE FROM `"._DB_PREFIX_."product_attachment` WHERE `id_attachment` = ".intval($id_attachment)." AND `id_product` IN (".psql($product_list).")";
  196. Db::getInstance()->Execute($sql);
  197. $sqlstr = array();
  198. $product_listarray = explode(',',$product_list);
  199. foreach($product_listarray AS $id_product)
  200. {
  201. $sqlstr[]='('.$id_product.','.$id_attachment.')';
  202. }
  203. $sqlstr = array_unique($sqlstr);
  204. $sql = "INSERT INTO `"._DB_PREFIX_."product_attachment` (id_product,id_attachment) VALUES ".psql(join(',',$sqlstr));
  205. Db::getInstance()->Execute($sql);
  206. if (version_compare(_PS_VERSION_,'1.4.0.2','>='))
  207. {
  208. $sql = "UPDATE `"._DB_PREFIX_."product` SET cache_has_attachments=1 WHERE `id_product` IN (".psql($product_list).")";
  209. Db::getInstance()->Execute($sql);
  210. }
  211. }
  212. if (version_compare(_PS_VERSION_,'1.6.0.0','>='))
  213. {
  214. clearstatcache();
  215. $file_size = @filesize(_PS_DOWNLOAD_DIR_.$file);
  216. Db::getInstance()->Execute('UPDATE '._DB_PREFIX_.'attachment SET file_size = '.(int)$file_size.' WHERE id_attachment = '.intval($id_attachment));
  217. }
  218. // PM Cache
  219. if(!empty($product_list))
  220. ExtensionPMCM::clearFromIdsProduct($product_list);
  221. break;
  222. case 'image':
  223. global $id_product,$id_image;
  224. $id_products=(Tools::getValue('product_list',0));
  225. $attr_list=(Tools::getValue('attr_list',0));
  226. $id_products = explode(",", $id_products);
  227. $generate_hight_dpi_images = (bool)SCI::getConfigurationValue('PS_HIGHT_DPI');
  228. foreach($id_products as $id_product)
  229. {
  230. $highPos=Image::getHighestPosition($id_product);
  231. $image = new Image();
  232. $image->id_product = $id_product;
  233. $highPos++;
  234. $image->position = $highPos;
  235. $legends=array();
  236. foreach($languages AS $lang){
  237. $product=new Product($id_product,false,$lang['id_lang']);
  238. $n=explode('\.',$fileName);
  239. array_pop($n);
  240. $legends[$lang['id_lang']]=str_replace('#','',Tools::substr($product->name,0,128));
  241. }
  242. $image->legend=$legends;
  243. // SCI::addToShops('image', array($image->id)); // to all shops
  244. if(SCMS)
  245. $image->id_shop_list = SCI::getSelectedShopActionList(false, $id_product);
  246. if (!$image->add())
  247. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 103, "message": "Error creating image object."}, "id" : "id"}');
  248. $id_image=$image->id;
  249. $ext=substr(Tools::strtolower($fileName),Tools::strlen(Tools::strtolower($fileName))-3,3);
  250. $imagesTypes = ImageType::getImagesTypes('products');
  251. $tmpName=$targetDir . $fileName;
  252. switch(_s('CAT_PROD_IMG_PNG_METHOD')){
  253. case 0:
  254. $newImageSourcePath=_PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,'','jpg');
  255. // if (!imageResize($tmpName, _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,'','jpg'),NULL,NULL,'jpg'))
  256. if (!copy($tmpName, $newImageSourcePath))
  257. die('{"jsonrpc" : "2.0", "result" : null, "rror" : {"code": 106, "message": "PS: An error occurred while copying image source"}, "id" : "id"}');
  258. foreach ($imagesTypes AS $k => $imageType)
  259. if (!imageResize($newImageSourcePath, _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,stripslashes($imageType['name']),'jpg'), $imageType['width'], $imageType['height'],'jpg'))
  260. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 106, "message": "PS: An error occurred while copying image ' . stripslashes($imageType['name']) . '"}, "id" : "id"}');
  261. else
  262. {
  263. if($generate_hight_dpi_images)
  264. {
  265. $name = _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,stripslashes($imageType['name']),'jpg');
  266. $name = str_replace(".jpg","2x.jpg", $name);
  267. imageResize($newImageSourcePath, $name, $imageType['width']*2, $imageType['height']*2,'jpg');
  268. }
  269. }
  270. break;
  271. case 1:
  272. if (!imageResize($tmpName, _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,'','jpg'),NULL,NULL,$ext))
  273. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 106, "message": "PS: An error occurred while copying image"}, "id" : "id"}');
  274. foreach ($imagesTypes AS $k => $imageType)
  275. if (!imageResize($tmpName, _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,stripslashes($imageType['name']),'jpg'), $imageType['width'], $imageType['height'],$ext))
  276. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 106, "message": "PS: An error occurred while copying image '.stripslashes($imageType['name']).'"}, "id" : "id"}');
  277. else
  278. {
  279. if($generate_hight_dpi_images)
  280. {
  281. $name = _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,stripslashes($imageType['name']),'jpg');
  282. $name = str_replace(".jpg","2x.jpg", $name);
  283. imageResize($tmpName, $name, $imageType['width']*2, $imageType['height']*2,$ext);
  284. }
  285. }
  286. break;
  287. case 2:
  288. if ($ext=='png' && !imageResize($tmpName, _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,'','png'),NULL,NULL,'png'))
  289. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 106, "message": "PS: An error occurred while copying image '.stripslashes($imageType['name']).'"}, "id" : "id"}');
  290. if (!imageResize($tmpName, _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,'','jpg'),NULL,NULL,'jpg'))
  291. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 106, "message": "PS: An error occurred while copying image '.stripslashes($imageType['name']).'"}, "id" : "id"}');
  292. foreach ($imagesTypes AS $k => $imageType)
  293. {
  294. if ($ext=='png' && !imageResize($tmpName, _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,stripslashes($imageType['name']),'png'), $imageType['width'], $imageType['height'],'png'))
  295. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 106, "message": "PS: An error occurred while copying image '.stripslashes($imageType['name']).'"}, "id" : "id"}');
  296. if (!imageResize($tmpName, _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,stripslashes($imageType['name']),'jpg'), $imageType['width'], $imageType['height'],'jpg'))
  297. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 106, "message": "PS: An error occurred while copying image '.stripslashes($imageType['name']).'"}, "id" : "id"}');
  298. else
  299. {
  300. if($generate_hight_dpi_images)
  301. {
  302. $name = _PS_IMG_DIR_.'p/'.getImgPath($id_product,$id_image,stripslashes($imageType['name']),'jpg');
  303. $name = str_replace(".jpg","2x.jpg", $name);
  304. imageResize($tmpName, $name, $imageType['width']*2, $imageType['height']*2,'jpg');
  305. }
  306. }
  307. }
  308. break;
  309. }
  310. //@unlink($tmpName);
  311. SCI::hookExec('watermark', array('id_image' => $id_image, 'id_product' => $id_product));
  312. if (!Image::getCover($image->id_product))
  313. {
  314. $first_img = Db::getInstance()->getRow('
  315. SELECT `id_image` FROM `'._DB_PREFIX_.'image`
  316. WHERE `id_product` = '.intval($image->id_product));
  317. Db::getInstance()->Execute('
  318. UPDATE `'._DB_PREFIX_.'image`
  319. SET `cover` = 1
  320. WHERE `id_image` = '.intval($first_img['id_image']));
  321. if (version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  322. {
  323. $sql = "UPDATE `"._DB_PREFIX_."image_shop` SET `cover` = 1 WHERE id_image=".intval($first_img['id_image'])." AND id_shop IN (".SCI::getSelectedShopActionList(true, $id_product).")";
  324. Db::getInstance()->Execute($sql);
  325. }
  326. }
  327. if(!empty($attr_list))
  328. {
  329. $attr_list = explode(",", $attr_list);
  330. foreach($attr_list as $attr)
  331. {
  332. if(!empty($attr))
  333. {
  334. $sql = "INSERT INTO `"._DB_PREFIX_."product_attribute_image` (id_product_attribute,id_image) VALUES ('".(int)$attr."','".(int)$id_image."')";
  335. Db::getInstance()->Execute($sql);
  336. }
  337. }
  338. }
  339. if (_s('CAT_PROD_IMG_SAVE_FILENAME'))
  340. {
  341. $sql="UPDATE "._DB_PREFIX_."image SET sc_path='".psql($fileName)."' WHERE id_image = ".intval($id_image);
  342. Db::getInstance()->Execute($sql);
  343. }
  344. }
  345. // PM Cache
  346. if(!empty($id_products))
  347. ExtensionPMCM::clearFromIdsProduct($id_products);
  348. break;
  349. default:
  350. die('{"jsonrpc" : "2.0", "result" : null, "error" : {"code": 105, "message": "Failed to create PS object."}, "id" : "id"}');
  351. }
  352. }
  353. die('{"jsonrpc" : "2.0", "result" : "'.$sql.'", "error" : null, "id" : "id"}');