functions.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. * This function closes all the opened HTML tags in *
  190. * a given string. *
  191. * *
  192. * @params: *
  193. * html: (string): The string with HTML tags. *
  194. * @return: (string): HTML with closed tags. *
  195. *****************************************************/
  196. function close_tags($html) {
  197. preg_match_all("#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU", $html, $result);
  198. $openedtags = $result[1];
  199. preg_match_all("#</([a-z]+)>#iU", $html, $result);
  200. $closedtags = $result[1];
  201. $len_opened = count($openedtags);
  202. if (count($closedtags) == $len_opened) {
  203. return $html;
  204. }
  205. $openedtags = array_reverse($openedtags);
  206. for ($i=0; $i < $len_opened; $i++) {
  207. if (!in_array($openedtags[$i], $closedtags)) {
  208. $html .= "</".$openedtags[$i].">";
  209. } else {
  210. unset($closedtags[array_search($openedtags[$i], $closedtags)]);
  211. }
  212. }
  213. return $html;
  214. }
  215. /*****************************************************
  216. * Text shortener. Given a string, it trims in the *
  217. * proximity of the desired string, ut to the next *
  218. * white character. If indicated, it will append a *
  219. * link to the full text. *
  220. * *
  221. * @params: *
  222. * text: (string): The text to shorten. *
  223. * length: (int): The desired length. *
  224. * linktext: (string): Text fot the link. *
  225. * link: (string): URI of the full text. *
  226. * @return: (string): Cutted text. *
  227. *****************************************************/
  228. function cut_text($text, $length, $linktext, $link){
  229. if (strlen($text) < $length){
  230. return $text;
  231. }
  232. $cut = substr($text, 0, strpos($text, " ", $length));
  233. $cut = closeTags($cut);
  234. if (strlen($cut) == 0){
  235. $cut = $text;
  236. }
  237. if (strlen($text) != strlen($cut)){
  238. $cut = $cut . "... <a href='$link'>$linktext</a>";
  239. }
  240. return $cut;
  241. }
  242. /*****************************************************
  243. * Finds out the IP address of the client. *
  244. * *
  245. * @return: (String): Client IP address. *
  246. *****************************************************/
  247. function get_ip(){
  248. $client = @$_SERVER["HTTP_CLIENT_IP"];
  249. $forward = @$_SERVER["HTTP_X_FORWARDED_FOR"];
  250. $remote = $_SERVER["REMOTE_ADDR"];
  251. if(filter_var($client, FILTER_VALIDATE_IP)){
  252. $ip = $client;
  253. }
  254. elseif(filter_var($forward, FILTER_VALIDATE_IP)){
  255. $ip = $forward;
  256. }
  257. else{
  258. $ip = $remote;
  259. }
  260. return $ip;
  261. }
  262. /*****************************************************
  263. * Registers the page viewed by the user. If it is *
  264. * first page shown in his visit, it also registers *
  265. * the visit. It will also increase the ad views *
  266. * count (if any was shown). *
  267. * *
  268. * @params: *
  269. * section: (string): Site section being visited. *
  270. * id: (int): ID of the entri being visited *
  271. *****************************************************/
  272. function stats($section, $id){
  273. // Get client data
  274. $ip = get_ip();
  275. $browser_data = get_browser(null, true);
  276. $os = $browser_data["platform"];
  277. $browser = $browser_data["browser"];
  278. $uagent = $browser_data["browser_name_pattern"];
  279. //If bot, do nothing
  280. $bot_kw = Array();
  281. $bot_kw[0] = "bot";
  282. $bot_kw[1] = "spider";
  283. $bot_kw[2] = "crawl";
  284. $bot_kw[3] = ".com";
  285. $bot_kw[4] = ".ru";
  286. $bot_kw[5] = "baidu";
  287. $bot_kw[6] = "survey";
  288. $bot_kw[7] = "scan";
  289. $bot_kw[8] = "feed";
  290. $bot_kw[9] = "bing";
  291. $bot_kw[10] = "yahoo";
  292. $bot_kw[11] = "engine";
  293. $bot_kw[12] = "preview";
  294. $bot_kw[13] = "checker";
  295. $bot_kw[14] = "catalog";
  296. $bot_kw[15] = "accelerator";
  297. $bot_kw[16] = "python";
  298. $bot_kw[14] = "qt";
  299. $bot_kw[15] = "webdav";
  300. $bot_kw[16] = "http";
  301. $bot_kw[17] = "url";
  302. $bot_kw[18] = "fake";
  303. $bot_kw[19] = "library";
  304. $bot_kw[20] = "commerce";
  305. $bot_kw[21] = "htmlbot";
  306. $bot_kw[22] = "fetch";
  307. $bot_kw[23] = "googleb";
  308. $bot_kw[24] = "facebook";
  309. $bot_kw[25] = "whatsapp";
  310. $bot_kw[26] = "pinterest";
  311. $bot_kw[27] = "scrapy";
  312. $bot_kw[28] = "libwww";
  313. $bot_kw[29] = "java standard library";
  314. $bot_kw[30] = "default browser";
  315. $bot_kw[31] = "twingly recon";
  316. $bot_kw[32] = "siteexplorer";
  317. $bot_kw[33] = "yandex";
  318. $bot_kw[34] = "wotbox";
  319. $bot_kw[35] = "apache synapse";
  320. $bot_kw[36] = "catexplorador";
  321. $bot_kw[37] = "internet archive";
  322. $i = 0;
  323. while ($i < sizeof($bot_kw)) {
  324. if (strpos(strtolower($uagent), $bot_kw[$i]) !== false || strpos(strtolower($browser), $bot_kw[$i]) !== false){
  325. mysqli_close($con);
  326. return;
  327. }
  328. $i ++;
  329. }
  330. if (strlen($os) == 0 || strlen($browser) == 0){ // Certain chinese hosting provider makes a lot of requests...
  331. mysqli_close($con);
  332. return;
  333. }
  334. //Look for a visit with the same IP in the last 30 mins.
  335. $con = startdb("rw");
  336. $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';");
  337. if (mysqli_num_rows($q) == 0){
  338. mysqli_query($con, "INSERT INTO stat_visit (ip, uagent, os, browser) VALUES ('$ip', '$uagent', '$os', '$browser');");
  339. $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;");
  340. }
  341. $r = mysqli_fetch_array($q);
  342. $visit = $r['visitid'];
  343. mysqli_query($con, "INSERT INTO stat_view (visit, section, entry) VALUES ($visit, '$section', '$id');");
  344. }
  345. ?>