functions.php 16 KB

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