<?php

/*
This script is called by the Transcoder when rendering of a mash has completed and
transferred without error. If we can authenticate the request, we update the mash's media
object into the user's data space for the freshly rendered file. If an error is
encountered a 400 header is returned and it is logged, if possible.
*/
$err = '';
$config = array();
if (!@(include_once dirname(__FILE__) . '/include/loadutils.php')) {
    $err = 'Problem loading utility script';
}
if (!$err && !load_utils('api', 'data')) {
    $err = 'Problem loading utility scripts';
}
if (!$err) {
    // pull in configuration so we can log other errors
    $config = config_get();
    $err = config_error($config);
}
if (!$err) {
    // see if the request is authenticated (does not redirect or exit)
    if (!auth_ok_callback()) {
        $err = 'Unauthenticated access';
    }
}
if (!$err) {
    // pull in other configuration and check for required input
    if (!($php_input = file_get_contents('php://input'))) {
        $err = 'JSON payload required';
	* the base file name is changed to 'media'
	* a directory is created in the user's directory, the ID is used for the name
	* the file is moved to this directory, and a 'meta' directory is created alongside it
	* extension, type and name properties are cached to the 'meta' directory for later use
The media ID is passed as a parameter to import_api.php, by setting the 'url' attribute in response.
If an error is encountered it is displayed in a javascript alert, by setting the 'get' attribute.
If possible, the response to client is logged.
*/
$response = array();
$err = '';
$config = array();
$log_responses = '';
if (!@(include_once dirname(__FILE__) . '/include/loadutils.php')) {
    $err = 'Problem loading utility script';
}
if (!$err && !load_utils('auth', 'mime')) {
    $err = 'Problem loading utility scripts';
}
if (!$err) {
    // pull in configuration so we can log other errors
    $config = config_get();
    $err = config_error($config);
    $log_responses = $config['log_response'];
}
if (!$err) {
    // see if the user is authenticated (does not redirect or exit)
    if (!auth_ok()) {
        $err = 'Unauthenticated access';
    }
}
if (!$err) {
and 'size' key indicating the number of bytes in the file. There is also an
optional 'label' key that defaults to the filename, 'extension' key that is
drawn from the filename, and 'type' key that's used if the mime type can't be
determined from the file extension. The JSON response will include an 'error'
key indicating any problem or an 'endpoint' key containing a URL to POST the
file to, a 'data' key containing additional parameters, and an 'api' key with
parameters to be sent to import_api.php after successfully uploading. 
*/
$response = array();
$log_responses = '';
$err = '';
$config = array();
if (!@(include_once dirname(__FILE__) . '/include/loadutils.php')) {
    $err = 'Problem loading utility script';
}
if (!$err && !load_utils('auth', 'service')) {
    $err = 'Problem loading utility scripts';
}
if (!$err) {
    // pull in configuration so we can log other errors
    $config = config_get();
    $err = config_error($config);
    $log_responses = $config['log_response'];
}
// autheticate the user (will exit if not possible)
if (!$err && !auth_ok()) {
    auth_challenge($config);
}
if (!$err) {
    // pull in other configuration and check for required input
    if (!($php_input = file_get_contents('php://input'))) {
/*
This script is called directly from the Movie Masher client, in response to clicks in browser
navigation and scrolling. The count, index and group values are sent as GET parameters.
Additional GET parameters are used to limit the result set. If the user is authenticated
the script searches either the relevant JSON file, depending on group parameter. Media
matching parameters are included in result set, paged with count and index parameters. If
an error is encountered it is ignored and an empty result set is returned. This script is
called repeatedly as the user scrolls down, until an empty result set is returned.
*/
$err = '';
$config = array();
if (!@(include_once dirname(__FILE__) . '/include/loadutils.php')) {
    $err = 'Problem loading utility script';
}
if (!$err && !load_utils('auth', 'data')) {
    $err = 'Problem loading utility scripts';
}
if (!$err) {
    // pull in configuration so we can log other errors
    $config = config_get();
    $err = config_error($config);
}
if (!$err) {
    // grab GET parameters
    $count = empty($_GET['count']) ? 100 : $_GET['count'];
    $index = empty($_GET['index']) ? 0 : $_GET['index'];
    $group = empty($_GET['group']) ? '' : $_GET['group'];
    // see if we want requests logged, and potentially do so
    $log_requests = empty($config['log_request']) ? '' : $config['log_request'];
    $log_responses = empty($config['log_response']) ? '' : $config['log_response'];
<?php

include_once dirname(__FILE__) . '/loadutils.php';
load_utils('config', 'json');
if (!function_exists('data_save')) {
    function data_save($type, $media_data = array(), $userid = '', $config = array())
    {
        $err = '';
        if (empty($userid)) {
            $err = 'parameter userid required';
        }
        if (!$err) {
            if (!$config) {
                $config = config_get();
            }
            $err = config_error($config);
        }
        if (!$err) {
            $id = empty($media_data['id']) ? '' : $media_data['id'];
            if (!$id) {
                $err = 'data must contain an id key';
            }
        }
        if (!$err) {
            $path_data = path_concat($config['user_data_directory'], $userid);
            $media_file_json_path = path_concat($config['web_root_directory'], path_concat($path_data, 'media_' . $type . '.json'));
            $media_file_existed = file_exists($media_file_json_path);
            if ($media_file_existed) {
                $json_str = file_get($media_file_json_path);
            } else {
                $json_str = '[]';
<?php

/*
This script is called from the Transcoder, when progress has occured during job processing.
If the request can be properly authenticated, the message body is saved to the temp directory
using the $job parameter provide as a base name.
Any error encountered during processing is logged if possible.
*/
$err = '';
$config = array();
if (!@(include_once dirname(__FILE__) . '/include/loadutils.php')) {
    $err = 'Problem loading utility script';
}
if (!$err && !load_utils('auth')) {
    $err = 'Problem loading utility scripts';
}
if (!$err) {
    // pull in configuration so we can log other errors
    $config = config_get();
    $err = config_error($config);
}
if (!$err) {
    // see if the request is authenticated (does not redirect or exit)
    if (!auth_ok_callback()) {
        $err = 'Unauthenticated access';
    }
}
if (!$err) {
    // pull in other configuration and check for required input
    if (!($php_input = file_get_contents('php://input'))) {
        $err = 'JSON payload required';
imported media file with keys id, extension, type and label. If the
media file is remote, the url key will contain its location. The script
generates a job and posts it to Movie Masher Transcoder. The resultant
job ID is passed along with the media ID and type to import_monitor.php,
by setting the 'url' attribute in response. If an error is encountered
it is displayed in a javascript alert, by setting the 'get' attribute.
If possible, the response to client is logged.
*/
$response = array();
$err = '';
$config = array();
$log_responses = '';
if (!@(include_once dirname(__FILE__) . '/include/loadutils.php')) {
    $err = 'Problem loading utility script';
}
if (!$err && !load_utils('api')) {
    $err = 'Problem loading utility scripts';
}
if (!$err) {
    // pull in configuration so we can log other errors
    $config = config_get();
    $err = config_error($config);
    $log_responses = $config['log_response'];
}
if (!$err) {
    // see if the user is authenticated (does not redirect or exit)
    if (!auth_ok()) {
        $err = 'Unauthenticated access';
    }
}
if (!$err) {
<?php

include_once dirname(dirname(__FILE__)) . '/include/loadutils.php';
load_utils('file', 'id', 'path', 'config');
function local_file_source($input, $config)
{
    return array('name' => $config['import_original_basename'], 'extension' => $input['extension'], 'type' => 'file', 'method' => 'symlink', 'directory' => path_concat(path_concat(path_concat($config['web_root_directory'], $config['user_media_directory']), $input['uid']), $input['id']));
}
function local_file_import_url($import, $config)
{
    $uid = empty($import['uid']) ? '' : $import['uid'];
    return path_add_slash_start(path_concat($config['user_media_url'], $uid));
}
function local_file_export_url($import, $config)
{
    return local_file_import_url($import, $config);
}
function local_client_enqueue($data, $config = array())
{
    $result = array();
    $err = '';
    $id = empty($data['id']) ? id_unique() : $data['id'];
    $result['id'] = $data['id'] = $id;
    $job_path = path_concat($config['queue_directory'], $id . '.json');
    $json_str = @json_encode($data);
    if (!$json_str) {
        $err = 'could not encode json';
    } else {
        file_safe($job_path);
        if (!file_put($job_path, $json_str)) {
            $err = 'could not write job to ' . $job_path;
<?php

include_once dirname(dirname(__FILE__)) . '/include/loadutils.php';
load_utils('auth', 'path', 'date', 'json', 'http', 'log');
function sqs_client_enqueue($data, $config)
{
    $result = array();
    $err = '';
    $variables = array();
    $variables['Action'] = 'SendMessage';
    $variables['MessageBody'] = json_encode($data);
    $variables['Version'] = '2012-11-05';
    $parsed_url = parse_url($config['sqs_queue_url']);
    $headers = array();
    $headers['Host'] = strtolower($parsed_url['host']);
    $headers['X-Amz-Date'] = gmdate(DATE_FORMAT_ISO8601_BASIC);
    $signature = __sqs_client_version_four($config['aws_secret_access_key'], $config['sqs_queue_url'], $variables, $headers, $config['s3_region'], 'post');
    $region = empty($config['sqs_region']) ? empty($config['s3_region']) ? 'us-east-1' : $config['s3_region'] : $config['sqs_region'];
    // fallback to same region as s3 bucket
    $date_str = substr($headers['X-Amz-Date'], 0, 8);
    $headers['Authorization'] = "AWS4-HMAC-SHA256 Credential={$config['aws_access_key_id']}/{$date_str}/{$region}/sqs/aws4_request, SignedHeaders=host;x-amz-date, Signature={$signature}";
    $post_result = http_send($config['sqs_queue_url'], $variables, $headers);
    $data = $post_result['result'];
    if ($data && $config['log_api_response']) {
        log_file("sqs response:\n" . print_r($data, 1), $config);
    }
    if ($post_result['error']) {
        $err = 'Could not make sqs request ' . $config['sqs_queue_url'] . ' ' . $post_result['error'];
    } else {
        if (!$data) {
            $err = 'Got no response from sqs request';
<?php

include_once dirname(dirname(__FILE__)) . '/include/loadutils.php';
load_utils('id', 'date', 'path', 'log');
require 'aws/vendor/autoload.php';
// pull in aws-sdk
function s3_file_source($input, $config)
{
    return array('name' => $config['import_original_basename'], 'extension' => $input['extension'], 'type' => 'http', 'host' => $config['user_media_host'], 'path' => path_concat(path_concat($config['user_media_url'], $input['uid']), $input['id']));
}
function s3_file_import_url($import, $config)
{
    $uid = empty($import['uid']) ? '' : $import['uid'];
    return path_concat('http://' . $config['user_media_host'], path_concat($config['user_media_url'], $uid));
}
function s3_file_export_url($import, $config)
{
    return s3_file_import_url($import, $config);
}
function s3_file_config_defaults($config)
{
    if (empty($config['s3_acl'])) {
        $config['s3_acl'] = 'public-read';
    }
    if (empty($config['s3_expires'])) {
        $config['s3_expires'] = '+ 1 hour';
    }
    if (empty($config['s3_region'])) {
        $config['s3_region'] = '';
    }
    return $config;
<?php

/*
This file provides hooks for the authentication mechanisms and is included by most
scripts. It uses PHP's built in HTTP authentication but allows ANY username/password
combination to be used. The auth_challenge() function is only called from the index page.
The auth_userid() function is called whenever paths are built to the user's content
(uploads, rendered videos, XML data files). The auth_data() function is called from
when callbacks are being generated for inclusion in the job XML for the transcoder.
*/
include_once dirname(__FILE__) . '/loadutils.php';
load_utils('config');
if (!function_exists('auth_challenge')) {
    function auth_challenge($config)
    {
        $realm = empty($config['authentication_prompt']) ? 'Any username and password will work for this example!' : $config['authentication_prompt'];
        // in this example we use HTTP authentication
        // if using sessions, you'll probably want to redirect to login page instead
        header('WWW-Authenticate: Basic realm="' . $realm . '"');
        header('HTTP/1.0 401 Unauthorized');
        exit;
    }
}
if (!function_exists('auth_ok')) {
    function auth_ok($config = array())
    {
        $ok = FALSE;
        // check for configuration problem
        if (!$config) {
            $config = config_get();
        }
<?php

include_once dirname(__FILE__) . '/loadutils.php';
load_utils('auth', 'id', 'float', 'log', 'mime', 'service');
if (!function_exists('api_export')) {
    function api_export($input = array(), $output = array(), $config = array())
    {
        $result = array();
        if (!$config) {
            $config = config_get();
        }
        $result['error'] = config_error($config);
        // create export job
        if (empty($result['error'])) {
            $result = api_job_export($input, $output, $config);
        }
        // queue job
        if (empty($result['error'])) {
            $result = api_queue_job($result, $config);
        }
        return $result;
    }
}
if (!function_exists('api_import')) {
    function api_import($input = array(), $output = array(), $config = array())
    {
        $result = array();
        if (!$config) {
            $config = config_get();
        }
        $result['error'] = config_error($config);
<?php

/*
This script is called from the Transcoder, when progress has occured during job processing.
If the request can be properly authenticated, the message body is saved to the temp directory
using the $job parameter provide as a base name.
Any error encountered during processing is logged if possible.
*/
$err = '';
$config = array();
if (!@(include_once dirname(__FILE__) . '/include/loadutils.php')) {
    $err = 'Problem loading utility script';
}
if (!$err && !load_utils('auth', 'json')) {
    $err = 'Problem loading utility scripts';
}
if (!$err) {
    // pull in configuration so we can log other errors
    $config = config_get();
    $err = config_error($config);
}
if (!$err) {
    // see if the request is authenticated (does not redirect or exit)
    if (!auth_ok_callback()) {
        $err = 'Unauthenticated access';
    }
}
if (!$err) {
    // pull in other configuration and check for required input
    if (!($php_input = file_get_contents('php://input'))) {
        $err = 'JSON payload required';
<?php

include_once dirname(__FILE__) . '/loadutils.php';
load_utils('file', 'mime', 'config');
if (!function_exists('service_config_defaults')) {
    function service_config_defaults($config = array())
    {
        if (empty($config['client'])) {
            $config['client'] = 'local';
        }
        if (empty($config['file'])) {
            $config['file'] = 'local';
        }
        if (__service_load('client', $config)) {
            $function_name = $config['client'] . '_client_config_defaults';
            if (function_exists($function_name)) {
                $config = $function_name($config);
            }
        }
        if (__service_load('file', $config)) {
            $function_name = $config['file'] . '_file_config_defaults';
            if (function_exists($function_name)) {
                $config = $function_name($config);
            }
        }
        return $config;
    }
}
if (!function_exists('service_config_error')) {
    function service_config_error($config = array())
    {
<?php

/*
This script receives the rendered mash from the Transcoder API as a video file in $_FILES. 
If the file is okay, it's moved to the directory named $id in the user's directory. If an
error is encountered a 400 header is returned and it is logged, if possible.
*/
$err = '';
$config = array();
if (!@(include_once dirname(__FILE__) . '/include/loadutils.php')) {
    $err = 'Problem loading utility script';
}
if (!$err && !load_utils('auth', 'id', 'archive')) {
    $err = 'Problem loading utility scripts';
}
if (!$err) {
    // pull in configuration so we can log other errors
    $config = config_get();
    $err = config_error($config);
}
if (!$err) {
    // see if the user is authenticated (does not redirect or exit)
    if (!auth_ok_callback($config)) {
        $err = 'Unauthenticated access';
    }
}
if (!$err) {
    // pull in other configuration and check for required input
    $id = empty($_REQUEST['id']) ? '' : $_REQUEST['id'];
    $job = empty($_REQUEST['job']) ? '' : $_REQUEST['job'];
    $uid = empty($_REQUEST['uid']) ? '' : $_REQUEST['uid'];
<?php

include_once dirname(__FILE__) . '/loadutils.php';
load_utils('file');
if (!function_exists('http_is_url')) {
    function http_is_url($url)
    {
        return 'http' == substr($url, 0, 4);
    }
}
if (!function_exists('http_execute_array')) {
    function http_execute_array($ch)
    {
        $result = array('error' => '', 'result' => '', 'status' => '');
        $result['result'] = curl_exec($ch);
        $result['info'] = curl_getinfo($ch);
        if (!empty($result['info']['http_code'])) {
            $result['status'] = $result['info']['http_code'];
            if ($result['status'] >= 400) {
                $result['error'] = 'Received status code ' . $result['info']['http_code'];
            }
        }
        if (empty($result['error'])) {
            $result['error'] = curl_error($ch);
        }
        return $result;
    }
}
if (!function_exists('http_get_contents')) {
    function http_get_contents($url)
    {
<?php

// A convenient place to suppress errors and avoid corrupt json responses
ini_set('display_errors', 0);
include_once dirname(__FILE__) . '/loadutils.php';
load_utils('service', 'http', 'log', 'path');
if (!function_exists('config_defaults')) {
    function config_defaults($config = array())
    {
        $config['authentication'] = empty($config['authentication']) ? '' : $config['authentication'];
        $config['aws_access_key_id'] = empty($config['aws_access_key_id']) ? '' : $config['aws_access_key_id'];
        $config['aws_secret_access_key'] = empty($config['aws_secret_access_key']) ? '' : $config['aws_secret_access_key'];
        $config['export_audio_codec_audio'] = empty($config['export_audio_codec_audio']) ? 'libmp3lame' : $config['export_audio_codec_audio'];
        $config['export_audio_bitrate'] = empty($config['export_audio_bitrate']) ? '128' : $config['export_audio_bitrate'];
        $config['export_audio_codec'] = empty($config['export_audio_codec']) ? 'aac' : $config['export_audio_codec'];
        $config['export_audio_extension'] = empty($config['export_audio_extension']) ? 'mp3' : $config['export_audio_extension'];
        $config['export_audio_rate'] = empty($config['export_audio_rate']) ? '44100' : $config['export_audio_rate'];
        $config['export_dimensions'] = empty($config['export_dimensions']) ? '512x288' : $config['export_dimensions'];
        $config['export_extension'] = empty($config['export_extension']) ? 'mp4' : $config['export_extension'];
        $config['export_video_rate'] = empty($config['export_video_rate']) ? '30' : $config['export_video_rate'];
        $config['export_meta_title'] = empty($config['export_meta_title']) ? '' : $config['export_meta_title'];
        $config['export_video_bitrate'] = empty($config['export_video_bitrate']) ? '2000' : $config['export_video_bitrate'];
        $config['export_video_codec'] = empty($config['export_video_codec']) ? 'libx264' : $config['export_video_codec'];
        $config['web_root_directory'] = empty($config['web_root_directory']) ? $_SERVER['DOCUMENT_ROOT'] : $config['web_root_directory'];
        $config['temporary_directory'] = empty($config['temporary_directory']) ? sys_get_temp_dir() : $config['temporary_directory'];
        $config['queue_directory'] = empty($config['queue_directory']) ? path_concat($config['temporary_directory'], 'queue') : $config['queue_directory'];
        $config['import_audio_bitrate'] = empty($config['import_audio_bitrate']) ? '128' : $config['import_audio_bitrate'];
        $config['import_audio_extension'] = empty($config['import_audio_extension']) ? 'mp3' : $config['import_audio_extension'];
        $config['import_audio_basename'] = empty($config['import_audio_basename']) ? 'audio' : $config['import_audio_basename'];
        $config['import_audio_rate'] = empty($config['import_audio_rate']) ? '44100' : $config['import_audio_rate'];
        $config['import_dimensions'] = empty($config['import_dimensions']) ? '256x144' : $config['import_dimensions'];