Guest User

Untitled

a guest
Feb 6th, 2017
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 38.10 KB | None | 0 0
  1. <?php
  2. if(!isset($_SERVER['REQUEST_URI'])){
  3. $req = $_SERVER['PHP_SELF'];
  4. if ( isset($_SERVER['QUERY_STRING']) && (strlen($_SERVER['QUERY_STRING']) > 0))
  5. $req .= '?'.$_SERVER['QUERY_STRING'];
  6. $_SERVER['REQUEST_URI'] = $GLOBALS['REQUEST_URI'] = $req;
  7. }
  8.  
  9. //frequently used functions
  10. function MagicQuotesRuntimeSetting()
  11. {
  12. ini_set("magic_quotes_runtime",0);
  13. }
  14.  
  15. function correct_URL( $url, $mode = "http" ){
  16.  
  17. $URLprefix = trim( $url );
  18. $URLprefix = str_replace(array('http://', 'https://', 'index.php'), '', $URLprefix);
  19. if ($URLprefix[ strlen($URLprefix)-1 ] == '/')
  20. $URLprefix = substr( $URLprefix, 0, strlen($URLprefix)-1 );
  21.  
  22. return ($mode."://".$URLprefix."/");
  23. }
  24.  
  25. /**
  26. * Sets access rights to files which uploaded with help move_uploaded_file
  27. * @param string $file_name
  28. */
  29. function SetRightsToUploadedFile( $file_name ){
  30. @chmod( $file_name, 0666);
  31. }
  32.  
  33. function Redirect($url){
  34. $softwareInfo = getServerInfo();
  35.  
  36. $winIIS = strstr(php_uname(), 'Windows') && ( $softwareInfo == 'IIS' );
  37.  
  38. if ( $winIIS ){
  39. $str_redirect = "Refresh: 0;url=%s";
  40. }else{
  41. $str_redirect = "Location: %s";
  42. }
  43. header(sprintf($str_redirect, escapeCRLF($url)));
  44. exit(1);
  45. //header("location: ".escapeCRLF($url), true, 302);
  46. //exit(1);
  47. }
  48.  
  49. function getServerInfo()
  50. {
  51. $ssoft=strtolower($_SERVER["SERVER_SOFTWARE"]);
  52. if (strstr($ssoft,"apache")){
  53. $sos="Apache";
  54. }elseif (strstr($ssoft,"iis")){
  55. $sos="IIS";
  56. }else{
  57. $sos = "Apache";
  58. }
  59. return $sos;
  60. }
  61.  
  62. function RedirectSQ($_params = '', $_url=''){
  63. Redirect(renderURL($_params,$_url));
  64. }
  65.  
  66. /**
  67. * round float value to 0.01 precision
  68. *
  69. * @param float $float_value
  70. * @return float
  71. */
  72. function RoundFloatValue( $float_value ){
  73. return round (100*$float_value)/100;
  74. }
  75.  
  76. // Purpose round float value to 0.01 precision
  77. // Inputs $float_value - value to float
  78. // Remarks this function returns string value.
  79. // Two digits locate after decimal point always.
  80. // Returns rounded value
  81. function RoundFloatValueStr( $float_value )
  82. {
  83. $str = RoundFloatValue( $float_value );
  84. $index = strpos($str,".");
  85. if ( $index === false )
  86. return $str.".00";
  87. else
  88. {
  89. if ( strlen($str)-1-$index == 1 )
  90. return $str."0";
  91. else
  92. return $str;
  93. }
  94. }
  95.  
  96. // Purpose gets all files in specified directory
  97. // Inputs $dir - full path directory
  98. function GetFilesInDirectory( $dir, $extension = '',$name_template = null)
  99. {
  100. if(!file_exists($dir))return array();
  101.  
  102. $dh = opendir($dir);
  103. $files = array();
  104. $pattern = '|'.($name_template?$name_template:'').'\.'.$extension.'$|msi';
  105. while (false !== ($filename = readdir($dh)))
  106. {
  107. if ( !is_dir($dir.'/'.$filename) && $filename != '.' && $filename != '..' ){
  108.  
  109. if(preg_match($pattern,$filename)){
  110. $files[] = $dir.'/'.$filename;
  111. }
  112. }
  113. }
  114. return $files;
  115. }
  116.  
  117. /**
  118. * Show a number and selected currency sign
  119. *
  120. * @param float $price - is in universal currency
  121. * @param mixed $custom_currency - if $custom_currency != 0 show price this currency with ID = $custom_currency
  122. * @param boolean $priceInUC - notify about price is in UC format
  123. * @return string
  124. */
  125. function show_price($price, $custom_currency = 0, $priceInUC = true){
  126.  
  127. if($custom_currency){
  128. $currencyEntry = new Currency();
  129. $currencyEntry->loadByCID($custom_currency);
  130. }else{
  131. $Register = &Register::getInstance();
  132. /*@var $Register Register*/
  133. $currencyEntry = $Register->get('admin_mode')?Currency::getDefaultCurrencyInstance():Currency::getSelectedCurrencyInstance();
  134. /*@var $currencyEntry Currency*/
  135. }
  136.  
  137. $price = $priceInUC?$currencyEntry->convertUnits($price):$price;
  138.  
  139. return $currencyEntry->getView($price);
  140. }
  141.  
  142. function ConvertPriceToUniversalUnit($priceWithOutUnit){
  143.  
  144. $currencyEntry = Currency::getSelectedCurrencyInstance();
  145. return $currencyEntry->convertToUnits($priceWithOutUnit, true);
  146. }
  147.  
  148. function show_priceWithOutUnit($price){
  149.  
  150. $currencyEntry = Currency::getSelectedCurrencyInstance();
  151.  
  152. return $currencyEntry->convertUnits($price, true);
  153. }
  154.  
  155. function ShowNavigator($a, $offset, $q, $path, &$out)
  156. {
  157. //shows navigator [prev] 1 2 3 4 � [next]
  158. //$a - count of elements in the array, which is being navigated
  159. //$offset - current offset in array (showing elements [$offset ... $offset+$q])
  160. //$q - quantity of items per page
  161. //$path - link to the page (f.e: "index.php?categoryID=1&")
  162.  
  163. if ($a > $q) //if all elements couldn't be placed on the page
  164. {
  165.  
  166. //[prev]
  167. if ($offset>0) $out .= "<a class=no_underline href=\"".xHtmlSetQuery($path."&offset=".($offset-$q))."\">&lt;&lt; ".translate("str_previous")."</a> &nbsp;&nbsp;";
  168.  
  169. //digital links
  170. $k = $offset / $q;
  171.  
  172. //not more than 4 links to the left
  173. $min = $k - 5;
  174. if ($min < 0) { $min = 0; }
  175. else {
  176. if ($min >= 1)
  177. { //link on the 1st page
  178. $out .= "<a class=no_underline href=\"".xHtmlSetQuery($path."&offset=0")."\">1</a> &nbsp;&nbsp;";
  179. if ($min != 1) { $out .= "... &nbsp;"; };
  180. }
  181. }
  182.  
  183. for ($i = $min; $i<$k; $i++)
  184. {
  185. $m = $i*$q + $q;
  186. if ($m > $a) $m = $a;
  187.  
  188. $out .= "<a class=no_underline href=\"".xHtmlSetQuery($path."&offset=".($i*$q))."\">".($i+1)."</a> &nbsp;&nbsp;";
  189. }
  190.  
  191. //# of current page
  192. if (strcmp($offset, "show_all"))
  193. {
  194. $min = $offset+$q;
  195. if ($min > $a) $min = $a;
  196. $out .= "<font class=faq><b>".($k+1)."</b></font> &nbsp;&nbsp;";
  197. }
  198. else
  199. {
  200. $min = $q;
  201. if ($min > $a) $min = $a;
  202. $out .= "<a class=no_underline href=\"".xHtmlSetQuery($path."&offset=0")."\">1</a> &nbsp;&nbsp;";
  203. }
  204.  
  205. //not more than 5 links to the right
  206. $min = $k + 6;
  207. if ($min > ceil($a/$q)) { $min = ceil($a/$q); };
  208. for ($i = $k+1; $i<$min; $i++)
  209. {
  210. $m = $i*$q+$q;
  211. if ($m > $a) $m = $a;
  212.  
  213. $out .= "<a class=no_underline href=\"".xHtmlSetQuery($path."&offset=".($i*$q))."\">".($i+1)."</a> &nbsp;&nbsp;";
  214. }
  215.  
  216. if ($min*$q < $a) { //the last link
  217. if ($min*$q < $a-$q) $out .= " ... &nbsp;&nbsp;";
  218. if (!($a%$q == 0))
  219. $out .= "<a class=no_underline href=\"".xHtmlSetQuery($path."&offset=".($a-$a%$q))."\">".(floor($a/$q)+1)."</a> &nbsp;&nbsp;";
  220. else //$a is divided by $q
  221. $out .= "<a class=no_underline href=\"".xHtmlSetQuery($path."&offset=".($a-$q))."\">".(floor($a/$q))."</a> &nbsp;&nbsp;";
  222. }
  223.  
  224. //[next]
  225. if (strcmp($offset, "show_all"))
  226. if ($offset<$a-$q) $out .= "<a class=no_underline href=\"".xHtmlSetQuery($path."&offset=".($offset+$q))."\">".translate("str_next")." &gt;&gt;</a> ";
  227.  
  228. //[show all]
  229. if(SHOWALL_ALLOWED_RECORDS_NUM >= $a || (!SystemSettings::is_hosted()&&SystemSettings::is_backend())){
  230. if (strcmp($offset, "show_all"))
  231. $out .= " |&nbsp; <a class=no_underline href=\"".xHtmlSetQuery($path."&offset=&show_all=yes")."\">".translate("str_showall")."</a>";
  232. else
  233. $out .= " |&nbsp; <B>".translate("str_showall")."</B>";
  234. }
  235. }
  236. }
  237.  
  238. function GetNavigatorHtml( $url, $countRowOnPage = CONF_PRODUCTS_PER_PAGE,
  239. $callBackFunction, $callBackParam, &$tableContent,
  240. &$offset, &$count )
  241. {
  242. if ( isset($_GET["offset"]) )
  243. $offset = (int)$_GET["offset"];
  244. else
  245. $offset = 0;
  246. $offset -= $offset % $countRowOnPage;//CONF_PRODUCTS_PER_PAGE;
  247. if ( $offset < 0 ) $offset = 0;
  248. $count = 0;
  249.  
  250. $url = preg_replace('@^[^\?\&]+@', '', $url);
  251.  
  252. $Register = &Register::getInstance();
  253. if ( !$Register->is_set("show_all") || !$Register->get('show_all')) //show 'CONF_PRODUCTS_PER_PAGE' products on this page
  254. {
  255. $tableContent = $callBackFunction( $callBackParam, $count,
  256. array(
  257. "offset" => $offset,
  258. "CountRowOnPage" => $countRowOnPage
  259. )
  260. );
  261. }else{ //show all products
  262.  
  263. $tableContent = $callBackFunction( $callBackParam, $count, null );
  264. $offset = "show_all";
  265. }
  266. $out = null;
  267. ShowNavigator( $count, $offset, $countRowOnPage, $url, $out);
  268. return $out;
  269. }
  270.  
  271. function moveCartFromSession2DB() //all products in shopping cart, which are in session vars, move to the database
  272. {
  273. if ( isset($_SESSION["gids"]) && isset($_SESSION["log"]) )
  274. {
  275.  
  276. $customerID = regGetIdByLogin( $_SESSION["log"] );
  277. $q = db_query( "select itemID from ".SHOPPING_CARTS_TABLE." where customerID=".$customerID );
  278. $items = array();
  279. while ( $item = db_fetch_row($q) )
  280. $items[] = $item["itemID"];
  281.  
  282. //$i=0;
  283. foreach( $_SESSION["gids"] as $key => $productID )
  284. {
  285. if ( $productID == 0 )
  286. continue;
  287.  
  288. // search product in current user's shopping cart content
  289. $itemID = null;
  290. for( $j=0; $j<count($items); $j++ )
  291. {
  292. $q = db_query( "select count(*) from ".SHOPPING_CART_ITEMS_TABLE." where productID=".$productID." AND ".
  293. " itemID=".$items[$j] );
  294. $count = db_fetch_row($q);
  295. $count = $count[0];
  296. if ( $count != 0 )
  297. {
  298. // compare configuration
  299. $configurationFromSession = $_SESSION["configurations"][$key];
  300. $configurationFromDB = GetConfigurationByItemId( $items[$j] );
  301. if ( CompareConfiguration($configurationFromSession, $configurationFromDB) )
  302. {
  303. $itemID = $items[$j];
  304. break;
  305. }
  306. $itemID = $items[$j];
  307.  
  308. }
  309. }
  310.  
  311.  
  312. if ( $itemID == null )
  313. {
  314. // create new item
  315. db_query( "insert into ".SHOPPING_CART_ITEMS_TABLE.
  316. " (productID) values('".$productID."')\n" ) or die (db_error());
  317. $itemID = db_insert_id();
  318.  
  319. // set content item
  320. foreach( $_SESSION["configurations"][$key] as $var )
  321. {
  322. db_query("insert into ".
  323. SHOPPING_CART_ITEMS_CONTENT_TABLE." ( itemID, variantID ) ".
  324. " values( '".$itemID."', '".$var."' )\n" ) or die (db_error());
  325. }
  326.  
  327. // insert item into cart
  328. db_query("insert ".SHOPPING_CARTS_TABLE.
  329. "(customerID, itemID, Quantity)".
  330. "values( '".$customerID."', '".$itemID."', '".$_SESSION["counts"][$key].
  331. "' )\n" ) or die (db_error());
  332. }
  333. else
  334. {
  335. db_query( "update ".SHOPPING_CARTS_TABLE.
  336. " set Quantity=Quantity + ".$_SESSION["counts"][$key]." ".
  337. " where customerID=".$customerID." and itemID=".$itemID."\n" ) or die (db_error());
  338. }
  339.  
  340. }
  341.  
  342. unset($_SESSION["gids"]);
  343. unset($_SESSION["counts"]);
  344. unset($_SESSION["configurations"]);
  345. session_unregister("gids"); //calling session_unregister() is required since unset() may not work on some systems
  346. session_unregister("counts");
  347. session_unregister("configurations");
  348. }
  349. }
  350.  
  351. /**
  352. * Reprganize array from array('hello_<some>'=>123) to array(<some>=>array('hello'=>123))
  353. *
  354. * @param array $a
  355. * @param array|string $varnames
  356. * @return array
  357. */
  358. function scanArrayKeysForID($a, $varnames){
  359.  
  360. if(!is_array($varnames)){
  361. $varnames = array($varnames);
  362. }
  363. $data = array();
  364. foreach($varnames as $name){
  365. foreach($a as $key => $value){
  366.  
  367. if (preg_match("/({$name})_/", $key, $kp)){
  368.  
  369. $key = preg_replace("/{$name}_/","",$key);
  370. $data[$key][$kp[1]] = $value;
  371. }
  372. }
  373. }
  374. return $data;
  375. }
  376.  
  377. define('URLRENDMODE_MODIFY', 1);
  378. define('URLRENDMODE_RESET', 2);
  379.  
  380. function renderGetVars($URL){
  381.  
  382. $GetVars = array();
  383. $parsedURL = parse_url($URL);
  384.  
  385. if(isset($parsedURL['query'])&&$parsedURL['query']){
  386.  
  387. $r_TokenStrs = explode('&', $parsedURL['query']);
  388.  
  389. foreach ($r_TokenStrs as $TokenStr){
  390.  
  391. $r_Token = explode('=', $TokenStr,2);
  392. if(isset($r_Token[1])){
  393. $GetVars[$r_Token[0]] = $r_Token[1];
  394. }
  395. }
  396. }
  397. return $GetVars;
  398. }
  399.  
  400. function renderURL($_vars = '', $_request = '', $_store = false, $furl = null,$external = false){
  401.  
  402. $RenderedURL = '';
  403.  
  404.  
  405. if(!$_request){
  406.  
  407. $_request = $_SERVER['REQUEST_URI'];
  408. $GetVars = $_GET;
  409. }else{
  410.  
  411. $GetVars = renderGetVars($_request);
  412. }
  413.  
  414. if(!MOD_REWRITE_SUPPORT)
  415. {
  416. if(strpos($_request, 'index.php') === false &&!$external)
  417. {
  418. if(strpos($_request, '?')) $_request = str_replace('?','index.php?',$_request);
  419. else $_request .= 'index.php';
  420. };
  421. if(preg_match("/^\?categoryID=(\d+)\&category_slug=[a-z0-9_]+$/i", $_vars, $matches))
  422. {
  423. $_vars = '?categoryID='.$matches[1];
  424. };
  425.  
  426. if(preg_match("/^\?ukey=product\&productID=(\d+)\&product_slug=[a-z0-9_\-]+$/i", $_vars, $matches))
  427. {
  428. $_vars = '?productID='.$matches[1];
  429. };
  430. };
  431.  
  432. $anchor = preg_match('@(#[^#]*)$@', $_request, $sp)?$sp[1]:'';
  433. $anchor = preg_match('@(#[^#]*)$@', $_vars, $sp)?$sp[1]:$anchor;
  434.  
  435. /**
  436. * Set render mode
  437. */
  438. if(strpos($_vars,'?')!==false){
  439.  
  440. $Mode = URLRENDMODE_RESET;
  441. $_vars = substr($_vars, 1, strlen($_vars)-1).'&lang_iso2=';
  442. }else{
  443.  
  444. $Mode = URLRENDMODE_MODIFY;
  445. }
  446.  
  447. /**
  448. * trim first ampersand
  449. */
  450. if(strpos($_vars,'&')===0)$_vars = substr($_vars, 1, strlen($_vars)-1);
  451.  
  452. /**
  453. * Render new get-tokens
  454. */
  455. $ReceivedTokens = array();
  456. $r_TokenStrs = explode('&', $_vars);
  457. $widgets_token = false;
  458. foreach ($r_TokenStrs as $TokenStr){
  459.  
  460. $r_Token = explode('=', $TokenStr,2);
  461. if($r_Token[0]=='widgets')$widgets_token = true;
  462. if(isset($r_Token[1])&& strlen($r_Token[1])){
  463.  
  464. $ReceivedTokens[$r_Token[0]] = $r_Token[1];
  465. if($Mode == URLRENDMODE_MODIFY){
  466.  
  467. $GetVars[$r_Token[0]] = $r_Token[1];
  468. }
  469. }else {
  470.  
  471. switch ($Mode){
  472. case URLRENDMODE_MODIFY:
  473.  
  474. if(isset($GetVars[$r_Token[0]]))
  475. unset($GetVars[$r_Token[0]]);
  476. break;
  477. case URLRENDMODE_RESET:
  478. if(isset($GetVars[$r_Token[0]]) && $r_Token[0]!='product_slug' && $r_Token[0]!='category_slug')
  479. $ReceivedTokens[$r_Token[0]] = $GetVars[$r_Token[0]];
  480. break;
  481. }
  482. }
  483. }
  484. /**
  485. * Render URL
  486. */
  487. $newGetVars = array();
  488. switch ($Mode){
  489. case URLRENDMODE_MODIFY:
  490. $newGetVars = &$GetVars;
  491. break;
  492. case URLRENDMODE_RESET:
  493. $newGetVars = &$ReceivedTokens;
  494. break;
  495. }
  496. if(!$widgets_token && count($newGetVars)){
  497. $Register = &Register::getInstance();
  498. /*@var $Register Register*/
  499. if($Register->get('widgets'))$newGetVars['widgets'] = 1;
  500. }
  501.  
  502. if($_store){
  503.  
  504. $_GET = $newGetVars;
  505. }
  506. if(class_exists('fURL')&& $furl !== false)
  507. fURL::convertGetToPath($_request, $newGetVars);
  508.  
  509. foreach ($newGetVars as $TokenName=>$TokenValue){
  510.  
  511. $newGetVars[$TokenName] = $TokenName.'='.$TokenValue;
  512. }
  513. $RenderedURL = implode('&', $newGetVars);
  514. if(strpos($_request, '?')!==false){
  515.  
  516. $RenderedURL = preg_replace('/\?.*$/','?'.$RenderedURL,$_request);
  517. }else {
  518.  
  519. $RenderedURL = $_request.'?'.$RenderedURL;
  520. }
  521.  
  522. $RenderedURL = preg_replace('@[\?\&]{1,2}$@', '', $RenderedURL);
  523.  
  524. if(strlen($anchor)>1)$RenderedURL = preg_replace('@#[^#]*$@', '', $RenderedURL).$anchor;
  525. /**
  526. * Strore URL
  527. */
  528. if($_store){
  529.  
  530. // $_SERVER['REQUEST_URI'] = $RenderedURL;
  531. }
  532.  
  533. return $RenderedURL;
  534. }
  535.  
  536. function set_query($_vars='', $_request = '', $_store = false, $external = false){
  537.  
  538. return renderURL($_vars, $_request, $_store,null,$external);
  539. }
  540.  
  541. function xHtmlSetQuery($_vars='', $_request = '', $_store = false){
  542.  
  543. return xHtmlSpecialChars(renderURL($_vars, $_request, $_store));
  544. }
  545.  
  546. function getListerRange($_pagenumber, $_totalpages, $_lister_num = 20){
  547.  
  548. if($_pagenumber<=0) return array('start'=>1, 'end'=>1);
  549. $lister_start=$_pagenumber-floor($_lister_num/2);
  550. $lister_start=($lister_start+$_lister_num<=$_totalpages?$lister_start:$_totalpages-$_lister_num+1);
  551. $lister_start=($lister_start>0?$lister_start:1);
  552. $lister_end=$lister_start+$_lister_num-1;
  553. $lister_end=($lister_end<=$_totalpages?$lister_end:$_totalpages);
  554. return array('start'=>$lister_start, 'end'=>$lister_end);
  555. }
  556.  
  557. function getLister($_pagenumber, $_totalpages, $_lister_num = 20){
  558.  
  559. if($_pagenumber<=0)return array(
  560. 'CurrentPage'=>1,
  561. 'LastPage' => 1,
  562. 'Range' =>array(1),
  563. );
  564. $Lister = array(
  565. 'CurrentPage'=>$_pagenumber,
  566. 'LastPage' => $_totalpages,
  567. 'Range' =>array(),
  568. );
  569. $lister_start=$_pagenumber-floor($_lister_num/2);
  570. $lister_start=($lister_start+$_lister_num<=$_totalpages?$lister_start:$_totalpages-$_lister_num+1);
  571. $lister_start=($lister_start>0?$lister_start:1);
  572. $lister_end=$lister_start+$_lister_num-1;
  573. $lister_end=($lister_end<=$_totalpages?$lister_end:$_totalpages);
  574. for (;$lister_start<=$lister_end;$lister_start++)
  575. $Lister['Range'][] = $lister_start;
  576. return $Lister;
  577. }
  578.  
  579. /**
  580. *Strip slashes if magic_quotes_gpc is On
  581. *
  582. *@param mixed
  583. * return mixed
  584. */
  585. function xStripSlashesGPC($_data){
  586.  
  587. if(!get_magic_quotes_gpc())return $_data;
  588. if(is_array($_data)){
  589.  
  590. foreach ($_data as $_ind => $_val){
  591.  
  592. $_data[$_ind] = xStripSlashesGPC($_val);
  593. }
  594. return $_data;
  595. }
  596. return stripslashes($_data);
  597. }
  598.  
  599. /**
  600. * mail txt message from template
  601. * @param string email
  602. * @param string email subject
  603. * @param string template name
  604. */
  605. function xMailTxt($_Email, $_Subject, $_TemplateName, $_AssignArray = array(), $html = false){
  606.  
  607. if(!$_Email)return 0;
  608. $mailSmarty = new View();
  609. foreach ($_AssignArray as $_var=>$_val){
  610.  
  611. $mailSmarty->assign($_var, $_val);
  612. }
  613. $_t = $mailSmarty->fetch('email/'.$_TemplateName);
  614. ss_mail($_Email, $_Subject, $_t, true);
  615. }
  616.  
  617. /**
  618. * replace newline symbols to &lt;br /&gt;
  619. * @param mixed data for action
  620. * @param array which elements test
  621. * @return mixed
  622. */
  623. function xNl2Br($_Data, $_Key = array()){
  624.  
  625.  
  626. if (!is_array($_Data)){
  627.  
  628. return nl2br($_Data);
  629. }
  630.  
  631. if (!is_array($_Key))$_Key = array($_Key);
  632. foreach ($_Data as $__Key=>$__Data){
  633.  
  634. if (count($_Key)&&!is_array($__Data)){
  635.  
  636. if (in_array($__Key, $_Key)){
  637.  
  638. $_Data[$__Key] = xNl2Br($__Data, $_Key);
  639. }
  640. }else $_Data[$__Key] = xNl2Br($__Data, $_Key);
  641.  
  642. }
  643. return $_Data;
  644. }
  645.  
  646. function xStrReplace($_Search, $_Replace, $_Data, $_Key=array()){
  647.  
  648. if (!is_array($_Data)){
  649.  
  650. return str_replace($_Search, $_Replace, $_Data);
  651. }
  652.  
  653. if (!is_array($_Key))$_Key = array($_Key);
  654. foreach ($_Data as $__Key=>$__Data){
  655.  
  656. if (count($_Key)&&!is_array($__Data)){
  657.  
  658. if (in_array($__Key, $_Key)){
  659.  
  660. $_Data[$__Key] = xStrReplace($_Search, $_Replace, $__Data, $_Key);
  661. }
  662. }else $_Data[$__Key] = xStrReplace($_Search, $_Replace, $__Data, $_Key);
  663.  
  664. }
  665. return $_Data;
  666. }
  667.  
  668. function xHtmlSpecialChars($_Data, $_Params = array(), $_Key = array()){
  669.  
  670.  
  671. if (!is_array($_Data)){
  672.  
  673. return htmlspecialchars($_Data, ENT_QUOTES);
  674. }
  675.  
  676. if (!is_array($_Key))$_Key = array($_Key);
  677. foreach ($_Data as $__Key=>$__Data){
  678.  
  679. if (count($_Key)&&!is_array($__Data)){
  680.  
  681. if (in_array($__Key, $_Key)){
  682.  
  683. $_Data[$__Key] = xHtmlSpecialChars( $__Data, $_Params, $_Key);
  684. }
  685. }else $_Data[$__Key] = xHtmlSpecialChars( $__Data, $_Params, $_Key);
  686.  
  687. }
  688. return $_Data;
  689. }
  690.  
  691. function xEscapeSQLstring ( $_Data, $_Params = array(), $_Key = array() ){
  692.  
  693. if (!is_array($_Data)){
  694.  
  695. return mysql_real_escape_string($_Data);
  696. }
  697.  
  698. if (!is_array($_Key))$_Key = array($_Key);
  699. foreach ($_Data as $__Key=>$__Data){
  700.  
  701. if (count($_Key)&&!is_array($__Data)){
  702.  
  703. if (in_array($__Key, $_Key)){
  704.  
  705. $_Data[$__Key] = xEscapeSQLstring( $__Data, $_Params, $_Key);
  706. }
  707. }else $_Data[$__Key] = xEscapeSQLstring( $__Data, $_Params, $_Key);
  708.  
  709. }
  710. return $_Data;
  711. }
  712.  
  713. function xSaveData($_ID, $_Data, $_TimeControl = 0){
  714.  
  715. if(!isset ($_SESSION ['_xSAVE_DATA'])){
  716. $_SESSION['_xSAVE_DATA'] = array();
  717. }
  718.  
  719. if(intval($_TimeControl)){
  720.  
  721. $_SESSION['_xSAVE_DATA'][$_ID] = array(
  722. $_ID.'_DATA' => $_Data,
  723. $_ID.'_TIME_CTRL' => array(
  724. 'timetag' => time(),
  725. 'timelimit' => $_TimeControl,
  726. ),
  727. );
  728. }else{
  729. $_SESSION['_xSAVE_DATA'][$_ID] = $_Data;
  730. }
  731. }
  732.  
  733. function xPopData($_ID){
  734.  
  735. if(!isset($_SESSION['_xSAVE_DATA'][$_ID])){
  736. return null;
  737. }
  738.  
  739. if(is_array($_SESSION['_xSAVE_DATA'][$_ID])){
  740.  
  741. if(isset($_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_TIME_CTRL'])){
  742.  
  743. if( ($_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_TIME_CTRL']['timetag']+$_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_TIME_CTRL']['timelimit']) < time() ){
  744. return null;
  745. }else{
  746.  
  747. $Return = $_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_DATA'];
  748. unset($_SESSION['_xSAVE_DATA'][$_ID]);
  749. return $Return;
  750. }
  751. }
  752. }
  753.  
  754. $Return = $_SESSION['_xSAVE_DATA'][$_ID];
  755. unset($_SESSION['_xSAVE_DATA'][$_ID]);
  756. return $Return;
  757. }
  758.  
  759. function xDataExists($_ID){
  760.  
  761. if(!isset($_SESSION['_xSAVE_DATA'][$_ID]))return 0;
  762.  
  763. if(is_array($_SESSION['_xSAVE_DATA'][$_ID])){
  764.  
  765. if(isset($_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_TIME_CTRL'])){
  766.  
  767. if( ($_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_TIME_CTRL']['timetag']+$_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_TIME_CTRL']['timelimit']) >= time() ){
  768. return 1;
  769. }else{
  770. return 0;
  771. }
  772. }else{
  773. return 1;
  774. }
  775. }else{
  776. return 1;
  777. }
  778. }
  779.  
  780. function xGetData($_ID){
  781.  
  782. if(!isset($_SESSION['_xSAVE_DATA'][$_ID])){
  783. return null;
  784. }
  785.  
  786. if(is_array($_SESSION['_xSAVE_DATA'][$_ID])){
  787.  
  788. if(isset($_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_TIME_CTRL'])){
  789.  
  790. if( ($_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_TIME_CTRL']['timetag']+$_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_TIME_CTRL']['timelimit']) < time() ){
  791. return null;
  792. }else{
  793.  
  794. $Return = $_SESSION['_xSAVE_DATA'][$_ID][$_ID.'_DATA'];
  795. return $Return;
  796. }
  797. }
  798. }
  799.  
  800. $Return = $_SESSION['_xSAVE_DATA'][$_ID];
  801. return $Return;
  802. }
  803.  
  804. function xCall($func_name, $data, $params = null){
  805.  
  806. if (!is_array($data))return call_user_func_array($func_name, array($data, $params));
  807.  
  808. foreach ($data as $k=>$v)$data[$k] = xCall($func_name, $v, $params);
  809. return $data;
  810. }
  811.  
  812. function isWindows(){
  813. if(defined('IS_WINDOWS')){
  814. return constant('IS_WINDOWS');
  815. }
  816. if(isset($_SERVER["WINDIR"]) || isset($_SERVER["windir"]))return true;
  817. if(isset($_SERVER['SERVER_SOFTWARE'])&&(strpos(strtolower($_SERVER['SERVER_SOFTWARE']),'microsoft')!==false)) return true;
  818. return false;
  819. }
  820.  
  821. function generateRndCode($_RndLength, $_RndCodes = 'qwertyuiopasdfghjklzxcvbnm0123456789'){
  822.  
  823. $l_name='';
  824. $top = strlen($_RndCodes)-1;
  825. srand((double) microtime()*1000000);
  826. for($j=0; $j<$_RndLength; $j++)$l_name .= $_RndCodes{rand(0,$top)};
  827. return $l_name;
  828. }
  829.  
  830. function get_NOTempty_elements_count($arr) //required for excel import
  831. //gets how many NOT NULL (not empty strings) elements are there in the $arr
  832. {
  833. $n = 0;
  834. for ($i=0;$i<count($arr);$i++)
  835. if (trim($arr[$i]) != "") $n++;
  836. return $n;
  837. } //get_NOTempty_elements_count
  838.  
  839. function mark_as_selected($a,$b) //required for excel import
  840. //returns " selected" if $a == $b
  841. {
  842. return !strcmp($a,$b) ? " selected" : "";
  843.  
  844. } //mark_as_selected
  845.  
  846. /**
  847. * Authorized access check
  848. *
  849. */
  850. function checkLogin(){
  851.  
  852. //authorized access check
  853. if (isset($_SESSION["log"])){ //look for user in the database
  854.  
  855. $sql = '
  856. SELECT cust_password FROM ?#CUSTOMERS_TABLE WHERE Login=?
  857. ';
  858.  
  859. $row = db_phquery_fetch(DBRFETCH_ROW, $sql, $_SESSION["log"]); //found customer - check password
  860.  
  861. if (!$row || !isset($_SESSION["pass"]) || strcmp($row[0], $_SESSION["pass"] )) //unauthorized access
  862. {
  863. unset($_SESSION["log"]);
  864. unset($_SESSION["pass"]);
  865. session_unregister("log"); //calling session_unregister() is required since unset() may not work on some systems
  866. session_unregister("pass");
  867. }
  868.  
  869. }
  870. }
  871.  
  872. function isHTTPS(){
  873.  
  874. return isset($_SERVER['HTTPS'])&&(strtolower($_SERVER['HTTPS'])!='off');
  875. }
  876.  
  877. function escapeCRLF($str){
  878.  
  879. return str_replace(array("\r\n",'%0d%0a', "\n",'%0a', "\r",'%0d'),'',$str);
  880. }
  881.  
  882. /**
  883. * Cut string
  884. *
  885. * @param string $String - source
  886. * @param int $Length - target length
  887. * @param string $EndString
  888. */
  889. function str_cut($String, $Length, $EndString = '...'){
  890.  
  891. $origlength = strlen($String);
  892. if($origlength<=$Length)return $String;
  893. $String = substr($String,0,$Length);
  894. $lastspace_i = strrpos($String,' ');
  895. if($lastspace_i !== false)
  896. $String = substr($String,0,$lastspace_i);
  897. return $String.($origlength>$Length?$EndString:'');
  898. }
  899.  
  900. function getUniqueWDataID($Length = 4){
  901.  
  902. $ID = '';
  903. do {
  904.  
  905. $ID = rand_name($Length);
  906. }while(issetWData($ID));
  907. return $ID;
  908. }
  909.  
  910. function rand_name($_length = 4){
  911.  
  912. $rand_simb = "qwertyuiopasdfghjklzxcvbnm0123456789";
  913. $l_name='';
  914. $top = strlen($rand_simb)-1;
  915. srand((double) microtime()*1000000);
  916. for($j=0; $j<$_length; $j++)$l_name .= $rand_simb{rand(0,$top)};
  917. return $l_name;
  918. }
  919.  
  920. function getUnicFile($_length = 4, $_tpl = "%s", $_path = "./"){
  921.  
  922. $fname = $_tpl;
  923. $limit = 0;
  924. do{
  925.  
  926. $fname = sprintf($_tpl, rand_name($_length));
  927. }while (file_exists($_path.$fname)&&300<$limit++);
  928. return $fname;
  929. }
  930.  
  931. function issetWData($VarName){
  932.  
  933. return isset($_SESSION['xPOST'][$VarName]);
  934. }
  935.  
  936. function storeWData($_VarName, $_VarData){
  937.  
  938. storePOST($_VarName, $_VarData);
  939. }
  940.  
  941. function loadWData($_VarName){
  942.  
  943. return loadPOST($_VarName);
  944. }
  945.  
  946. function unsetWData($VarName){
  947.  
  948. unset($_SESSION['xPOST'][$VarName]);
  949. }
  950.  
  951. function popWData($VarName){
  952.  
  953. $WData = loadWData($VarName);
  954. unsetWData($VarName);
  955. return $WData;
  956. }
  957.  
  958. function storePOST($_VarName, $_VarData){
  959.  
  960. if(!isset ($_SESSION ['xPOST'])) {
  961. $_SESSION ['xPOST'] =array();
  962. }
  963.  
  964. $_SESSION['xPOST'][$_VarName] = $_VarData;
  965. }
  966.  
  967. function loadPOST($_VarName){
  968.  
  969. if(!isset($_SESSION['xPOST'][$_VarName])) return null;
  970. return $_SESSION['xPOST'][$_VarName];
  971. }
  972.  
  973. function unsetPOST(){
  974.  
  975. if(isset($_SESSION['xPOST']))
  976. unset($_SESSION['xPOST']);
  977. }
  978.  
  979. /**
  980. * is used all around the software
  981. * $headers = array('From'=>'from_value','FromName'=>'FromName_value','Sender'=>'Sender_value')
  982. *
  983. * @param string $email
  984. * @param string $subject
  985. * @param string $text
  986. * @param boolean $is_html
  987. * @param array $headers
  988. * @return boolean
  989. */
  990. function ss_mail($email, $subject, $text, $is_html = true,$headers = array()){
  991.  
  992. //$mailer = new PHPMailer();
  993. $mailer = new SSMailer();
  994. if(isset($headers['From']))
  995. $mailer->From = $headers['From'];
  996. else
  997. $mailer->From = CONF_GENERAL_EMAIL;
  998. if(isset($headers['Sender']))
  999. $mailer->Sender = $headers['Sender'];
  1000. else
  1001. $mailer->Sender = CONF_GENERAL_EMAIL;
  1002. if(isset($headers['FromName']))
  1003. $mailer->FromName = $headers['FromName'];
  1004. else
  1005. $mailer->FromName = CONF_SHOP_NAME;
  1006. $emails = explode(',',$email);
  1007. foreach($emails as $email){
  1008. $mailer->AddAddress($email);
  1009. }
  1010. $mailer->Subject = $subject;
  1011. $mailer->Body = $text;
  1012.  
  1013. $mailer->CharSet = 'utf-8';
  1014. $mailer->IsHTML($is_html === true || $is_html === 2);
  1015. if($is_html === true){
  1016.  
  1017. $mailer->AltBody = str_replace("\n", "\r\n", str_replace("\r", '', strip_tags($text)));
  1018. }
  1019.  
  1020. return $mailer->Send();
  1021. }
  1022.  
  1023. /**
  1024. * @param string $string
  1025. * @param bool $in_false_source - if true and translation not found, return original constant
  1026. * @return unknown
  1027. */
  1028. function translate($string, $in_false_constant = true){
  1029.  
  1030. /**
  1031. * Old language localization
  1032. */
  1033. //if(defined($string))return constant($string);
  1034.  
  1035. $Register = &Register::getInstance();
  1036. $currlang_locals = &$Register->get('CURRLANG_LOCALS');
  1037. if(isset($currlang_locals[$string])&&$currlang_locals[$string])return $currlang_locals[$string];
  1038. $deflang_locals = &$Register->get('DEFLANG_LOCALS');
  1039. if(isset($deflang_locals[$string])&&$deflang_locals[$string])return $deflang_locals[$string];
  1040.  
  1041.  
  1042. //DEBUG:
  1043. if(false&&($fp = fopen(DIR_TEMP.'/missed_locals.log','a'))){
  1044. $backtrace = debug_backtrace();
  1045. $backtrace = $backtrace[0];
  1046. $file = str_replace(WBS_DIR,'',str_replace('\\','/',$backtrace['file']));
  1047. fwrite($fp,"{$string}\t{$file}\t{$backtrace['line']}\n");
  1048. fclose($fp);
  1049. }
  1050.  
  1051. return $in_false_constant?$string:'';
  1052. }
  1053.  
  1054. /**
  1055. * Check safe mode and redirect to some page with message about safe mode
  1056. *
  1057. * @param bool $check - check safe mode
  1058. * @param string $query - query for http redirect
  1059. * @return false|null
  1060. */
  1061. function safeMode($check, $query = ''){
  1062.  
  1063. if(!$check || !CONF_BACKEND_SAFEMODE)return false;
  1064.  
  1065. Message::raiseMessageRedirectSQ(MSG_ERROR, $query, translate("msg_safemode_warning"));
  1066. }
  1067.  
  1068. function pear_dump($data, $comment = ''){
  1069.  
  1070. ob_start();
  1071. print '<pre>';
  1072. print_r($data);
  1073. print '</pre>';
  1074. PEAR::raiseError($comment.' - '.ob_get_contents());
  1075. ob_end_clean();
  1076. }
  1077.  
  1078. function is_image($file){
  1079.  
  1080. if(!preg_match('/\.(jpg|jpeg|jpe|gif|pcx|bmp|png)$/i', $file, $r))return false;
  1081.  
  1082. return $r[1];
  1083. }
  1084.  
  1085. function checkPath($_path, $dont_check_path = ''){
  1086.  
  1087. if(file_exists($_path))return true;
  1088. $dont_check_path = realpath($dont_check_path);
  1089.  
  1090. $_path = str_replace('\\','/',$_path);
  1091. $explFolders=explode('/',$_path);
  1092. $fldNum=count($explFolders);
  1093. for($wer=0;$wer<$fldNum;$wer++){
  1094.  
  1095. $tPath='';
  1096. for($qwe=0;$qwe<=$wer;$qwe++)$tPath.=$explFolders[$qwe].'/';
  1097.  
  1098. if($dont_check_path && strpos($dont_check_path, $tPath) === 0 )continue;
  1099. if(!file_exists($tPath) && $tPath){
  1100. mkdir($tPath);
  1101. }
  1102. }
  1103. return true;
  1104. }
  1105.  
  1106. function copy_dir( $src, $dest ){
  1107.  
  1108. static $max;
  1109. if(!isset($max))$max=0;
  1110. $max++;
  1111. if($max>25)return false;
  1112.  
  1113. checkPath($dest);
  1114.  
  1115. $handle = opendir($src);
  1116. $C = 0;
  1117. while ( false !== ($file = readdir($handle)) && $C++<100) {
  1118.  
  1119. if( $file == '.' || $file=='..')continue;
  1120.  
  1121. if(is_dir($src.'/'.$file)){
  1122. copy_dir($src.'/'.$file, $dest.'/'.$file);
  1123. }else{
  1124. copy($src.'/'.$file, $dest.'/'.$file);
  1125. }
  1126. }
  1127.  
  1128. if($C>=100){
  1129. print "$src, $dest<br>";
  1130. }
  1131. @closedir( $handle );
  1132. }
  1133.  
  1134. function delete_file($path){
  1135.  
  1136. if(is_file($path)){
  1137. unlink($path);
  1138. }else{
  1139.  
  1140. if ( !($handle = @opendir($path)) )
  1141. return;
  1142.  
  1143. while ( false !== ($file = readdir($handle)) ) {
  1144.  
  1145. if ( $file == "." || $file == ".." ) continue;
  1146.  
  1147. if(is_file($path.'/'.$file)){
  1148.  
  1149. unlink($path.'/'.$file);
  1150. }else{
  1151.  
  1152. delete_file($path.'/'.$file);
  1153. }
  1154. }
  1155.  
  1156. @closedir( $handle );
  1157.  
  1158. rmdir($path);
  1159. }
  1160. }
  1161.  
  1162. function getMonthDays($time){
  1163.  
  1164.  
  1165. $time = strtotime(date('Y-m-15', $time));
  1166. return date('d', strtotime('-1 day', strtotime(date('Y-m-01', strtotime('+1 month', $time)))));
  1167. }
  1168.  
  1169. function getWeekdayName($n){
  1170.  
  1171. global $rWeekDays;
  1172.  
  1173. return isset($rWeekDays[$n])?$rWeekDays[$n]:'';
  1174. }
  1175.  
  1176. /**
  1177. * Transforms cyrillic symbols that string contains into latin with regard for transliteration
  1178. *
  1179. * @param string $str
  1180. * @return string
  1181. */
  1182. function translit($str){
  1183. //if($UTF8)
  1184. //$str = iconv("UTF-8", "WINDOWS-1251",$str);
  1185. $result = "";
  1186.  
  1187. $compliances = array("а"=>"a", "б"=>"b","в"=>"v", "г"=>"g", "д"=>"d", "е"=>"e", "ё"=>"yo","ж"=>"zh", "з"=>"z", "и"=>"i", "й"=>"j", "к"=>"k",
  1188. "л"=>"l", "м"=>"m", "н"=>"n","о"=>"o","п"=>"p", "р"=>"r", "с"=>"s", "т"=>"t", "у"=>"u", "ф"=>"f", "х"=>"h","ц"=>"c", "ч"=>"ch",
  1189. "ш"=>"sh", "щ"=>"sh", "ы"=>"y", "ь"=>"'", "ю"=>"ju", "я"=>"ja", "э"=>"e",
  1190.  
  1191. "А"=>"A", "Б"=>"B","В"=>"V", "Г"=>"G", "Д"=>"D", "Е"=>"E", "Ё"=>"Yo","Ж"=>"Zh", "З"=>"Z", "И"=>"I", "Й"=>"J", "К"=>"K",
  1192. "Л"=>"L", "М"=>"M", "Н"=>"N","О"=>"O","П"=>"P", "Р"=>"R", "С"=>"S", "Т"=>"T", "У"=>"U", "Ф"=>"F", "Х"=>"H","Ц"=>"C", "Ч"=>"Ch",
  1193. "Ш"=>"Sh", "Щ"=>"Sh", "Ы"=>"Y", "Ь"=>"'", "Ю"=>"Ju", "Я"=>"Ja", "Э"=>"E");
  1194. //Use ASCII Page codes
  1195. /*$compliances = array(184=>'yo',168=>'Yo',
  1196. 192=>"A","B","V","G","D","E","Zh","Z","I","J","K",
  1197. "L","M","N","O","P","R","S","T","U","F","H","C","Ch",
  1198. "Sh","Sh","","Y","'","E","Ju","Ja",
  1199. "a","b","v","g","d","e","zh","z","i","j","k",
  1200. "l","m","n","o","p","r","s","t","u","f","h","c","ch",
  1201. "sh","sh",'',"y","'","e","ju","ja");*/
  1202.  
  1203.  
  1204. $strlen = mb_strlen($str,'UTF-8');
  1205. for ($i = 0; $i < $strlen; $i++) {
  1206. $char = mb_substr($str,$i,1,'UTF-8');
  1207. //$symbol = ord($char);
  1208. //$symbol_ = (int)$char;
  1209. $result .= isset($compliances[$char])?$compliances[$char]:$char;
  1210.  
  1211. }
  1212.  
  1213. return $result;
  1214. }
  1215.  
  1216. function utf8_bad_replace($str, $replace = '?') {
  1217. $UTF8_BAD =
  1218. '([\x00-\x7F]'. # ASCII (including control chars)
  1219. '|[\xC2-\xDF][\x80-\xBF]'. # non-overlong 2-byte
  1220. '|\xE0[\xA0-\xBF][\x80-\xBF]'. # excluding overlongs
  1221. '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'. # straight 3-byte
  1222. '|\xED[\x80-\x9F][\x80-\xBF]'. # excluding surrogates
  1223. '|\xF0[\x90-\xBF][\x80-\xBF]{2}'. # planes 1-3
  1224. '|[\xF1-\xF3][\x80-\xBF]{3}'. # planes 4-15
  1225. '|\xF4[\x80-\x8F][\x80-\xBF]{2}'. # plane 16
  1226. '|(.{1}))'; # invalid byte
  1227. ob_start();
  1228. while (preg_match('/'.$UTF8_BAD.'/S', $str, $matches)) {
  1229. if ( !isset($matches[2])) {
  1230. echo $matches[0];
  1231. } else {
  1232. echo $replace;
  1233. }
  1234. $str = substr($str,strlen($matches[0]));
  1235. }
  1236. $result = ob_get_contents();
  1237. ob_end_clean();
  1238. return $result;
  1239. }
  1240.  
  1241. function make_slug($str){
  1242.  
  1243. $str = strtolower(translit($str));
  1244. $str = preg_replace('/ /ui', '-', $str);
  1245. $str = preg_replace('/[^a-z0-9\-\_]/ui', '', $str);
  1246. $str = preg_replace('/\-+/u', '-', $str);
  1247. $str = preg_replace('/\_+/u', '_', $str);
  1248. return $str == '-'?'':$str;
  1249. }
  1250.  
  1251. function encodeArray( $src_array, $excludes = null )
  1252. {
  1253. if ( is_null($excludes) )
  1254. $excludes = array();
  1255.  
  1256. $result = array();
  1257.  
  1258. foreach( $src_array as $key=>$value )
  1259. if ( !in_array( $key, $excludes ) )
  1260. $result[$key] = base64_encode( $value );
  1261. else
  1262. $result[$key] = $value;
  1263.  
  1264. return $result;
  1265. }
  1266.  
  1267. function decodeArray($src_array, $excludes = null){
  1268.  
  1269. if ( is_null($excludes) )
  1270. $excludes = array();
  1271.  
  1272. $result = array();
  1273.  
  1274. foreach( $src_array as $key=>$value )
  1275. if ( !in_array( $key, $excludes ) )
  1276. $result[$key] = base64_decode( $value );
  1277. else
  1278. $result[$key] = $value;
  1279.  
  1280. return $result;
  1281. }
  1282.  
  1283.  
  1284. function valid_email($email) {
  1285.  
  1286. // First, we check that there's one @ symbol, and that the lengths are right
  1287. if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
  1288. // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
  1289. return false;
  1290. }
  1291. // Split it into sections to make life easier
  1292. $email_array = explode("@", $email);
  1293. $local_array = explode(".", $email_array[0]);
  1294. for ($i = 0; $i < sizeof($local_array); $i++) {
  1295. if (!ereg("^(([A-Za-z0-9!#$%&#038;'*+/=?^_`{|}~-][A-Za-z0-9!#$%&#038;'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
  1296. return false;
  1297. }
  1298. }
  1299. if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
  1300. $domain_array = explode(".", $email_array[1]);
  1301. if (sizeof($domain_array) < 2) {
  1302. return false; // Not enough parts to domain
  1303. }
  1304. for ($i = 0; $i < sizeof($domain_array); $i++) {
  1305. if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
  1306. return false;
  1307. }
  1308. }
  1309. }
  1310. return true;
  1311. }
  1312.  
  1313. /**
  1314. * @param mixed $space - file size
  1315. * @param string $from_units - file size units (B,KB,MB,GB)
  1316. * @param string $to_units - display string units
  1317. * @return string
  1318. */
  1319. function getDisplayFileSize($space, $from_units, $to_units = null){
  1320.  
  1321. $allowed_units = array('B', 'KB', 'MB', 'GB');
  1322. $units_view = array('B' => 'bytes', 'KB' => 'Kb', 'MB' => 'Mb', 'GB' => 'Gb');
  1323. if(!in_array($from_units, $allowed_units))return $space;
  1324. if(!is_null($to_units) && !in_array($to_units, $allowed_units))return $space;
  1325.  
  1326. if(is_null($to_units)){
  1327.  
  1328. $begin_conversion = false;
  1329. $last_units = $from_units;
  1330. $last_space = $space;
  1331. foreach ($allowed_units as $curr_units){
  1332.  
  1333. if($begin_conversion){
  1334.  
  1335. $tspace = $last_space/1000;
  1336. if($tspace<1){
  1337. break;
  1338. }else{
  1339. $last_units = $curr_units;
  1340. $last_space = ceil($tspace*100)/100;
  1341. }
  1342. }elseif($curr_units == $from_units){
  1343.  
  1344. $begin_conversion = true;
  1345. }
  1346. }
  1347. return $last_space.' '.$units_view[$last_units];
  1348. }
  1349. }
  1350.  
  1351. function detectPDA(){
  1352. $container = $_SERVER['HTTP_USER_AGENT'];
  1353. $useragents = array (
  1354. 'iPhone','iPod',"Elaine/3.0","Palm","EudoraWeb","Blazer","AvantGo","Windows CE","Cellphone","Small","MMEF20","Danger","hiptop"
  1355. ,"Proxinet","ProxiNet","Newt","PalmOS","NetFront","SHARP-TQ-GX10","SonyEricsson","SymbianOS","UP.Browser"
  1356. ,"UP.Link","TS21i-10","BlackBerry","MOT-V",'portalmmm','Nokia','DoCoMo','Opera Mini'
  1357. ,"Palm" ,"Handspring","Nokia","Kyocera","Samsung","Motorola","Mot" ,"Smartphone","Blackberry"
  1358. ,"WAP","PlayStation Portable","LG","MMP","OPWV","Symbian","EPOC");
  1359. $pda = false;
  1360. foreach ( $useragents as $useragent ) {
  1361. if (!eregi($useragent,$container))continue;
  1362. $pda = true;
  1363. break;
  1364. }
  1365. return $pda;
  1366. }
  1367.  
  1368. function make_clean_slug($string,$prefix,$table,$slug_field,$id_field = '',$id = null){
  1369. $slug = make_slug($string);
  1370. $used_string = array();
  1371. $Register = &Register::getInstance();
  1372. $DBHandler = &$Register->get(VAR_DBHANDLER);
  1373. /* @var DBHandler DataBase*/
  1374. $query = "SELECT DISTINCT`{$slug_field}` as slug FROM {$table} WHERE `{$slug_field}` LIKE ?".($id?" AND NOT(`{$id_field}` LIKE ?)":'');
  1375. $DBHandler->ph_query($query,$prefix.$slug.'%',$id);
  1376. while($row = $DBHandler->fetch_assoc()){
  1377. $used_slug[]= $row['slug'];
  1378. }
  1379. $DBHandler->freeResult();
  1380.  
  1381. $max_i = 100;$_slug = $slug;
  1382. while(($max_i--)>0 && in_array($prefix.$_slug,$used_slug)){
  1383. $_slug = $slug.'_'.rand_name(3);
  1384. }
  1385.  
  1386. return $_slug;
  1387. }
  1388.  
  1389. function initCurlProxySettings(&$ch){
  1390. $options = getProxySettings();
  1391.  
  1392. if (isset($options['host'])&&strlen($options['host'])) {
  1393. curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
  1394. curl_setopt($ch, CURLOPT_PROXY, sprintf("%s%s",$options['host'],(isset($options['port'])&&$options['port']) ? ':'.$options['port'] :''));
  1395. // print(sprintf("%s%s",$options['host'],(isset($options['port'])&&($options['port'])) ? ':'.$options['port'] : '').'<br><hr>');
  1396.  
  1397. if (isset($options['user'])&&strlen($options['user'])) {
  1398. curl_setopt($ch, CURLOPT_PROXYUSERPWD,sprintf("%s:%s",$options['user'],$options['password']));
  1399. // print(sprintf("%s:%s",$options['user'],$options['password']).'<br><hr>');
  1400. }
  1401. }
  1402. }
  1403.  
  1404. function getProxySettings(){
  1405. $Register = &Register::getInstance();
  1406. /* @var $Register Register */
  1407. $options = $Register->get('PROXY');
  1408. if(is_null($options)){
  1409. $options = SystemSettings::get(array(
  1410. 'host'=>'PROXY_HOST','port'=>'PROXY_PORT',
  1411. 'user'=>'PROXY_USER','password'=>'PROXY_PASS'));
  1412. $Register->set('PROXY',$options);
  1413. }
  1414. return $options;
  1415. }
  1416.  
  1417. function error404page($debug = null){
  1418. global $error404;
  1419. $register = Register::getInstance();
  1420. $smarty = $register->get(VAR_SMARTY);
  1421. $error404 = true;
  1422. header("HTTP/1.1 404 Not Found;");
  1423. header("Status: 404 Not Found;");
  1424. $smarty->assign('link404',$_SERVER['REDIRECT_URL']);
  1425. $smarty->assign('page_not_found404',true);
  1426. }
  1427.  
  1428. ?>
Add Comment
Please, Sign In to add comment