PageRenderTime 34ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 1ms

/download/cache.php

https://github.com/markhoney/nzxmltv
PHP | 2059 lines | 1623 code | 145 blank | 291 comment | 229 complexity | 42c0c722c880a2dbc835193e5baf8bc0 MD5 | raw file
Possible License(s): GPL-3.0
  1. <?php
  2. /*
  3. This file is part of NZ XMLTV Listings.
  4. NZ XMLTV Listings is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. NZ XMLTV Listings is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with NZ XMLTV Listings. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. include '../libs/nzxmltv.php';
  16. ob_start();
  17. connectToDB();
  18. DeclareConstants;
  19. /* Generic Functions */
  20. function echoIfNotSilent($string)
  21. {
  22. echo (runSilently != 'yes' ? $string : NULL);
  23. ob_flush();
  24. flush();
  25. }
  26. function sqlOR($orarray, $fieldName)
  27. {
  28. foreach ($orarray as $or)
  29. {
  30. $sqlStatement = $sqlStatement . $fieldName . "='" . $or . "' OR ";
  31. }
  32. return substr($sqlStatement, 0, -4);
  33. }
  34. function GetPage($url, $saveTo = NULL, $saveFilename = NULL, $minimumFileSize = 2048) //Get a page of data, either from the local filesystem or a website
  35. {
  36. if ($saveTo == '' OR $saveTo == NULL)
  37. {
  38. unset($saveTo);
  39. }
  40. if ($saveFilename == '' OR $saveFilename == NULL)
  41. {
  42. $localFilename = $saveTo . basename($url);
  43. }
  44. else
  45. {
  46. $localFilename = $saveTo . $saveFilename;
  47. }
  48. $fileType = strtolower(pathinfo($localFilename, PATHINFO_EXTENSION));
  49. if (isset($saveTo) AND file_exists($localFilename)) //If the file already exists locally
  50. {
  51. $url = $localFilename; // Change the URL to point to the local version
  52. }
  53. $datapage = file_get_contents($url); //Get the page content
  54. if ($datapage <> '' AND $datapage <> FALSE AND strlen($datapage) > $minimumFileSize) //If the page isn't empty
  55. {
  56. if (isset($saveTo) AND !file_exists($localFilename))
  57. {
  58. if (!file_exists($saveTo)) //If the folder doesn't exist
  59. {
  60. mkdir($saveTo, 0777, true); //Recursively make the folder
  61. }
  62. file_put_contents($localFilename, $datapage); //Save a copy
  63. if (verboseOutput == 'yes')
  64. {
  65. echoIfNotSilent('Cached file ' . $localFilename . '<br />' . "\n");
  66. }
  67. }
  68. if ($fileType <> 'jpg' AND $fileType <> 'jpeg' AND $fileType <> 'gif' AND $fileType <> 'png')
  69. {
  70. $datapage = FixBadCharacters(stripslashes($datapage));
  71. }
  72. return $datapage; //Return the contents of the page
  73. }
  74. }
  75. function DBInsert($table, $sqlArray, $verbose = FALSE)
  76. {
  77. foreach ($sqlArray as $insert => $value)
  78. {
  79. $inserts = $inserts . $insert . ",";
  80. $values = $values . ((is_null($value) OR trim($value)=='') ? "NULL" : "'" . mysql_real_escape_string(trim(html_entity_decode(stripslashes($value)))) . "'") . ",";
  81. }
  82. $sqlQuery = "REPLACE INTO " . $table . " (" . rtrim($inserts, ",") . ") VALUES (" . rtrim($values, ",") . ")";
  83. if ($verbose)
  84. {
  85. //print_r($sqlArray);
  86. //echoIfNotSilent($sqlQuery . "<br />\r\n");
  87. }
  88. mysql_query($sqlQuery) or die(mysql_error());
  89. }
  90. function DBUpdate($table, $sqlArray, $whereArray)
  91. {
  92. foreach ($sqlArray as $column => $value)
  93. {
  94. $values = $values . $column . "=" . ((is_null($value) OR trim($value)=='') ? 'NULL' : "'" . mysql_real_escape_string(trim(html_entity_decode(stripslashes($value)))) . "'") . ",";
  95. }
  96. foreach ($whereArray as $column => $value)
  97. {
  98. $wheres = $wheres . $column . "=" . ((is_null($value) OR trim($value)=='') ? 'NULL' : "'" . mysql_real_escape_string($value) . "'") . " AND ";
  99. }
  100. $sqlQuery = "UPDATE " . $table . " SET " . rtrim($values, ",") . " WHERE " . substr($wheres, 0, -5) . ")";
  101. //echoIfNotSilent($sqlQuery . "<br />\r\n");
  102. mysql_query($sqlQuery) or die(mysql_error());
  103. }
  104. function CreateList($inputArray, $element, $separator)
  105. {
  106. if (is_array($inputArray))
  107. {
  108. foreach ($inputArray as $arrayElement)
  109. {
  110. if (($element = "") or (empty($element)))
  111. {
  112. $item = $arrayElement;
  113. }
  114. else
  115. {
  116. $item = $arrayElement->$element;
  117. }
  118. if (is_string($item))
  119. {
  120. if (trim($item) <> "")
  121. {
  122. $outputList = $outputList . trim($arrayElement->$element) . $separator;
  123. }
  124. }
  125. }
  126. return rtrim($outputList, ",");
  127. }
  128. }
  129. function BlankValue($value, $nullvalue)
  130. {
  131. $return = (($value == $nullvalue OR trim($value) == "") ? "" : $value);
  132. return $return;
  133. }
  134. /* Data scraping */
  135. function TelstraGetListings($datadate, $hours, $package) //Get TV listings for a specified date and number of hours
  136. {
  137. return GetPage(telstraDataURL . 'tvg-gridlist-base.cfm?v=l&c=' . $package . '&h=1&f=' . $hours . '&d=' . $datadate, listingsFolder); //Return the page for relevant day and number of hours (v = view, c = channels, h = hour start, f = number of hours, d = date )
  138. }
  139. /* Channels */
  140. function TelstraGrabChannelPackages()
  141. {
  142. $optionsURL = telstraDataURL . "tvg-grid-top.cfm";
  143. preg_match_all('~<option value="pkg-' .
  144. '(?P<package>.*?)' .
  145. '">~ism',
  146. GetPage($optionsURL /*, listingsFolder */), $packages, PREG_SET_ORDER);
  147. foreach ($packages as $package)
  148. {
  149. preg_match_all('~<td rowspan="1000" align="center" valign="top"><img src="' .
  150. '(?P<url>.*?)' . //Channel Image URL
  151. '" alt="' .
  152. '(?P<name>.*?)' . //Name of channel
  153. '"~ism',
  154. TelstraGetListings(currentDate, 24, 'pkg-' . urlencode($package[package])), $programs, PREG_SET_ORDER); //1 = URL of channel image, 2 = Name of channel, 4 = Details URL for first programme
  155. $packageChannels = '';
  156. foreach ($programs as $program)
  157. {
  158. $result = mysql_query("Select TC_id FROM xmltvChannels WHERE display_name='$program[name]'") or die(mysql_error());
  159. $row = mysql_fetch_assoc($result);
  160. $packageChannels .= $row[TC_id] . ",";
  161. }
  162. $packageChannels = rtrim($packageChannels, ",");
  163. if ($packageChannels <> "")
  164. {
  165. mysql_query("INSERT INTO ChannelPackages (provider,package,channels) VALUES('Telstra','$package[url]','$packageChannels')") or die(mysql_error());
  166. }
  167. }
  168. }
  169. function MergeChannelsTables($source) //Merge data from the Channels table (manually updated) into the Channels table (auto-generated).
  170. {
  171. global $availableSources;
  172. $availableNumbers = array('Sky', 'Freeview', 'Analogue', 'All');
  173. $channels = mysql_query("SELECT * FROM Channels WHERE " . $source . "_id IS NOT NULL");
  174. while ($channel = mysql_fetch_assoc($channels))
  175. {
  176. $channel = CleanQuoteArray($channel);
  177. $saveSources = "";
  178. foreach ($availableSources as $availableSource)
  179. {
  180. $saveSources .= ", " . $availableSource . "_id=" . $channel[$availableSource . '_id'];
  181. }
  182. $saveNumbers = "";
  183. foreach ($availableNumbers as $number)
  184. {
  185. $saveNumbers .= ", " . $number . "_number=" . $channel[$number . '_number'];
  186. }
  187. mysql_query("UPDATE xmltvChannels SET display_name=" . $channel['display_name'] . $saveSources . $saveNumbers . ", large_icon=" . $channel[large_icon] . ", url=" . $channel['url'] . " WHERE " . $source . "_id=" . $channel[$source . '_id']); // or die(mysql_error());
  188. foreach(array('small_icon','genre') as $field)
  189. {
  190. if ($channel[$field] <> 'NULL')
  191. {
  192. mysql_query("UPDATE xmltvChannels SET " . $field . "=" . $channel[$field] . " WHERE " . $source . "_id=" . $channel[$source . '_id']); // or die(mysql_error());
  193. }
  194. }
  195. }
  196. }
  197. function UpdateChannelsTable($display_name, $source, $channel_id, $genre = NULL, $small_icon = NULL)
  198. {
  199. mysql_query("UPDATE xmltvChannels SET display_name='$display_name' WHERE " . $source . "_id='" . $source . "-" . $channel_id . "'"); // or die(mysql_error());
  200. mysql_query("UPDATE xmltvChannels SET " . $source . "_id='" . $source . "-" . $channel_id . "' WHERE display_name='$display_name'"); // or die(mysql_error());
  201. if ($genre <> NULL)
  202. {
  203. $extraFields = ',genre,small_icon';
  204. $extraFieldValues = ",'" . $genre . "','" . $small_icon . "'";
  205. }
  206. mysql_query("INSERT INTO xmltvChannels (" . $source . "_id,display_name" . $extraFields . ") VALUES('" . $source . "-" . $channel_id . "','$display_name'" . $extraFieldValues . ")"); // or die(mysql_error());
  207. }
  208. function TelstraGrabChannelList()
  209. {
  210. $source = 'TC';
  211. $provider = 'Telstra';
  212. $genresURL = telstraDataURL . "tvg-grid-top.cfm";
  213. $channelsURL = telstraDataURL . "tvg-channel-favourites.cfm?v=ga&mf=1";
  214. echoIfNotSilent('<p>');
  215. preg_match_all('~<option value="genre-(?P<code>.*?)">(?P<name>.*?)</option>~ism', GetPage($genresURL, listingsFolder), $genres, PREG_SET_ORDER);
  216. foreach ($genres as &$genre)
  217. {
  218. $genrelist[$genre[code]] = $genre[name];
  219. }
  220. preg_match_all('~\'\)"><img src="' .
  221. '(?P<image>.*?)' .
  222. '" alt="' .
  223. '(?P<id>.*?)' .
  224. '" width="47" height="47" vspace="4" border="0"><a></a><br>' .
  225. '.*?' .
  226. 'value="' .
  227. '(?P<name>.*?)' .
  228. '" genre="' .
  229. '(?P<genre>.*?)' .
  230. '"~ism',
  231. GetPage($channelsURL, listingsFolder), $channels, PREG_SET_ORDER);
  232. foreach ($channels as $channel)
  233. {
  234. $genre = $genrelist[ltrim($channel[genre], "g")];
  235. mysql_query("UPDATE xmltvChannels SET Telstra_genre='" . $genre . "' WHERE " . $source . "_id='" . $source . "-" . $channel[id] . "'");
  236. UpdateChannelsTable($channel[id], $source, $channel[name], $genre, mysql_real_escape_string($channel[image]));
  237. $channelList[$channel[name]] = Array("source" => $source, "name" => $channel[id], "genre" => $genre, "image" => mysql_real_escape_string($channel[image]));
  238. echoIfNotSilent('Added ' . $provider . ' channel ' . $channel[name] . '<br />' . "\n");
  239. }
  240. preg_match_all('~<td rowspan="1000" align="center" valign="top"><img src="' .
  241. '(?P<image>.*?)' . //Channel Image URL
  242. '" alt="' .
  243. '(?P<name>.*?)' . //Name of channel
  244. '" width="47" height="47">' .
  245. '.*?' .
  246. 'openBrWindow\(\'' .
  247. '(?P<url>.*?)' . //Details URL for first programme
  248. '\',~ism',
  249. TelstraGetListings(currentDate, 1, 'all'), $programs, PREG_SET_ORDER); //1 = URL of channel image, 2 = Name of channel, 4 = Details URL for first programme
  250. foreach ($programs as $program)
  251. {
  252. preg_match('~<strong>Channel: </strong></td>' .
  253. '.*?' .
  254. '<strong>' .
  255. '(?P<name>.*?)' . //Channel Name
  256. ' \(' .
  257. '(Channel|Digital|Analogue) ' .
  258. '(?P<number>.*?)' . //Channel Number
  259. '\) </strong></td>~ism',
  260. GetPage(telstraDataURL . $program[url], programsFolder), $channelNumber);
  261. mysql_query("UPDATE xmltvChannels SET " . $provider . "_number='" . $channelNumber[number] . "' WHERE " . $source . "_id='" . $source . "-" . GrabTelstraID($program[4]) . "'");
  262. $channelList[GrabTelstraID($program[url])]["number"] = $channelNumber[number];
  263. }
  264. MergeChannelsTables($source);
  265. echoIfNotSilent('</p>' . "\n");
  266. return $channelList;
  267. }
  268. function YahooGrabChannelList($channelSet)
  269. {
  270. $source = 'YH';
  271. $provider = 'Yahoo';
  272. echoIfNotSilent('<p>');
  273. $channelsURL = "http://nz.tv.yahoo.com/tv-guide/?hour=00&min=00&date=" . date('d') . "&mon=" . date('m') . "&year=" . date('Y') . "&tvrg=" . $channelSet;
  274. //echo $channelsURL . "<br />\r\n";
  275. preg_match_all('~<div class="lt-listing-wrapper"><a href="http://nz.tv.yahoo.com/tv-guide/search/index.html\?venue=' .
  276. '(?P<id>.*?)' .
  277. '&now=' .
  278. '.*?' .
  279. '">' .
  280. '(?P<name>.*?)' .
  281. '</a></div>~ism',
  282. GetPage($channelsURL, listingsFolder), $matches, PREG_SET_ORDER);
  283. foreach ($matches as $match)
  284. {
  285. if ($channelSet . "-" . $match[id] <> "2-20") //If the channel's not a duplicate of TAB Trackside
  286. {
  287. UpdateChannelsTable($match[name], $source, $channelSet . "-" . $match[id]);
  288. $channelList[$channelSet . "-" . $match[is]] = Array("source" => $source, "name" => $match[name]);
  289. echoIfNotSilent('Added ' . $provider . ' channel ' . $match[name] . '<br />' . "\n");
  290. }
  291. }
  292. MergeChannelsTables($source);
  293. echoIfNotSilent('</p>' . "\n");
  294. }
  295. function FreeViewGrabChannelList()
  296. {
  297. $source = 'FV';
  298. $provider = 'Freeview';
  299. echoIfNotSilent('<p>');
  300. $pageXML = new SimpleXMLElement(GetPage('http://freeviewnz.tv/epg_data.php', listingsFolder));
  301. foreach ($pageXML->item as $channel)
  302. {
  303. preg_match('~http://listings.tvnz.co.nz/freeview/(?P<id>.*?)_7days.xml~ism', $channel->url, $tvnzidArray);
  304. /*if ($channel->name == 'TV3 PLUS 1')
  305. {
  306. $tvnzidArray[id] = 'tv3plus1';
  307. }*/
  308. UpdateChannelsTable($channel->name, $source, $tvnzidArray[id]);
  309. echoIfNotSilent('Added ' . $provider . ' channel ' . $channel->name . '<br />' . "\n");
  310. }
  311. MergeChannelsTables($source);
  312. echoIfNotSilent('</p>' . "\n");
  313. }
  314. function SatelliteGrabChannelList()
  315. {
  316. }
  317. function GrabIcons()
  318. {
  319. echoIfNotSilent('<h1>Caching Icons...</h1>' . "\n" . '<p>' . "\n");
  320. foreach (array('small', 'large') as $iconSize)
  321. {
  322. $result = mysql_query("SELECT " . $iconSize . "_icon FROM xmltvChannels WHERE " . $iconSize . "_icon IS NOT NULL");
  323. while ($row = mysql_fetch_assoc($result))
  324. {
  325. GetPage($row[$iconSize . '_icon'], iconsFolder . $iconSize . '/');
  326. }
  327. }
  328. $result = mysql_query("SELECT icon FROM ProgramRatings WHERE icon IS NOT NULL");
  329. while ($row = mysql_fetch_assoc($result))
  330. {
  331. GetPage($row[icon], ratingsFolder);
  332. }
  333. echoIfNotSilent('</p>' . "\n");
  334. }
  335. /* Programs */
  336. function TelstraGrabProgramList($day)
  337. {
  338. $dataDate = date('Y-m-d', strtotime(currentDateSQL . " +" . $day . " days"));
  339. if (preg_match_all('~<td valign="top" class="tvgtime">' .
  340. '(?P<startalt>.*?)' . //Start Time
  341. '</td>' .
  342. '.*?' .
  343. 'onmouseover="return escape\(\'' .
  344. '(?P<genres>.*?)' . //Genre(s)
  345. '<br><b>' .
  346. '(?P<title>.*?)' . //Title
  347. '</b><br><b>' .
  348. '(?P<channel>.*?)' . //Channel
  349. '</b><br><b>' .
  350. '(?P<start>.*?)' . //Start Time
  351. '-' .
  352. '(?P<end>.*?)' . //End Time
  353. '</b>' .
  354. '.*?' .
  355. 'openBrWindow\(\'' .
  356. '(?P<url>.*?)' . //Details URL
  357. '\',' .
  358. '.*?' .
  359. //'<span class="tvgclassification">\(' .
  360. '</a>' .
  361. '(?P<rating>.*?)' . //Age Classification
  362. //'\)</span>~ism',
  363. '</td>~ism',
  364. TelstraGetListings($dataDate, 24, 'all'), $programs, PREG_SET_ORDER) > 0) // 1 = Start Time, 2 = Genre(s), comma delimited, 3 = Title, 4 = Channel, 5 = Start Time, 6 = End Time, 7 = Details URL, 8 = Age Classification
  365. {
  366. foreach ($programs as $program)
  367. {
  368. unset($listing);
  369. $listing['file'] = trim($program[url]);
  370. $programResult = mysql_query("SELECT file FROM xmltvSourcePrograms WHERE file='" . $listing['file'] . "'") or die(mysql_error());
  371. if (mysql_num_rows($programResult) < 1)
  372. {
  373. //$listing['date'] = $dataDate;
  374. preg_match('~&ds=(?P<date>.*?)&st=~ism', $listing['file'], $dateArray);
  375. $startdate = $dateArray[date];
  376. $startTime = FixTime(trim($program[start]));
  377. $stopTime = FixTime(trim($program[end]));
  378. $listing['title'] = trim(htmlspecialchars_decode($program[title]));
  379. $listing['start'] = date('Y-m-d H:i:s', strtotime($startdate . ' ' . $startTime));
  380. //$listing['stop'] = date('Y-m-d H:i:s', strtotime($startdate . ' ' . $stopTime));
  381. $stopDate = $startdate;
  382. if (strtotime($startTime) >= strtotime($stopTime))
  383. {
  384. $stopDate = date('Y-m-d', strtotime($startdate . " +1 day"));;
  385. }
  386. $listing['stop'] = date('Y-m-d H:i:s', strtotime($stopDate . ' ' . $stopTime));
  387. $listing['channel_id'] = "TC-" . GrabTelstraID($listing['file']);
  388. $channelnameresult = mysql_query("SELECT All_id FROM xmltvChannels WHERE TC_id = '" . $listing['channel_id'] . "'") or die(mysql_error());
  389. $channelnamerow = mysql_fetch_assoc($channelnameresult);
  390. $listing['channel'] = $channelnamerow['All_id'];
  391. //$listing['rating'] = trim($program[8]);
  392. preg_match('~<span class="tvgclassification">\((?P<rating>.*?)\)</span>~ism', trim($program[rating]), $ratingArray);
  393. $listing['rating'] = $ratingArray[rating];
  394. if (preg_match('~<td valign="top"><span class="tvbluesml"><strong class="tvhdrpurple"> <br>' . "\r" .
  395. '(?P<title>.*?)' . // Title
  396. '</strong></span>' .
  397. '.*?' .
  398. '<strong class="tvhdrpurple"><img src="' .
  399. telstraImagesURL .
  400. '(?P<image>.*?)' . // TV Channel Image
  401. '" alt="Logo" width="47" height="47"' .
  402. '.*?' .
  403. '<strong>Channel: </strong></td>' .
  404. '.*?' .
  405. '<strong>' .
  406. '(?P<channel>.*?)' . //Channel Name
  407. ' \(' .
  408. '(Channel|Digital|Analogue) ' .
  409. '(?P<number>.*?)' . //Channel Number
  410. '\) </strong></td>' .
  411. '.*?' .
  412. '<strong>Playing: </strong></td>' .
  413. '.*?' .
  414. '<td><strong class="tvbluesml">' .
  415. '(?P<day>.*?)' . //Broadcast Day
  416. ' at ' .
  417. '(?P<time>.*?)' . //Broadcast time
  418. '<!---' .
  419. '.*?' .
  420. '---></strong></td>' .
  421. '.*' .
  422. '<strong>Duration: </strong>' .
  423. '.*?' .
  424. '<td class="tvbluesml">' .
  425. '(?P<duration>.*?)' . //Duration in minutes
  426. ' Minutes</td>' .
  427. '.*?' .
  428. '<strong>Genre: </strong>' .
  429. '.*?' .
  430. '<td class="tvbluesml">' .
  431. '(?P<genre>.*?)' . //Genre
  432. '</td>' .
  433. '.*?' .
  434. '</table>' .
  435. '(?P<description>.*?)' . //Description
  436. '<br>~ism',
  437. GetPage(telstraDataURL . $listing['file'], programsFolder), $details) <> 0) // 1 = Title, 2 = Channel ID, 3 = Channel Name, 4 = Channel Number, 5 = Broadcast Day, 6 = Broadcast time, 7 = Duration in Minutes, 8 = Genre, 9 = Description
  438. {
  439. //$listing['title'] = trim($details[title]);
  440. if (substr($listing['title'], strlen($listing['title']) - 8, 8) == '&laquo; ') { $listing['title'] = substr($listing['title'], 8, strlen($listing['title']) - 8); }
  441. if (substr($listing['title'], 0, 8) == ' &raquo;') { $listing['title'] = substr($listing['title'], 0, strlen($listing['title']) - 8); }
  442. /*preg_match('~ \((.*?)\)$~ism', $listing['title'], $rating);
  443. if (isset($rating[1]))
  444. {
  445. $listing['rating'] = trim($rating[1]);
  446. }*/
  447. //$listing['day'] = trim($details[day]);
  448. //$listing['duration'] = trim($details[duration]);
  449. $listing['category'] = trim($details[genre]);
  450. /*
  451. if ($listing['category'] == 'undefined, default value')
  452. {
  453. unset($listing['category']);
  454. }
  455. */
  456. $listing['description'] = trim(htmlspecialchars_decode($details[description]));
  457. /*
  458. if ($listing['category'] <> "Radio")
  459. {
  460. //$listing['quality'] = 'SD';
  461. }
  462. */
  463. /*
  464. foreach ($listing as $insert => $value)
  465. {
  466. $inserts = $inserts . $insert . ",";
  467. $values = $values . $value . ",";
  468. }
  469. mysql_query("INSERT INTO xmltvSourcePrograms (" . rtrim($inserts, ",") . ") VALUES(" . rtrim($values, ",") . ")") or die(mysql_error());
  470. */
  471. DBInsert("xmltvSourcePrograms", $listing);
  472. if (verboseOutput == 'yes')
  473. {
  474. echoIfNotSilent('Grabbed program ' . $listing['file'] . '<br />' . "\n");
  475. }
  476. }
  477. else
  478. {
  479. if (verboseOutput == 'yes')
  480. {
  481. echoIfNotSilent('Failed to grab program ' . $listing['file'] . '<br />' . "\n");
  482. }
  483. }
  484. }
  485. else
  486. {
  487. if (verboseOutput == 'yes')
  488. {
  489. echoIfNotSilent('Already grabbed program ' . $listing['file'] . '<br />' . "\n");
  490. }
  491. }
  492. }
  493. }
  494. else
  495. {
  496. if (verboseOutput == 'yes')
  497. {
  498. echoIfNotSilent('Failed to grab any program listings for day ' . $day . '<br />' . "\n");
  499. }
  500. }
  501. }
  502. function YahooGrabProgramList($day)
  503. {
  504. foreach (array('0', '2') as $channelSet)
  505. {
  506. for ( $hour = 00; $hour <= 23; $hour += 1)
  507. {
  508. $programsURL = "http://nz.tv.yahoo.com/tv-guide/1/" . $channelSet . "/" . $day . "/" . $hour . "/";
  509. //echoIfNotSilent('<a href="' . $programsURL . '">' . $programsURL . "</a><br />\r\n");
  510. preg_match('~<input type="hidden" id="tvguide-form-start" value="' .
  511. '(?P<time>.*?)' .
  512. '"><input value="' .
  513. '(?P<offset>.*?)' .
  514. '" type="hidden" id="tvguide-form-offset">~ism',
  515. GetPage($programsURL, listingsFolder, $channelSet . "-" . $day . "-" . $hour . ".html", 25000), $programlist);
  516. //echoIfNotSilent($programlist['time'] . "<br />\r\n");
  517. $yesterday = date('Y-m-d', strtotime(date('Y-m-d', $programlist['time'] + ($programlist['offset'] * 60)) . " +" . strval($day - 1) . " days"));
  518. $today = date('Y-m-d', strtotime(date('Y-m-d', $programlist['time'] + ($programlist['offset'] * 60)) . " +" . strval($day) . " days"));
  519. $tomorrow = date('Y-m-d', strtotime(date('Y-m-d', $programlist['time'] + ($programlist['offset'] * 60)) . " +" . strval($day + 1) . " days"));
  520. preg_match_all('~<h3><a href="/tv-guide/channel/' .
  521. '(?P<id>.*?)' .
  522. '/">' .
  523. '(?P<details>.*?)' .
  524. '</ul></div>~ism',
  525. GetPage($programsURL, listingsFolder, $channelSet . "-" . $day . "-" . $hour . ".html"), $channels, PREG_SET_ORDER);
  526. foreach ($channels as $channel)
  527. {
  528. //echoIfNotSilent($channel['id'] . "<br />\r\n");
  529. //echoIfNotSilent(strlen($channel['details']) . "<br />\r\n");
  530. preg_match_all('~<h4 class="title"><a href="/tv-guide/search/' .
  531. '.*?' .
  532. '/">' .
  533. '(?P<title>.*?)' .
  534. '</a></h4>' .
  535. '.*?' .
  536. '<span class="stamp">' .
  537. '(?P<start>.*?)' .
  538. ' - ' .
  539. '(?P<stop>.*?)' .
  540. '</span>' .
  541. '.*?' .
  542. '<dl class="info">' .
  543. '(?P<info>.*?)' .
  544. '</dl>' .
  545. '.*?' .
  546. '<p class="abstract">' .
  547. '(?P<description>.*?)' .
  548. '</p>~ism',
  549. $channel['details'], $programs, PREG_SET_ORDER);
  550. foreach ($programs as $programDetails)
  551. {
  552. unset($sqlArray);
  553. $sqlArray['channel_id'] = "YH-" . $channelSet . "-" . $channel['id'];
  554. $sqlArray['file'] = $sqlArray['channel_id'] . " " . $day . " " . $programDetails[start];
  555. //echoIfNotSilent($sqlArray['file'] . "<br />\r\n");
  556. $channeldetails = mysql_query("SELECT All_id FROM xmltvChannels WHERE YH_id = '" . $sqlArray['channel_id'] . "'") or die(mysql_error());
  557. $channeldetailsrow = mysql_fetch_assoc($channeldetails);
  558. preg_match_all('~<dt>' .
  559. '(?P<item>.*?)' .
  560. ':</dt>' .
  561. '.*?' .
  562. '<dd>' .
  563. '(?P<content>.*?)' .
  564. '</dd>~ism',
  565. $programDetails[info], $info, PREG_SET_ORDER);
  566. foreach ($info as $infoitem) //Classified, Genre
  567. {
  568. $infoarray[$infoitem[item]] = $infoitem[content];
  569. }
  570. $sqlArray['title'] = $programDetails['title'];
  571. $sqlArray['description'] = $programDetails['description'];
  572. $sqlArray['category'] = $infoarray['Genre'];
  573. $sqlArray['channel'] = $channeldetailsrow['All_id'];
  574. $startday = $today;
  575. $stopday = $today;
  576. /*
  577. if (strtotime($programDetails['stop']) < strtotime($programDetails['start']))
  578. {
  579. if ($hour <= 12)
  580. {
  581. $startday = $yesterday;
  582. }
  583. else
  584. {
  585. $stopday = $tomorrow;
  586. }
  587. }
  588. elseif (strtotime($programDetails['start']) < strtotime(strval($hour) . ":00:00 am"))
  589. {
  590. $startday = $tomorrow;
  591. $stopday = $tomorrow;
  592. }
  593. */
  594. if ($hour > 12)
  595. {
  596. if (strtotime($programDetails['start']) < strtotime("12:00:00"))
  597. {
  598. //echoIfNotSilent("Start: " . strtotime($programDetails['start']) . " < " . strtotime("02:00:00") . "<br />\r\n");
  599. $startday = $tomorrow;
  600. }
  601. if (strtotime($programDetails['stop']) < strtotime("12:00:00"))
  602. {
  603. //echoIfNotSilent("Stop: " . strtotime($programDetails['stop']) . " < " . strtotime("04:00:00") . "<br />\r\n");
  604. $stopday = $tomorrow;
  605. }
  606. }
  607. elseif ($hour < 12)
  608. {
  609. if (strtotime($programDetails['start']) > strtotime("12:00:00"))
  610. {
  611. //echoIfNotSilent("Start: " . strtotime($programDetails['start']) . " > " . strtotime("20:00:00") . "<br />\r\n");
  612. $startday = $yesterday;
  613. }
  614. if (strtotime($programDetails['stop']) > strtotime("12:00:00"))
  615. {
  616. //echoIfNotSilent("Stop: " . strtotime($programDetails['stop']) . " > " . strtotime("22:00:00") . "<br />\r\n");
  617. $stopday = $yesterday;
  618. }
  619. }
  620. $sqlArray['start'] = date('Y-m-d H:i:s', strtotime($startday . " " . $programDetails['start']));
  621. $sqlArray['stop'] = date('Y-m-d H:i:s', strtotime($stopday . " " . $programDetails['stop']));
  622. //echoIfNotSilent($sqlArray['start'] . " - " . $sqlArray['stop'] . "<br />\r\n");
  623. $sqlArray['rating'] = $infoarray['Classified'];
  624. DBInsert("xmltvSourcePrograms", $sqlArray);
  625. if (verboseOutput == 'yes')
  626. {
  627. echoIfNotSilent('Grabbed program ' . $filename . '<br />' . "\n");
  628. }
  629. }
  630. }
  631. }
  632. }
  633. }
  634. function FreeViewGrabProgramList()
  635. {
  636. $result = mysql_query("SELECT FV_id, All_id FROM xmltvChannels WHERE FV_id IS NOT NULL") or die(mysql_error());
  637. while ($row = mysql_fetch_assoc($result))
  638. {
  639. $tvnzArray = explode("-", $row[FV_id]);
  640. if ($tvnzArray[1] <> '' AND $tvnzArray[1] <> NULL)
  641. {
  642. $programsURL = "http://listings.tvnz.co.nz/freeview/" . $tvnzArray[1] . "_7days.xml";
  643. /*if ($tvnzArray[1] == 'tv3plus1')
  644. {
  645. $programsURL = "http://listings.tvnz.co.nz/freeview/tv3_7days.xml";
  646. }*/
  647. $freeviewPage = "";
  648. $freeviewPage = GetPage($programsURL, listingsFolder);
  649. if ($freeviewPage <> "")
  650. {
  651. $pageXML = new SimpleXMLElement($freeviewPage);
  652. foreach ($pageXML->channel->programmes->programme as $program)
  653. {
  654. $filename = CleanString($tvnzArray[1] . ' ' . $program['datetime_start']);
  655. $programResult = mysql_query("SELECT file FROM xmltvSourcePrograms WHERE file='" . $filename . "'") or die(mysql_error());
  656. if (mysql_num_rows($programResult) < 1)
  657. {
  658. /*
  659. mysql_query("INSERT INTO xmltvSourcePrograms (file,title,description,channel,start,stop,rating,quality,subtitles,url) VALUES('" . $filename . "','" . CleanString($program->title) . "'," . NullQuoteString(CleanString($program->synopsis)) . ",'" . $row[FV_id] . "','" . FreeViewToSQLTime($program['datetime_start']) . "','" . FreeViewToSQLTime($program['datetime_end']) . "'," . NullQuoteString($program['classification']) . "," . ($program['hd'] == 'Y' ? "'HDTV'" : "NULL") . "," . ($program['captioned'] == 'Y' ? "'teletext'" : "NULL") . "," . NullQuoteString(trim($program['website'])) . ")"); //or die(mysql_error());
  660. if ($tvnzArray[1] == 'tv3plus1')
  661. {
  662. mysql_query("UPDATE xmltvSourcePrograms SET start=start + INTERVAL 1 HOUR, stop=stop + INTERVAL 1 HOUR WHERE file='" . $filename . "'") or die(mysql_error());
  663. }
  664. */
  665. $freeViewStartTime = FreeViewToSQLTime($program['datetime_start']);
  666. $freeViewEndTime = FreeViewToSQLTime($program['datetime_end']);
  667. /*if ($tvnzArray[1] == 'tv3plus1')
  668. {
  669. $freeViewStartTime = date('Y-m-d H:i:s', strtotime($freeViewStartTime . ' +1 hour'));
  670. $freeViewEndTime = date('Y-m-d H:i:s', strtotime($freeViewEndTime . ' +1 hour'));
  671. }*/
  672. $sqlArray['file'] = $filename;
  673. $sqlArray['title'] = $program->title;
  674. $sqlArray['description'] = $program->synopsis;
  675. $sqlArray['channel_id'] = $row['FV_id'];
  676. $sqlArray['channel'] = $row['All_id'];
  677. $sqlArray['start'] = $freeViewStartTime;
  678. $sqlArray['stop'] = $freeViewEndTime;
  679. $sqlArray['rating'] = $program['classification'];
  680. $sqlArray['quality'] = ($program['hd'] == 'Y' ? "'HD'":"");
  681. $sqlArray['subtitles'] = ($program['captioned'] == 'Y' ? "'teletext'":"");
  682. $sqlArray['url'] = $program['website'];
  683. DBInsert("xmltvSourcePrograms", $sqlArray);
  684. //mysql_query("INSERT INTO xmltvSourcePrograms (file,title,description,channel_id,channel,start,stop,rating,quality,subtitles,url) VALUES('" . $filename . "','" . CleanString($program->title) . "'," . NullQuoteString(CleanString($program->synopsis)) . ",'" . $row['FV_id'] . "','" . $row['All_id'] . "','" . $freeViewStartTime . "','" . $freeViewEndTime . "'," . NullQuoteString($program['classification']) . "," . ($program['hd'] == 'Y' ? "'HD'" : "NULL") . "," . ($program['captioned'] == 'Y' ? "'teletext'" : "NULL") . "," . NullQuoteString(trim($program['website'])) . ")"); //or die(mysql_error());
  685. //
  686. if (verboseOutput == 'yes')
  687. {
  688. echoIfNotSilent('Grabbed program ' . $filename . '<br />' . "\n");
  689. }
  690. }
  691. else
  692. {
  693. if (verboseOutput == 'yes')
  694. {
  695. echoIfNotSilent('Already grabbed program ' . $filename . '<br />' . "\n");
  696. }
  697. }
  698. }
  699. }
  700. }
  701. echoIfNotSilent('<h2>Grabbed Freeview data for channel ' . $tvnzArray[1] . '</h2>' . "\n");
  702. }
  703. }
  704. function GeekNZGrabProgramList()
  705. {
  706. //GetPage('http://epg.pvr.geek.nz/epg/listings-all.xml.gz', listingsFolder);
  707. //$fp = gzopen(listingsFolder . 'listings-all.xml.gz', "r");
  708. $fp = gzopen('http://epg.pvr.geek.nz/epg/listings-all.xml.gz', "r");
  709. $contents = gzread($fp, 100000000);
  710. $pageXML = new SimpleXMLElement($contents);
  711. foreach ($pageXML->programme as $program)
  712. {
  713. $start = substr($program['start'], 0, -6);
  714. $stop = substr($program['stop'], 0, -6);
  715. mysql_query("INSERT INTO xmltvSourcePrograms (file,title,description,channel,channel_id,start,stop,url) VALUES('" . $program['channel'] . "-" . $start . "','" . CleanString($program->title) . "'," . NullQuoteString(CleanString($program->desc)) . ",'" . $channel . "','" . $program['channel'] . "','" . $start . "','" . $stop . "'," . NullQuoteString(trim($program->url)) . ")"); //or die(mysql_error());
  716. if (verboseOutput == 'yes')
  717. {
  718. echoIfNotSilent('Grabbed program ' . $program['channel'] . "-" . $start . '<br />' . "\n");
  719. }
  720. }
  721. $channelNames = mysql_query("SELECT All_id,geeksky_id FROM xmltvChannels WHERE geeksky_id IS NOT NULL"); //or die(mysql_error());
  722. while ($channelName = mysql_fetch_assoc($channelNames))
  723. {
  724. mysql_query("UPDATE xmltvSourcePrograms SET channel='" . $channelName['All_id'] . "' WHERE channel_id='" . $channelName['geeksky_id'] . ".sky.co.nz'"); //or die(mysql_error());
  725. }
  726. $channelNames = mysql_query("SELECT All_id,geekfv_id FROM xmltvChannels WHERE geekfv_id IS NOT NULL"); //or die(mysql_error());
  727. while ($channelName = mysql_fetch_assoc($channelNames))
  728. {
  729. mysql_query("UPDATE xmltvSourcePrograms SET channel='" . $channelName['All_id'] . "' WHERE channel_id='" . $channelName['geekfv_id'] . ".freeviewnz.tv'"); //or die(mysql_error());
  730. }
  731. }
  732. function SatellitePerlGrabProgramList()
  733. {
  734. $pageXML = new SimpleXMLElement(GetPage('TVGuide.xml', '/home/administrator/D2XMLTV/'));
  735. foreach ($pageXML->programme as $program)
  736. {
  737. /*if ($current_channel <> $program['channel'])
  738. {
  739. $channelrow = mysql_query("SELECT All_id FROM xmltvChannels WHERE satellite_id='" . $program['channel'] . "'");
  740. $channel_id = mysql_fetch_assoc($channelrow);
  741. $channel = $channel_id['All_id'];
  742. }
  743. $current_channel = $program['channel'];*/
  744. mysql_query("INSERT INTO xmltvSourcePrograms (file,title,description,channel,channel_id,start,stop,url) VALUES('" . $program['channel'] . "-" . $program['start'] . "','" . CleanString($program->title) . "'," . NullQuoteString(CleanString($program->desc)) . ",'" . $channel . "','" . $program['channel'] . "','" . $program['start'] . "','" . $program['stop'] . "'," . NullQuoteString(trim($program->url)) . ")"); //or die(mysql_error());
  745. if (verboseOutput == 'yes')
  746. {
  747. echoIfNotSilent('Grabbed program ' . $program['channel'] . "-" . $program['start'] . '<br />' . "\n");
  748. }
  749. }
  750. $channelNames = mysql_query("SELECT All_id,satellite_id FROM xmltvChannels WHERE satellite_id IS NOT NULL"); //or die(mysql_error());
  751. while ($channelName = mysql_fetch_assoc($channelNames))
  752. {
  753. mysql_query("UPDATE xmltvSourcePrograms SET channel='" . $channelName['All_id'] . "' WHERE channel_id='" . $channelName['satellite_id'] . "'"); //or die(mysql_error());
  754. }
  755. }
  756. function AvenardGrabProgramList()
  757. {
  758. //http://www.avenard.org/iptv/tpg-guide.php
  759. }
  760. /* Fixes */
  761. function FreeViewFixRNZNTimes()
  762. {
  763. $rnznresult = mysql_query("SELECT file, start, stop FROM tempSourcePrograms WHERE channel = 'national'"); //or die(mysql_error());
  764. while ($rnznrow = mysql_fetch_assoc($rnznresult))
  765. {
  766. $changedTime = FALSE;
  767. $roundedstart = date('Y-m-d H:i:s', round(strtotime($rnznrow['start']) / (60 * 5)) * 60 * 5);
  768. if ($rnznrow['start'] <> $roundedstart)
  769. {
  770. $rnznrow['start'] = $roundedstart;
  771. $changedTime = TRUE;
  772. }
  773. $roundedstop = date('Y-m-d H:i:s', round(strtotime($rnznrow['stop']) / (60 * 5)) * 60 * 5);
  774. if ($rnznrow['stop'] <> $roundedstop)
  775. {
  776. $rnznrow['stop'] = $roundedstop;
  777. $changedTime = TRUE;
  778. }
  779. if ($changedTime == TRUE)
  780. {
  781. mysql_query("UPDATE tempSourcePrograms SET start = '" . $rnznrow['start'] . "', stop = '" . $rnznrow['stop'] . "' WHERE file = '" . $rnznrow['file'] . "'") or die(mysql_error());
  782. if (verboseOutput == 'yes')
  783. {
  784. echoIfNotSilent('Fixed time for Radio NZ National program ' . $rnznrow['file'] . '<br />' . "\n");
  785. }
  786. }
  787. }
  788. }
  789. function ReplaceTV1BBCWorld()
  790. {
  791. $channel = 'tv1';
  792. $idsresult = mysql_query("SELECT TC_id, YH_id, FV_id FROM xmltvChannels WHERE All_id = '" . $channel . "'") or die(mysql_error());
  793. $row = mysql_fetch_assoc($idsresult);
  794. $availableSources = array('TC', 'YH', 'FV');
  795. $bbcSource = "TC-BBCV";
  796. foreach ($availableSources as $source)
  797. {
  798. //$channelnameresult = mysql_query("SELECT id FROM xmltvChannels WHERE " . $source . "_id = '" . $row[$source . '_id'] . "'") or die(mysql_error());
  799. //$channelnamerow = mysql_fetch_assoc($channelnameresult);
  800. //$channelid = $channelnamerow['id'];
  801. $bbcresult = mysql_query("SELECT file, start, stop FROM tempSourcePrograms WHERE channel_id = '" . $row[$source . '_id'] . "' AND title LIKE 'BBC World%'"); //or die(mysql_error());
  802. while ($bbcrow = mysql_fetch_assoc($bbcresult))
  803. {
  804. mysql_query("DELETE FROM tempSourcePrograms WHERE file = '" . $bbcrow[file] . "'") or die(mysql_error());
  805. $programsresult = mysql_query("SELECT * FROM tempSourcePrograms WHERE channel_id = '" . $bbcSource . "' AND stop > '" . $bbcrow[start] . "' AND start < '" . $bbcrow[stop] . "' ORDER BY start") or die(mysql_error());
  806. unset($programArray);
  807. while ($programrow = mysql_fetch_assoc($programsresult))
  808. {
  809. $programArray[] = $programrow;
  810. }
  811. if (count($programArray) >= 1)
  812. {
  813. $programArray[0][start] = $bbcrow[start];
  814. if (count($programArray) >= 2)
  815. {
  816. $programArray[count($programArray) - 1][stop] = $bbcrow[stop];
  817. }
  818. foreach ($programArray as $program)
  819. {
  820. $program[file] = $row[$source . '_id'] . " " . $program[start];
  821. $program[channel] = $row[$source . '_id'];
  822. $program = CleanArray($program);
  823. mysql_query("INSERT INTO tempSourcePrograms (file,title,description,channel_id,channel,start,stop,category,rating) VALUES('" . $program[file] . "', '" . $program[title] . "', " . NullQuoteString($program[description]) . ", '" . $program[channel] . "', '" . $channel . "', '" . $program[start] . "', '" . $program[stop] . "', " . NullQuoteString($program[category]) . ", " . NullQuoteString($program[rating]) . ")"); //or die(mysql_error());
  824. if (verboseOutput == 'yes')
  825. {
  826. echoIfNotSilent('Inserted BBC Program ' . $program[file] . '<br />' . "\n");
  827. }
  828. }
  829. }
  830. }
  831. }
  832. }
  833. function FixTitles()
  834. {
  835. $fixesresult = mysql_query("SELECT * FROM ProgramTitleFixes") or die(mysql_error());
  836. while ($fix = mysql_fetch_assoc($fixesresult))
  837. {
  838. mysql_query("UPDATE tempSourcePrograms SET title=$fix[title] WHERE title REGEXP $fix[regex]") or die(mysql_error());
  839. }
  840. }
  841. function FixProblemChannelTimes()
  842. {
  843. //$channelsArray[] = "ctv2";
  844. //$channelsArray[] = "ctv3";
  845. //$channelsArray[] = "discovery";
  846. $channels = mysql_query("SELECT All_id FROM xmltvChannels WHERE fix_times = '1'"); //or die(mysql_error());
  847. while ($channel = mysql_fetch_assoc($channels))
  848. {
  849. FixTimes($channel['All_id']);
  850. }
  851. }
  852. function FixTimes($channel_id)
  853. {
  854. $programsresult = mysql_query("SELECT file, start, stop FROM tempSourcePrograms WHERE channel_id = '" . $channel_id . "' ORDER BY start"); //or die(mysql_error());
  855. while ($program = mysql_fetch_assoc($programsresult))
  856. {
  857. $programdata[] = $program;
  858. }
  859. for ($i = 0; $i < count($programdata) - 1; $i++)
  860. {
  861. //if ($programdata[$i]['start'] == date('Y-m-d H:i:s', strtotime($programdata[$i]['stop'] . " -1 minute")) AND $programdata[$i]['stop'] <> $programdata[$i + 1]['start'])
  862. if ($programdata[$i]['stop'] < $programdata[$i + 1]['start'])
  863. {
  864. mysql_query("UPDATE tempSourcePrograms SET stop = '" . $programdata[$i + 1]['start'] . "' WHERE file = '" . $programdata[$i]['file'] . "'") or die(mysql_error());
  865. if (verboseOutput == 'yes')
  866. {
  867. echoIfNotSilent('Fixed time for program ' . $programdata[$i]['file'] . '<br />' . "\n");
  868. }
  869. }
  870. if ($programdata[$i]['stop'] > $programdata[$i + 1]['start']) //If start and stop are one minute apart
  871. {
  872. mysql_query("UPDATE tempSourcePrograms SET stop = '" . $programdata[$i + 1]['start'] . "' WHERE file = '" . $programdata[$i]['file'] . "'") or die(mysql_error());
  873. if (verboseOutput == 'yes')
  874. {
  875. echoIfNotSilent('Fixed time for program ' . $programdata[$i]['file'] . '<br />' . "\n");
  876. }
  877. }
  878. }
  879. }
  880. function FixBadCharacters($text)
  881. {
  882. /*
  883. $characters['“'] = '"'; // left side double smart quote
  884. $characters['”'] = '"'; // right side double smart quote
  885. $characters['‘'] = "'"; // left side single smart quote
  886. $characters['’'] = "'"; // right side single smart quote
  887. $characters['…'] = "..."; // elipsis
  888. $characters['—'] = "-"; // em dash
  889. $characters['–'] = "-"; // en dash
  890. */
  891. $find = array('‘', '’', '“', '”', '…', '—', '–');
  892. //$find2 = array('‘', '’', '“', '”', '…', '—', '–');
  893. //$find3 = array('‘', '’', '“', '”', '…', '—', '–');
  894. $find2 = array("\\xe2\\x80\\x98", "\\xe2\\x80\\x99", "\\xe2\\x80\\x9c", "\\xe2\\x80\\x9d", "\\xe2\\x80\\xa6", "\\xe2\\x80\\x94", "\\xe2\\x80\\x93");
  895. //é = e acute
  896. $replace = array("'", "'", '"', '"', "...", "-", "-");
  897. return str_replace($find, $replace, str_replace($find2, $replace, $text));
  898. //return str_replace($find, $replace, str_replace($find2, $replace, str_replace($find3, $replace, $text)));
  899. }
  900. function FixDBBadCharacters()
  901. {
  902. /*
  903. $characters['â€Â'] = "â€";
  904. $characters['“'] = '"'; // left side double smart quote
  905. $characters['”'] = '"'; // right side double smart quote
  906. $characters['‘'] = "'"; // left side single smart quote
  907. $characters['’'] = "'"; // right side single smart quote
  908. $characters['…'] = "..."; // elipsis
  909. $characters['—'] = "-"; // em dash
  910. $characters['–'] = "-"; // en dash
  911. */
  912. /*
  913. $characters['’'] = "'";
  914. $characters['‘'] = "'";
  915. $characters['“'] = '"';
  916. $characters['”'] = '"';
  917. $characters['…'] = "...";
  918. $characters['–'] = "-";
  919. $characters['—'] = "-";
  920. print_r($characters);
  921. unset($characters);
  922. */
  923. $characters[] = '‘';
  924. $characters[] = '’';
  925. $characters[] = '“';
  926. $characters[] = '”';
  927. $characters[] = '…';
  928. $characters[] = '—';
  929. $characters[] = '–';
  930. foreach (array("title", "description") as $field)
  931. {
  932. mysql_query("UPDATE tempSourcePrograms SET " . $field . "=REPLACE(" . $field . ", '‘', '\'') WHERE " . $field . " LIKE '%€%'") or die(mysql_error());
  933. mysql_query("UPDATE tempSourcePrograms SET " . $field . "=REPLACE(" . $field . ", '’', '\'') WHERE " . $field . " LIKE '%€%'") or die(mysql_error());
  934. mysql_query("UPDATE tempSourcePrograms SET " . $field . "=REPLACE(" . $field . ", '“', '\"') WHERE " . $field . " LIKE '%€%'") or die(mysql_error());
  935. mysql_query("UPDATE tempSourcePrograms SET " . $field . "=REPLACE(" . $field . ", '”', '\"') WHERE " . $field . " LIKE '%€%'") or die(mysql_error());
  936. mysql_query("UPDATE tempSourcePrograms SET " . $field . "=REPLACE(" . $field . ", '…', '...') WHERE " . $field . " LIKE '%€%'") or die(mysql_error());
  937. mysql_query("UPDATE tempSourcePrograms SET " . $field . "=REPLACE(" . $field . ", '—', '-') WHERE " . $field . " LIKE '%€%'") or die(mysql_error());
  938. mysql_query("UPDATE tempSourcePrograms SET " . $field . "=REPLACE(" . $field . ", '–', '-') WHERE " . $field . " LIKE '%€%'") or die(mysql_error());
  939. foreach ($characters as $find => $replace)
  940. {
  941. //echo "123";
  942. //mysql_query("UPDATE tempSourcePrograms SET " . $field . "=REPLACE(" . $field . ", '" . $find . "', '" . $replace . "') WHERE " . $field . " LIKE '%€%'") or die(mysql_error());
  943. }
  944. }
  945. }
  946. function RemoveGenericTitles()
  947. {
  948. $channels = mysql_query("SELECT All_id, remove_generic FROM xmltvChannels WHERE remove_generic IS NOT NULL"); //or die(mysql_error());
  949. while ($channel = mysql_fetch_assoc($channels))
  950. {
  951. RemoveProgram($channel['All_id'], $channel['remove_generic']);
  952. }
  953. }
  954. function RemoveProgram($channel, $title)
  955. {
  956. $deleteresult = mysql_query("DELETE FROM tempSourcePrograms WHERE channel = '" . $channel . "' AND title='" . $title . "'") or die(mysql_error());
  957. if (verboseOutput == 'yes')
  958. {
  959. echoIfNotSilent($deleteresult . '<br />' . "\n");
  960. }
  961. }
  962. function CleanNullValues()
  963. {
  964. $replacearray[] = "For details please refer to www.wtv.co.nz";
  965. $replacearray[] = "No Description Available";
  966. $replacearray[] = "C42 plays back-to-back alternative music 24-hours a day.";
  967. $replacearray[] = "CCTV International offers a Chinese perspective on international and national events. Available globally, presenting News with in-depth reports, expert analysis and features.";
  968. $replacearray[] = "Direct feed from CCTV4";
  969. $replacearray[] = "Direct feed from MBC";
  970. $replacearray[] = "Direct feed from NHK";
  971. $replacearray[] = "For all the latest sports news from New Zealand and around the world, catch Sport 365 Headlines.";
  972. $replacearray[] = "Programme to be determined.";
  973. $replacearray[] = "STAR PLUS the flagship channel of the STAR network is the undisputed king of Hindi general entertainment in India. Over 65 million viewers tune-in to India's No 1 channel. More info www.startv.com";
  974. $replacearray[] = "Phone the studio on 09 360 4444 or email the dj studio@georgefm.co.nz Visit www.georgefm.co.nz for show schedules.";
  975. $replacearray[] = "100% New Zealand Music";
  976. $replacearray[] = "TBN is the world's largest religious network and America's most watched faith channel. TBN offers 24 hours of commercial-free inspirational programming that appeal to people in a wide variety of Protestant, Catholic and Messianic Jewish denominations.";
  977. $replacearray[] = "Direct feed from MBC";
  978. $replacearray[] = "Wild TV ceased broadcast on July 1st. We apologise for any inconvenience.";
  979. $replacearray[] = "For full programme schedules visit: http://www.dw-world.de/";
  980. $replacearray[] = "What's happening with the weather in your neck of the woods? We bring you the latest in weather information with regular updates from Metservice.";
  981. $replacearray[] = "Your tourism guide to Canterbury. 24 hours a day, 7 days a week.";
  982. //Remove all descriptions where
  983. foreach ($replacearray as $replace)
  984. {
  985. mysql_query("UPDATE tempSourcePrograms SET description=NULL WHERE description= '" . mysql_real_escape_string($replace) . "'") or die(mysql_error());
  986. }
  987. mysql_query("UPDATE tempSourcePrograms SET description=NULL WHERE title = 'Song listings on skytv.co.nz'") or die(mysql_error());
  988. mysql_query("UPDATE tempSourcePrograms SET category=NULL WHERE category = 'undefined, default value'") or die(mysql_error());
  989. mysql_query("UPDATE tempSourcePrograms SET category='Special Interest' WHERE category = 'Special Interest   '") or die(mysql_error());
  990. }
  991. function FixEmptyTVNZSportExtra()
  992. {
  993. $sportresult = mysql_query("SELECT * FROM tempSourcePrograms WHERE channel = 'FV-tvnzsportextra'"); //or die(mysql_error());
  994. if (mysql_num_rows($sportresult) < 1)
  995. {
  996. }
  997. }
  998. function FixTitleSuffixes()
  999. {
  1000. foreach (Array("The", "A") as $prefix)
  1001. {
  1002. $sqlQuery = "UPDATE tempSourcePrograms SET title=TRIM(CONCAT('" . $prefix . " ', SUBSTR(title, 0, " . strval(0 - (strlen($prefix) + 2)) . "))) WHERE title LIKE '%, " . $prefix . "'";
  1003. //echoIfNotSilent($sqlQuery . "<br />\r\n");
  1004. mysql_query($sqlQuery) or die(mysql_error());
  1005. }
  1006. }
  1007. function FixMoviePrefixes()
  1008. {
  1009. foreach (Array("Popcorn Sessions:", "MTV Movie:", "World Cinema:", "Short Film:", "British Theatre:", "Classic Film:", "Real View:", "MOVIE:", "Rialto Premiere:") as $prefix)
  1010. {
  1011. $sqlQuery = "UPDATE tempSourcePrograms SET title=TRIM(SUBSTR(title, " . strval(strlen($prefix) + 1) . ")), category='Movies' WHERE title LIKE '" . mysql_real_escape_string($prefix) . "%'";
  1012. //echoIfNotSilent($sqlQuery . "<br />\r\n");
  1013. mysql_query($sqlQuery) or die(mysql_error());
  1014. }
  1015. }
  1016. function GetProgramMetadataRepeated()
  1017. {
  1018. $metadataSuffix[0]['searchValue'] = " HD";
  1019. $metadataSuffix[0]['metadataField'] = "quality";
  1020. $metadataSuffix[0]['metadataValue'] = "HD";
  1021. $metadataSuffix[1]['searchValue'] = " (WS)";
  1022. $metadataSuffix[1]['metadataField'] = "aspect";
  1023. $metadataSuffix[1]['metadataValue'] = "16:9";
  1024. foreach (Array("title", "description") as $sourceField)
  1025. {
  1026. foreach ($metadataSuffix as $dataset)
  1027. {
  1028. foreach (Array("", ".") as $valueEnd)
  1029. {
  1030. mysql_query("UPDATE tempSourcePrograms SET " . $dataset['metadataField'] . "='" . $dataset['metadataValue'] . "' WHERE " . $sourceField . " LIKE '%" . $dataset['searchValue'] . $valueEnd . "' AND " . $dataset['metadataField'] . " IS NULL") or die(mysql_error());
  1031. mysql_query("UPDATE tempSourcePrograms SET " . $sourceField . "=TRIM(LEFT(" . $sourceField . ", LENGTH(" . $sourceField . ") " . strval(0 - strlen($dataset['searchValue'])) . ")) WHERE " . $sourceField . " LIKE '%" . $dataset['searchValue'] . $valueEnd . "'") or die(mysql_error());
  1032. }
  1033. }
  1034. }
  1035. $metadataPrefix[0]['searchValue'] = "All New ";
  1036. $metadataPrefix[0]['metadataField'] = "premiere";
  1037. $metadataPrefix[0]['metadataValue'] = "1";
  1038. foreach ($metadataPrefix as $dataset)
  1039. {
  1040. foreach (Array("", ".") as $valueEnd)
  1041. {
  1042. mysql_query("UPDATE tempSourcePrograms SET " . $dataset['metadataField'] . "='" . $dataset['metadataValue'] . "' WHERE " . $sourceField . " LIKE '" . $dataset['searchValue'] . $valueEnd . "%' AND " . $dataset['metadataField'] . " IS NULL") or die(mysql_error());
  1043. mysql_query("UPDATE tempSourcePrograms SET " . $sourceField . "=TRIM(RIGHT(" . $sourceField . ", LENGTH(" . $sourceField . ") " . strval(0 - strlen($dataset['searchValue'])) . ")) WHERE " . $sourceField . " LIKE '" . $dataset['searchValue'] . $valueEnd . "%'") or die(mysql_error());
  1044. }
  1045. }
  1046. $sqlQuery = "UPDATE tempSourcePrograms SET year=RIGHT(description, 4), description=TRIM(LEFT(description, LENGTH(description) - 4)) WHERE description RLIKE '(19|20)[0-9]{2}$'";
  1047. //echoIfNotSilent($sqlQuery . "<br />\r\n");
  1048. mysql_query($sqlQuery) or die(mysql_error());
  1049. foreach (Array(".", "") as $yearend)
  1050. {
  1051. $sqlQuery = "UPDATE tempSourcePrograms SET year=CONVERT(SUBSTRING(description, LENGTH(description) " . strval(0 - strlen("1948)" . $yearend) + 2) . ", 4), UNSIGNED INTEGER), description=TRIM(LEFT(description, LENGTH(description) " . strval(0 - strlen("(1984)" . $yearend)) . ")) WHERE description RLIKE '(19|20)[0-9]{2}" . $yearend . "$'";
  1052. //echoIfNotSilent($sqlQuery . "<br />\r\n");
  1053. mysql_query($sqlQuery) or die(mysql_error());
  1054. }
  1055. foreach (Array("Starring:", "Starring ", "Stars:") as $starringtext)
  1056. {
  1057. $programs = mysql_query("SELECT file, description FROM tempSourcePrograms WHERE description RLIKE '" . $starringtext . "[[:alpha:][.space.][.comma.][.hyphen.][.apostrophe.]]+[[.period.]]{0,1}$'") or die(mysql_error());
  1058. while ($program = mysql_fetch_assoc($programs))
  1059. {
  1060. preg_match("~" . $starringtext . "(?P<actors>[a-zA-Z ,\-\']+\.{0,1})$~ism", $program['description'], $result);
  1061. if (!is_null($result))
  1062. {
  1063. $sqlQuery = "UPDATE tempSourcePrograms SET actors='" . mysql_real_escape_string(trim(rtrim(str_replace(", ", ",", $result['actors']), "."))) . "', description=TRIM(LEFT(description, LENGTH(description) " . strval(0 - strlen($starringtext . $result['actors'] . ".")) . ")) WHERE file='" . mysql_real_escape_string($program['file']) . "'";
  1064. //echoIfNotSilent($sqlQuery . "<br />\r\n");
  1065. mysql_query($sqlQuery) or die(mysql_error());
  1066. }
  1067. }
  1068. }
  1069. foreach (Array("Director:", "Dir:", "Directed by ") as $directortext)
  1070. {
  1071. $programs = mysql_query("SELECT file, description FROM tempSourcePrograms WHERE description RLIKE '" . $directortext . "[[:alpha:][.space.][.comma.][.hyphen.][.apostrophe.]]+[[.period.]]{0,1}$'") or die(mysql_error());
  1072. while ($program = mysql_fetch_assoc($programs))
  1073. {
  1074. preg_match("~" . $directortext . "(?P<directors>[a-zA-Z ,\-\']+\.{0,1})$~ism", $program['description'], $result);
  1075. if (!is_null($result))
  1076. {
  1077. $sqlQuery = "UPDATE tempSourcePrograms SET directors='" . mysql_real_escape_string(trim(rtrim(str_replace(", ", ",", $result['directors']), "."))) . "', description=TRIM(LEFT(description, LENGTH(description) " . strval(0 - strlen($directortext . $result['directors'] . ".")) . ")) WHERE file='" . mysql_real_escape_string($program['file']) . "'";
  1078. //echoIfNotSilent($sqlQuery . "<br />\r\n");
  1079. mysql_query($sqlQuery) or die(mysql_error());
  1080. }
  1081. }
  1082. }
  1083. //Description starting with:
  1084. //FV - 'Jack's Back'.
  1085. //mgm on YH - 2001: or 2001. for films
  1086. //Drama: for YH films
  1087. //Part x:
  1088. //Pt x.
  1089. //Pt 3 of 3. Time:
  1090. //Description ending with:
  1091. // Starring: Julia Roberts. (WS). HD.
  1092. // (2007)
  1093. // Starring: Sean Connery, Michelle Pfeiffer.
  1094. // Starring: Julia Roberts.
  1095. //Thriller: 1988: A jaded New Yorker thinks she has found tranquility in a suburban Arizona town but starts to suspect her husband may be a vicious serial killer as he tries to prove his innocence. Starring: David Keith, Cathy Moriarty
  1096. }
  1097. function GetProgramMetadata()
  1098. {
  1099. $advertArray = Array("Infomercials", "Infomercials.", "Infomercials for your shop at home pleasure.");
  1100. mysql_query("UPDATE tempSourcePrograms SET category='Shopping', description=NULL WHERE " . sqlOR($advertArray, "description")) or die(mysql_error());
  1101. $advertArray = Array("Infomercials", "Home Shopping", "Infomercial 2003");
  1102. mysql_query("UPDATE tempSourcePrograms SET category='Shopping', description=NULL WHERE " . sqlOR($advertArray, "title")) or die(mysql_error());
  1103. foreach (Array(":", ".", " ") as $subtitleend)
  1104. {
  1105. $programs = mysql_query("SELECT file, description FROM tempSourcePrograms WHERE description LIKE '\'%\'" . $subtitleend . "%' AND sub_title IS NULL") or die(mysql_error());
  1106. while ($program = mysql_fetch_assoc($programs))
  1107. {
  1108. preg_match("~^'(?P<subtitle>.*?)'" . $subtitleend . "~ism", $program['description'], $result);
  1109. if (!is_null($result))
  1110. {
  1111. mysql_query("UPDATE tempSourcePrograms SET sub_title='" . mysql_real_escape_string(trim($result['subtitle'])) . "', description=TRIM(RIGHT(description, LENGTH(description) " . strval(0 - strlen("'" . $result['subtitle'] . "'" . $subtitleend)) . ")) WHERE file='" . mysql_real_escape_string($program['file']) . "'") or die(mysql_error());
  1112. }
  1113. }
  1114. }
  1115. foreach (Array(":", ".") as $yearend)
  1116. {
  1117. $sqlQuery = "UPDATE tempSourcePrograms SET year=LEFT(description, 4), description=TRIM(RIGHT(description, LENGTH(description) - 5)) WHERE description RLIKE '^(19|20)[0-9]{2}" . $yearend . "'";
  1118. //echoIfNotSilent($sqlQuery . "<br />\r\n");
  1119. mysql_query($sqlQuery) or die(mysql_error());
  1120. }
  1121. //Description starting with:
  1122. //FV - 'Jack's Back'.
  1123. //mgm on YH - 2001: or 2001. for films
  1124. //Drama: for YH films
  1125. //Part x:
  1126. //Pt x.
  1127. //Pt 3 of 3. Time:
  1128. //Description ending with:
  1129. // Starring: Julia Roberts. (WS). HD.
  1130. // (2007)
  1131. // Starring: Sean Connery, Michelle Pfeiffer.
  1132. // Starring: Julia Roberts.
  1133. }
  1134. function CleanTitlesDescriptions()
  1135. {
  1136. $allprograms = mysql_query("SELECT file, title, sub_title, description FROM tempSourcePrograms"); //or die(mysql_error());
  1137. while ($program = mysql_fetch_assoc($allprograms))
  1138. {
  1139. if ($program['category'] == 'undefined, default value')
  1140. {
  1141. unset($listing['category']);
  1142. }
  1143. $listing['description'] = trim(htmlspecialchars_decode($details[description]));
  1144. if (substr($listing['description'], -2) == 'HD')
  1145. {
  1146. $listing['quality'] = 'HD';
  1147. $listing['description'] = trim(substr($listing['description'], 0, -2));
  1148. }
  1149. else if ($listing['category'] <> "Radio")
  1150. {
  1151. //$listing['quality'] = 'SD';
  1152. }
  1153. if (substr($listing['description'], -4) == '(WS)')
  1154. {
  1155. $listing['aspect'] = '16:9';
  1156. $listing['description'] = trim(substr($listing['description'], 0, -4));
  1157. }
  1158. $listing = CleanArray($listing);
  1159. //At this point, need to clean up...
  1160. //Title
  1161. // Pick the longest one, when ... has been removed from the end of any disagreeing ones
  1162. // Match against the titles that need changing (table ProgramTitleFixes)
  1163. // Remove any title identifiers, such as (HD) and (1975), and convert them to relevant fields (quality, year, aspect, etc). Repeat until no match. If nothing left, undo last match!
  1164. // Dashes,spaces
  1165. // Remove
  1166. //
  1167. //Description
  1168. // Remove any excess info from the program description
  1169. //
  1170. // $10.99 will be charged to your account for each block ordered.
  1171. // Remove, or maybe add newlines (<br />)
  1172. // 6 hourly blocks starts every 3 hours from 9pm.
  1173. // Remove, or maybe add newlines (<br />)
  1174. // www.adultchannel.co.nz for more information
  1175. // Remove
  1176. // Dashes,spaces
  1177. // Remove
  1178. // Episode 12 of 13:
  1179. // Convert to episode number
  1180. // Beginning of description matches title
  1181. // Remove
  1182. //
  1183. //Rating
  1184. // Generate rating icon link
  1185. // e.g. http://www.censorship.govt.nz/img/G-label.gif
  1186. // Fix ratings, for AO
  1187. //
  1188. //Genres
  1189. // Match any channels that broadcast exclusively one genre with that genre (table xmltvChannels, field xmltv_category)
  1190. // Match titles against known genres for programs (table ProgramCategories)
  1191. //Any other fixes currently run against the DB, as this is the only place to run them and remain consistent (apart from when importing the source data, which we don't want to taint)
  1192. }
  1193. }
  1194. /* Program Lookups */
  1195. function DoLookups()
  1196. {
  1197. LookupMovies();
  1198. LookupPrograms();
  1199. }
  1200. function LookupMovies()
  1201. {
  1202. $movielookup = mysql_query("SELECT DISTINCT title FROM tempPrograms WHERE (channel LIKE 'bo2%' OR channel LIKE 'movies%' OR channel = 'rialto' OR channel = 'mgm' OR channel = 'tcm' OR category='Movies And Features' OR category='Movies' OR category='Movie, Drama') AND TIMEDIFF(stop, start) > '01:29:00.00'"); //or die(mysql_error());
  1203. //or length > 2 hours, but not sports channels?
  1204. while ($moviename = mysql_fetch_assoc($movielookup))
  1205. {
  1206. //echoIfNotSilent($moviename['title'] . "<br />\r\n");
  1207. LookupMovie($moviename['title']);
  1208. }
  1209. }
  1210. function LookupMovie($moviename)
  1211. {
  1212. include_once('../libs/TMDb.php');
  1213. $passmatch = 180;
  1214. $sqlArray['listingtitle'] = $moviename;
  1215. $movielookup = mysql_query("SELECT id, combined, title FROM tmdbMatches WHERE listingtitle = '" . CleanString($sqlArray['listingtitle']) . "'") or die(mysql_error());
  1216. if (mysql_num_rows($movielookup) == 0)
  1217. {
  1218. $tmdb = new TMDb(theMovieDBAPIKey);
  1219. $movies = json_decode($tmdb->searchMovie($sqlArray['listingtitle']));
  1220. if ($movies[0] == "Nothing found.")
  1221. {
  1222. $sqlArray['id'] = 0;
  1223. }
  1224. else
  1225. {
  1226. $match = 0;
  1227. $scorematch = 0;
  1228. $namematch = 0;
  1229. $bestscore = $movies[0]->score;
  1230. foreach ($movies as $movie)
  1231. {
  1232. similar_text(strtolower($sqlArray['listingtitle']), strtolower($movie->name), $percentmatch[0]);
  1233. similar_text(strtolower($sqlArray['listingtitle']), strtolower($movie->alternative_name), $percentmatch[1]);
  1234. $scorepercent = $movie->score * 100 / $bestscore;
  1235. foreach ($percentmatch as $namepercent)
  1236. {
  1237. $totalscore = $namepercent + $scorepercent;
  1238. if ($totalscore > $match)
  1239. {
  1240. $match = $totalscore;
  1241. $namematch = $namepercent;
  1242. $scorematch = $scorepercent;
  1243. $movieid = $movie->id;
  1244. $movietitle = $movie->name;
  1245. }
  1246. }
  1247. $sqlArray['title'] = $movietitle;
  1248. $sqlArray['score'] = $scorematch;
  1249. $sqlArray['similar'] = $namematch;
  1250. $sqlArray['combined'] = $match;
  1251. $sqlArray['id'] = $movieid;
  1252. }
  1253. }
  1254. DBInsert("tmdbMatches", $sqlArray);
  1255. //if (($scorematch > 80) and ($namematch > 80) and ($match > $passmatch)) //90, 90 and 180?
  1256. if ($match > $passmatch) //90, 90 and 180?
  1257. {
  1258. $lookupMovie = true;
  1259. }
  1260. }
  1261. else
  1262. {
  1263. $moviedetails = mysql_fetch_assoc($movielookup);
  1264. if ($moviedetails['combined'] > $passmatch)
  1265. {
  1266. $sqlArray['id'] = $moviedetails['id'];
  1267. $tmdb = new TMDb(theMovieDBAPIKey);
  1268. $sqlArray['title'] = $moviedetails['title'];
  1269. $lookupMovie = true;
  1270. }
  1271. }
  1272. if ($lookupMovie == true)
  1273. {
  1274. $movielookup = mysql_query("SELECT id FROM tmdbMovies WHERE id = '" . $sqlArray['id'] . "'") or die(mysql_error());
  1275. if (mysql_num_rows($movielookup) == 0)
  1276. {
  1277. unset($sqlArray['listingtitle']);
  1278. unset($sqlArray['score']);
  1279. unset($sqlArray['similar']);
  1280. unset($sqlArray['combined']);
  1281. $movieobject = json_decode($tmdb->getMovie($sqlArray['id']));
  1282. $separator = ",";
  1283. $sqlArray['title'] = $movieobject[0]->name;
  1284. $sqlArray['poster'] = $movieobject[0]->posters[0]->image->url;
  1285. $sqlArray['fanart'] = $movieobject[0]->backdrops[0]->image->url;
  1286. $sqlArray['sub_title'] = $movieobject[0]->tagline;
  1287. $sqlArray['description'] = BlankValue($movieobject[0]->overview, "No overview found.");
  1288. $sqlArray['genres'] = CreateList($movieobject[0]->genres, "name", $separator);
  1289. $sqlArray['language'] = $movieobject[0]->language;
  1290. $sqlArray['runtime'] = BlankValue($movieobject[0]->runtime, 0);
  1291. $sqlArray['released'] = $movieobject[0]->released;
  1292. $sqlArray['certification'] = $movieobject[0]->certification;
  1293. $sqlArray['rating'] = BlankValue($movieobject[0]->rating, 0);
  1294. $sqlArray['countries'] = CreateList($movieobject[0]->countries, "code", $separator);
  1295. foreach ($movieobject[0]->cast as $castmember)
  1296. {
  1297. switch ($castmember->department)
  1298. {
  1299. case "Directing":
  1300. $directors[] = $castmember->name;
  1301. break;
  1302. case "Writing":
  1303. $writers[] = $castmember->name;
  1304. break;
  1305. case "Actors":
  1306. $actors[] = $castmember->name;
  1307. break;
  1308. }
  1309. }
  1310. $sqlArray['directors'] = CreateList($directors, "", $separator);
  1311. $sqlArray['writers'] = CreateList($writers, "", $separator);
  1312. $sqlArray['actors'] = CreateList($actors, "", $separator);
  1313. $sqlArray['url'] = $movieobject[0]->homepage;
  1314. $sqlArray['trailer'] = $movieobject[0]->trailer;
  1315. $sqlArray['imdb'] = $movieobject[0]->imdb_id;
  1316. DBInsert("tmdbMovies", $sqlArray);
  1317. //echoIfNotSilent($sqlArray['title'] . " (" . $sqlArray['listingname'] . ") " . $sqlArray['combined'] . " (" . $sqlArray['score'] . "/" . $sqlArray['similar'] . ")<br />\r\n");
  1318. }
  1319. }
  1320. $movielookup = mysql_query("SELECT * FROM tmdbMovies JOIN tmdbMatches ON tmdbMovies.id=tmdbMatches.id WHERE tmdbMatches.listingtitle = '" . CleanString($sqlArray['listingtitle']) . "' AND tmdbMatches.combined > '" . $passmatch . "'") or die(mysql_error());
  1321. //$movielookup = mysql_query("SELECT tmdbMovies.*, tmdbMatches.listingtitle FROM tmdbMovies, tmdbMatches ON tmdbMovies.id=tmdbMatches.id WHERE tmdbMatches.listingtitle = '" . CleanString($sqlArray['listingtitle']) . "' AND tmdbMatches.combined > '" . $passmatch . "'") or die(mysql_error());
  1322. $moviedetails = mysql_fetch_assoc($movielookup);
  1323. if (!empty($moviedetails))
  1324. {
  1325. print_r($moviedetails);
  1326. echoIfNotSilent("\r\n<br /><br /><br />\r\n");
  1327. //mysql_query("UPDATE xmltvSourcePrograms SET title='" . $moviedetails['title'] . "' WHERE title='" . $moviedetails['listingtitle'] . "' AND ");
  1328. }
  1329. }
  1330. function LookupPrograms()
  1331. {
  1332. $programlookup = mysql_query("SELECT DISTINCT description, title, sub_title FROM tempPrograms WHERE title='The Simpsons'") or die(mysql_error());
  1333. while ($programname = mysql_fetch_assoc($programlookup))
  1334. {
  1335. //echoIfNotSilent($programname['description'] . "<br />\r\n");
  1336. $programdetails = LookupProgram($programname['title']);
  1337. if (!is_null($programdetails))
  1338. {
  1339. if (is_null($programname['sub_title']))
  1340. {
  1341. $episodedetails = MatchEpisodeByDescription($programdetails['id'], $programname['description']);
  1342. }
  1343. else
  1344. {
  1345. $episodedetails = MatchEpisodeBySubTitle($programdetails['id'], $programname['sub_title']);
  1346. }
  1347. }
  1348. }
  1349. }
  1350. function LookupProgram($programname)
  1351. {
  1352. include_once('../libs/TVDB.php');
  1353. $passmatch = 80;
  1354. $sqlArray['listingtitle'] = $programname;
  1355. $programlookup = mysql_query("SELECT id, title, similar FROM tvdbMatches WHERE listingtitle = '" . CleanString($sqlArray['listingtitle']) . "'") or die(mysql_error());
  1356. if (mysql_num_rows($programlookup) == 0)
  1357. {
  1358. $tvShows = TV_Shows::search($programname);
  1359. if (empty($tvShows[0]))
  1360. {
  1361. $sqlArray['id'] = 0;
  1362. }
  1363. else
  1364. {
  1365. $match = 0;
  1366. foreach ($tvShows as $tvShow)
  1367. {
  1368. similar_text(strtolower($programname), strtolower($tvShow->seriesName), $percentmatch);
  1369. if ($percentmatch > $match)
  1370. {
  1371. $match = $percentmatch;
  1372. $programid = $tvShow->id;
  1373. $programtitle = $tvShow->seriesName;
  1374. }
  1375. }
  1376. $sqlArray['listingtitle'] = $programname;
  1377. $sqlArray['title'] = $programtitle;
  1378. $sqlArray['id'] = $programid;
  1379. $sqlArray['similar'] = $match;
  1380. }
  1381. DBInsert("tvdbMatches", $sqlArray);
  1382. //echoIfNotSilent($scorematch . " - " . $namematch);
  1383. if ($match > $passmatch)
  1384. {
  1385. $lookupProgram = true;
  1386. }
  1387. }
  1388. else
  1389. {
  1390. $programdetails = mysql_fetch_assoc($programlookup);
  1391. if ($programdetails['similar'] > $passmatch)
  1392. {
  1393. $sqlArray['id'] = $programdetails['id'];
  1394. $sqlArray['title'] = $programdetails['title'];
  1395. $lookupProgram = true;
  1396. }
  1397. }
  1398. if ($lookupProgram == true)
  1399. {
  1400. $programlookup = mysql_query("SELECT id FROM tvdbPrograms WHERE id = '" . $sqlArray['id'] . "'") or die(mysql_error());
  1401. if (mysql_num_rows($programlookup) == 0)
  1402. {
  1403. unset($sqlArray['listingtitle']);
  1404. unset($sqlArray['similar']);
  1405. $programobject = TV_Shows::findById($sqlArray['id']);
  1406. $separator = ",";
  1407. $sqlArray['title'] = $programobject->seriesName;
  1408. $sqlArray['description'] = $programobject->overview;
  1409. $sqlArray['genres'] = CreateList($programobject->genres, "", $separator);
  1410. $sqlArray['runtime'] = BlankValue($programobject->runtime, 0);
  1411. $sqlArray['released'] = $programobject->firstAired;
  1412. $sqlArray['rating'] = BlankValue($programobject->rating, 0);
  1413. $sqlArray['actors'] = CreateList($programobject->actors, "", $separator);
  1414. $sqlArray['imdb'] = $programobject->imdbId;
  1415. /*$sqlArray['poster'] = $programobject->posters[0]->image->url;
  1416. $sqlArray['fanart'] = $programobject->backdrops[0]->image->url;
  1417. $sqlArray['language'] = $programobject->language;
  1418. $sqlArray['certification'] = $programobject->certification;
  1419. $sqlArray['countries'] = CreateList($programobject->countries, "code", $separator);
  1420. $sqlArray['url'] = $programobject->homepage;
  1421. $sqlArray['trailer'] = $programobject->trailer;*/
  1422. DBInsert("tvdbPrograms", $sqlArray);
  1423. //echoIfNotSilent($sqlArray['title'] . " (" . $sqlArray['listingname'] . ") " . $sqlArray['combined'] . " (" . $sqlArray['score'] . "/" . $sqlArray['similar'] . ")<br />\r\n");
  1424. }
  1425. }
  1426. //TIMEDIFF(stop, start)
  1427. /*
  1428. if ($programdetails['updated'])
  1429. {
  1430. */
  1431. $programlookup = mysql_query("SELECT * FROM tvdbPrograms JOIN tvdbMatches ON tvdbPrograms.id=tvdbMatches.id WHERE tvdbMatches.listingtitle = '" . CleanString($programname) . "'") or die(mysql_error());
  1432. $programdetails = mysql_fetch_assoc($programlookup);
  1433. if (!empty($programdetails)) //Need a column for last lookup time, and only look for new episodes if more than a week old.
  1434. {
  1435. return $programdetails;
  1436. }
  1437. //LookupEpisodes($sqlArray['id']);
  1438. /*
  1439. }
  1440. */
  1441. }
  1442. function LookupEpisodes($programid)
  1443. {
  1444. $programobject = TV_Shows::findById($programid);
  1445. $season = 0;
  1446. $missingSeason = 0;
  1447. $missingEposide = 0;
  1448. do
  1449. {
  1450. $season = $season + 1;
  1451. $missingSeason = $missingSeason + 1;
  1452. $episode = 0;
  1453. do
  1454. {
  1455. $episode = $episode + 1;
  1456. $episodelookup = mysql_query("SELECT id FROM tvdbEpisodes WHERE id = '" . $sqlArray['id'] . "' AND season='" . $season . "' AND episode='" . $episode . "'") or die(mysql_error());
  1457. if (mysql_num_rows($episodelookup) == 0)
  1458. {
  1459. $tvEpisode = $programobject->getEpisode($season, $episode);
  1460. if (empty($tvEpisode))
  1461. {
  1462. $missingEpisode = $missingEpisode + 1;
  1463. }
  1464. else
  1465. {
  1466. $programlookup = mysql_query("SELECT id FROM tvdbEpisodes WHERE id = '" . $tvEpisode->id . "'") or die(mysql_error());
  1467. if (mysql_num_rows($programlookup) == 0)
  1468. {
  1469. unset($sqlArray);
  1470. $sqlArray['id'] = $tvEpisode->id;
  1471. $sqlArray['program_id'] = $programid;
  1472. $sqlArray['season'] = $tvEpisode->season;
  1473. $sqlArray['episode'] = $tvEpisode->episode;
  1474. $sqlArray['description'] = $tvEpisode->overview;
  1475. $sqlArray['title'] = $tvEpisode->name;
  1476. $sqlArray['released'] = $tvEpisode->firstAired;
  1477. $sqlArray['actors'] = CreateList($tvEpisode->guestStars, "", $separator);
  1478. $sqlArray['directors'] = CreateList($tvEpisode->directors, "", $separator);
  1479. $sqlArray['writers'] = CreateList($tvEpisode->writers, "", $separator);
  1480. $sqlArray['imdb'] = $tvEpisode->imdbId;
  1481. DBInsert("tvdbEpisodes", $sqlArray);
  1482. }
  1483. $missingEpisode = 0;
  1484. $missingSeason = 0;
  1485. }
  1486. }
  1487. else
  1488. {
  1489. $missingEpisode = 0;
  1490. $missingSeason = 0;
  1491. }
  1492. }
  1493. while ($missingEpisode < 2);
  1494. }
  1495. while ($missingSeason < 1);
  1496. }
  1497. function MatchEpisodeBySubTitle($programid, $subtitle)
  1498. {
  1499. }
  1500. function MatchEpisodeByDescription($programid, $episodedescription)
  1501. {
  1502. $episodelookup = mysql_query("SELECT id FROM tvdbEpisodeMatches WHERE listingdescription = '" . mysql_real_escape_string($episodedescription) . "'") or die(mysql_error());
  1503. if (mysql_num_rows($episodelookup) == 0)
  1504. {
  1505. $sqlArray['listingdescription'] = $episodedescription;
  1506. $match = 0;
  1507. unset($seasonnumber);
  1508. unset($episodenumber);
  1509. $skipWordArray = array("a", "the", "to", "and", "him", "her", "he", "she", "for", "when", "that", "of", "if", "");
  1510. $removePunctuationArray = array(".", ",", "!", ":", "?", "/", "\\");
  1511. foreach ($removePunctuationArray as $punctuation)
  1512. {
  1513. $wordlist = str_replace($punctuation, " ", $episodedescription);
  1514. }
  1515. //echoIfNotSilent($episodedescription . "<br />\r\n");
  1516. $descriptionWordArray = explode(" ", $wordlist);
  1517. //$descriptionWordArray = preg_split ("/\s+/", $wordlist);
  1518. //print_r($descriptionWordArray);
  1519. foreach ($descriptionWordArray as $word)
  1520. {
  1521. if (!in_array($word, $skipWordArray))
  1522. {
  1523. $wordArray[] = strtolower($word);
  1524. }
  1525. }
  1526. $wordArray = array_unique($wordArray);
  1527. $descriptionlength = strlen(implode("", $wordArray));
  1528. $episodeslookup = mysql_query("SELECT id, season, episode, title, description FROM tvdbEpisodes WHERE program_id = '" . $programid . "'") or die(mysql_error());
  1529. if (mysql_num_rows($episodeslookup) > 0)
  1530. {
  1531. while ($episode = mysql_fetch_assoc($episodeslookup))
  1532. {
  1533. $percentmatch = 0;
  1534. foreach (Array(strtolower($episode['title']), strtolower($episode['description'])) as $episodetext)
  1535. {
  1536. if ((!is_null($episodetext)) and ($episodetext <> ""))
  1537. {
  1538. foreach ($wordArray as $word)
  1539. {
  1540. if (strpos($episodetext, $word) <> FALSE)
  1541. {
  1542. $percentmatch += strlen($word);
  1543. }
  1544. }
  1545. }
  1546. }
  1547. $percentmatch = ($percentmatch / $descriptionlength) * 100;
  1548. if ($percentmatch > $sqlArray['similar'])
  1549. {
  1550. $sqlArray['similar'] = $percentmatch;
  1551. $sqlArray['id'] = $episode['id'];
  1552. $sqlArray['title'] = $episode['title'];
  1553. $sqlArray['description'] = $episode['description'];
  1554. }
  1555. }
  1556. DBInsert("tvdbEpisodeMatches", $sqlArray);
  1557. }
  1558. }
  1559. else
  1560. {
  1561. $episode = mysql_fetch_assoc($episodelookup);
  1562. }
  1563. return $episodeid;
  1564. }
  1565. /* Merge */
  1566. function MergePrograms()
  1567. {
  1568. echoIfNotSilent('<h2>Emptying Table tempSourcePrograms...</h2>' . "\n");
  1569. mysql_query("TRUNCATE TABLE tempSourcePrograms") or die(mysql_error());
  1570. echoIfNotSilent('<h2>Copying Table xmltvSourcePrograms into tempSourcePrograms...</h2>' . "\n");
  1571. //mysql_query("INSERT INTO tempSourcePrograms SELECT * FROM xmltvSourcePrograms WHERE channel IS NOT NULL AND channel <> '' ORDER BY start, channel_id") or die(mysql_error());
  1572. $copycolumns = implode(",", array("file", "channel", "channel_id", "start", "stop", "title", "description", "category", "rating", "quality", "subtitles", "url"));
  1573. mysql_query("INSERT INTO tempSourcePrograms (" . $copycolumns . ") SELECT " . $copycolumns . " FROM xmltvSourcePrograms WHERE channel IS NOT NULL AND channel <> '' ORDER BY start, channel, channel_id") or die(mysql_error());
  1574. echoIfNotSilent('<h2>Fixing Program Listings...</h2>' . "\n");
  1575. RunFixes();
  1576. echoIfNotSilent('<h2>Emptying Table tempPrograms...</h2>' . "\n");
  1577. mysql_query("TRUNCATE TABLE tempPrograms") or die(mysql_error());
  1578. echoIfNotSilent('<h2>Amalgamating program data into table tempPrograms...</h2>' . "\n");
  1579. $programsresult = mysql_query("SELECT channel, start, stop,
  1580. GROUP_CONCAT(DISTINCT title SEPARATOR '^') AS title,
  1581. GROUP_CONCAT(DISTINCT description SEPARATOR '^') AS description,
  1582. GROUP_CONCAT(DISTINCT channel_id SEPARATOR '^') AS channel_id,
  1583. GROUP_CONCAT(DISTINCT category SEPARATOR '^') AS category,
  1584. GROUP_CONCAT(DISTINCT rating SEPARATOR '^') AS rating,
  1585. GROUP_CONCAT(DISTINCT aspect SEPARATOR '^') AS aspect,
  1586. GROUP_CONCAT(DISTINCT quality SEPARATOR '^') AS quality,
  1587. GROUP_CONCAT(DISTINCT subtitles SEPARATOR '^') AS subtitles,
  1588. GROUP_CONCAT(DISTINCT url SEPARATOR '^') AS url
  1589. FROM tempSourcePrograms GROUP BY channel, start, stop ORDER BY channel, stop, start") or die(mysql_error());
  1590. while ($programrow = mysql_fetch_assoc($programsresult))
  1591. {
  1592. $channels = explode("^", $programrow['channel_id']);
  1593. foreach ($programrow as &$programvalue)
  1594. {
  1595. $programvalue = strstrb($programvalue, '^');
  1596. }
  1597. /*
  1598. foreach ($channels as $channel)
  1599. {
  1600. $programrow[substr($channel, 0, 2) . "_id"] = $channel;
  1601. }
  1602. */
  1603. $dbprogramscheck = mysql_query("SELECT channel, start, stop, title FROM tempPrograms WHERE channel = '" . $programrow['channel'] . "' AND start < '" . $programrow['stop'] . "' AND stop > '" . $programrow['start'] . "'") or die(mysql_error());
  1604. if (mysql_num_rows($dbprogramscheck) >= 1)
  1605. {
  1606. $dbprogramrow = mysql_fetch_assoc($dbprogramscheck);
  1607. $clashcount++;
  1608. echoIfNotSilent($dbprogramrow['channel'] . " (" . $dbprogramrow['start'] . " - " . $dbprogramrow['stop'] . ") " . $dbprogramrow['title'] . "<br />" . $programrow['channel_id'] . " (" . $programrow['start'] . " - " . $programrow['stop'] . ") " . $programrow['title'] . "<br /><br />\r\n");
  1609. }
  1610. //$programrow = CleanArray($programrow);
  1611. //if ($programrow['description'] == "No Description Available")
  1612. //{
  1613. //unset($programrow['description']);
  1614. //}
  1615. //mysql_query("INSERT into tempPrograms (title, description, TC_id, YH_id, FV_id, channel, start, stop, category, rating, aspect, quality, subtitles, url) VALUES ('" . $programrow['title'] . "'," . NullQuoteString($programrow['description']) . "," . NullQuoteString($programrow['TC_id']) . "," . NullQuoteString($programrow['YH_id']) . "," . NullQuoteString($programrow['FV_id']) . ",'" . $programrow['channel_name'] . "','" . $programrow['start'] . "','" . $programrow['stop'] . "'," . NullQuoteString($programrow['category']) . "," . NullQuoteString($programrow['rating']) . "," . NullQuoteString($programrow['aspect']) . "," . NullQuoteString($programrow['quality']) . "," . NullQuoteString($programrow['subtitles']) . "," . NullQuoteString($programrow['url']) . ")"); //or die(mysql_error());
  1616. //echoIfNotSilent(print_r($programrow) . "<br />\r\n");
  1617. unset($programrow['channel_id']);
  1618. DBInsert("tempPrograms", $programrow);
  1619. $dbprograms = mysql_query("SELECT channel FROM tempPrograms WHERE channel = '" . $programrow['channel'] . "' AND start='" . $programrow['start'] . "'") or die(mysql_error());
  1620. if (mysql_num_rows($dbprograms) < 1)
  1621. {
  1622. //mysql_query("INSERT into tempPrograms (title, description, channel, start, stop, category, rating, aspect, quality, subtitles, url) VALUES ('" . $programrow['title'] . "'," . NullQuoteString($programrow['description']) . ",'" . $programrow['channel'] . "','" . $programrow['start'] . "','" . $programrow['stop'] . "'," . NullQuoteString($programrow['category']) . "," . NullQuoteString($programrow['rating']) . "," . NullQuoteString($programrow['aspect']) . "," . NullQuoteString($programrow['quality']) . "," . NullQuoteString($programrow['subtitles']) . "," . NullQuoteString($programrow['url']) . ")") or die(mysql_error());
  1623. if (verboseOutput == 'yes')
  1624. {
  1625. echoIfNotSilent('Merged program ' . $programrow['channel'] . " " . $programrow['start'] . '<br />' . "\n");
  1626. }
  1627. }
  1628. else
  1629. {
  1630. //mysql_query("UPDATE tempPrograms SET title = '" . $programrow['title'] . "', description = " . NullQuoteString($programrow['description']) . ", TC_id = " . NullQuoteString($programrow['TC_id']) . ", YH_id = " . NullQuoteString($programrow['YH_id']) . ", FV_id = " . NullQuoteString($programrow['FV_id']) . ", category = " . NullQuoteString($programrow['category']) . ", rating = " . NullQuoteString($programrow['rating']) . ", aspect = " . NullQuoteString($programrow['aspect']) . ", quality = " . NullQuoteString($programrow['quality']) . ", subtitles = " . NullQuoteString($programrow['subtitles']) . ", url = " . NullQuoteString($programrow['url']) . " WHERE channel_name = '" . $programrow['channel_name'] . "' AND start = '" . $programrow['start'] . "' AND stop = '" . $programrow['stop'] . "'") or die(mysql_error());
  1631. foreach (array("channel", "start", "stop") as $element)
  1632. {
  1633. $whererow[$element] = $programrow[$element];
  1634. unset($programrow[$element]);
  1635. }
  1636. //mysql_query("UPDATE tempPrograms SET title = '" . $programrow['title'] . "', description = " . NullQuoteString($programrow['description']) . ", category = " . NullQuoteString($programrow['category']) . ", rating = " . NullQuoteString($programrow['rating']) . ", aspect = " . NullQuoteString($programrow['aspect']) . ", quality = " . NullQuoteString($programrow['quality']) . ", subtitles = " . NullQuoteString($programrow['subtitles']) . ", url = " . NullQuoteString($programrow['url']) . " WHERE channel = '" . $programrow['channel'] . "' AND start = '" . $programrow['start'] . "' AND stop = '" . $programrow['stop'] . "'") or die(mysql_error());
  1637. DBInsert("tempPrograms", $programrow, $whererow);
  1638. }
  1639. }
  1640. echoIfNotSilent("<h3>Total Clashes: " . $clashcount . "</h3>");
  1641. }
  1642. function CopyMerge()
  1643. {
  1644. echoIfNotSilent('<h2>Emptying Table xmltvPrograms...</h2>' . "\n");
  1645. mysql_query("TRUNCATE TABLE xmltvPrograms") or die(mysql_error());
  1646. echoIfNotSilent('<h2>Copying Table tempPrograms into xmltvPrograms...</h2>' . "\n");
  1647. mysql_query("INSERT INTO xmltvPrograms SELECT * FROM tempPrograms") or die(mysql_error());
  1648. }
  1649. function CheckMerge()
  1650. {
  1651. $channelsresult = mysql_query("SELECT DISTINCT channel FROM xmltvPrograms");
  1652. while ($channelrow = mysql_fetch_assoc($channelsresult))
  1653. {
  1654. $programsresult = mysql_query("SELECT start, stop FROM xmltvPrograms WHERE channel = '" . $channelrow['channel'] . "' ORDER BY start");
  1655. while ($programrow = mysql_fetch_assoc($programsresult))
  1656. {
  1657. if ($programrow['start'] <> $stop)
  1658. {
  1659. echo $channelrow['channel'] . " - " . $programrow['start'] . "<br />\r\n";
  1660. }
  1661. $stop = $programrow['stop'];
  1662. }
  1663. }
  1664. }
  1665. /* Running options */
  1666. function RunFixes()
  1667. {
  1668. FixDBBadCharacters();
  1669. echoIfNotSilent('<h3>Fixed bad characters</h3>' . "\n");
  1670. ReplaceTV1BBCWorld();
  1671. echoIfNotSilent('<h3>Inserted BBC Programs to TV1</h3>' . "\n");
  1672. FreeViewFixRNZNTimes();
  1673. echoIfNotSilent('<h3>Fixed Radio NZ National Times</h3>' . "\n");
  1674. FixProblemChannelTimes();
  1675. echoIfNotSilent('<h3>Fixed program stop times</h3>' . "\n");
  1676. RemoveGenericTitles();
  1677. echoIfNotSilent('<h3>Removed generic programs</h3>' . "\n");
  1678. FixTitleSuffixes();
  1679. FixMoviePrefixes();
  1680. echoIfNotSilent('<h3>Fixed title naming</h3>' . "\n");
  1681. CleanNullValues();
  1682. echoIfNotSilent('<h3>Created Null values</h3>' . "\n");
  1683. GetProgramMetadata();
  1684. for ($i = 0; $i <= 5; $i++)
  1685. {
  1686. GetProgramMetadataRepeated();
  1687. }
  1688. echoIfNotSilent('<h3>Grabbed data from program titles/descriptions</h3>' . "\n");
  1689. }
  1690. function GrabChannelLists()
  1691. {
  1692. echoIfNotSilent('<h1>Grabbing Channels...</h1>' . "\n");
  1693. mysql_query("TRUNCATE TABLE xmltvChannels");
  1694. mysql_query("INSERT INTO xmltvChannels SELECT * FROM Channels ORDER BY All_id");
  1695. TelstraGrabChannelList();
  1696. YahooGrabChannelList(1);
  1697. YahooGrabChannelList(2);
  1698. FreeViewGrabChannelList();
  1699. GrabIcons();
  1700. }
  1701. function GrabChannelPackages()
  1702. {
  1703. //mysql_query("TRUNCATE TABLE ChannelPackages");
  1704. TelstraGrabChannelPackages();
  1705. }
  1706. function GrabPrograms()
  1707. {
  1708. echoIfNotSilent('<h2>Emptying Table xmltvSourcePrograms...</h2>' . "\n");
  1709. mysql_query("TRUNCATE TABLE xmltvSourcePrograms") or die(mysql_error());
  1710. echoIfNotSilent('<h1>Grabbing Programs...</h1>' . "\n");
  1711. for ($i = 0; $i <= maxDays; $i++)
  1712. {
  1713. echoIfNotSilent('<h2>Grabbing Yahoo data for day ' . $i . '...</h2>' . "\n");
  1714. YahooGrabProgramList($i);
  1715. echoIfNotSilent('<h3>Grabbed Yahoo data for day ' . $i . '.</h3>' . "\n");
  1716. echoIfNotSilent('<h2>Grabbing Telstra data for day ' . $i . '...</h2>' . "\n");
  1717. TelstraGrabProgramList($i);
  1718. echoIfNotSilent('<h3>Grabbed Telstra data for day ' . $i . '.</h3>' . "\n");
  1719. }
  1720. echoIfNotSilent('<h2>Grabbing Freeview data...</h2>' . "\n");
  1721. FreeViewGrabProgramList();
  1722. echoIfNotSilent('<h3>Grabbed Freeview data.</h3>' . "\n");
  1723. //echoIfNotSilent('<h2>Grabbing Satellite Perl data...</h2>' . "\n");
  1724. //SatellitePerlGrabProgramList();
  1725. //echoIfNotSilent('<h3>Grabbed Satellite Perl data.</h3>' . "\n");
  1726. }
  1727. function RemoveOldPrograms()
  1728. {
  1729. echoIfNotSilent('<h1>Removing Old Programs...</h1>' . "\n");
  1730. $programsResult = mysql_query("SELECT file FROM xmltvSourcePrograms WHERE stop < '" . currentDateSQL . "'") or die(mysql_error());
  1731. while ($programRow = mysql_fetch_assoc($programsResult))
  1732. {
  1733. $filenamePath = programsFolder . $programRow['file'];
  1734. if (file_exists($filenamePath))
  1735. {
  1736. if (filemtime($filenamePath) < strtotime(currentDate . " -7 days"))
  1737. {
  1738. unlink($filenamePath);
  1739. }
  1740. }
  1741. if (verboseOutput == 'yes')
  1742. {
  1743. echoIfNotSilent('Removed file ' . $programRow['file'] . '<br />' . "\n");
  1744. }
  1745. }
  1746. mysql_query("DELETE FROM xmltvSourcePrograms WHERE stop < '" . currentDateSQL . "'") or die(mysql_error());
  1747. mysql_query("DELETE FROM xmltvPrograms WHERE stop < '" . currentDateSQL . "'") or die(mysql_error());
  1748. if ($handle = opendir(programsFolder))
  1749. {
  1750. while (false !== ($file = readdir($handle)))
  1751. {
  1752. if ($file != "." && $file != ".." && filemtime(programsFolder . $file) < strtotime(currentDate . " -7 days"))
  1753. {
  1754. $filesResult = mysql_query("SELECT file FROM xmltvSourcePrograms WHERE file='" . $file . "'") or die(mysql_error());
  1755. if (mysql_num_rows($filesResult) < 1)
  1756. {
  1757. unlink(programsFolder . $file);
  1758. if (verboseOutput == 'yes')
  1759. {
  1760. echoIfNotSilent('Removed file ' . $file . '<br />' . "\n");
  1761. }
  1762. }
  1763. }
  1764. }
  1765. }
  1766. if ($handle = opendir(xmltvFolder . 'listings/'))
  1767. {
  1768. while (false !== ($file = readdir($handle)))
  1769. {
  1770. $folderPath = xmltvFolder . 'listings/' . $file;
  1771. if ($file != "." && $file != ".." && strtotime($file) < strtotime(currentDate) AND is_dir($folderPath))
  1772. {
  1773. if ($handle2 = opendir($folderPath))
  1774. {
  1775. while (false !== ($file2 = readdir($handle2)))
  1776. {
  1777. if ($file2 != "." && $file2 != "..")
  1778. {
  1779. unlink($folderPath . '/' . $file2);
  1780. }
  1781. }
  1782. }
  1783. rmdir($folderPath);
  1784. }
  1785. }
  1786. }
  1787. echoIfNotSilent('<h2>Old programs removed</h2>' . "\n");
  1788. }
  1789. /* Get options */
  1790. if ($_GET["silent"] == "yes")
  1791. {
  1792. define("runSilently", 'yes');
  1793. }
  1794. else
  1795. {
  1796. define("runSilently", 'no');
  1797. }
  1798. if ($_GET["verbose"] == "yes")
  1799. {
  1800. define("verboseOutput", 'yes');
  1801. }
  1802. else
  1803. {
  1804. define("verboseOutput", 'no');
  1805. }
  1806. if (isset($_GET["day"]))
  1807. {
  1808. $day = (int)$_GET["day"];
  1809. if (is_int($day))
  1810. {
  1811. if ($day >= 0 AND $day < maxDays)
  1812. {
  1813. //if (strtotime($datadate) > strtotime(lastfulldatadate)) {$cachedata = false;}
  1814. }
  1815. }
  1816. }
  1817. switch ($_GET["cache"])
  1818. {
  1819. case 'none':
  1820. define("listingsFolder", '');
  1821. define("programsFolder", '');
  1822. break;
  1823. case 'programs':
  1824. define("listingsFolder", '');
  1825. define("programsFolder", xmltvFolder . 'programs/');
  1826. break;
  1827. default:
  1828. define("listingsFolder", xmltvFolder . 'listings/' . currentDate . '/');
  1829. define("programsFolder", xmltvFolder . 'programs/');
  1830. break;
  1831. }
  1832. if ($_GET["password"] == cachePassword)
  1833. {
  1834. if ($_GET["all"] == "yes")
  1835. {
  1836. //GrabChannelLists();
  1837. /*GrabChannelPackages();*/ // Do not run, as it wipes the existing table, which has been updated manually after this script has been run.
  1838. GrabPrograms();
  1839. RemoveOldPrograms();
  1840. //RunFixes();
  1841. MergePrograms();
  1842. DoLookups();
  1843. CopyMerge();
  1844. }
  1845. if ($_GET["fixes"] == "yes")
  1846. {
  1847. //GrabChannelLists();
  1848. /*GrabChannelPackages();*/ // Do not run, as it wipes the existing table, which has been updated manually after this script has been run.
  1849. //GrabPrograms();
  1850. //RemoveOldPrograms();
  1851. //RunFixes();
  1852. MergePrograms();
  1853. DoLookups();
  1854. CopyMerge();
  1855. }
  1856. else
  1857. {
  1858. if ($_GET["channels"] == "yes")
  1859. {
  1860. GrabChannelLists();
  1861. }
  1862. if ($_GET["programs"] == "yes")
  1863. {
  1864. GrabPrograms();
  1865. RemoveOldPrograms();
  1866. //RunFixes();
  1867. }
  1868. if ($_GET["geek"] == "yes")
  1869. {
  1870. GeekNZGrabProgramList();
  1871. }
  1872. if ($_GET["movietest"] == "yes")
  1873. {
  1874. LookupMovies();
  1875. }
  1876. if ($_GET["tvtest"] == "yes")
  1877. {
  1878. LookupPrograms();
  1879. }
  1880. if ($_GET["satelliteperl"] == "yes")
  1881. {
  1882. SatellitePerlGrabProgramList();
  1883. }
  1884. if ($_GET["clearcache"] == "yes")
  1885. {
  1886. RemoveOldPrograms();
  1887. }
  1888. if ($_GET["icons"] == "yes")
  1889. {
  1890. GrabIcons();
  1891. }
  1892. if ($_GET["packages"] == "yes")
  1893. {
  1894. GrabChannelPackages();
  1895. }
  1896. if ($_GET["merge"] == "yes")
  1897. {
  1898. MergePrograms();
  1899. }
  1900. if ($_GET["check"] == "yes")
  1901. {
  1902. CheckMerge();
  1903. }
  1904. }
  1905. echoIfNotSilent('<h1>All done!</h1>');
  1906. }
  1907. else
  1908. {
  1909. echoIfNotSilent('<h1>Incorrect Password or No Password Given</h1>');
  1910. }
  1911. ?>