functions.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. * 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. ****************************************************/
  213. function closeTags($html) {
  214. preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
  215. $openedtags = $result[1];
  216. preg_match_all('#</([a-z]+)>#iU', $html, $result);
  217. $closedtags = $result[1];
  218. $len_opened = count($openedtags);
  219. if (count($closedtags) == $len_opened) {
  220. return $html;
  221. }
  222. $openedtags = array_reverse($openedtags);
  223. for ($i=0; $i < $len_opened; $i++) {
  224. if (!in_array($openedtags[$i], $closedtags)) {
  225. $html .= '</'.$openedtags[$i].'>';
  226. } else {
  227. unset($closedtags[array_search($openedtags[$i], $closedtags)]);
  228. }
  229. }
  230. return $html;
  231. }
  232. /****************************************************
  233. * Text shortener. Given a string, it trims in the *
  234. * proximity of the desired streng, ut to the next *
  235. * white character. If indicated, it will append a *
  236. * link to the full text. *
  237. * *
  238. * @params: *
  239. * text: (string): The text to shorten. *
  240. * length: (int): The desired length. *
  241. * linktext: (string): Text fot the link. *
  242. * link: (string): URI of the full text. *
  243. ****************************************************/
  244. function cutText($text, $length, $linktext, $link){
  245. if (strlen($text) < $length){
  246. return $text;
  247. }
  248. $cut = substr($text, 0, strpos($text, " ", $length));
  249. $cut = closeTags($cut);
  250. if (strlen($cut) == 0){
  251. $cut = $text;
  252. }
  253. if (strlen($text) != strlen($cut)){
  254. $cut = $cut . "... <a href='$link'>$linktext</a>";
  255. }
  256. return $cut;
  257. }
  258. /****************************************************
  259. * Increases version value in table settings by one. *
  260. * Helpfull for the app to know when to perform a *
  261. * full sync. Must be called after every INSERT, *
  262. * UPDATE or DELETE query to the database. *
  263. ****************************************************/
  264. function version(){
  265. $con = startdb('rw');
  266. mysqli_query($con, 'UPDATE settings SET value = value + 1 WHERE name = "version";');
  267. }
  268. function ad($con, $lang, $lng){
  269. $id = -1;
  270. //If the user hasn't still see an add on this session
  271. if (isset($_SESSION['ad']) == false){
  272. //25% chance of seeing an add
  273. if (rand (0, 3) == 0){
  274. //Create an array with weighted values
  275. $q = mysqli_query($con, "SELECT id, round(ammount/10) AS value FROM sponsor;");
  276. if (mysqli_num_rows($q) == 0){
  277. return $id;
  278. }
  279. $total = 0;
  280. $sponsors = array();
  281. while ($r = mysqli_fetch_array($q)){
  282. $times = $r['value'];
  283. $id = $r['id'];
  284. for ($i = 0; $i < $times; $i ++) {
  285. array_push($sponsors, $id);
  286. $total ++;
  287. }
  288. }
  289. //Get a random id from the array
  290. $id = $sponsors[rand (0, $total - 1)];
  291. //Get sponsor data
  292. $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;");
  293. $r = mysqli_fetch_array($q);
  294. echo("<div id='ad' class='section'>\n");
  295. echo("<div id='ad_details'>\n");
  296. echo($lng['ad_title']);
  297. echo("<img class='pointer' src='/img/misc/slid-close.png' onClick='closeAd();' />\n");
  298. echo("</div>\n");
  299. echo("<h3><a target='_blank' href='$r[link]'>$r[name]</a></h3>\n");
  300. echo("<div class='entry'>\n");
  301. if (strlen($r['image']) > 0){
  302. echo("<div id='ad_image_container'>\n");
  303. echo("<img src='/img/spo/miniature/$r[image]'/>\n");
  304. echo("</div>\n");
  305. }
  306. echo($r['text']);
  307. 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");
  308. echo("</div>\n");
  309. echo("</div>\n");
  310. echo("<script type='text/javascript'>showAd();</script>\n");
  311. //Set ad as seen
  312. $_SESSION['ad'] = 1;
  313. }
  314. }
  315. return $id;
  316. }
  317. // Function to get visitor ip
  318. function getUserIP(){
  319. $client = @$_SERVER['HTTP_CLIENT_IP'];
  320. $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
  321. $remote = $_SERVER['REMOTE_ADDR'];
  322. if(filter_var($client, FILTER_VALIDATE_IP)){
  323. $ip = $client;
  324. }
  325. elseif(filter_var($forward, FILTER_VALIDATE_IP)){
  326. $ip = $forward;
  327. }
  328. else{
  329. $ip = $remote;
  330. }
  331. return $ip;
  332. }
  333. function stats($ad, $ad_static, $section, $id){
  334. // Get client data
  335. $ip = getUserIP();
  336. $browser_data = get_browser(null, true);
  337. $os = $browser_data['platform'];
  338. $browser = $browser_data['browser'];
  339. $uagent = $browser_data['browser_name_pattern'];
  340. //If bot, do nothing
  341. $bot_kw = Array();
  342. $bot_kw[0] = 'bot';
  343. $bot_kw[1] = 'spider';
  344. $bot_kw[2] = 'crawl';
  345. $bot_kw[3] = '.com';
  346. $bot_kw[4] = '.ru';
  347. $bot_kw[5] = 'baidu';
  348. $bot_kw[6] = 'survey';
  349. $bot_kw[7] = 'scan';
  350. $bot_kw[8] = 'feed';
  351. $bot_kw[9] = 'bing';
  352. $bot_kw[10] = 'yahoo';
  353. $bot_kw[11] = 'engine';
  354. $bot_kw[12] = 'preview';
  355. $bot_kw[13] = 'checker';
  356. $bot_kw[14] = 'catalog';
  357. $bot_kw[15] = 'accelerator';
  358. $bot_kw[16] = 'python';
  359. $bot_kw[14] = 'qt';
  360. $bot_kw[15] = 'webdav';
  361. $bot_kw[16] = 'http';
  362. $bot_kw[17] = 'url';
  363. $bot_kw[18] = 'fake';
  364. $bot_kw[19] = 'library';
  365. $bot_kw[20] = 'commerce';
  366. $bot_kw[21] = 'html';
  367. $bot_kw[22] = 'fetch';
  368. $i = 1;
  369. while ($i < sizeof($bot_kw)) {
  370. if (strpos(strtolower($uagent), $bot_kw[$i]) !== false){
  371. mysqli_close($con);
  372. return;
  373. }
  374. $i ++;
  375. }
  376. //Look for a visit with the same IP in the last 30 mins.
  377. $con = startdb('rw');
  378. $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';");
  379. if (mysqli_num_rows($q) == 0){
  380. mysqli_query($con, "INSERT INTO stat_visit (ip, uagent, os, browser) VALUES ('$ip', '$uagent', '$os', '$browser');");
  381. $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;");
  382. }
  383. $r = mysqli_fetch_array($q);
  384. $visit = $r['visitid'];
  385. mysqli_query($con, "INSERT INTO stat_view (visit, section, entry) VALUES ($visit, '$section', '$id');");
  386. //Increase pop ad advertiser count
  387. if ($ad > 0){
  388. mysqli_query($con, "UPDATE sponsor SET print = print + 1 WHERE id = $ad;");
  389. }
  390. if (is_array($ad_static)){
  391. foreach ($ad_static as &$sponsor) {
  392. mysqli_query($con, "UPDATE sponsor SET print_static = print_static + 1 WHERE id = $sponsor;");
  393. }
  394. }
  395. }
  396. ?>