PageRenderTime 42ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/chronique/includes/MiscFunctions.php

http://chronique.googlecode.com/
PHP | 387 lines | 325 code | 42 blank | 20 comment | 46 complexity | 8d57c9ca2a8066028a387818cbf042e9 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, LGPL-2.1, MPL-2.0-no-copyleft-exception
  1. <?php
  2. /* $Id: MiscFunctions.php 4761 2011-12-03 03:03:38Z daintree $*/
  3. /* ****************************************** */
  4. /** STANDARD MESSAGE HANDLING & FORMATTING **/
  5. /* ****************************************** */
  6. function prnMsg($Msg,$Type='info', $Prefix=''){
  7. echo getMsg($Msg, $Type, $Prefix);
  8. }//prnMsg
  9. function reverse_escape($str) {
  10. $search=array("\\\\","\\0","\\n","\\r","\Z","\'",'\"');
  11. $replace=array("\\","\0","\n","\r","\x1a","'",'"');
  12. return str_replace($search,$replace,$str);
  13. }
  14. function getMsg($Msg,$Type='info',$Prefix=''){
  15. $Colour='';
  16. if (isset($_SESSION['LogSeverity']) and $_SESSION['LogSeverity']>0) {
  17. $LogFile=fopen($_SESSION['LogPath'].'/webERP-test.log', 'a');
  18. }
  19. switch($Type){
  20. case 'error':
  21. $Class = 'error';
  22. $Prefix = $Prefix ? $Prefix : _('ERROR') . ' ' ._('Message Report');
  23. if (isset($_SESSION['LogSeverity']) and $_SESSION['LogSeverity']>0) {
  24. fwrite($LogFile, date('Y-m-d h-m-s').','.$Type.','.$_SESSION['UserID'].','.trim($Msg,',')."\n");
  25. }
  26. break;
  27. case 'warn':
  28. $Class = 'warn';
  29. $Prefix = $Prefix ? $Prefix : _('WARNING') . ' ' . _('Message Report');
  30. if (isset($_SESSION['LogSeverity']) and $_SESSION['LogSeverity']>1) {
  31. fwrite($LogFile, date('Y-m-d h-m-s').','.$Type.','.$_SESSION['UserID'].','.trim($Msg,',')."\n");
  32. }
  33. break;
  34. case 'success':
  35. $Class = 'success';
  36. $Prefix = $Prefix ? $Prefix : _('SUCCESS') . ' ' . _('Report');
  37. if (isset($_SESSION['LogSeverity']) and $_SESSION['LogSeverity']>3) {
  38. fwrite($LogFile, date('Y-m-d h-m-s').','.$Type.','.$_SESSION['UserID'].','.trim($Msg,',')."\n");
  39. }
  40. break;
  41. case 'info':
  42. default:
  43. $Prefix = $Prefix ? $Prefix : _('INFORMATION') . ' ' ._('Message');
  44. $Class = 'info';
  45. if (isset($_SESSION['LogSeverity']) and $_SESSION['LogSeverity']>2) {
  46. fwrite($LogFile, date('Y-m-d h-m-s').','.$Type.','.$_SESSION['UserID'].','.trim($Msg,',')."\n");
  47. }
  48. }
  49. return '<div class="'.$Class.'"><b>' . $Prefix . '</b> : ' .$Msg . '</div>';
  50. }//getMsg
  51. function IsEmailAddress($Email){
  52. $AtIndex = strrpos ($Email, "@");
  53. if ($AtIndex == false) {
  54. return false; // No @ sign is not acceptable.
  55. }
  56. if (preg_match('/\\.\\./', $Email)){
  57. return false; // > 1 consecutive dot is not allowed.
  58. }
  59. // Check component length limits
  60. $Domain = mb_substr ($Email, $AtIndex+1);
  61. $Local= mb_substr ($Email, 0, $AtIndex);
  62. $LocalLen = mb_strlen ($Local);
  63. $DomainLen = mb_strlen ($Domain);
  64. if ($LocalLen < 1 || $LocalLen > 64){
  65. // local part length exceeded
  66. return false;
  67. }
  68. if ($DomainLen < 1 || $DomainLen > 255){
  69. // domain part length exceeded
  70. return false;
  71. }
  72. if ($Local[0] == '.' OR $Local[$LocalLen-1] == '.') {
  73. // local part starts or ends with '.'
  74. return false;
  75. }
  76. if (!preg_match ('/^[A-Za-z0-9\\-\\.]+$/', $Domain )){
  77. // character not valid in domain part
  78. return false;
  79. }
  80. if (!preg_match ('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace ("\\\\", "" ,$Local) )){
  81. // character not valid in local part unless local part is quoted
  82. if (!preg_match ('/^"(\\\\"|[^"])+"$/', str_replace("\\\\", "", $Local) )) {
  83. return false;
  84. }
  85. }
  86. // Check for a DNS 'MX' or 'A' record.
  87. // Windows supported from PHP 5.3.0 on - so check.
  88. $Ret = true;
  89. /* Apparentely causes some problems on some versions - perhaps bleeding edge just yet
  90. if (version_compare(PHP_VERSION, '5.3.0') >= 0 OR mb_strtoupper(mb_substr(PHP_OS, 0, 3) !== 'WIN')) {
  91. $Ret = checkdnsrr( $Domain, 'MX' ) OR checkdnsrr( $Domain, 'A' );
  92. }
  93. */
  94. return $Ret;
  95. }
  96. function ContainsIllegalCharacters ($CheckVariable) {
  97. if (mb_strstr($CheckVariable,"'")
  98. OR mb_strstr($CheckVariable,'+')
  99. OR mb_strstr($CheckVariable,'?')
  100. OR mb_strstr($CheckVariable,'.')
  101. OR mb_strstr($CheckVariable,"\"")
  102. OR mb_strstr($CheckVariable,'&')
  103. OR mb_strstr($CheckVariable,"\\")
  104. OR mb_strstr($CheckVariable,'"')
  105. OR mb_strstr($CheckVariable,'>')
  106. OR mb_strstr($CheckVariable,'<')){
  107. return true;
  108. } else {
  109. return false;
  110. }
  111. }
  112. function pre_var_dump(&$var){
  113. echo '<div align=left><pre>';
  114. var_dump($var);
  115. echo '</pre></div>';
  116. }
  117. class XmlElement {
  118. var $name;
  119. var $attributes;
  120. var $content;
  121. var $children;
  122. };
  123. function GetECBCurrencyRates () {
  124. /* See http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html
  125. for detail of the European Central Bank rates - published daily */
  126. if (http_file_exists('http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml')) {
  127. $xml = file_get_contents('http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml');
  128. $parser = xml_parser_create();
  129. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  130. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  131. xml_parse_into_struct($parser, $xml, $tags);
  132. xml_parser_free($parser);
  133. $elements = array(); // the currently filling [child] XmlElement array
  134. $stack = array();
  135. foreach ($tags as $tag) {
  136. $index = count($elements);
  137. if ($tag['type'] == 'complete' OR $tag['type'] == 'open') {
  138. $elements[$index] = new XmlElement;
  139. $elements[$index]->name = $tag['tag'];
  140. $elements[$index]->attributes = $tag['attributes'];
  141. $elements[$index]->content = $tag['value'];
  142. if ($tag['type'] == 'open') { // push
  143. $elements[$index]->children = array();
  144. $stack[count($stack)] = &$elements;
  145. $elements = &$elements[$index]->children;
  146. }
  147. }
  148. if ($tag['type'] == 'close') { // pop
  149. $elements = &$stack[count($stack) - 1];
  150. unset($stack[count($stack) - 1]);
  151. }
  152. }
  153. $Currencies = array();
  154. foreach ($elements[0]->children[2]->children[0]->children as $CurrencyDetails){
  155. $Currencies[$CurrencyDetails->attributes['currency']]= $CurrencyDetails->attributes['rate'] ;
  156. }
  157. $Currencies['EUR']=1; //ECB delivers no rate for Euro
  158. //return an array of the currencies and rates
  159. return $Currencies;
  160. } else {
  161. return false;
  162. }
  163. }
  164. function GetCurrencyRate($CurrCode,$CurrenciesArray) {
  165. if ((!isset($CurrenciesArray[$CurrCode]) or !isset($CurrenciesArray[$_SESSION['CompanyRecord']['currencydefault']]))){
  166. return quote_oanda_currency($CurrCode);
  167. } elseif ($CurrCode=='EUR'){
  168. if ($CurrenciesArray[$_SESSION['CompanyRecord']['currencydefault']]==0) {
  169. return 0;
  170. } else {
  171. return 1/$CurrenciesArray[$_SESSION['CompanyRecord']['currencydefault']];
  172. }
  173. } else {
  174. if ($CurrenciesArray[$_SESSION['CompanyRecord']['currencydefault']]==0) {
  175. return 0;
  176. } else {
  177. return $CurrenciesArray[$CurrCode]/$CurrenciesArray[$_SESSION['CompanyRecord']['currencydefault']];
  178. }
  179. }
  180. }
  181. function quote_oanda_currency($CurrCode) {
  182. if (http_file_exists('http://www.oanda.com/convert/fxdaily?value=1&redirected=1&exch=' . $CurrCode . '&format=CSV&dest=Get+Table&sel_list=' . $_SESSION['CompanyRecord']['currencydefault'])) {
  183. $page = file('http://www.oanda.com/convert/fxdaily?value=1&redirected=1&exch=' . $CurrCode . '&format=CSV&dest=Get+Table&sel_list=' . $_SESSION['CompanyRecord']['currencydefault']);
  184. $match = array();
  185. preg_match('/(.+),(\w{3}),([0-9.]+),([0-9.]+)/i', implode('', $page), $match);
  186. if ( sizeof($match) > 0 ){
  187. return $match[3];
  188. } else {
  189. return false;
  190. }
  191. }
  192. }
  193. function AddCarriageReturns($str) {
  194. return str_replace('\r\n',chr(10),$str);
  195. }
  196. function wikiLink($type, $id) {
  197. if ($_SESSION['WikiApp']==_('WackoWiki')){
  198. echo '<a target="_blank" href="../' . $_SESSION['WikiPath'] . '/' . $type . $id . '">' . _('Wiki ' . $type . ' Knowlege Base') . '</a><br />';
  199. } elseif ($_SESSION['WikiApp']==_('MediaWiki')){
  200. echo '<a target="_blank" href="../' . $_SESSION['WikiPath'] . '/index.php/' . $type . '/' . $id . '">' . _('Wiki ' . $type . ' Knowlege Base') . '</a><br />';
  201. } elseif ($_SESSION['WikiApp']==_('DokuWiki')){
  202. echo ' ../' . $_SESSION['WikiPath'] . '/doku.php?id=' . $type . ':' . $id . ' ' . _('Wiki ' . $type . ' Knowlege Base') . ' <br />';
  203. }
  204. }//wikiLink
  205. // Lindsay debug stuff
  206. function LogBackTrace( $dest = 0 ) {
  207. error_log( "***BEGIN STACK BACKTRACE***", $dest );
  208. $stack = debug_backtrace();
  209. // Leave out our frame and the topmost - huge for xmlrpc!
  210. for( $ii = 1; $ii < count( $stack ) - 3; $ii++ )
  211. {
  212. $frame = $stack[$ii];
  213. $msg = "FRAME " . $ii . ": ";
  214. if( isset( $frame['file'] ) ) {
  215. $msg .= "; file=" . $frame['file'];
  216. }
  217. if( isset( $frame['line'] ) ) {
  218. $msg .= "; line=" . $frame['line'];
  219. }
  220. if( isset( $frame['function'] ) ) {
  221. $msg .= "; function=" . $frame['function'];
  222. }
  223. if( isset( $frame['args'] ) ) {
  224. // Either function args, or included file name(s)
  225. $msg .= ' (';
  226. foreach( $frame['args'] as $val ) {
  227. $typ = gettype( $val );
  228. switch( $typ ) {
  229. case 'array':
  230. $msg .= '[ ';
  231. foreach( $val as $v2 ) {
  232. if( gettype( $v2 ) == 'array' ) {
  233. $msg .= '[ ';
  234. foreach( $v2 as $v3 )
  235. $msg .= $v3;
  236. $msg .= ' ]';
  237. } else {
  238. $msg .= $v2 . ', ';
  239. }
  240. $msg .= ' ]';
  241. break;
  242. }
  243. case 'string':
  244. $msg .= $val . ', ';
  245. break;
  246. case 'integer':
  247. $msg .= sprintf( "%d, ", $val );
  248. break;
  249. default:
  250. $msg .= '<' . gettype( $val ) . '>, ';
  251. break;
  252. }
  253. $msg .= ' )';
  254. }
  255. }
  256. error_log( $msg, $dest );
  257. }
  258. error_log( '++++END STACK BACKTRACE++++', $dest );
  259. return;
  260. }
  261. function http_file_exists($url) {
  262. $f=@fopen($url,'r');
  263. if($f) {
  264. fclose($f);
  265. return true;
  266. }
  267. return false;
  268. }
  269. /*Functions to display numbers in locale of the user */
  270. function locale_number_format($Number, $DecimalPlaces=0) {
  271. global $DecimalPoint;
  272. global $ThousandsSeparator;
  273. if ($_SESSION['Language']=='hi_IN.utf8' OR $_SESSION['Language']=='en_IN.utf8'){
  274. return indian_number_format($Number,$DecimalPlaces);
  275. } else {
  276. if (!is_numeric($DecimalPlaces) AND $DecimalPlaces == 'Variable'){
  277. $DecimalPlaces = mb_strlen($Number) - mb_strlen(intval($Number));
  278. if ($DecimalPlaces > 0){
  279. $DecimalPlaces--;
  280. }
  281. }
  282. return number_format($Number,$DecimalPlaces,$DecimalPoint,$ThousandsSeparator);
  283. }
  284. }
  285. /* and to parse the input of the user into useable number */
  286. function filter_number_format($Number) {
  287. global $DecimalPoint;
  288. global $ThousandsSeparator;
  289. $SQLFormatNumber = str_replace($DecimalPoint,'.',str_replace($ThousandsSeparator,'',trim($Number)));
  290. /*It is possible if the user entered the $DecimalPoint as a thousands separator and the $DecimalPoint is a comma that the result of this could contain several periods "." so need to ditch all but the last "." */
  291. if (mb_substr_count($SQLFormatNumber,'.')>1){
  292. return str_replace('.','',mb_substr($SQLFormatNumber,0,mb_strrpos($SQLFormatNumber,'.'))) . mb_substr($SQLFormatNumber,mb_strrpos($SQLFormatNumber,'.'));
  293. echo '<br /> Number of periods: ' . $NumberOfPeriods . ' $SQLFormatNumber = ' . $SQLFormatNumber;
  294. } else {
  295. return $SQLFormatNumber;
  296. }
  297. }
  298. function indian_number_format($Number,$DecimalPlaces){
  299. $IntegerNumber = intval($Number);
  300. $DecimalValue = $Number - $IntegerNumber;
  301. if ($DecimalPlaces !='Variable'){
  302. $DecimalValue= round($DecimalValue,$DecimalPlaces);
  303. }
  304. if ($DecimalPlaces!='Variable' AND strlen(substr($DecimalValue,2))>0){
  305. /*If the DecimalValue is longer than '0.' then chop off the leading 0*/
  306. $DecimalValue = substr($DecimalValue,1);
  307. if ($DecimalPlaces > 0){
  308. $DecimalValue = str_pad($DecimalValue,$DecimalPlaces,'0');
  309. } else {
  310. $DecimalValue ='';
  311. }
  312. } else {
  313. if ($DecimalPlaces!='Variable' AND $DecimalPlaces > 0){
  314. $DecimalValue = '.' . str_pad($DecimalValue,$DecimalPlaces,'0');
  315. } elseif($DecimalPlaces==0) {
  316. $DecimalValue ='';
  317. }
  318. }
  319. if(strlen($IntegerNumber)>3){
  320. $LastThreeNumbers = substr($IntegerNumber, strlen($IntegerNumber)-3, strlen($IntegerNumber));
  321. $RestUnits = substr($IntegerNumber, 0, strlen($IntegerNumber)-3); // extracts the last three digits
  322. $RestUnits = (strlen($RestUnits)%2 == 1)?'0'.$RestUnits:$RestUnits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
  323. $FirstPart ='';
  324. $ExplodedUnits = str_split($RestUnits, 2);
  325. for($i=0; $i<sizeof($ExplodedUnits); $i++){
  326. $FirstPart .= intval($ExplodedUnits[$i]).','; // creates each of the 2's group and adds a comma to the end
  327. }
  328. return $FirstPart.$LastThreeNumbers.$DecimalValue;
  329. } else {
  330. return $IntegerNumber. $DecimalValue;
  331. }
  332. }
  333. ?>