functions.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. /*****************************************************
  3. * This function is called from almost everywhere at *
  4. * the beggining of the page. It initializes the *
  5. * session variables, connect to the db, enabling *
  6. * the variable $con for futher use everywhere in *
  7. * the php code, and populates the arrays $user *
  8. * and $permission, with info about the user. *
  9. * *
  10. * @return: (db connection): The connection handler. *
  11. *****************************************************/
  12. function start_db(){
  13. //Include the db configuration file. It's somehow like this
  14. /*
  15. <?php
  16. $db_host = "XXXX";
  17. $db_name = "XXXX";
  18. $db_user = "XXXX";
  19. $db_pass = "XXXX";
  20. ?>
  21. */
  22. include ".htpasswd";
  23. $con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
  24. // Check connection
  25. if (mysqli_connect_errno()){
  26. error_log("Failed to connect to database: " . mysqli_connect_error());
  27. return -1;
  28. }
  29. //Set encoding options
  30. mysqli_set_charset($con, "utf-8");
  31. header("Content-Type: text/html; charset=utf8");
  32. mysqli_query($con, "SET NAMES utf8;");
  33. //Return the db connection
  34. return $con;
  35. }
  36. /*****************************************************
  37. * Finds out the protocol the user is connecting to *
  38. * the site with (http or https) *
  39. * @return: (string): "http://" or "https://". *
  40. ****************************************************/
  41. function get_protocol(){
  42. if (isset($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on" || $_SERVER["HTTPS"] == 1) || isset($_SERVER["HTTP_X_FORWARDED_PROTO"]) && $_SERVER["HTTP_X_FORWARDED_PROTO"] == "https") {
  43. $protocol = "https://";
  44. }
  45. else {
  46. $protocol = "http://";
  47. }
  48. return $protocol;
  49. }
  50. /*****************************************************
  51. * This function selects the language the page will *
  52. * be displayed inf the page. Several methods are *
  53. * used: cookie detection, and browser language *
  54. * preferences. *
  55. * @return: (string): Language code. *
  56. *****************************************************/
  57. // TODO: Redo using database
  58. function select_language(){
  59. // Check for language in uri
  60. $lang = substr($_SERVER['REQUEST_URI'], 1, 2);
  61. if ($lang == "es" || $lang == "en" || $lang == "eu"){
  62. return $lang;
  63. }
  64. else{
  65. // Language is not in url. Find it out and redirect
  66. // Is passed on the URL?
  67. $lang = $_GET["lang"];
  68. if ($lang == "es" || $lang == "en" || $lang == "eu"){
  69. header("Location: " . get_protocol() . $_SERVER["HTTP_HOST"] . "/" . $lang . $_SERVER["REQUEST_URI"]);
  70. return $lang;
  71. }
  72. // Try to read cookie.
  73. header("Cache-control: private");
  74. if (isSet($_COOKIE["lang"])){
  75. $lang = $_COOKIE["lang"];
  76. if ($lang == "es" || $lang == "en" || $lang == "eu"){
  77. header("Location: " . get_protocol() . $_SERVER["HTTP_HOST"] . "/" . $lang . $_SERVER["REQUEST_URI"]);
  78. return $lang;
  79. }
  80. }
  81. //If no cookie, select from client browser preferences.
  82. else{
  83. $available_languages = array("en", "eu", "es");
  84. $langs = prefered_language($available_languages, $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
  85. $lang = $langs[0];
  86. if ($lang == "es" || $lang == "en" || $lang == "eu"){
  87. header("Location: " . get_protocol() . $_SERVER["HTTP_HOST"] . "/" . $lang . $_SERVER["REQUEST_URI"]);
  88. return $lang;
  89. }
  90. }
  91. // If no method was succesfull, default language
  92. $lang = "es";
  93. header("Location: " . get_protocol() . $_SERVER["HTTP_HOST"] . "/" . $lang . $_SERVER["REQUEST_URI"]);
  94. return $lang;
  95. }
  96. }
  97. /*****************************************************
  98. * This function parses the language prefrences of *
  99. * the client broser, comparing them to th languages *
  100. * offered by the site. *
  101. * *
  102. * @params: *
  103. * available_languages: (string array) Contains *
  104. * a list of strins offered *
  105. * by the site. *
  106. * http_accept_language: (string) Raw header with *
  107. * info about client *
  108. * language preferences. *
  109. * @return: (string array) List of the languages *
  110. * offered, sorted by prefference. *
  111. *****************************************************/
  112. function prefered_language(array $available_languages, $http_accept_language) {
  113. $available_languages = array_flip($available_languages);
  114. $langs;
  115. preg_match_all("~([\w-]+)(?:[^,\d]+([\d.]+))?~", strtolower($http_accept_language), $matches, PREG_SET_ORDER);
  116. foreach($matches as $match) {
  117. list($a, $b) = explode("-", $match[1]) + array("", "");
  118. $value = isset($match[2]) ? (float) $match[2] : 1.0;
  119. if(isset($available_languages[$match[1]])) {
  120. $langs[$match[1]] = $value;
  121. continue;
  122. }
  123. if(isset($available_languages[$a])) {
  124. $langs[$a] = $value - 0.1;
  125. }
  126. }
  127. arsort($langs);
  128. return $langs;
  129. }
  130. /*****************************************************
  131. * This function turns a date string into a human *
  132. * readable string, deppending o the specified *
  133. * language. *
  134. * *
  135. * @params: *
  136. * strdate: (string): Date string. *
  137. * lang: (string): Language code (es, en, eu). *
  138. * time: (boolean): Append the time at the end. *
  139. * @return: (string): Formatted date string. *
  140. *****************************************************/
  141. function format_date($strdate, $lang, $time = true){
  142. $date = strtotime($strdate);
  143. $year = date("o", $date);
  144. $month = date("n", $date);
  145. $month --;
  146. $day = date("j", $date);
  147. $wday = date("N", $date);
  148. $wday --;
  149. $hour = date("H", $date);
  150. $minute = date("i", $date);
  151. switch ($lang){
  152. case "en":
  153. $week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
  154. $months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  155. if ($time){
  156. $str = "$week[$wday], $months[$month] $day, $year at $hour:$minute";
  157. }
  158. else{
  159. $str = "$week[$wday], $months[$month] $day, $year";
  160. }
  161. break;
  162. case "eu":
  163. $week = ["astelehena", "asteartea", "asteazkena", "osteguna", "ostirala", "larumbata", "igandea"];
  164. $months = ["urtarrilaren", "otsailaren", "martxoaren", "apirilaren", "maiatzaren", "ekainaren", "uztailaren", "abuztuaren", "irailaren", "urriaren", "azaroaren", "abenduaren"];
  165. if ($time){
  166. $str = $year . "ko $months[$month] $day" . "an, $week[$wday], $hour:$minute";
  167. }
  168. else{
  169. $str = $year . "ko $months[$month] $day" . "an, $week[$wday]";
  170. }
  171. break;
  172. default:
  173. $week = ["Lunes", "Martes", "Mi&eacute;rcoles", "Jueves", "Viernes", "S&aacute;bado", "Domingo"];
  174. $months = ["enero", " febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"];
  175. if ($time){
  176. $str = "$week[$wday] $day de $months[$month] de $year a las $hour:$minute";
  177. }
  178. else{
  179. $str = "$week[$wday] $day de $months[$month] de $year";
  180. }
  181. }
  182. return $str;
  183. }
  184. /*****************************************************
  185. * Generates a URL-valid string from a regular one. *
  186. * *
  187. * @params: *
  188. * text: (string): Original string. *
  189. * @return: (string): URL-valid string. *
  190. *****************************************************/
  191. function permalink($text){
  192. $unwanted_array = array("Š"=>"S", "š"=>"s", "Ž"=>"Z", "ž"=>"z", "À"=>"A", "Á"=>"A", "Â"=>"A", "Ã"=>"A", "Ä"=>"A", "Å"=>"A", "Æ"=>"A", "Ç"=>"C", "È"=>"E", "É"=>"E",
  193. "Ê"=>"E", "Ë"=>"E", "Ì"=>"I", "Í"=>"I", "Î"=>"I", "Ï"=>"I", "Ñ"=>"N", "Ò"=>"O", "Ó"=>"O", "Ô"=>"O", "Õ"=>"O", "Ö"=>"O", "Ø"=>"O", "Ù"=>"U",
  194. "Ú"=>"U", "Û"=>"U", "Ü"=>"U", "Ý"=>"Y", "Þ"=>"B", "ß"=>"Ss", "à"=>"a", "á"=>"a", "â"=>"a", "ã"=>"a", "ä"=>"a", "å"=>"a", "æ"=>"a", "ç"=>"c",
  195. "è"=>"e", "é"=>"e", "ê"=>"e", "ë"=>"e", "ì"=>"i", "í"=>"i", "î"=>"i", "ï"=>"i", "ð"=>"o", "ñ"=>"n", "ò"=>"o", "ó"=>"o", "ô"=>"o", "õ"=>"o",
  196. "ö"=>"o", "ø"=>"o", "ù"=>"u", "ú"=>"u", "û"=>"u", "ý"=>"y", "þ"=>"b", "ÿ"=>"y" );
  197. $str = strtr( $text, $unwanted_array );
  198. $str = preg_replace("/[^\da-zA-Z ]/i", "", $str);
  199. $str = str_replace(" ", "-", $str);
  200. return $str;
  201. }
  202. /*****************************************************
  203. * Retrieves a text fragment from the database. *
  204. * *
  205. * @params: *
  206. * con (Mysql connection): Connection handler. *
  207. * id: (string): Text identifier. *
  208. * lang: (string): Language identifier. *
  209. * @return: (string): Text. *
  210. *****************************************************/
  211. function text($con, $id, $lang){
  212. $q = mysqli_query($con, "SELECT text, file FROM text WHERE id = '$id' AND lang = '$lang';");
  213. $r = mysqli_fetch_array($q);
  214. if (strlen($r["file"]) > 0){
  215. return file_get_contents($_SERVER["DOCUMENT_ROOT"] . "string/" . $r["file"]);
  216. }
  217. else{
  218. return $r["text"];
  219. }
  220. }
  221. /*****************************************************
  222. * This function closes all the opened HTML tags in *
  223. * a given string. *
  224. * *
  225. * @params: *
  226. * html: (string): The string with HTML tags. *
  227. * @return: (string): HTML with closed tags. *
  228. *****************************************************/
  229. function close_tags($html) {
  230. preg_match_all("#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU", $html, $result);
  231. $openedtags = $result[1];
  232. preg_match_all("#</([a-z]+)>#iU", $html, $result);
  233. $closedtags = $result[1];
  234. $len_opened = count($openedtags);
  235. if (count($closedtags) == $len_opened) {
  236. return $html;
  237. }
  238. $openedtags = array_reverse($openedtags);
  239. for ($i=0; $i < $len_opened; $i++) {
  240. if (!in_array($openedtags[$i], $closedtags)) {
  241. $html .= "</".$openedtags[$i].">";
  242. } else {
  243. unset($closedtags[array_search($openedtags[$i], $closedtags)]);
  244. }
  245. }
  246. return $html;
  247. }
  248. /*****************************************************
  249. * Text shortener. Given a string, it trims in the *
  250. * proximity of the desired string, ut to the next *
  251. * white character. If indicated, it will append a *
  252. * link to the full text. *
  253. * *
  254. * @params: *
  255. * text: (string): The text to shorten. *
  256. * length: (int): The desired length. *
  257. * linktext: (string): Text fot the link. *
  258. * link: (string): URI of the full text. *
  259. * @return: (string): Cutted text. *
  260. *****************************************************/
  261. function cut_text($text, $length, $linktext, $link){
  262. if (strlen($text) < $length){
  263. return $text;
  264. }
  265. $cut = substr($text, 0, strpos($text, " ", $length));
  266. $cut = closeTags($cut);
  267. if (strlen($cut) == 0){
  268. $cut = $text;
  269. }
  270. if (strlen($text) != strlen($cut)){
  271. $cut = $cut . "... <a href='$link'>$linktext</a>";
  272. }
  273. return $cut;
  274. }
  275. /*****************************************************
  276. * Finds out the IP address of the client. *
  277. * *
  278. * @return: (String): Client IP address. *
  279. *****************************************************/
  280. function get_ip(){
  281. $client = @$_SERVER["HTTP_CLIENT_IP"];
  282. $forward = @$_SERVER["HTTP_X_FORWARDED_FOR"];
  283. $remote = $_SERVER["REMOTE_ADDR"];
  284. if(filter_var($client, FILTER_VALIDATE_IP)){
  285. $ip = $client;
  286. }
  287. elseif(filter_var($forward, FILTER_VALIDATE_IP)){
  288. $ip = $forward;
  289. }
  290. else{
  291. $ip = $remote;
  292. }
  293. return $ip;
  294. }
  295. /*****************************************************
  296. * Registers the page viewed by the user. If it is *
  297. * first page shown in his visit, it also registers *
  298. * the visit. It will also increase the ad views *
  299. * count (if any was shown). *
  300. * *
  301. * @params: *
  302. * con (Mysql connection): Connection handler. *
  303. * section: (string): Site section being visited. *
  304. * id: (int): ID of the entri being visited *
  305. *****************************************************/
  306. function stats($con, $section, $id){
  307. // Get client data
  308. $ip = get_ip();
  309. $browser_data = get_browser(null, true);
  310. $os = $browser_data["platform"];
  311. $browser = $browser_data["browser"];
  312. $uagent = $browser_data["browser_name_pattern"];
  313. //If bot, do nothing
  314. $bot_kw = Array();
  315. $bot_kw[0] = "bot";
  316. $bot_kw[1] = "spider";
  317. $bot_kw[2] = "crawl";
  318. $bot_kw[3] = ".com";
  319. $bot_kw[4] = ".ru";
  320. $bot_kw[5] = "baidu";
  321. $bot_kw[6] = "survey";
  322. $bot_kw[7] = "scan";
  323. $bot_kw[8] = "feed";
  324. $bot_kw[9] = "bing";
  325. $bot_kw[10] = "yahoo";
  326. $bot_kw[11] = "engine";
  327. $bot_kw[12] = "preview";
  328. $bot_kw[13] = "checker";
  329. $bot_kw[14] = "catalog";
  330. $bot_kw[15] = "accelerator";
  331. $bot_kw[16] = "python";
  332. $bot_kw[14] = "qt";
  333. $bot_kw[15] = "webdav";
  334. $bot_kw[16] = "http";
  335. $bot_kw[17] = "url";
  336. $bot_kw[18] = "fake";
  337. $bot_kw[19] = "library";
  338. $bot_kw[20] = "commerce";
  339. $bot_kw[21] = "htmlbot";
  340. $bot_kw[22] = "fetch";
  341. $bot_kw[23] = "googleb";
  342. $bot_kw[24] = "facebook";
  343. $bot_kw[25] = "whatsapp";
  344. $bot_kw[26] = "pinterest";
  345. $bot_kw[27] = "scrapy";
  346. $bot_kw[28] = "libwww";
  347. $bot_kw[29] = "java standard library";
  348. $bot_kw[30] = "default browser";
  349. $bot_kw[31] = "twingly recon";
  350. $bot_kw[32] = "siteexplorer";
  351. $bot_kw[33] = "yandex";
  352. $bot_kw[34] = "wotbox";
  353. $bot_kw[35] = "apache synapse";
  354. $bot_kw[36] = "catexplorador";
  355. $bot_kw[37] = "internet archive";
  356. $i = 0;
  357. while ($i < sizeof($bot_kw)) {
  358. if (strpos(strtolower($uagent), $bot_kw[$i]) !== false || strpos(strtolower($browser), $bot_kw[$i]) !== false){
  359. mysqli_close($con);
  360. return;
  361. }
  362. $i ++;
  363. }
  364. if (strlen($os) == 0 || strlen($browser) == 0){ // Certain chinese hosting provider makes a lot of requests...
  365. mysqli_close($con);
  366. return;
  367. }
  368. //Look for a visit with the same IP in the last 30 mins.
  369. $q = mysqli_query($con, "SELECT stat_visit.id AS visitid FROM stat_view, stat_visit WHERE visit = stat_visit.id AND stat_view.dtime > DATE_SUB(now(), INTERVAL 30 MINUTE) AND ip = '$ip' AND uagent = '$uagent';");
  370. if (mysqli_num_rows($q) == 0){
  371. mysqli_query($con, "INSERT INTO stat_visit (ip, uagent, os, browser) VALUES ('$ip', '$uagent', '$os', '$browser');");
  372. $q = mysqli_query($con, "SELECT stat_visit.id AS visitid FROM stat_visit WHERE ip = '$ip' AND uagent = '$uagent' ORDER BY stat_visit.id DESC LIMIT 1;");
  373. }
  374. $r = mysqli_fetch_array($q);
  375. $visit = $r['visitid'];
  376. mysqli_query($con, "INSERT INTO stat_view (visit, section, entry) VALUES ($visit, '$section', '$id');");
  377. }
  378. ?>