Exemple #1
0
 /**
  * @covers \PressBooks\Media\is_valid_media
  */
 public function test_is_valid_media()
 {
     $goodFiles = ['video.mp4', 'video.webm', 'video.ogv', 'audio.ogg', 'audio.mp3', 'audio.aac', 'audio.vorbis'];
     foreach ($goodFiles as $file) {
         $this->assertTrue(\PressBooks\Media\is_valid_media('__UNUSED__', $file));
     }
     $badFiles = ['image.png', 'image.gif', 'image.jpg', 'image.jpeg', 'foo.bar', '/etc/hosts'];
     foreach ($badFiles as $file) {
         $this->assertFalse(\PressBooks\Media\is_valid_media('__UNUSED__', $file));
     }
 }
 /**
  * Fetch a url with wp_remote_get(), save it to $fullpath with a unique name.
  * Will return an empty string if something went wrong.
  * 
  * @staticvar array $already_done
  * @param string $url
  * @param string $fullpath
  * @return string|array
  */
 protected function fetchAndSaveUniqueMedia($url, $fullpath)
 {
     // Cheap cache
     static $already_done = array();
     if (isset($already_done[$url])) {
         return $already_done[$url];
     }
     $response = wp_remote_get($url, array('timeout' => $this->timeout));
     // WordPress error?
     if (is_wp_error($response)) {
         // TODO: handle $response->get_error_message();
         $already_done[$url] = '';
         return '';
     }
     // Basename without query string
     $filename = explode('?', basename($url));
     $filename = array_shift($filename);
     $filename = sanitize_file_name(urldecode($filename));
     $filename = Sanitize\force_ascii($filename);
     $tmp_file = \PressBooks\Utility\create_tmp_file();
     file_put_contents($tmp_file, wp_remote_retrieve_body($response));
     if (!\PressBooks\Media\is_valid_media($tmp_file, $filename)) {
         $already_done[$url] = '';
         return '';
         // Not a valid media type
     }
     // Check for duplicates, save accordingly
     if (!file_exists("{$fullpath}/{$filename}")) {
         copy($tmp_file, "{$fullpath}/{$filename}");
     } elseif (md5(file_get_contents($tmp_file)) != md5(file_get_contents("{$fullpath}/{$filename}"))) {
         $filename = wp_unique_filename($fullpath, $filename);
         copy($tmp_file, "{$fullpath}/{$filename}");
     }
     $already_done[$url] = $filename;
     return $filename;
 }