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