PageRenderTime 25ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/admin/classes/lib/util.php

https://bitbucket.org/dmcnerney/hockey-registration-system
PHP | 377 lines | 268 code | 86 blank | 23 comment | 85 complexity | ba030b73d738cf02c334d8e25b08ccbc MD5 | raw file
  1. <?php
  2. function rootUrl() {
  3. return (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
  4. }
  5. //-----------------------------------------------------------------------------
  6. function &arr_get(&$arr, $subindex) {
  7. if (!isset($arr[$subindex])) $arr[$subindex] = array();
  8. return $arr[$subindex];
  9. }
  10. function arr_add(&$arr, $subindex, $val) {
  11. if (!isset($arr[$subindex])) $arr[$subindex] = array();
  12. $arr[$subindex][] = $val;
  13. }
  14. # Provide 5.5 functionality
  15. if (!function_exists('array_column')) {
  16. function array_column($input, $column_key) {
  17. return array_map(function($v) use ($column_key) { return $v[$column_key]; }, $input);
  18. }
  19. }
  20. //-----------------------------------------------------------------------------
  21. // Returns a default value for empty value
  22. function emptyValue(&$var, $def) {
  23. if (empty($var)) return $def;
  24. return $var;
  25. }
  26. //-----------------------------------------------------------------------------
  27. function cleanName($player, $format = "Fn LN") {
  28. if (!$player) return $player;
  29. if ($format==='') {
  30. return unicode_trim($player);
  31. }
  32. $player = trim(preg_replace("/[^A-Za-z, ]/", "", $player));
  33. $a = strpos($player, ",");
  34. if ($a) {
  35. $lastname = substr($player, 0, $a);
  36. $b = strpos($player, "," , $a+1);
  37. if (!$b) $b = strlen($player);
  38. $firstname = substr($player, $a+1, $b);
  39. } else {
  40. $c = strrpos($player, " ");
  41. $lastname = substr($player, $c+1);
  42. $firstname = substr($player, 0, $c);
  43. }
  44. $firstname = trim(preg_replace('/[^A-Za-z ]/', '', $firstname));
  45. $lastname = trim(preg_replace('/[^A-Za-z]/', '', $lastname));
  46. if (!$firstname) return cleanName($lastname);
  47. switch ($format) {
  48. case "LN, Fn":
  49. $player = strtoupper($lastname).", ".ucwords(strtolower($firstname));
  50. break;
  51. case "[Fn][LN]":
  52. return array("Fn"=>ucwords(strtolower($firstname)),
  53. "LN"=>strtoupper($lastname));
  54. case "Fn LN":
  55. default:
  56. $player = ucwords(strtolower($firstname))." ".strtoupper($lastname);
  57. break;
  58. }
  59. $player = trim($player);
  60. if ($player == ',') $player = "";
  61. return $player;
  62. }
  63. //-----------------------------------------------------------------------------
  64. function unicode_trim ($str) {
  65. return preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u','',$str);
  66. }
  67. //-----------------------------------------------------------------------------
  68. function phone($player) {
  69. $result = "";
  70. foreach (explode(" ", $player) as $name) {
  71. if (!$name) continue;
  72. if ($result) $result .= " ";
  73. $result .= metaphone($name);
  74. }
  75. return $result;
  76. }
  77. //-----------------------------------------------------------------------------
  78. function seasonStart($ts) {
  79. $year = date('Y', $ts);
  80. $month = date('n', $ts);
  81. if ($month < 8) $year = $year - 1;
  82. return Date::create_from_string($year.".08.01 00:00");
  83. }
  84. function currentSeasonStart() {
  85. $css = \Input::param('css', null);
  86. if ($css == null) $ts = time();
  87. else $ts = strtotime($css);
  88. return seasonStart($ts);
  89. }
  90. //-----------------------------------------------------------------------------
  91. function generatePassword($length) {
  92. return substr(str_pad(rand(0,pow(10,$length)-1),$length,'0'), 0, $length);
  93. }
  94. //-----------------------------------------------------------------------------
  95. function firstThursday($now = null) {
  96. if ($now == null) $now = date('Y-m-d');
  97. $thisMonth = date('M Y',strtotime($now));
  98. $startDate = strtotime("first thursday of $thisMonth + 1 day");
  99. //debug('Date1:'.date('Y-m-d', $startDate)." ".strtotime($now)." B".$startDate);
  100. if (strtotime($now) < $startDate) {
  101. $thisMonth = date('M Y', strtotime(date('Y-m-d', $startDate)." - 20 days"));
  102. $startDate = strtotime("first thursday of $thisMonth + 1 day");
  103. }
  104. return $startDate;
  105. }
  106. function nextFirstThursday($now = null) {
  107. if ($now == null) $now = date('Y-m-d');
  108. $thisMonth = date('M Y',strtotime($now));
  109. $startDate = strtotime("first thursday of $thisMonth + 1 day");
  110. //debug('Date1:'.$now." = ".date('Y-m-d', $startDate)." ".strtotime($now)." B".$startDate);
  111. if (strtotime($now) >= $startDate) {
  112. $thisMonth = date('M Y', strtotime(date('Y-m-20', $startDate)." + 1 month"));
  113. $startDate = strtotime("first thursday of $thisMonth + 1 day");
  114. }
  115. return $startDate;
  116. }
  117. function rangeEnd($now = null) {
  118. $nextThursdayForRange = firstThursday(date('Y-m-d', strtotime($now.' + 3 days')));
  119. $firstThursdayForRange = firstThursday(date('Y-m-d', $nextThursdayForRange - (24*60*60)));
  120. return array($firstThursdayForRange, $nextThursdayForRange);
  121. }
  122. //-----------------------------------------------------------------------------
  123. function parse($str) {
  124. $config = Config::get("config.pattern.team");
  125. $patterns = array();
  126. $replacements = array();
  127. foreach ($config as $pattern) {
  128. $parts = explode($pattern[0], $pattern);
  129. if (count($parts) < 3) continue;
  130. $patterns[] = "/${parts[1]}/i";
  131. $replacements[] = $parts[2];
  132. }
  133. $str = preg_replace($patterns, $replacements, trim($str));
  134. if ($str == '!') return null;
  135. $matches = array();
  136. if (!preg_match('/^([a-z ]*[a-z])(?:\s+([0-9]+))?$/i', trim($str), $matches)) {
  137. throw new Exception("Cannot match team '$str'");
  138. }
  139. $result = array('club'=>$matches[1]);
  140. if (count($matches) > 2) {
  141. $result['team'] = $matches[2];
  142. } else {
  143. $result['team'] = 1;
  144. }
  145. $result['name'] = $result['club'] .' '. $result['team'];
  146. return $result;
  147. }
  148. //-----------------------------------------------------------------------------
  149. function parseCompetition($str, $competitions) {
  150. $config = Config::get("config.pattern.competition");
  151. if (!$config) {
  152. Log::warn("No competition patterns specified");
  153. }
  154. $patterns = array();
  155. $replacements = array();
  156. foreach ($config as $pattern) {
  157. if (trim($pattern) == '') break;
  158. $parts = explode($pattern[0], $pattern);
  159. if (count($parts) < 3) continue;
  160. $patterns[] = "/${parts[1]}/i";
  161. $replacements[] = $parts[2];
  162. }
  163. $newstr = trim(preg_replace($patterns, $replacements, trim($str)));
  164. if ($newstr == '!') return null;
  165. if ($competitions != null && !in_array($newstr, $competitions)) {
  166. throw new Exception("Cannot resolve competition '$newstr' ('$str')");
  167. }
  168. return $newstr;
  169. }
  170. //-----------------------------------------------------------------------------
  171. function strToHex($string){
  172. $hex='';
  173. for ($i=0; $i < strlen($string); $i++){
  174. $hex .= dechex(ord($string[$i]));
  175. }
  176. return $hex;
  177. }
  178. //-----------------------------------------------------------------------------
  179. function arrayToCSV($arr) {
  180. // Create a stream opening it with read / write mode
  181. $stream = fopen('data://text/plain,' . "", 'w+');
  182. // Iterate over the data, writting each line to the text stream
  183. foreach ($data as $val) {
  184. fputcsv($stream, $val);
  185. }
  186. // Rewind the stream
  187. rewind($stream);
  188. // You can now echo it's content
  189. $result = stream_get_contents($stream);
  190. // Close the stream
  191. fclose($stream);
  192. return $result;
  193. }
  194. //-----------------------------------------------------------------------------
  195. function scrape($src, $explain = false) {
  196. libxml_use_internal_errors(true);
  197. $xml = new DOMDocument();
  198. $xml->loadHTML($src);
  199. $xpath = new DOMXPath($xml);
  200. $competition = null;
  201. $date = null;
  202. $fixtures = array();
  203. foreach ($xml->getElementsByTagName('table') as $table) {
  204. if (!($table->getAttribute('class') == 'frData league' || $table->getAttribute('class') == 'frData diagram')) {
  205. continue;
  206. }
  207. foreach ($table->childNodes as $child) {
  208. if ($child->getAttribute('class') == 'competition') {
  209. $competition = $child->childNodes->item(0)->nodeValue;
  210. continue;
  211. }
  212. if ($child->getAttribute('class') == 'date') {
  213. $date = str_replace("/", "-", $child->childNodes->item(0)->nodeValue);
  214. continue;
  215. }
  216. if ($date == null or $competition == null) continue;
  217. $result = array("competition"=>$competition);
  218. if (stripos($child->getAttribute('class'), 'item') !== false) {
  219. foreach ($child->childNodes as $item) {
  220. $key = $item->getAttribute('class');
  221. if ($explain) echo "$key = ".$item->nodeValue."\n";
  222. if ($key == 'time') $result['datetime'] = "$date ".$item->nodeValue;
  223. if ($key == 'homeClub') $result['home'] = $item->nodeValue;
  224. if ($key == 'awayClub') $result['away'] = $item->nodeValue;
  225. if ($key == 'homeScore') $result['home_score'] = $item->nodeValue;
  226. if ($key == 'awayScore') $result['away_score'] = $item->nodeValue;
  227. if ($item->hasChildNodes()) {
  228. $fidspan = $item->childNodes->item(0);
  229. if ($fidspan->nodeName == 'span' and $fidspan->hasAttribute('fid')) {
  230. $result['fixtureID'] = $fidspan->getAttribute('fid');
  231. }
  232. }
  233. }
  234. }
  235. if (isset($result['fixtureID'])) {
  236. if (isset($result['home_score']) && isset($result['away_score'])) {
  237. $result['played'] = 'yes';
  238. if ($explain) echo "Played\n";
  239. }
  240. $fixtures[] = $result;
  241. }
  242. }
  243. }
  244. $fixtureId = 0;
  245. foreach ($xml->getElementsByTagName('link') as $link) {
  246. if (!$link->hasAttribute("rel") || $link->getAttribute("rel") != "canonical") continue;
  247. $matches = array();
  248. if (preg_match('/https?:\/\/[^\/]*\/[^\/]*\/([0-9]*)\/.*/', $link->getAttribute("href"), $matches)) {
  249. $fixtureId = $matches[1] * 1000;
  250. break;
  251. }
  252. }
  253. foreach ($xml->getElementsByTagName('ul') as $elm) {
  254. $classes = $elm->getAttribute("class");
  255. $classes = explode(" ", $classes);
  256. if (!in_array("fixtures", $classes) && !in_array("results", $classes)) continue;
  257. $result = array();
  258. $result['competition'] = $elm->getAttribute("data-compname");
  259. $result['datetime'] = $elm->getAttribute("data-date")." ".$elm->getAttribute("data-time");
  260. $result['home'] = $elm->getAttribute("data-hometeam");
  261. $result['away'] = $elm->getAttribute("data-awayteam");
  262. $result['home_score'] = $elm->getAttribute("data-homescore");
  263. $result['away_score'] = $elm->getAttribute("data-awayscore");
  264. $result['comment'] = $elm->getAttribute("data-comment");
  265. $result['played'] = ($result['home_score'] != '' && $result['away_score'] != '' ? "yes" : "no");
  266. $fixtures[] = $result;
  267. }
  268. usort($fixtures, function($a, $b) {
  269. $rdiff = strcasecmp($a['home'], $b['home']);
  270. if ($rdiff) return $rdiff;
  271. return strcasecmp($a['away'], $b['away']);
  272. });
  273. foreach ($fixtures as &$fixture) {
  274. if (!isset($fixture['fixtureID'])) {
  275. $fixture['fixtureID'] = ++$fixtureId;
  276. }
  277. }
  278. if ($explain) echo "<pre>".print_r($fixtures,true)."</pre>\n";
  279. return $fixtures;
  280. }
  281. //-----------------------------------------------------------------------------
  282. function enqueue($command, $timestamp=null) {
  283. $fp = fopen("../../../queue", "a");
  284. $resultTask = null;
  285. if (flock($fp, LOCK_EX)) {
  286. $task = array('command-endpoint'=>$command);
  287. if ($timestamp) $task['date'] = $timestamp;
  288. fputs($fp, json_encode($task)."\n");
  289. }
  290. fclose($fp);
  291. }