functions.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. * @params: *
  10. * mode: (string) Indicates required permissions *
  11. * on database. 'ro' gives read *
  12. * permissions, and 'rw' read and write *
  13. * permissions. Other values will result in *
  14. * errors. *
  15. * @return: (db connection): The connection handler. *
  16. ****************************************************/
  17. function startdb($mode = 'ro'){
  18. //Include the db configuration file. It's somehow like this
  19. /*
  20. <?php
  21. $host = 'XXXX';
  22. $db_name = 'XXXX';
  23. $username_ro = 'XXXX';
  24. $username_rw = 'XXXX';
  25. $pass_ro = 'XXXX';
  26. $pass_rw = 'XXXX';
  27. ?>
  28. */
  29. include('.htpasswd');
  30. //Connect to to database
  31. if ($mode == 'ro')
  32. $con = mysqli_connect($host, $username_ro, $pass_ro, $db_name);
  33. else if ($mode == 'rw'){
  34. $con = mysqli_connect($host, $username_rw, $pass_rw, $db_name);
  35. }
  36. // Check connection
  37. if (mysqli_connect_errno()){
  38. error_log("Failed to connect to database: " . mysqli_connect_error());
  39. return -1;
  40. }
  41. //Set encoding options
  42. mysqli_set_charset($con, 'utf-8');
  43. header('Content-Type: text/html; charset=utf8');
  44. mysqli_query($con, 'SET NAMES utf8;');
  45. //Return the db connection
  46. return $con;
  47. }
  48. /****************************************************
  49. * This function selects the language the page will *
  50. * be displayed inf the page. Several methods are *
  51. * used: cookie detection, and browser language *
  52. * preferences. *
  53. * @return: (string): Language code. *
  54. ****************************************************/
  55. function selectLanguage(){
  56. //Try to read cookie.
  57. header('Cache-control: private');
  58. if (isSet($_COOKIE['lang'])){
  59. $lang = $_COOKIE['lang'];
  60. if ($lang == 'es' || $lang == 'en' || $lang == 'eu'){
  61. return $lang;
  62. }
  63. else{
  64. return 'es';
  65. }
  66. }
  67. //If no cookie, select from client browser preferences.
  68. else{
  69. $available_languages = array("en", "eu", "es");
  70. $langs = prefered_language($available_languages, $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
  71. $lang = $langs[0];
  72. if ($lang != 'es' && $lang != 'en' && $lang != 'eu'){
  73. return 'es';
  74. }
  75. else{
  76. return $langs[0]; //TODO test this
  77. }
  78. }
  79. }
  80. /****************************************************
  81. * This function parses the language prefrences of *
  82. * the client broser, comparing them to th languages *
  83. * offered by the site. *
  84. * the variable $con for futher use everywhere in *
  85. * the php code, and populates the arrays $user *
  86. * and $permission, with info about the user. *
  87. * @params: *
  88. * available_languages: (string array) Contains *
  89. * a list of strins offered *
  90. * by the site. *
  91. * http_accept_language: (string) Raw header with *
  92. * info about client *
  93. * language preferences. *
  94. * @return: (string array) List of the languages *
  95. * offered, sorted by prefference. *
  96. ****************************************************/
  97. function prefered_language(array $available_languages, $http_accept_language) {
  98. $available_languages = array_flip($available_languages);
  99. $langs;
  100. preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER);
  101. foreach($matches as $match) {
  102. list($a, $b) = explode('-', $match[1]) + array('', '');
  103. $value = isset($match[2]) ? (float) $match[2] : 1.0;
  104. if(isset($available_languages[$match[1]])) {
  105. $langs[$match[1]] = $value;
  106. continue;
  107. }
  108. if(isset($available_languages[$a])) {
  109. $langs[$a] = $value - 0.1;
  110. }
  111. }
  112. arsort($langs);
  113. return $langs;
  114. }
  115. /****************************************************
  116. * This function turns a date string into a human *
  117. * readable string, deppending o the specified *
  118. * language. *
  119. * @params: *
  120. * strdate: (string): Date string. *
  121. * lang: (string): Language code (es, en, eu). *
  122. * http_accept_language: (string) Raw header with *
  123. * info about client *
  124. * language preferences. *
  125. * time: (boolean): Append the time at the end. *
  126. * @return: (string array) List of the languages *
  127. * offered, sorted by prefference. *
  128. ****************************************************/
  129. function formatDate($strdate, $lang, $time = true){
  130. $date = strtotime($strdate);
  131. $year = date('o', $date);
  132. $month = date('n', $date);
  133. $month --;
  134. $day = date('j', $date);
  135. $wday = date('N', $date);
  136. $wday --;
  137. $hour = date('H', $date);
  138. $minute = date('i', $date);
  139. switch ($lang){
  140. case 'en':
  141. $week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
  142. $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  143. if ($time){
  144. $str = "$week[$wday], $months[$month] $day, $year at $hour:$minute";
  145. }
  146. else{
  147. $str = "$week[$wday], $months[$month] $day, $year";
  148. }
  149. break;
  150. case 'eu':
  151. $week = ['astelehena', 'asteartea', 'asteazkena', 'osteguna', 'ostirala', 'larumbata', 'igandea'];
  152. $months = ['urtarrilaren', 'otsailaren', 'martxoaren', 'apirilaren', 'maiatzaren', 'ekainaren', 'uztailaren', 'abuztuaren', 'irailaren', 'urriaren', 'azaroaren', 'abenduaren'];
  153. if ($time){
  154. $str = $year . "ko $months[$month] $day" . "an, $week[$wday], $hour:$minute";
  155. }
  156. else{
  157. $str = $year . "ko $months[$month] $day" . "an, $week[$wday]";
  158. }
  159. break;
  160. default:
  161. $week = ['Lunes', 'Martes', 'Mi&eacute;rcoles', 'Jueves', 'Viernes', 'S&aacute;bado', 'Domingo'];
  162. $months = ['enero', ' febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];
  163. if ($time){
  164. $str = "$week[$wday] $day de $months[$month] de $year a las $hour:$minute";
  165. }
  166. else{
  167. $str = "$week[$wday] $day de $months[$month] de $year";
  168. }
  169. }
  170. return $str;
  171. }
  172. /****************************************************
  173. * This function turns a date string into a human *
  174. * readable string, deppending o the specified *
  175. * language. It is designed to be used for festival *
  176. * days only, since it doesnt return the weekday. *
  177. * @params: *
  178. * strdate: (string): Date string. *
  179. * lang: (string): Language code (es, en, eu). *
  180. * http_accept_language: (string) Raw header with *
  181. * info about client *
  182. * language preferences. *
  183. * @return: (string array) List of the languages *
  184. * offered, sorted by prefference. *
  185. ****************************************************/
  186. function formatFestivalDate($strdate, $lang){
  187. $date = strtotime($strdate);
  188. $month = date('n', $date);
  189. $month --;
  190. $day = date('j', $date);
  191. switch ($lang){
  192. case 'en':
  193. $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  194. $str = "$months[$month] $day";
  195. break;
  196. case 'eu':
  197. $months = ['urtarrilaren', 'otsailaren', 'martxoaren', 'apirilaren', 'maiatzaren', 'ekainaren', 'uztailaren', 'abuztuaren', 'irailaren', 'urriaren', 'azaroaren', 'abenduaren'];
  198. $str = "$months[$month] $day";
  199. break;
  200. default:
  201. $months = ['enero', ' febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];
  202. $str = "$day de $months[$month]";
  203. }
  204. return $str;
  205. }
  206. /****************************************************
  207. * Generates a URL-valid string from a regular one. *
  208. * *
  209. * @params: *
  210. * text: (string): Original string. *
  211. * @return: (string): URL-valid string. *
  212. ****************************************************/
  213. function permalink($text){
  214. $unwanted_array = array('Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
  215. 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
  216. 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
  217. 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
  218. 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
  219. $str = strtr( $text, $unwanted_array );
  220. $str = preg_replace('/[^\da-zA-Z ]/i', '', $str);
  221. $str = str_replace(' ', '-', $str);
  222. return $str;
  223. }
  224. /****************************************************
  225. * This function closes all the opened HTML tags in *
  226. * a given string. *
  227. * *
  228. * @params: *
  229. * html: (string): The string with HTML tags *
  230. ****************************************************/
  231. function closeTags($html) {
  232. preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
  233. $openedtags = $result[1];
  234. preg_match_all('#</([a-z]+)>#iU', $html, $result);
  235. $closedtags = $result[1];
  236. $len_opened = count($openedtags);
  237. if (count($closedtags) == $len_opened) {
  238. return $html;
  239. }
  240. $openedtags = array_reverse($openedtags);
  241. for ($i=0; $i < $len_opened; $i++) {
  242. if (!in_array($openedtags[$i], $closedtags)) {
  243. $html .= '</'.$openedtags[$i].'>';
  244. } else {
  245. unset($closedtags[array_search($openedtags[$i], $closedtags)]);
  246. }
  247. }
  248. return $html;
  249. }
  250. /****************************************************
  251. * Text shortener. Given a string, it trims in the *
  252. * proximity of the desired string, ut to the next *
  253. * white character. If indicated, it will append a *
  254. * link to the full text. *
  255. * *
  256. * @params: *
  257. * text: (string): The text to shorten. *
  258. * length: (int): The desired length. *
  259. * linktext: (string): Text fot the link. *
  260. * link: (string): URI of the full text. *
  261. ****************************************************/
  262. function cutText($text, $length, $linktext, $link){
  263. if (strlen($text) < $length){
  264. return $text;
  265. }
  266. $cut = substr($text, 0, strpos($text, " ", $length));
  267. $cut = closeTags($cut);
  268. if (strlen($cut) == 0){
  269. $cut = $text;
  270. }
  271. if (strlen($text) != strlen($cut)){
  272. $cut = $cut . "... <a href='$link'>$linktext</a>";
  273. }
  274. return $cut;
  275. }
  276. /****************************************************
  277. * Increases version value in table settings by one. *
  278. * Helpfull for the app to know when to perform a *
  279. * full sync. Must be called after every INSERT, *
  280. * UPDATE or DELETE query to the database. *
  281. ****************************************************/
  282. function version(){
  283. $con = startdb('rw');
  284. mysqli_query($con, 'UPDATE settings SET value = value + 1 WHERE name = "version";');
  285. }
  286. function ad($con, $lang, $lng){
  287. $id = -1;
  288. //If the user hasn't still see an add on this session
  289. if (isset($_SESSION['ad']) == false){
  290. //25% chance of seeing an add
  291. if (rand (0, 3) == 0){
  292. //Create an array with weighted values
  293. $q = mysqli_query($con, "SELECT id, round(ammount/10) AS value FROM sponsor;");
  294. if (mysqli_num_rows($q) == 0){
  295. return $id;
  296. }
  297. $total = 0;
  298. $sponsors = array();
  299. while ($r = mysqli_fetch_array($q)){
  300. $times = $r['value'];
  301. $id = $r['id'];
  302. for ($i = 0; $i < $times; $i ++) {
  303. array_push($sponsors, $id);
  304. $total ++;
  305. }
  306. }
  307. //Get a random id from the array
  308. $id = $sponsors[rand (0, $total - 1)];
  309. //Get sponsor data
  310. $q = mysqli_query($con, "SELECT name_$lang AS name, text_$lang AS text, image, address_$lang AS address, link, lat, lon FROM sponsor WHERE id = $id;");
  311. $r = mysqli_fetch_array($q);
  312. echo("<div id='ad' class='section'>\n");
  313. echo("<div id='ad_details'>\n");
  314. echo($lng['ad_title']);
  315. echo("<img class='pointer' src='/img/misc/slid-close.png' onClick='closeAd();' />\n");
  316. echo("</div>\n");
  317. echo("<h3><a target='_blank' href='$r[link]'>$r[name]</a></h3>\n");
  318. echo("<div class='entry'>\n");
  319. if (strlen($r['image']) > 0){
  320. echo("<div id='ad_image_container'>\n");
  321. echo("<img src='/img/spo/miniature/$r[image]'/>\n");
  322. echo("</div>\n");
  323. }
  324. echo($r['text']);
  325. if(strlen($r["address"]) > 0){
  326. echo("<br/><br/><a target='_blank' href='https://www.google.es/maps/@$r[lat],$r[lon],14z'><img id='ad_pinpoint' src='/img/misc/pinpoint.png'\>$r[address]</a>\n");
  327. }
  328. echo("</div>\n");
  329. echo("</div>\n");
  330. echo("<script type='text/javascript'>showAd();</script>\n");
  331. //Set ad as seen
  332. $_SESSION['ad'] = 1;
  333. }
  334. }
  335. return $id;
  336. }
  337. // Function to get visitor ip
  338. function getUserIP(){
  339. $client = @$_SERVER['HTTP_CLIENT_IP'];
  340. $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
  341. $remote = $_SERVER['REMOTE_ADDR'];
  342. if(filter_var($client, FILTER_VALIDATE_IP)){
  343. $ip = $client;
  344. }
  345. elseif(filter_var($forward, FILTER_VALIDATE_IP)){
  346. $ip = $forward;
  347. }
  348. else{
  349. $ip = $remote;
  350. }
  351. return $ip;
  352. }
  353. function stats($ad, $ad_static, $section, $id){
  354. // Get client data
  355. $ip = getUserIP();
  356. $browser_data = get_browser(null, true);
  357. $os = $browser_data['platform'];
  358. $browser = $browser_data['browser'];
  359. $uagent = $browser_data['browser_name_pattern'];
  360. //If bot, do nothing
  361. $bot_kw = Array();
  362. $bot_kw[0] = 'bot';
  363. $bot_kw[1] = 'spider';
  364. $bot_kw[2] = 'crawl';
  365. $bot_kw[3] = '.com';
  366. $bot_kw[4] = '.ru';
  367. $bot_kw[5] = 'baidu';
  368. $bot_kw[6] = 'survey';
  369. $bot_kw[7] = 'scan';
  370. $bot_kw[8] = 'feed';
  371. $bot_kw[9] = 'bing';
  372. $bot_kw[10] = 'yahoo';
  373. $bot_kw[11] = 'engine';
  374. $bot_kw[12] = 'preview';
  375. $bot_kw[13] = 'checker';
  376. $bot_kw[14] = 'catalog';
  377. $bot_kw[15] = 'accelerator';
  378. $bot_kw[16] = 'python';
  379. $bot_kw[14] = 'qt';
  380. $bot_kw[15] = 'webdav';
  381. $bot_kw[16] = 'http';
  382. $bot_kw[17] = 'url';
  383. $bot_kw[18] = 'fake';
  384. $bot_kw[19] = 'library';
  385. $bot_kw[20] = 'commerce';
  386. $bot_kw[21] = 'html';
  387. $bot_kw[22] = 'fetch';
  388. $i = 0;
  389. while ($i < sizeof($bot_kw)) {
  390. if (strpos(strtolower($uagent), $bot_kw[$i]) !== false){
  391. mysqli_close($con);
  392. return;
  393. }
  394. $i ++;
  395. }
  396. //Look for a visit with the same IP in the last 30 mins.
  397. $con = startdb('rw');
  398. $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';");
  399. if (mysqli_num_rows($q) == 0){
  400. mysqli_query($con, "INSERT INTO stat_visit (ip, uagent, os, browser) VALUES ('$ip', '$uagent', '$os', '$browser');");
  401. $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;");
  402. }
  403. $r = mysqli_fetch_array($q);
  404. $visit = $r['visitid'];
  405. mysqli_query($con, "INSERT INTO stat_view (visit, section, entry) VALUES ($visit, '$section', '$id');");
  406. //Increase pop ad advertiser count
  407. if ($ad > 0){
  408. mysqli_query($con, "UPDATE sponsor SET print = print + 1 WHERE id = $ad;");
  409. }
  410. if (is_array($ad_static)){
  411. foreach ($ad_static as &$sponsor) {
  412. mysqli_query($con, "UPDATE sponsor SET print_static = print_static + 1 WHERE id = $sponsor;");
  413. }
  414. }
  415. }
  416. ?>