<?php
/**
 * Library module
 * 
 * Upload file script used for workgroup user
 * 
 * @package linea21\core\library
 * @author $Author$ - Simon Georget <simon@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

//header('Content-type: application/json');
//header('Content-type: text/plain');

@set_time_limit(0);
include_once('../config/define.php');
session_start();

$id = $_REQUEST['id'];
$file = $_FILES['file'];

if(isset($_REQUEST['is_shared'])) $foldername = 'shared';
else $foldername = $id;


if(!$l21auth->isWorkgroupUser($id, $sql_object)) die('no way!');

if (!empty($_FILES)) {
  $tempFile = $_FILES['file']['tmp_name'];
  $file = $_FILES['file'];
  $filename_parts = pathinfo($_FILES['file']['name']);
  $filename = Stringy\Stringy::create($filename_parts['filename'], CHARSET)->slugify().'.'.$filename_parts['extension'];


  $targetPath = dirname(__FILE__). DIRECTORY_SEPARATOR . 'userfiles'. DIRECTORY_SEPARATOR . 'workgroups' . DIRECTORY_SEPARATOR . $foldername . DIRECTORY_SEPARATOR;

  $targetFile = str_replace('//','/',$targetPath) . $filename;

  if (in_array(strtolower($filename_parts['extension']),explode(',', MEDIA_ALLOWED_EXT))) {
    if(!file_exists(str_replace('//','/',$targetPath)))
    mkdir(str_replace('//','/',$targetPath), 0755, true);

    move_uploaded_file($tempFile,$targetFile);
    echo '{"transfer":"success", "filename":"'.$filename.'","type":"'.$file['type'].'","size":"'.$file['size'].'"}';
  } else {
    echo '{"transfer":"failed", "filename":"'.$filename.'","type":"'.$file['type'].'","size":"'.$file['size'].'"msg" : "File transfer error"}';
  }
}
?>