gatzkerob

GetThumbnails

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