View source
<?php
class MediaFile {
public $path = '';
public $extension = '';
public $filemime = '';
public $class = '';
public $type = '';
public $file = null;
public $stream = '';
public function __construct($file) {
if (!empty($file)) {
$file = gettype($file) == 'string' ? array(
'path' => $file,
) : $file;
$file = (object) $file;
$this->file = $file;
$this->path = $this
->getPath($file);
$this->extension = empty($file->extension) ? $this
->getExt() : $file->extension;
$this->mimetype = $this
->getMimeType($file);
$this->type = $this
->getType();
$this->class = $this
->getClass();
$this->mediaType = !empty($file->mediaType) ? $file->mediaType : $this->class;
}
}
private function getPath($file) {
if (!empty($file->url)) {
return $file->url;
}
if (!empty($file->path)) {
if (file_valid_uri($file->path)) {
return file_create_url($file->path);
}
else {
return $file->path;
}
}
if (!empty($file->uri)) {
if (preg_match('/^http(s)?\\:\\/\\//', $file->uri)) {
return $file->uri;
}
else {
return file_create_url($file->uri);
}
}
if (!empty($file->value)) {
return $file->value;
}
if (!empty($file->input)) {
return $file->input;
}
return '';
}
private function getMimeType($file) {
if (!empty($file->filemime)) {
return $file->filemime;
}
if (!empty($file->mimetype)) {
return $file->mimetype;
}
switch ($this->extension) {
case 'png':
case 'jpeg':
case 'jpg':
case 'gif':
return 'image/' . $this->extension;
case 'mp4':
case 'm4v':
case 'flv':
case 'f4v':
return 'video/mp4';
case 'webm':
case 'webv':
return 'video/webm';
case 'ogg':
case 'ogv':
return 'video/ogg';
case '3g2':
return 'video/3gpp2';
case '3gpp':
case '3gp':
return 'video/3gpp';
case 'mov':
return 'video/quicktime';
case 'swf':
return 'application/x-shockwave-flash';
case 'oga':
return 'audio/ogg';
case 'mp3':
return 'audio/mpeg';
case 'm4a':
case 'f4a':
return 'audio/mp4';
case 'aac':
return 'audio/aac';
case 'wav':
return 'audio/vnd.wave';
case 'wma':
return 'audio/x-ms-wma';
case 'weba':
return 'audio/webm';
default:
return '';
}
return '';
}
private function getType() {
$parts = explode('/', $this->mimetype);
$mimetype = $parts[0];
$image = in_array($this->extension, array(
'jpg',
'jpeg',
'png',
'gif',
));
$image |= $mimetype == 'image';
if ($image) {
return 'image';
}
$video = in_array($this->extension, array(
'mp4',
'm4v',
'flv',
'f4v',
'webm',
'webv',
'ogg',
'ogv',
'3g2',
'3gpp',
'3gp',
'mov',
'swf',
));
$video |= $mimetype == 'video';
if ($video) {
return 'video';
}
$audio = in_array($this->extension, array(
'oga',
'mp3',
'm4a',
'f4a',
'aac',
'wav',
'wma',
'weba',
));
$audio |= $mimetype == 'audio';
if ($audio) {
return 'audio';
}
}
private function getClass() {
if ($this->type) {
return $this->type == 'image' ? 'image' : 'media';
}
return '';
}
private function getExt() {
return drupal_strtolower(drupal_substr($this->path, strrpos($this->path, '.') + 1));
}
}