Client.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. <?php
  2. namespace Moinax\TvDb;
  3. use Moinax\TvDb\CurlException;
  4. use Moinax\TvDb\Http\CurlClient;
  5. use Moinax\TvDb\Http\HttpClient;
  6. /**
  7. * Base TVDB library class, provides universal functions and variables
  8. *
  9. * @package TvDb
  10. * @author Jérôme Poskin <moinax@gmail.com>
  11. **/
  12. class Client
  13. {
  14. const POST = 'post';
  15. const GET = 'get';
  16. const MIRROR_TYPE_XML = 1;
  17. const MIRROR_TYPE_BANNER = 2;
  18. const MIRROR_TYPE_ZIP = 4;
  19. const DEFAULT_LANGUAGE = 'en';
  20. const FORMAT_XML = 'xml';
  21. const FORMAT_ZIP = 'zip';
  22. /**
  23. * Base url for TheTVDB
  24. *
  25. * @var string
  26. */
  27. protected $baseUrl = '';
  28. /**
  29. * API key for thetvdb.com
  30. *
  31. * @var string
  32. */
  33. protected $apiKey = '';
  34. /**
  35. * Array of available mirrors
  36. *
  37. * @var array
  38. */
  39. protected $mirrors = array();
  40. /**
  41. * Array of available languages
  42. *
  43. * @var array
  44. */
  45. protected $languages = array();
  46. /**
  47. * Default language.
  48. *
  49. * @var string
  50. */
  51. protected $defaultLanguage = 'en';
  52. /**
  53. * HttpClient used to query the API.
  54. *
  55. * @var HttpClient
  56. */
  57. protected $httpClient;
  58. /**
  59. * @param string $baseUrl Domain name of the api without trailing slash
  60. * @param string $apiKey Api key provided by http://thetvdb.com
  61. */
  62. public function __construct($baseUrl, $apiKey)
  63. {
  64. $this->baseUrl = $baseUrl;
  65. $this->apiKey = $apiKey;
  66. $this->httpClient = new CurlClient();
  67. }
  68. /**
  69. * Set the HttpClient used to query the API.
  70. *
  71. * @param HttpClient $client
  72. */
  73. public function setHttpClient(HttpClient $client)
  74. {
  75. $this->httpClient = $client;
  76. }
  77. /**
  78. * Get a language information
  79. *
  80. * @param string $abbreviation
  81. * @return array
  82. * @throws \Exception
  83. */
  84. public function getLanguage($abbreviation)
  85. {
  86. if (empty($this->languages)) {
  87. $this->getLanguages();
  88. }
  89. if (!isset($this->languages[$abbreviation])) {
  90. throw new \Exception('This language is not available');
  91. }
  92. return $this->languages[$abbreviation];
  93. }
  94. /**
  95. * Set the default query language. It must be a valid language code.
  96. *
  97. * @param string $language
  98. */
  99. public function setDefaultLanguage($language) {
  100. $this->defaultLanguage = $language;
  101. }
  102. /**
  103. * Get the default query language.
  104. *
  105. * @return string
  106. */
  107. public function getDefaultLanguage() {
  108. return $this->defaultLanguage;
  109. }
  110. /**
  111. * Get the server time for further updates
  112. *
  113. * @return string
  114. */
  115. public function getServerTime()
  116. {
  117. return (string)$this->fetchXml('Updates.php?type=none')->Time;
  118. }
  119. /**
  120. * Searches for tv serie based on series name
  121. *
  122. * @param string $seriesName
  123. * @param string $language
  124. * @return array
  125. */
  126. public function getSeries($seriesName, $language = null)
  127. {
  128. $language = $language ? : $this->defaultLanguage;
  129. $data = $this->fetchXml('GetSeries.php?seriesname=' . urlencode($seriesName) . '&language=' . $language);
  130. $series = array();
  131. foreach ($data->Series as $serie) {
  132. $series[] = new Serie($serie);
  133. }
  134. return $series;
  135. }
  136. /**
  137. * Find a tv serie by the id from thetvdb.com
  138. *
  139. * @var int $serieId
  140. * @var string $language
  141. *
  142. * @return Serie A serie object or false if not found
  143. **/
  144. public function getSerie($serieId, $language = null)
  145. {
  146. $language = $language ? : $this->defaultLanguage;
  147. $data = $this->fetchXml('series/' . $serieId . '/' . $language . '.xml');
  148. return new Serie($data->Series);
  149. }
  150. /**
  151. * Find a tv serie by a remote id
  152. *
  153. * @param array $remoteId
  154. * @param string $language
  155. *
  156. * @example <pre><code>$obj->getSerieByRemoteId(array('imdbid' => '<imdbid>'));</code></pre>
  157. * @example <pre><code>$obj->getSerieByRemoteId(array('zap2it' => '<zap2it>'));</code></pre>
  158. *
  159. * @return Serie
  160. */
  161. public function getSerieByRemoteId(array $remoteId, $language = null)
  162. {
  163. $language = $language ? : $this->defaultLanguage;
  164. $data = $this->fetchXml('GetSeriesByRemoteID.php?' . http_build_query($remoteId) . '&language=' . $language);
  165. return new Serie($data->Series);
  166. }
  167. /**
  168. * Find all banners related to a serie
  169. *
  170. * @param int $serieId
  171. * @return string
  172. */
  173. public function getBanners($serieId)
  174. {
  175. $data = $this->fetchXml('series/' . $serieId . '/banners.xml');
  176. $banners = array();
  177. foreach ($data->Banner as $banner) {
  178. $banners[] = new Banner($banner);
  179. }
  180. return $banners;
  181. }
  182. /**
  183. * Find banners that match a filter string
  184. * Eg: poster or season
  185. */
  186. public function getBannersFiltered($serieId,$filter) {
  187. $data = $this->getBanners($serieId);
  188. $banners = array();
  189. foreach($data as $image) {
  190. if($image->type == $filter) {
  191. $banners[] = $image;
  192. }
  193. }
  194. return $banners;
  195. }
  196. /**
  197. * Find all actors related to a serie
  198. *
  199. * @param int $serieId
  200. * @return array
  201. */
  202. public function getActors($serieId)
  203. {
  204. $data = $this->fetchXml('series/'. $serieId . '/actors.xml');
  205. $actors = array();
  206. foreach ($data->Actor as $actor) {
  207. $actors [] = new Actor($actor);
  208. }
  209. return $actors;
  210. }
  211. /**
  212. * Get all episodes for a serie
  213. *
  214. * @param int $serieId
  215. * @param string $language
  216. * @param string $format
  217. * @return array
  218. * @throws \ErrorException
  219. */
  220. public function getSerieEpisodes($serieId, $language = null, $format = self::FORMAT_XML)
  221. {
  222. $language = $language ? : $this->defaultLanguage;
  223. switch ($format) {
  224. case self::FORMAT_XML:
  225. $data = $this->fetchXml('series/' . $serieId . '/all/' . $language . '.' . $format);
  226. break;
  227. case self::FORMAT_ZIP:
  228. if (!in_array('zip', stream_get_wrappers())) {
  229. throw new \ErrorException('Your PHP does nort support ZIP stream wrappers');
  230. }
  231. $data = $this->fetchZIP('series/' . $serieId . '/all/' . $language . '.' . $format, array(), self::GET, $language.".xml");
  232. break;
  233. default:
  234. throw new \ErrorException('Unsupported format');
  235. break;
  236. }
  237. $serie = new Serie($data->Series);
  238. $episodes = array();
  239. foreach ($data->Episode as $episode) {
  240. $episodes[(int)$episode->id] = new Episode($episode);
  241. }
  242. return array('serie' => $serie, 'episodes' => $episodes);
  243. }
  244. /**
  245. * Get a specific episode by season and episode number
  246. *
  247. * @var int $serieId required the id of the serie
  248. * @var int $season required the season number
  249. * @var int $episode required the episode number
  250. * @var string $language language abbreviation
  251. *
  252. * @return Episode
  253. **/
  254. public function getEpisode($serieId, $season, $episode, $language = null)
  255. {
  256. $language = $language ? : $this->defaultLanguage;
  257. $data = $this->fetchXml('series/' . $serieId . '/default/' . $season . '/' . $episode . '/' . $language . '.xml');
  258. return new Episode($data->Episode);
  259. }
  260. /**
  261. * Get a specific episode by his id
  262. *
  263. * @var int $episodeId required the id of the episode
  264. * @var string $language
  265. * @return Episode
  266. **/
  267. public function getEpisodeById($episodeId, $language = null)
  268. {
  269. $language = $language ? : $this->defaultLanguage;
  270. $data = $this->fetchXml('episodes/' . $episodeId . '/' . $language . '.xml');
  271. return new Episode($data->Episode);
  272. }
  273. /**
  274. * @param $serieId
  275. * @param $airdate
  276. * @param null $language
  277. *
  278. * @return Episode
  279. */
  280. public function getEpisodeByAirDate($serieId, $airdate, $language = null)
  281. {
  282. $language = $language ? : $this->defaultLanguage;
  283. $data = $this->fetchXml('GetEpisodeByAirDate.php?apikey=' . $this->apiKey . '&seriesid=' . $serieId . '&airdate=' . $airdate . '&language=' . $language );
  284. return new Episode($data->Episode);
  285. }
  286. /**
  287. * Get updates list based on previous time you got data
  288. *
  289. * @param int $previousTime
  290. * @return array
  291. */
  292. public function getUpdates($previousTime)
  293. {
  294. $data = $this->fetchXml('Updates.php?type=all&time=' . $previousTime);
  295. $series = array();
  296. foreach ($data->Series as $serieId) {
  297. $series[] = (int)$serieId;
  298. }
  299. $episodes = array();
  300. foreach ($data->Episode as $episodeId) {
  301. $episodes[] = (int)$episodeId;
  302. }
  303. return array('series' => $series, 'episodes' => $episodes);
  304. }
  305. /**
  306. * Fetch banner raw jpeg data from banner mirror.
  307. *
  308. * @param string $banner the banner to fetch like graphical/79349-g7.jpg
  309. * @return string raw jpeg data
  310. */
  311. public function fetchBanner($banner)
  312. {
  313. $url = $this->getMirror(self::MIRROR_TYPE_BANNER) . '/banners/' . $banner;
  314. return $this->httpClient->fetch($url, array(), self::GET);
  315. }
  316. /**
  317. * Fetches data via curl and returns result
  318. *
  319. * @access protected
  320. * @param string $function The function used to fetch data in xml
  321. * @param array $params
  322. * @param string $method
  323. * @return string The data
  324. */
  325. protected function fetchXml($function, $params = array(), $method = self::GET)
  326. {
  327. if (strpos($function, '.php') > 0) { // no need of api key for php calls
  328. $url = $this->getMirror(self::MIRROR_TYPE_XML) . '/api/' . $function;
  329. } else {
  330. $url = $this->getMirror(self::MIRROR_TYPE_XML) . '/api/' . $this->apiKey . '/' . $function;
  331. }
  332. $data = $this->httpClient->fetch($url, $params, $method);
  333. $simpleXml = $this->getXml($data);
  334. return $simpleXml;
  335. }
  336. /**
  337. * Fetches data via curl and returns result
  338. *
  339. * @access protected
  340. * @param string $function The function used to fetch data in zip
  341. * @param array $params
  342. * @param string $method
  343. * @param string $file The file to extract from the ZIP
  344. * @return string The data
  345. */
  346. protected function fetchZIP($function, $params = array(), $method = self::GET, $file=null)
  347. {
  348. if (strpos($function, '.php') > 0) { // no need of api key for php calls
  349. $url = $this->getMirror(self::MIRROR_TYPE_ZIP) . '/api/' . $function;
  350. } else {
  351. $url = $this->getMirror(self::MIRROR_TYPE_ZIP) . '/api/' . $this->apiKey . '/' . $function;
  352. }
  353. $zipName = tempnam(sys_get_temp_dir(), "tvdb-");
  354. $zip = fopen($zipName, "w");
  355. fwrite($zip, $this->httpClient->fetch($url, $params, $method));
  356. fclose($zip);
  357. if (is_null($file)) {
  358. $file = $this->getDefaultLanguage().".xml";
  359. }
  360. $dataPath = "zip://".$zipName."#".$file;
  361. $data = file_get_contents($dataPath);
  362. $simpleXml = $this->getXml($data);
  363. return $simpleXml;
  364. }
  365. /**
  366. * Fetch data with curl
  367. *
  368. * @param string $url
  369. * @param array $params
  370. * @param string $method
  371. * @throws CurlException
  372. * @return bool|string
  373. */
  374. protected function fetch($url, array $params = array(), $method = self::GET)
  375. {
  376. return $this->httpClient->fetch($url, $params, $method);
  377. }
  378. /**
  379. * Convert xml string to SimpleXMLElement
  380. *
  381. * @param string $data
  382. * @return \SimpleXMLElement
  383. * @throws \ErrorException|\Exception
  384. */
  385. protected function getXml($data)
  386. {
  387. if (extension_loaded('libxml')) {
  388. libxml_use_internal_errors(true);
  389. }
  390. $simpleXml = simplexml_load_string($data);
  391. if (!$simpleXml) {
  392. if (extension_loaded('libxml')) {
  393. $xmlErrors = libxml_get_errors();
  394. $errors = array();
  395. foreach ($xmlErrors as $error) {
  396. $errors[] = sprintf('Error in file %s on line %d with message : %s', $error->file, $error->line, $error->message);
  397. }
  398. if (count($errors) > 0) {
  399. throw new XmlException(implode("\n", $errors));
  400. }
  401. }
  402. throw new XmlException('Xml file could not be loaded');
  403. }
  404. return $simpleXml;
  405. }
  406. /**
  407. * Get a list of mirrors available to fetchXml the data from the api
  408. * @return void
  409. */
  410. protected function getMirrors()
  411. {
  412. $data = $this->httpClient->fetch($this->baseUrl . '/api/' . $this->apiKey . '/mirrors.xml');
  413. $mirrors = $this->getXml($data);
  414. foreach ($mirrors->Mirror as $mirror) {
  415. $typeMask = (int)$mirror->typemask;
  416. $mirrorPath = (string)$mirror->mirrorpath;
  417. if ($typeMask & self::MIRROR_TYPE_XML) {
  418. $this->mirrors[self::MIRROR_TYPE_XML][] = $mirrorPath;
  419. }
  420. if ($typeMask & self::MIRROR_TYPE_BANNER) {
  421. $this->mirrors[self::MIRROR_TYPE_BANNER][] = $mirrorPath;
  422. }
  423. if ($typeMask & self::MIRROR_TYPE_ZIP) {
  424. $this->mirrors[self::MIRROR_TYPE_ZIP][] = $mirrorPath;
  425. }
  426. }
  427. }
  428. /**
  429. * Get a random mirror from the list of available mirrors
  430. *
  431. * @param int $typeMask
  432. * @return string
  433. * @access protected
  434. */
  435. public function getMirror($typeMask = self::MIRROR_TYPE_XML)
  436. {
  437. if (empty($this->mirrors)) {
  438. $this->getMirrors();
  439. }
  440. return $this->mirrors[$typeMask][array_rand($this->mirrors[$typeMask], 1)];
  441. }
  442. /**
  443. * Get a list of languages available for the content of the api
  444. * @return \SimpleXMLElement
  445. */
  446. protected function getLanguages()
  447. {
  448. $languages = $this->fetchXml('languages.xml');
  449. foreach ($languages->Language as $language) {
  450. $this->languages[(string)$language->abbreviation] = array(
  451. 'name' => (string)$language->name,
  452. 'abbreviation' => (string)$language->abbreviation,
  453. 'id' => (int)$language->id,
  454. );
  455. }
  456. }
  457. /**
  458. * Removes indexes from an array if they are zero length after trimming
  459. *
  460. * @param array $array The array to remove empty indexes from
  461. * @return array An array with all empty indexes removed
  462. **/
  463. public static function removeEmptyIndexes($array)
  464. {
  465. $length = count($array);
  466. for ($i = $length - 1; $i >= 0; $i--) {
  467. if (trim($array[$i]) == '') {
  468. unset($array[$i]);
  469. }
  470. }
  471. sort($array);
  472. return $array;
  473. }
  474. }