PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/administrator/components/com_virtuemart/classes/ps_main.php

https://bitbucket.org/dgough/annamaria-daneswood-25102012
PHP | 1323 lines | 855 code | 125 blank | 343 comment | 204 complexity | ae4fbc6876355775956a2e5aaa4417ad MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
  3. /**
  4. * This is no class! This file only provides core virtuemart functions.
  5. *
  6. * @version $Id: ps_main.php 1483 2008-07-23 20:25:12Z soeren_nb $
  7. * @package VirtueMart
  8. * @subpackage classes
  9. * @copyright Copyright (C) 2004-2008 soeren - All rights reserved.
  10. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
  11. * VirtueMart is free software. This version may have been modified pursuant
  12. * to the GNU General Public License, and as distributed it includes or
  13. * is derivative of works licensed under the GNU General Public License or
  14. * other free or open source software licenses.
  15. * See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details.
  16. *
  17. * http://virtuemart.net
  18. */
  19. /**
  20. * This function validates a given date and creates a timestamp
  21. * @deprecated
  22. *
  23. * @param array $d
  24. * @param string $field The name of the field
  25. * @param string $type
  26. * @return boolean
  27. */
  28. function process_date_time(&$d,$field,$type="") {
  29. $month = $d["$field" . "_month"];
  30. $day = $d["$field" . "_day"];
  31. $year = $d["$field" . "_year"];
  32. $hour = $d["$field" . "_hour"];
  33. $minute = $d["$field" . "_minute"];
  34. $use = $d["$field" . "_use"];
  35. $valid = true;
  36. /* If user unchecked "Use date and time" then time = 0 */
  37. if (!$use) {
  38. $d[$field] = 0;
  39. return true;
  40. }
  41. if (!checkdate($month,$day,$year)) {
  42. $d["error"] .= "ERROR: $type date is invalid.";
  43. $valid = false;
  44. }
  45. if (!$hour and !$minute) {
  46. $hour = 0;
  47. $minute = 0;
  48. } elseif ($hour < 0 or $hour > 23 or $minute < 0 or $minute > 59) {
  49. $d["error"] .= "ERROR: $type time is invalid.";
  50. $valid = false;
  51. }
  52. if ($valid) {
  53. $d[$field] = mktime($hour,$minute,0,$month,$day,$year);
  54. }
  55. return $valid;
  56. }
  57. /**
  58. * Validates an email address by using regular expressions
  59. * Does not resolve the domain name!
  60. *
  61. * @param string $email
  62. * @return boolean The result of the validation
  63. */
  64. function vmValidateEmail( $email ) {
  65. $valid = preg_match( '/^[\w\.\-]+@\w+[\w\.\-]*?\.\w{1,4}$/', $email );
  66. return $valid;
  67. }
  68. /**
  69. * Checks if a given string is a valid (from-)name or subject for an email
  70. *
  71. * @since 1.0.7
  72. * @param string $string String to check for validity
  73. * @return boolean
  74. */
  75. function vmValidateName( $string ) {
  76. /*
  77. * The following regular expression blocks all strings containing any low control characters:
  78. * 0x00-0x1F, 0x7F
  79. * These should be control characters in almost all used charsets.
  80. * The high control chars in ISO-8859-n (0x80-0x9F) are unused (e.g. http://en.wikipedia.org/wiki/ISO_8859-1)
  81. * Since they are valid UTF-8 bytes (e.g. used as the second byte of a two byte char),
  82. * they must not be filtered.
  83. */
  84. $invalid = preg_match( '/[\x00-\x1F\x7F]/', $string );
  85. if ($invalid) {
  86. return false;
  87. } else {
  88. return true;
  89. }
  90. }
  91. /**
  92. * Validates an EU-vat number
  93. * @author Steve Endredy
  94. * @param string $euvat EU-vat number to validate
  95. * @return boolean The result of the validation
  96. */
  97. function vmValidateEUVat( $euvat ){
  98. require_once( CLASSPATH . 'nusoap/nusoap.php' );
  99. require_once( CLASSPATH . 'euvatcheck.class.php' );
  100. $GLOBALS['vmLogger']->debug( 'Checking for valid EU VAT ID' );
  101. $vatcheck = new VmEUVatCheck($euvat);
  102. return $vatcheck->validvatid;
  103. }
  104. /**
  105. * Returns the current time in microseconds
  106. *
  107. * @return float current time in microseconds
  108. */
  109. function utime()
  110. {
  111. list($usec, $sec) = explode(" ", microtime());
  112. return ((float)$usec + (float)$sec);
  113. }
  114. /**
  115. * Checks if $item is in $list
  116. *
  117. * @param array $list
  118. * @param string $item
  119. * @return mixed An integer representing the postion of $item in $list, false when not in list
  120. */
  121. function in_list($list, $item) {
  122. for ($i=0;$i<$list["cnt"];$i++) {
  123. if (!strcmp($list[$i]["name"],$item)) {
  124. return $i;
  125. }
  126. }
  127. return False;
  128. }
  129. /**
  130. * reads a file and returns its content as a string
  131. *
  132. * @param string $file The path to the file that shall be read
  133. * @param string $defaultfile The path to the file to is read when $file doesn't exist
  134. * @return string The file contents
  135. */
  136. function read_file( $file, $defaultfile='' ) {
  137. // open the HTML file and read it into $html
  138. if (file_exists( $file )) {
  139. $html_file = fopen( $file, "r" );
  140. }
  141. elseif( !empty( $defaultfile ) && file_exists( $defaultfile ) ) {
  142. $html_file = fopen( $defaultfile, "r" );
  143. }
  144. else {
  145. return;
  146. }
  147. if( $html_file === false ) {
  148. $GLOBALS['vmLogger']->err( 'Could not open '.basename( $file ).'.' );
  149. return;
  150. }
  151. $html = "";
  152. while (!feof($html_file)) {
  153. $buffer = fgets($html_file, 1024);
  154. $html .= $buffer;
  155. }
  156. fclose ($html_file);
  157. return( $html );
  158. }
  159. /**
  160. * Includes all needed classes for a core module and create + populate the objects
  161. *
  162. * @param string $module The name of the virtuemart core module
  163. */
  164. function include_class($module) {
  165. // globalize the vars so that they can be used outside of this function
  166. global $VM_LANG, $ps_vendor, $ps_affiliate, $ps_manufacturer, $ps_manufacturer_category,
  167. $ps_user, $ps_vendor_category, $ps_checkout, $ps_intershipper, $ps_shipping, $ps_order, $ps_order_status,
  168. $ps_product,$ps_product_category , $ps_product_attribute,
  169. $ps_product_type, // Changed Product Type
  170. $ps_product_type_parameter, // Changed Product Type
  171. $ps_product_product_type, // Changed Product Type
  172. $ps_product_price, $nh_report, $ps_payment_method, $ps_shopper, $ps_shopper_group,
  173. $ps_cart, $ps_zone,$ps_tax, $zw_waiting_list;
  174. $VM_LANG->load($module);
  175. switch ( $module ) {
  176. case "account":
  177. break;
  178. case "admin" :
  179. // Load class files
  180. require_once(CLASSPATH. 'ps_html.php' );
  181. require_once(CLASSPATH. 'ps_function.php' );
  182. require_once(CLASSPATH. 'ps_module.php' );
  183. require_once(CLASSPATH. 'ps_perm.php' );
  184. require_once(CLASSPATH. 'ps_user.php' );
  185. require_once(CLASSPATH. 'ps_user_address.php' );
  186. require_once(CLASSPATH. 'ps_session.php' );
  187. //Instantiate Classes
  188. $ps_html = new ps_html;
  189. $ps_function = new ps_function;
  190. $ps_module= new ps_module;
  191. $ps_perm= new ps_perm;
  192. $ps_user= new ps_user;
  193. $ps_user_address = new ps_user_address;
  194. $ps_session = new ps_session;
  195. break;
  196. case "affiliate" :
  197. // Load class file
  198. require_once(CLASSPATH. 'ps_affiliate.php' );
  199. //Instantiate Class
  200. $ps_affiliate = new ps_affiliate;
  201. break;
  202. case "checkout" :
  203. // Load class file
  204. require_once(CLASSPATH. 'ps_checkout.php' );
  205. //Instantiate Class
  206. //$ps_checkout = new ps_checkout;
  207. break;
  208. case "order" :
  209. // Load classes
  210. require_once(CLASSPATH.'ps_order.php' );
  211. require_once(CLASSPATH.'ps_order_status.php' );
  212. // Instantiate Classes
  213. $ps_order = new ps_order;
  214. $ps_order_status = new ps_order_status;
  215. break;
  216. case "product" :
  217. // Load Classes
  218. require_once(CLASSPATH.'ps_product.php' );
  219. require_once(CLASSPATH.'ps_product_category.php' );
  220. require_once(CLASSPATH.'ps_product_attribute.php' );
  221. require_once(CLASSPATH.'ps_product_type.php' ); // Changed Product Type
  222. require_once(CLASSPATH.'ps_product_type_parameter.php' ); // Changed Product Type
  223. require_once(CLASSPATH.'ps_product_product_type.php' ); // Changed Product Type
  224. require_once(CLASSPATH.'ps_product_price.php' );
  225. // Instantiate Classes
  226. $ps_product = new ps_product;
  227. $ps_product_category = new ps_product_category;
  228. $ps_product_attribute = new ps_product_attribute;
  229. $ps_product_type = new ps_product_type; // Changed Product Type
  230. $ps_product_type_parameter = new ps_product_type_parameter; // Changed Product Type
  231. $ps_product_product_type = new ps_product_product_type; // Changed Product Type
  232. $ps_product_price = new ps_product_price;
  233. break;
  234. case "reportbasic" :
  235. // Load Classes
  236. require_once( CLASSPATH . 'ps_reportbasic.php');
  237. $nh_report = new nh_report;
  238. break;
  239. case "shipping" :
  240. // Load Class
  241. require_once( CLASSPATH . 'ps_shipping.php');
  242. // Instantiate Class
  243. $ps_shipping = new ps_shipping;
  244. break;
  245. case "shop" :
  246. // Load Classes
  247. require_once( CLASSPATH. 'ps_cart.php' );
  248. require_once( CLASSPATH. 'zw_waiting_list.php');
  249. // Instantiate Classes
  250. $ps_cart = new ps_cart;
  251. $zw_waiting_list = new zw_waiting_list;
  252. break;
  253. case "shopper" :
  254. // Load Classes
  255. require_once( CLASSPATH . 'ps_shopper.php' );
  256. require_once( CLASSPATH . 'ps_shopper_group.php' );
  257. // Instantiate Classes
  258. $ps_shopper = new ps_shopper;
  259. $ps_shopper_group = new ps_shopper_group;
  260. break;
  261. case "store" :
  262. // Load Classes
  263. require_once( CLASSPATH . 'ps_payment_method.php' );
  264. // Instantiate Classes
  265. $ps_payment_method = new ps_payment_method;
  266. break;
  267. case "tax" :
  268. // Load Classes
  269. require_once ( CLASSPATH . 'ps_tax.php' );
  270. // Instantiate Classes
  271. $ps_tax = new ps_tax;
  272. break;
  273. case "vendor" :
  274. // Load Classes
  275. require_once (CLASSPATH . 'ps_vendor.php' );
  276. require_once (CLASSPATH . 'ps_vendor_category.php' );
  277. // Instantiate Classes
  278. $ps_vendor = new ps_vendor;
  279. $ps_vendor_category = new ps_vendor_category;
  280. break;
  281. case "zone" :
  282. // Load Class
  283. require_once (CLASSPATH . 'ps_zone.php');
  284. // Instantiate Class
  285. $ps_zone = new ps_zone;
  286. break;
  287. case "manufacturer" :
  288. require_once (CLASSPATH . 'ps_manufacturer.php');
  289. require_once (CLASSPATH . 'ps_manufacturer_category.php');
  290. $ps_manufacturer = new ps_manufacturer;
  291. $ps_manufacturer_category = new ps_manufacturer_category;
  292. break;
  293. }
  294. }
  295. /**
  296. * Login validation function
  297. *
  298. * Username and encoded password is compared to db entries in the mos_users
  299. * table. A successful validation returns true, otherwise false
  300. */
  301. function vmCheckPass() {
  302. global $database, $perm, $my, $mainframe;
  303. // only allow access to admins or storeadmins
  304. if( $perm->check("admin,storeadmin")) {
  305. $username = $my->username;
  306. $passwd_plain = $passwd = trim( vmGet( $_POST, 'passwd', '' ) );
  307. if( empty( $passwd_plain )) {
  308. $GLOBALS['vmLogger']->err( 'Password empty!');
  309. return false;
  310. }
  311. $passwd = md5( $passwd );
  312. $bypost = 1;
  313. if (!$username || !$passwd || $_REQUEST['option'] != "com_virtuemart") {
  314. return false;
  315. } elseif( vmIsJoomla('1.5') ) {
  316. $credentials = array();
  317. $credentials['username'] = $username;
  318. $credentials['password'] = $passwd_plain;
  319. $options = array();
  320. jimport( 'joomla.user.authentication');
  321. $authenticate = & JAuthentication::getInstance();
  322. $response = $authenticate->authenticate($credentials, $options);
  323. if ($response->status === JAUTHENTICATE_STATUS_SUCCESS) {
  324. return true;
  325. } else {
  326. return false;
  327. }
  328. } else {
  329. if( vmIsJoomla('1.0.12', '<=', false )) {
  330. $database->setQuery( "SELECT id, gid, block, usertype"
  331. . "\nFROM #__users"
  332. . "\nWHERE username='$username' AND password='$passwd'"
  333. );
  334. $row = null;
  335. $res = $database->loadObject( $row );
  336. } else {
  337. $query = "SELECT id, name, username, password, usertype, block, gid"
  338. . "\n FROM #__users"
  339. . "\n WHERE username = ". $database->Quote( $username );
  340. $database->setQuery( $query );
  341. $row = null;
  342. $database->loadObject( $row );
  343. list($hash, $salt) = explode(':', $row->password);
  344. $cryptpass = md5($passwd_plain.$salt);
  345. $res = $hash == $cryptpass;
  346. }
  347. if ($res) {
  348. return true;
  349. }
  350. else {
  351. $GLOBALS['vmLogger']->err( 'The Password you\'ve entered is not correct for your User Account');
  352. return false;
  353. }
  354. }
  355. }
  356. return false;
  357. }
  358. /**
  359. * Formerly used to print a search header for lists
  360. * use class listFactory instead
  361. * @deprecated
  362. *
  363. */
  364. function search_header() {
  365. echo "### THIS FUNCTION IS DEPRECATED. Use the class listFactory instead. ###";
  366. }
  367. /**
  368. * Formerly used to print a search header for lists
  369. * use class listFactory instead
  370. * @deprecated
  371. *
  372. */
  373. function search_footer() {
  374. echo "### THIS FUNCTION IS DEPRECATED. Use the class listFactory instead. ###";
  375. }
  376. /**
  377. * Used by the frontend adminsitration to save editor field contents
  378. *
  379. * @param string $editor1 the name of the editor field no. 1
  380. * @param string $editor2 the name of the editor field no. 2
  381. */
  382. function editorScript($editor1='', $editor2='') {
  383. ?>
  384. <script type="text/javascript">
  385. function submitbutton(pressbutton) {
  386. var form = document.adminForm;
  387. if (pressbutton == 'cancel') {
  388. submitform( pressbutton );
  389. return;
  390. }
  391. <?php
  392. if ($editor1 != '') {
  393. if( vmIsJoomla(1.5) ) {
  394. jimport('joomla.html.editor');
  395. $editor = JEditor::getInstance($GLOBALS['mainframe']->getCfg('editor'));
  396. echo $editor->getContent('editor1');
  397. } else {
  398. getEditorContents( 'editor1', $editor1 );
  399. }
  400. }
  401. if ($editor2 != '') {
  402. if( vmIsJoomla(1.5) ) {
  403. jimport('joomla.html.editor');
  404. $editor = JEditor::getInstance($GLOBALS['mainframe']->getCfg('editor'));
  405. echo $editor->getContent('editor2');
  406. } else {
  407. getEditorContents( 'editor2', $editor2 );
  408. }
  409. } ?>
  410. submitform( pressbutton );
  411. }
  412. </script><?php
  413. }
  414. /**
  415. * Function to create an email object for further use (uses phpMailer)
  416. * @param string From e-mail address
  417. * @param string From name
  418. * @param string E-mail subject
  419. * @param string Message body
  420. * @return phpMailer Mail object
  421. */
  422. function vmCreateMail( $from='', $fromname='', $subject='', $body='' ) {
  423. global $mosConfig_absolute_path, $mosConfig_sendmail;
  424. global $mosConfig_smtpauth, $mosConfig_smtpuser;
  425. global $mosConfig_smtppass, $mosConfig_smtphost;
  426. global $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_mailer;
  427. $phpmailer_classname='phpmailer';
  428. if( file_exists( $mosConfig_absolute_path . '/libraries/phpmailer/phpmailer.php') ) {
  429. $phpmailer_path = $mosConfig_absolute_path . '/libraries/phpmailer/phpmailer.php';
  430. }elseif( file_exists( $mosConfig_absolute_path . '/includes/phpmailer/class.phpmailer.php')) {
  431. $phpmailer_path = $mosConfig_absolute_path . '/includes/phpmailer/class.phpmailer.php';
  432. $phpmailer_classname = 'mosphpmailer';
  433. }
  434. require_once( $phpmailer_path );
  435. if( class_exists( $phpmailer_classname )) {
  436. $mail = new $phpmailer_classname();
  437. }
  438. $phpmailer_path = dirname( $phpmailer_path );
  439. $mail->PluginDir = $phpmailer_path .'/';
  440. $mail->SetLanguage( 'en', $phpmailer_path . '/language/' );
  441. $mail->CharSet = vmGetCharset();
  442. $mail->IsMail();
  443. $mail->From = $from ? $from : $mosConfig_mailfrom;
  444. $mail->FromName = $fromname ? $fromname : $mosConfig_fromname;
  445. $mail->Sender = $from ? $from : $mosConfig_mailfrom;
  446. $mail->Mailer = $mosConfig_mailer;
  447. // Add smtp values if needed
  448. if ( $mosConfig_mailer == 'smtp' ) {
  449. $mail->SMTPAuth = $mosConfig_smtpauth;
  450. $mail->Username = $mosConfig_smtpuser;
  451. $mail->Password = $mosConfig_smtppass;
  452. $mail->Host = $mosConfig_smtphost;
  453. } else
  454. // Set sendmail path
  455. if ( $mosConfig_mailer == 'sendmail' ) {
  456. if (isset($mosConfig_sendmail))
  457. $mail->Sendmail = $mosConfig_sendmail;
  458. } // if
  459. if( $subject ) {
  460. $mail->Subject = vmAbstractLanguage::safe_utf8_encode( $subject, $mail->CharSet );
  461. }
  462. if( $body) {
  463. $mail->Body = $body;
  464. }
  465. // Patch to get correct Line Endings
  466. switch( substr( strtoupper( PHP_OS ), 0, 3 ) ) {
  467. case "WIN":
  468. $mail->LE = "\r\n";
  469. break;
  470. case "MAC": // fallthrough
  471. case "DAR": // Does PHP_OS return 'Macintosh' or 'Darwin' ?
  472. $mail->LE = "\r";
  473. default: // change nothing
  474. break;
  475. }
  476. return $mail;
  477. }
  478. /**
  479. * Mail function (uses phpMailer)
  480. * @param string From e-mail address
  481. * @param string From name
  482. * @param string/array Recipient e-mail address(es)
  483. * @param string E-mail subject
  484. * @param string Message body
  485. * @param boolean false = plain text, true = HTML
  486. * @param string/array CC e-mail address(es)
  487. * @param string/array BCC e-mail address(es)
  488. * @param array Images path,cid,name,filename,encoding,mimetype
  489. * @param string/array Attachment file name(s)
  490. * @return boolean Mail send success
  491. */
  492. function vmMail($from, $fromname, $recipient, $subject, $body, $Altbody='', $mode=false, $cc=NULL, $bcc=NULL, $images=null, $attachment=null ) {
  493. global $mosConfig_debug;
  494. // Filter from, fromname and subject
  495. if (!vmValidateEmail( $from ) || !vmValidateName( $fromname ) || !vmValidateName( $subject )) {
  496. return false;
  497. }
  498. $mail = vmCreateMail( $from, $fromname, $subject, $body );
  499. if( $Altbody != "" ) {
  500. // In this section we take care for utf-8 encoded mails
  501. $mail->AltBody = vmAbstractLanguage::safe_utf8_encode( $Altbody, $mail->CharSet );
  502. }
  503. // activate HTML formatted emails
  504. if ( $mode ) {
  505. $mail->IsHTML(true);
  506. }
  507. if( $mail->ContentType == "text/plain" ) {
  508. $mail->Body = vmAbstractLanguage::safe_utf8_encode( $mail->Body, $mail->CharSet );
  509. }
  510. if( is_array($recipient) ) {
  511. foreach ($recipient as $to) {
  512. if( vmValidateEmail( $to )) {
  513. $mail->AddAddress($to);
  514. }
  515. }
  516. } else {
  517. if( vmValidateEmail( $recipient )) {
  518. $mail->AddAddress($recipient);
  519. }
  520. }
  521. if (isset($cc)) {
  522. if( is_array($cc) )
  523. foreach ($cc as $to) {
  524. if( vmValidateEmail( $to )) {
  525. $mail->AddCC($to);
  526. }
  527. }
  528. else {
  529. if( vmValidateEmail( $cc )) {
  530. $mail->AddCC($cc);
  531. }
  532. }
  533. }
  534. if (isset($bcc)) {
  535. if( is_array($bcc) )
  536. foreach ($bcc as $to) {
  537. if( vmValidateEmail( $to )) {
  538. $mail->AddBCC($to);
  539. }
  540. }
  541. else {
  542. if( vmValidateEmail( $bcc )) {
  543. $mail->AddBCC($bcc);
  544. }
  545. }
  546. }
  547. if( $images ) {
  548. foreach( $images as $image) {
  549. $mail->AddEmbeddedImage( $image['path'], $image['name'], $image['filename'], $image['encoding'], $image['mimetype']);
  550. }
  551. }
  552. if ($attachment) {
  553. if ( is_array($attachment) )
  554. foreach ($attachment as $fname) $mail->AddAttachment($fname);
  555. else
  556. $mail->AddAttachment($attachment);
  557. }
  558. $mailssend = $mail->Send();
  559. if( $mosConfig_debug ) {
  560. //$mosDebug->message( "Mails send: $mailssend");
  561. }
  562. if( $mail->error_count > 0 ) {
  563. //$mosDebug->message( "The mail message $fromname <$from> about $subject to $recipient <b>failed</b><br /><pre>$body</pre>", false );
  564. //$mosDebug->message( "Mailer Error: " . $mail->ErrorInfo . "" );
  565. }
  566. return $mailssend;
  567. }
  568. // $ Id: html_entity_decode.php,v 1.7 2005/01/26 04:55:13 aidan Exp $
  569. if (!defined('ENT_NOQUOTES')) {
  570. define('ENT_NOQUOTES', 0);
  571. }
  572. if (!defined('ENT_COMPAT')) {
  573. define('ENT_COMPAT', 2);
  574. }
  575. if (!defined('ENT_QUOTES')) {
  576. define('ENT_QUOTES', 3);
  577. }
  578. /**
  579. * Replace html_entity_decode()
  580. *
  581. * @category PHP
  582. * @package PHP_Compat
  583. * @link http://php.net/function.html_entity_decode
  584. * @author David Irvine <dave@codexweb.co.za>
  585. * @author Aidan Lister <aidan@php.net>
  586. * @since PHP 4.3.0
  587. * @internal Setting the charset will not do anything
  588. * @require PHP 4.0.0 (user_error)
  589. */
  590. function vmHtmlEntityDecode($string, $quote_style = ENT_COMPAT, $charset = null) {
  591. if( function_exists('html_entity_decode')) {
  592. return @html_entity_decode( $string, $quote_style, $charset );
  593. }
  594. if (!is_int($quote_style) && !is_null($quote_style)) {
  595. user_error(__FUNCTION__.'() expects parameter 2 to be long, ' .
  596. gettype($quote_style) . ' given', E_USER_WARNING);
  597. return;
  598. }
  599. $trans_tbl = get_html_translation_table(HTML_ENTITIES);
  600. $trans_tbl = array_flip($trans_tbl);
  601. // Add single quote to translation table;
  602. $trans_tbl['&#039;'] = '\'';
  603. // Not translating double quotes
  604. if ($quote_style & ENT_NOQUOTES) {
  605. // Remove double quote from translation table
  606. unset($trans_tbl['&quot;']);
  607. }
  608. return strtr($string, $trans_tbl);
  609. }
  610. /**
  611. * Unescapes REQUEST values if magic_quotes_gpc is set
  612. *
  613. * @param string $string The string to strip slashes from
  614. * @return string
  615. * @since 1.1.0
  616. */
  617. function vmGetUnEscaped( $string ) {
  618. if (get_magic_quotes_gpc()==1) {
  619. // if (ini_get('magic_quotes_sybase')) return str_replace("''","'",$string);
  620. return ( stripslashes( $string )); // this does not handle it correctly if magic_quotes_sybase is ON.
  621. } else {
  622. return ( $string );
  623. }
  624. }
  625. /**
  626. * Reads a file and sends them in chunks to the browser
  627. * This should overcome memory problems
  628. * http://www.php.net/manual/en/function.readfile.php#54295
  629. *
  630. * @since 1.0.3
  631. * @param string $filename
  632. * @param boolean $retbytes
  633. * @return mixed
  634. */
  635. function vmReadFileChunked($filename,$retbytes=true) {
  636. $chunksize = 1*(1024*1024); // how many bytes per chunk
  637. $buffer = '';
  638. $cnt =0;
  639. // $handle = fopen($filename, 'rb');
  640. $handle = fopen($filename, 'rb');
  641. if ($handle === false) {
  642. return false;
  643. }
  644. // Prevent time outs on big files
  645. @set_time_limit(0);
  646. // PHP on Windows has a useless "usleep" function until 5.0.0
  647. if( substr( strtoupper( PHP_OS ), 0, 3 ) == 'WIN' && version_compare( phpversion(), '5.0' ) < 0 ) {
  648. $sleepfunc = 'sleep';
  649. $time = 1; // sec.
  650. } else {
  651. $sleepfunc = 'usleep';
  652. $time = 100; // msec.
  653. }
  654. while (!feof($handle)) {
  655. $buffer = fread($handle, $chunksize);
  656. echo $buffer;
  657. $sleepfunc($time);
  658. @ob_flush();
  659. flush();
  660. if ($retbytes) {
  661. $cnt += strlen($buffer);
  662. }
  663. }
  664. $status = fclose($handle);
  665. if ($retbytes && $status) {
  666. return $cnt; // return num. bytes delivered like readfile() does.
  667. }
  668. return $status;
  669. }
  670. /**
  671. * Returns the charset string from the global _ISO constant
  672. *
  673. * @return string UTF-8 by default
  674. * @since 1.0.5
  675. */
  676. function vmGetCharset() {
  677. $iso = explode( '=', @constant('_ISO') );
  678. if( !empty( $iso[1] )) {
  679. return $iso[1];
  680. }
  681. else {
  682. return 'UTF-8';
  683. }
  684. }
  685. /**
  686. * Create a file system - safe file name
  687. *
  688. * @param string $filename
  689. * @since 1.1.0
  690. */
  691. function vmSafeFileName( $filename ) {
  692. $filename = preg_replace('/[^a-zA-Z0-9\.]/', '_', $filename );
  693. return $filename;
  694. }
  695. function vmIsAdminMode() {
  696. global $page;
  697. return ( (defined( '_VM_IS_BACKEND' )
  698. || @$_REQUEST['pshop_mode'] == 'admin'
  699. || strstr($page,'_list')
  700. || strstr($page,'_form'))
  701. && ( strncmp('account.',$page, 8) !== 0
  702. && strncmp('checkout.',$page, 9) !== 0
  703. && strncmp('shop.',$page, 5) !== 0
  704. )
  705. );
  706. }
  707. function vmCreateHash( $seed='virtuemart' ) {
  708. return md5( ENCODE_KEY . md5( $seed ) );
  709. }
  710. /**
  711. * Generate a random password
  712. *
  713. * @static
  714. * @param int $length Length of the password to generate
  715. * @return string Random Password
  716. * @since 1.1
  717. */
  718. function vmGenRandomPassword($length = 8)
  719. {
  720. $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  721. $len = strlen($salt);
  722. $makepass = '';
  723. mt_srand(10000000 * (double) microtime());
  724. for ($i = 0; $i < $length; $i ++) {
  725. $makepass .= $salt[mt_rand(0, $len -1)];
  726. }
  727. return $makepass;
  728. }
  729. /**
  730. * Equivalent to Joomla's josSpoofCheck function
  731. * @author Joomla core team
  732. *
  733. * @param boolean $header
  734. * @param unknown_type $alt
  735. */
  736. function vmSpoofCheck( $header=NULL, $alt=NULL ) {
  737. global $vm_mainframe;
  738. if( !empty( $_GET['vmtoken']) || !empty( $_POST['vmtoken'])) {
  739. $validate_hash = vmGet( $_REQUEST, 'vmtoken', null );
  740. $validate = vmSpoofValue($alt) == $validate_hash;
  741. } else {
  742. $validate = vmGet( $_REQUEST, vmSpoofValue($alt), 0 );
  743. }
  744. // probably a spoofing attack
  745. if (!$validate) {
  746. header( 'HTTP/1.0 403 Forbidden' );
  747. $vm_mainframe->errorAlert( 'Sorry, but we could not verify your Security Token.\nGo back and try again please.' );
  748. return false;
  749. }
  750. // First, make sure the form was posted from a browser.
  751. // For basic web-forms, we don't care about anything
  752. // other than requests from a browser:
  753. if (!isset( $_SERVER['HTTP_USER_AGENT'] )) {
  754. header( 'HTTP/1.0 403 Forbidden' );
  755. $vm_mainframe->errorAlert( 'Sorry, but we could not identify your web browser.\nBut this is necessary for using this web page.' );
  756. return false;
  757. }
  758. /* //NOTE: this is not really necessary, because GET request should also be allowed.
  759. // Make sure the request was done using "POST"
  760. if (!$_SERVER['REQUEST_METHOD'] == 'POST' ) {
  761. header( 'HTTP/1.0 403 Forbidden' );
  762. $vm_mainframe->errorAlert( $VM_LANG->_('NOT_AUTH') );
  763. return false;
  764. }
  765. */
  766. if ($header) {
  767. // Attempt to defend against header injections:
  768. $badStrings = array(
  769. 'Content-Type:',
  770. 'MIME-Version:',
  771. 'Content-Transfer-Encoding:',
  772. 'bcc:',
  773. 'cc:'
  774. );
  775. // Loop through each POST'ed value and test if it contains
  776. // one of the $badStrings:
  777. foreach ($_POST as $k => $v){
  778. foreach ($badStrings as $v2) {
  779. if (strpos( $v, $v2 ) !== false) {
  780. header( "HTTP/1.0 403 Forbidden" );
  781. $vm_mainframe->errorAlert( 'We are sorry, but using E-Mail Headers in Fields is not allowed.' );
  782. return false;
  783. }
  784. }
  785. }
  786. // Made it past spammer test, free up some memory
  787. // and continue rest of script:
  788. unset($k, $v, $v2, $badStrings);
  789. }
  790. return true;
  791. }
  792. /**
  793. * Equivalent to Joomla's josSpoofValue function
  794. *
  795. * @param boolean $alt
  796. * @return string Validation Hash
  797. */
  798. function vmSpoofValue($alt=NULL) {
  799. global $auth, $mainframe, $_VERSION;
  800. if ($alt) {
  801. if ( $alt == 1 ) {
  802. $random = date( 'Ymd' );
  803. } else {
  804. $random = $alt . date( 'Ymd' );
  805. }
  806. } else {
  807. $random = date( 'dmY' );
  808. }
  809. $validate = vmCreateHash( $mainframe->getCfg( 'db' ) . $random . $auth['user_id']);
  810. if( $_VERSION->DEV_LEVEL >= 11 ) {
  811. // Joomla 1.0.11 compatibility workaround
  812. // the prefix ensures that the hash is non-numeric
  813. // otherwise it will be intercepted by globals.php
  814. $validate = 'j' . $validate;
  815. }
  816. return $validate;
  817. }
  818. /**
  819. * This function creates the superglobal variable $product_currency
  820. * This variable is used for currency conversion
  821. *
  822. */
  823. function vmSetGlobalCurrency(){
  824. global $vendor_accepted_currencies, $vendor_currency, $vmLogger;
  825. if( !defined('_VM_IS_BACKEND') && empty( $_REQUEST['ajax_request']) && empty($_REQUEST['pshop_mode'])) {
  826. if( isset( $_REQUEST['product_currency']) ) {
  827. $GLOBALS['product_currency'] = $_SESSION['product_currency'] = vmGet($_REQUEST, 'product_currency' );
  828. }
  829. }
  830. $GLOBALS['product_currency'] = vmGet($_SESSION, 'product_currency', $vendor_currency);
  831. // Check if the selected currency is accepted! (the vendor currency is always accepted)
  832. if( $GLOBALS['product_currency'] != $vendor_currency ) {
  833. if( empty( $vendor_accepted_currencies )) {
  834. $vendor_accepted_currencies = $vendor_currency;
  835. }
  836. $page = vmGet($_REQUEST,'page');
  837. $acceptedCurrencies = explode(',', $vendor_accepted_currencies );
  838. if( !in_array( $GLOBALS['product_currency'], $acceptedCurrencies)
  839. && (stristr( $page, 'checkout.') || stristr( $page, 'account.') || stristr( $page, 'shop.cart')) ) {
  840. // Fallback to global vendor currency (as set in the store form)
  841. $vmLogger->warning( 'The Currency you had selected ('.$GLOBALS['product_currency'].') is not accepted for Checkout.');
  842. $GLOBALS['product_currency'] = $vendor_currency;
  843. }
  844. }
  845. }
  846. function vmIsJoomla( $version='', $operator='=', $compare_minor_versions=true) {
  847. global $_VERSION;
  848. $this_version = '';
  849. if( !empty($_VERSION) && is_object($_VERSION)) {
  850. $jversion =& $_VERSION;
  851. $this_version = $jversion->RELEASE;
  852. }
  853. elseif ( defined('JVERSION')) {
  854. $jversion = new JVersion();
  855. $this_version = $jversion->RELEASE;
  856. } else {
  857. include_once( $GLOBALS['mosConfig_absolute_path'].'/includes/version.php' );
  858. $jversion =& $_VERSION;
  859. $this_version = $jversion->RELEASE;
  860. }
  861. if( !$compare_minor_versions ) $this_version .= '.'. $jversion->DEV_LEVEL;
  862. if( empty( $version ) ) {
  863. return !empty($this_version) && strtolower($jversion->PRODUCT) == 'joomla!';
  864. }
  865. $allowed_operators = array( '<', 'lt', '<=', 'le', '>', 'gt', '>=', 'ge', '==', '=', 'eq', '!=', '<>', 'ne' );
  866. if( $compare_minor_versions ) {
  867. if( $jversion->RELEASE != $version ) {
  868. return false;
  869. }
  870. }
  871. if( in_array($operator, $allowed_operators )) {
  872. return version_compare( $this_version, $version, $operator );
  873. }
  874. return false;
  875. }
  876. function vmIsHttpsMode() {
  877. return ($_SERVER['SERVER_PORT'] == 443 || @$_SERVER['HTTPS'] == 'on');
  878. }
  879. /**
  880. * Checks if the Request is a XML HTTP Request (via Ajax)
  881. * @since 1.1.1
  882. * @return boolean
  883. */
  884. function vmIsXHR() {
  885. return strtolower(vmGet($_SERVER,'HTTP_X_REQUESTED_WITH')) == 'xmlhttprequest'
  886. || vmGet($_POST,'ajax_request') == '1';
  887. }
  888. /**
  889. * Utility function redirect the browser location to another url
  890. *
  891. * Can optionally provide a message.
  892. * @param string The URL to redirect to
  893. * @param string A Message to display to the user
  894. */
  895. function vmRedirect( $url, $msg='' ) {
  896. if( function_exists('mosRedirect')) {
  897. mosRedirect($url, $msg );
  898. } elseif( vmIsJoomla( '1.5', '>=' ) ) {
  899. global $mainframe;
  900. $mainframe->redirect( $url, $msg );
  901. } else {
  902. global $mainframe;
  903. // specific filters
  904. $iFilter = vmInputFilter::getInstance();
  905. $url = $iFilter->process( $url );
  906. if (!empty($msg)) {
  907. $msg = $iFilter->process( $msg );
  908. }
  909. // Strip out any line breaks and throw away the rest
  910. $url = preg_split("/[\r\n]/", $url);
  911. $url = $url[0];
  912. if ($iFilter->badAttributeValue( array( 'href', $url ))) {
  913. $url = $GLOBALS['mosConfig_live_site'];
  914. }
  915. if (trim( $msg )) {
  916. if (strpos( $url, '?' )) {
  917. $url .= '&mosmsg=' . urlencode( $msg );
  918. } else {
  919. $url .= '?mosmsg=' . urlencode( $msg );
  920. }
  921. }
  922. if (headers_sent()) {
  923. echo '<script type="text/javascript">document.location.href=\''.$url.'\';</script>';
  924. } else {
  925. @ob_end_clean(); // clear output buffer
  926. header( 'HTTP/1.1 301 Moved Permanently' );
  927. header( "Location: ". $url );
  928. }
  929. $GLOBALS['vm_mainframe']->close(true);
  930. }
  931. }
  932. /**
  933. * Raise the memory limit when it is lower than the needed value
  934. *
  935. * @param string $setLimit Example: 16M
  936. */
  937. function vmRaiseMemoryLimit( $setLimit ) {
  938. $memLimit = @ini_get('memory_limit');
  939. if( stristr( $memLimit, 'k') ) {
  940. $memLimit = str_replace( 'k', '', str_replace( 'K', '', $memLimit )) * 1024;
  941. }
  942. elseif( stristr( $memLimit, 'm') ) {
  943. $memLimit = str_replace( 'm', '', str_replace( 'M', '', $memLimit )) * 1024 * 1024;
  944. }
  945. if( stristr( $setLimit, 'k') ) {
  946. $setLimitB = str_replace( 'k', '', str_replace( 'K', '', $setLimit )) * 1024;
  947. }
  948. elseif( stristr( $setLimit, 'm') ) {
  949. $setLimitB = str_replace( 'm', '', str_replace( 'M', '', $setLimit )) * 1024 * 1024;
  950. }
  951. if( $memLimit < $setLimitB ) {
  952. @ini_set('memory_limit', $setLimit );
  953. }
  954. }
  955. /**
  956. * Returns a formatted date
  957. *
  958. * @param int $time TimeStamp format
  959. * @param String $dateformat strftime Format String
  960. * @return String
  961. */
  962. function vmFormatDate( $time=0, $dateformat='' ) {
  963. global $vendor_date_format;
  964. if( empty($time)) $time = time();
  965. if( empty( $dateformat )) {
  966. return strftime( $vendor_date_format, $time );
  967. } else {
  968. return strftime( $dateformat, $time );
  969. }
  970. }
  971. /**
  972. * Function to strip additional / or \ in a path name
  973. * @param string The path
  974. * @param boolean Add trailing slash
  975. */
  976. function vmPathName($p_path,$p_addtrailingslash = true) {
  977. $retval = "";
  978. $isWin = (substr(PHP_OS, 0, 3) == 'WIN');
  979. if ($isWin) {
  980. $retval = str_replace( '/', '\\', $p_path );
  981. if ($p_addtrailingslash) {
  982. if (substr( $retval, -1 ) != '\\') {
  983. $retval .= '\\';
  984. }
  985. }
  986. // Check if UNC path
  987. $unc = substr($retval,0,2) == '\\\\' ? 1 : 0;
  988. // Remove double \\
  989. $retval = str_replace( '\\\\', '\\', $retval );
  990. // If UNC path, we have to add one \ in front or everything breaks!
  991. if ( $unc == 1 ) {
  992. $retval = '\\'.$retval;
  993. }
  994. } else {
  995. $retval = str_replace( '\\', '/', $p_path );
  996. if ($p_addtrailingslash) {
  997. if (substr( $retval, -1 ) != '/') {
  998. $retval .= '/';
  999. }
  1000. }
  1001. // Check if UNC path
  1002. $unc = substr($retval,0,2) == '//' ? 1 : 0;
  1003. // Remove double //
  1004. $retval = str_replace('//','/',$retval);
  1005. // If UNC path, we have to add one / in front or everything breaks!
  1006. if ( $unc == 1 ) {
  1007. $retval = '/'.$retval;
  1008. }
  1009. }
  1010. return $retval;
  1011. }
  1012. /**
  1013. * Utility function to read the files in a directory
  1014. * @param string The file system path
  1015. * @param string A filter for the names
  1016. * @param boolean Recurse search into sub-directories
  1017. * @param boolean True if to prepend the full path to the file name
  1018. */
  1019. function vmReadDirectory( $path, $filter='.', $recurse=false, $fullpath=false ) {
  1020. $arr = array();
  1021. if (!@is_dir( $path )) {
  1022. return $arr;
  1023. }
  1024. $handle = opendir( $path );
  1025. while ($file = readdir($handle)) {
  1026. $dir = vmPathName( $path.'/'.$file, false );
  1027. $isDir = is_dir( $dir );
  1028. if (($file != ".") && ($file != "..")) {
  1029. if (preg_match( "/$filter/", $file )) {
  1030. if ($fullpath) {
  1031. $arr[] = trim( vmPathName( $path.'/'.$file, false ) );
  1032. } else {
  1033. $arr[] = trim( $file );
  1034. }
  1035. }
  1036. if ($recurse && $isDir) {
  1037. $arr2 = vmReadDirectory( $dir, $filter, $recurse, $fullpath );
  1038. $arr = array_merge( $arr, $arr2 );
  1039. }
  1040. }
  1041. }
  1042. closedir($handle);
  1043. asort($arr);
  1044. return $arr;
  1045. }
  1046. /**
  1047. * Helper Function to completely remove a subdirectory
  1048. *
  1049. * @param string $dirname
  1050. * @return boolean
  1051. */
  1052. function vmRemoveDirectoryR( $dirname ) {
  1053. if ($dirHandle = opendir($dirname)){
  1054. $old_cwd = getcwd();
  1055. chdir($dirname);
  1056. while ($file = readdir($dirHandle)){
  1057. if ($file == '.' || $file == '..') continue;
  1058. if (is_dir($file)){
  1059. if (!vmRemoveDirectoryR($file)) return false;
  1060. }else{
  1061. if (!@unlink($file)) return false;
  1062. }
  1063. }
  1064. closedir($dirHandle);
  1065. chdir($old_cwd);
  1066. if (!@rmdir($dirname)) return false;
  1067. return true;
  1068. }else{
  1069. return false;
  1070. }
  1071. }
  1072. /**
  1073. * Utility function to return a value from a named array or a specified default
  1074. *
  1075. * @static
  1076. * @param array $array A named array
  1077. * @param string $name The key to search for
  1078. * @param mixed $default The default value to give if no key found
  1079. * @param string $type Return type for the variable (INT, FLOAT, STRING, WORD, BOOLEAN, ARRAY)
  1080. * @return mixed The value from the source array
  1081. * @since 1.1
  1082. */
  1083. function vmGetArrayValue(&$array, $name, $default=null, $type='') {
  1084. // Initialize variables
  1085. $result = null;
  1086. if (isset ($array[$name])) {
  1087. $result = $array[$name];
  1088. }
  1089. // Handle the default case
  1090. if ((is_null($result))) {
  1091. $result = $default;
  1092. }
  1093. // Handle the type constraint
  1094. switch (strtoupper($type)) {
  1095. case 'INT' :
  1096. case 'INTEGER' :
  1097. // Only use the first integer value
  1098. @ preg_match('/-?[0-9]+/', $result, $matches);
  1099. $result = @ (int) $matches[0];
  1100. break;
  1101. case 'FLOAT' :
  1102. case 'DOUBLE' :
  1103. // Only use the first floating point value
  1104. @ preg_match('/-?[0-9]+(\.[0-9]+)?/', $result, $matches);
  1105. $result = @ (float) $matches[0];
  1106. break;
  1107. case 'BOOL' :
  1108. case 'BOOLEAN' :
  1109. $result = (bool) $result;
  1110. break;
  1111. case 'ARRAY' :
  1112. if (!is_array($result)) {
  1113. $result = array ($result);
  1114. }
  1115. break;
  1116. case 'STRING' :
  1117. $result = (string) $result;
  1118. break;
  1119. case 'WORD' :
  1120. $result = (string) preg_replace( '#\W#', '', $result );
  1121. break;
  1122. case 'NONE' :
  1123. default :
  1124. // No casting necessary
  1125. break;
  1126. }
  1127. return $result;
  1128. }
  1129. function vmGetCleanArrayFromKeyword( $keyword ) {
  1130. global $database;
  1131. $keywordArr = array();
  1132. if( empty( $keyword )) return $keywordArr;
  1133. $keywords = explode( " ", $keyword, 10 );
  1134. foreach( $keywords as $searchstring ) {
  1135. $searchstring = trim( stripslashes($searchstring) );
  1136. $strlen = strlen($searchstring);
  1137. if( $strlen > 2 ) {
  1138. /*if( $searchstring[0] == "\"" || $searchstring[0]=="'" ) {
  1139. $searchstring[0] = " ";
  1140. }
  1141. if( $searchstring[strlen($searchstring)-1] == "\"" || $searchstring[strlen($searchstring)-1]=="'" ) {
  1142. $searchstring[strlen($searchstring)-1] = " ";
  1143. }*/
  1144. $searchstring = $database->getEscaped( $searchstring );
  1145. $searchstring = str_replace('\"', '"', $searchstring );
  1146. $keywordArr[] = $searchstring;
  1147. }
  1148. }
  1149. return $keywordArr;
  1150. }
  1151. /**
  1152. * Replaces &amp; with & for xhtml compliance
  1153. *
  1154. * Needed to handle unicode conflicts due to unicode conflicts
  1155. */
  1156. function vmAmpReplace( $text ) {
  1157. $text = str_replace( '&&', '*--*', $text );
  1158. $text = str_replace( '&#', '*-*', $text );
  1159. $text = str_replace( '&amp;', '&', $text );
  1160. $text = preg_replace( '|&(?![\w]+;)|', '&amp;', $text );
  1161. $text = str_replace( '*-*', '&#', $text );
  1162. $text = str_replace( '*--*', '&&', $text );
  1163. return $text;
  1164. }
  1165. /**
  1166. * Converts array to integer values
  1167. *
  1168. * @param array
  1169. * @param int A default value to assign if $array is not an array
  1170. * @return array
  1171. */
  1172. function vmArrayToInts( &$array, $default=null ) {
  1173. if (is_array( $array )) {
  1174. foreach( $array as $key => $value ) {
  1175. $array[$key] = (int) $value;
  1176. }
  1177. } else {
  1178. if (is_null( $default )) {
  1179. $array = array();
  1180. return array(); // Kept for backwards compatibility
  1181. } else {
  1182. $array = array( (int) $default );
  1183. return array( $default ); // Kept for backwards compatibility
  1184. }
  1185. }
  1186. }
  1187. function vmRoute( $nonSefUrl) {
  1188. if (class_exists('JApplication')) { // J 1.5
  1189. $nonSefUrl = str_replace( '&amp;', '&', $nonSefUrl);
  1190. $nonSefUrl = str_replace( JURI::base(), '', $nonSefUrl); // you are adding &amp; and mosConfig_live_site to urls, but it is actually the role of the sef function to do this. So we have to remove them, otherwise Joomla router will not accept to sef-y the url
  1191. $url = JRoute::_( $nonSefUrl);
  1192. } else { // J 1.0
  1193. $url = sefRelToAbs( $nonSefUrl);
  1194. }
  1195. return $url;
  1196. }
  1197. ?>