functions.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. <?php
  2. $IMG_SIZE_PREVIEW = 600;
  3. $IMG_SIZE_MINIATURE = 200;
  4. /*****************************************************
  5. * This function is called from almost everywhere at *
  6. * the beggining of the page. It initializes the *
  7. * session variables, connect to the db, enabling *
  8. * the variable $con for futher use everywhere in *
  9. * the php code, and populates the arrays $user *
  10. * and $permission, with info about the user. *
  11. * *
  12. * @return: (db connection): The connection handler. *
  13. *****************************************************/
  14. function start_db(){
  15. //Include the db configuration file. It's somehow like this
  16. /*
  17. <?php
  18. $db_host = "XXXX";
  19. $db_name = "XXXX";
  20. $db_user = "XXXX";
  21. $db_pass = "XXXX";
  22. ?>
  23. */
  24. include ".htpasswd";
  25. $con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
  26. // Check connection
  27. if (mysqli_connect_errno()){
  28. error_log("Failed to connect to database: " . mysqli_connect_error());
  29. return -1;
  30. }
  31. //Set encoding options
  32. mysqli_set_charset($con, "utf-8");
  33. header("Content-Type: text/html; charset=utf8");
  34. mysqli_query($con, "SET NAMES utf8;");
  35. //Return the db connection
  36. return $con;
  37. }
  38. /*****************************************************
  39. * Finds out the protocol the user is connecting to *
  40. * the site with (http or https) *
  41. * @return: (string): "http://" or "https://". *
  42. ****************************************************/
  43. function get_protocol(){
  44. if (isset($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on" || $_SERVER["HTTPS"] == 1) || isset($_SERVER["HTTP_X_FORWARDED_PROTO"]) && $_SERVER["HTTP_X_FORWARDED_PROTO"] == "https") {
  45. $protocol = "https://";
  46. }
  47. else {
  48. $protocol = "http://";
  49. }
  50. return $protocol;
  51. }
  52. /****************************************************
  53. * This function turns a date string into a human *
  54. * readable string, deppending o the specified *
  55. * language. *
  56. * @params: *
  57. * strdate: (string): Date string. *
  58. * lang: (string): Language code (es, en, eu). *
  59. * http_accept_language: (string) Raw header with *
  60. * info about client *
  61. * language preferences. *
  62. * time: (boolean): Append the time at the end. *
  63. * @return: (string array) List of the languages *
  64. * offered, sorted by prefference. *
  65. ****************************************************/
  66. function format_date($strdate, $lang, $time = true){
  67. $date = strtotime($strdate);
  68. $year = date('o', $date);
  69. $month = date('n', $date);
  70. $month --;
  71. $day = date('j', $date);
  72. $wday = date('N', $date);
  73. $wday --;
  74. $hour = date('H', $date);
  75. $minute = date('i', $date);
  76. switch ($lang){
  77. case 'en':
  78. $week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
  79. $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  80. if ($time){
  81. $str = "$week[$wday], $months[$month] $day, $year at $hour:$minute";
  82. }
  83. else{
  84. $str = "$week[$wday], $months[$month] $day, $year";
  85. }
  86. break;
  87. case 'eu':
  88. $week = ['astelehena', 'asteartea', 'asteazkena', 'osteguna', 'ostirala', 'larumbata', 'igandea'];
  89. $months = ['urtarrilaren', 'otsailaren', 'martxoaren', 'apirilaren', 'maiatzaren', 'ekainaren', 'uztailaren', 'abuztuaren', 'irailaren', 'urriaren', 'azaroaren', 'abenduaren'];
  90. if ($time){
  91. $str = $year . "ko $months[$month] $day" . "an, $week[$wday], $hour:$minute";
  92. }
  93. else{
  94. $str = $year . "ko $months[$month] $day" . "an, $week[$wday]";
  95. }
  96. break;
  97. default:
  98. $week = ['Lunes', 'Martes', 'Mi&eacute;rcoles', 'Jueves', 'Viernes', 'S&aacute;bado', 'Domingo'];
  99. $months = ['enero', ' febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];
  100. if ($time){
  101. $str = "$week[$wday] $day de $months[$month] de $year a las $hour:$minute";
  102. }
  103. else{
  104. $str = "$week[$wday] $day de $months[$month] de $year";
  105. }
  106. }
  107. return $str;
  108. }
  109. /*****************************************************
  110. * Generates a URL-valid string from a regular one. *
  111. * *
  112. * @params: *
  113. * text: (string): Original string. *
  114. * @return: (string): URL-valid string. *
  115. *****************************************************/
  116. function permalink($text){
  117. $unwanted_array = array("Š"=>"S", "š"=>"s", "Ž"=>"Z", "ž"=>"z", "À"=>"A", "Á"=>"A", "Â"=>"A", "Ã"=>"A", "Ä"=>"A", "Å"=>"A", "Æ"=>"A", "Ç"=>"C", "È"=>"E", "É"=>"E",
  118. "Ê"=>"E", "Ë"=>"E", "Ì"=>"I", "Í"=>"I", "Î"=>"I", "Ï"=>"I", "Ñ"=>"N", "Ò"=>"O", "Ó"=>"O", "Ô"=>"O", "Õ"=>"O", "Ö"=>"O", "Ø"=>"O", "Ù"=>"U",
  119. "Ú"=>"U", "Û"=>"U", "Ü"=>"U", "Ý"=>"Y", "Þ"=>"B", "ß"=>"Ss", "à"=>"a", "á"=>"a", "â"=>"a", "ã"=>"a", "ä"=>"a", "å"=>"a", "æ"=>"a", "ç"=>"c",
  120. "è"=>"e", "é"=>"e", "ê"=>"e", "ë"=>"e", "ì"=>"i", "í"=>"i", "î"=>"i", "ï"=>"i", "ð"=>"o", "ñ"=>"n", "ò"=>"o", "ó"=>"o", "ô"=>"o", "õ"=>"o",
  121. "ö"=>"o", "ø"=>"o", "ù"=>"u", "ú"=>"u", "û"=>"u", "ý"=>"y", "þ"=>"b", "ÿ"=>"y" );
  122. $str = strtr( $text, $unwanted_array );
  123. $str = preg_replace("/[^\da-zA-Z ]/i", "", $str);
  124. $str = str_replace(" ", "-", $str);
  125. return $str;
  126. }
  127. /*****************************************************
  128. * Retrieves a text fragment from the database. *
  129. * *
  130. * @params: *
  131. * con (Mysql connection): Connection handler. *
  132. * id: (string): Text identifier. *
  133. * lang: (string): Language identifier. *
  134. * @return: (string): Text. *
  135. *****************************************************/
  136. function text($con, $id, $lang){
  137. $q = mysqli_query($con, "SELECT text, file FROM text WHERE id = '$id' AND lang = '$lang';");
  138. $r = mysqli_fetch_array($q);
  139. if (strlen($r["file"]) > 0){
  140. return file_get_contents($_SERVER["DOCUMENT_ROOT"] . "string/" . $r["file"]);
  141. }
  142. else{
  143. return $r["text"];
  144. }
  145. }
  146. /*****************************************************
  147. * This function closes all the opened HTML tags in *
  148. * a given string. *
  149. * *
  150. * @params: *
  151. * html: (string): The string with HTML tags. *
  152. * @return: (string): HTML with closed tags. *
  153. *****************************************************/
  154. function close_tags($html) {
  155. preg_match_all("#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU", $html, $result);
  156. $openedtags = $result[1];
  157. preg_match_all("#</([a-z]+)>#iU", $html, $result);
  158. $closedtags = $result[1];
  159. $len_opened = count($openedtags);
  160. if (count($closedtags) == $len_opened) {
  161. return $html;
  162. }
  163. $openedtags = array_reverse($openedtags);
  164. for ($i=0; $i < $len_opened; $i++) {
  165. if (!in_array($openedtags[$i], $closedtags)) {
  166. $html .= "</".$openedtags[$i].">";
  167. } else {
  168. unset($closedtags[array_search($openedtags[$i], $closedtags)]);
  169. }
  170. }
  171. return $html;
  172. }
  173. /*****************************************************
  174. * Text shortener. Given a string, it trims in the *
  175. * proximity of the desired string, ut to the next *
  176. * white character. If indicated, it will append a *
  177. * link to the full text. *
  178. * *
  179. * @params: *
  180. * text: (string): The text to shorten. *
  181. * length: (int): The desired length. *
  182. * linktext: (string): Text fot the link. *
  183. * link: (string): URI of the full text. *
  184. * @return: (string): Cutted text. *
  185. *****************************************************/
  186. function cut_text($text, $length, $linktext, $link){
  187. if (strlen($text) < $length){
  188. return $text;
  189. }
  190. $cut = substr($text, 0, strpos($text, " ", $length));
  191. $cut = close_tags($cut);
  192. if (strlen($cut) == 0){
  193. $cut = $text;
  194. }
  195. if (strlen($text) != strlen($cut)){
  196. $cut = $cut . "... <a href='$link'>$linktext</a>";
  197. }
  198. return $cut;
  199. }
  200. /*****************************************************
  201. * Finds out the IP address of the client. *
  202. * *
  203. * @return: (String): Client IP address. *
  204. *****************************************************/
  205. function get_ip(){
  206. $client = @$_SERVER["HTTP_CLIENT_IP"];
  207. $forward = @$_SERVER["HTTP_X_FORWARDED_FOR"];
  208. $remote = $_SERVER["REMOTE_ADDR"];
  209. if(filter_var($client, FILTER_VALIDATE_IP)){
  210. $ip = $client;
  211. }
  212. elseif(filter_var($forward, FILTER_VALIDATE_IP)){
  213. $ip = $forward;
  214. }
  215. else{
  216. $ip = $remote;
  217. }
  218. return $ip;
  219. }
  220. /*****************************************************
  221. * Tries to login a user to the internal page. *
  222. * *
  223. * @params: *
  224. * con (Mysql connection): Connection handler. *
  225. * user (string): Username, plain text. *
  226. * pass (string): Password SHA-1 sum. *
  227. * @return: (boolean): True if user pass/match, *
  228. * false otherwise. *
  229. *****************************************************/
  230. function login($con, $user, $pass){
  231. session_start();
  232. $q = mysqli_query($con,"SELECT id, salt, username AS username, sha1(salt) AS s FROM user WHERE (lower(username) = lower('$user') OR lower(email) = lower('$user')) AND password = sha1(concat('$pass', sha1(salt)));");
  233. if (mysqli_num_rows($q) == 1){
  234. $r = mysqli_fetch_array($q);
  235. $_SESSION['id'] = $r['id'];
  236. $_SESSION['salt'] = $r['s'];
  237. $_SESSION['name'] = $r['username'];
  238. return true;
  239. }
  240. else{
  241. error_log("Invalid login. username = $user, id = $r[id];");
  242. return false;
  243. }
  244. }
  245. /*****************************************************
  246. * Checks if a user is logged in. *
  247. * *
  248. * @params: *
  249. * con (Mysql connection): Connection handler. *
  250. * @return: (boolean): True if the user is signed *
  251. * in, false otherwise. *
  252. *****************************************************/
  253. function check_session($con){
  254. session_start(['cookie_lifetime' => 1800,]);
  255. $qr = mysqli_query($con, "SELECT id FROM user WHERE id = '$_SESSION[id]' AND sha1(salt) = '$_SESSION[salt]';");
  256. //error_log("SELECT id FROM user WHERE id = '$_SESSION[id]' AND md5(salt) = '$_SESSION[salt]';");
  257. if (mysqli_num_rows($qr) == 1)
  258. return true;
  259. else{
  260. return false;
  261. error_log("Invalid session. username = $_SESSION[name], id = $_SESSION[id]");
  262. }
  263. }
  264. /*****************************************************
  265. * Performs an update in the database. *
  266. * *
  267. * @params: *
  268. * con (Mysql connection): Connection handler. *
  269. * s_table (string): Table name. *
  270. * s_column (string): Column name. *
  271. * type (string): Column type (VARCHAR, NUMBER, *
  272. * DATE or TIME. If the value to insert in *
  273. * null, type must be NULL). *
  274. * s_value (string): New value. Ignoered if type *
  275. * is NULL. *
  276. * id (string): Row id. If the table doesn't have *
  277. * a column named 'id', this can't be used. *
  278. *****************************************************/
  279. function db_update($con, $s_table, $s_column, $type, $s_value, $id){
  280. $table = mysqli_real_escape_string($con, $s_table);
  281. $column = mysqli_real_escape_string($con, $s_column);
  282. switch (strtoupper($type)){
  283. case "NULL":
  284. $value = "null";
  285. break;
  286. case "VARCHAR":
  287. $value = "'" . mysqli_real_escape_string($con, $s_value) . "'";
  288. break;
  289. case "NUMBER":
  290. $value = intval(mysqli_real_escape_string($con, $s_value));
  291. break;
  292. case "DATE":
  293. if (!preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) \d{2}:\d{2}:\d{2}$/",$s_value)){
  294. return -2;
  295. }
  296. $value = "str_to_date('$s_value', '%Y-%m-%d')";
  297. break;
  298. case "TIME":
  299. if (!preg_match("^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$",$s_value)){
  300. return -2;
  301. }
  302. $value = "str_to_date('$s_value', '%Y-%m-%d %H:%i:%s')";
  303. break;
  304. default:
  305. return -1;
  306. }
  307. $q = mysqli_query($con, "UPDATE $table SET $column = $value WHERE id = $id;");
  308. return 0;
  309. }
  310. /*****************************************************
  311. * Performs a delete . *
  312. * *
  313. * @params: *
  314. * con (Mysql connection): Connection handler. *
  315. * s_table (string): Table name. *
  316. * id (string): Row id. If the table doesn't have *
  317. * a column named 'id', this can't be used. *
  318. *****************************************************/
  319. function db_delete($con, $s_table, $id){
  320. $table = mysqli_real_escape_string($con, $s_table);
  321. $q = mysqli_query($con, "DELETE FROM $table WHERE id = $id;");
  322. return 0;
  323. }
  324. ?>