PageRenderTime 49ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/code/web/api/common/utils.php

https://bitbucket.org/mattraykowski/ryzomcore_demoshard
PHP | 466 lines | 344 code | 69 blank | 53 comment | 84 complexity | 68623af23fe069540efd0dc2813c6eff MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /* Copyright (C) 2009 Winch Gate Property Limited
  3. *
  4. * This file is part of ryzom_api.
  5. * ryzom_api is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Lesser General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * ryzom_api is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public License
  16. * along with ryzom_api. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. include_once('logger.php');
  19. include_once('dfm.php');
  20. define('SERVER', 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
  21. function stripslashes_deep($value)
  22. {
  23. $value = is_array($value) ?
  24. array_map('stripslashes_deep', $value) :
  25. stripslashes($value);
  26. return $value;
  27. }
  28. if (ini_get('magic_quotes_gpc') == 1) {
  29. $_POST = stripslashes_deep($_POST);
  30. $_GET = stripslashes_deep($_GET);
  31. }
  32. // Always use this function to get param because in game, the param can be pass by _GET or by _POST
  33. function ryzom_get_param($var, $default='')
  34. {
  35. if (isset($_POST[$var]))
  36. return $_POST[$var];
  37. else
  38. if (isset($_GET[$var]))
  39. return $_GET[$var];
  40. else
  41. return $default;
  42. }
  43. function parse_query($var)
  44. {
  45. $var = parse_url($var);
  46. $arr = array();
  47. if (isset($var['query'])) {
  48. $var = html_entity_decode($var['query']);
  49. $var = explode('&', $var);
  50. foreach($var as $val) {
  51. $x = explode('=', $val);
  52. if (count($x) > 1)
  53. $arr[$x[0]] = urldecode($x[1]);
  54. else
  55. $arr[$x[0]] = '';
  56. }
  57. unset($val, $x, $var);
  58. }
  59. return $arr;
  60. }
  61. function ryzom_get_params()
  62. {
  63. if (!isset($GLOBALS['URL_PARAMS']))
  64. $GLOBALS['URL_PARAMS'] = parse_query($_SERVER['REQUEST_URI']);
  65. return $GLOBALS['URL_PARAMS'];
  66. }
  67. function ryzom_unset_url_param($name) {
  68. if (!isset($GLOBALS['URL_PARAMS']))
  69. $GLOBALS['URL_PARAMS'] = parse_query($_SERVER['REQUEST_URI']);
  70. unset($GLOBALS['URL_PARAMS'][$name]);
  71. return $GLOBALS['URL_PARAMS'];
  72. }
  73. if (!function_exists('http_build_query')) {
  74. function http_build_query($data, $prefix='', $sep='', $key='') {
  75. $ret = array();
  76. foreach ((array)$data as $k => $v) {
  77. if (is_int($k) && $prefix != null) {
  78. $k = urlencode($prefix . $k);
  79. }
  80. if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
  81. if (is_array($v) || is_object($v)) {
  82. array_push($ret, http_build_query($v, '', $sep, $k));
  83. } else {
  84. array_push($ret, $k.'='.urlencode($v));
  85. }
  86. }
  87. if (empty($sep)) $sep = ini_get('arg_separator.output');
  88. return implode($sep, $ret);
  89. }
  90. }
  91. if(!function_exists('_url')){
  92. function _url($base_params=null, $add_params=array()){
  93. if ($base_params !== null)
  94. return SERVER.'?'.http_build_query(array_merge($base_params, $add_params));
  95. else
  96. return SERVER;
  97. }
  98. }
  99. if(!function_exists('_h')){
  100. function _h($s){
  101. return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
  102. }
  103. }
  104. if(!function_exists('_i')){
  105. function _i($img, $alt=''){
  106. if (substr($img, strlen($img)-4) == '.tga') // img from client texture : ig only
  107. return $img;
  108. if (is_file(RYAPI_PATH.'/data/icons/'.$img.'.png'))
  109. $img = RYAPI_URL.'/data/icons/'.$img.'.png';
  110. else if (is_file(RYAPP_PATH.'/data/icons/'.$img.'.png'))
  111. $img = RYAPP_URL.'/data/icons/'.$img.'.png';
  112. else
  113. $img = 'view_remove';
  114. if ($alt)
  115. return '<img src="'.$img.'" title="'.$alt.'" alt="'.utf8_decode($alt).'" />';
  116. else
  117. return '<img src="'.$img.'" />';
  118. }
  119. }
  120. if(!function_exists('_l')){
  121. function _l($text, $base_params=array(), $add_params=array())
  122. {
  123. return '<a href="'.SERVER.'?'.http_build_query(array_merge($base_params, $add_params)).'">'.$text.'</a>';
  124. }
  125. }
  126. if(!function_exists('_b')){
  127. function _b($text, $base_params=array(), $add_params=array())
  128. {
  129. return '<a href="'.SERVER.'?'.http_build_query(array_merge($base_params, $add_params)).'" class="ryzom-ui-button">'.$text.'</a>';
  130. }
  131. }
  132. /***
  133. *
  134. * Translation utilities
  135. *
  136. * ***/
  137. function translation_exists($id) {
  138. global $user, $ryzom_texts;
  139. return isset($ryzom_texts[$id]) && isset($ryzom_texts[$id][$user['lang']]);
  140. }
  141. // Translate the $id in the selected language
  142. function get_translation($id, $lang, $args=array()) {
  143. global $ryzom_texts, $user;
  144. if(!isset($ryzom_texts[$id])) return '{'.$id.'}';
  145. if(empty($ryzom_texts[$id][$lang])){
  146. if(isset($ryzom_texts[$id]['en'])) return @vsprintf($ryzom_texts[$id]['en'], $args);
  147. return '{'.$id.'['.$lang.']}';
  148. }
  149. return @vsprintf($ryzom_texts[$id][$lang], $args);
  150. }
  151. // Translate the $id in the user language
  152. function _t($id, $args=array()) {
  153. global $ryzom_texts, $user;
  154. $a = '';
  155. if ($args) {
  156. if (is_array($args)) {
  157. $a = array();
  158. foreach ($args as $arg)
  159. $a[] = strval($arg);
  160. $a = ' '.implode(', ', $a);
  161. } else
  162. $a = ' '.strval($args);
  163. }
  164. if(!isset($ryzom_texts[$id])) return '{'.$id.$a.'}';
  165. if(empty($ryzom_texts[$id][$user['lang']])){
  166. if(!empty($ryzom_texts[$id]['en'])) return @vsprintf($ryzom_texts[$id]['en'], $args);
  167. if(!empty($ryzom_texts[$id]['fr'])) return '{'.$id.$a.'}';
  168. if(!empty($ryzom_texts[$id]['de'])) return '{'.$id.$a.'}';
  169. return '{'.$id.'['.$user['lang'].']'.$a.'}';
  170. }
  171. return @vsprintf($ryzom_texts[$id][$user['lang']], $args);
  172. }
  173. /***
  174. *
  175. * Ryzom time
  176. *
  177. * ***/
  178. function ryzom_timer($timestamp) {
  179. $d = intval($timestamp / 86400);
  180. $timestamp = $timestamp % 86400;
  181. $h = intval($timestamp / 3600);
  182. $timestamp = $timestamp % 3600;
  183. $m = intval($timestamp / 60);
  184. $s = $timestamp % 60;
  185. if ($d>1)
  186. return sprintf('%d'._t('days').' %02d:%02d:%02d', $d, $h, $m, $s);
  187. else if ($d)
  188. return sprintf('%d'._t('day').' %02d:%02d:%02d', $d, $h, $m, $s);
  189. else
  190. return sprintf("%02d:%02d:%02d", $h, $m, $s);
  191. }
  192. // Get a human and translated readable time, for example "3 days ago"
  193. function ryzom_relative_time($timestamp) {
  194. global $ryzom_periods, $user;
  195. $difference = time() - $timestamp;
  196. $lengths = array("60","60","24","7","4.35","12","10");
  197. if ($difference >= 0) { // this was in the past
  198. $ending = _t('ago');
  199. } else { // this was in the future
  200. $difference = -$difference;
  201. $ending = _t('to_go');
  202. }
  203. for($j = 0,$m=count($lengths); $j<$m && $difference >= $lengths[$j]; $j++)
  204. $difference /= $lengths[$j];
  205. // round hours as '1.2 hours to go'
  206. $difference = round($difference, ($j == 2) ? 1 : 0);
  207. $form = ($difference == 1) ? 'singular' : 'plural';
  208. // Handle exceptions
  209. // French uses singular form if difference = 0
  210. if ($user['lang'] == 'fr' && ($difference == 0)) {
  211. $form = 'singular';
  212. }
  213. // Russian has a different plural form for plurals of 2 through 4
  214. if ($user['lang'] == 'ru' && ($form == 'plural')) {
  215. if ($difference < 5) {
  216. $form = '2-4';
  217. }
  218. }
  219. if(!empty($ryzom_periods[$user['lang']][$form][$j]))
  220. $final = $ryzom_periods[$user['lang']][$form][$j];
  221. else
  222. $final = $ryzom_periods['en'][$form][$j];
  223. $text = _t('date_format', array($difference, $final, $ending));
  224. return $text;
  225. }
  226. // Get a human and translated absolute date
  227. function ryzom_absolute_time($timestamp) {
  228. global $user, $ryzom_daysofweek, $ryzom_monthnames;
  229. $day_of_month = date("j", $timestamp);
  230. $dow = date("w", $timestamp);
  231. $month = date("n", $timestamp);
  232. $day_of_week = $ryzom_daysofweek[$user['lang']][$dow];
  233. $month_str = $ryzom_monthnames[$user['lang']][$month-1];
  234. $text = _t("absolute_date_format", array($day_of_month, $day_of_week, $month_str, $month, date("m", $timestamp), date("d", $timestamp)));
  235. return $text;
  236. }
  237. /***
  238. *
  239. * Ryzom utilities
  240. *
  241. *
  242. * ***/
  243. function ryzom_generate_password($length=8, $level=2, $oneofeach=false) {
  244. $validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
  245. $validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  246. $validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/";
  247. $password = "";
  248. $counter = 0;
  249. while ($counter < $length) {
  250. $actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);
  251. // if $oneofeach then All character must be different (slower)
  252. if (!$oneofeach || !strstr($password, $actChar)) {
  253. $password .= $actChar;
  254. $counter++;
  255. }
  256. }
  257. return $password;
  258. }
  259. function file_get_contents_cached($fn, $cache_time=300) {
  260. global $ryzom_bench_text;
  261. $lfn = 'tmp/'.strtr($fn, ':/.?&=', '____________');
  262. // get the new file from internet every $cache_time (default=5min)
  263. if (file_exists($lfn) && filesize($lfn) > 0 && time() < filemtime($lfn) + $cache_time) {
  264. $content = file_get_contents($lfn);
  265. } else {
  266. $content = file_get_contents($fn);
  267. if ($content != '') file_put_contents($lfn, $content);
  268. }
  269. return $content;
  270. }
  271. function ryzom_redirect($url, $group='', $extra_lua='') {
  272. global $user;
  273. $lua = $extra_lua."\n";
  274. if ($user['ig']) {
  275. if (!$group)
  276. $lua .= 'getUI(__CURRENT_WINDOW__):browse("'.str_replace('&', '&amp;', $url).'")';
  277. else {
  278. if (substr($group, 0, 3) == 'ui:')
  279. $lua .= 'getUI("'.$group.'"):browse("'.str_replace('&', '&amp;', $url).'")';
  280. else
  281. $lua .= 'getUI("ui:interface:'.$group.':content:html"):browse("'.str_replace('&', '&amp;', $url).'")';
  282. }
  283. echo '<lua>'.$lua.'</lua>';
  284. exit();
  285. } else {
  286. header('Location: '.$url);
  287. exit();
  288. }
  289. }
  290. /***
  291. *
  292. * Debug tools
  293. *
  294. * ***/
  295. function alert($var, $value=NULL, $level=1) {
  296. p($var, $value, '#FF7777', $level);
  297. }
  298. define('pNULL', '§$£¤*µ%ù²&#!;,;:.?/?.<>');
  299. function p($var, $value=pNULL, $color='#FFFF00', $level=0) {
  300. ob_start();
  301. debug_print_backtrace();
  302. $bt = ob_get_contents();
  303. ob_end_clean();
  304. $bt = explode("\n#",$bt);
  305. if (isset($bt[$level]))
  306. $bt1 = explode('[', $bt[$level]);
  307. else
  308. $bt1 = array('');
  309. if (isset($bt[$level+1]))
  310. $bt2 = explode('[', $bt[$level+1]);
  311. else
  312. $bt2 = array('');
  313. $c = '';
  314. if ($value !== pNULL) {
  315. $c .= '<font color="#FFFFFF">'.$var.' : </font>';
  316. $var = $value;
  317. }
  318. $c .= '<font color="#AAFFFF">'.substr(str_replace("\n", "", $bt2[count($bt2)-1]), 0, -1).' =&gt; '.substr(str_replace("\n", "", $bt1[count($bt1)-1]), 0, -1)."</font> ";
  319. ryLogger::getInstance()->addPrint($c);
  320. ob_start();
  321. var_dump($var);
  322. ryLogger::getInstance()->addPrint(_h(ob_get_contents()), $color);
  323. ob_end_clean();
  324. }
  325. /***
  326. *
  327. * Lua tools
  328. *
  329. * ***/
  330. class ryLua {
  331. static private $lua = array();
  332. static private $luaend = array();
  333. static private $indent;
  334. static private $indentend;
  335. static private $linkTargetId = 0;
  336. static function add($code, $indent=NULL) {
  337. if ($indent !== NULL)
  338. self::$indent += $indent;
  339. $tabs = str_repeat(" ", self::$indent);
  340. $a = $tabs.str_replace("\n", "\n ".$tabs, $code);
  341. self::$lua[] = $a;
  342. }
  343. static function addEnd($code, $indent=NULL) {
  344. if ($indent !== NULL)
  345. self::$indentend += $indent;
  346. $tabs = str_repeat(" ", self::$indentend);
  347. $a = $tabs.str_replace("\n", "\n ".$tabs, $code);
  348. self::$luaend[] = $a;
  349. }
  350. static function get($ig) {
  351. ryLogger::getInstance()->addPrint(implode("\n", self::$lua), '#FF00FF');
  352. $ret = ($ig)?"<lua>\n".implode("\n", self::$lua)."\n</lua>":'';
  353. self::$lua = array();
  354. return $ret;
  355. }
  356. static function getEnd($ig) {
  357. ryLogger::getInstance()->addPrint(implode("\n", self::$luaend), '#FF55FF');
  358. $ret = ($ig)?"<lua>\n".implode("\n", self::$luaend)."\n</lua>":'';
  359. self::$luaend = array();
  360. return $ret;
  361. }
  362. static function text($text) {
  363. return str_replace('"', '\"', $text);
  364. }
  365. static function url($base_params=null, $add_params=array()) {
  366. return str_replace('&', '&amp;', _url($base_params, $add_params));
  367. }
  368. function openLink($text, $target='webig', $base_params=array(), $add_params=array(), $urllua='', $runlua='')
  369. {
  370. $url = self::url($base_params, $add_params);
  371. if ($target == "help_browser")
  372. $url .= "&amp;ignore=";
  373. $id = ryzom_generate_password(8).strval(time()).strval(self::$linkTargetId++);
  374. $lua = <<< END
  375. function openLink{$id}()
  376. runAH(nil, "browse", "name=ui:interface:{$target}:content:html|url={$url}"{$urllua})
  377. {$runlua}
  378. end
  379. END;
  380. self::add($lua);
  381. if (RYZOM_IG)
  382. return '<a href="ah:lua&openLink'.$id.'()">'.$text.'</a>';
  383. return $text;
  384. }
  385. static function link($id, $luacode, $text) {
  386. $lua = <<<END
  387. function runLua{$id}()
  388. {$luacode}
  389. end
  390. END;
  391. self::add($lua);
  392. if (RYZOM_IG)
  393. return '<a href="ah:lua&runLua'.$id.'()">'.$text.'</a>';
  394. return $text;
  395. }
  396. }
  397. ?>