PageRenderTime 44ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/public/zf-demos/Zend/Gdata/YouTubeVideoApp/operations.php

https://bitbucket.org/hieronim1981/tunethemusic
PHP | 1097 lines | 755 code | 112 blank | 230 comment | 64 complexity | 1c326a6bca41c5caacafa25ab6d830e2 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Gdata
  17. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /**
  21. * PHP sample code for the YouTube data API. Utilizes the Zend Framework
  22. * Zend_Gdata component to communicate with the YouTube data API.
  23. *
  24. * Requires the Zend Framework Zend_Gdata component and PHP >= 5.1.4
  25. * This sample is run from within a web browser. These files are required:
  26. * session_details.php - a script to view log output and session variables
  27. * operations.php - the main logic, which interfaces with the YouTube API
  28. * index.php - the HTML to represent the web UI, contains some PHP
  29. * video_app.css - the CSS to define the interface style
  30. * video_app.js - the JavaScript used to provide the video list AJAX interface
  31. *
  32. * NOTE: If using in production, some additional precautions with regards
  33. * to filtering the input data should be used. This code is designed only
  34. * for demonstration purposes.
  35. */
  36. require_once 'Zend/Loader.php';
  37. Zend_Loader::loadClass('Zend_Gdata_YouTube');
  38. Zend_Loader::loadClass('Zend_Gdata_AuthSub');
  39. Zend_Loader::loadClass('Zend_Gdata_App_Exception');
  40. /*
  41. * The main controller logic.
  42. *
  43. * POST used for all authenticated requests
  44. * otherwise use GET for retrieve and supplementary values
  45. */
  46. session_start();
  47. setLogging('on');
  48. generateUrlInformation();
  49. if (!isset($_POST['operation'])) {
  50. // if a GET variable is set then process the token upgrade
  51. if (isset($_GET['token'])) {
  52. updateAuthSubToken($_GET['token']);
  53. } else {
  54. if (loggingEnabled()) {
  55. logMessage('reached operations.php without $_POST or $_GET variables set', 'error');
  56. header('Location: index.php');
  57. }
  58. }
  59. }
  60. $operation = $_POST['operation'];
  61. switch ($operation) {
  62. case 'create_upload_form':
  63. createUploadForm($_POST['videoTitle'],
  64. $_POST['videoDescription'],
  65. $_POST['videoCategory'],
  66. $_POST['videoTags']);
  67. break;
  68. case 'edit_meta_data':
  69. editVideoData($_POST['newVideoTitle'],
  70. $_POST['newVideoDescription'],
  71. $_POST['newVideoCategory'],
  72. $_POST['newVideoTags'],
  73. $_POST['videoId']);
  74. break;
  75. case 'check_upload_status':
  76. checkUpload($_POST['videoId']);
  77. break;
  78. case 'delete_video':
  79. deleteVideo($_POST['videoId']);
  80. break;
  81. case 'auth_sub_request':
  82. generateAuthSubRequestLink();
  83. break;
  84. case 'auth_sub_token_upgrade':
  85. updateAuthSubToken($_GET['token']);
  86. break;
  87. case 'clear_session_var':
  88. clearSessionVar($_POST['name']);
  89. break;
  90. case 'retrieve_playlists':
  91. retrievePlaylists();
  92. break;
  93. case 'create_playlist':
  94. createPlaylist($_POST['playlistTitle'], $_POST['playlistDescription']);
  95. break;
  96. case 'delete_playlist':
  97. deletePlaylist($_POST['playlistTitle']);
  98. break;
  99. case 'update_playlist':
  100. updatePlaylist($_POST['newPlaylistTitle'],
  101. $_POST['newPlaylistDescription'],
  102. $_POST['oldPlaylistTitle']);
  103. break;
  104. case (strcmp(substr($operation, 0, 7), 'search_') == 0):
  105. // initialize search specific information
  106. $searchType = substr($operation, 7);
  107. searchVideos($searchType, $_POST['searchTerm'], $_POST['startIndex'],
  108. $_POST['maxResults']);
  109. break;
  110. case 'show_video':
  111. echoVideoPlayer($_POST['videoId']);
  112. break;
  113. default:
  114. unsupportedOperation($_POST);
  115. break;
  116. }
  117. /**
  118. * Perform a search on youtube. Passes the result feed to echoVideoList.
  119. *
  120. * @param string $searchType The type of search to perform.
  121. * If set to 'owner' then attempt to authenticate.
  122. * @param string $searchTerm The term to search on.
  123. * @param string $startIndex Start retrieving search results from this index.
  124. * @param string $maxResults The number of results to retrieve.
  125. * @return void
  126. */
  127. function searchVideos($searchType, $searchTerm, $startIndex, $maxResults)
  128. {
  129. // create an unauthenticated service object
  130. $youTubeService = new Zend_Gdata_YouTube();
  131. $query = $youTubeService->newVideoQuery();
  132. $query->setQuery($searchTerm);
  133. $query->setStartIndex($startIndex);
  134. $query->setMaxResults($maxResults);
  135. switch ($searchType) {
  136. case 'most_viewed':
  137. $query->setFeedType('most viewed');
  138. $query->setTime('this_week');
  139. $feed = $youTubeService->getVideoFeed($query);
  140. break;
  141. case 'most_recent':
  142. $query->setFeedType('most recent');
  143. $query->setTime('this_week');
  144. $feed = $youTubeService->getVideoFeed($query);
  145. break;
  146. case 'recently_featured':
  147. $query->setFeedType('recently featured');
  148. $feed = $youTubeService->getVideoFeed($query);
  149. break;
  150. case 'top_rated':
  151. $query->setFeedType('top rated');
  152. $query->setTime('this_week');
  153. $feed = $youTubeService->getVideoFeed($query);
  154. break;
  155. case 'username':
  156. $feed = $youTubeService->getUserUploads($searchTerm);
  157. break;
  158. case 'all':
  159. $feed = $youTubeService->getVideoFeed($query);
  160. break;
  161. case 'owner':
  162. $httpClient = getAuthSubHttpClient();
  163. $youTubeService = new Zend_Gdata_YouTube($httpClient);
  164. try {
  165. $feed = $youTubeService->getUserUploads('default');
  166. if (loggingEnabled()) {
  167. logMessage($httpClient->getLastRequest(), 'request');
  168. logMessage($httpClient->getLastResponse()->getBody(),
  169. 'response');
  170. }
  171. } catch (Zend_Gdata_App_HttpException $httpException) {
  172. print 'ERROR ' . $httpException->getMessage()
  173. . ' HTTP details<br /><textarea cols="100" rows="20">'
  174. . $httpException->getRawResponseBody()
  175. . '</textarea><br />'
  176. . '<a href="session_details.php">'
  177. . 'click here to view details of last request</a><br />';
  178. return;
  179. } catch (Zend_Gdata_App_Exception $e) {
  180. print 'ERROR - Could not retrieve users video feed: '
  181. . $e->getMessage() . '<br />';
  182. return;
  183. }
  184. echoVideoList($feed, true);
  185. return;
  186. default:
  187. echo 'ERROR - Unknown search type - \'' . $searchType . '\'';
  188. return;
  189. }
  190. if (loggingEnabled()) {
  191. $httpClient = $youTubeService->getHttpClient();
  192. logMessage($httpClient->getLastRequest(), 'request');
  193. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  194. }
  195. echoVideoList($feed);
  196. }
  197. /**
  198. * Finds the URL for the flash representation of the specified video.
  199. *
  200. * @param Zend_Gdata_YouTube_VideoEntry $entry The video entry
  201. * @return (string|null) The URL or null, if the URL is not found
  202. */
  203. function findFlashUrl($entry)
  204. {
  205. foreach ($entry->mediaGroup->content as $content) {
  206. if ($content->type === 'application/x-shockwave-flash') {
  207. return $content->url;
  208. }
  209. }
  210. return null;
  211. }
  212. /**
  213. * Check the upload status of a video
  214. *
  215. * @param string $videoId The video to check.
  216. * @return string A message about the video's status.
  217. */
  218. function checkUpload($videoId)
  219. {
  220. $httpClient = getAuthSubHttpClient();
  221. $youTubeService = new Zend_Gdata_YouTube($httpClient);
  222. $feed = $youTubeService->getuserUploads('default');
  223. $message = 'No further status information available yet.';
  224. foreach($feed as $videoEntry) {
  225. if ($videoEntry->getVideoId() == $videoId) {
  226. // check if video is in draft status
  227. try {
  228. $control = $videoEntry->getControl();
  229. } catch (Zend_Gdata_App_Exception $e) {
  230. print 'ERROR - not able to retrieve control element '
  231. . $e->getMessage();
  232. return;
  233. }
  234. if ($control instanceof Zend_Gdata_App_Extension_Control) {
  235. if (($control->getDraft() != null) &&
  236. ($control->getDraft()->getText() == 'yes')) {
  237. $state = $videoEntry->getVideoState();
  238. if ($state instanceof Zend_Gdata_YouTube_Extension_State) {
  239. $message = 'Upload status: ' . $state->getName() . ' '
  240. . $state->getText();
  241. } else {
  242. print $message;
  243. }
  244. }
  245. }
  246. }
  247. }
  248. print $message;
  249. }
  250. /**
  251. * Store location of the demo application into session variables.
  252. *
  253. * @return void
  254. */
  255. function generateUrlInformation()
  256. {
  257. if (!isset($_SESSION['operationsUrl']) || !isset($_SESSION['homeUrl'])) {
  258. $_SESSION['operationsUrl'] = 'http://'. $_SERVER['HTTP_HOST']
  259. . $_SERVER['PHP_SELF'];
  260. $path = explode('/', $_SERVER['PHP_SELF']);
  261. $path[count($path)-1] = 'index.php';
  262. $_SESSION['homeUrl'] = 'http://'. $_SERVER['HTTP_HOST']
  263. . implode('/', $path);
  264. }
  265. }
  266. /**
  267. * Log a message to the session variable array.
  268. *
  269. * @param string $message The message to log.
  270. * @param string $messageType The type of message to log.
  271. * @return void
  272. */
  273. function logMessage($message, $messageType)
  274. {
  275. if (!isset($_SESSION['log_maxLogEntries'])) {
  276. $_SESSION['log_maxLogEntries'] = 20;
  277. }
  278. if (!isset($_SESSION['log_currentCounter'])) {
  279. $_SESSION['log_currentCounter'] = 0;
  280. }
  281. $currentCounter = $_SESSION['log_currentCounter'];
  282. $currentCounter++;
  283. if ($currentCounter > $_SESSION['log_maxLogEntries']) {
  284. $_SESSION['log_currentCounter'] = 0;
  285. }
  286. $logLocation = 'log_entry_'. $currentCounter . '_' . $messageType;
  287. $_SESSION[$logLocation] = $message;
  288. $_SESSION['log_currentCounter'] = $currentCounter;
  289. }
  290. /**
  291. * Update an existing video's meta-data.
  292. *
  293. * @param string $newVideoTitle The new title for the video entry.
  294. * @param string $newVideoDescription The new description for the video entry.
  295. * @param string $newVideoCategory The new category for the video entry.
  296. * @param string $newVideoTags The new set of tags for the video entry (whitespace separated).
  297. * @param string $videoId The video id for the video to be edited.
  298. * @return void
  299. */
  300. function editVideoData($newVideoTitle, $newVideoDescription, $newVideoCategory, $newVideoTags, $videoId)
  301. {
  302. $httpClient = getAuthSubHttpClient();
  303. $youTubeService = new Zend_Gdata_YouTube($httpClient);
  304. $feed = $youTubeService->getVideoFeed('https://gdata.youtube.com/feeds/users/default/uploads');
  305. $videoEntryToUpdate = null;
  306. foreach($feed as $entry) {
  307. if ($entry->getVideoId() == $videoId) {
  308. $videoEntryToUpdate = $entry;
  309. break;
  310. }
  311. }
  312. if (!$videoEntryToUpdate instanceof Zend_Gdata_YouTube_VideoEntry) {
  313. print 'ERROR - Could not find a video entry with id ' . $videoId
  314. . '<br />' . printCacheWarning();
  315. return;
  316. }
  317. try {
  318. $putUrl = $videoEntryToUpdate->getEditLink()->getHref();
  319. } catch (Zend_Gdata_App_Exception $e) {
  320. print 'ERROR - Could not obtain video entry\'s edit link: '
  321. . $e->getMessage() . '<br />';
  322. return;
  323. }
  324. $videoEntryToUpdate->setVideoTitle($newVideoTitle);
  325. $videoEntryToUpdate->setVideoDescription($newVideoDescription);
  326. $videoEntryToUpdate->setVideoCategory($newVideoCategory);
  327. // convert tags from space separated to comma separated
  328. $videoTagsArray = explode(' ', trim($newVideoTags));
  329. // strip out empty array elements
  330. foreach($videoTagsArray as $key => $value) {
  331. if (strlen($value) < 2) {
  332. unset($videoTagsArray[$key]);
  333. }
  334. }
  335. $videoEntryToUpdate->setVideoTags(implode(', ', $videoTagsArray));
  336. try {
  337. $updatedEntry = $youTubeService->updateEntry($videoEntryToUpdate, $putUrl);
  338. if (loggingEnabled()) {
  339. logMessage($httpClient->getLastRequest(), 'request');
  340. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  341. }
  342. } catch (Zend_Gdata_App_HttpException $httpException) {
  343. print 'ERROR ' . $httpException->getMessage()
  344. . ' HTTP details<br /><textarea cols="100" rows="20">'
  345. . $httpException->getRawResponseBody()
  346. . '</textarea><br />'
  347. . '<a href="session_details.php">'
  348. . 'click here to view details of last request</a><br />';
  349. return;
  350. } catch (Zend_Gdata_App_Exception $e) {
  351. print 'ERROR - Could not post video meta-data: ' . $e->getMessage();
  352. return;
  353. }
  354. print 'Entry updated successfully.<br /><a href="#" onclick="'
  355. . 'ytVideoApp.presentFeed(\'search_owner\', 5, 0, \'none\'); '
  356. . 'ytVideoApp.refreshSearchResults();" >'
  357. . '(refresh your video listing)</a><br />'
  358. . printCacheWarning();
  359. }
  360. /**
  361. * Create upload form by sending the incoming video meta-data to youtube and
  362. * retrieving a new entry. Prints form HTML to page.
  363. *
  364. * @param string $VideoTitle The title for the video entry.
  365. * @param string $VideoDescription The description for the video entry.
  366. * @param string $VideoCategory The category for the video entry.
  367. * @param string $VideoTags The set of tags for the video entry (whitespace separated).
  368. * @param string $nextUrl (optional) The URL to redirect back to after form upload has completed.
  369. * @return void
  370. */
  371. function createUploadForm($videoTitle, $videoDescription, $videoCategory, $videoTags, $nextUrl = null)
  372. {
  373. $httpClient = getAuthSubHttpClient();
  374. $youTubeService = new Zend_Gdata_YouTube($httpClient);
  375. $newVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
  376. $newVideoEntry->setVideoTitle($videoTitle);
  377. $newVideoEntry->setVideoDescription($videoDescription);
  378. //make sure first character in category is capitalized
  379. $videoCategory = strtoupper(substr($videoCategory, 0, 1))
  380. . substr($videoCategory, 1);
  381. $newVideoEntry->setVideoCategory($videoCategory);
  382. // convert videoTags from whitespace separated into comma separated
  383. $videoTagsArray = explode(' ', trim($videoTags));
  384. $newVideoEntry->setVideoTags(implode(', ', $videoTagsArray));
  385. $tokenHandlerUrl = 'https://gdata.youtube.com/action/GetUploadToken';
  386. try {
  387. $tokenArray = $youTubeService->getFormUploadToken($newVideoEntry, $tokenHandlerUrl);
  388. if (loggingEnabled()) {
  389. logMessage($httpClient->getLastRequest(), 'request');
  390. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  391. }
  392. } catch (Zend_Gdata_App_HttpException $httpException) {
  393. print 'ERROR ' . $httpException->getMessage()
  394. . ' HTTP details<br /><textarea cols="100" rows="20">'
  395. . $httpException->getRawResponseBody()
  396. . '</textarea><br />'
  397. . '<a href="session_details.php">'
  398. . 'click here to view details of last request</a><br />';
  399. return;
  400. } catch (Zend_Gdata_App_Exception $e) {
  401. print 'ERROR - Could not retrieve token for syndicated upload. '
  402. . $e->getMessage()
  403. . '<br /><a href="session_details.php">'
  404. . 'click here to view details of last request</a><br />';
  405. return;
  406. }
  407. $tokenValue = $tokenArray['token'];
  408. $postUrl = $tokenArray['url'];
  409. // place to redirect user after upload
  410. if (!$nextUrl) {
  411. $nextUrl = $_SESSION['homeUrl'];
  412. }
  413. print <<< END
  414. <br /><form action="${postUrl}?nexturl=${nextUrl}"
  415. method="post" enctype="multipart/form-data">
  416. <input name="file" type="file"/>
  417. <input name="token" type="hidden" value="${tokenValue}"/>
  418. <input value="Upload Video File" type="submit" />
  419. </form>
  420. END;
  421. }
  422. /**
  423. * Deletes a Video.
  424. *
  425. * @param string $videoId Id of the video to be deleted.
  426. * @return void
  427. */
  428. function deleteVideo($videoId)
  429. {
  430. $httpClient = getAuthSubHttpClient();
  431. $youTubeService = new Zend_Gdata_YouTube($httpClient);
  432. $feed = $youTubeService->getVideoFeed('https://gdata.youtube.com/feeds/users/default/uploads');
  433. $videoEntryToDelete = null;
  434. foreach($feed as $entry) {
  435. if ($entry->getVideoId() == $videoId) {
  436. $videoEntryToDelete = $entry;
  437. break;
  438. }
  439. }
  440. // check if videoEntryToUpdate was found
  441. if (!$videoEntryToDelete instanceof Zend_Gdata_YouTube_VideoEntry) {
  442. print 'ERROR - Could not find a video entry with id ' . $videoId . '<br />';
  443. return;
  444. }
  445. try {
  446. $httpResponse = $youTubeService->delete($videoEntryToDelete);
  447. if (loggingEnabled()) {
  448. logMessage($httpClient->getLastRequest(), 'request');
  449. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  450. }
  451. } catch (Zend_Gdata_App_HttpException $httpException) {
  452. print 'ERROR ' . $httpException->getMessage()
  453. . ' HTTP details<br /><textarea cols="100" rows="20">'
  454. . $httpException->getRawResponseBody()
  455. . '</textarea><br />'
  456. . '<a href="session_details.php">'
  457. . 'click here to view details of last request</a><br />';
  458. return;
  459. } catch (Zend_Gdata_App_Exception $e) {
  460. print 'ERROR - Could not delete video: '. $e->getMessage();
  461. return;
  462. }
  463. print 'Entry deleted succesfully.<br />' . $httpResponse->getBody()
  464. . '<br /><a href="#" onclick="'
  465. . 'ytVideoApp.presentFeed(\'search_owner\', 5, 0, \'none\');"'
  466. . '">(refresh your video listing)</a><br />'
  467. . printCacheWarning();
  468. }
  469. /**
  470. * Enables logging.
  471. *
  472. * @param string $loggingOption 'on' to turn logging on, 'off' to turn logging off.
  473. * @param integer|null $maxLogItems Maximum items to log, default is 10.
  474. * @return void
  475. */
  476. function setLogging($loggingOption, $maxLogItems = 10)
  477. {
  478. switch ($loggingOption) {
  479. case 'on' :
  480. $_SESSION['logging'] = 'on';
  481. $_SESSION['log_currentCounter'] = 0;
  482. $_SESSION['log_maxLogEntries'] = $maxLogItems;
  483. break;
  484. case 'off':
  485. $_SESSION['logging'] = 'off';
  486. break;
  487. }
  488. }
  489. /**
  490. * Check whether logging is enabled.
  491. *
  492. * @return boolean Return true if session variable for logging is set to 'on'.
  493. */
  494. function loggingEnabled()
  495. {
  496. if ($_SESSION['logging'] == 'on') {
  497. return true;
  498. }
  499. }
  500. /**
  501. * Unset a specific session variable.
  502. *
  503. * @param string $name Name of the session variable to delete.
  504. * @return void
  505. */
  506. function clearSessionVar($name)
  507. {
  508. if (isset($_SESSION[$name])) {
  509. unset($_SESSION[$name]);
  510. }
  511. header('Location: session_details.php');
  512. }
  513. /**
  514. * Generate an AuthSub request Link and print it to the page.
  515. *
  516. * @param string $nextUrl URL to redirect to after performing the authentication.
  517. * @return void
  518. */
  519. function generateAuthSubRequestLink($nextUrl = null)
  520. {
  521. $scope = 'https://gdata.youtube.com';
  522. $secure = false;
  523. $session = true;
  524. if (!$nextUrl) {
  525. generateUrlInformation();
  526. $nextUrl = $_SESSION['operationsUrl'];
  527. }
  528. $url = Zend_Gdata_AuthSub::getAuthSubTokenUri($nextUrl, $scope, $secure, $session);
  529. echo '<a href="' . $url
  530. . '"><strong>Click here to authenticate with YouTube</strong></a>';
  531. }
  532. /**
  533. * Upgrade the single-use token to a session token.
  534. *
  535. * @param string $singleUseToken A valid single use token that is upgradable to a session token.
  536. * @return void
  537. */
  538. function updateAuthSubToken($singleUseToken)
  539. {
  540. try {
  541. $sessionToken = Zend_Gdata_AuthSub::getAuthSubSessionToken($singleUseToken);
  542. } catch (Zend_Gdata_App_Exception $e) {
  543. print 'ERROR - Token upgrade for ' . $singleUseToken
  544. . ' failed : ' . $e->getMessage();
  545. return;
  546. }
  547. $_SESSION['sessionToken'] = $sessionToken;
  548. generateUrlInformation();
  549. header('Location: ' . $_SESSION['homeUrl']);
  550. }
  551. /**
  552. * Convenience method to obtain an authenticted Zend_Http_Client object.
  553. *
  554. * @return Zend_Http_Client An authenticated client.
  555. */
  556. function getAuthSubHttpClient()
  557. {
  558. try {
  559. $httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
  560. } catch (Zend_Gdata_App_Exception $e) {
  561. print 'ERROR - Could not obtain authenticated Http client object. '
  562. . $e->getMessage();
  563. return;
  564. }
  565. $httpClient->setHeaders('X-GData-Key', 'key='. $_SESSION['developerKey']);
  566. return $httpClient;
  567. }
  568. /**
  569. * Echo img tags for the first thumbnail representing each video in the
  570. * specified video feed. Upon clicking the thumbnails, the video should
  571. * be presented.
  572. *
  573. * @param Zend_Gdata_YouTube_VideoFeed $feed The video feed
  574. * @return void
  575. */
  576. function echoThumbnails($feed)
  577. {
  578. foreach ($feed as $entry) {
  579. $videoId = $entry->getVideoId();
  580. $firstThumbnail = htmlspecialchars(
  581. $entry->mediaGroup->thumbnail[0]->url);
  582. echo '<img id="' . $videoId . '" class="thumbnail" src="'
  583. . $firstThumbnail .'" width="130" height="97" onclick="'
  584. . 'ytVideoApp.presentVideo(\'' . $videoId . '\', 1);" '
  585. . 'title="click to watch: ' .
  586. htmlspecialchars($entry->getVideoTitle()) . '" />';
  587. }
  588. }
  589. /**
  590. * Echo the list of videos in the specified feed.
  591. *
  592. * @param Zend_Gdata_YouTube_VideoFeed $feed The video feed.
  593. * @param boolean|null $authenticated If true then the videoList will
  594. * attempt to create additional forms to edit video meta-data.
  595. * @return void
  596. */
  597. function echoVideoList($feed, $authenticated = false)
  598. {
  599. $table = '<table id="videoResultList" class="videoList"><tbody>';
  600. $results = 0;
  601. foreach ($feed as $entry) {
  602. $videoId = $entry->getVideoId();
  603. $thumbnailUrl = 'notfound.jpg';
  604. if (count($entry->mediaGroup->thumbnail) > 0) {
  605. $thumbnailUrl = htmlspecialchars(
  606. $entry->mediaGroup->thumbnail[0]->url);
  607. }
  608. $videoTitle = htmlspecialchars($entry->getVideoTitle());
  609. $videoDescription = htmlspecialchars($entry->getVideoDescription());
  610. $videoCategory = htmlspecialchars($entry->getVideoCategory());
  611. $videoTags = $entry->getVideoTags();
  612. $table .= '<tr id="video_' . $videoId . '">'
  613. . '<td width="130"><img onclick="ytVideoApp.presentVideo(\''
  614. . $videoId. '\')" src="' . $thumbnailUrl. '" /></td>'
  615. . '<td><a href="#" onclick="ytVideoApp.presentVideo(\''
  616. . $videoId . '\')">'. stripslashes($videoTitle) . '</a>'
  617. . '<p class="videoDescription">'
  618. . stripslashes($videoDescription) . '</p>'
  619. . '<p class="videoCategory">category: ' . $videoCategory
  620. . '</p><p class="videoTags">tagged: '
  621. . htmlspecialchars(implode(', ', $videoTags)) . '</p>';
  622. if ($authenticated) {
  623. $table .= '<p class="edit">'
  624. . '<a onclick="ytVideoApp.presentMetaDataEditForm(\''
  625. . addslashes($videoTitle) . '\', \''
  626. . addslashes($videoDescription) . '\', \''
  627. . $videoCategory . '\', \''
  628. . addslashes(implode(', ', $videoTags)) . '\', \''
  629. . $videoId . '\');" href="#">edit video data</a> | '
  630. . '<a href="#" onclick="ytVideoApp.confirmDeletion(\''
  631. . $videoId
  632. . '\');">delete this video</a></p><br clear="all">';
  633. }
  634. $table .= '</td></tr>';
  635. $results++;
  636. }
  637. if ($results < 1) {
  638. echo '<br />No results found<br /><br />';
  639. } else {
  640. echo $table .'</tbody></table><br />';
  641. }
  642. }
  643. /**
  644. * Echo the video embed code, related videos and videos owned by the same user
  645. * as the specified videoId.
  646. *
  647. * @param string $videoId The video
  648. * @return void
  649. */
  650. function echoVideoPlayer($videoId)
  651. {
  652. $youTubeService = new Zend_Gdata_YouTube();
  653. try {
  654. $entry = $youTubeService->getVideoEntry($videoId);
  655. } catch (Zend_Gdata_App_HttpException $httpException) {
  656. print 'ERROR ' . $httpException->getMessage()
  657. . ' HTTP details<br /><textarea cols="100" rows="20">'
  658. . $httpException->getRawResponseBody()
  659. . '</textarea><br />'
  660. . '<a href="session_details.php">'
  661. . 'click here to view details of last request</a><br />';
  662. return;
  663. }
  664. $videoTitle = htmlspecialchars($entry->getVideoTitle());
  665. $videoUrl = htmlspecialchars(findFlashUrl($entry));
  666. $relatedVideoFeed = getRelatedVideos($entry->getVideoId());
  667. $topRatedFeed = getTopRatedVideosByUser($entry->author[0]->name);
  668. print <<<END
  669. <b>$videoTitle</b><br />
  670. <object width="425" height="350">
  671. <param name="movie" value="${videoUrl}&autoplay=1"></param>
  672. <param name="wmode" value="transparent"></param>
  673. <embed src="${videoUrl}&autoplay=1" type="application/x-shockwave-flash" wmode="transparent"
  674. width="425" height="350"></embed>
  675. </object>
  676. END;
  677. echo '<br />';
  678. echoVideoMetadata($entry);
  679. echo '<br /><b>Related:</b><br />';
  680. echoThumbnails($relatedVideoFeed);
  681. echo '<br /><b>Top rated videos by user:</b><br />';
  682. echoThumbnails($topRatedFeed);
  683. }
  684. /**
  685. * Returns a feed of videos related to the specified video
  686. *
  687. * @param string $videoId The video
  688. * @return Zend_Gdata_YouTube_VideoFeed The feed of related videos
  689. */
  690. function getRelatedVideos($videoId)
  691. {
  692. $youTubeService = new Zend_Gdata_YouTube();
  693. $ytQuery = $youTubeService->newVideoQuery();
  694. // show videos related to the specified video
  695. $ytQuery->setFeedType('related', $videoId);
  696. // order videos by rating
  697. $ytQuery->setOrderBy('rating');
  698. // retrieve a maximum of 5 videos
  699. $ytQuery->setMaxResults(5);
  700. // retrieve only embeddable videos
  701. $ytQuery->setFormat(5);
  702. return $youTubeService->getVideoFeed($ytQuery);
  703. }
  704. /**
  705. * Returns a feed of top rated videos for the specified user
  706. *
  707. * @param string $user The username
  708. * @return Zend_Gdata_YouTube_VideoFeed The feed of top rated videos
  709. */
  710. function getTopRatedVideosByUser($user)
  711. {
  712. $userVideosUrl = 'https://gdata.youtube.com/feeds/users/' .
  713. $user . '/uploads';
  714. $youTubeService = new Zend_Gdata_YouTube();
  715. $ytQuery = $youTubeService->newVideoQuery($userVideosUrl);
  716. // order by the rating of the videos
  717. $ytQuery->setOrderBy('rating');
  718. // retrieve a maximum of 5 videos
  719. $ytQuery->setMaxResults(5);
  720. // retrieve only embeddable videos
  721. $ytQuery->setFormat(5);
  722. return $youTubeService->getVideoFeed($ytQuery);
  723. }
  724. /**
  725. * Echo video metadata
  726. *
  727. * @param Zend_Gdata_YouTube_VideoEntry $entry The video entry
  728. * @return void
  729. */
  730. function echoVideoMetadata($entry)
  731. {
  732. $title = htmlspecialchars($entry->getVideoTitle());
  733. $description = htmlspecialchars($entry->getVideoDescription());
  734. $authorUsername = htmlspecialchars($entry->author[0]->name);
  735. $authorUrl = 'http://www.youtube.com/profile?user=' .
  736. $authorUsername;
  737. $tags = htmlspecialchars(implode(', ', $entry->getVideoTags()));
  738. $duration = htmlspecialchars($entry->getVideoDuration());
  739. $watchPage = htmlspecialchars($entry->getVideoWatchPageUrl());
  740. $viewCount = htmlspecialchars($entry->getVideoViewCount());
  741. $rating = 0;
  742. if (isset($entry->rating->average)) {
  743. $rating = $entry->rating->average;
  744. }
  745. $numRaters = 0;
  746. if (isset($entry->rating->numRaters)) {
  747. $numRaters = $entry->rating->numRaters;
  748. }
  749. $flashUrl = htmlspecialchars(findFlashUrl($entry));
  750. print <<<END
  751. <b>Title:</b> ${title}<br />
  752. <b>Description:</b> ${description}<br />
  753. <b>Author:</b> <a href="${authorUrl}">${authorUsername}</a><br />
  754. <b>Tags:</b> ${tags}<br />
  755. <b>Duration:</b> ${duration} seconds<br />
  756. <b>View count:</b> ${viewCount}<br />
  757. <b>Rating:</b> ${rating} (${numRaters} ratings)<br />
  758. <b>Flash:</b> <a href="${flashUrl}">${flashUrl}</a><br />
  759. <b>Watch page:</b> <a href="${watchPage}">${watchPage}</a> <br />
  760. END;
  761. }
  762. /**
  763. * Print message about YouTube caching.
  764. *
  765. * @return string A message
  766. */
  767. function printCacheWarning()
  768. {
  769. return '<p class="note">'
  770. . 'Please note that the change may not be reflected in the API '
  771. . 'immediately due to caching.<br/>'
  772. . 'Please refer to the API documentation for more details.</p>';
  773. }
  774. /**
  775. * Retrieve playlists for the currently authenticated user and print.
  776. * @return void
  777. */
  778. function retrievePlaylists()
  779. {
  780. $httpClient = getAuthSubHttpClient();
  781. $youTubeService = new Zend_Gdata_YouTube($httpClient);
  782. $feed = $youTubeService->getPlaylistListFeed('default');
  783. if (loggingEnabled()) {
  784. logMessage($httpClient->getLastRequest(), 'request');
  785. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  786. }
  787. if (!$feed instanceof Zend_Gdata_YouTube_PlaylistListFeed) {
  788. print 'ERROR - Could not retrieve playlists<br />'.
  789. printCacheWarning();
  790. return;
  791. }
  792. $playlistEntries = '<ul>';
  793. $entriesFound = 0;
  794. foreach($feed as $entry) {
  795. $playlistTitle = $entry->getTitleValue();
  796. $playlistDescription = $entry->getDescription()->getText();
  797. $playlistEntries .= '<li><h3>' . $playlistTitle
  798. . '</h3>' . $playlistDescription . ' | '
  799. . '<a href="#" onclick="ytVideoApp.prepareUpdatePlaylistForm(\''
  800. . $playlistTitle . '\', \'' . $playlistDescription
  801. . '\'); ">update</a> | '
  802. . '<a href="#" onclick="ytVideoApp.confirmPlaylistDeletion(\''
  803. . $playlistTitle . '\');">delete</a></li>';
  804. $entriesFound++;
  805. }
  806. $playlistEntries .= '</ul><br /><a href="#" '
  807. . 'onclick="ytVideoApp.prepareCreatePlaylistForm(); '
  808. . 'return false;">'
  809. . 'Add new playlist</a><br />'
  810. . '<div id="addNewPlaylist"></div>';
  811. if (loggingEnabled()) {
  812. logMessage($httpClient->getLastRequest(), 'request');
  813. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  814. }
  815. if ($entriesFound > 0) {
  816. print $playlistEntries;
  817. } else {
  818. print 'No playlists found';
  819. }
  820. }
  821. /**
  822. * Create a new playlist for the currently authenticated user
  823. *
  824. * @param string $playlistTitle Title of the new playlist
  825. * @param string $playlistDescription Description for the new playlist
  826. * @return void
  827. */
  828. function createPlaylist($playlistTitle, $playlistDescription)
  829. {
  830. $httpClient = getAuthSubHttpClient();
  831. $youTubeService = new Zend_Gdata_YouTube($httpClient);
  832. $feed = $youTubeService->getPlaylistListFeed('default');
  833. if (loggingEnabled()) {
  834. logMessage($httpClient->getLastRequest(), 'request');
  835. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  836. }
  837. $newPlaylist = $youTubeService->newPlaylistListEntry();
  838. $newPlaylist->description = $youTubeService->newDescription()->setText($playlistDescription);
  839. $newPlaylist->title = $youTubeService->newTitle()->setText($playlistDescription);
  840. if (!$feed instanceof Zend_Gdata_YouTube_PlaylistListFeed) {
  841. print 'ERROR - Could not retrieve playlists<br />'
  842. . printCacheWarning();
  843. return;
  844. }
  845. $playlistFeedUrl = 'https://gdata.youtube.com/feeds/users/default/playlists';
  846. try {
  847. $updatedEntry = $youTubeService->insertEntry($newPlaylist, $playlistFeedUrl);
  848. if (loggingEnabled()) {
  849. logMessage($httpClient->getLastRequest(), 'request');
  850. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  851. }
  852. } catch (Zend_Gdata_App_HttpException $httpException) {
  853. print 'ERROR ' . $httpException->getMessage()
  854. . ' HTTP details<br /><textarea cols="100" rows="20">'
  855. . $httpException->getRawResponseBody()
  856. . '</textarea><br />'
  857. . '<a href="session_details.php">'
  858. . 'click here to view details of last request</a><br />';
  859. return;
  860. } catch (Zend_Gdata_App_Exception $e) {
  861. print 'ERROR - Could not create new playlist: ' . $e->getMessage();
  862. return;
  863. }
  864. print 'Playlist added succesfully.<br /><a href="#" onclick="'
  865. . 'ytVideoApp.retrievePlaylists();"'
  866. . '">(refresh your playlist listing)</a><br />'
  867. . printCacheWarning();
  868. }
  869. /**
  870. * Delete a playlist
  871. *
  872. * @param string $playlistTitle Title of the playlist to be deleted
  873. * @return void
  874. */
  875. function deletePlaylist($playlistTitle)
  876. {
  877. $httpClient = getAuthSubHttpClient();
  878. $youTubeService = new Zend_Gdata_YouTube($httpClient);
  879. $feed = $youTubeService->getPlaylistListFeed('default');
  880. if (loggingEnabled()) {
  881. logMessage($httpClient->getLastRequest(), 'request');
  882. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  883. }
  884. $playlistEntryToDelete = null;
  885. foreach($feed as $playlistEntry) {
  886. if ($playlistEntry->getTitleValue() == $playlistTitle) {
  887. $playlistEntryToDelete = $playlistEntry;
  888. break;
  889. }
  890. }
  891. if (!$playlistEntryToDelete instanceof Zend_Gdata_YouTube_PlaylistListEntry) {
  892. print 'ERROR - Could not retrieve playlist to be deleted<br />'
  893. . printCacheWarning();
  894. return;
  895. }
  896. try {
  897. $response = $playlistEntryToDelete->delete();
  898. if (loggingEnabled()) {
  899. logMessage($httpClient->getLastRequest(), 'request');
  900. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  901. }
  902. } catch (Zend_Gdata_App_HttpException $httpException) {
  903. print 'ERROR ' . $httpException->getMessage()
  904. . ' HTTP details<br /><textarea cols="100" rows="20">'
  905. . $httpException->getRawResponseBody()
  906. . '</textarea><br />'
  907. . '<a href="session_details.php">'
  908. . 'click here to view details of last request</a><br />';
  909. return;
  910. } catch (Zend_Gdata_App_Exception $e) {
  911. print 'ERROR - Could not delete the playlist: ' . $e->getMessage();
  912. return;
  913. }
  914. print 'Playlist deleted succesfully.<br />'
  915. . '<a href="#" onclick="ytVideoApp.retrievePlaylists();">'
  916. . '(refresh your playlist listing)</a><br />' . printCacheWarning();
  917. }
  918. /**
  919. * Delete a playlist
  920. *
  921. * @param string $newplaylistTitle New title for the playlist to be updated
  922. * @param string $newPlaylistDescription New description for the playlist to be updated
  923. * @param string $oldPlaylistTitle Title of the playlist to be updated
  924. * @return void
  925. */
  926. function updatePlaylist($newPlaylistTitle, $newPlaylistDescription, $oldPlaylistTitle)
  927. {
  928. $httpClient = getAuthSubHttpClient();
  929. $youTubeService = new Zend_Gdata_YouTube($httpClient);
  930. $feed = $youTubeService->getPlaylistListFeed('default');
  931. if (loggingEnabled()) {
  932. logMessage($httpClient->getLastRequest(), 'request');
  933. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  934. }
  935. $playlistEntryToDelete = null;
  936. foreach($feed as $playlistEntry) {
  937. if ($playlistEntry->getTitleValue() == $oldplaylistTitle) {
  938. $playlistEntryToDelete = $playlistEntry;
  939. break;
  940. }
  941. }
  942. if (!$playlistEntryToDelete instanceof Zend_Gdata_YouTube_PlaylistListEntry) {
  943. print 'ERROR - Could not retrieve playlist to be updated<br />'
  944. . printCacheWarning();
  945. return;
  946. }
  947. try {
  948. $response = $playlistEntryToDelete->delete();
  949. if (loggingEnabled()) {
  950. logMessage($httpClient->getLastRequest(), 'request');
  951. logMessage($httpClient->getLastResponse()->getBody(), 'response');
  952. }
  953. } catch (Zend_Gdata_App_HttpException $httpException) {
  954. print 'ERROR ' . $httpException->getMessage()
  955. . ' HTTP details<br /><textarea cols="100" rows="20">'
  956. . $httpException->getRawResponseBody()
  957. . '</textarea><br />'
  958. . '<a href="session_details.php">'
  959. . 'click here to view details of last request</a><br />';
  960. return;
  961. } catch (Zend_Gdata_App_Exception $e) {
  962. print 'ERROR - Could not delete the playlist: ' . $e->getMessage();
  963. return;
  964. }
  965. print 'Playlist deleted succesfully.<br /><a href="#" onclick="' .
  966. 'ytVideoApp.retrievePlaylists();"'.
  967. '">(refresh your playlist listing)</a><br />'.
  968. printCacheWarning();
  969. }
  970. /**
  971. * Helper function if an unsupported operation is passed into this files main loop.
  972. *
  973. * @param array $post (Optional) The post variables that accompanied the operation, if available.
  974. * @return void
  975. */
  976. function unsupportedOperation($_POST)
  977. {
  978. $message = 'ERROR An unsupported operation has been called - post variables received '
  979. . print_r($_POST, true);
  980. if (loggingEnabled()) {
  981. logMessage($message, 'error');
  982. }
  983. print $message;
  984. }
  985. ?>