TEXT_Helper.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. <?php
  2. /**
  3. * DB helper file.
  4. *
  5. * Provides a helper to perform database operations.
  6. *
  7. * @author Iñigo Valentin <i@inigovalentin.com>
  8. * @license https://www.gnu.org/licenses/gpl-3.0.en.html GNU General Public License V3
  9. * @package IV
  10. */
  11. require_once(__DIR__ . "/Helper.php");
  12. /**
  13. * Text helper.
  14. *
  15. * Contains utilities to show and manipulate texts.
  16. *
  17. * @category Helper.
  18. */
  19. final class TEXT extends Helper{
  20. /**
  21. * Selects the language the page will be displayed on.
  22. *
  23. * First, it tries to read the language cookie in the client. If none is set, get the browser
  24. * language preference list. If none is provided or they are not supported, it will use the
  25. * default language.
  26. *
  27. * @return string Lowercase, two-letter language code.
  28. * @todo Refactor to use user definced languages.
  29. */
  30. function select_language(){
  31. // Get available languages from db
  32. $available_languages = array();
  33. $q_lang = mysqli_query($db, "SELECT code FROM lang WHERE active = 1;");
  34. while ($r_lang = mysqli_fetch_array($q_lang))
  35. array_push($available_languages, $r_lang["code"]);
  36. // Is there a language cookie installed on the client?.
  37. header("Cache-control: private");
  38. if (isSet($_COOKIE["lang"])){
  39. $lang = $_COOKIE["lang"];
  40. if (in_array($lang, $available_languages)) return $lang;
  41. }
  42. // If no cookie, select from client browser preferences.
  43. $lang = prefered_language($available_languages, $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
  44. if (in_array($lang, $available_languages)) return $lang;
  45. // If no method was succesfull, default language
  46. $lang = $available_languages[0];
  47. return $lang;
  48. }
  49. /**
  50. * Parses the language prefrences of the client broser, comparing them to the languages
  51. * offered by the site and selects the prefered one among the ones supported.
  52. *
  53. * @param string[] available_languages List of lowercase, two-letter language codes allowed by
  54. * the site.
  55. * @param string http_accept_language Raw header with info about client language preferences.
  56. * @return string Lowercase, two-letter code of the prefered available language.
  57. * @todo Refactor to user user defined languages.
  58. */
  59. function prefered_language(array $available_languages, $http_accept_language) {
  60. $available_languages = array_flip($available_languages);
  61. $langs = [];
  62. preg_match_all(
  63. "~([\w-]+)(?:[^,\d]+([\d.]+))?~", strtolower($http_accept_language),
  64. $matches, PREG_SET_ORDER
  65. );
  66. foreach($matches as $match) {
  67. list($a, $b) = explode("-", $match[1]) + array("", "");
  68. $value = isset($match[2]) ? (float) $match[2] : 1.0;
  69. if(isset($available_languages[$match[1]])) {
  70. $langs[$match[1]] = $value;
  71. continue;
  72. }
  73. if(isset($available_languages[$a])) $langs[$a] = $value - 0.1;
  74. }
  75. if (count($langs) > 0){
  76. arsort($langs);
  77. //return $langs[0];
  78. return array_values($langs)[0];
  79. }
  80. else return 'en';
  81. }
  82. /**
  83. * Returns a date string into a human readable string on the specified language. Only works
  84. * for spanish, basque and english.
  85. *
  86. * @param string $str_date Date string ('yyyy-mm-dd' or 'yyyy-mm-dd HH:MM:SS')
  87. * @param string $lang Language code (es, en, eu).
  88. * @param string $time Append the time at the end.
  89. * @return string Formatted date string.
  90. */
  91. function format_date($str_date, $lang, $time = true){
  92. $date = strtotime($str_date);
  93. $year = date("o", $date);
  94. $month = date("n", $date);
  95. $month --;
  96. $day = date("j", $date);
  97. $wday = date("N", $date);
  98. $wday --;
  99. $hour = date("H", $date);
  100. $minute = date("i", $date);
  101. switch ($lang){
  102. case "en":
  103. $week = [
  104. "Monday", "Tuesday", "Wednesday", "Thursday",
  105. "Friday", "Saturday", "Sunday"
  106. ];
  107. $months = [
  108. "January", "February", "March", "April", "May", "June",
  109. "July", "August", "September", "October", "November", "December"
  110. ];
  111. if ($time) $str = "$week[$wday], $months[$month] $day, $year at $hour:$minute";
  112. else $str = "$week[$wday], $months[$month] $day, $year";
  113. break;
  114. case "eu":
  115. $week = [
  116. "astelehena", "asteartea", "asteazkena", "osteguna",
  117. "ostirala", "larumbata", "igandea"
  118. ];
  119. $months = [
  120. "urtarrilaren", "otsailaren", "martxoaren", "apirilaren",
  121. "maiatzaren","ekainaren", "uztailaren", "abuztuaren",
  122. "irailaren", "urriaren", "azaroaren", "abenduaren"
  123. ];
  124. if ($time)
  125. $str = $year . "ko $months[$month] $day" . "an, $week[$wday], $hour:$minute";
  126. else $str = $year . "ko $months[$month] $day" . "an, $week[$wday]";
  127. break;
  128. default:
  129. $week = [
  130. "Lunes", "Martes", "Mi&eacute;rcoles", "Jueves",
  131. "Viernes", "S&aacute;bado", "Domingo"
  132. ];
  133. $months = [
  134. "enero", " febrero", "marzo", "abril", "mayo", "junio",
  135. "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"
  136. ];
  137. if ($time)
  138. $str = "$week[$wday] $day de $months[$month] de $year a las $hour:$minute";
  139. else $str = "$week[$wday] $day de $months[$month] de $year";
  140. }
  141. return $str;
  142. }
  143. /**
  144. * Retrieves a text fragment from the database.
  145. *
  146. * @param string $id Text identifier.
  147. * @param bool $html True to decode for HTML.
  148. * @returns string The text, or an empty string if it's not found.
  149. */
  150. public static function get($id, $html = true){
  151. $statement = get_context()->get_db()->prepare(
  152. "SELECT text, file FROM text WHERE id = :id AND lang = :lang"
  153. );
  154. $statement->bindValue(':id', $id, PDO::PARAM_STR);
  155. $statement->bindValue(':lang', get_context()->get_lang(), PDO::PARAM_STR);
  156. $statement->execute();
  157. $row = $statement->fetch(PDO::FETCH_ASSOC);
  158. if ($row !== false){
  159. $text = "";
  160. if (strlen($row["file"]) > 0) $text = file_get_contents(PATH::TEXT . $row["file"]);
  161. else $text = $row["text"];
  162. //$text = utf8_decode($text);
  163. if ($html === true) $text = htmlentities($text, ENT_QUOTES | ENT_SUBSTITUTE);
  164. return $text;
  165. }
  166. else{
  167. Log::error("Text resource with id '$id' not found.");
  168. return "";
  169. }
  170. }
  171. /**
  172. * Retrieves and formats atext fragment from the database.
  173. *
  174. * @param string $id Text identifier.
  175. * @param string[] $fragments Texts to replace each "#" character with.
  176. * @param bool $html True to decode for HTML.
  177. * @returns string The text.
  178. */
  179. public static function compose($id, $fragments, $html = true){
  180. $text = Text::get($id, $html);
  181. foreach ($fragments as $fragment){
  182. $pos = strpos($text, "$");
  183. if ($pos !== false)
  184. $text = substr($text, 0, $pos) . $fragment . substr($text, $pos + 1);
  185. }
  186. return $text;
  187. }
  188. /**
  189. * This function closes all the opened HTML tags in a given string.
  190. *
  191. * @param string html The string with HTML tags.
  192. * @return string HTML with closed tags.
  193. */
  194. function close_tags($html) {
  195. $result = [];
  196. preg_match_all(
  197. "#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU", $html, $result
  198. );
  199. $openedtags = $result[1];
  200. preg_match_all("#</([a-z]+)>#iU", $html, $result);
  201. $closedtags = $result[1];
  202. $len_opened = count($openedtags);
  203. if (count($closedtags) == $len_opened) return $html;
  204. $openedtags = array_reverse($openedtags);
  205. for ($i=0; $i < $len_opened; $i++) {
  206. if (!in_array($openedtags[$i], $closedtags)) $html .= "</".$openedtags[$i].">";
  207. else unset($closedtags[array_search($openedtags[$i], $closedtags)]);
  208. }
  209. return $html;
  210. }
  211. /**
  212. * Text shortener. Given a string, it trims in the proximity of the desired string, up to the
  213. * next white character. If indicated, it will append a link to the full text.
  214. *
  215. * @param string $text The text to shorten.
  216. * @param int $length The desired length.
  217. * @param string $link_text Text for the link. Optional.
  218. * @param string $link URI of the link.
  219. * @return string Shortened text.
  220. */
  221. function cut_text($text, $length, $link_text = "", $link = ""){
  222. if (strlen($text) < $length) return $text;
  223. $cut = substr($text, 0, strpos($text, " ", $length));
  224. $cut = close_tags($cut);
  225. if (strlen($cut) == 0) $cut = $text;
  226. if (strlen($text) != strlen($cut) && strlen($link) > 0 && strlen($link_text) > 0)
  227. $cut = $cut . "... <a href='$link'>$link_text</a>";
  228. return $cut;
  229. }
  230. /**
  231. * Creates the srcset attribute for content images.
  232. *
  233. * Creates 9 different resolutions, from 100px to 900px.
  234. *
  235. * @param string $file Path to the file, relative to $path["img"]["content"]).
  236. * @return string srcset atttribute content.
  237. */
  238. public static function srcset($file){
  239. global $static;
  240. $srcset = "";
  241. $dir = dirname($file);
  242. $name = basename($file);
  243. foreach (range(1, 9) as $d)
  244. $srcset .= $static["content"] . $dir . "/x" . $d . "00/" . $name . " " . $d . "00px, ";
  245. $srcset = rtrim($srcset, ", ");
  246. return $srcset;
  247. }
  248. }