PageRenderTime 36ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/application/views/partials/admin/functions.php

https://bitbucket.org/chadsaun/ifrogz-panel
PHP | 2039 lines | 1815 code | 72 blank | 152 comment | 397 complexity | a6830724aef4ffb2fbf63333bedfbd80 MD5 | raw file
  1. <?php
  2. //This code is copyright (c) Internet Business Solutions SL, all rights reserved.
  3. //The contents of this file are protect under law as the intellectual property of Internet
  4. //Business Solutions SL. Any use, reproduction, disclosure or copying of any kind
  5. //without the express and written permission of Internet Business Solutions SL is forbidden.
  6. //Author: Vince Reid, vince@virtualred.net
  7. $incfunctionsdefined=TRUE;
  8. @set_magic_quotes_runtime(0);
  9. $magicq = (get_magic_quotes_gpc()==1);
  10. if(@$emailencoding=="") $emailencoding="iso-8859-1";
  11. if(@$adminencoding=="") $adminencoding="iso-8859-1";
  12. if(@$_SESSION["languageid"] != "") $languageid=$_SESSION["languageid"];
  13. function getadminsettings(){
  14. global $alreadygotadmin,$splitUSZones,$adminLocale,$countryCurrency,$orcurrencyisosymbol,$useEuro,$storeurl,$stockManage,$useStockManagement,$adminProdsPerPage,$countryTax,$delAfter,$delccafter,$handling,$adminCanPostUser,$packtogether,$origZip,$shipType,$origCountry,$origCountryCode,$uspsUser,$uspsPw,$upsUser,$upsPw,$upsAccess,$adminUnits,$emailAddr,$sendEmail,$adminTweaks,$adminlanguages,$adminlangsettings,$currRate1,$currSymbol1,$currRate2,$currSymbol2,$currRate3,$currSymbol3,$currConvUser,$currConvPw,$currLastUpdate;
  15. if(! @$alreadygotadmin){
  16. $sSQL = "SELECT adminEmail,adminEmailConfirm,adminTweaks,adminProdsPerPage,adminStoreURL,adminHandling,adminPacking,adminDelUncompleted,adminDelCC,adminUSZones,adminStockManage,adminShipping,adminCanPostUser,adminZipCode,adminUnits,adminUSPSUser,adminUSPSpw,adminUPSUser,adminUPSpw,adminUPSAccess,adminlanguages,adminlangsettings,currRate1,currSymbol1,currRate2,currSymbol2,currRate3,currSymbol3,currConvUser,currConvPw,currLastUpdate,countryLCID,countryCurrency,countryName,countryCode,countryTax FROM admin LEFT JOIN countries ON admin.adminCountry=countries.countryID WHERE adminID=1";
  17. $result = mysql_query($sSQL) or print(mysql_error());
  18. $rs = mysql_fetch_array($result);
  19. $splitUSZones = ((int)$rs["adminUSZones"]==1);
  20. $adminLocale = $rs["countryLCID"];
  21. $countryCurrency = $rs["countryCurrency"];
  22. if(@$orcurrencyisosymbol != "") $countryCurrency=$orcurrencyisosymbol;
  23. $useEuro = ($rs["countryCurrency"]=="EUR");
  24. $storeurl = $rs["adminStoreURL"];
  25. $stockManage = (int)$rs["adminStockManage"];
  26. $useStockManagement = ($stockManage != 0);
  27. $adminProdsPerPage = $rs["adminProdsPerPage"];
  28. $countryTax=(double)$rs["countryTax"];
  29. $delAfter = (int)$rs["adminDelUncompleted"];
  30. $delccafter = (int)$rs["adminDelCC"];
  31. $handling=(double)$rs["adminHandling"];
  32. $adminCanPostUser=trim($rs["adminCanPostUser"]);
  33. $packtogether = ((int)$rs["adminPacking"]==1);
  34. $origZip = $rs["adminZipCode"];
  35. $shipType=(int)$rs["adminShipping"];
  36. $origCountry = $rs["countryName"];
  37. $origCountryCode = $rs["countryCode"];
  38. $uspsUser = $rs["adminUSPSUser"];
  39. $uspsPw = $rs["adminUSPSpw"];
  40. $upsUser = upsdecode($rs["adminUPSUser"], "");
  41. $upsPw = upsdecode($rs["adminUPSpw"], "");
  42. $upsAccess = $rs["adminUPSAccess"];
  43. if((int)$rs["adminUnits"]==0) $adminUnits="KGS"; else $adminUnits="LBS";
  44. $emailAddr = $rs["adminEmail"];
  45. $sendEmail = ((int)$rs["adminEmailConfirm"]==1);
  46. $adminTweaks = (int)$rs["adminTweaks"];
  47. $adminlanguages = (int)$rs["adminlanguages"];
  48. $adminlangsettings = (int)$rs["adminlangsettings"];
  49. $currRate1=(double)$rs["currRate1"];
  50. $currSymbol1=trim($rs["currSymbol1"]);
  51. $currRate2=(double)$rs["currRate2"];
  52. $currSymbol2=trim($rs["currSymbol2"]);
  53. $currRate3=(double)$rs["currRate3"];
  54. $currSymbol3=trim($rs["currSymbol3"]);
  55. $currConvUser=$rs["currConvUser"];
  56. $currConvPw=$rs["currConvPw"];
  57. $currLastUpdate=$rs["currLastUpdate"];
  58. mysql_free_result($result);
  59. }
  60. // Overrides
  61. global $orstoreurl,$oremailaddr;
  62. if(@$orstoreurl != "") $storeurl=$orstoreurl;
  63. if((substr(strtolower($storeurl),0,7) != "http://") && (substr(strtolower($storeurl),0,8) != "https://"))
  64. $storeurl = "http://" . $storeurl;
  65. if(substr($storeurl,-1) != "/") $storeurl .= "/";
  66. if(@$oremailaddr != "") $emailAddr=$oremailaddr;
  67. return(TRUE);
  68. }
  69. function cleanforurl($surl){
  70. $surl = str_replace(' ','_',strtolower(strip_tags($surl)));
  71. return(preg_replace('/[^a-z_0-9]/','',$surl));
  72. }
  73. function getlangid($col, $bfield){
  74. global $languageid, $adminlangsettings;
  75. if(@$languageid=="" || @$languageid==1){
  76. return($col);
  77. }else{
  78. if(($adminlangsettings & $bfield) != $bfield) return($col);
  79. }
  80. return($col . $languageid);
  81. }
  82. function xmlencodecharref($xmlstr){
  83. $xmlstr = str_replace(array('&reg;','&','<','>','®'),array('','&#x26;','&#x3c;','&#x3e;',''),$xmlstr);
  84. $tmp_str="";
  85. for($i=0; $i < strlen($xmlstr); $i++){
  86. $ch_code=ord(substr($xmlstr,$i,1));
  87. if($ch_code<=130) $tmp_str .= substr($xmlstr,$i,1);
  88. }
  89. return($tmp_str);
  90. }
  91. function CalcHmacSha1($data, $key){
  92. $blocksize = 64;
  93. $hashfunc = 'sha1';
  94. if (strlen($key) > $blocksize){
  95. $key = pack('H*', $hashfunc($key));
  96. }
  97. $key = str_pad($key, $blocksize, chr(0x00));
  98. $ipad = str_repeat(chr(0x36), $blocksize);
  99. $opad = str_repeat(chr(0x5c), $blocksize);
  100. $hmac = pack('H*', $hashfunc(($key^$opad).pack('H*', $hashfunc(($key^$ipad).$data))));
  101. return $hmac;
  102. }
  103. function parsedate($tdat){
  104. global $admindateformat;
  105. if($admindateformat==0)
  106. list($year, $month, $day) = sscanf($tdat, "%d-%d-%d");
  107. elseif($admindateformat==1)
  108. list($month, $day, $year) = sscanf($tdat, "%d/%d/%d");
  109. elseif($admindateformat==2)
  110. list($day, $month, $year) = sscanf($tdat, "%d/%d/%d");
  111. if(! is_numeric($year))
  112. $year = date("Y");
  113. elseif((int)$year < 39)
  114. $year = (int)$year + 2000;
  115. elseif((int)$year < 100)
  116. $year = (int)$year + 1900;
  117. if($year < 1970 || $year > 2038) $year = date("Y");
  118. if(! is_numeric($month))
  119. $month = date("m");
  120. if(! is_numeric($day))
  121. $day = date("d");
  122. return(mktime(0, 0, 0, $month, $day, $year));
  123. }
  124. function unstripslashes($slashedText){
  125. global $magicq;
  126. if($magicq)
  127. return stripslashes($slashedText);
  128. else
  129. return $slashedText;
  130. }
  131. function getattributes($attlist,$attid){
  132. $pos = strpos($attlist, $attid.'=');
  133. if($pos === false)
  134. return '';
  135. $pos += strlen($attid) + 1;
  136. $quote = $attlist[$pos];
  137. $pos2 = strpos($attlist, $quote, $pos + 1);
  138. $retstr = substr($attlist, $pos + 1, $pos2 - ($pos + 1));
  139. return($retstr);
  140. }
  141. class vrNodeList{
  142. var $length;
  143. var $childNodes;
  144. var $nodeName;
  145. var $nodeValue;
  146. var $attributes;
  147. function createNodeList($xmlStr){
  148. $xLen = strlen($xmlStr);
  149. for($i=0; $i < $xLen; $i++){
  150. if(substr($xmlStr, $i, 1)=="<" && substr($xmlStr, $i+1, 1) != "/" && substr($xmlStr, $i+1, 1) != "?"){ // Got a tag
  151. $j = strpos($xmlStr,">",$i);
  152. $l = strpos($xmlStr," ",$i);
  153. if(is_integer($l) && $l < $j){
  154. $this->nodeName[$this->length]=substr($xmlStr,$i+1,$l-($i+1));
  155. $this->attributes[$this->length] = substr($xmlStr,$l+1,($j-$l)-1);
  156. }else
  157. $this->nodeName[$this->length]=substr($xmlStr,$i+1,$j-($i+1));
  158. // print "Got Node: " . $this->nodeName[$this->length] . "<br />\n";
  159. $k = $i+1;
  160. $nodeNameLen=strlen($this->nodeName[$this->length]);
  161. $currLev=0;
  162. while($k < $xLen && $currLev >= 0){
  163. if(substr($xmlStr, $k, 2)=="</"){
  164. if($currLev==0 && substr($xmlStr, $k+2, $nodeNameLen)==$this->nodeName[$this->length])
  165. break;
  166. $currLev--;
  167. }elseif(substr($xmlStr, $k, 1)=="<")
  168. $currLev++;
  169. elseif(substr($xmlStr, $k, 2)=="/>")
  170. $currLev--;
  171. $k++;
  172. }
  173. $this->nodeValue[$this->length]=substr($xmlStr,$j+1,$k-($j+1));
  174. // print "Got Value: xxx" . str_replace("<","<br />&lt;",$this->nodeValue[$this->length]) . "xxx<br />\n";
  175. $this->childNodes[$this->length] = new vrNodeList($this->nodeValue[$this->length]);
  176. $this->length++;
  177. $i = $k;
  178. }
  179. }
  180. }
  181. function vrNodeList($xmlStr){
  182. $this->length=0;
  183. $this->childNodes="";
  184. $this->createNodeList($xmlStr);
  185. }
  186. function getValueByTagName($tagname){
  187. for($i=0; $i < $this->length; $i++){
  188. //print "name: " . $this->nodeName[$i] . ", " . $this->nodeValue[$i] . "<br>";
  189. if($this->nodeName[$i]==$tagname){
  190. return($this->nodeValue[$i]);
  191. }else{
  192. if($this->childNodes!=''){
  193. if(($retval = $this->childNodes[$i]->getValueByTagName($tagname)) != NULL)
  194. return($retval);
  195. }
  196. }
  197. }
  198. return NULL;
  199. }
  200. function getAttributeByTagName($tagname, $attrib){
  201. for($i=0; $i < $this->length; $i++){
  202. if($this->nodeName[$i]==$tagname){
  203. return(getattributes($this->attributes[$i], $attrib));
  204. }else{
  205. if($this->childNodes!=''){
  206. if(($retval = $this->childNodes[$i]->getAttributeByTagName($tagname, $attrib)) != NULL)
  207. return($retval);
  208. }
  209. }
  210. }
  211. return NULL;
  212. }
  213. }
  214. class vrXMLDoc{
  215. var $tXMLStr;
  216. var $nodeList;
  217. function vrXMLDoc($xmlStr){
  218. $this->tXMLStr = $xmlStr;
  219. $this->nodeList = new vrNodeList($xmlStr);
  220. }
  221. function getElementsByTagName($tagname){
  222. $currlevel=0;
  223. $taglen = strlen($tagname);
  224. }
  225. }
  226. $netnav = TRUE;
  227. if(strstr(@$HTTP_SERVER_VARS["HTTP_USER_AGENT"], "compatible") || strstr(@$HTTP_SERVER_VARS["HTTP_USER_AGENT"], "Gecko")) $netnav = FALSE;
  228. function atb($size){
  229. global $netnav;
  230. if($netnav)
  231. return round($size / 2 + 1);
  232. else
  233. return $size;
  234. }
  235. $codestr="2952710692840328509902143349209039553396765";
  236. function upsencode($thestr, $propcodestr){
  237. global $codestr;
  238. if($propcodestr=="") $localcodestr=$codestr; else $localcodestr=$propcodestr;
  239. $newstr="";
  240. for($index=0; $index < strlen($localcodestr); $index++){
  241. $thechar = substr($localcodestr,$index,1);
  242. if(! is_numeric($thechar)){
  243. $thechar = ord($thechar) % 10;
  244. }
  245. $newstr .= $thechar;
  246. }
  247. $localcodestr = $newstr;
  248. while(strlen($localcodestr) < 40)
  249. $localcodestr .= $localcodestr;
  250. $newstr="";
  251. for($index=0; $index < strlen($thestr); $index++){
  252. $thechar = substr($thestr,$index,1);
  253. $newstr .= chr(ord($thechar)+(int)substr($localcodestr,$index,1));
  254. }
  255. return $newstr;
  256. }
  257. function upsdecode($thestr, $propcodestr){
  258. global $codestr;
  259. if($propcodestr=="") $localcodestr=$codestr; else $localcodestr=$propcodestr;
  260. $newstr="";
  261. for($index=0; $index < strlen($localcodestr); $index++){
  262. $thechar = substr($localcodestr,$index,1);
  263. if(! is_numeric($thechar)){
  264. $thechar = ord($thechar) % 10;
  265. }
  266. $newstr .= $thechar;
  267. }
  268. $localcodestr = $newstr;
  269. while(strlen($localcodestr) < 40)
  270. $localcodestr .= $localcodestr;
  271. if(is_null($thestr)){
  272. return "";
  273. }else{
  274. $newstr="";
  275. for($index=0; $index < strlen($thestr); $index++){
  276. $thechar = substr($thestr,$index,1);
  277. $newstr .= chr(ord($thechar)-(int)substr($localcodestr,$index,1));
  278. }
  279. return($newstr);
  280. }
  281. }
  282. $locale_info = "";
  283. function FormatEuroCurrency($amount){
  284. global $useEuro, $adminLocale, $locale_info, $overridecurrency, $orcsymbol, $orcdecplaces, $orcdecimals, $orcthousands, $orcpreamount;
  285. if(@$overridecurrency==TRUE){
  286. if($orcpreamount)
  287. return $orcsymbol . number_format($amount,$orcdecplaces,$orcdecimals,$orcthousands);
  288. else
  289. return number_format($amount,$orcdecplaces,$orcdecimals,$orcthousands) . $orcsymbol;
  290. }else{
  291. if(! is_array($locale_info)){
  292. setlocale(LC_MONETARY,$adminLocale);
  293. $locale_info = localeconv();
  294. setlocale(LC_MONETARY,"en_US");
  295. }
  296. if($useEuro)
  297. return number_format($amount,2,$locale_info["decimal_point"],$locale_info["thousands_sep"]) . " &euro;";
  298. else
  299. return $locale_info["currency_symbol"] . number_format($amount,2,$locale_info["decimal_point"],$locale_info["thousands_sep"]);
  300. }
  301. }
  302. function FormatEmailEuroCurrency($amount){
  303. global $useEuro, $adminLocale, $locale_info, $overridecurrency, $orcemailsymbol, $orcdecplaces, $orcdecimals, $orcthousands, $orcpreamount;
  304. if(@$overridecurrency==TRUE){
  305. if($orcpreamount)
  306. return $orcemailsymbol . number_format($amount,$orcdecplaces,$orcdecimals,$orcthousands);
  307. else
  308. return number_format($amount,$orcdecplaces,$orcdecimals,$orcthousands) . $orcemailsymbol;
  309. }else{
  310. if(! is_array($locale_info)){
  311. setlocale(LC_ALL,$adminLocale);
  312. $locale_info = localeconv();
  313. setlocale(LC_ALL,"en_US");
  314. }
  315. if($useEuro)
  316. return number_format($amount,2,$locale_info["decimal_point"],$locale_info["thousands_sep"]) . " Euro";
  317. else
  318. return $locale_info["currency_symbol"] . number_format($amount,2,$locale_info["decimal_point"],$locale_info["thousands_sep"]);
  319. }
  320. }
  321. //AFFILIATE
  322. /*if(trim(@$_GET["PARTNER"]) != "" || trim(@$_GET["REFERER"]) != ""){
  323. if(@$expireaffiliate == "") $expireaffiliate=30;
  324. if(trim(@$_GET["PARTNER"])!="") $thereferer=trim(@$_GET["PARTNER"]); else $thereferer=trim(@$_GET["REFERER"]);
  325. print "<script src='/admin/savecookie.php?PARTNER=" . $thereferer . "&EXPIRES=" . $expireaffiliate . "'></script>";
  326. }*/
  327. //share a sale and commission junction affilates
  328. if(trim(@$_GET["ifrogz_affiliate"]) != "" || trim(@$_GET["ifrogz_affiliate"]) != ""){
  329. if(@$expireaffiliate == "") $expireaffiliate=30;
  330. if(trim(@$_GET["ifrogz_affiliate"])!="") $thereferer=trim(@$_GET["ifrogz_affiliate"]); else $thereferer=trim(@$_GET["REFERER"]);
  331. print "<script src='/admin/savecookie.php?ifrogz_affiliate=" . $thereferer . "&EXPIRES=" . $expireaffiliate . "'></script>";
  332. }
  333. //GET COUPON CODE FROM EMAIL
  334. /*if($_GET['utm_campaign'] == 'Free_Shipping_Dec_20_2007') {
  335. $_SESSION['os'] = 'freeshipping1220';
  336. }*/
  337. //echo '$_SESSION[os]='.$_SESSION['os'];
  338. //end sas and cj
  339. //$stockManage=0;
  340. function do_stock_management($smOrdId){
  341. global $stockManage;
  342. if($stockManage != 0){
  343. $sSQL="SELECT cartID,cartProdID,cartQuantity,pSell, pInStock FROM cart INNER JOIN products ON cart.cartProdID=products.pID WHERE pDropship=0 AND (cartCompleted=0 OR cartCompleted=2) AND cartOrderID='" . mysql_real_escape_string(unstripslashes($smOrdId)) . "'";
  344. $result1 = mysql_query($sSQL) or print(mysql_error());
  345. while($rs1 = mysql_fetch_array($result1)){
  346. if(($rs1["pSell"] & 2) == 2){
  347. $sSQL = "SELECT coOptID, optStyleID, optStock, coOptGroup FROM cartoptions INNER JOIN options ON cartoptions.coOptID=options.optID INNER JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE (optType=2 OR optType=-2) AND coCartID=" . $rs1["cartID"];
  348. $result2 = mysql_query($sSQL) or print(mysql_error());
  349. while($rs2 = mysql_fetch_array($result2)){
  350. $newQty = $rs1["cartQuantity"];
  351. // If this option is a Custom Hype Rim, then make quantity double. (They are ordered as pairs, but inventory is kept individually)
  352. // * Remember to change this in other places too ( release_stock(), getOnOrderStock(), and printpackingslips.php line 151 )
  353. if ($rs1['cartProdID'] == 'customhype' && strstr($rs2['coOptGroup'],'Rim')) {
  354. $newQty = $rs1["cartQuantity"] * 2;
  355. }
  356. $sSQL = "UPDATE options SET optStock=optStock-" . $newQty . " WHERE optID=" . $rs2["coOptID"];
  357. mysql_query($sSQL) or print(mysql_error());
  358. //record change
  359. $empID = $_SESSION['employee']['id'];
  360. if (empty($empID)) {
  361. $empID = 81;
  362. }
  363. $sql="INSERT INTO inv_adjustments (iaOptID, iaProdStyle, iaAmt, iaDate, iaReason, iaEmpID, iaOldValue, iaNewValue, iaNotes)
  364. VALUES ('".$rs2["coOptID"]."','".$rs1["cartProdID"]."-".$rs2["optStyleID"]."','-".$newQty."','".date('Y-m-d H:i:s')."','7','".$empID."',".$rs2["optStock"].",".($rs2["optStock"]-$rs1["cartQuantity"]).", 'ordID: $smOrdId')";
  365. //mail("chadsaun@gmail.com", "iFrogz Inv Test: Stock Manage", $sql);
  366. mysql_query($sql) or mail("chadsaun@gmail.com", "iFrogz Inv Test Error: Stock Manage", $sql);
  367. }
  368. mysql_free_result($result2);
  369. }else{
  370. $sSQL = "UPDATE products SET pInStock=pInStock-" . $rs1["cartQuantity"] . " WHERE pID='" . $rs1["cartProdID"] . "'";
  371. mysql_query($sSQL) or print(mysql_error());
  372. //record change
  373. $empID = $_SESSION['employee']['id'];
  374. if (empty($empID)) {
  375. $empID = 81;
  376. }
  377. $sql="INSERT INTO inv_adjustments (iaOptID,iaProdID,iaAmt,iaDate,iaReason,iaEmpID,iaOldValue,iaNewValue, iaNotes)
  378. VALUES ('0','".$rs1["cartProdID"]."','-".$rs1["cartQuantity"]."','".date('Y-m-d H:i:s')."','7','".$empID."',".$rs1["pInStock"].",".($rs1["pInStock"]-$rs1["cartQuantity"]).", 'ordID: $smOrdId')";
  379. //mail("chadsaun@gmail.com", "iFrogz Inv Test: Stock Manage", $sql);
  380. mysql_query($sql) or mail("chadsaun@gmail.com", "iFrogz Inv Test Error: Stock Manage", $sql);
  381. }
  382. }
  383. mysql_free_result($result1);
  384. }
  385. }
  386. function release_stock($smOrdId) {
  387. global $stockManage;
  388. if($stockManage != 0){
  389. $sSQL="SELECT cartID,cartProdID,cartQuantity,pSell,pDownload,p_iscert, pInStock FROM cart INNER JOIN products ON cart.cartProdID=products.pID WHERE products.pDropship=0 AND cartCompleted=1 AND cartOrderID=" . $smOrdId;
  390. $result = mysql_query($sSQL) or print(mysql_error());
  391. while($rs = mysql_fetch_array($result)){
  392. if((($rs["pSell"] & 2) == 2)){
  393. $sSQL = "SELECT coOptID, coCartOption, optStyleID, optStock, coOptGroup FROM cartoptions INNER JOIN options ON cartoptions.coOptID=options.optID INNER JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE (optType=2 OR optType=-2) AND coCartID=" . $rs["cartID"];
  394. $result2 = mysql_query($sSQL) or print(mysql_error());
  395. while($rs2 = mysql_fetch_array($result2)){
  396. $newQty = $rs["cartQuantity"];
  397. // If this option is a Custom Hype Rim, then make quantity double. (They are ordered as pairs, but inventory is kept individually)
  398. // * Remember to change this in other places too ( do_stock_management(), getOnOrderStock(), and printpackingslips.php line 151 )
  399. if ($rs['cartProdID'] == 'customhype' && strstr($rs2['coOptGroup'],'Rim')) {
  400. $newQty = $rs["cartQuantity"] * 2;
  401. }
  402. if (empty($newQty)) {
  403. $newQty = 0;
  404. }
  405. $sSQL = "UPDATE options SET optStock=optStock+" . $newQty . " WHERE optID=" . $rs2["coOptID"];
  406. mysql_query($sSQL) or print(mysql_error().$sSQL);
  407. //record change
  408. $empID = $_SESSION['employee']['id'];
  409. if (empty($empID)) {
  410. $empID = 81;
  411. }
  412. $sql="INSERT INTO inv_adjustments (iaOptID, iaProdStyle, iaAmt, iaDate, iaReason, iaEmpID, iaOldValue, iaNewValue, iaNotes)
  413. VALUES ('".$rs2["coOptID"]."', '".$rs["cartProdID"]."-".$rs2["optStyleID"]."', '".$newQty."', '".date('Y-m-d H:i:s')."', '6', '".$empID."', ".$rs2["optStock"].", ".($rs2["optStock"]+$rs["cartQuantity"]).", 'ordID: $smOrdId')";
  414. //mail("chadsaun@gmail.com", "iFrogz Inv Test: Release Stock", $sql);
  415. mysql_query($sql) or mail("chadsaun@gmail.com", "iFrogz Inv Test Error: Release Stock", $sql);
  416. }
  417. mysql_free_result($result2);
  418. }else{
  419. $sSQL = "UPDATE products SET pInStock=pInStock+" . $rs["cartQuantity"] . " WHERE pID='" . $rs["cartProdID"] . "'";
  420. mysql_query($sSQL) or print(mysql_error());
  421. //record change
  422. $empID = $_SESSION['employee']['id'];
  423. if (empty($empID)) {
  424. $empID = 81;
  425. }
  426. $sql="INSERT INTO inv_adjustments (iaOptID,iaProdID,iaAmt,iaDate,iaReason,iaEmpID,iaOldValue,iaNewValue, iaNotes)
  427. VALUES ('0','".$rs["cartProdID"]."','".$rs["cartQuantity"]."','".date('Y-m-d H:i:s')."','6','".$empID."',".$rs["pInStock"].",".($rs["pInStock"]+$rs["cartQuantity"]).", 'ordID: $smOrdId')";
  428. //mail("chadsaun@gmail.com", "iFrogz Inv Test: Release Stock", $sql);
  429. mysql_query($sql) or mail("chadsaun@gmail.com", "iFrogz Inv Test Error: Release Stock", $sql);
  430. }
  431. }
  432. mysql_free_result($result);
  433. }
  434. }
  435. //END
  436. function productdisplayscript($doaddprodoptions){
  437. global $prodoptions, $countryTax, $xxPrdEnt, $xxPrdChs, $xxPrd255, $xxOptOOS, $useStockManagement, $prodlist, $OWSP;
  438. global $currSymbol1,$currFormat1,$currSymbol2,$currFormat2,$currSymbol3,$currFormat3;
  439. if($currSymbol1!="" && $currFormat1=="") $currFormat1='%s <strong>' . $currSymbol1 . '</strong>';
  440. if($currSymbol2!="" && $currFormat2=="") $currFormat2='%s <strong>' . $currSymbol2 . '</strong>';
  441. if($currSymbol3!="" && $currFormat3=="") $currFormat3='%s <strong>' . $currSymbol3 . '</strong>';
  442. ?>
  443. <script language="JavaScript" type="text/javascript">
  444. <!--
  445. var aPC = new Array();<?php
  446. if($useStockManagement){ ?>
  447. var aPS = new Array();
  448. checkStock=function(x, i){
  449. if(i!='' && aPS[i] > 0)return(true);
  450. alert('<?php print str_replace("'","\'",$xxOptOOS)?>');
  451. x.focus();return(false);
  452. }<?php } ?>
  453. var isW3 = (document.getElementById&&true);
  454. var tax=<?php print $countryTax ?>;
  455. dummyfunc=function(){};
  456. <?php
  457. $prodoptions="";
  458. if($doaddprodoptions && $prodlist != ""){
  459. $sSQL = "SELECT DISTINCT optID," . $OWSP . "optPriceDiff,optStock,optDisplay_point FROM options INNER JOIN prodoptions ON options.optGroup=prodoptions.poOptionGroup WHERE prodoptions.poProdID IN (" . $prodlist . ")";
  460. $result = mysql_query($sSQL) or print(mysql_error());
  461. $rowcounter=0;
  462. while($row = mysql_fetch_array($result)){
  463. if($useStockManagement) print 'aPS[' . $row["optID"] . ']=' . ($row["optStock"]) . ';';
  464. print "aPC[". $row["optID"] . "]=" . $row["optPriceDiff"] . ";";
  465. if(($rowcounter % 10)==9) print "\r\n";
  466. $rowcounter++;
  467. }
  468. print "\r\n";
  469. }
  470. ?>
  471. pricechecker=function(i){
  472. if(i!='')return(aPC[i]);return(0);}
  473. enterValue=function(x){
  474. alert('<?php print str_replace("'","\'",$xxPrdEnt)?>');
  475. x.focus();return(false);}
  476. chooseOption=function(x){
  477. alert('<?php print str_replace("'","\'",$xxPrdChs)?>');
  478. x.focus();return(false);}
  479. dataLimit=function(x){
  480. alert('<?php print str_replace("'","\'",$xxPrd255)?>');
  481. x.focus();return(false);}
  482. formatprice=function(i, currcode, currformat){
  483. <?php
  484. $tempStr = FormatEuroCurrency(0);
  485. $tempStr2 = number_format(0,2,".",",");
  486. print "var pTemplate='" . $tempStr . "';\n";
  487. print "if(currcode!='') pTemplate=' " . $tempStr2 . "' + (currcode!=' '?'<strong>'+currcode+'<\/strong>':'');";
  488. if(strstr($tempStr,",") || strstr($tempStr,".")){ ?>
  489. if(currcode==' JPY')i = Math.round(i).toString();
  490. else if(i==Math.round(i))i=i.toString()+".00";
  491. else if(i*10.0==Math.round(i*10.0))i=i.toString()+"0";
  492. else if(i*100.0==Math.round(i*100.0))i=i.toString();
  493. <?php }
  494. print 'if(currcode!="")pTemplate = currformat.toString().replace(/%s/,i.toString());';
  495. print 'else pTemplate = pTemplate.toString().replace(/\d[,.]*\d*/,i.toString());';
  496. if(strstr($tempStr,","))
  497. print "return(pTemplate.replace(/\./,','));";
  498. else
  499. print "return(pTemplate);";
  500. ?>}
  501. openEFWindow= function(id) {
  502. window.open('/emailfriend.php?utm_source=emailfriend&id='+id,'email_friend','menubar=no, scrollbars=no, width=400, height=460, directories=no,location=no,resizable=yes,status=no,toolbar=no')
  503. }
  504. //-->
  505. </script><?php
  506. }
  507. function updatepricescript($doaddprodoptions){
  508. global $prodoptions,$Count,$rs,$WSP,$noprice,$pricezeromessage,$showtaxinclusive,$currRate1,$currRate2,$currRate3,$currSymbol1,$currSymbol2,$currSymbol3,$currFormat1,$currFormat2,$currFormat3,$useStockManagement,$currencyseparator;
  509. $pPrice_adj=1;
  510. if(!empty($WSP)) $pPrice_adj=getPricingAdj($_SESSION['custID'],1,$rs["pPricing_group"]);
  511. ?>
  512. <script language="JavaScript" type="text/javascript">
  513. <!--
  514. formvalidator<?php print $Count?>= function(theForm){
  515. <?php
  516. $prodoptions="";
  517. $hasonepriceoption=FALSE;
  518. if($doaddprodoptions){
  519. $sSQL = "SELECT poOptionGroup,optType,optFlags FROM prodoptions LEFT JOIN optiongroup ON optiongroup.optGrpID=prodoptions.poOptionGroup WHERE poProdID='" . $rs["pId"] . "' ORDER BY poID";
  520. $result = mysql_query($sSQL) or print(mysql_error());
  521. for($rowcounter=0;$rowcounter<mysql_num_rows($result);$rowcounter++){
  522. $prodoptions[$rowcounter] = mysql_fetch_array($result);
  523. }
  524. if(is_array($prodoptions)){
  525. foreach($prodoptions as $rowcounter => $theopt){
  526. if($theopt["optType"]==3){
  527. print "if(theForm.voptn" . $rowcounter . ".value=='')return(enterValue(theForm.voptn" . $rowcounter . "));\n";
  528. print "if(theForm.voptn" . $rowcounter . ".value.length>255)return(dataLimit(theForm.voptn" . $rowcounter . "));\n";
  529. }elseif(abs($theopt["optType"])==2){
  530. $hasonepriceoption=TRUE;
  531. if($theopt["optType"]==2)
  532. print 'if(theForm.optn' . $rowcounter . '.selectedIndex==0)return(chooseOption(theForm.optn' . $rowcounter . "));\n";
  533. if($useStockManagement && (($rs["pSell"] & 2) == 2)) print 'if(!checkStock(theForm.optn' . $rowcounter . ',theForm.optn' . $rowcounter . '.options[theForm.optn' . $rowcounter . '.selectedIndex].value))return(false);' . "\r\n";
  534. }
  535. }
  536. }
  537. }
  538. if(@$customvalidator != "") print $customvalidator;
  539. ?>return (true);
  540. }
  541. <?php
  542. if(@$noprice!=TRUE && ! ($rs["pPrice"]==0 && @$pricezeromessage != "") && $hasonepriceoption){
  543. print 'updateprice' . $Count . "= function(){\r\n";
  544. print 'var totAdd=' . ($rs["pPrice"]*$pPrice_adj) . ";\r\n";
  545. print 'if(!isW3) return;';
  546. foreach($prodoptions as $rowcounter => $theopt){
  547. if(abs($theopt["optType"])!=3){
  548. if(($theopt["optFlags"]&1)==1)
  549. print 'totAdd=totAdd+((' . ($rs["pPrice"]*$pPrice_adj) . "*pricechecker(document.forms.tForm" . $Count . ".optn" . $rowcounter . ".options[document.forms.tForm" . $Count . ".optn" . $rowcounter . ".selectedIndex].value))/100.0);\n";
  550. else
  551. print 'totAdd=totAdd+pricechecker(document.forms.tForm' . $Count . ".optn" . $rowcounter . ".options[document.forms.tForm" . $Count . ".optn" . $rowcounter . ".selectedIndex].value);\n";
  552. }
  553. }
  554. print "document.getElementById('pricediv" . $Count . "').innerHTML=formatprice(Math.round(totAdd*100.0)/100.0, '', '');\r\n";
  555. if(@$showtaxinclusive && ($rs["pExemptions"] & 2)!=2) print "document.getElementById('pricedivti" . $Count . "').innerHTML=formatprice(Math.round((totAdd+(totAdd*tax/100.0))*100.0)/100.0, '', '');\n";
  556. $extracurr = "";
  557. if($currRate1!=0 && $currSymbol1!="") $extracurr = "+formatprice(Math.round((totAdd*" . $currRate1 . ")*100.0)/100.0, ' " . $currSymbol1 . "','" . str_replace("'","\'",$currFormat1) . "')+'".str_replace("'","\'",$currencyseparator)."'\n";
  558. if($currRate2!=0 && $currSymbol2!="") $extracurr .= "+formatprice(Math.round((totAdd*" . $currRate2 . ")*100.0)/100.0, ' " . $currSymbol2 . "','" . str_replace("'","\'",$currFormat2) . "')+'".str_replace("'","\'",$currencyseparator)."'\n";
  559. if($currRate3!=0 && $currSymbol3!="") $extracurr .= "+formatprice(Math.round((totAdd*" . $currRate3 . ")*100.0)/100.0, ' " . $currSymbol3 . "','" . str_replace("'","\'",$currFormat3) . "');\n";
  560. if($extracurr!="") print "document.getElementById('pricedivec" . $Count . "').innerHTML=''" . $extracurr . "\r\n";
  561. print "}";
  562. }
  563. ?>//-->
  564. </script><?php
  565. }
  566. //////////////
  567. //// added by blake for auto add products
  568. function productdisplayscript2($doaddprodoptions){
  569. global $prodoptions, $countryTax, $xxPrdEnt, $xxPrdChs, $xxPrd255, $xxOptOOS, $useStockManagement, $prodlist, $OWSP;
  570. global $currSymbol1,$currFormat1,$currSymbol2,$currFormat2,$currSymbol3,$currFormat3;
  571. if($currSymbol1!="" && $currFormat1=="") $currFormat1='%s <strong>' . $currSymbol1 . '</strong>';
  572. if($currSymbol2!="" && $currFormat2=="") $currFormat2='%s <strong>' . $currSymbol2 . '</strong>';
  573. if($currSymbol3!="" && $currFormat3=="") $currFormat3='%s <strong>' . $currSymbol3 . '</strong>';
  574. ?>
  575. <script language="JavaScript" type="text/javascript">
  576. var taPC = new Array();<?php
  577. if($useStockManagement){ ?>
  578. var taPS = new Array();
  579. tcheckStock=function(x, i){
  580. if(i!='' && taPS[i] > 0)return(true);
  581. alert('<?php print str_replace("'","\'",$xxOptOOS)?>');
  582. x.focus();return(false);
  583. }<?php } ?>
  584. tisW3 = (document.getElementById&&true);
  585. //alert(tisW3);
  586. var ttax=<?php print $countryTax ?>;
  587. tdummyfunc=function(){};
  588. <?php
  589. $prodoptions="";
  590. if($doaddprodoptions && $prodlist != ""){
  591. $sSQL = "SELECT DISTINCT optID," . $OWSP . "optPriceDiff,optStock,optDisplay_point
  592. FROM options INNER JOIN prodoptions ON options.optGroup=prodoptions.poOptionGroup
  593. WHERE prodoptions.poProdID IN (" . $prodlist . ")";
  594. $result = mysql_query($sSQL) or print(mysql_error());
  595. $rowcounter=0;
  596. while($row = mysql_fetch_array($result)){
  597. if ($useStockManagement) {
  598. print 'taPS[' . $row["optID"] . ']=' . ($row["optStock"]) . ';';
  599. }
  600. print "taPC[". $row["optID"] . "]=" . $row["optPriceDiff"] . ";";
  601. if(($rowcounter % 10)==9) print "\r\n";
  602. $rowcounter++;
  603. }
  604. print "\r\n";
  605. }
  606. ?>
  607. tpricechecker=function(i){
  608. if(i!='')return(taPC[i]);return(0);}
  609. tenterValue=function(x){
  610. alert('<?php print str_replace("'","\'",$xxPrdEnt)?>');
  611. x.focus();return(false);}
  612. tchooseOption=function(x){
  613. alert('<?php print str_replace("'","\'",$xxPrdChs)?>');
  614. x.focus();return(false);}
  615. tdataLimit=function(x){
  616. alert('<?php print str_replace("'","\'",$xxPrd255)?>');
  617. x.focus();return(false);}
  618. tformatprice=function(i, currcode, currformat){
  619. <?php
  620. $tempStr = FormatEuroCurrency(0);
  621. $tempStr2 = number_format(0,2,".",",");
  622. print "var pTemplate='" . $tempStr . "';\n";
  623. print "if(currcode!='') pTemplate=' " . $tempStr2 . "' + (currcode!=' '?'<strong>'+currcode+'<\/strong>':'');";
  624. if(strstr($tempStr,",") || strstr($tempStr,".")){ ?>
  625. if(currcode==' JPY')i = Math.round(i).toString();
  626. else if(i==Math.round(i))i=i.toString()+".00";
  627. else if(i*10.0==Math.round(i*10.0))i=i.toString()+"0";
  628. else if(i*100.0==Math.round(i*100.0))i=i.toString();
  629. <?php }
  630. print 'if(currcode!="")pTemplate = currformat.toString().replace(/%s/,i.toString());';
  631. print 'else pTemplate = pTemplate.toString().replace(/\d[,.]*\d*/,i.toString());';
  632. if(strstr($tempStr,","))
  633. print "return(pTemplate.replace(/\./,','));";
  634. else
  635. print "return(pTemplate);";
  636. ?>}
  637. topenEFWindow= function(id) {
  638. window.open('/emailfriend.php?utm_source=emailfriend&id='+id,'email_friend','menubar=no, scrollbars=no, width=400, height=460, directories=no,location=no,resizable=yes,status=no,toolbar=no')
  639. }
  640. </script><?php
  641. }
  642. function updatepricescript2($doaddprodoptions){
  643. global $prodoptions,$Count,$rs,$WSP,$noprice,$pricezeromessage,$showtaxinclusive,$currRate1,$currRate2,$currRate3,$currSymbol1,$currSymbol2,$currSymbol3,$currFormat1,$currFormat2,$currFormat3,$useStockManagement,$currencyseparator;
  644. $pPrice_adj=1;
  645. if(!empty($WSP)) $pPrice_adj=getPricingAdj($_SESSION['custID'],1,$rs["pPricing_group"]);
  646. ?>
  647. <script language="JavaScript" type="text/javascript">
  648. tformvalidator<?php print $Count?>= function(theForm){
  649. <?php
  650. $prodoptions="";
  651. $hasonepriceoption=FALSE;
  652. if($doaddprodoptions){
  653. $sSQL = "SELECT poOptionGroup,optType,optFlags FROM prodoptions LEFT JOIN optiongroup ON optiongroup.optGrpID=prodoptions.poOptionGroup WHERE poProdID='" . $rs["pId"] . "' ORDER BY poID";
  654. $result = mysql_query($sSQL) or print(mysql_error());
  655. for($rowcounter=0;$rowcounter<mysql_num_rows($result);$rowcounter++){
  656. $prodoptions[$rowcounter] = mysql_fetch_array($result);
  657. }
  658. if(is_array($prodoptions)){
  659. foreach($prodoptions as $rowcounter => $theopt){
  660. if($theopt["optType"]==3){
  661. print "if(theForm.voptn" . $rowcounter . ".value=='')return(tenterValue(theForm.voptn" . $rowcounter . "));\n";
  662. print "if(theForm.voptn" . $rowcounter . ".value.length>255)return(tdataLimit(theForm.voptn" . $rowcounter . "));\n";
  663. }elseif(abs($theopt["optType"])==2){
  664. $hasonepriceoption=TRUE;
  665. if($theopt["optType"]==2)
  666. print 'if(theForm.optn_' .$Count. '_' . $rowcounter . '.selectedIndex==0)return(tchooseOption(theForm.optn_' .$Count. '_' . $rowcounter . "));\n";
  667. if($useStockManagement && (($rs["pSell"] & 2) == 2)) print 'if(!tcheckStock(theForm.optn_' .$Count. '_' . $rowcounter . ',theForm.optn_' .$Count. '_' . $rowcounter . '.options[theForm.optn_' .$Count. '_' . $rowcounter . '.selectedIndex].value))return(false);' . "\r\n";
  668. }
  669. }
  670. }
  671. }
  672. if(@$customvalidator != "") print $customvalidator;
  673. ?>return (true);
  674. }
  675. <?php
  676. if(@$noprice!=TRUE && ! ($rs["pPrice"]==0 && @$pricezeromessage != "") && $hasonepriceoption){
  677. print 'tupdateprice' . $Count . "= function(){\r\n";
  678. print 'var totAdd=' . ($rs["pPrice"]*$pPrice_adj) . ";\r\n";
  679. print 'if(!tisW3) return;';
  680. foreach($prodoptions as $rowcounter => $theopt){
  681. if(abs($theopt["optType"])!=3){
  682. if(($theopt["optFlags"]&1)==1)
  683. print 'totAdd=totAdd+((' . ($rs["pPrice"]*$pPrice_adj) . "*tpricechecker(document.forms.tForm" . $Count . ".optn_" .$Count. "_" . $rowcounter . ".options[document.forms.tForm" . $Count . ".optn_" .$Count. "_" . $rowcounter . ".selectedIndex].value))/100.0);\n";
  684. else
  685. print 'totAdd=totAdd+tpricechecker(document.forms.tForm' . $Count . ".optn_" .$Count. "_" . $rowcounter . ".options[document.forms.tForm" . $Count . ".optn_" .$Count. "_" . $rowcounter . ".selectedIndex].value);\n";
  686. }
  687. }
  688. print "document.getElementById('pricediv" . $Count . "').innerHTML=tformatprice(Math.round(totAdd*100.0)/100.0, '', '');\r\n";
  689. if(@$showtaxinclusive && ($rs["pExemptions"] & 2)!=2) print "document.getElementById('pricedivti" . $Count . "').innerHTML=tformatprice(Math.round((totAdd+(totAdd*tax/100.0))*100.0)/100.0, '', '');\n";
  690. $extracurr = "";
  691. if($currRate1!=0 && $currSymbol1!="") $extracurr = "+tformatprice(Math.round((totAdd*" . $currRate1 . ")*100.0)/100.0, ' " . $currSymbol1 . "','" . str_replace("'","\'",$currFormat1) . "')+'".str_replace("'","\'",$currencyseparator)."'\n";
  692. if($currRate2!=0 && $currSymbol2!="") $extracurr .= "+tformatprice(Math.round((totAdd*" . $currRate2 . ")*100.0)/100.0, ' " . $currSymbol2 . "','" . str_replace("'","\'",$currFormat2) . "')+'".str_replace("'","\'",$currencyseparator)."'\n";
  693. if($currRate3!=0 && $currSymbol3!="") $extracurr .= "+tformatprice(Math.round((totAdd*" . $currRate3 . ")*100.0)/100.0, ' " . $currSymbol3 . "','" . str_replace("'","\'",$currFormat3) . "');\n";
  694. if($extracurr!="") print "document.getElementById('pricedivec" . $Count . "').innerHTML=''" . $extracurr . "\r\n";
  695. print "}";
  696. }
  697. ?>
  698. </script><?php
  699. }
  700. function checkRelatedDiscounts(){
  701. global $WSP;
  702. $newprice="";
  703. $sSQL = "SELECT cartID,cartProdID,cartAltPrice,cartProdPrice,cartQuantity FROM cart WHERE cartCompleted=0 AND cartSessionID='" . session_id() . "'";
  704. $total_in_cart=0;
  705. $result = mysql_query($sSQL) or print(mysql_error());
  706. $i=0;
  707. while($rs=mysql_fetch_assoc($result)){
  708. $reldisc[$i]=$rs;
  709. $reldisc[$i][$rs['cartProdID']]['rel_disc']+=$rs['cartQuantity'];
  710. $i++;
  711. }
  712. $total_in_cart=calculateTotal();
  713. //echo "<br />Total=".$total_in_cart;
  714. $cnt=count($reldisc);
  715. for($j=0;$j<$cnt;$j++){
  716. $sql_mini="SELECT *
  717. FROM related_discounts rd
  718. LEFT JOIN products p ON rd.relProd=p.pID
  719. WHERE relProd='".$reldisc[$j]['cartProdID']."'
  720. AND IF(relBegin != '0000-00-00 00:00:00', relBegin <= '" . date('Y-m-d H:i:s') . "', 1=1) AND IF(relEnd != '0000-00-00 00:00:00', relEnd > '" . date('Y-m-d H:i:s') . "', 1=1)";
  721. //$sql_mini.= " AND relCartTotal+pPrice<=".$total_in_cart;
  722. //echo $sql_mini;
  723. $result_mini=mysql_query($sql_mini);
  724. $num_rows=mysql_num_rows($result_mini);
  725. if($num_rows>0) {
  726. $rs_mini=mysql_fetch_assoc($result_mini);
  727. //echo $rs_mini['relCartTotal'].'<='.($total_in_cart.' - '.$reldisc[$j]['cartProdPrice']);
  728. if ($rs_mini['relPrice']>-1) {
  729. if (($rs_mini['relCartTotal']<=$total_in_cart-$reldisc[$j]['cartProdPrice']) && $rs_mini['relNumber']>=($reldisc[$j][$rs_mini['relProd']]['rel_disc']+$prodcnt[$rs_mini['relProd']])){
  730. //echo "<br />".'Test'.$rs_mini['relNumber'].'<'.$reldisc[$j][$reldisc[$j]['cartProdID']]['rel_disc']."<br />";
  731. $theprice = $rs_mini['relPrice'];
  732. $cartAltPrice = $rs_mini['relPrice'];
  733. //echo '$rs_mini[relPrice]='.$rs_mini['relPrice'];
  734. //echo '$prodcnt[$rs_mini[relProd]]='.$prodcnt[$reldisc[$j]['cartProdID']]."<br />";
  735. $prodcnt[$rs_mini['relProd']]++;
  736. } else {
  737. $sql_p = "SELECT pPrice FROM products WHERE pID='".$reldisc[$j]['cartProdID']."'";
  738. $result = mysql_query($sql_p);
  739. $rs_p = mysql_fetch_assoc($result);
  740. //if($reldisc[$i]['cartProdPrice']!=$rs_p['pPrice'])$theprice=$reldisc[$j]['cartProdPrice'];
  741. //else
  742. $theprice = $rs_p['pPrice'];
  743. $cartAltPrice = -1;
  744. }
  745. //echo "<br />".$reldisc[$j]['cartProdID'].'-'.$theprice."-".$reldisc[$j]['cartQuantity']."<br />";
  746. $sSQL = "UPDATE cart SET cartProdPrice='".$theprice."', cartAltPrice='".$cartAltPrice."' WHERE cartCompleted=0 AND cartSessionID='" . session_id() . "' AND cartID='".mysql_real_escape_string($reldisc[$j]['cartID'])."'";
  747. //echo $sSQL;
  748. mysql_query($sSQL) or print(mysql_error().$sSQL);
  749. }
  750. }
  751. }
  752. }
  753. function calculateTotal(){
  754. //global $totaldiscounts;
  755. $sSQL = "SELECT SUM(cartProdPrice*cartQuantity) AS totalPrice FROM cart c LEFT JOIN products p ON c.cartProdID=p.pID WHERE cartCompleted=0 AND cartSessionID='" . session_id() . "'";
  756. $result = mysql_query($sSQL) or print(mysql_error());
  757. if($rs=mysql_fetch_assoc($result)){
  758. //echo "<br />======".$rs['totalPrice'].'-'.$_SESSION["discounts"]."<br />";
  759. return $rs['totalPrice']-$_SESSION["discounts"];
  760. }
  761. }
  762. ///// end auto add ////
  763. function checkDPs($currcode){
  764. if($currcode=="JPY") return(0); else return(2);
  765. }
  766. function checkCurrencyRates($currConvUser,$currConvPw,$currLastUpdate,&$currRate1,$currSymbol1,&$currRate2,$currSymbol2,&$currRate3,$currSymbol3){
  767. global $countryCurrency,$usecurlforfsock,$pathtocurl,$curlproxy;
  768. $ccsuccess = true;
  769. if($currConvUser!="" && $currConvPw!="" && (strtotime($currLastUpdate) < time()-(60*60*24))){
  770. $str = "";
  771. if($currSymbol1!="") $str .= "&curr=" . $currSymbol1;
  772. if($currSymbol2!="") $str .= "&curr=" . $currSymbol2;
  773. if($currSymbol3!="") $str .= "&curr=" . $currSymbol3;
  774. if($str==""){
  775. mysql_query("UPDATE admin SET currLastUpdate='" . date("Y-m-d H:i:s", time()) . "'") or print(mysql_error());
  776. return;
  777. }
  778. $str = "?source=" . $countryCurrency . "&user=" . $currConvUser . "&pw=" . $currConvPw . $str;
  779. if(@$usecurlforfsock){
  780. if(@$pathtocurl != ""){
  781. exec($pathtocurl . ' --data-binary \'' . str_replace("'","\'","X") . '\' http://www.ecommercetemplates.com/currencyxml.asp' . $str, $res, $retvar);
  782. $sXML = implode("\n",$res);
  783. }else{
  784. if (!$ch = curl_init()) {
  785. $success = false;
  786. $errormsg = "cURL package not installed in PHP";
  787. $ccsuccess = FALSE;
  788. }else{
  789. curl_setopt($ch, CURLOPT_URL,'http://www.ecommercetemplates.com/currencyxml.asp' . $str);
  790. curl_setopt($ch, CURLOPT_POST, 1);
  791. curl_setopt($ch, CURLOPT_HEADER, 0);
  792. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  793. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  794. curl_setopt($ch, CURLOPT_POSTFIELDS, "X");
  795. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  796. if(@$curlproxy!=''){
  797. curl_setopt($ch, CURLOPT_PROXY, $curlproxy);
  798. }
  799. $sXML = curl_exec($ch);
  800. if(curl_error($ch) != "") print "Error with cURL installation: " . curl_error($ch) . "<br />";
  801. curl_close($ch);
  802. }
  803. }
  804. }else{
  805. $header = "POST /currencyxml.asp" . $str . " HTTP/1.0\r\n";
  806. $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  807. $header .= "Content-Length: 1\r\n\r\n";
  808. $fp = fsockopen ('www.ecommercetemplates.com', 80, $errno, $errstr, 30);
  809. if (!$fp){
  810. echo "$errstr ($errno)"; // HTTP error handling
  811. $ccsuccess = FALSE;
  812. }else{
  813. fputs ($fp, $header . "X");
  814. $sXML="";
  815. while (!feof($fp))
  816. $sXML .= fgets ($fp, 1024);
  817. }
  818. }
  819. if($ccsuccess){
  820. // print str_replace("<","<br />&lt;",$sXML) . "<br />\n";
  821. $xmlDoc = new vrXMLDoc($sXML);
  822. $nodeList = $xmlDoc->nodeList->childNodes[0];
  823. for($j = 0; $j < $nodeList->length; $j++){
  824. if($nodeList->nodeName[$j]=="currError"){
  825. print $nodeList->nodeValue[$j];
  826. $ccsuccess = false;
  827. }elseif($nodeList->nodeName[$j]=="selectedCurrency"){
  828. $e = $nodeList->childNodes[$j];
  829. $currRate = 0;
  830. for($i = 0; $i < $e->length; $i++){
  831. if($e->nodeName[$i]=="currSymbol")
  832. $currSymbol = $e->nodeValue[$i];
  833. elseif($e->nodeName[$i]=="currRate")
  834. $currRate = $e->nodeValue[$i];
  835. }
  836. if($currSymbol1 == $currSymbol){
  837. $currRate1 = $currRate;
  838. mysql_query("UPDATE admin SET currRate1=" . $currRate . " WHERE adminID=1") or print(mysql_error());
  839. }
  840. if($currSymbol2 == $currSymbol){
  841. $currRate2 = $currRate;
  842. mysql_query("UPDATE admin SET currRate2=" . $currRate . " WHERE adminID=1") or print(mysql_error());
  843. }
  844. if($currSymbol3 == $currSymbol){
  845. $currRate3 = $currRate;
  846. mysql_query("UPDATE admin SET currRate3=" . $currRate . " WHERE adminID=1") or print(mysql_error());
  847. }
  848. }
  849. }
  850. if($ccsuccess) mysql_query("UPDATE admin SET currLastUpdate='" . date("Y-m-d H:i:s", time()) . "'");
  851. }
  852. }
  853. }
  854. function getsectionids($thesecid, $delsections){
  855. $secid = $thesecid;
  856. $iterations = 0;
  857. $iteratemore = TRUE;
  858. if(@$_SESSION["clientLoginLevel"] != "") $minloglevel=$_SESSION["clientLoginLevel"]; else $minloglevel=0;
  859. if($delsections) $nodel = ""; else $nodel = 'sectionDisabled<=' . $minloglevel . ' AND ';
  860. while($iteratemore && $iterations<10){
  861. $sSQL2 = "SELECT DISTINCT sectionID,rootSection FROM sections WHERE " . $nodel . "(topSection IN (" . $secid . ") OR (sectionID IN (" . $secid . ") AND rootSection=1))";
  862. $secid = "";
  863. $iteratemore = FALSE;
  864. $result2 = mysql_query($sSQL2) or print(mysql_error());
  865. $addcomma = "";
  866. while($rs2 = mysql_fetch_assoc($result2)){
  867. if($rs2["rootSection"]==0) $iteratemore = TRUE;
  868. $secid .= $addcomma . $rs2["sectionID"];
  869. $addcomma = ",";
  870. }
  871. $iterations++;
  872. }
  873. if($secid=="") $secid = "0";
  874. return($secid);
  875. }
  876. function getpayprovdetails($ppid,&$ppdata1,&$ppdata2,&$ppdata3,&$ppdemo,&$ppmethod){
  877. $sSQL = "SELECT payProvData1,payProvData2,payProvData3,payProvDemo,payProvMethod FROM payprovider WHERE payProvEnabled=1 AND payProvID='" . mysql_real_escape_string($ppid) . "'";
  878. $result = mysql_query($sSQL) or print(mysql_error());
  879. if($rs = mysql_fetch_assoc($result)){
  880. $ppdata1 = trim($rs['payProvData1']);
  881. $ppdata2 = trim($rs['payProvData2']);
  882. $ppdata3 = trim($rs['payProvData3']);
  883. $ppdemo = ((int)$rs['payProvDemo']==1);
  884. $ppmethod = (int)$rs['payProvMethod'];
  885. }else
  886. return(FALSE);
  887. return(TRUE);
  888. }
  889. function callcurlfunction($cfurl, $cfxml, &$cfres, &$cfcert, &$cferrmsg, $settimeouts){
  890. global $curlproxy,$pathtocurl;
  891. $cfsuccess=TRUE;
  892. //print str_replace("<","<br />&lt;",str_replace("</","&lt;/",$cfxml)) . "<br />\n";
  893. if(@$pathtocurl != ""){
  894. exec($pathtocurl . ($cfcert != '' ? ' -E \'' . $cfcert . '\'' : '') . ' --data-binary \'' . str_replace("'","\'",$cfxml) . '\' ' . $cfurl, $cfres, $retvar);
  895. $cfres = implode("\n",$cfres);
  896. }else{
  897. if (!$ch = curl_init()) {
  898. $cferrmsg = "cURL package not installed in PHP. Set \$pathtocurl parameter.";
  899. $cfsuccess=FALSE;
  900. }else{
  901. curl_setopt($ch, CURLOPT_URL, $cfurl);
  902. if($cfcert != '') curl_setopt($ch, CURLOPT_SSLCERT, $cfcert);
  903. curl_setopt($ch, CURLOPT_POST, 1);
  904. curl_setopt($ch, CURLOPT_HEADER, 0);
  905. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  906. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  907. curl_setopt($ch, CURLOPT_POSTFIELDS, $cfxml);
  908. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  909. if($settimeouts) curl_setopt($ch, CURLOPT_TIMEOUT, 120);
  910. if(@$curlproxy!=''){
  911. curl_setopt($ch, CURLOPT_PROXY, $curlproxy);
  912. }
  913. $cfres = curl_exec($ch);
  914. //print str_replace("<","<br />&lt;",str_replace("</","&lt;/",$cfres)) . "<br />\n";
  915. if(curl_error($ch) != ""){
  916. if($cfcert != '' && ! file_exists($cfcert)){
  917. $cferrmsg='Certificate file not found: ' . $cfcert . '<br />';
  918. }else
  919. $cferrmsg='cURL error: ' . curl_error($ch) . '<br />';
  920. $cfsuccess=FALSE;
  921. }else{
  922. curl_close($ch);
  923. }
  924. }
  925. }
  926. return($cfsuccess);
  927. }
  928. function writehiddenvar($hvname,$hvval){
  929. print '<input type="hidden" name="' . $hvname . '" id="' . $hvname . '" value="' . str_replace('"','&quot;',$hvval) . '" />' . "\r\n";
  930. }
  931. function ppsoapheader($username, $password){
  932. return '<?xml version="1.0" encoding="utf-8"?>' .
  933. '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">' .
  934. ' <soap:Header>' .
  935. ' <RequesterCredentials xmlns="urn:ebay:api:PayPalAPI">' .
  936. ' <Credentials xmlns="urn:ebay:apis:eBLBaseComponents">' .
  937. ' <Username>' . $username . '</Username>' .
  938. ' <ebl:Password xmlns:ebl="urn:ebay:apis:eBLBaseComponents">' . $password . '</ebl:Password>' .
  939. ' </Credentials>' .
  940. ' </RequesterCredentials>' .
  941. ' </soap:Header>';
  942. }
  943. if(@$enableclientlogin==TRUE){
  944. if(@$_SESSION["clientUser"] != ""){
  945. }elseif(@$_POST["checktmplogin"]=="1" && @$_POST["sessionid"] != ""){
  946. $sSQL = "SELECT tmploginname FROM tmplogin WHERE tmploginid='" . trim(@$_POST["sessionid"]) . "'";
  947. $result = mysql_query($sSQL) or print(mysql_error());
  948. if($rs = mysql_fetch_array($result)){
  949. $_SESSION["clientUser"]=$rs["tmploginname"];
  950. mysql_free_result($result);
  951. mysql_query("DELETE FROM tmplogin WHERE tmploginid='" . trim(@$_POST["sessionid"]) . "'") or print(mysql_error());
  952. $sSQL = "SELECT clientActions,clientLoginLevel,clientPercentDiscount FROM clientlogin WHERE clientUser='" . $_SESSION["clientUser"] . "'";
  953. $result = mysql_query($sSQL) or print(mysql_error());
  954. if($rs = mysql_fetch_array($result)){
  955. $_SESSION["clientActions"]=$rs["clientActions"];
  956. $_SESSION["clientLoginLevel"]=$rs["clientLoginLevel"];
  957. $_SESSION["clientPercentDiscount"]=(100.0-(double)$rs["clientPercentDiscount"])/100.0;
  958. }
  959. }
  960. mysql_free_result($result);
  961. }elseif(@$_COOKIE["WRITECLL"] != ""){
  962. $sSQL = "SELECT clientUser,clientActions,clientLoginLevel,clientPercentDiscount FROM clientlogin WHERE clientUser='" . trim($_COOKIE["WRITECLL"]) . "' AND clientPW='" . trim($_COOKIE["WRITECLP"]) . "'";
  963. $result = mysql_query($sSQL) or print(mysql_error());
  964. if($rs = mysql_fetch_array($result)){
  965. $_SESSION["clientUser"]=$rs["clientUser"];
  966. $_SESSION["clientActions"]=$rs["clientActions"];
  967. $_SESSION["clientLoginLevel"]=$rs["clientLoginLevel"];
  968. $_SESSION["clientPercentDiscount"]=(100.0-(double)$rs["clientPercentDiscount"])/100.0;
  969. }
  970. mysql_free_result($result);
  971. }
  972. if(@$requiredloginlevel != ""){
  973. if((int)$requiredloginlevel > @$_SESSION["clientLoginLevel"]){
  974. ob_end_clean();
  975. if(@$_SERVER["HTTPS"] == "on" || @$_SERVER["SERVER_PORT"] == "443")$prot='https://';else $prot='http://';
  976. header('Location: /admin/clientlogin.php?refurl=' . urlencode(@$_SERVER["PHP_SELF"] . (@$_SERVER["QUERY_STRING"] !="" ? "?" . @$_SERVER["QUERY_STRING"] : "")));
  977. exit();
  978. }
  979. }
  980. }
  981. function isPermitted($permission = 'all') {
  982. global $_SESSION;
  983. $mappings = array(
  984. 'accounting' => 'i_f_t',
  985. 'admin' => 'i_f_a',
  986. 'all' => 'all',
  987. 'customer service' => 'i_f_c',
  988. 'customer service admin' => 'i_f_ca', // deprecated
  989. 'hong kong' => 'i_f_h',
  990. 'inventory' => 'i_f_v',
  991. 'it' => 'i_f_i',
  992. 'management' => 'i_f_m',
  993. 'nadal' => 'i_f_n', // deprecated
  994. 'product' => 'i_f_p',
  995. 'quality control' => 'i_f_qc',
  996. 'reports_retail' => 'i_f_rr',
  997. 'sales' => 'i_f_sa',
  998. 'shieldzone' => 'i_f_z', // deprecated
  999. 'shipping' => 'i_f_s',
  1000. );
  1001. $permission = strtolower($permission);
  1002. if (isset($mappings[$permission])) {
  1003. $permission = $mappings[$permission];
  1004. }
  1005. if (isset($_SESSION['employee']['permissions'])) {
  1006. $roles = preg_split('/,+/', $_SESSION['employee']['permissions']);
  1007. $length = count($roles);
  1008. for ($i = 0; $i < $length; $i++) {
  1009. $roles[$i] = trim($roles[$i]);
  1010. if (!empty($roles[$i]) && ($roles[$i] == $permission)) {
  1011. return TRUE;
  1012. }
  1013. }
  1014. }
  1015. return FALSE;
  1016. }
  1017. function showarray($array)
  1018. {
  1019. echo '<ul>';
  1020. foreach($array as $k=>$v)
  1021. {
  1022. if(is_array($v))
  1023. {
  1024. echo '<li>K:'.$k.'</li>';
  1025. showarray($v);
  1026. }
  1027. else
  1028. {
  1029. echo '<li>'.$k.'='.$v.'</li>';
  1030. }
  1031. }
  1032. echo '</ul>';
  1033. }
  1034. // END ADDED
  1035. // ADDED by Chad (Mar30,06) set new location
  1036. // + location = INT
  1037. // + ordID = INT
  1038. function setNewLocation($location,$ordID,$type='Automatic',$reason='') {
  1039. global $_SESSION;
  1040. if(empty($ordID)) {
  1041. return false;
  1042. }
  1043. $qry = "SELECT statPrivate FROM orderstatus WHERE statID = $location";
  1044. if(!$res = mysql_query($qry)) {
  1045. echo '1';
  1046. return false;
  1047. }
  1048. if(!$row = mysql_fetch_assoc($res)) {
  1049. echo '2';
  1050. return false;
  1051. }
  1052. $locName = $row['statPrivate'];
  1053. mysql_free_result($res);
  1054. $qry = "INSERT INTO location ( ordID , employeeID , stamp , statNum , location , locType , locTypeReason )
  1055. VALUES ( $ordID , '".$_SESSION["employee"]["id"]."' , '".date("Y-m-d H:i:s")."' , '".$location."' ,
  1056. '$locName' , '$type' , '$reason' )";
  1057. if(!$res = mysql_query($qry)) {
  1058. echo '3-'.mysql_error().'<br />'.$qry;
  1059. return false;
  1060. }
  1061. return true;
  1062. }
  1063. // END ADDED
  1064. // ADDED by Chad (Apr10,06) check for additional notes
  1065. function isAddInfo($ordID) {
  1066. $qry = "SELECT ordAddInfo FROM orders WHERE ordID = '$ordID'";
  1067. $res = mysql_query($qry) or print(mysql_error());
  1068. if(mysql_num_rows($res) > 0) {
  1069. $row = mysql_fetch_assoc($res);
  1070. }
  1071. if(!empty($row['ordAddInfo'])) {
  1072. return true;
  1073. }
  1074. return false;
  1075. }
  1076. // END ADDED
  1077. // ADDED by Shane (may24,06) for "how get" wholesale pricing
  1078. function getPricingStructure($id=1) {
  1079. $query = 'select * from pricing_struct where id="'.$id.'"';
  1080. $result = mysql_query($query);
  1081. $rv = mysql_fetch_assoc($result);
  1082. $query = 'select * from pricing_tier where pricing_struct_id="'.$id.'" order by quantity_start';
  1083. $result = mysql_query($query);
  1084. for($i=0;$row=mysql_fetch_assoc($result);$i++)
  1085. $rv[tiers][$i] = $row;
  1086. return $rv;
  1087. }
  1088. // END ADDED
  1089. // ADDED by Chad (July 3,06)
  1090. function getCustPricingStructures($custID,$current_struct='') {
  1091. //$qry = "SELECT * FROM pricing_cust WHERE customer_id = " . $custID;
  1092. $next_month=date('Y-m-d',mktime(0,0,0,date('m')+1,1,date('Y')));
  1093. $qry = "SELECT pc.id as pcid,pc.*,ps.*
  1094. FROM pricing_cust pc, pricing_struct ps
  1095. WHERE pc.pricing_struct_id = ps.id
  1096. AND customer_id =$custID";
  1097. if($current_struct) $qry.=" AND date_start<'$next_month'";
  1098. else $qry.=" AND date_start>='$next_month'";
  1099. $qry.=" ORDER BY ps.pricing_group, pc.date_start";
  1100. if($current_struct) $qry.=" DESC";
  1101. $res = mysql_query($qry) or print(mysql_error());
  1102. $aPrc = array();
  1103. $i=0;
  1104. $pricing_group='';
  1105. while($row = mysql_fetch_assoc($res)) {
  1106. if($row['pricing_group']!=$pricing_group){
  1107. $aStructure = getPricingStructure($row['pricing_struct_id']);
  1108. $aPrc[$i]=$aStructure;
  1109. $aPrc[$i]['date_start']=$row['date_start'];
  1110. $aPrc[$i]['custID']=$row['customer_id'];
  1111. $aPrc[$i]['psID']=$row['pcid'];
  1112. $aPrc[$i]['pricing_struct_id']=$row['pricing_struct_id'];
  1113. if($current_struct) $pricing_group=$row['pricing_group'];
  1114. $i++;
  1115. }
  1116. }
  1117. return $aPrc;
  1118. }
  1119. // END ADDED
  1120. // ADDED by Shane (may24,06) for "how get" wholesale pricing
  1121. function getPricingAdj($wsID,$qty=1,$pricing_group=1) {
  1122. $query = '
  1123. SELECT *
  1124. FROM `pricing_struct` ps, pricing_tier pt, pricing_cust pc
  1125. WHERE ps.id = pc.pricing_struct_id
  1126. AND pc.customer_id ="'.$wsID.'"
  1127. AND pt.pricing_struct_id = ps.id
  1128. AND ps.pricing_group='.$pricing_group.'
  1129. AND pt.quantity_start<='.$qty.'
  1130. AND pc.date_start < "'.date('Y-m-d').'"
  1131. ORDER BY pc.date_start DESC,pt.quantity_start DESC
  1132. LIMIT 1';
  1133. //echo $query;
  1134. $result = mysql_query($query);
  1135. $num_rows=mysql_num_rows($result);
  1136. if($num_rows>0) {
  1137. $row=mysql_fetch_assoc($result);
  1138. return (100-$row['discount'])/100;
  1139. } else return 1;
  1140. }
  1141. function getPricingAdjtest($wsID,$qty=1,$pricing_group=1) {
  1142. $query = '
  1143. SELECT *
  1144. FROM `pricing_struct` ps, pricing_tier pt, pricing_cust pc
  1145. WHERE ps.id = pc.pricing_struct_id
  1146. AND pc.customer_id ="'.$wsID.'"
  1147. AND pt.pricing_struct_id = ps.id
  1148. AND ps.pricing_group='.$pricing_group.'
  1149. AND pt.quantity_start<='.$qty.'
  1150. AND pc.date_start < "'.date('Y-m-d').'"
  1151. ORDER BY pc.date_start DESC,pt.quantity_start DESC
  1152. LIMIT 1';
  1153. echo $query;
  1154. exit();
  1155. $result = mysql_query($query);
  1156. $num_rows=mysql_num_rows($result);
  1157. if($num_rows>0) {
  1158. $row=mysql_fetch_assoc($result);
  1159. return (100-$row['discount'])/100;
  1160. } else return 1;
  1161. }
  1162. // END ADDED
  1163. // Added by Blake Jan 5, 2006
  1164. // gets all products in pricing group
  1165. function getProductPricingGroups($pricing_group,$pDisplay=TRUE){
  1166. $arr='';
  1167. $sql_pg="SELECT DISTINCT pName,pWholesalePrice FROM products WHERE pPricing_group=".$pricing_group;
  1168. if(!$pDisplay) $sql_pg.=" AND pDisplay=1";
  1169. $sql_pg.=" ORDER BY pName";
  1170. //echo $sql_pg;
  1171. $result_pg=mysql_query($sql_pg);
  1172. if(mysql_num_rows($result_pg)>0){
  1173. $i=0;
  1174. while($row_pg=mysql_fetch_assoc($result_pg)){
  1175. $arr[$i++]=array($row_pg['pName'],$row_pg['pWholesalePrice']);
  1176. }
  1177. }
  1178. return $arr;
  1179. }
  1180. // END
  1181. // ADDED by Chad (May 31,06)
  1182. function Encrypt($string, $key)
  1183. {
  1184. $result = '';
  1185. for($i=1; $i<=strlen($string); $i++)
  1186. {
  1187. $char = substr($string, $i-1, 1);
  1188. $keychar = substr($key, ($i % strlen($key))-1, 1);
  1189. $char = chr(ord($char)+ord($keychar));
  1190. $result.=$char;
  1191. }
  1192. return $result;
  1193. }
  1194. function Decrypt($string, $key)
  1195. {
  1196. $result = '';
  1197. for($i=1; $i<=strlen($string); $i++)
  1198. {
  1199. $char = substr($string, $i-1, 1);
  1200. $keychar = substr($key, ($i % strlen($key))-1, 1);
  1201. $char = chr(ord($char)-ord($keychar));
  1202. $result.=$char;
  1203. }
  1204. return $result;
  1205. }
  1206. // ADD ENDED
  1207. function getCCType($ccNum) {
  1208. if (preg_match("/^5[1-5]/", $ccNum)) {
  1209. $type = 'Mastercard';
  1210. }
  1211. else if (preg_match("/^4/", $ccNum)) {
  1212. $type = 'Visa';
  1213. }
  1214. else if (preg_match("/^3[47]/", $ccNum)) {
  1215. $type = 'Amex';
  1216. }
  1217. else if (preg_match("/^3(0[0-5]|[68])/" ,$ccNum)) {
  1218. $type = 'Diners Club';
  1219. }
  1220. else if (preg_match("/^6011/",$ccNum)) {
  1221. $type = 'Discover';
  1222. }
  1223. else if (preg_match("/^(3|2131|1800)/", $ccNum)) {
  1224. $type = 'JCB';
  1225. }
  1226. else {
  1227. $type = 'Not Found';
  1228. }
  1229. /*
  1230. if(ereg("^5[1-5]",$ccNum)) {
  1231. $type = 'Mastercard';
  1232. }elseif(ereg("^4",$ccNum)) {
  1233. $type = 'Visa';
  1234. }elseif(ereg("^3[47]",$ccNum)) {
  1235. $type = 'Amex';
  1236. }elseif(ereg("^3(0[0-5]|[68])",$ccNum)) {
  1237. $type = 'Diners Club';
  1238. }elseif(ereg("^6011",$ccNum)) {
  1239. $type = 'Discover';
  1240. }elseif(ereg("^(3|2131|1800)",$ccNum)) {
  1241. $type = 'JCB';
  1242. }else{
  1243. $type = 'Not Found';
  1244. }
  1245. */
  1246. return $type;
  1247. }
  1248. function aimTransaction($amt, $cnum, $expdate, $type, $transid='', $fname='', $lname='', $inv='', $note='', $address='', $address2='', $city='', $state='', $zip='', $ccv='') {
  1249. // CHECK REQUIRED VARIABLES
  1250. if(empty($amt) || empty($cnum) || empty($expdate) || empty($type)) {
  1251. return false;
  1252. }
  1253. $type = strtoupper($type);
  1254. // GET THE LOGIN AND TRANSID
  1255. $sql = "SELECT payProvDemo, payProvData1, payProvData2 FROM payprovider WHERE payProvID=13";
  1256. $res = mysql_query($sql) or print(mysql_error());
  1257. $info = mysql_fetch_assoc($res);
  1258. // IF IN DEMO MODE
  1259. if($info['payProvDemo']) {
  1260. return false;
  1261. }
  1262. $login = $info['payProvData1'];
  1263. $tran_key = $info['payProvData2'];
  1264. $strParams = '';
  1265. // REQUIRED FOR ALL CC TRANSACTIONS
  1266. $strParams .= 'x_version=3.1';
  1267. $strParams .= '&x_delim_data=True';
  1268. $strParams .= '&x_delim_char=|';
  1269. $strParams .= '&x_relay_response=False';
  1270. $strParams .= '&x_login='.$login;
  1271. $strParams .= '&x_tran_key='.$tran_key;
  1272. $strParams .= '&x_amount='.$amt;
  1273. $strParams .= '&x_card_num='.$cnum;
  1274. $strParams .= '&x_exp_date='.$expdate;
  1275. $strParams .= '&x_type='.$type;
  1276. if($type!='AUTH_CAPTURE') {
  1277. $strParams .= '&x_trans_id='.$transid;
  1278. }
  1279. // OPTIONAL
  1280. $strParams .= '&x_first_name='.$fname;
  1281. $strParams .= '&x_last_name='.$lname;
  1282. $strParams .= '&x_invoice_num='.$inv;
  1283. $strParams .= '&x_description='.$note;
  1284. if($type=='AUTH_CAPTURE') {
  1285. $strParams .= '&x_address='.$address.' '.$address2;
  1286. $strParams .= '&x_city='.$city;
  1287. $strParams .= '&x_state='.$state;
  1288. $strParams .= '&x_zip='.$zip;
  1289. $strParams .= '&x_card_code='.$ccv;
  1290. }
  1291. $sql5 = "INSERT INTO aimtest (resp, date_created)
  1292. VALUES ( '$strParams', '" . date('Y-m-d H:i:s') . "' )";
  1293. $res5 = mysql_query($sql5) or print(mysql_error());
  1294. $ch = curl_init();
  1295. curl_setopt($ch, CURLOPT_URL,'https://secure.authorize.net/gateway/transact.dll');
  1296. curl_setopt($ch, CURLOPT_POST, 1);
  1297. curl_setopt($ch, CURLOPT_HEADER, 0);
  1298. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  1299. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  1300. curl_setopt($ch, CURLOPT_POSTFIELDS, $strParams);
  1301. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1302. $resp = curl_exec($ch);
  1303. $sql = "INSERT INTO aimtest (resp, date_created)
  1304. VALUES ('$resp', '" . date('Y-m-d H:i:s') . "')";
  1305. $res = mysql_query($sql) or print(mysql_error());
  1306. if(curl_error($ch) != ""){
  1307. return false;
  1308. }else{
  1309. curl_close($ch);
  1310. }
  1311. return $resp;
  1312. }
  1313. // ADDED by Blake (July 11,06) insert record into ws_sales
  1314. function addWSSales($wsid,$ordID,$cartID,$msrp,$amt_charged,$discount,$pricing_group,$pricing_struct){
  1315. $sql = "INSERT INTO ws_sales
  1316. SET wsid=$wsid,
  1317. ordID=$ordID,
  1318. cartID=$cartID,
  1319. msrp=$msrp,
  1320. amt_charged=$amt_charged,
  1321. discount=$discount,
  1322. pricing_struct_id=$pricing_struct,
  1323. date_ordered='".date("Y-m-d H:i:s")."'";//
  1324. //echo $sql;
  1325. $result=mysql_query($sql) or print(mysql_error().$sql);
  1326. return $result;
  1327. }
  1328. //returns wholesale pricing structure
  1329. function getWSPricing($wsID,$qty=1,$pricing_group=1) {
  1330. $query = '
  1331. SELECT *
  1332. FROM `pricing_struct` ps, pricing_tier pt, pricing_cust pc
  1333. WHERE ps.id = pc.pricing_struct_id
  1334. AND pc.customer_id ="'.$wsID.'"
  1335. AND pt.pricing_struct_id = ps.id
  1336. AND ps.pricing_group='.$pricing_group.'
  1337. AND pt.quantity_start<='.$qty.'
  1338. AND pc.date_start < "'.date('Y-m-d').'"
  1339. ORDER BY pc.date_start DESC,pt.quantity_start DESC
  1340. LIMIT 1';
  1341. $result = mysql_query($query);
  1342. $row=mysql_fetch_assoc($result);
  1343. if(!empty($row)) return $row;
  1344. else return false;
  1345. }
  1346. function addWSSalesOrder($wsid,$ordID){
  1347. $sql="SELECT * FROM cart c, products p WHERE c.cartProdID=p.pID AND c.cartOrderID=".$ordID;
  1348. $result=mysql_query($sql) or print(mysql_error().$sql);
  1349. while($row=mysql_fetch_assoc($result)){
  1350. $cartID = $row['cartID'];
  1351. $msrp = $row['pWholesalePrice'];
  1352. $amt_charged = $row['cartProdPrice'];
  1353. $pricing_group = $row['pPricing_group'];
  1354. $struct = getWSPricing($wsid,1,$pricing_group);
  1355. $discount = $struct['discount'];
  1356. $pricing_struct = $struct['pricing_struct_id'];
  1357. addWSSales($wsid,$ordID,$cartID,$msrp,$amt_charged,$discount,$pricing_group,$pricing_struct);
  1358. }
  1359. }
  1360. // END ADDED
  1361. // Added June 2 2006 By Blake
  1362. // removes uploaded images for custom screenz
  1363. function deleteUploadedImages(){
  1364. global $hrs_img_on_server,$days_delete_cust;
  1365. $img_orig='imguploads/img_orig';
  1366. $img_final='imguploads/img_final';
  1367. $img_thumb='imguploads/img_thumb';
  1368. $img_screen='imguploads/img_screen';
  1369. $img_flash='imguploads/img_flash';
  1370. $delete_time=time()-(60*60*$hrs_img_on_server);
  1371. $sql1 = "SELECT *
  1372. FROM uploaded_images ui
  1373. WHERE ui.img_status = 'pending'
  1374. AND ui.date_added < '".date('Y-m-d H:i:s', $delete_time)."'";
  1375. $result1=mysql_query($sql1);
  1376. if(mysql_num_rows($result1)>0) {
  1377. while($row1=mysql_fetch_assoc($result1)) {
  1378. $display_image=$row1['display_image'];
  1379. $sql = "SELECT * FROM cartoptions co, cart c
  1380. WHERE co.coCartID = c.cartID
  1381. AND co.coCartOption LIKE '".$row1['id']."%'";
  1382. $result=mysql_query($sql);
  1383. if(mysql_num_rows($result)>0) {
  1384. while($row=mysql_fetch_assoc($result)) {
  1385. //delete original and thumb images when cart is complete
  1386. if($row['cartCompleted']==1) {
  1387. if(file_exists($img_orig.'/'.$display_image.'.jpg')) unlink($img_orig.'/'.$display_image.'.jpg');
  1388. if(file_exists($img_thumb.'/'.$display_image.'.jpg')) unlink($img_thumb.'/'.$display_image.'.jpg');
  1389. } elseif($row['cartCompleted']==0 || $row['cartCompleted']=='') {
  1390. $error=FALSE;
  1391. $error_reason='Cart Not Completed cartCompleted='.$row['cartCompleted'];
  1392. if(file_exists($img_final.'/'.$display_image.'.jpg')) unlink($img_final.'/'.$display_image.'.jpg');
  1393. else {$error=TRUE;$error_reason.=' final,';}
  1394. if(file_exists($img_orig.'/'.$display_image.'.jpg')) unlink($img_orig.'/'.$display_image.'.jpg');
  1395. else {$error=TRUE;$error_reason.=' original,';}
  1396. if(file_exists($img_screen.'/'.$display_image.'.gif')) unlink($img_screen.'/'.$display_image.'.gif');
  1397. else {$error=TRUE;$error_reason.=' screen,';}
  1398. if(file_exists($img_thumb.'/'.$display_image.'.jpg')) unlink($img_thumb.'/'.$display_image.'.jpg');
  1399. else {$error=TRUE;$error_reason.=' thumb';}
  1400. $sql3="UPDATE uploaded_images SET img_status='deleted',note='incfunctions date=".date('Y-m-d H:i:s' )." reason=".$error_reason."' WHERE id=".$row1['id'];
  1401. mysql_query($sql3);
  1402. }
  1403. }
  1404. } else {
  1405. $error=FALSE;
  1406. $error_reason='No Join To Cart Option or Cart';
  1407. if(file_exists($img_final.'/'.$display_image.'.jpg')) unlink($img_final.'/'.$display_image.'.jpg');
  1408. else {$error=TRUE;$error_reason.=' final,';}
  1409. if(file_exists($img_orig.'/'.$display_image.'.jpg')) unlink($img_orig.'/'.$display_image.'.jpg');
  1410. else {$error=TRUE;$error_reason.=' original,';}
  1411. if(file_exists($img_screen.'/'.$display_image.'.gif')) unlink($img_screen.'/'.$display_image.'.gif');
  1412. else {$error=TRUE;$error_reason.=' screen,';}
  1413. if(file_exists($img_thumb.'/'.$display_image.'.jpg')) unlink($img_thumb.'/'.$display_image.'.jpg');
  1414. else {$error=TRUE;$error_reason.=' thumb';}
  1415. $sql3="UPDATE uploaded_images SET img_status='deleted',note='incfunctions date=".date('Y-m-d H:i:s' )." reason=".$error_reason."' WHERE id=".$row1['id'];
  1416. mysql_query($sql3);
  1417. }
  1418. //delete flash images
  1419. if(file_exists($img_flash.'/W_screen_'.$row1['id'].'.gif')) unlink($img_flash.'/W_screen_'.$row1['id'].'.gif');
  1420. if(file_exists($img_flash.'/Y_screen_'.$row1['id'].'.gif')) unlink($img_flash.'/Y_screen_'.$row1['id'].'.gif');
  1421. if(file_exists($img_flash.'/X_screen_'.$row1['id'].'.gif')) unlink($img_flash.'/X_screen_'.$row1['id'].'.gif');
  1422. if(file_exists($img_flash.'/p_screen_'.$row1['id'].'.gif')) unlink($img_flash.'/p_screen_'.$row1['id'].'.gif');
  1423. }
  1424. }
  1425. }
  1426. // END ADDED
  1427. // ADDED BY Blake 7-19-2006
  1428. // inserts record into uploaded img history
  1429. function setImgUpHistory($id,$type,$batch=''){
  1430. $sql="INSERT INTO uploaded_images_history (changed_to,date_changed,batch_number) VALUES('$type','".date('Y-m-d H:i:s')."','$batch')";
  1431. if(mysql_query($sql)) return true;
  1432. else return false;
  1433. }
  1434. // END ADDED
  1435. // ADDED BY Blake 8-9-2006
  1436. // gets stock amounts in cart
  1437. function getOnOrderStock($pID,$optID="") {
  1438. global $stockManage;
  1439. if($stockManage != 0){
  1440. /*$sSQL = "SELECT pSell FROM products WHERE pID='" . $pID . "'";
  1441. $result = mysql_query($sSQL) or print(mysql_error());
  1442. $row=mysql_fetch_assoc($result);
  1443. $pSell=$row['pSell'];
  1444. //echo 'pSell='.$pSell;
  1445. mysql_free_result($result);
  1446. if($pSell == '2'){*/
  1447. if($optID !=""){
  1448. $sSQL = "SELECT SUM(cartQuantity) AS cartQuant FROM cart INNER JOIN cartoptions ON cart.cartID=cartoptions.coCartID JOIN orders o ON cartOrderID=o.ordID WHERE ordStatus BETWEEN 3 AND 9 AND cartCompleted=1 AND coOptID=" . $optID;
  1449. //echo $sSQL;
  1450. $result = mysql_query($sSQL) or print(mysql_error());
  1451. if($rs = mysql_fetch_assoc($result)) {
  1452. if (! is_null($rs["cartQuant"])) {
  1453. $totQuant = (int)$rs["cartQuant"];
  1454. // See if its a custom Hype Rim. If so double the quantity since the product doesn't come as pairs
  1455. // * Remember any changes need to be made elsewhere too ( do_stock_management(), release_stock(), and printpackingslips.php line 151 )
  1456. $sql = "SELECT og.optGrpName
  1457. FROM optiongroup og, options o
  1458. WHERE o.optGroup = og.optGrpID
  1459. AND o.optID = ".$optID;
  1460. $res = mysql_query($sql);
  1461. $row = mysql_fetch_assoc($res);
  1462. if ($pID == 'customhype' && strstr($row['optGrpName'], 'Rim')) {
  1463. $totQuant = (int)$rs["cartQuant"] * 2;
  1464. }
  1465. } else {
  1466. $totQuant = '0';
  1467. }
  1468. }
  1469. }else{
  1470. $sSQL = "SELECT SUM(cartQuantity) AS cartQuant FROM cart c, orders o WHERE c.cartOrderID=o.ordID AND ordStatus BETWEEN 3 AND 9 AND cartCompleted=1 AND cartProdID='" . $pID . "'";
  1471. $result = mysql_query($sSQL) or print(mysql_error());
  1472. if($rs = mysql_fetch_array($result)) {
  1473. if(! is_null($rs["cartQuant"])) $totQuant = (int)$rs["cartQuant"];
  1474. else $totQuant = '0';
  1475. }
  1476. }
  1477. mysql_free_result($result);
  1478. return $totQuant;
  1479. } else return '0';
  1480. }
  1481. // ADDED BY BLAKE AUG 24, 2006
  1482. // RETURNS REBATE DETAILS IN AN ARRAY
  1483. function getWSNumOrders($thisDate,$custID=''){
  1484. $sSQL = "SELECT c.Name, c.Email, c.custID
  1485. FROM clientlogin cl, customers c
  1486. WHERE cl.clientUser=c.Email
  1487. AND cl.clientWholesaler>0 ORDER BY c.Name";
  1488. if($custID!='') $sSQL .=" AND c.custID=".$custID;
  1489. $result=mysql_query($sSQL);
  1490. $i=0;
  1491. $num_rows=mysql_num_rows($result);
  1492. if($num_rows>0){
  1493. while($row=mysql_fetch_assoc($result)){
  1494. $alldata[$i]=$row;
  1495. $custID=$row['custID'];
  1496. $thecount='';
  1497. $sql1="SELECT SUM(c.cartQuantity) as thecount, SUM(p.pWholesalePrice*c.cartQuantity) as theamt, p.pPricing_group FROM orders o, cart c, products p WHERE o.ordID=c.cartOrderID AND c.cartProdID=p.pID AND o.ordDate LIKE '" .$thisDate ."%' AND ordEID=".$custID." AND cartCompleted=1 GROUP BY p.pPricing_group";
  1498. $result1=mysql_query($sql1);
  1499. if(mysql_num_rows($result1)>0){
  1500. while($row1=mysql_fetch_assoc($result1)){
  1501. $thecount[$row1['pPricing_group']]['cnt'] = $row1['thecount'];
  1502. $thecount[$row1['pPricing_group']]['amt'] = $row1['theamt'];
  1503. }
  1504. } else {
  1505. $thecount[$row1['pPricing_group']]['cnt'] = '0';
  1506. $thecount[$row1['pPricing_group']]['amt'] = '0';
  1507. }
  1508. $pstruct=getCustPricingStructures($custID);
  1509. if(is_array($pstruct)) $struct_count=count($pstruct);
  1510. $rebate_total=0;
  1511. $prod_total=0;
  1512. $amt_total;
  1513. for($j=0;$j<$struct_count;$j++){
  1514. $num_tiers=0;
  1515. $this_rebate=0;
  1516. $this_num_prods=0;
  1517. $high_tier_discount=0;
  1518. $next_tier=0;
  1519. $next_tier_discount=0;
  1520. $rebate_discount=0;
  1521. if(is_array($pstruct[$j]['tiers'])) $struct_count2=count($pstruct[$j]['tiers']);
  1522. $alldata[$i]['pstruct'][$j]['pricing_group']=$pstruct[$j]['pricing_group'];
  1523. for($k=0;$k<$struct_count2;$k++){
  1524. if($thecount[$pstruct[$j]['pricing_group']]['cnt']>=$pstruct[$j]['tiers'][$k]['quantity_start']) {
  1525. $alldata[$i]['pstruct'][$j]['tiers'][$k]['discount']=$pstruct[$j]['tiers'][$k]['discount'];
  1526. $alldata[$i]['pstruct'][$j]['tiers'][$k]['quantity_start']=$pstruct[$j]['tiers'][$k]['quantity_start'];
  1527. $alldata[$i]['pstruct'][$j]['tiers'][$k]['structID']=$pstruct[$j]['tiers'][$k]['pricing_struct_id'];
  1528. $num_tiers++;
  1529. $rebate_discount=$pstruct[$j]['tiers'][$k]['discount']-$pstruct[$j]['tiers'][0]['discount'];
  1530. $high_tier_discount=$pstruct[$j]['tiers'][$k]['discount'];
  1531. $high_tier_qty=$pstruct[$j]['tiers'][$k]['quantity_start'];
  1532. $next_tier=$pstruct[$j]['tiers'][$k+1]['quantity_start'];
  1533. $next_tier_discount=$pstruct[$j]['tiers'][$k+1]['discount'];
  1534. }
  1535. }
  1536. if($num_tiers==0)$num_tiers=1;
  1537. if($next_tier==0)$next_tier=$pstruct[$j]['tiers'][1]['quantity_start'];
  1538. if($next_tier_discount==0)$next_tier_discount=$pstruct[$j]['tiers'][1]['discount'];
  1539. if($high_tier_discount==0) $high_tier_discount=$pstruct[$j]['tiers'][0]['discount'];
  1540. $alldata[$i]['pstruct'][$j]['next_tier_discount']=$next_tier_discount;
  1541. $alldata[$i]['pstruct'][$j]['next_tier']=$next_tier;
  1542. $alldata[$i]['pstruct'][$j]['high_tier_discount']=$high_tier_discount;
  1543. $alldata[$i]['pstruct'][$j]['tier_count']=$num_tiers;
  1544. $alldata[$i]['pstruct'][$j]['rebate_discount']=$rebate_discount;
  1545. $alldata[$i]['pstruct'][$j]['num_prods']=$thecount[$pstruct[$j]['pricing_group']]['cnt'];
  1546. if(empty($alldata[$i]['pstruct'][$j]['num_prods'])) $alldata[$i]['pstruct'][$j]['num_prods']='0';
  1547. $alldata[$i]['pstruct'][$j]['amt']=$thecount[$pstruct[$j]['pricing_group']]['amt'];
  1548. if($num_tiers>1) $alldata[$i]['pstruct'][$j]['rebate']=($thecount[$pstruct[$j]['pricing_group']]['amt'])*(($rebate_discount)/100);
  1549. else $alldata[$i]['pstruct'][$j]['rebate']=0;
  1550. $rebate_total+=$alldata[$i]['pstruct'][$j]['rebate'];
  1551. $prod_total+=$alldata[$i]['pstruct'][$j]['num_prods'];
  1552. $amt_total+=$alldata[$i]['pstruct'][$j]['amt'];
  1553. }
  1554. $alldata[$i]['rebate_total']+=$rebate_total;
  1555. $alldata[$i]['prod_total']+=$prod_total;
  1556. $alldata[$i]['amt_total']+=$amt_total;
  1557. $i++;
  1558. }
  1559. }
  1560. return $alldata;
  1561. }
  1562. // END
  1563. // ADDED BY BLAKE AUG 31, 2006
  1564. // RETURNS TOP PRODUCT DETAILS IN AN ARRAY
  1565. // ALL
  1566. function getAllTopProds($days,$show_start,$show_end,$prod_type=""){
  1567. $array_wrap=getTopProds('wrap',$days,$show_start,$show_end);
  1568. $array_band=getTopProds('band',$days,$show_start,$show_end);
  1569. $array_screen=getTopProds('screen',$days,$show_start,$show_end,$prod_type);
  1570. $cnt=count($array_wrap);
  1571. for($i=0;$i<$cnt;$i++) {
  1572. $top_prods[$i]["wrap"]=$array_wrap[$i]["wrap"];
  1573. $top_prods[$i]["band"]=$array_band[$i]["band"];
  1574. $top_prods[$i]["screen"]=$array_screen[$i]["screen"];
  1575. }
  1576. return $top_prods;
  1577. }
  1578. function getTopProds($type,$days,$show_start,$show_end,$prod_type=""){
  1579. $sSQL = "SELECT sum(cartQuantity) AS total, co.coCartOption, co.coOptID
  1580. FROM cart c, cartoptions co, options o
  1581. WHERE c.cartID = co.coCartID
  1582. AND co.coOptID=o.optID
  1583. AND o.optDisplay='yes'
  1584. AND o.optStock>o.optDisplay_point
  1585. AND c.cartCompleted =1
  1586. AND co.coOptGroup LIKE '%".$type."%'
  1587. AND c.cartDateAdded >= '".date('Y-m-d',mktime(0,0,0,date('m'),date('d')-$days,date('Y')))."%'
  1588. GROUP BY co.coCartOption
  1589. ORDER BY total DESC
  1590. LIMIT ".$show_start.",".$show_end;
  1591. $result = mysql_query($sSQL) or print(mysql_error()."<br />".$sSQL);
  1592. //echo $sSQL;
  1593. $i=0;
  1594. $type2=trim($type);
  1595. while($rs = mysql_fetch_assoc($result)){
  1596. $sql_prod= "SELECT p.pID,o.optStyleID,o.optID,p.pImage,o.optColor,o.optPriceDiff,og.optFlags,p.isSet,og.optGrpName,o.optDisplay
  1597. FROM prodoptions po, products p, options o, optiongroup og
  1598. WHERE o.optGroup=po.poOptionGroup
  1599. AND po.poProdID=p.pID
  1600. AND p.pID NOT LIKE '%_old%' AND p.pID NOT LIKE '%_Old%'
  1601. AND o.optID='".$rs["coOptID"]."'
  1602. AND og.optGrpName LIKE '%".$type."%'";
  1603. if(!empty($prod_type)) $sql_prod.=" AND p.pID LIKE '".$prod_type."%'";
  1604. $sql_prod.="ORDER BY p.isSet, o.optGroup";
  1605. //echo $sql_prod;
  1606. $result_prod = mysql_query($sql_prod) or print(mysql_error());
  1607. $rs2 = mysql_fetch_assoc($result_prod);
  1608. $styleID=$rs2["optStyleID"];
  1609. if(strstr('screen',$type2)){
  1610. $prodID=$rs2['pID'];
  1611. $pos=strpos($prodID,'-');
  1612. //if($pos>=0) {$prodID=substr($prodID,($pos+1));$styleID=$rs2["optStyleID"];}
  1613. //else
  1614. $styleID=$rs2["optStyleID"];
  1615. }
  1616. $top_prods[$i][$type]['optID']=$rs2["optID"];
  1617. $top_prods[$i][$type]['option']=$rs["coCartOption"];
  1618. $top_prods[$i][$type]['style']=$styleID;
  1619. $top_prods[$i][$type]['count']=$rs["total"];
  1620. $top_prods[$i][$type]['pID']=$rs2['pID'];
  1621. $top_prods[$i][$type]['styleID']=$rs2["optStyleID"];
  1622. $top_prods[$i][$type]['pImage']=$rs2["pImage"];
  1623. $top_prods[$i][$type]['optColor']=$rs2["optColor"];
  1624. $top_prods[$i][$type]['optGroup']=$rs2["optGrpName"];
  1625. $price_diff_type='';
  1626. if($rs2["optPriceDiff"]==1) $price_diff_type='%';
  1627. $top_prods[$i][$type]['optPriceDiff']=$rs2["optPriceDiff"].$price_diff_type;
  1628. $i++;
  1629. }
  1630. return $top_prods;
  1631. }
  1632. // SETS
  1633. function getTopSets($days){
  1634. $sSQL ="SELECT c.cartID, c.cartQuantity, co.coOptGroup, co.coCartOption, co.coID, o.optColor, o.optStyleID, o.optID
  1635. FROM cart c, cartoptions co, options o, products p
  1636. WHERE c.cartID = co.coCartID
  1637. AND co.coOptID=o.optID
  1638. AND c.cartProdID = p.pID
  1639. AND c.cartCompleted =1
  1640. AND p.isSet = 'yes'
  1641. AND c.cartDateAdded >= '".date('Y-m-d',mktime(0,0,0,date('m'),date('d')-$days,date('Y')))."'
  1642. ORDER BY co.coID";
  1643. $result = mysql_query($sSQL) or print(mysql_error());
  1644. //echo $sSQL;
  1645. if(mysql_num_rows($result) > 0){
  1646. $i=0;
  1647. $cnt=0;
  1648. $old_cartID='';
  1649. while($rs = mysql_fetch_assoc($result)){
  1650. if($cnt % 3 ==0 && !empty($old_cartID)){
  1651. $report[$i]['option_combination']=$option_set_combination;
  1652. $report[$i]['count']=$option_set_count;
  1653. $option_set_combination='';
  1654. $option_set_count='';
  1655. $spacer='';
  1656. $cnt=0;
  1657. $i++;
  1658. }
  1659. $option_set_combination.=$spacer.$rs['coCartOption'];
  1660. $option_set_count=$rs['cartQuantity'];
  1661. if($cnt==2){
  1662. $report[$i]['set'][$cnt]['style']=$rs['optStyleID'];
  1663. $report[$i]['set']['optID']=$rs['optID'];
  1664. }
  1665. else $report[$i]['set'][$cnt]['color']=$rs['optColor'];
  1666. $report[$i]['set'][$cnt]['optName']=$rs['coCartOption'];
  1667. $spacer='-';
  1668. $old_cartID=$rs['cartID'];
  1669. $cnt++;
  1670. }
  1671. }
  1672. if(!empty($report)) sort($report);
  1673. //showarray($report);
  1674. //exit();
  1675. $last_combination='';
  1676. $cnt_r=count($report);
  1677. for($i=0,$j=-1;$i<$cnt_r;$i++) {
  1678. if($report[$i]['option_combination']==$last_combination) {
  1679. $report_final[$j]['count']+=$report[$i]['count'];
  1680. } else {
  1681. $j++;
  1682. $report_final[$j]['count']=1;
  1683. $report_final[$j]['option_combination']=$report[$i]['option_combination'];
  1684. $report_final[$j]['set']=$report[$i]['set'];
  1685. }
  1686. $last_combination=$report[$i]['option_combination'];
  1687. }
  1688. $report='';
  1689. if(!empty($report_final)) array_multisort($report_final, SORT_DESC);
  1690. //showarray($report_final);
  1691. return $report_final;
  1692. }
  1693. function getProdPrice($pID){
  1694. $SQL="SELECT pPrice FROM products WHERE pID='".$pID."'";
  1695. $result=mysql_query($SQL);
  1696. if(!$result) return '';
  1697. else {
  1698. $row=mysql_fetch_assoc($result);
  1699. return $row['pPrice'];
  1700. }
  1701. }
  1702. // END
  1703. // Blake 12/15/05
  1704. // Insert plotter_history record
  1705. function updateplotterhistory($pID,$oldamt,$newamt,$empid,$type=''){
  1706. $update=FALSE;
  1707. if(!empty($type)){
  1708. $sql1="SELECT id FROM plotter_history WHERE phPID='".$pID."' AND phType='".$type."'";
  1709. //echo $sql1.'<br />';
  1710. $result1=mysql_query($sql1);
  1711. if(mysql_num_rows($result1)>0)$update=TRUE;
  1712. }
  1713. if($update){
  1714. $sql="UPDATE plotter_history SET phEndingAmt=".$newamt." WHERE phType='".$type."'";
  1715. //echo $sql.'<br />';
  1716. $result=mysql_query($sql);
  1717. } else {
  1718. if(empty($type))$type='Manual';
  1719. $sql="INSERT INTO plotter_history
  1720. (phPID,phDateAdded,phStartAmt,phEndingAmt,empID,phType)
  1721. VALUES
  1722. ('".$pID."','".date('Y-m-d H:i:s')."',".$oldamt.",".$newamt.",'".$empid."','".$type."')";
  1723. //echo $sql.'<br />';
  1724. $result=mysql_query($sql);
  1725. }
  1726. if($result) return TRUE;
  1727. else return FALSE;
  1728. }
  1729. function getRelatedProducts($pID,$orderID){
  1730. global $hasrelated;
  1731. //find related products
  1732. $today=date('Y-m-d H:i:s');
  1733. $sql = "SELECT * FROM related_prods rp, related_prods_disc rpd, related_prods_disc_add rpda, related_prods_add rpa, products p
  1734. WHERE rp.related_prod_disc_id=rpd.id
  1735. AND rpda.related_prod_disc_id=rpd.id
  1736. AND rpda.add_prod_id=rpa.id
  1737. AND rpa.add_pID=p.pID
  1738. AND rp.pID='".$pID."'
  1739. AND Startdate<'".$today."'
  1740. AND Enddate>'".$today."'";
  1741. $result=mysql_query($sql);
  1742. $num_rows=mysql_num_rows($result);
  1743. if($num_rows>0){
  1744. //$displaytext='';
  1745. while($row=mysql_fetch_assoc($result)){
  1746. //calc discount
  1747. if(!$hasrelated[$row['add_pID']]){
  1748. if($row['add_disc_type']==0) $add_disc=($row['pPrice']-$row['add_disc']);
  1749. elseif($row['add_disc_type']==1) $add_disc=($row['pPrice']-($row['pPrice']*($row['add_disc']/100)));
  1750. if($add_disc<0)$add_disc=0;
  1751. $sql_check="SELECT * FROM cart WHERE cartSessionID='".session_id()."' AND cartProdID='".$row['add_pID']."' AND cartAddProd=1";
  1752. $result_check=mysql_query($sql_check);
  1753. $num_rows_check=mysql_num_rows($result_check);
  1754. if($num_rows_check==0){
  1755. $sql_insert = "INSERT INTO cart (cartSessionID,cartProdID,cartProdName,cartProdPrice,cartDateAdded,cartQuantity,cartOrderID,cartCompleted,cartAddProd)
  1756. VALUES ('".session_id()."','".$row['add_pID']."','".$row['pName']."',".$add_disc.",'".$today."',".$row['add_qty'].",".$orderID.",0,1)";
  1757. $result_insert=mysql_query($sql_insert);
  1758. $hasrelated[mysql_insert_id()]=$row['add_display_text'];
  1759. $hasrelated['disc_display_text']=$row['display_text'];
  1760. $hasrelated[$row['add_pID']]=TRUE;
  1761. }
  1762. }
  1763. }
  1764. }
  1765. mysql_free_result($result);
  1766. }
  1767. // gift cert move from incemail page
  1768. // Blake 12/21/06
  1769. function create_certificate($ordID){
  1770. $certarray = array();
  1771. $prodarray = array();
  1772. $strsql = "SELECT cert_code, cert_amt FROM certificates WHERE cert_order_id =".$ordID;
  1773. if(!empty($_SESSION['cert_prod'])) $strsql .=" AND cert_prod_id='".$_SESSION['cert_prod']."'";
  1774. $result = mysql_query($strsql);
  1775. if(mysql_num_rows($result) > 0) {
  1776. while($rs=mysql_fetch_assoc($result)) {
  1777. $certarray[] = "(\$".number_format($rs['cert_amt']).") ".$rs['cert_code'];
  1778. }
  1779. return implode("|",$certarray);
  1780. }
  1781. $strsql = "SELECT pID FROM products WHERE p_iscert > 0";
  1782. $result = mysql_query($strsql);
  1783. while ($rs=mysql_fetch_assoc($result)) {
  1784. $prodarray[] = $rs['pID'];
  1785. }
  1786. $prodarray = "'".implode("','",$prodarray)."'";
  1787. if($prodarray == "") $prodarray = "NOVALIDPRODIDFORTHISQUERY696986";
  1788. $strsql = "SELECT cartID, cartProdPrice, cartQuantity, cartProdID, ordEmail FROM cart, orders WHERE ordID =".$ordID." AND cartOrderID =".$ordID." AND cartProdID IN (".$prodarray.")";
  1789. $result = mysql_query($strsql);
  1790. while ($rs=mysql_fetch_assoc($result)) {
  1791. // CHECK OPTIONS FOR HARD CARD CERTIFICATES
  1792. if($_SESSION['cert_prod']==$rs['cartProdID']||$_SESSION['cert_prod']==''){
  1793. $sql_hc = "SELECT * FROM cartoptions WHERE coCartID = " . $rs['cartID'];
  1794. $res_hc = mysql_query($sql_hc);
  1795. $row_hc = mysql_fetch_assoc($res_hc);
  1796. if($row_hc['coCartOption'] != 'Card via Mail') {
  1797. $expdate = time()+(720*24*3600);
  1798. for ($x = 0; $x < $rs['cartQuantity'];$x++) {
  1799. do {
  1800. $sqlrows = 1;
  1801. $certcode = 'G'.RandomString(11);
  1802. $strsql = "SELECT * FROM certificates WHERE cert_code='".$certcode."'";
  1803. $sqlrows = mysql_num_rows(mysql_query($strsql));
  1804. } while ($sqlrows > 0);
  1805. $certarray[] = "(\$".number_format($rs['cartProdPrice']).") ".$certcode;
  1806. $strsql = "INSERT INTO certificates (cert_code, cert_prod_id, cert_amt, cert_order_id, cert_email, cert_exp_dt, date_created)
  1807. VALUES ('".$certcode."','".$rs['cartProdID']."',".$rs['cartProdPrice'].",".$ordID.",'".$rs['ordEmail']."',".$expdate.",'".date('Y-m-d H:i:s')."')";
  1808. mysql_query($strsql);
  1809. }
  1810. }else{
  1811. $certarray[] = "(\$".number_format($rs['cartProdPrice']).") Card to be Mailed";
  1812. }
  1813. }
  1814. }
  1815. $_SESSION['cert_prod']='';
  1816. return implode("|",$certarray);
  1817. }
  1818. // function to generate random strings
  1819. function RandomString($length=32) {
  1820. $randstr='';
  1821. srand((double)microtime()*1000000);
  1822. //our array add all letters and numbers if you wish
  1823. $chars = array ( 'B','C','D','F','G','H','J','R','T','X','Y','Z','2','4','6','8','3','5','7','9');
  1824. for ($rand = 0; $rand <= $length; $rand++)
  1825. {
  1826. $random = rand(0, count($chars) -1);
  1827. $randstr .= $chars[$random];
  1828. }
  1829. return $randstr;
  1830. }
  1831. //google
  1832. function sendmessagewithbasicauth($themessage){
  1833. global $googledata1,$googledata2,$googledemomode,$curlproxy,$success;
  1834. $cfurl='https://' . ($googledemomode ? 'sandbox' : 'checkout') . '.google.com' . ($googledemomode ? '/checkout' : '') . '/cws/v2/Merchant/' . $googledata1 . '/request';
  1835. $success = TRUE;
  1836. if(@$pathtocurl != ''){
  1837. exec($pathtocurl . ' -H \'Authorization: Basic ' . base64_encode($googledata1 . ":" . $googledata2) . '\' -H \'Content-Type: application/xml\' -H \'Accept: application/xml\' --data-binary \'' . str_replace("'","\'", '<?xml version="1.0" encoding="UTF-8"?>' . $themessage) . '\' ' . $cfurl, $cfres, $retvar);
  1838. $cfres = implode("\n",$cfres);
  1839. }else{
  1840. if (!$ch = curl_init()) {
  1841. print "cURL package not installed in PHP. Set \$pathtocurl parameter.";
  1842. $success=FALSE;
  1843. }else{
  1844. curl_setopt($ch, CURLOPT_URL, $cfurl);
  1845. $headers = array('Authorization: Basic ' . base64_encode($googledata1 . ":" . $googledata2), 'Content-Type: application/xml', 'Accept: application/xml');
  1846. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1847. curl_setopt($ch, CURLOPT_POST, 1);
  1848. curl_setopt($ch, CURLOPT_HEADER, 0);
  1849. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  1850. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  1851. curl_setopt($ch, CURLOPT_POSTFIELDS, '<?xml version="1.0" encoding="UTF-8"?>' . $themessage);
  1852. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1853. if(@$curlproxy!=''){
  1854. curl_setopt($ch, CURLOPT_PROXY, $curlproxy);
  1855. }
  1856. $cfres = curl_exec($ch);
  1857. // print str_replace("<","<br />&lt;",str_replace('<'.'/','&lt;/',$cfres)) . "<br />\n";
  1858. if(curl_error($ch) != ""){
  1859. print 'cURL error: ' . curl_error($ch) . '<br />';
  1860. $success=FALSE;
  1861. }else{
  1862. curl_close($ch);
  1863. }
  1864. }
  1865. }
  1866. return($cfres);
  1867. }
  1868. function check_email_mx($email) {
  1869. if( (preg_match('/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/', $email)) ||
  1870. (preg_match('/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/',$email)) ) {
  1871. $host = explode('@', $email);
  1872. if(checkdnsrr($host[1].'.', 'MX') ) return true;
  1873. if(checkdnsrr($host[1].'.', 'A') ) return true;
  1874. if(checkdnsrr($host[1].'.', 'CNAME') ) return true;
  1875. }
  1876. return false;
  1877. }
  1878. function notifyCustShipped($ordID) {
  1879. $customHeaders = '';
  1880. $message = '';
  1881. $from = 'ifrogz Customer Service';
  1882. $fromEmail = 'support@ifrogz.com';
  1883. $to = '';
  1884. $subject = 'Your Order Has Been Shipped!';
  1885. $customHeaders .= "From: $from <$fromEmail>\n";
  1886. $customHeaders .= "Return-Path: <$fromEmail>\n";
  1887. $customHeaders .= "MIME-Version: 1.0\n";
  1888. $customHeaders .= "Content-Type: text/HTML; charset=ISO-8859-1\n";
  1889. $sql = "SELECT * FROM orders WHERE ordID = '$ordID'";
  1890. $res = mysql_query($sql) or print(mysql_error());
  1891. $row = mysql_fetch_assoc($res);
  1892. $to = $row['ordEmail'];
  1893. $message .= '<p>Your order <strong>'.$ordID.'</strong> has been shipped. If you selected FedEx for shipping, your tracking information should be available within 24 hours, which will allow you can track your order every step of the way from our <a href="http://ifrogz.com/order_info.php?ordID='.$ordID.'&email='.$to.'">order status</a> page.</p>';
  1894. $message .= '<p>Below you can find how many days until your order should arrive depending on the shipping you selected.</p>';
  1895. $message .= '<ul>';
  1896. $message .= ' <li><strong>Standard:</strong> 5 - 8 business days</li>';
  1897. $message .= ' <li><strong>Priority Mail:</strong> 3 - 4 business days</li>';
  1898. $message .= ' <li><strong>FedEx:</strong> 2 - 3 business days</li>';
  1899. $message .= ' <li><strong>International:</strong> 10 - 12 business days</li>';
  1900. $message .= '</ul>';
  1901. $message .= '<p>Thank you for your order, and we hope you enjoy your new ifrogz product!</p>';
  1902. mail($to, $subject, $message, $customHeaders);
  1903. }
  1904. // A usort function used in printpackingslips.php to sort by bin # correctly
  1905. function cmpBins($a, $b) {
  1906. if (strstr($a['bin'], "*") && strstr($b['bin'], "*")) { // If both follow the same format for Bins with asterisks
  1907. $arrBin = explode("*", $a['bin']);
  1908. $arrBin2 = explode("*", $b['bin']);
  1909. if ($arrBin[1] == $arrBin2[1]) { // Same bin letter
  1910. if ($arrBin[2] == $arrBin2[2]) {
  1911. return 0;
  1912. }
  1913. if ($arrBin[2] < $arrBin2[2]) {
  1914. return -1;
  1915. } else {
  1916. return 1;
  1917. }
  1918. } else {
  1919. if ($arrBin[1] < $arrBin2[1]) {
  1920. return -1;
  1921. } else {
  1922. return 1;
  1923. }
  1924. }
  1925. } else {
  1926. $bin1 = simplify_bin($a['bin']);
  1927. $bin2 = simplify_bin($b['bin']);
  1928. if ($bin1 == $bin2) {
  1929. return 0;
  1930. }
  1931. if ($bin1 < $bin2) {
  1932. return -1;
  1933. } else {
  1934. return 1;
  1935. }
  1936. }
  1937. }
  1938. function simplify_bin($bin) {
  1939. $first_asterisk = strpos($bin, '*') != FALSE ? strpos($bin, '*')+1 : FALSE;
  1940. $first_hyphen = strpos($bin, '-') != FALSE ? strpos($bin, '-')+1 : FALSE;
  1941. if(strcmp($bin, '') == 0) {
  1942. return $bin;
  1943. } else if($first_asterisk > 0) {
  1944. $temp_string = substr($bin, $first_asterisk);
  1945. $second_asterisk = strpos($temp_string, '*')+$first_asterisk;
  1946. return substr($bin, $first_asterisk, $second_asterisk - $first_asterisk);
  1947. } else {
  1948. $temp = substr($bin, 0, $first_hyphen);
  1949. return $temp;
  1950. }
  1951. }
  1952. ?>