functions.php 17 KB

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