Advertisement
codebureau

AWS S3 Bucket Browser fix

Feb 16th, 2018
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.64 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Plugin Name: AWS S3 Bucket Browser
  5. * Plugin URI: https://www.wptechguides.com
  6. * Description: A custom Amazon S3 File Browser
  7. * Version: 1.1
  8. * Author: Dan Dulaney
  9. * Author URI: https://www.convexcode.com
  10. **/
  11.  
  12.  
  13.  
  14.  
  15. require(dirname(__FILE__) . "/aws/aws-autoloader.php");
  16.  
  17. use Aws\S3\S3Client;
  18. use Aws\Credentials\Credentials;
  19. use Aws\S3\Exception\S3Exception;
  20.  
  21. add_action( 'wp_enqueue_scripts', 's3_browse_register_scripts' );
  22. function s3_browse_register_scripts() {
  23.     wp_register_script( 'browse-s3-js', plugins_url( '/assets/js/script.js' , __FILE__ ), array(), '', true );
  24.  
  25.  
  26.     wp_register_style( 'browse-s3-css', plugins_url( '/assets/css/styles.css' , __FILE__ ));
  27.     wp_enqueue_style( 'browse-s3-css' );
  28.  
  29. }
  30.  
  31. //creates an entry on the admin menu for s3 uploader
  32. add_action('admin_menu', 's3_browse_plugin_menu');
  33.  
  34. //creates a menu page with the following settings
  35. function s3_browse_plugin_menu() {
  36.     add_submenu_page('tools.php', 'S3 Browser', 'S3 Browser', 'manage_options', 's3-browse-settings', 's3_browse_display_settings');
  37. }
  38.  
  39. //on-load, sets up the following settings for the plugin
  40. add_action( 'admin_init', 's3_browse_settings' );
  41.  
  42. function s3_browse_settings() {
  43.     register_setting( 'browse-s3-plugin-settings-group', 's3_browse_aws_access_key' );
  44.     register_setting( 'browse-s3-plugin-settings-group', 's3_browse_aws_secret' );
  45.     register_setting( 'browse-s3-plugin-settings-group', 's3_browse_aws_region' );
  46. }
  47.  
  48. //displays the settings page
  49. function s3_browse_display_settings() {
  50.  
  51.     //first part here displays a form to change the settings
  52.     echo "<form method=\"post\" action=\"options.php\">";
  53.  
  54.     settings_fields( 'browse-s3-plugin-settings-group' );
  55.     do_settings_sections( 'browse-s3-plugin-settings-group' );
  56.  
  57.     echo "
  58.    
  59.     <style>.seperator { border-bottom: 1px solid black; }</style>
  60.    
  61.     <div><h1>S3 Browser Settings</h1><p>
  62. Welcome to the AWS S3 Browser Plugin. Please set your AWS access key and secret key that have the appripriate iams permissions to access the buckets you're going to wish to display.
  63. </p><p>You can use the shortcode of the format: <b>[s3browse bucket=bucketname]</b> to display the files listing in a page or a post. The bucket attribute is required.</p>
  64. <p><b>Features</b>
  65. <ul><li>All files hosted on AWS S3: No local server traffic / space required.</li>
  66. <li>Links auto-expire after 60 minutes. No worries about hot-linking</li>
  67. <li>Searching without ever leaving the page.</li>
  68. <li>Since this is run via shortcode, able to put in a password protected page or post</li>
  69. </ul>
  70. <b>Limitations:</b>
  71. <ul>
  72. <li>Must Use AWS</li>
  73. <li>View / Download only (for now, uploading in a future version)</li>
  74. <li>Only works for 3 levels deep. Bucket (and items in), Folders (and items in), and Subfolders (and items in). Any deeper and they will not display correctly, although they will still show in search. This is being worked on for a future version.</li>
  75. </ul></p>
  76. <table class=\"form-table\">
  77.     <tr><td colspan=\"3\"><h2>General AWS S3 Settings (All REQUIRED)</h2></td></tr>
  78.       <tr valign=\"top\">
  79.        <th scope=\"row\">AWS Access Key</th>
  80.        <td><input type=\"text\" name=\"s3_browse_aws_access_key\" value=\"".esc_attr( get_option('s3_browse_aws_access_key') )."\" /></td>
  81. <td><p>Enter your AWS access key here.</p></td>
  82.        </tr>
  83.        
  84.        <tr valign=\"top\">
  85.        <th scope=\"row\">AWS Secret Key</th>
  86.        <td><input type=\"text\" name=\"s3_browse_aws_secret\" value=\"".esc_attr( get_option('s3_browse_aws_secret') )."\" /></td>
  87. <td><p>Shown only when creating account.</p></td>
  88.        </tr>
  89.        
  90.         <tr valign=\"top\" class=\"seperator\">
  91.        <th scope=\"row\">AWS Region</th>
  92.        <td><input type=\"text\" name=\"s3_browse_aws_region\" value=\"".esc_attr( get_option('s3_browse_aws_region') )."\" /></td>
  93. <td><p>Get your region from your S3 url. Ex) us-west-1</p></td>
  94.        </tr></table>";
  95.    
  96.     submit_button();
  97.  
  98.     echo "</form><br><br>";
  99.  
  100.     echo "</div>";
  101.  
  102. }
  103.  
  104.  
  105.  
  106. //shortcode-to-display-bucket
  107. function s3_browse_shortcode_disp($atts){
  108.  
  109.     $aws_access_key = esc_attr( get_option('s3_browse_aws_access_key') );
  110.     $aws_secret = esc_attr( get_option('s3_browse_aws_secret') );
  111.     $aws_region = esc_attr( get_option('s3_browse_aws_region') );
  112.  
  113.  
  114.  
  115.     if ($aws_access_key == '' || $aws_secret == '' || $aws_region == '') {
  116.  
  117.         echo "Make sure your access key, secret key, and region are all entered.";
  118.         return;
  119.  
  120.     }
  121.  
  122.     //Handles attribures. If none are specified, defaults to no scroll, 1st drive  
  123.     $atts = shortcode_atts(
  124.         array(
  125.             'bucket' => 'none',
  126.         ), $atts, 's3browse' );
  127.  
  128.     $bucket = $atts['bucket'];
  129.  
  130.  
  131.     if ($bucket == 'none') {
  132.  
  133.         echo "You must enter a bucket name in your shortcode. [s3browse bucket=bucketname]";
  134.         return;
  135.  
  136.  
  137.     }
  138.  
  139.     $htmlOutput = "<div class=\"files-div\"><div class=\"filemanager\">
  140.  
  141.         <div class=\"search\">
  142.             <input type=\"search\" placeholder=\"Find a file..\" />
  143.         </div>
  144.  
  145.         <div class=\"breadcrumbs\"></div>
  146.  
  147.         <ul class=\"data\"></ul>
  148.  
  149.         <div class=\"nothingfound\">
  150.             <div class=\"nofiles\"></div>
  151.             <span>No files here.</span>
  152.         </div>
  153.  
  154.     </div>
  155.     </div>";
  156.  
  157.  
  158.  
  159. $credentials = new Credentials("$aws_access_key", "$aws_secret");
  160.  
  161. //Instantiate the S3 client with your AWS credentials
  162.  $s3Client = S3Client::factory(array(
  163.     'credentials' => $credentials,
  164.     'region' => "$aws_region",
  165.     'version' => 'latest' ));
  166.  
  167. try {
  168.     $objects = $s3Client->getIterator('ListObjects', array('Bucket' => $bucket));
  169.  
  170.     $path_array=array();
  171.     $size_array=array();
  172.     $link_array=array();
  173.  
  174.     foreach ($objects as $object) {
  175.         if (!isset($objectarray)) { $objectarray = array(); }
  176.         //print_r($object);
  177.         $name = $object['Key'];
  178.         $size = $object['Size'];
  179.  
  180.         if ($object['Size'] != '0') {
  181.  
  182.             $base = basename($object['Key']);
  183.        
  184.             $cmd = $s3Client->getCommand('GetObject', [
  185.                 'Bucket' => "$bucket",
  186.                 'Key' => "$name",
  187.                 'ResponseContentType'           => 'application/octet-stream',
  188.                 'ResponseContentDisposition'    => 'attachment; filename="'.$base.'"',
  189.             ]);
  190.  
  191.             $request = $s3Client->createPresignedRequest($cmd, '+60 minutes');
  192.  
  193.             $link = (string) $request->getUri();
  194.             $path = 'Home/'.$name;
  195.        
  196.             $path_array[] = $path;
  197.             $size_array[] = $size;
  198.             $link_array[] = $link;
  199.  
  200.         }
  201.    
  202.     }
  203.  
  204.  
  205.  
  206. function &placeInArray(array &$dest, array $path_array, $size, $pathorig,$link) {
  207.     // If we're at the leaf of the tree, just push it to the array and return
  208.     //echo $pathorig;
  209.     //echo $size."<br>";
  210.  
  211.     global $folders_added;
  212.     if (count($path_array) === 1) {
  213.         if ($path_array[0] !== '') {
  214.           $file_array = array();
  215.           $file_array['name'] = $path_array[0];
  216.          $file_array['size'] = $size;
  217.           $file_array['type'] = 'file';
  218.          $file_array['path'] = $pathorig;
  219.         $file_array['link'] = $link;
  220.             array_push($dest['items'], $file_array);
  221.         }
  222.         return $dest;
  223.     }
  224.  
  225.     // If not (if multiple elements exist in path_array) then shift off the next path-part...
  226.     // (this removes $path_array's first element off, too)
  227.     $path = array_shift($path_array);
  228.  
  229.     if ($path) {
  230.  
  231.         $newpath_temp = explode($path,$pathorig);
  232.         $newpath = $newpath_temp[0].$path.'/';
  233.         // ...make a new sub-array for it...
  234.  
  235.  
  236.         //if (!isset($dest['items'][$path])) {
  237.         if($folders_added == null ||  !in_array($newpath,$folders_added,true)) {
  238.             $dest['items'][] = array(
  239.  
  240.             'name' => $path,
  241.             'type' => 'folder',
  242.             'path' => $newpath,
  243.             'items' => array() 
  244.  
  245.           );
  246.         $folders_added[] = $newpath;
  247.         //print_r($folders_added);
  248.         }
  249.         $count = count($dest['items']);
  250.         $count--;
  251.         //echo $count.'<br>';  
  252.         //print_r($dest['items'][$path]);
  253.  
  254.         // ...and continue the process on the sub-array
  255.         return placeInArray($dest['items'][$count], $path_array, $size, $pathorig,$link);
  256.     }
  257.  
  258.     // This is just here to blow past multiple slashes (an empty path-part), like
  259.     // /path///to///thing
  260.     return placeInArray($dest, $path_array, $size, $pathorig,$link);
  261. }
  262.  
  263.     $output = array();
  264.     $folders_added = array();
  265.     $i=0;
  266.     foreach ($path_array as $path) {
  267.         $size = $size_array[$i];
  268.         $link = $link_array[$i];
  269.         placeInArray($output, explode('/', $path), $size, $path, $link);
  270.         $i++;
  271.     }
  272.  
  273.    
  274.    
  275.  
  276.     $json_final = json_encode($output['items'][0]);
  277.  
  278.     //enques the js script and sends the json object to it.
  279.     wp_enqueue_script( 'browse-s3-js' );
  280.     wp_localize_script('browse-s3-js', 's3_browse_vars', array(
  281.             'json_array' => __($json_final)
  282.         )
  283.     );
  284.    
  285. }
  286. catch (S3Exception $e) {
  287.  
  288.     echo $e->getMessage() . "\n";
  289. }
  290.  
  291. return $htmlOutput;
  292. }
  293. //shortcode for form
  294. add_shortcode('s3browse', 's3_browse_shortcode_disp');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement