functions.php 16 KB

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