functions.php 19 KB

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