<?php
if ( !function_exists('file_put_contents') ){
function file_put_contents($filename, $data){
$fh = fopen($filename, 'w');
if ( !$fh ) return false;
$res = fwrite($fh, $data);
fclose($fh);
return $res;
}
}
if (!function_exists('mime_content_type') and function_exists('finfo_open')) {
function mime_content_type($filename) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
}
} else
if ( !function_exists ( 'mime_content_type' ) )
{
function mime_content_type ( $f )
{
return trim ( exec ('file -bi ' . escapeshellarg ( $f ) ) ) ;
}
}
class tables_files {
function beforeInsert(&$record){
$user =& getUser();
if ( $user ){
$record->setValue('owner_id', $user->val('user_id'));
}
}
function beforeSave(&$record){
$mime = $record->val('file_mimetype');
if ( !$mime or $mime == 'application/octet-stream'){
$mime = $this->guessMimeType($record->val('file'));
$record->setValue('file_mimetype', $mime);
}
if ( !$record->val('preview_image') and $record->val('file') and preg_match('/^video\//', $record->val('file_mimetype')) ){
$app =& Dataface_Application::getInstance();
//import(DATAFACE_SITE_PATH.'/lib/phpvideotoolkit.php');
//$vt = new PHPVideoToolkit(DATAFACE_SITE_PATH.'/templates_c/');
$ffmpeg = $app->_conf['ffmpeg']['path'];
$previewField =& $record->_table->getField('preview_image');
$savepath = $previewField['savepath'];
$fileField =& $record->_table->getField('file');
$videopath = $fileField['savepath'].'/'.basename($record->val('file'));
$filename = basename($record->val('file')).'.jpg';
$filepath = $savepath.'/'.basename($filename);
while ( file_exists($filepath) ){
$filepath = tempnam($savepath, basename($record->val('file')).'.').'.jpg';
$filename = basename($filepath);
}
//$res = $vt->setInputFile($videopath);
//$timecode = '00:00:01.1';
exec($ffmpeg.' -i '.escapeshellarg($videopath).' -ss 00:00:01.00 -vcodec mjpeg -vframes 1 -f image2 '.escapeshellarg($filepath));
//$data = $vt->getFileInfo($videopath);
//if ( !$data ) return;
//$duration = intval($data['duration']['seconds']);
//if ($duration > 5 ){
// $timecode = '00:00:05.1';
//} else {
// $timecode = '00:00:00.1';
//}
//$vt->setVideoOutputDimensions(PHPVIdeoToolkit::SIZE_SAS);
//$res = $vt->setOutput($savepath.'/', $filename, PHPVideoToolkit::OVERWRITE_EXISTING);
//if ( !$res ) return;
//$res = $vt->execute(false,true);
$record->setValue('preview_image', $filename);
$record->setValue('preview_image_mimetype', 'image/jpeg');
if ( $record->valueChanged('file') and isset($app->_conf['s3']) and isset($app->_conf['s3']['access_key']) and isset($app->_conf['s3']['secret_key']) and isset($app->_conf['s3']['bucket']) ){
// We are using Amazon's Simple Storage Service for live video services
$mimetypes = @$app->_conf['s3']['mimetypes'];
$mimetypes = explode(',', strtolower($mimetypes));
if ( in_array(strtolower($record->val('file_mimetype')), $mimetypes) ){
// We are using one of the mimetypes that is to be served from S3
$record->pouch['s3_update'] = true;
//echo "We are going to move this to S3";exit;
}
} else if ( isset($app->_conf['s3']) ){
trigger_error("Your conf.ini file indicates that you wish to use S3 for storage, but you have not specified one of {access_key, secret_key, bucket}", E_USER_ERROR);
}
}
}
function afterSave(&$record){
if ( @$record->pouch['s3_update'] ){
$s3rec = df_get_record('s3', array('file_id'=>$record->val("file_id")));
if ( !$s3rec ){
$s3rec = new Dataface_Record('s3', array());
$s3rec->setValue('file_id', $record->val("file_id"));
}
$s3rec->setValue('status', 'PENDING');
$s3rec->save();
$app =& Dataface_Application::getInstance();
$conf =& $app->_conf['s3'];
unset($record->pouch['s3_update']);
}
}
function afterDelete(&$record){
$app =& Dataface_Application::getInstance();
$conf =& $app->_conf['s3'];
$fileField =& $record->_table->getField('file');
$savepath = $fileField['savepath'];
if ( $savepath{ strlen($savepath)-1 } != '/' ) $savepath .= '/';
$filepath = $savepath.basename($record->val('file'));
@unlink($filepath);
import('lib/S3.php');
$s3 = new S3($conf['access_key'], $conf['secret_key']);
$s3->deleteObject($conf['bucket'], urlencode(basename($filepath)));
}
function file__display(&$record){
static $mimetypes = -1;
static $conf = -1;
if ( $mimetypes == -1 ){
$app =& Dataface_Application::getInstance();
if ( isset($app->_conf['s3']) ){
$conf = $app->_conf['s3'];
$mimetypes = @$conf['mimetypes'];
$mimetypes = array_flip(explode(',',strtolower($mimetypes)));
}
else {
$conf = null;
$mimetypes = array();
}
}
//print_r($mimetypes);
if ( isset($mimetypes[$record->val("file_mimetype")]) ){
return 'http://s3.amazonaws.com/'.$conf['bucket'].'/'.basename($record->val('file'));
} else {
$field =& $record->_table->getField('file');
$url = $field['url'];
if ( $url{ strlen($url)-1} != '/' ) $url .= '/';
return $url.basename($record->val('file'));
}
}
function __import__zip(&$data, $defaults=array()){
import(DATAFACE_SITE_PATH.'/lib/Archive/Zip.php');
$importDir = DATAFACE_SITE_PATH.'/import';
$file = tempnam($importDir, 'import');
file_put_contents($file, $data);
$zip = new Archive_Zip($file);
$res = $zip->extract(array('remove_all_path'=>true, 'add_path'=>$importDir));
//print_r($res);exit;
foreach ($res as $item){
if ( $item['folder'] ){
@unlink($importDir.'/'.basename($item['filename']));
}
}
@unlink($file);
$result = $this->__import__fs($data, $defaults);
return $result;
}
function __import__fs(&$data, $defaults=array()){
import(dirname(__FILE__).'/Importer/fs.php');
$path = DATAFACE_SITE_PATH.'/import';
$dh = opendir($path);
if ( !$dh ){
trigger_error("Failed to open import directory", E_USER_ERROR);
}
$out = array();
while ( $file = readdir($dh) ){
$filepath = $path.'/'.basename($file);
if ( is_dir($filepath) ) continue;
$mime = mime_content_type($filepath);
if ( !$mime or $mime == 'application/octet-stream') $mime = $this->guessMimeType($filepath);
if ( !$mime ){
continue;
}
$d = array(
'file'=>basename($file),
'file_mimetype'=>$mime,
'file_title'=>ucwords(str_replace('_',' ',$file))
);
$out[] = new tables_files_Importer_fs($d);
}
return $out;
}
function __import__url_list(&$data, $defaults=array()){
$urls = explode("\n", $data);
$importPath = DATAFACE_SITE_PATH.'/import';
foreach ($urls as $url){
$contents = file_get_contents($url);
if ( !$contents ){
trigger_error("Failed to get url $url", E_USER_ERROR);
}
$filepath = $importPath.'/'.basename($url);
$res = file_put_contents($filepath, $contents);
if ( !$res ) trigger_error("Failed to save url $url", E_USER_ERROR);
}
return $this->__import__fs($data, $defaults);
}
function guessMimeType($filepath){
$parts = explode('.', $filepath);
$ext = $parts[count($parts)-1];
switch ($ext){
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'gif':
return 'image/gif';
case 'png':
return 'image/png';
case 'mp3':
return 'audio/mpeg';
case 'aiff':
case 'aifc':
return 'audio/x-aiff';
case 'wav':
return 'audio/x-wav';
case 'mp2':
case 'mpa':
case 'mpe':
case 'mpeg':
case 'mpg':
case 'mpv2':
return 'video/mpeg';
case 'mov':
case 'qt':
return 'video/quicktime';
case 'm4a':
case 'm4b':
case 'm4p':
return 'audio/m4a-latm';
case 'm4v':
return 'video/x-m4v';
case 'mp4':
return 'video/mp4';
case 'flv':
return 'video/x-flv';
}
return null;
}
function section__embed_code(&$record){
if ( preg_match('/^image\//', $record->val('file_mimetype') ) ){
$content = $this->_imageEmbedCode($record);
} else if ( strtolower($record->val('file_mimetype')) == 'video/x-flv' ){
$content = $this->_flvEmbedCode($record);
} else {
$content = 'Sorry this mimetype is not yet handled.';
}
return array(
'content' => $content,
'label' => 'Embed Code',
'class' => 'main'
);
}
function _imageEmbedCode(&$record){
$img_path = $record->display('file');
$out = '<script language="javascript"><!--
var selected_path = encodeURI("'.$img_path.'");
function selectPhoto(path){
var status_message = document.getElementById(\'Status-Message\');
status_message.style.display = \'block\';
selected_path = path;
var details = document.getElementById(\'photo-details\');
details.style.display=\'block\';
var photo = document.getElementById(\'selected-photo\');
photo.style.display=\'none\';
var widthfield = document.getElementById(\'selected-photo-width\');
var width = parseInt(widthfield.value);
var max_width = 640;
if ( width > 0 ){
max_width = width;
}
var contrast_field = document.getElementById(\'photo-contrast\');
var brightness_field = document.getElementById(\'photo-brightness\');
var gaussian_blur_field = document.getElementById(\'photo-gaussian-blur\');
var qstr = \'?max_width=\'+max_width;
if ( contrast_field.value ) qstr = qstr + \'&filter:contrast=\'+contrast_field.value;
if ( brightness_field.value ) qstr = qstr + \'&filter:brightness=\'+brightness_field.value;
if ( gaussian_blur_field.value ) qstr = qstr + \'&filter:gaussian_blur=\'+gaussian_blur_field.value;
photo.src = path+qstr;
widthfield.value = max_width;
var urlfield = document.getElementById(\'photo-url\');
var location = window.location;
var pasteurl = \'http://\'+window.location.host+path;
pasteurl = pasteurl + qstr;
urlfield.value = pasteurl;
var htmlfield = document.getElementById(\'photo-html\');
htmlfield.value = \'<img src="\'+pasteurl+\'"/>\';
}
function updatePhoto(){
selectPhoto(selected_path);
}
function imageLoaded(img){
document.getElementById(\'Status-Message\').style.display = \'none\';
document.getElementById(\'selected-photo\').style.display = \'\';
}
//--></script>
<div id="photo-details">
<h3>Selected Photo</h3>
<img id="selected-photo" onload="imageLoaded(this)" src="'.$img_path.'"/><br/>
<div id="Status-Message" style="display: none">Processing ... Please wait ...</div>
<h4>Instructions</h4>
<p>Adjust the size of the photo using <em>Photo Width</em> field. When you are happy
with the size of the photo, you can copy and paste either the URL for the photo, or
the HTML source code into your web page.</p>
<table>
<tr><th><label for="selected-photo-width">Max Width:</label></th><td><input type="text" id="selected-photo-width" size="4" onchange="updatePhoto()"/></td></tr>
<tr><th>Contrast:</th><td><input type="text" size="4" id="photo-contrast" onchange="updatePhoto()"/>
<span class="formHelp">(-100 = max contrast, 0 = no change, +100 = min contrast)</span></td></tr>
<tr><th>Brightness:</th><td><input type="text" size="4" id="photo-brightness" onchange="updatePhoto()"/>
<span class="formHelp">(-255 = min brightness, 0 = no change, +255 = max brightness)</span>
</td></tr>
<tr><th>Gaussian Blur</th><td><input type="text" size="4" id="photo-gaussian-blur" onchange="updatePhoto()"/>
<span class="formHelp">(Number of times to apply gaussian blur. Large numbers may take a long time to process. Try very low numbers like 1 or 5 to start.</span>
</td></tr>
</table>
<fieldset><legend>Embed Code</legend>
<label>SRC URL</label><input type="text" id="photo-url" size="60" onclick="this.select()"/><br/>
<label>IMG Tag</label><br/><textarea id="photo-html" rows="5" onclick="this.select()"></textarea>
</fieldset>
<script language="javascript"><!--
updatePhoto();
//--></script>
</div>';
return $out;
}
function field__video_info(&$record){
import(DATAFACE_SITE_PATH.'/lib/phpvideotoolkit.php');
$vt = new PHPVideoToolkit(DATAFACE_SITE_PATH.'/templates_c/');
$fileField =& $record->_table->getField('file');
$savepath = $fileField['savepath'];
$videopath = $savepath.'/'.basename($record->val('file'));
$res = $vt->setInputFile($videopath);
$data = $vt->getFileInfo($videopath);
return $data;
}
function _flvEmbedCode(&$record){
if ( in_array($record->val('status') , array('PROCESSING','PENDING')) ){
$dataface_url = DATAFACE_SITE_URL;
$progress_img_src = $dataface_url.'/images/progress.gif';
return <<<END
<h3>Processing... <img src="$progress_img_src" /></h3>
<p>This video is currently being processed. It should be ready shortly.</p>
END;
}
$info = $record->val('video_info');
//print_r($info);
if ( $info ){
$def_width = $info['video']['dimensions']['width'];
$def_height = $info['video']['dimensions']['height'];
}
if ( !$def_width ){
$def_width = 320;
}
if ( !$def_height ){
$def_height = 240;
}
if ( @$_REQUEST['-width'] ){
$width = $_REQUEST['-width'];
if ( !@$_REQUEST['-height'] ){
$height = intval($width*$def_height/$def_width);
}
}
if ( @$_REQUEST['-height'] ){
$height = $_REQUEST['-height'];
if ( !@$_REQUEST['-width']){
$width = intval($height*$def_width/$def_height);
}
}
if ( !$height ) $height = $def_height;
if ( !$width ) $width = $def_width;
$playerHeight = $height + 24;
$form = <<<END
<script language="javascript"><!--
function refreshVideo(){
var video_width = document.getElementById('video-width').value;
var video_height = document.getElementById('video-height').value;
var search = window.location.search;
if ( search.indexOf('&-width=') != -1 ){
search = search.replace(/&-width=[^&]*/, '&-width='+video_width);
} else {
search = search + '&-width='+video_width;
}
if ( search.indexOf('&-height=') != -1 ){
search = search.replace(/&-height=[^&]*/, '&-height='+video_height);
} else {
search = search + '&-height='+video_height;
}
window.location.search = search;
}
//--></script>
<fieldset>
<legend>Video Settings</legend>
<table>
<tr><th>Width</th><td><input type="text" size="4" id="video-width" value="$width"/></td></tr>
<tr><th>Height</th><td><input type="text" size="4" id="video-height" value="$height"/></td></tr>
<tr><th> </th><td><input type="button" value="Refresh" onclick="refreshVideo();"/></td></tr>
</table>
</fieldset>
END;
//$embed = '<embed src="'.df_absolute_url(DATAFACE_SITE_URL.'/lib/flvplayer.swf').'" width="'.$width.'" height="'.$playerHeight.'" bgcolor="#FFFFFF" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="file='.urlencode(df_absolute_url($record->display('file'))).'&image='.urlencode(df_absolute_url($record->display('preview_image'))).'&showdigits=true&autostart=false" />';
$embed = '<script type="text/javascript" src="'.df_absolute_url(DATAFACE_SITE_URL.'/js/flowplayer-3.0.6.min.js').'"></script><a href="'.htmlspecialchars(df_absolute_url($record->display('file'))).'" style="display:block;width:'.$width.'px;height:'.$playerHeight.'px" id="player-'.$record->val('file_id').'"></a><script>flowplayer("player-'.$record->val('file_id').'", "'.df_absolute_url(DATAFACE_SITE_URL.'/lib/flowplayer-3.0.7.swf').'");</script>';
$input = '<input type="text" size="60" onclick="this.select()" value="'.htmlspecialchars($embed).'" />';
return $form.$embed.'<h3>Embed Code:</h3>'.$input;
}
function logo_field__display(&$record){
if ( preg_match('/^image/', $record->val('file_mimetype')) ){
return $record->display('file').'?max_width=225&max_height=225';
} else if ( preg_match('/^video/', $record->val('file_mimetype')) ){
if ( $record->val('preview_image') ){
return $record->display('preview_image').'?max_width=225&max_height=225';
} else {
return 'images/video-x-generic.png';
}
} else {
return 'images/image-x-generic.png';
}
}
function logo_field__htmlValue(&$record){
return '<img src="'.$record->display('logo_field').'" class="logo_field" />';
}
function file_title__htmlValue(&$record){
return '<a href="'.$record->getURL('-action=view').'">'.$record->display('file_title').'</a>';
}
}