PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/animedb/library/X/VlcShares/Plugins/AnimeDb.php

http://vlc-shares.googlecode.com/
PHP | 789 lines | 464 code | 175 blank | 150 comment | 83 complexity | 1f56ca2e7e4bb39b5631a01beeaae3bf MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. require_once 'Zend/Http/CookieJar.php';
  3. require_once 'Zend/Http/Cookie.php';
  4. require_once 'X/VlcShares/Plugins/Abstract.php';
  5. require_once 'Zend/Dom/Query.php';
  6. /**
  7. * Add AnimeDB.tv site as a video source
  8. * @author ximarx
  9. *
  10. */
  11. class X_VlcShares_Plugins_AnimeDb extends X_VlcShares_Plugins_Abstract implements X_VlcShares_Plugins_ResolverInterface {
  12. const VERSION = '0.2.1';
  13. const VERSION_CLEAN = '0.2.1';
  14. /**
  15. * @var Zend_Http_CookieJar
  16. */
  17. private $jar = null;
  18. public function __construct() {
  19. $this->setPriority('gen_beforeInit')
  20. ->setPriority('getCollectionsItems')
  21. ->setPriority('preRegisterVlcArgs')
  22. ->setPriority('getShareItems')
  23. ->setPriority('preGetModeItems')
  24. ->setPriority('getIndexManageLinks')
  25. ->setPriority('getIndexMessages')
  26. ->setPriority('getTestItems')
  27. ->setPriority('prepareConfigElement');
  28. }
  29. /**
  30. * Inizialize translator for this plugin
  31. * @param Zend_Controller_Action $controller
  32. */
  33. function gen_beforeInit(Zend_Controller_Action $controller) {
  34. $this->helpers()->language()->addTranslation(__CLASS__);
  35. }
  36. /**
  37. * Add the main link for animedb library
  38. * @param Zend_Controller_Action $controller
  39. */
  40. public function getCollectionsItems(Zend_Controller_Action $controller) {
  41. X_Debug::i("Plugin triggered");
  42. $link = new X_Page_Item_PItem($this->getId(), X_Env::_('p_animedb_collectionindex'));
  43. $link->setIcon('/images/animedb/logo.png')
  44. ->setDescription(X_Env::_('p_animedb_collectionindex_desc'))
  45. ->setType(X_Page_Item_PItem::TYPE_CONTAINER)
  46. ->setLink(
  47. array(
  48. 'controller' => 'browse',
  49. 'action' => 'share',
  50. 'p' => $this->getId(),
  51. ), 'default', true
  52. );
  53. return new X_Page_ItemList_PItem(array($link));
  54. }
  55. /**
  56. * Get category/video list
  57. * @param unknown_type $provider
  58. * @param unknown_type $location
  59. * @param Zend_Controller_Action $controller
  60. */
  61. public function getShareItems($provider, $location, Zend_Controller_Action $controller) {
  62. // this plugin add items only if it is the provider
  63. if ( $provider != $this->getId() ) return;
  64. X_Debug::i("Plugin triggered");
  65. $urlHelper = $controller->getHelper('url');
  66. $items = new X_Page_ItemList_PItem();
  67. //try to disable SortItems plugin, so link are listed as in html page
  68. X_VlcShares_Plugins::broker()->unregisterPluginClass('X_VlcShares_Plugins_SortItems');
  69. X_Debug::i("Requested location: $location");
  70. $split = $location != '' ? @explode('/', $location, 4) : array();
  71. X_Debug::i("Exploded location: ".var_export($split, true));
  72. switch ( count($split) ) {
  73. // i should not be here, so i fallback to video case
  74. case 4:
  75. // show the list of video in the page
  76. // here authentication is required if it's possibile
  77. case 3:
  78. $this->_fetchVideos($items, $split[0], $split[1], $split[2]);
  79. break;
  80. // show the list of thread in category by letter
  81. case 2:
  82. $this->_fetchThreads($items, $split[0], $split[1]);
  83. break;
  84. // show the list of A-B-C.... if an area is selected
  85. case 1:
  86. $this->_fetchClassification($items, $split[0]);
  87. break;
  88. default:
  89. $this->_fetchLists($items);
  90. }
  91. return $items;
  92. }
  93. /**
  94. * This hook can be used to add low priority args in vlc stack
  95. *
  96. * @param X_Vlc $vlc vlc wrapper object
  97. * @param string $provider id of the plugin that should handle request
  98. * @param string $location to stream
  99. * @param Zend_Controller_Action $controller the controller who handle the request
  100. */
  101. public function preRegisterVlcArgs(X_Vlc $vlc, $provider, $location, Zend_Controller_Action $controller) {
  102. // this plugin inject params only if this is the provider
  103. if ( $provider != $this->getId() ) return;
  104. // i need to register source as first, because subtitles plugin use source
  105. // for create subfile
  106. X_Debug::i('Plugin triggered');
  107. $location = $this->resolveLocation($location);
  108. if ( $location !== null ) {
  109. // TODO adapt to newer api when ready
  110. $vlc->registerArg('source', "\"$location\"");
  111. } else {
  112. X_Debug::e("No source o_O");
  113. }
  114. }
  115. /**
  116. * Add button -watch megavideo stream directly-
  117. *
  118. * @param string $provider
  119. * @param string $location
  120. * @param Zend_Controller_Action $controller
  121. */
  122. public function preGetModeItems($provider, $location, Zend_Controller_Action $controller) {
  123. if ( $provider != $this->getId()) return;
  124. X_Debug::i("Plugin triggered");
  125. $url = $this->resolveLocation($location);
  126. if ( $url ) {
  127. $link = new X_Page_Item_PItem('core-directwatch', X_Env::_('p_animedb_watchdirectly'));
  128. $link->setIcon('/images/icons/play.png')
  129. ->setType(X_Page_Item_PItem::TYPE_PLAYABLE)
  130. ->setLink($url);
  131. return new X_Page_ItemList_PItem(array($link));
  132. } else {
  133. // if there is no link, i have to remove start-vlc button
  134. // and replace it with a Warning button
  135. X_Debug::i('Setting priority to filterModeItems');
  136. $this->setPriority('filterModeItems', 99);
  137. $link = new X_Page_Item_PItem('megavideo-warning', X_Env::_('p_animedb_invalidmegavideo'));
  138. $link->setIcon('/images/msg_error.png')
  139. ->setType(X_Page_Item_PItem::TYPE_ELEMENT)
  140. ->setLink(array (
  141. 'controller' => 'browse',
  142. 'action' => 'share',
  143. 'p' => $this->getId(),
  144. 'l' => X_Env::encode($this->getParentLocation($location)),
  145. ), 'default', true);
  146. return new X_Page_ItemList_PItem(array($link));
  147. }
  148. }
  149. /**
  150. * Remove vlc-play button if location is invalid
  151. * @param X_Page_Item_PItem $item,
  152. * @param string $provider
  153. * @param Zend_Controller_Action $controller
  154. */
  155. public function filterModeItems(X_Page_Item_PItem $item, $provider,Zend_Controller_Action $controller) {
  156. X_Debug::i('plugin triggered');
  157. if ( $item->getKey() == 'core-play') {
  158. X_Debug::w('core-play flagged as invalid because megavideo link is invalid');
  159. return false;
  160. }
  161. }
  162. /**
  163. * @see X_VlcShares_Plugins_ResolverInterface::resolveLocation
  164. * @param string $location
  165. * @return string real address of a resource
  166. */
  167. function resolveLocation($location = null) {
  168. if ( $location == null ) return false;
  169. $split = $location != '' ? @explode('/', $location, 4) : array();
  170. if ( count($split) == 4 ) {
  171. // $split[3] have a resource hoster:id
  172. $href = $split[3];
  173. // new hoster api
  174. @list($hoster, $videoId) = explode(':', $href, 2);
  175. try {
  176. return $this->helpers()->hoster()->getHoster($hoster)->getPlayable($videoId);
  177. } catch (Exception $e) {
  178. X_Debug::e("Invalid hoster {{$hoster}}");
  179. }
  180. }
  181. return false;
  182. }
  183. /**
  184. * No support for parent location
  185. * @see X_VlcShares_Plugins_ResolverInterface::getParentLocation
  186. * @param $location
  187. */
  188. function getParentLocation($location = null) {
  189. if ($location == null || $location == '') return false;
  190. $split = @explode('/', $location, 4);
  191. $return = false;
  192. if ( count($split) == 1 ) {
  193. return false;
  194. } else {
  195. array_pop($split);
  196. return implode('/', $split);
  197. }
  198. }
  199. /**
  200. * Add the link for -manage-megavideo-
  201. * @param Zend_Controller_Action $this
  202. * @return X_Page_ItemList_ManageLink
  203. */
  204. public function getIndexManageLinks(Zend_Controller_Action $controller) {
  205. $link = new X_Page_Item_ManageLink($this->getId(), X_Env::_('p_animedb_mlink'));
  206. $link->setTitle(X_Env::_('p_animedb_managetitle'))
  207. ->setIcon('/images/animedb/logo.png')
  208. ->setLink(array(
  209. 'controller' => 'config',
  210. 'action' => 'index',
  211. 'key' => 'animedb'
  212. ), 'default', true);
  213. return new X_Page_ItemList_ManageLink(array($link));
  214. }
  215. /**
  216. * Show a warning message if username and password aren't specified yet
  217. * @param Zend_Controller_Action $this
  218. * @return X_Page_ItemList_Message
  219. */
  220. public function getIndexMessages(Zend_Controller_Action $controller) {
  221. X_Debug::i('Plugin triggered');
  222. if ( $this->config('auth.username', '') == '' || $this->config('auth.password', '') == '' ) {
  223. $m = new X_Page_Item_Message($this->getId(), X_Env::_('p_animedb_dashboardwarning'));
  224. $m->setType(X_Page_Item_Message::TYPE_WARNING);
  225. return new X_Page_ItemList_Message(array($m));
  226. }
  227. }
  228. /**
  229. * Animedb tests:
  230. * - check for username & password
  231. * - check for data/animedb/ path writable
  232. * @param Zend_Config $options
  233. * @param Zend_Controller_Action $controller
  234. * @return X_Page_ItemList_Message
  235. */
  236. public function getTestItems(Zend_Config $options,Zend_Controller_Action $controller) {
  237. $tests = new X_Page_ItemList_Test();
  238. $test = new X_Page_Item_Test($this->getId().'-writeaccess', '[AnimeDb] Checking for write access to /data/animedb/ folder');
  239. if ( is_writable(APPLICATION_PATH . '/../data/animedb/') ) {
  240. $test->setType(X_Page_Item_Message::TYPE_INFO);
  241. $test->setReason('Write access granted');
  242. } else {
  243. $test->setType(X_Page_Item_Message::TYPE_WARNING);
  244. $test->setReason("CookieJar file can't be stored, items fetch will be really slow");
  245. }
  246. $tests->append($test);
  247. $test = new X_Page_Item_Test($this->getId().'-credentials', '[AnimeDb] Checking for authentication credentials');
  248. if ( $this->config('auth.username', '') != '' && $this->config('auth.password', '') != '' ) {
  249. $test->setType(X_Page_Item_Message::TYPE_INFO);
  250. $test->setReason('Credentials configurated');
  251. } else {
  252. $test->setType(X_Page_Item_Message::TYPE_WARNING);
  253. $test->setReason("Credentials not configurated. Some contents could be not viewed");
  254. }
  255. $tests->append($test);
  256. return $tests;
  257. }
  258. /**
  259. * Remove cookie.jar if configs change and convert form password to password element
  260. * @param string $section
  261. * @param string $namespace
  262. * @param unknown_type $key
  263. * @param Zend_Form_Element $element
  264. * @param Zend_Form $form
  265. * @param Zend_Controller_Action $controller
  266. */
  267. public function prepareConfigElement($section, $namespace, $key, Zend_Form_Element $element, Zend_Form $form, Zend_Controller_Action $controller) {
  268. // nothing to do if this isn't the right section
  269. if ( $namespace != $this->getId() ) return;
  270. switch ($key) {
  271. // i have to convert it to a password element
  272. case 'plugins_animedb_auth_password':
  273. $password = $form->createElement('password', 'plugins_animedb_auth_password', array(
  274. 'label' => $element->getLabel(),
  275. 'description' => $element->getDescription(),
  276. 'renderPassword' => true,
  277. ));
  278. $form->plugins_animedb_auth_password = $password;
  279. break;
  280. }
  281. // remove cookie.jar if somethings has value
  282. if ( !$form->isErrors() && !is_null($element->getValue()) && file_exists(APPLICATION_PATH . '/../data/animedb/cookie.jar') ) {
  283. if ( @!unlink(APPLICATION_PATH . '/../data/animedb/cookie.jar') ) {
  284. X_Debug::e("Error removing cookie.jar");
  285. }
  286. }
  287. }
  288. /**
  289. * Fetch the list page and add items to the list
  290. * @param X_Page_ItemList_PItem $items
  291. */
  292. private function _fetchLists(X_Page_ItemList_PItem $items) {
  293. X_Debug::i("Fetching lists");
  294. $pageIndex = $this->config('index.url', 'http://animedb.tv/forum/liste.php');
  295. $htmlString = $this->_loadPage($pageIndex);
  296. $dom = new Zend_Dom_Query($htmlString);
  297. // xpath index stars from 1
  298. $results = $dom->queryXpath('//div[@class="forumbits"][1]//div[@class="forumrow"]//h2[@class="forumtitle"]//a');
  299. X_Debug::i("Lists found: ".$results->count());
  300. for ( $i = 0; $i < $results->count(); $i++, $results->next()) {
  301. $current = $results->current();
  302. $label = trim(trim($current->nodeValue), chr(0xC2).chr(0xA0));
  303. $href = $current->getAttribute('href');
  304. $item = new X_Page_Item_PItem($this->getId()."-$label", $label);
  305. $item->setIcon('/images/icons/folder_32.png')
  306. ->setType(X_Page_Item_PItem::TYPE_CONTAINER)
  307. ->setCustom(__CLASS__.':location', $href)
  308. ->setLink(array(
  309. 'l' => X_Env::encode($href)
  310. ), 'default', false);
  311. if ( APPLICATION_ENV == 'development' ) {
  312. $item->setDescription($href);
  313. }
  314. $items->append($item);
  315. }
  316. }
  317. private function _fetchClassification(X_Page_ItemList_PItem $items, $category) {
  318. $lets = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,09,EXTRA';
  319. $lets = explode(',', $lets);
  320. foreach ( $lets as $l ) {
  321. $item = new X_Page_Item_PItem($this->getId()."-$l", $l);
  322. $item->setIcon('/images/icons/folder_32.png')
  323. ->setType(X_Page_Item_PItem::TYPE_CONTAINER)
  324. ->setCustom(__CLASS__.':location', "$category/$l")
  325. ->setLink(array(
  326. 'l' => X_Env::encode("$category/$l")
  327. ), 'default', false);
  328. if ( APPLICATION_ENV == 'development' ) {
  329. $item->setDescription("$category/$l");
  330. }
  331. $items->append($item);
  332. }
  333. }
  334. private function _fetchThreads(X_Page_ItemList_PItem $items, $category, $letter) {
  335. X_Debug::i("Fetching threads for $category/$letter");
  336. $baseUrl = $this->config('base.url', 'http://animedb.tv/forum/');
  337. $baseUrl .= "$category&let=$letter";
  338. $htmlString = $this->_loadPage($baseUrl);
  339. $dom = new Zend_Dom_Query($htmlString);
  340. // xpath index stars from 1
  341. $results = $dom->queryXpath('//div[@id="threadlist"]//ol//h3[@class="threadtitle"]//a[@class="title"]');
  342. X_Debug::i("Threads found: ".$results->count());
  343. for ( $i = 0; $i < $results->count(); $i++, $results->next()) {
  344. $current = $results->current();
  345. $label = trim(trim($current->nodeValue), chr(0xC2).chr(0xA0));
  346. $href = $current->getAttribute('href');
  347. // WARNING: base64 encoding of "d.php?" expose / char <.<
  348. $item = new X_Page_Item_PItem($this->getId()."-$label", $label);
  349. $item->setIcon('/images/icons/folder_32.png')
  350. ->setType(X_Page_Item_PItem::TYPE_CONTAINER)
  351. ->setCustom(__CLASS__.':location', "$category/$letter/$href")
  352. ->setLink(array(
  353. 'l' => X_Env::encode("$category/$letter/$href")
  354. ), 'default', false);
  355. if ( APPLICATION_ENV == 'development' ) {
  356. $item->setDescription("$category/$letter/$href");
  357. }
  358. $items->append($item);
  359. }
  360. }
  361. private function _fetchVideos(X_Page_ItemList_PItem $items, $category, $letter, $thread) {
  362. X_Debug::i("Fetching videos for $category/$letter/$thread");
  363. $baseUrl = $this->config('base.url', 'http://animedb.tv/forum/');
  364. $baseUrl .= "$thread";
  365. $htmlString = $this->_loadPage($baseUrl, true);
  366. if ( $this->config('scraper.alternative.enabled', false) ) {
  367. X_Debug::w("Using alternative scaper");
  368. // From a patch submitted by Valerio Moretti
  369. $this->_parseAlternativeScaper($htmlString, $items, $category, $letter, $thread);
  370. // all items should be in the list. It's useless to continue
  371. return;
  372. }
  373. $dom = new Zend_Dom_Query($htmlString);
  374. // xpath index stars from 1
  375. $results = $dom->queryXpath('//ol[@id="posts"]/li[1]//div[@class="content"]//a');
  376. X_Debug::i("Links found: ".$results->count());
  377. $found = false;
  378. for ( $i = 0; $i < $results->count(); $i++, $results->next()) {
  379. $current = $results->current();
  380. $label = trim(trim($current->nodeValue), chr(0xC2).chr(0xA0));
  381. if ( $label == '') {
  382. $label = X_Env::_('p_animedb_nonamevideo');
  383. }
  384. $href = $current->getAttribute('href');
  385. try {
  386. $hoster = $this->helpers()->hoster()->findHoster($href);
  387. } catch ( Exception $e) {
  388. // no hoster = no valid href
  389. continue;
  390. }
  391. $label .= " [".ucfirst($hoster->getId())."]";
  392. $href = "{$hoster->getId()}:{$hoster->getResourceId($href)}";
  393. $found = true;
  394. X_Debug::i("Valid link found: $href");
  395. $item = new X_Page_Item_PItem($this->getId()."-$label", $label);
  396. $item->setIcon('/images/icons/folder_32.png')
  397. ->setType(X_Page_Item_PItem::TYPE_ELEMENT)
  398. ->setCustom(__CLASS__.':location', "$category/$letter/$thread/$href")
  399. ->setLink(array(
  400. 'action' => 'mode',
  401. 'l' => X_Env::encode("$category/$letter/$thread/$href")
  402. ), 'default', false);
  403. if ( APPLICATION_ENV == 'development' ) {
  404. $item->setDescription("$category/$letter/$thread/$href");
  405. }
  406. $items->append($item);
  407. }
  408. /*
  409. if (!$found) {
  410. $item = new X_Page_Item_PItem($this->getId().'-ops', X_Env::_('p_animedb_opsnovideo'));
  411. $item->setType(X_Page_Item_PItem::TYPE_ELEMENT)
  412. ->setLink(X_Env::completeUrl(
  413. //$urlHelper->url()
  414. ));
  415. $items->append($item);
  416. }
  417. */
  418. }
  419. /**
  420. * Find links using an alternative way
  421. * @author Valerio Moretti
  422. */
  423. private function _parseAlternativeScaper($htmlString, X_Page_ItemList_PItem $items, $category, $letter, $thread) {
  424. //mi suddivido il post in righe
  425. $htmlRows = explode('<br />', $htmlString);
  426. /*
  427. //qua volevo selezionarmi solo il codice del post per rendere il tutto piu' veloce
  428. //pero' sbaglio qualcosa e non mi funziona
  429. $dom = new Zend_Dom_Query($htmlString);
  430. $content = $dom->queryXpath('//ol[@id="posts"]/li[1]//div[@class="content"]');
  431. $htmlPost = $content->current();
  432. $htmlRows = explode('<br />', $htmlPost);
  433. */
  434. //analizzo riga per riga
  435. foreach($htmlRows as $row)
  436. {
  437. //la mia ignoranza del Xpath e' immensa e questo e' l'unico modo che ho trovato per farlo funzionare
  438. $row = '<root>'.$row.'</root>';
  439. $dom = new Zend_Dom_Query($row);
  440. // xpath index stars from 1
  441. $results = $dom->queryXpath('//a');
  442. X_Debug::i("Links found: ".$results->count());
  443. $found = false;
  444. $title = ''; //il testo del primo link della riga
  445. for ( $i = 0; $i < $results->count(); $i++, $results->next()) {
  446. $current = $results->current();
  447. $label = trim(trim($current->nodeValue), chr(0xC2).chr(0xA0));
  448. if ( $label == '') {
  449. $label = X_Env::_('p_animedb_nonamevideo');
  450. }
  451. if ($title == '') {
  452. $title = $label;
  453. }
  454. $href = $current->getAttribute('href');
  455. try {
  456. $hoster = $this->helpers()->hoster()->findHoster($href);
  457. } catch ( Exception $e) {
  458. // no hoster = no valid href
  459. continue;
  460. }
  461. $href = "{$hoster->getId()}:{$hoster->getResourceId($href)}";
  462. $label = $label == $title ? $label : $title.' | '.$label;
  463. $label .= " [".ucfirst($hoster->getId())."]";
  464. $found = true;
  465. X_Debug::i("Valid link found: $href");
  466. $item = new X_Page_Item_PItem($this->getId()."-$label", $label);
  467. $item->setIcon('/images/icons/folder_32.png')
  468. ->setType(X_Page_Item_PItem::TYPE_ELEMENT)
  469. ->setCustom(__CLASS__.':location', "$category/$letter/$thread/$href")
  470. ->setLink(array(
  471. 'action' => 'mode',
  472. 'l' => X_Env::encode("$category/$letter/$thread/$href")
  473. ), 'default', false);
  474. if ( APPLICATION_ENV == 'development' ) {
  475. $item->setDescription("$category/$letter/$thread/$href");
  476. }
  477. $items->append($item);
  478. }
  479. }
  480. }
  481. private function _loadPage($uri, $forceAuth = false) {
  482. X_Debug::i("Loading page $uri");
  483. $http = new Zend_Http_Client($uri, array(
  484. 'maxredirects' => $this->config('request.maxredirects', 10),
  485. 'timeout' => $this->config('request.timeout', 10),
  486. 'keepalive' => true
  487. ));
  488. $http->setHeaders(array(
  489. $this->config('hide.useragent', false) ? 'User-Agent: vlc-shares/'.X_VlcShares::VERSION : 'User-Agent: Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20101019 Firefox/4.0.1'
  490. //'Accept-encoding' => 'deflate',
  491. ));
  492. $jarFile = APPLICATION_PATH . '/../data/animedb/cookie.jar';
  493. $ns = new Zend_Session_Namespace(__CLASS__);
  494. if ( $this->jar == null ) {
  495. if ( false && isset($ns->jar) && $ns->jar instanceof Zend_Http_CookieJar ) {
  496. $this->jar = $ns->jar;
  497. X_Debug::i('Loading stored authentication in Session');
  498. } elseif ( file_exists($jarFile) ) {
  499. $this->jar = new Zend_Http_CookieJar();
  500. $cookies = unserialize(file_get_contents($jarFile));
  501. foreach ($cookies as $c) {
  502. $_c = new Zend_Http_Cookie($c['name'], $c['value'], $c['domain'], $c['exp'], $c['path']);
  503. $this->jar->addCookie($_c);
  504. }
  505. X_Debug::i('Loading stored authentication in File');
  506. }
  507. }
  508. $http->setCookieJar($this->jar);
  509. //time to make the request
  510. $response = $http->request();
  511. $htmlString = $response->getBody();
  512. //X_Debug::i($htmlString);
  513. // before return the page, I have to check if i'm authenticated
  514. // TODO REMOVE AUTH
  515. if ( $forceAuth && $this->config('auth.username', '') != '' && $this->config('auth.password', '') != '' && !$this->_isAuthenticated($htmlString) ) {
  516. X_Debug::i("Autentication needed");
  517. $token = $this->_getSecurityToken($htmlString);
  518. //$sValue = $this->_getSValue($htmlString);
  519. // do new login
  520. $http->setCookieJar(true);
  521. $pageLogin = $this->config('login.url', 'http://animedb.tv/forum/login.php?do=login');
  522. $http->setUri($pageLogin);
  523. $http->setParameterPost ( array (
  524. // TODO REMOVE AUTH
  525. 'vb_login_username' => (string) $this->config('auth.username', ''),
  526. 'vb_login_password' => (string) $this->config('auth.password', ''),
  527. 'vb_login_password_hint' => 'Password',
  528. 'vb_login_md5password' => '',
  529. 'vb_login_md5password_utf' => '',
  530. 'securitytoken' => $token,
  531. 'do' => 'login',
  532. 'cookieuser' => 1,
  533. 's' => '',
  534. 'x' => 13,
  535. 'y' => 30
  536. ) );
  537. // TODO remove this
  538. if ( APPLICATION_ENV == 'development' ) {
  539. $response = $http->request(Zend_Http_Client::POST);
  540. if ( !$this->_isAuthenticated($response->getBody(), '<p class="blockrow restore">Grazie per esserti collegato,' )) {
  541. X_Debug::w('Wrong credentials or authentication procedure doesn\'t work');
  542. } else {
  543. X_Debug::w('Client authenticated. Full access granted');
  544. }
  545. //X_Debug::i($response->getBody());
  546. } else {
  547. $http->request(Zend_Http_Client::POST);
  548. }
  549. $this->jar = $http->getCookieJar();
  550. // store the cookiejar
  551. $cks = $this->jar->getAllCookies(Zend_Http_CookieJar::COOKIE_OBJECT);
  552. foreach ($cks as $i => $c) {
  553. /* @var $c Zend_Http_Cookie */
  554. $cks[$i] = array(
  555. 'domain' => $c->getDomain(),
  556. 'exp' => $c->getExpiryTime(),
  557. 'name' => $c->getName(),
  558. 'path' => $c->getPath(),
  559. 'value' => $c->getValue()
  560. );
  561. }
  562. if ( @file_put_contents($jarFile, serialize($cks), LOCK_EX) === false ) {
  563. X_Debug::e('Error while writing jar file. Check permissions. Everything will work, but much more slower');
  564. }
  565. //$ns->jar = $this->jar;
  566. // time to do a new old request
  567. //$http->resetParameters();
  568. $http->setUri($uri);
  569. $response = $http->request(Zend_Http_Client::GET);
  570. $htmlString = $response->getBody();
  571. //X_Debug::i($htmlString);
  572. }
  573. return $htmlString;
  574. }
  575. /**
  576. * Search the html string for pattern that
  577. * give info about authentication
  578. * @param string $htmlString an animedb page
  579. */
  580. private function _isAuthenticated($htmlString, $pattern = '<li class="welcomelink">') {
  581. //$pattern = '<li class="welcomelink">';
  582. return ( strpos($htmlString, $pattern) !== false );
  583. }
  584. private function _getSecurityToken($htmlString) {
  585. $pattern = 'var SECURITYTOKEN = "';
  586. $start = strpos($htmlString, $pattern);
  587. if ( $start === false ) {
  588. return '';
  589. }
  590. $start += strlen($pattern);
  591. $end = strpos($htmlString, '"', $start);
  592. $token = substr($htmlString, $start, $end - $start);
  593. X_Debug::i('Security token: '.$token);
  594. return $token;
  595. }
  596. private function _getSValue($htmlString) {
  597. $pattern = '<input type="hidden" name="s" value="';
  598. $start = strpos($htmlString, $pattern);
  599. if ( $start === false ) {
  600. return '';
  601. }
  602. $start += strlen($pattern);
  603. $end = strpos($htmlString, '"', $start);
  604. $token = substr($htmlString, $start, $end - $start);
  605. X_Debug::i('S value: '.$token);
  606. return $token;
  607. }
  608. }