Advertisement
Guest User

RYTV API

a guest
Oct 2nd, 2014
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 26.25 KB | None | 0 0
  1. <?php
  2. /**
  3.  * The plugin API.
  4.  *
  5.  * @package     relatedYouTubeVideos
  6.  * @copyright   Copyright (c) 2013 http://www.meomundo.com
  7.  * @author      Christian Doerr <doerr@meomundo.com>
  8.  * @license     http://opensource.org/licenses/gpl-2.0.php GNU General Public License, version 2 (GPL-2.0)
  9.  *
  10.  */
  11. class RelatedYouTubeVideos_API {
  12.  
  13.   /**
  14.    * @var string $latestCall Store the latest URL call to the YouTube webservice.
  15.    */
  16.   protected $latestCall = '';
  17.  
  18.   /**
  19.    * @var array $meta Acts as cache for storing post meta data like the tilte, categories, and tags.
  20.    */
  21.   protected $meta;
  22.  
  23.   /**
  24.    * @var int $timeout = PHP/Server settings: Max Execution Time - 5 seconds
  25.    */
  26.   protected $timeout;
  27.  
  28.   /**
  29.    * The Constructor
  30.    */
  31.   public function __construct() {
  32.    
  33.     $max_execution_time = (int) ini_get('max_execution_time');
  34.    
  35.     $this->timeout      = ( $max_execution_time > 0 ) ? ( $max_execution_time - 5 ) : 15;
  36.    
  37.   }
  38.  
  39.   /**
  40.    * Do the actual YouTube search by generating a GET request.
  41.    *
  42.    * @param   array   $args   An array of parameters.
  43.    * @return  mixed           FALSE in case the request was invalid or some other error has occured (like a timeout) or an array containing the search results.
  44.    */
  45.   public function searchYouTube( $args ) {
  46.  
  47.     $searchTerms  = isset( $args['searchTerms'] ) ? $args['searchTerms']      : '';
  48.    
  49.     if( $searchTerms == '' && isset( $args['terms'] ) ) {
  50.      
  51.       $searchTerms = $args['terms'];
  52.      
  53.     }
  54.  
  55.     if( $searchTerms == '' && isset( $args['search'] ) ) {
  56.      
  57.       $searchTerms = $args['search'];
  58.      
  59.     }
  60.    
  61.     $orderBy      = isset( $args['orderBy'] )     ? $args['orderBy']          : '';
  62.  
  63.     $start        = isset( $args['start'] )       ? $args['start']            : '';
  64.  
  65.     $max          = isset( $args['max'] )         ? $args['max']              : '';
  66.  
  67.     $apiVersion   = isset( $args['apiVersion'] )  ? (int) $args['apiVersion'] : 2;
  68.  
  69.     $lang         = ( isset( $args['lang'] ) && preg_match( '#^[a-z]{2}$#i', $args['lang'] ) ) ? strtolower( $args['lang'] ) : '';
  70.  
  71.     $region       = ( isset( $args['region'] ) && preg_match( '#^[a-z]{2}$#i', $args['region'] ) ) ? strtoupper( $args['region'] ) : '';
  72.  
  73.     $author       = ( isset( $args['author'] ) ) ? trim( $args['author'] ) : '';
  74.  
  75.     $exact        = ( isset( $args['exact'] ) && $args['exact'] === true ) ? true : false;
  76.  
  77.     $searchTerms  = ( $exact === true ) ? '%22' . urlencode( $searchTerms ) . '%22' : urlencode( $searchTerms );
  78.  
  79.     $orderBy      = urlencode( $orderBy );
  80.  
  81.     $duration     = ( isset( $args['duration'] ) && preg_match( '#^(short|medium|long)$#i', trim( $args['duration']  ) ) ) ? trim( strtolower( $args['duration'] ) ) : '';
  82.  
  83.     $start        = (int) $start +1;
  84.    
  85.     $max          = (int) $max;
  86.    
  87.     $random       = ( isset( $args['random'] ) && $args['random'] > $max )  ? (int) $args['random'] : $max;
  88.  
  89.     if( $random > $max ) {
  90.      
  91.       $target     = 'http://gdata.youtube.com/feeds/api/videos?q=' . $searchTerms . '&orderby=' . $orderBy . '&start-index=' . $start . '&max-results=' . $random . '&v=2';
  92.      
  93.     }
  94.     else {
  95.  
  96.       $target     = 'http://gdata.youtube.com/feeds/api/videos?q=' . $searchTerms . '&orderby=' . $orderBy . '&start-index=' . $start . '&max-results=' . $max . '&v=2';
  97.    
  98.     }
  99.  
  100.     /**
  101.      * Now that the basic URL has been build,
  102.      * add optional parameter only when they're actually set.
  103.      * Otherwise YouTube tends to invalidate the whole request sometimes!
  104.      */
  105.  
  106.     // Optional: Duration
  107.     if( $duration !== '' ) {
  108.      
  109.       $target     .= '&duration=' . $duration;
  110.      
  111.     }
  112.  
  113.     // Optional: Language
  114.     if( $lang !== '' ) {
  115.  
  116.       $target     .= '&lr=' . $lang;
  117.  
  118.     }
  119.  
  120.     // Optional: Region/Country
  121.     if( $region !== '' ) {
  122.  
  123.       $target     .= '&region=' . $region;
  124.  
  125.     }
  126.  
  127.     // Optional: Author/YouTube user
  128.     if( $author !== '' ) {
  129.  
  130.       $target     .= '&author=' . $author;
  131.  
  132.     }
  133.  
  134.     $this->latestCall = $target;
  135.  
  136.     // Call the YouTube Search Webservice
  137.     $loadURL  = ( defined( 'RYTV_METHOD' ) && RYTV_METHOD === 'curl' ) ? 'loadUrlVia_curl' : 'loadUrlVia_fopen';
  138.    
  139.     $data     = $this->$loadURL( $target );
  140.    
  141.     // Make the request by loading the response directly into a SimpleXML object.
  142.     // $xml          = @simplexml_load_file( $target );
  143.  
  144.     $xml      = @simplexml_load_string( $data );
  145.  
  146.     // Return FALSE in case the URL could not be loaded or no SimpleXML object could be created from it.
  147.     if( !is_object( $xml ) ) {
  148.    
  149.       return array();
  150.    
  151.     }
  152.  
  153.     // In case the YouTube response XML contains an error message, respectively code, return it!
  154.     if( isset( $xml->errors->error->code ) ) {
  155.      
  156.       return array( 'error' => $xml->errors->error->code );
  157.      
  158.     }
  159.  
  160.     /**
  161.      * Now build the list of videos according to the plugin configuration and "input parameters" (shortcode/widget).
  162.      */
  163.     if( !isset( $xml->entry ) ) {
  164.      
  165.       return array();
  166.      
  167.     }
  168.  
  169.     $result       = array();
  170.    
  171.     foreach( $xml->entry as $video ) {
  172.  
  173.       $result[]   = $video;
  174.  
  175.     }
  176.  
  177.     /* {max} random videos out of {random} */
  178.     if( $random > $max ) {
  179.  
  180.       $total      = count( $result );
  181.      
  182.       if( $total < $random ) {
  183.        
  184.         $random   = $total;
  185.        
  186.       }
  187.  
  188.       $count      = 0;
  189.      
  190.       $randIndex  = array();
  191.  
  192.       /* Generate random index numbers, between 0 and $random */
  193.       while( $count < $max ) {
  194.        
  195.         $tmp = ( $random > 1 ) ? mt_rand( 0, ( $random -1 ) ) : 0;
  196.  
  197.         if( !in_array( $tmp, $randIndex ) ) {
  198.          
  199.           $randIndex[] = $tmp;
  200.          
  201.           $count++;
  202.          
  203.         }
  204.        
  205.       }
  206.  
  207.       /* Use the random index number so re-build the results array */
  208.       $randResults  = array();
  209.  
  210.       foreach( $randIndex as $index ) {
  211.        
  212.         $randResults[] = $result[ $index ];
  213.        
  214.       }
  215.  
  216.       return $randResults;
  217.      
  218.     }
  219.     else {
  220.    
  221.       return $result;
  222.    
  223.     }
  224.  
  225.   }
  226.  
  227.   /**
  228.    * Take the array of search results and generate an unordered HTML list out of it.
  229.    * The HTML for embedding the videos is hopefully valid (x)HTML!
  230.    *
  231.    * @param   array   $results  An array of YouTube search results.
  232.    * @param   array   $args     An array for further (plugin) configuration.
  233.    * @return  string            Unorderd HTML list.
  234.    */
  235.   public function displayResults( $results, $args = array() ) {
  236.  
  237.     /**
  238.      * These kinds of errors should not break your site. So instead of echoing the error message in a way that's visibile
  239.      * to everyone, it'll only up in the HTML source code in form of a comment line.
  240.      */
  241.     if( !is_array( $results ) || empty( $results) ) {
  242.      
  243.       $options = get_option( 'relatedyoutubevideos' );
  244.      
  245.       $errMsg = '';
  246.      
  247.       if( isset( $options['customMessage'] ) && trim( $options['customMessage'] ) !== '' ) {
  248.        
  249.         $errMsg .= $options['customMessage'];
  250.        
  251.       }
  252.      
  253.       $errMsg .= "\n" . '<!-- relatedYouTubeVideos Error: No related videos found! (' . $this->latestCall . ') -->' . "\n";
  254.      
  255.       return $errMsg;
  256.      
  257.     }
  258.    
  259.     if( isset( $results['error'] ) ) {
  260.  
  261.       return '<!-- relatedYouTubeVideos Error: ' . str_replace( '_', ' ', $results['error'] ) . '! -->';
  262.  
  263.     }
  264.  
  265.     $class        = isset( $args['class'] )   ? 'class="relatedYouTubeVideos ' . strip_tags( $args['class'] ) . '"' : 'class="relatedYouTubeVideos"';
  266.    
  267.     $id           = ( isset( $args['id'] ) && !empty( $args['id'] ) ) ? 'id="' . strip_tags( $args['id'] ) . '"'                            : '';
  268.    
  269.     $width        = isset( $args['width'] )   ? (int) $args['width']  : 0;
  270.    
  271.     $height       = isset( $args['height'] )  ? (int) $args['height'] : 0;
  272.    
  273.     $viewRelated  = ( isset( $args['viewrelated'] ) && (int) $args['viewrelated'] === 0 ) ? 0 : 1;
  274.  
  275.     /**
  276.      * Starting the HTML generation.
  277.      */
  278.     $html   = '';
  279.    
  280.     /**
  281.      * In PREVIEW mode only the images will be displayed. When clicked such an image will be replace with the video.
  282.      * This requires Javascript to be enabled in the browser!!
  283.      */
  284.  
  285.     if( isset( $args['preview'] ) && $args['preview'] === true ) {
  286.      
  287.       $jsFunction =<<<EOF
  288. <script type="text/javascript">
  289. if( typeof showRelatedVideo !== 'function' ) {
  290.   function showRelatedVideo( config ) {
  291.    
  292.     'use strict';
  293.    
  294.     if( undefined === config.videoID ) {
  295.       return '<i>Invalid Video ID</i>';
  296.     }
  297.  
  298.     if( undefined === config.width ) {
  299.       config.width = 480;
  300.     }
  301.    
  302.     if( undefined === config.height ) {
  303.       config.height = 360;
  304.     }
  305.  
  306.     var video = '',
  307.         videoTitle = ( undefined === config.title ) ? '' : config.title;
  308.    
  309.     video += '<object data="http://www.youtube.com/embed/' +  config.videoID + '?autoplay=1&rel={$viewRelated}" width="' + config.width +  '" height="' + config.height + '">';
  310.     video += ' <param name="movie" value="http://www.youtube.com/v/' + config.videoID + '?rel={$viewRelated}" />';
  311.     video += ' <param name="wmode" value="transparent" />';
  312.     video += ' <param name="allowfullscreen" value="true" />';
  313.     video += ' <a href="http://www.youtube.com/watch?v=' + config.videoID + '"><img src="http://img.youtube.com/vi/' + config.videoID + '/0.jpg" alt="' + videoTitle + '" /><br />YouTube Video</a>';
  314.     video += '</object>';
  315.    
  316.     if( undefined !== config.title ) {
  317.       video += '<div class="title">' + config.title + '</div>';
  318.     }
  319.    
  320.     if( undefined !== config.description ) {
  321.       video += '<div class="description">' + config.description + '</div>';
  322.     }
  323.  
  324.     return video;
  325.  
  326.   }
  327. }
  328. </script>
  329. EOF;
  330.  
  331.       $html                    .= $jsFunction;
  332.      
  333.       $html                    .= '  <ul ' . $class . ' ' . $id . '>' . "\n";
  334.  
  335.       foreach( $results as $video ) {
  336.  
  337.         // Try detecting the YouTube Video ID
  338.         preg_match( '#\?v=([^&]*)&#i', $video->link['href'], $match );
  339.  
  340.         $videoID                = isset( $match[1] )      ? (string) $match[1]          : null;
  341.  
  342.         $videoTitle             = isset( $video->title )  ? strip_tags( $video->title ) : 'YouTube Video';
  343.        
  344.         $videoTitle_clean       = $videoTitle;
  345.  
  346.         $videoTitle_esc         = preg_replace( array( '#"#im', "#'#im" ), array( '&quot;', '&rsquo;' ), $videoTitle );
  347.        
  348.         $videoDescription       = (string) $video->children('media', true)->group->children('media', true )->description;
  349.        
  350.         $videoDescription_clean = $videoDescription;
  351.        
  352.         $videoDescription_esc   = preg_replace( array( '#"#im', "#'#im" ), array( '&quot;', '&rsquo;' ), $videoDescription );
  353.  
  354.         $videoTitle             = ( isset( $args['showvideotitle'] ) && $args['showvideotitle'] === true ) ? ", title : '" . $videoTitle_esc . "'" : '';
  355.  
  356.         $videoDescription       = ( isset( $args['showvideodescription'] ) && $args['showvideodescription'] === true ) ? ", description : '" . $videoDescription_esc . "'" : '';
  357.        
  358.         $argsObj                = "{ videoID:'" . $videoID . "', width:" . $width . ", height:" . $height . $videoTitle . $videoDescription . "}";
  359.  
  360.         $html                  .= "   <li onClick=\"innerHTML=showRelatedVideo(" . $argsObj . ");removeAttribute('onClick');\">\n";
  361.  
  362.         if( $videoID != null ) {
  363.  
  364.           $html           .= '     <img src="http://img.youtube.com/vi/' . $videoID . '/0.jpg" alt="' . $videoTitle . '" width="' . $width . '" height="' . $height . '" />' . "\n";
  365.  
  366.  
  367.           if( isset( $args['showvideotitle'] ) && $args['showvideotitle'] === true ) {
  368.            
  369.             $html         .= '    <div class="title">' . $videoTitle_clean . "</div>\n";
  370.          
  371.           }
  372.        
  373.           if( isset( $args['showvideodescription'] ) && $args['showvideodescription'] === true ) {
  374.            
  375.             $html         .= '    <div class="description">' . $videoDescription_clean . "</div>\n";
  376.          
  377.           }
  378.  
  379.         }
  380.         else {
  381.  
  382.           $html           .= '  <li><a href="' . $video->link['href'] . '" title="' . $videoTitle . '">' . $videoTitle . '</a></li>';
  383.  
  384.         }
  385.  
  386.         $html             .= "   </li>\n";
  387.  
  388.       }
  389.  
  390.       $html               .= "  </ul>\n";
  391.  
  392.      
  393.       $video              = null;
  394.      
  395.     }
  396.     else {
  397.    
  398.       $html               .= '  <ul ' . $class . ' ' . $id . '>' . "\n";
  399.  
  400.       foreach( $results as $video ) {
  401.  
  402.         // Try detecting the YouTube Video ID
  403.         preg_match( '#\?v=([^&]*)&#i', $video->link['href'], $match );
  404.  
  405.         $videoID          = isset( $match[1] )      ? (string) $match[1]          : null;
  406.  
  407.         $videoTitle       = isset( $video->title )  ? strip_tags( $video->title ) : 'YouTube Video';
  408.  
  409.         $videoDescription = (string) $video->children('media', true)->group->children('media', true )->description;
  410.  
  411.         $html             .= "   <li>\n";
  412.  
  413.         /**
  414.          * This is meant to be valid (x)HTML embedding of the videos, so please correct me if I'm wrong!
  415.          */
  416.         if( $videoID != null ) {
  417.  
  418.           $html           .= '    <object data="http://www.youtube.com/embed/' . $videoID  . '?rel=' . $viewRelated . '" width="' . $width . '" height="' . $height . '">' . "\n";
  419.           $html           .= '     <param name="movie" value="http://www.youtube.com/v/' . $videoID . '?rel=' . $viewRelated . '" />' . "\n";
  420.           $html           .= '     <param name="wmode" value="transparent" />' . "\n";
  421.           $html           .= '     <param name="allowfullscreen" value="true" />' . "\n";
  422.           $html           .= '     <a href="http://www.youtube.com/watch?v=' . $videoID . '"><img src="http://img.youtube.com/vi/' . $videoID . '/0.jpg" alt="' . $videoTitle . '" /><br />YouTube Video</a>' . "\n";
  423.           $html           .= "    </object>\n";
  424.  
  425.           if( isset( $args['showvideotitle'] ) && $args['showvideotitle'] === true ) {
  426.            
  427.             $html         .= '    <div class="title">' . $videoTitle . "</div>\n";
  428.          
  429.           }
  430.        
  431.           if( isset( $args['showvideodescription'] ) && $args['showvideodescription'] === true ) {
  432.            
  433.             $html         .= '    <div class="description">' . $videoDescription . "</div>\n";
  434.          
  435.           }
  436.  
  437.         }
  438.         else {
  439.  
  440.           $html           .= '   <li><a href="' . $video->link['href'] . '" title="' . $videoTitle . '">' . $videoTitle . '</a></li>';
  441.  
  442.         }
  443.  
  444.         $html             .= "   </li>\n";
  445.  
  446.         $video            = null;
  447.  
  448.       }
  449.  
  450.       $html               .= "  </ul>\n";
  451.    
  452.     }
  453.  
  454.     return $html;
  455.    
  456.   }
  457.  
  458.   /**
  459.    * Validate a configurational array.
  460.    *
  461.    * @param   array $args   Array for configuring the YouTube search as well as the plugin output.
  462.    * @return  array         Normalized data.
  463.    */
  464.   public function validateConfiguration( $args = array() ) {
  465.  
  466.     $title        = isset( $args['title'] )       ? strip_tags( trim( $args['title'] ) )    : '';
  467.  
  468.     $searchTerms  = isset( $args['terms'] )       ? strip_tags( trim( $args['terms'] ) )    : '';
  469.  
  470.     $orderBy      = isset( $args['orderBy'] )     ? strtolower( trim( $args['orderBy'] ) )  : '';
  471.    
  472.     /* Array indexes are case-sensitive^^ */
  473.     $orderBy      = isset( $args['orderby'] )     ? strtolower( trim( $args['orderby'] ) )  : $orderBy;
  474.    
  475.     if( $orderBy !== 'published' && $orderBy !== 'rating' && $orderBy !== 'viewcount' ) {
  476.      
  477.       $orderBy    = 'relevance';
  478.      
  479.     }
  480.  
  481.     // The YouTube API is case sensitive!
  482.     if( $orderBy === 'viewcount' ) {
  483.  
  484.       $orderBy    = 'viewCount';
  485.  
  486.     }
  487.    
  488.     // Start
  489.     $start        = isset( $args['start'] )       ? (int) abs( $args['start'] )             : 0;
  490.    
  491.     if( $start === 0 && isset( $args['offset'] ) ) {
  492.      
  493.       $start      = (int) abs( $args['offset'] );
  494.      
  495.     }
  496.    
  497.     if( $start < 0 ) {
  498.      
  499.       $start      = 0;
  500.      
  501.     }
  502.    
  503.     // Max
  504.     $max          = isset( $args['max'] )         ? (int) abs( $args['max'] )               : 10;
  505.    
  506.     if( $max < 1 ) {
  507.      
  508.       $max        = 1;
  509.      
  510.     }
  511.     else if( $max > 10 ) {
  512.      
  513.       $max        = 10;
  514.      
  515.     }
  516.  
  517.     $showTitle    = ( isset( $args['showvideotitle'] ) && ( $args['showvideotitle'] === true || $args['showvideotitle'] == 'true' || (int) $args['showvideotitle'] == 1 || $args['showvideotitle'] == 'on' ) ) ? true : false;
  518.  
  519.     $showDescr    = ( isset( $args['showvideodescription'] ) && ( $args['showvideodescription'] === true || $args['showvideodescription'] == 'true' || (int) $args['showvideodescription'] == 1 || $args['showvideodescription'] == 'on' ) ) ? true : false;
  520.    
  521.     $exact        = ( isset( $args['exact'] ) && ( $args['exact'] === true || $args['exact'] == 'true' || (int) $args['exact'] == 1 || $args['exact'] == 'on' ) ) ? true : false;
  522.  
  523.     $apiVersion   = isset( $args['apiVersion'] )  ? (int) abs( $args['apiVersion'] )        : 2;
  524.  
  525.     $width        = isset( $args['width'] )       ? (int) abs( $args['width'] )             : 0; // The default width should be specified in the calling environment (widget or shortode)
  526.  
  527.     $height       = isset( $args['height'] )      ? (int) abs( $args['height'] )            : 0; // The default height should be specified in the calling environment (widget or shortode)
  528.    
  529.     $duration     = ( isset( $args['duration'] ) && preg_match( '#^(short|medium|long)$#i', trim( $args['duration']  ) ) ) ? trim( strtolower( $args['duration'] ) ) : '';
  530.  
  531.     $class        = isset( $args['class'] )       ? strip_tags( $args['class'] )            : '';
  532.    
  533.     $id           = isset( $args['id'] )          ? strip_tags( $args['id'] )               : '';
  534.    
  535.     $relation     = isset( $args['relation'] )    ? strtolower( $args['relation'] )         : '';
  536.  
  537.     $wpSearch     = ( isset( $args['wpSearch'] ) && $args['wpSearch'] == true ) ? true      : false;  // Will only have an effect on the search results page
  538.    
  539.     $preview      = ( isset( $args['preview'] ) && ( $args['preview'] === true || $args['preview'] == 'true' || (int) $args['preview'] == 1 || $args['preview'] == 'on' ) ) ? true : false;
  540.    
  541.     // Random pool
  542.     $random       = ( isset( $args['random'] ) )    ? (int) abs( $args['random'] )            : $max;
  543.  
  544.     if( $random < $max ) {
  545.      
  546.       $random = $max;
  547.      
  548.     }
  549.  
  550.     $lang         = ( isset( $args['lang'] ) && preg_match( '#^[a-z]{2}$#i', $args['lang'] ) ) ? strtolower( $args['lang'] ) : '';
  551.  
  552.     $region       = ( isset( $args['region'] ) && preg_match( '#^[a-z]{2}$#i', $args['region'] ) ) ? strtoupper( $args['region'] ) : '';
  553.  
  554.     $author       = ( isset( $args['author'] ) ) ? trim( $args['author'] ) : '';
  555.  
  556.     $viewRelated  = ( isset( $args['viewrelated'] ) && ( (int) $args['viewrelated'] === 0 || strtolower( $args['viewrelated'] ) === 'false' || strtolower( $args['viewrelated'] ) === 'no' ) ) ? 0 : 1;
  557.    
  558.     if( isset( $args['viewrelated'] ) && ( strtolower( $args['viewrelated'] ) === 'yes' || strtolower( $args['viewrelated'] ) === 'true' ) ) {
  559.      
  560.       $viewRelated = 1;
  561.      
  562.     }
  563.  
  564.     /**
  565.      * Depending on what relation has been specified generate the proper keywords for searching YouTube.
  566.      */
  567.     if( $relation !== 'posttags' && $relation !== 'keywords' && $relation !== 'postcategories' ) {
  568.      
  569.       $relation   = 'posttitle';
  570.      
  571.     }
  572.  
  573.     // Relation: Post title.
  574.     if( $relation === 'posttitle' ) {
  575.      
  576.       $search = $this->getPostTitle();
  577.      
  578.     }
  579.     // Relation: Post tags.
  580.     elseif( $relation == 'posttags' ) {
  581.      
  582.       $search  = $this->getPostTags();
  583.  
  584.     }
  585.     // Relation: Post categories.
  586.     elseif( $relation === 'postcategories' ) {
  587.  
  588.       $search = $this->getPostCategories();
  589.      
  590.     }
  591.     // Relation: Custom Keywords.
  592.     elseif( $relation === 'keywords' ) {
  593.      
  594.       $search     = trim( $searchTerms );
  595.      
  596.     }
  597.  
  598.     /**
  599.      * You can add additional filtering paramets via the "filter" parameter.
  600.      * The filter value will simply be added to the search terms.
  601.      */
  602.     $filter     = '';
  603.    
  604.     if( isset( $args['filter'] ) && !empty( $args['filter'] ) ) {
  605.      
  606.       $filter   = trim( strip_tags( $args['filter'] ) );
  607.      
  608.       // Use $tmp so $filter stays untouched an can be saved as widget option.
  609.       $tmp      = preg_replace( '#\+posttitle#i', $this->getPostTitle(), $filter );
  610.      
  611.       $tmp      = preg_replace( '#\+posttags#i', $this->getPostTags(), $tmp );
  612.        
  613.       $tmp      = preg_replace( '#\+postcategories#i', $this->getPostCategories(), $tmp );
  614.      
  615.       $tmp      = trim( $tmp );
  616.  
  617.       $search   .= ' ' . $tmp;
  618.  
  619.     }
  620.  
  621.     $norm         = array(
  622.       'title'                 => $title,
  623.       'terms'                 => $searchTerms,
  624.       'orderBy'               => $orderBy,
  625.       'start'                 => $start,
  626.       'max'                   => $max,
  627.       'apiVersion'            => $apiVersion,
  628.       'width'                 => $width,
  629.       'height'                => $height,
  630.       'class'                 => $class,
  631.       'id'                    => $id,
  632.       'relation'              => $relation,
  633.       'search'                => $search,
  634.       'wpSearch'              => $wpSearch,
  635.       'exact'                 => $exact,
  636.       'random'                => $random,
  637.       'showvideotitle'        => $showTitle,
  638.       'showvideodescription'  => $showDescr,
  639.       'preview'               => $preview,
  640.       'duration'              => $duration,
  641.       'lang'                  => $lang,
  642.       'region'                => $region,
  643.       'author'                => $author,
  644.       'filter'                => $filter,
  645.       'viewrelated'           => $viewRelated
  646.     );
  647.  
  648.     return $norm;
  649.  
  650.   }
  651.  
  652.   /**
  653.    * Load external file/URL via cURL
  654.    *
  655.    * @param   string  $url    URL to be loaded.
  656.    * @return  string          Response from the YT web service or a plain error message.
  657.    */
  658.   public function loadUrlVia_curl( $url ) {
  659.  
  660.     try {
  661.    
  662.       // Configure cURL
  663.       $curl   = curl_init();
  664.  
  665.       curl_setopt( $curl, CURLOPT_URL, $url );
  666.  
  667.       // The YouTube search API is requires connecting via SSL/HTTPS which cURL needs to be configurated for.
  668.       if( isset( $match[1] ) && strtolower( $match[1] ) === 'https' ) {
  669.        
  670.         curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
  671.  
  672.         curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 0 );
  673.      
  674.       }
  675.  
  676.       curl_setopt( $curl, CURLOPT_TIMEOUT, $this->timeout );
  677.  
  678.       curl_setopt( $curl, CURLOPT_FILETIME, true );
  679.  
  680.       curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
  681.    
  682.  
  683.       // Load the URL/response
  684.       $data   = curl_exec( $curl );
  685.  
  686.       $error  = (int) curl_errno( $curl );
  687.    
  688.  
  689.       curl_close( $curl );
  690.    
  691.  
  692.       if( $error !== 0 ) {
  693.      
  694.         return 'cURL error code: ' . $error;
  695.      
  696.       }
  697.       else {
  698.    
  699.         return $data;
  700.    
  701.       }
  702.  
  703.     }
  704.     catch( Exception $e ) {
  705.    
  706.       return 'cURL exception: ' . $e->getMessage();
  707.    
  708.     }
  709.  
  710.   }
  711.  
  712.   /**
  713.    * Load external file/URL via fopen
  714.    *
  715.    * @param   string  $url    URL to be loaded.
  716.    * @return  string          Response from the YT web service or a plain error message.
  717.    */
  718.   public function loadUrlVia_fopen( $url ) {
  719.    
  720.     if( preg_match( '#^https#i', $url ) && ( RYTV_METHOD === false ) ) {
  721.      
  722.       return '<!-- RelatedYouTubeVideos: Error: Cannot open HTTPS connection! Please install either curl or an HTTPS wrapper for the fopen function. -->';
  723.      
  724.     }
  725.  
  726.     $context  = stream_context_create(
  727.       array(
  728.         'http' =>
  729.           array(
  730.             'timeout' => $this->timeout
  731.         )
  732.       )
  733.     );
  734.    
  735.     $data     = @file_get_contents( $url, false, $context );
  736.    
  737.     return ( $data === false ) ? 'Cannot reach YouTube Search API!' : $data;
  738.    
  739.   }
  740.  
  741.   /**
  742.    * Get the (current) post title.
  743.    * Use cached data if possible.
  744.    *
  745.    * @return string The post title (or an empty string).
  746.    */
  747.   public function getPostTitle() {
  748.    
  749.     global $post;
  750.    
  751.     if( !isset( $post->ID ) ) {
  752.      
  753.       return '';
  754.      
  755.     }
  756.    
  757.     if( isset( $this->meta[ $post->ID ]['title'] ) ) {
  758.      
  759.       return $this->meta[ $post->ID ]['title'];
  760.      
  761.     }
  762.     else {
  763.  
  764.       $title = ( isset( $post->post_title ) ) ? $post->post_title : '';
  765.      
  766.       $this->meta[ $post->ID ]['title'] = $title;
  767.      
  768.       return $title;
  769.  
  770.     }
  771.  
  772.   }
  773.  
  774.   /**
  775.    * Get a list of all tags for the current post.
  776.    * Use cached data if possible instead of calling the database over and over again.
  777.    *
  778.    * @return string List of post tags.
  779.    */
  780.   public function getPostTags() {
  781.  
  782.     global $post;
  783.    
  784.     if( !isset( $post->ID ) ) {
  785.      
  786.       return '';
  787.    
  788.     }
  789.    
  790.     if( isset( $this->meta[ $post->ID ]['tags'] ) ) {
  791.      
  792.       return $this->meta[ $post->ID ]['tags'];
  793.      
  794.     }
  795.     else {
  796.    
  797.       $list       = '';
  798.    
  799.       $tags     = wp_get_post_tags( $post->ID );
  800.      
  801.       foreach( $tags as $tag ) {
  802.        
  803.         $list   .= ' ' . $tag->name;
  804.        
  805.       }
  806.      
  807.       $list     = trim( $list );
  808.      
  809.       $this->meta[ $post->ID ]['tags'] = $list;
  810.      
  811.       return $list;
  812.      
  813.     }
  814.  
  815.   }
  816.  
  817.   /**
  818.    * Get a list of all categories for the current post.
  819.    * Use cached data if possible instead of calling the database over and over again.
  820.    *
  821.    * @return string List of all categories.
  822.    */
  823.   public function getPostCategories() {
  824.    
  825.     global $post;
  826.    
  827.     if( !isset( $post->ID ) ) {
  828.      
  829.       return '';
  830.      
  831.     }
  832.    
  833.     if( isset( $this->meta[ $post->ID ]['categories'] ) ) {
  834.      
  835.       return $this->meta[ $post->ID ]['categories'];
  836.      
  837.     }
  838.     else {
  839.  
  840.       $list         = '';
  841.    
  842.       $categories = wp_get_post_categories( $post->ID );
  843.  
  844.       foreach( $categories as $category ) {
  845.      
  846.         $cat      = get_category( $category );
  847.      
  848.         $list     .= ' ' . $cat->name;
  849.    
  850.       }
  851.    
  852.       $list       = trim( $list );
  853.  
  854.       $this->meta[ $post->ID ]['categories'] = $list;
  855.  
  856.       return $list;
  857.  
  858.     }
  859.  
  860.   }
  861.  
  862. }
  863. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement