<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/6 0006
 * Time: 17:30
 */
header('Access-Control-Allow-Origin:*');//允许跨域
define('IN_WEB', true);
$sid = 1;
$lid = 1;
$str = $_REQUEST['param'];
$sign = substr($str,0,1).substr($str,2,strlen($str));
$sign = substr($sign,0,floor((strlen($sign)-16)/2)-1).substr($sign,floor((strlen($sign)-16)/2)+15,strlen($sign));
$sign = base64_decode($sign);
$sign = trim($sign,'&');
$sign = explode('&',$sign);
foreach ($sign as $row){
    $temp = explode('=',$row,2);
    $_POST[$temp[0]] = $temp[1];
} 
include_once dirname(__FILE__) . "/../com.php";

$uid = intval($_POST['uid']);
$toUid = intval($_POST['toUid']);
$token = $_POST['saToken'];
$file = $_POST['audio'];

if(empty($uid) || empty($token) || empty($file)){
    return response(-6, 'param error');
}

$redisToken = oo::commonOprRedis('common')->get(okeys::UserToken($uid));
if(empty($token) || $token != $redisToken ){
    return response(-5, 'token error');
}

if(empty($toUid)){
    $audioDir = 'storage/World/';
}else{
    $audioDir = 'storage/'.$uid.'_'.$toUid.'/';
}

$uploadPath = getFolder('../'.$audioDir);
if(!$uploadPath) {
    return  response(-1, '存放文件图片文件夹创建失败');
}

$fileName = getName();
$newFile = $uploadPath.$fileName;

if(!file_put_contents($newFile, base64_decode($file))) {
    return response(-3, '文件出错');
}

amrTomp3($audioDir,$fileName);

$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://": "http://";
$path = $protocol.$_SERVER['SERVER_NAME'].'/'.$audioDir.str_replace('.amr','.mp3',$fileName);


die(response(1, '文件上传成功', ['audioPath' => $path]));
//---------end----------

/**
 * 自动创建存储文件夹
 * @return string
 */
 function getFolder($pathStr)
{
    if ( !is_dir( $pathStr ) ) {
        if ( !mkdir( $pathStr , 0777 , true ) ) {
            return false;
        }
    }

    return $pathStr;
}

/**
 * 重命名文件
 * @return string
 */
function getName()
{
    $ext = '.amr';
    return $fileName = time().uniqid().'_'.rand(1, 999).$ext;
}

function amrTomp3($path , $amr){
    $base = WWWROOT;
    $amrPath = $base.$path.$amr;
    $mp3Path = $base.$path.str_replace('.amr','.mp3',$amr);
    $command = "ffmpeg -i $amrPath $mp3Path";
    exec($command,$error);
  	unlink($amrPath);
}

/**
 * 统一输出返回json内容
 *
 * @access public
 * @date   2016-08-16
 * @param int    $ret  状态码,0成功
 * @param string $msg  错误信息
 * @param array  $data 返回数据内容
 * @return json;
 */
function response($ret = 0, $msg = '', array $data = array())
{
    $result = [
        'code'  => $ret,
        'msg'  => $msg,
        'data' => $data,
    ];

    die(json_encode($result));
}
