PageRenderTime 151ms CodeModel.GetById 74ms RepoModel.GetById 0ms app.codeStats 1ms

/boca-1.5.0/src/globals.php

https://bitbucket.org/jorgenio/boca
PHP | 327 lines | 299 code | 7 blank | 21 comment | 21 complexity | 2a45351da5f5d4db27c94fda39db51f2 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. ////////////////////////////////////////////////////////////////////////////////
  3. //BOCA Online Contest Administrator
  4. // Copyright (C) 2003-2012 by BOCA Development Team (bocasystem@gmail.com)
  5. //
  6. // This program is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // This program is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. // You should have received a copy of the GNU General Public License
  16. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. ////////////////////////////////////////////////////////////////////////////////
  18. // Last modified 21/jul/2012 by cassio@ime.usp.br
  19. require_once('db.php');
  20. define("dbcompat_1_4_1",true);
  21. // sanitization
  22. function sanitizeVariables(&$item, $key)
  23. {
  24. if (!is_array($item))
  25. {
  26. // undoing 'magic_quotes_gpc = On' directive
  27. if (get_magic_quotes_gpc())
  28. $item = stripcslashes($item);
  29. $item = sanitizeText($item);
  30. }
  31. }
  32. function filedownload($oid,$fname,$msg='') {
  33. $cf = globalconf();
  34. $if = rawurlencode(encryptData($fname, session_id() . $cf['key'],false));
  35. $p = myhash($oid . $fname . $msg . session_id() . $cf["key"]);
  36. $str = "oid=". $oid . "&filename=". $if . "&check=" . $p;
  37. if($msg != '') $str .= "&msg=" . rawurlencode($msg);
  38. return $str;
  39. }
  40. function cleardir($dir,$cddir=true,$secure=false) {
  41. if(is_dir($dir)) {
  42. $ds = DIRECTORY_SEPARATOR;
  43. if($ds=="") $ds = "/";
  44. if($cddir) {
  45. @chdir($dir);
  46. @chdir('..');
  47. }
  48. $d = @opendir($dir);
  49. while (($file = @readdir($d)) !== false) {
  50. if(!is_dir($dir . $ds . $file)) {
  51. if($secure)
  52. file_put_contents($dir . $ds . $file,str_repeat('XXXXXXXXXX',10000));
  53. @unlink($dir . $ds . $file);
  54. }
  55. else {
  56. if($file != '.' && $file != '..') {
  57. $cdir1 = $dir . $ds . $file;
  58. $d1 = @opendir($cdir1);
  59. while (($file1 = @readdir($d1)) !== false)
  60. if(!is_dir($cdir1 . $ds . $file1)) {
  61. if($secure)
  62. file_put_contents($cdir1 . $ds . $file1,str_repeat('XXXXXXXXXX',10000));
  63. @unlink($cdir1 . $ds . $file1);
  64. }
  65. @rmdir($cdir1);
  66. }
  67. }
  68. }
  69. @rmdir($dir);
  70. } else {
  71. if($secure)
  72. file_put_contents($dir,str_repeat('XXXXXXXXXX',10000));
  73. @unlink($dir);
  74. }
  75. }
  76. // gen random alphanum string
  77. function randstr($len=8,$from='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
  78. $str='';
  79. $fromlen=strlen($from);
  80. while($len > 0) {
  81. $str .= substr($from,rand(0,$fromlen-1),1);
  82. $len--;
  83. }
  84. return $str;
  85. }
  86. function myhtmlspecialchars($text) {
  87. return sanitizeText($text,false);
  88. }
  89. // does the actual 'html' and 'sql' sanitization.
  90. function sanitizeText($text, $doamp=true)
  91. {
  92. if($doamp)
  93. $text = str_replace("&", "&amp;", $text);
  94. $text = str_replace("<", "&lt;", $text);
  95. $text = str_replace(">", "&gt;", $text);
  96. $text = str_replace("\"", "&quot;", $text);
  97. $text = str_replace("'", "&#39;", $text);
  98. $text = str_replace("`", "&#96;", $text);
  99. //$text = escape_string($text);
  100. $text = addslashes($text);
  101. return $text;
  102. }
  103. array_walk_recursive($_FILES, 'sanitizeVariables');
  104. array_walk_recursive($_POST, 'sanitizeVariables');
  105. array_walk_recursive($_GET, 'sanitizeVariables');
  106. array_walk_recursive($_COOKIE, 'sanitizeVariables');
  107. //name of calling function
  108. function getFunctionName($num=2) {
  109. if(strcmp(phpversion(),'5.3.6')<0) {
  110. $backtrace = debug_backtrace();
  111. } else {
  112. if(strcmp(phpversion(),'5.4.0')<0)
  113. $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
  114. else
  115. $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT,$num+5);
  116. }
  117. $ret = '';
  118. for($i=0; $i<$num; $i++)
  119. if(isset($backtrace[$i]) && isset($backtrace[$i]['function']))
  120. $ret .= " " . $backtrace[$i]['function'];
  121. if($ret =='') $ret='undef';
  122. return $ret;
  123. }
  124. function getIP() {
  125. if (getenv("REMOTE_ADDR"))
  126. $ip = getenv("REMOTE_ADDR");
  127. else
  128. return "UNKNOWN";
  129. if(defined("dbcompat_1_4_1") && dbcompat_1_4_1==true) return $ip;
  130. $ip1='';
  131. if (getenv("HTTP_X_FORWARDED_FOR")) {
  132. $ip1 = getenv("HTTP_X_FORWARDED_FOR");
  133. $ip1 = strtok ($ip1, ",");
  134. if($ip1 != $ip) $ip .= ';' . $ip1;
  135. }
  136. if (getenv("HTTP_X_CLIENTIP")) {
  137. $ip1a = getenv("HTTP_X_CLIENTIP");
  138. $ip1a = strtok ($ip1a, ",");
  139. if($ip1a != $ip1 && $ip1a != getenv("REMOTE_ADDR")) $ip .= ';' . $ip1a;
  140. }
  141. if (getenv("HTTP_CLIENT_IP")) {
  142. $ip2 = getenv("HTTP_CLIENT_IP");
  143. $ip2 = strtok ($ip2, ",");
  144. if($ip2 != $ip1a && $ip1 != $ip2 && $ip2 != getenv("REMOTE_ADDR")) $ip .= ';' . $ip2;
  145. } else {
  146. if (getenv('HTTP_X_FORWARDED')) {
  147. $ip .= ';' . getenv('HTTP_X_FORWARDED');
  148. } else {
  149. if (getenv('HTTP_FORWARDED')) {
  150. $ip .= ';' . getenv('HTTP_FORWARDED');
  151. }
  152. }
  153. }
  154. return sanitizeText($ip);
  155. }
  156. //retorna ip e hostname do cliente
  157. function getIPHost() {
  158. $ips = explode(';',getIP());
  159. $s='';
  160. for($ipn=0;$ipn<count($ips);$ipn++) {
  161. $ip = $ips[$ipn];
  162. $host = @gethostbyaddr($ip);
  163. if ($host != $ip && $host != "")
  164. $s .= $ip . "(" . $host . ") ";
  165. else
  166. $s .= $ip . ' ';
  167. }
  168. return $s;
  169. }
  170. //trata o caso de sessao invalida
  171. function InvalidSession($where) {
  172. $msg = "Session expired on $where";
  173. LOGLevel($msg,3);
  174. unset($_SESSION["usertable"]);
  175. MSGError("Session expired. You must log in again.");
  176. }
  177. //trata o caso de tentativa de burlar as regras
  178. function IntrusionNotify($where) {
  179. $msg = "Security Violation: $where";
  180. if (isset($_SESSION["usertable"]["username"]))
  181. $msg .= " (" . $_SESSION["usertable"]["username"] . "/" . $_SESSION["usertable"]["usersitenumber"] .")";
  182. unset($_SESSION["usertable"]);
  183. LOGLevel($msg,1);
  184. MSGError("Violation ($where). Admin warned.");
  185. }
  186. // verifica se a sessao esta aberta e ok
  187. function ValidSession() {
  188. if (!isset($_SESSION["usertable"])) return(FALSE);
  189. $_SESSION["usertable"] = DBUserInfo($_SESSION["usertable"]["contestnumber"],
  190. $_SESSION["usertable"]["usersitenumber"],
  191. $_SESSION["usertable"]["usernumber"]);
  192. if ($_SESSION["usertable"]["usersession"] != session_id() &&
  193. ($_SESSION["usertable"]["usermultilogin"] != 't' ||
  194. $_SESSION["usertable"]["usertype"] != 'score'))
  195. return(FALSE);
  196. return(TRUE);
  197. }
  198. // grava erro no arquivo de log
  199. function LOGError($msg) {
  200. LOGLevel($msg,0);
  201. }
  202. // grava linha no arquivo de log com o nivel especificado
  203. function LOGLevel($msg,$level) {
  204. $msga = sanitizeText(str_replace("\n", " ", $msg));
  205. $msg = now() . ": ";
  206. define_syslog_variables ();
  207. $prior = LOG_CRIT;
  208. switch ($level) {
  209. case 0: $msg .= "ERROR: ";
  210. $type = "error";
  211. $prior = LOG_ERR;
  212. break;
  213. case 1: $msg .= "WARN: ";
  214. $type = "warn";
  215. $prior = LOG_WARNING;
  216. break;
  217. case 2: $msg .= "INFO: ";
  218. $type = "info";
  219. $prior = LOG_INFO;
  220. break;
  221. case 3: $msg .= "DEBUG: ";
  222. $type = "debug";
  223. $prior = LOG_DEBUG;
  224. break;
  225. }
  226. $msg .= getIPHost() . ": " . $msga;
  227. openlog ("BOCA", LOG_ODELAY, LOG_USER);
  228. syslog ($prior, $msg);
  229. closelog();
  230. if (isset($_SESSION["usertable"]))
  231. DBNewLog($_SESSION["usertable"]["contestnumber"], $_SESSION["usertable"]["usersitenumber"],
  232. $_SESSION["usertable"]["usernumber"], $type, getIP(), $msga, "");
  233. }
  234. //retorna data e hora atuais
  235. function now () {
  236. return date('H\:i:s T \- d/M/Y');
  237. }
  238. //retorna data e hora em seg convertida para padrao
  239. function dateconv ($d) {
  240. return date('H\:i:s T \- d/M/Y', $d);
  241. }
  242. //retorna data e hora em seg convertida para padrao simples
  243. function dateconvsimple ($d) {
  244. return date('H\:i', $d);
  245. }
  246. //transforma segundos para minutos
  247. function dateconvminutes ($d) {
  248. return (int)($d/60);
  249. }
  250. //alerta mensagem via javascript
  251. function MSGError($msg) {
  252. $msg = str_replace("\n", " ", $msg);
  253. echo "<script language=\"JavaScript\">\n";
  254. echo "alert('". $msg . "');\n";
  255. echo "</script>\n";
  256. }
  257. //gera script para voltar aa tela dada
  258. function ForceLoad($where) {
  259. echo "<script language=\"JavaScript\">\n";
  260. echo "document.location='" . $where . "';\n";
  261. echo "</script></html>\n";
  262. exit;
  263. }
  264. function ForceClose() {
  265. echo "<script language=\"JavaScript\">\n";
  266. echo "window.close;\n";
  267. echo "</script></html>\n";
  268. exit;
  269. }
  270. /**
  271. * Compare an IP address to network(s)
  272. *
  273. * The network(s) argument may be a string or an array. A negative network
  274. * match must start with a "!". Depending on the 3rd parameter, it will
  275. * return true or false on the first match, or any negative rule will have
  276. * absolute priority (default).
  277. *
  278. * Samples:
  279. * match_network ("192.168.1.0/24", "192.168.1.1") -> true
  280. *
  281. * match_network (array ("192.168.1.0/24", "!192.168.1.1"), "192.168.1.1") -> false
  282. * match_network (array ("192.168.1.0/24", "!192.168.1.1"), "192.168.1.1", true) -> true
  283. * match_network (array ("!192.168.1.0/24", "192.168.1.1"), "192.168.1.1") -> false
  284. * match_network (array ("!192.168.1.0/24", "192.168.1.1"), "192.168.1.1", true) -> false
  285. *
  286. * @param mixed Network to match
  287. * @param string IP address
  288. * @param bool true: first match will return / false: priority to negative rules (default)
  289. * @see http://php.benscom.com/manual/en/function.ip2long.php#56373
  290. */
  291. function match_network ($nets, $ip) {
  292. if (!is_array ($nets)) $nets = explode(",",$nets);
  293. foreach ($nets as $net) {
  294. $net = trim($net);
  295. $rev = (preg_match ("/^\!/", $net)) ? true : false;
  296. $net = preg_replace ("/^\!/", "", $net);
  297. $ip_arr = explode('/', $net);
  298. $net_long = ip2long(trim($ip_arr[0]));
  299. $x = ip2long(trim($ip_arr[1]));
  300. $mask = long2ip($x) == ((int) trim($ip_arr[1])) ? $x : 0xffffffff << (32 - ((int) trim($ip_arr[1])));
  301. $ip_long = ip2long($ip);
  302. if ($rev) {
  303. if (($ip_long & $mask) != ($net_long & $mask)) return true;
  304. } else {
  305. if (($ip_long & $mask) == ($net_long & $mask)) return true;
  306. }
  307. }
  308. return false;
  309. }
  310. // eof
  311. ?>