gatzkerob

GetThumbnails_2

Jan 5th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.39 KB | None | 0 0
  1. <?php
  2.  
  3. // This class receives a page URL from the user then searches
  4. // the destination for potential thumbnails via Embedly.
  5. // The thumbnails (if found) are then returned as base64 in a JSON response.
  6. class GetThumbnails{
  7.    
  8.     private $embedlyPrivateKey = '<HIDDEN - YOU CAN GET ONE FOR FREE FROM EMBED.LY>';
  9.    
  10.     private $debugInfoArray = array();
  11.     private $imageFlavour; // jpeg | x-icon
  12.     private $imagesToKeep;
  13.     private $maxWidth;
  14.     private $maxHeight;
  15.     private $useDefaultThumb = 'false';
  16.    
  17.     public function __construct($imagesToKeep = 3, $maxWidth = 70, $maxHeight = 55){
  18.         $this->imagesToKeep = $imagesToKeep;
  19.         $this->maxWidth = $maxWidth;
  20.         $this->maxHeight = $maxHeight;
  21.     }
  22.    
  23.     // This function accepts a page URL.
  24.     // Embedly uses this URL to find images on that page. (see: http://embed.ly/docs/api/extract)
  25.     // Returns array of found image URLs.
  26.     private function getImagesByPageUrl($pageURL){
  27.    
  28.         $imageUrlArray = array();
  29.        
  30.         // Follow any redirects from original URL before requesting images.
  31.         $finalPageUrl = $this->cURL($pageURL)['finalPageUrl'];
  32.        
  33.         $curlResponse = $this->cURL('http://api.embed.ly/1/extract?key=' . $this->embedlyPrivateKey . '&url=' . urlencode($finalPageUrl));
  34.         $responseCode = $curlResponse['responseCode'];
  35.         $embedlyJSON = json_decode($curlResponse['embedlyJSON'], true);
  36.        
  37.         if($responseCode == '200'){
  38.            
  39.             if(!empty($embedlyJSON['images'])){
  40.                
  41.                 $this->imageFlavour = 'jpeg';
  42.                
  43.                 $this->debugInfo("Embedly found " . count($embedlyJSON['images']) . " images.");
  44.                
  45.                 if(count($embedlyJSON['images']) >= $this->imagesToKeep){
  46.                     $this->debugInfo("Keeping first " . $this->imagesToKeep . "..");
  47.                 }
  48.                
  49.                 foreach($embedlyJSON['images'] as $embedlyImageURL){
  50.                     array_push($imageUrlArray, $embedlyImageURL['url']);
  51.                 }
  52.                
  53.             }else{
  54.                
  55.                 $this->debugInfo("Embedly failed to find images.");
  56.                 $this->debugInfo("Searching for favicon..");
  57.                
  58.                 if(!empty($embedlyJSON['favicon_url'])){
  59.                    
  60.                     $this->imageFlavour = 'x-icon';
  61.                    
  62.                     $this->debugInfo("Embedly found a favicon.");
  63.                    
  64.                     array_push($imageUrlArray, $embedlyJSON['favicon_url']);
  65.                    
  66.                 }else{
  67.                     $this->debugInfo("Embedly failed to find favicon..");
  68.                     $this->debugInfo("Default thumbnail will be used..");
  69.                     $this->useDefaultThumb = 'true';
  70.                 }
  71.             }
  72.                
  73.             if(count($imageUrlArray) > $this->imagesToKeep){
  74.                 $imageUrlArray = array_slice($imageUrlArray, 0, $this->imagesToKeep, true);
  75.             }
  76.            
  77.         }else{
  78.             $this->debugInfo("Page response was \"" . $responseCode . "\" for \"" . $pageURL . "\"..");
  79.             $this->useDefaultThumb = 'true';
  80.         }
  81.        
  82.         return array(
  83.             'responseCode'=>$responseCode,
  84.             'finalPageUrl'=>$finalPageUrl,
  85.             'imageUrlArray'=>$imageUrlArray
  86.         );
  87.     }
  88.    
  89.     // This function creates thumbnails and returns them in base64.
  90.     // Image URLs are sent to Embedly along with desired dimensions for cropping. (see: http://embed.ly/docs/api/display/endpoints/1/display/crop)
  91.     // Responses are base64 encoded before being returned to user via JSON (Instead of using JavaScript which would reveal Embedly private key).
  92.     private function getThumbnailImagesViaEmbedly($imageUrlArray){
  93.        
  94.         $imageSourceBase64Array = array();
  95.        
  96.         if(!empty($imageUrlArray)){
  97.            
  98.             if($this->imageFlavour == 'jpeg'){
  99.                
  100.                 foreach($imageUrlArray as $selectedimageSource){
  101.                    
  102.                     $thumbnailedImageUrl = $this->cURL(
  103.                         'https://i.embed.ly/1/display/crop?key=' .
  104.                         $this->embedlyPrivateKey .
  105.                         '&url=' . urlencode($selectedimageSource) .
  106.                         '&height=' . $this->maxHeight .
  107.                         '&width=' . $this->maxWidth)['embedlyJSON'];
  108.                    
  109.                     array_push($imageSourceBase64Array, 'data:image/' . $this->imageFlavour . ';base64,' . base64_encode($thumbnailedImageUrl));
  110.                 }
  111.                
  112.             }elseif($this->imageFlavour == 'x-icon'){
  113.                
  114.                 // Thumbnails (x-icon) are not cropped, so no need to send back to Embedly first.
  115.                
  116.                 array_push($imageSourceBase64Array, 'data:image/' . $this->imageFlavour . ';base64,' . base64_encode($this->cURL($imageUrlArray[0])['embedlyJSON']));
  117.                
  118.                 // Make sure favicon remains square.
  119.                 $this->maxWidth = $this->maxHeight;
  120.                
  121.             }else{
  122.                 $this->debugInfo("No image flavour specified - No images were cropped..");
  123.                 $this->useDefaultThumb = 'true';
  124.             }
  125.         }else{
  126.             $this->debugInfo("No URLs provided for cropping - No images were cropped..");
  127.             $this->useDefaultThumb = 'true';
  128.         }
  129.        
  130.         return $imageSourceBase64Array;
  131.     }
  132.  
  133.     // Function accepts URL as parameter.
  134.     // Returns array of:
  135.     //   JSON from Embedly.
  136.     //   Response code. (200, 404 etc.).
  137.     //   Redirect URL (if supplied URL is redirected).
  138.     private function cURL($pageURL){
  139.        
  140.         $ch = curl_init($pageURL);
  141.        
  142.         // Set user agent to avoid "random" results.
  143.         curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36');
  144.        
  145.         // Return page as string only.
  146.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  147.        
  148.         // Disabled to avoid some errors.
  149.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  150.        
  151.         // Follow all redirected URLs.
  152.         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  153.        
  154.         $embedlyJSON = curl_exec($ch);
  155.         $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  156.         $finalPageUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  157.  
  158.         curl_close($ch);
  159.        
  160.         return array(
  161.             'embedlyJSON'=>$embedlyJSON,
  162.             'responseCode'=>$responseCode,
  163.             'finalPageUrl'=>$finalPageUrl
  164.         );
  165.     }
  166.    
  167.     private function debugInfo($info){
  168.         array_push($this->debugInfoArray, $info);
  169.     }
  170.    
  171.     //////////////////////////////////////////////////////////////////////
  172.     //////////////////////////////////////////////////////////////////////
  173.    
  174.     // Final response to user request.
  175.     public function createJsonResponse(){
  176.        
  177.         $finalPageUrl = "";
  178.         $imageUrlArray = array();
  179.         $thumbnailedImages = array();
  180.         $width = "";
  181.         $height = "";
  182.        
  183.         // *No security for now! (regex later).
  184.         if(isset($_GET['pageUrl']) && $_GET['pageUrl'] != ''){
  185.            
  186.             $getImageInfo = $this->getImagesByPageUrl($_GET['pageUrl']);
  187.            
  188.             $finalPageUrl = $getImageInfo['finalPageUrl'];
  189.             $imageUrlArray = $getImageInfo['imageUrlArray'];
  190.             $thumbnailedImages = $this->getThumbnailImagesViaEmbedly($getImageInfo['imageUrlArray']);
  191.             $width = $this->maxWidth;
  192.             $height = $this->maxHeight;
  193.            
  194.         }else{
  195.             $this->debugInfo("No initial URL provided for image search.");
  196.             $this->useDefaultThumb = 'true';
  197.         }
  198.        
  199.         echo json_encode(array(
  200.             'useDefaultThumb'=>$this->useDefaultThumb,
  201.             'debugInfoArray'=>$this->debugInfoArray,
  202.             'finalPageUrl'=>$finalPageUrl,
  203.             'imageUrlArray'=>$imageUrlArray,
  204.             'thumbnailedImages'=>$thumbnailedImages,
  205.             'thumbnailDimensions'=>array(
  206.                 'width'=>$width,
  207.                 'height'=>$height
  208.             )
  209.         ));
  210.     }
  211.    
  212.     // THIS FUNCTION IS FOR DEMO ONLY!
  213.     public function demo(){
  214.            
  215.         // *No security for now! (regex later).
  216.         if(isset($_GET['pageUrl']) && $_GET['pageUrl'] != ''){
  217.             $pageUrl = $_GET['pageUrl'];
  218.         }else{
  219.             // STATIC URL FOR DEMO ONLY - replace for different results.
  220.             $pageUrl = 'http://www.microsoft.com';
  221.         }
  222.        
  223.         $getImageInfo = $this->getImagesByPageUrl($pageUrl);
  224.         $finalPageUrl = $getImageInfo['finalPageUrl'];
  225.         $imageUrlArray = $getImageInfo['imageUrlArray'];
  226.         $thumbnailedImages = $this->getThumbnailImagesViaEmbedly($getImageInfo['imageUrlArray']);
  227.    
  228.         echo '<pre>';
  229.        
  230.             echo '<u>The JSON array returned to the user:</u><br><br>';
  231.            
  232.             print_r(array(
  233.                 'useDefaultThumb'=>$this->useDefaultThumb,
  234.                 'debugInfoArray'=>$this->debugInfoArray,
  235.                 'finalPageUrl'=>$finalPageUrl,
  236.                 'imageUrlArray'=>$imageUrlArray,
  237.                 'thumbnailedImages'=>$thumbnailedImages,
  238.                 'thumbnailDimensions'=>array(
  239.                     'width'=>$this->maxWidth,
  240.                     'height'=>$this->maxHeight
  241.                 )
  242.             ));
  243.            
  244.             echo '<br><u>Sample images:</u><br>';
  245.            
  246.             if(count($imageUrlArray) == 0){
  247.                 echo '<br>No images found.';
  248.             }else{
  249.                 for($i=0; $i<count($imageUrlArray); $i++){
  250.                     echo '<br>Image ' . ($i+1) . ' before being cropped and thumbed:<br><br>';
  251.                     echo '<img src="' . $imageUrlArray[$i] . '" /><br>';
  252.                     echo '<br>Image ' . ($i+1) . ' after being cropped and thumbed:<br><br>';
  253.                     echo '<img src="' . $thumbnailedImages[$i] . '" /><br>';
  254.                 }
  255.             }
  256.            
  257.         echo '</pre>';
  258.        
  259.     }
  260. }
  261.  
  262. // $thumbnails = (new GetThumbnails())->createJsonResponse();
  263.  
  264. $thumbnails = (new GetThumbnails())->demo();
  265.  
  266. ?>
Add Comment
Please, Sign In to add comment