Simple Groupware PHP Cross Reference Groupware Applications

Source: /src/upload.php - 237 lines - 10129 bytes - Summary - Text - Print

   1  <?php
   2      /**************************************************************************\
   3      * Simple Groupware 0.743                                                   *
   4      * http://www.simple-groupware.de                                           *
   5      * Copyright (C) 2002-2012 by Thomas Bley                                   *
   6      * ------------------------------------------------------------------------ *
   7      *  This program is free software; you can redistribute it and/or           *
   8      *  modify it under the terms of the GNU General Public License Version 2   *
   9      *  as published by the Free Software Foundation; only version 2            *
  10      *  of the License, no later version.                                       *
  11      *                                                                          *
  12      *  This program is distributed in the hope that it will be useful,         *
  13      *  but WITHOUT ANY WARRANTY; without even the implied warranty of          *
  14      *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the            *
  15      *  GNU General Public License for more details.                            *
  16      *                                                                          *
  17      *  You should have received a copy of the GNU General Public License       *
  18      *  Version 2 along with this program; if not, write to the Free Software   *
  19      *  Foundation, Inc., 59 Temple Place - Suite 330, Boston,                  *
  20      *  MA  02111-1307, USA.                                                    *
  21      \**************************************************************************/
  22  
  23  define("NOCONTENT",true);
  24  define("NOSESSION",true);
  25  require ("index.php");
  26  
  27  if (empty($_REQUEST["item"]) and empty($_REQUEST["filename"])) sys_error("Missing parameters.","403 Forbidden");
  28  sys_check_auth();
  29  
  30  $ext = modify::getfileext(urldecode($_SERVER["REQUEST_URI"]));
  31  if (in_array($ext, explode(",", INVALID_EXTENSIONS))) {
  32    sys_error(sprintf("{t}this file extension is not allowed{/t} (%s)", $ext),"403 Forbidden");
  33  }
  34  
  35  $content_length = sys_get_header("Content-Length");
  36  if ($content_length==0 and strtolower($_REQUEST["action"])!="move") {
  37    _upload_success();
  38  }
  39  
  40  if (strtolower($_REQUEST["action"])=="move" and !empty($_SERVER["HTTP_DESTINATION"])) {
  41    $_SERVER["REQUEST_URI"] = substr($_SERVER["HTTP_DESTINATION"],strpos($_SERVER["HTTP_DESTINATION"],"/sgdav/"));
  42  }
  43  
  44  if ($_REQUEST["item"]=="session") {
  45    $path = str_replace("//","/",urldecode($_SERVER["REQUEST_URI"]));
  46    $filename = basename($path);
  47    $path = dirname($path);
  48    if (sys_strbegins($filename,"~") or sys_strbegins($filename,".") or modify::getfileext($filename)=="tmp") {
  49      $target = SIMPLE_CACHE."/upload/".$_SESSION["username"].sha1($path)."--".urlencode($filename);
  50      if ($fp = fopen("php://input","r") and $ft = fopen($target,"wb")) {
  51        while (!feof($fp)) fwrite($ft,fread($fp,8192));
  52        fclose($fp);
  53        fclose($ft);
  54        _upload_success();
  55      } else {
  56        sys_error("cant write","403 Forbidden");
  57      }
  58    } else {
  59      $target_lnk = SIMPLE_CACHE."/upload/".$_SESSION["username"].sha1($path)."--".urlencode($filename).".link";
  60      if (file_exists($target_lnk)) {
  61        $link = file($target_lnk);
  62        if (preg_match("|^/sgdav/(.+)/(\d+)_0__.+|",$link[0],$match)) {
  63          $_REQUEST["folder"] = "/".$match[1]."/";
  64          $_REQUEST["item"] = array($match[2]);
  65        }
  66      } else {
  67        $db_path = substr($path,strlen("/sgdav"));
  68        _upload_create_file($db_path, $target_lnk, $path, $filename);
  69  } } }
  70  
  71  // TODO use sgsml class
  72  
  73  folder_process_session_request();
  74  folder_build_folders();
  75  $GLOBALS["table"] = db_get_schema($GLOBALS["schemafile"],$GLOBALS["tfolder"],$GLOBALS["tview"]);
  76  $GLOBALS["tname"] = $GLOBALS["table"]["att"]["NAME"];
  77  
  78  sys_process_session_request();
  79  
  80  if (empty($_REQUEST["field"])) $field = "filedata"; else $field = ltrim($_REQUEST["field"],"_");
  81  $field = sql_fieldname($field);
  82  
  83  if ($content_length > _upload_get_limit($field)) {
  84    sys_error("{t}Upload failed{/t}: {t}file is too big. Please upload a smaller one.{/t} ({t}insufficient folder rights{/t})","409 Conflict");
  85  }
  86  
  87  $t = &$GLOBALS["t"];
  88  $t["sqlvars"]["item"] = $_REQUEST["item"];
  89  $t["sqlvarsnoquote"]["permission_sql_read_nq"] = $_SESSION["permission_sql_write"];
  90  $t["sqlvarsnoquote"]["permission_sql_write_nq"] = $_SESSION["permission_sql_write"];
  91  
  92  $row = db_select_first($GLOBALS["tname"],array_unique(array($field,"folder","id","dsize")),$t["sqlwhere"],"",$t["sqlvars"],array("sqlvarsnoquote"=>$t["sqlvarsnoquote"]));
  93  if (empty($row["folder"])) sys_error("{t}file not found in database.{/t}");
  94  
  95  if (!db_get_right($row["folder"],"write")) {
  96    sys_error("{t}Access to this file has been denied.{/t} ({t}insufficient folder rights{/t})","403 Forbidden");
  97  }
  98  
  99  if (empty($row[$field])) $row[$field] = "";
 100  $row_filename = $row[$field];
 101  
 102  if ($row_filename!="") {
 103    $file = explode("|",trim($row[$field],"|"));
 104    if (empty($_REQUEST["subitem"])) $_REQUEST["subitem"] = 0;
 105    if (!empty($file[$_REQUEST["subitem"]])) $row_filename = $file[$_REQUEST["subitem"]]; else $row_filename = "";
 106  }
 107  
 108  if ($row_filename=="") {
 109    $filename = urldecode(basename($_REQUEST["filename"]));
 110    list($target,$filename) = sys_build_filename($filename,"simple_files");
 111    dirs_checkdir($target);
 112    $target .= sys_get_pathnum($row["folder"])."/";
 113    dirs_checkdir($target);
 114    $target .= md5($row["folder"]).$filename;
 115    $newfilename = $target;
 116  } else {
 117    if (file_exists($row_filename.".lck") and !sys_can_unlock($row_filename,$_SESSION["username"])) {
 118      sys_error("{t}Access to this file has been denied.{/t}","409 Conflict");
 119    } else {
 120      $i = 1;
 121      $newfilename = preg_replace("|_rev\d+|","",$row_filename);
 122      $base = basename($newfilename);
 123      $dir = dirname($newfilename);
 124      while (file_exists($newfilename)) {
 125        if (($pos = strrpos($base,"."))) $name = substr($base,0,$pos)."_rev".($i++).substr($base,$pos); else $name = $base."_rev".($i++);
 126        $newfilename = $dir."/".$name;
 127      }
 128      if (!rename($row_filename,$newfilename)) {
 129        sys_error("{t}Error moving file{/t}","409 Conflict");
 130      }
 131      $target = $row_filename;
 132  
 133      if (strtolower($_REQUEST["action"])=="move" and !empty($_REQUEST["filename"])) {
 134        $path = str_replace("//","/",urldecode($_REQUEST["filename"]));
 135        $tmpfile = SIMPLE_CACHE."/upload/".$_SESSION["username"].sha1(dirname($path))."--".urlencode(basename($path));
 136        if (file_exists($tmpfile)) rename($tmpfile,$target);
 137  } } }
 138  
 139  $result = _upload_append_file($row,$field,$target,$newfilename);
 140  if (!$result) {
 141    @rename($newfilename,$row_filename);
 142    sys_error("Error writing file","409 Conflict");
 143  }
 144  
 145  function _upload_append_file($row,$field,$target,$newfilename) {
 146    $t = $GLOBALS["t"];
 147    if (!file_exists($target) and $fp=fopen("php://input","r") and $ft=fopen($target,"wb")) {
 148      while (!feof($fp)) fwrite($ft,fread($fp,8192));
 149      fclose($fp);
 150      fclose($ft);
 151    }
 152    if (!file_exists($target)) return false;
 153    if ($row[$field]!="") $files = explode("|",trim($row[$field],"|")); else $files = array();
 154    $files[] = $newfilename;
 155    $size = filesize($newfilename) + $row["dsize"];
 156    $history = sprintf("{t}Item edited (%s) by %s at %s{/t}",$field,$_SESSION["username"],sys_date("{t}m/d/y g:i:s a{/t}"))."\n{t}File{/t}: + ".modify::basename($newfilename)."\n\n";
 157    $error_sql = db_update($GLOBALS["tname"],array($field=>"|".implode("|",$files)."|","dsize"=>$size,"history"=>$history),$t["sqlwhere"],$t["sqlvars"],array("sqlvarsnoquote"=>$t["sqlvarsnoquote"]));
 158    if ($error_sql=="") {
 159      db_update_treesize($GLOBALS["tname"],$row["folder"]);
 160      db_search_update($GLOBALS["tname"],$t["sqlvars"]["item"],$GLOBALS["table"]["fields"]);
 161      _upload_success("204 No Content");
 162    }
 163    return false;
 164  }
 165  
 166  function _upload_get_limit($field_name) {
 167    $size = 0;
 168    $fields = $GLOBALS["table"]["fields"];
 169    if (isset($fields[$field_name]["SIMPLE_FILE_SIZE"])) {
 170      $size = $fields[$field_name]["SIMPLE_FILE_SIZE"];
 171      $size = str_replace(array("M","K"),array("000000","000"),$size);
 172    }
 173    return $size;
 174  }
 175  
 176  function _upload_process_folder_string($folder) {
 177    $parent = 0;
 178    $parent_last = 0;
 179    $nodes = explode("/",$folder);
 180    $left = count($nodes);
 181    foreach ($nodes as $node) {
 182      $left--;
 183      if ($node=="") continue;
 184      $where = array("ftitle=@title@", "parent=@parent@", $_SESSION["permission_sql_read"]);
 185      $vars = array("title"=>$node,"parent"=>$parent);
 186      $row_id = db_select_value("simple_sys_tree","id",$where,$vars);
 187      if (!empty($row_id)) {
 188        $parent_last = $parent;
 189        $parent = $row_id;
 190      } else {
 191        return array(0,$left,$parent);
 192      }
 193    }
 194    return array($parent,$left,$parent_last);
 195  }
 196  
 197  function _upload_create_file($db_path, $target_lnk, $path, $filename) {
 198    list($id,$left,$unused) = _upload_process_folder_string($db_path."/");
 199    if ($left!=0 or $id==0) sys_error("path not found","409 Conflict");
 200    
 201    $ftype = db_select_value("simple_sys_tree","ftype","id=@id@",array("id"=>$id));
 202    if (db_get_right($id, "write") and !empty($ftype) and $ftype=="files") {
 203    
 204      list($target,$a_filename) = sys_build_filename($filename,"simple_files");
 205      dirs_checkdir($target);
 206      $target .= sys_get_pathnum($id)."/";
 207      dirs_checkdir($target);
 208      $target .= md5($id).$a_filename;
 209  
 210      if ($fp = fopen("php://input","r") and $ft = fopen($target,"wb")) {
 211        while (!feof($fp)) fwrite($ft,fread($fp,8192));
 212        fclose($fp);
 213        fclose($ft);
 214        $a_id = sql_genID("simple_files")*100+$_SESSION["serverid"];
 215        $data = array(
 216          "id"=>$a_id, "folder"=>$id, "dsize"=>filesize($target),
 217          "filedata"=>"|".$target."|", "filename"=>$filename,
 218          "rread_users"=>"|anonymous|", "rwrite_users"=>"|anonymous|",
 219          "history"=>sprintf("{t}Item created by %s at %s{/t}\n",$_SESSION["username"],sys_date("{t}m/d/y g:i:s a{/t}"))
 220        );
 221         $error_sql = db_insert("simple_files",$data);
 222        if ($error_sql=="") {
 223          db_update_treesize("simple_files",$id);
 224          $fields = array("filename"=>"text", "filedata"=>"files", "folder"=>"id", "id"=>"id");
 225          db_search_update("simple_files",$a_id,array(),$fields);
 226          sys_log_stat("new_records",1);
 227  
 228          file_put_contents($target_lnk, $path."/".$a_id."_0__".$filename."\n".$target, LOCK_EX);
 229          _upload_success();
 230    } } }
 231    sys_error("cant write new","403 Forbidden");
 232  }
 233  
 234  function _upload_success($string="201 Created") {
 235    header("HTTP/1.1 ".$string);
 236    exit;
 237  }

title

Description

title

Description

title

Description

title

title

Body