changeset 845:123cd6868b1b

Rework file upload backend code a bit.
author Matti Hamalainen <ccr@tnsp.org>
date Tue, 25 Nov 2014 23:49:41 +0200
parents fcaafeda4faa
children e0c9bf182bb7
files msite.inc.php
diffstat 1 files changed, 54 insertions(+), 71 deletions(-) [+]
line wrap: on
line diff
--- a/msite.inc.php	Tue Nov 25 22:12:01 2014 +0200
+++ b/msite.inc.php	Tue Nov 25 23:49:41 2014 +0200
@@ -842,7 +842,22 @@
 //
 // Create a path, or URL from specified components
 //
-function stMakePath($isURL, $repExt, $components)
+function stFilterPathComponent($str)
+{
+  return preg_replace("/[^a-zA-Z0-9\,\.\/_-]/", "_", $str);
+}
+
+
+function stReplaceFileExt($filename, $fext)
+{
+  if (($spos = strrpos($filename, ".")) !== FALSE)
+    return substr($filename, 0, $spos).$fext;
+  else
+    return $filename.$fext;
+}
+
+
+function stMakePath($isURL, $components)
 {
   $res = array();
 
@@ -856,29 +871,19 @@
     $first = TRUE;
 
   // Handle each path component
-  foreach ($components as $subComponent)
+  if (count($components) > 0)
   {
-    foreach (explode("/", $subComponent) as $item)
+    for ($i = 0; $i < count($components) - 1; $i++)
+    foreach (explode("/", $components[$i]) as $item)
     {
       if ($item == "..")
         array_pop($res);
       else
       if ($item != "." && ($item != "" || $first))
-        $res[] = preg_replace("/[^a-zA-Z0-9\,\.\/_-]/", "_", $item);
-
+        $res[] = stFilterPathComponent($item);
       $first = FALSE;
     }
-  }
-
-  // Optionally, replace the file extension with given string
-  if ($repExt !== FALSE && ($tmp = array_pop($res)) !== false)
-  {
-    if (($spos = strrpos($tmp, ".")) !== FALSE)
-      $tmp = substr($tmp, 0, $spos).$repExt;
-    else
-      $tmp .= $repExt;
-
-    $res[] = $tmp;
+    $res[] = $components[$i];  
   }
 
   return implode("/", $res);
@@ -1048,53 +1053,34 @@
 //
 // File table entry adding
 //
-function stAddFileEntry($filename, $size, $uploaderID, $type, $entryID, &$fileID)
+function stFindOrAddFileEntry($entry, $type, $origName, $fileSize, $fileExt, $uploaderID)
 {
+  // Compute destination filename
+  $fileName = sprintf("%03d-%s--%s%s.%s",
+    $entry["id"],
+    stFilterPathComponent($entry["author"]),
+    stFilterPathComponent($entry["name"]),
+    ($type == "preview" ? "_preview" : ""),
+    $fileExt);
+
   // Create new file entry
   $sql = stPrepareSQL(
-    "INSERT INTO files (orig_filename,filesize,entry_id,uploader_id,utime) VALUES (%s,%d,%d,%d,%d)",
-    $filename, $size, $entryID, $uploaderID, time());
+    "INSERT INTO files (filename,origname,filetype,filesize,entry_id,uploader_id,utime) ".
+    "VALUES (%s,%s,%s,%d,%d,%d,%d)",
+    $fileName, $origName, $fileInfo["id"], $fileSize, $entry["id"], $uploaderID, time());
 
   if (($fileID = stExecSQLInsert($sql)) === false)
-    return stError("Failed to add new ".$type." for entry #".$entryID." '".$filename."'.");
+    return stError("Failed to add new ".$type." for entry #".$entry["id"]." '".$origName."'.");
 
-  // Update entry's data
-  $sql = stPrepareSQL("UPDATE entries SET ".$type."_id=%d WHERE id=%d",
-    $fileID, $entryID);
+  // Update entry's reference
+  $sql = stPrepareSQL("UPDATE entries SET ".($type == "preview" ? "preview" : "file")."_id=%d WHERE id=%d",
+    $fileID, $entry["id"]);
 
   if (stExecSQL($sql) === false)
-    return stError("Failed to update entry #".$entryID." ".$type." ID ... :S");
-
-  return TRUE;
-}
-
+    return stError("Failed to update entry #".$entry["id"]." ".$type." ID ... :S");
 
-function stSetFileEntryFilename($fileID, $type, $entry, $fext, $ftype, &$fname)
-{
-  switch ($type)
-  {
-    case "preview":
-      $fname = sprintf("%03d-%s--%s_%s_(%03d).%s",
-	$entry["id"],
-	$entry["author"], $entry["name"],
-	$type, $fileID, $fext);
-      break;
-
-    case "entry":
-      $fname = sprintf("%03d-%s--%s_(%03d).%s",
-	$entry["id"],
-	$entry["author"], $entry["name"],
-	$fileID, $fext);
-      break;
-
-    default:
-      return FALSE;
-  }
-
-  $sql = stPrepareSQL("UPDATE files SET filename=%s,filetype=%s WHERE id=%d",
-    $fname, $ftype, $fileID);
-
-  return stExecSQL($sql) !== false;
+  // Return file entry
+  return stFetchSQL("SELECT * FROM files WHERE id=".$fileID);
 }
 
 
@@ -1133,16 +1119,20 @@
   }
 
   // Check file status data
-  $fileEntry = $uploadType."ToUpload".$entryID;
   $maxFileSize = stGetSetting($uploadType."MaxSize");
-  $fileSize = $_FILES[$fileEntry]["size"];
+
+  $index = $uploadType."ToUpload".$entryID;
+  $fileSize = $_FILES[$index]["size"];
+  $tmpFilename = $_FILES[$index]["tmp_name"];
+  $orgFilename = $_FILES[$index]["name"];
+
   if ($fileSize > $maxFileSize)
     stError("File size ".$fileSize." exceeds FAPWeb's size of ".$maxFileSize." bytes for ".$uploadType." uploads.");
 
   if ($fileSize < 128)
     stError("File size ".$fileSize." is less than 128 bytes. This can't be right.");
 
-  switch ($_FILES[$fileEntry]["error"])
+  switch ($_FILES[$index]["error"])
   {
     case UPLOAD_ERR_INI_SIZE:
       stError("File size exceeds PHP's max upload size.");
@@ -1177,7 +1167,6 @@
 
 
   // Check file properties ..
-  $tmpFilename = $_FILES[$fileEntry]["tmp_name"];
   if (($fileInfo = stProbeFileInfo($tmpFilename)) === false)
     return FALSE;
 
@@ -1185,21 +1174,15 @@
     return stError("Preview file upload is not one of the supported preview file types.");
   
   // Get original extension
-  $origFilename = $_FILES[$fileEntry]["name"];
   if (($fext = $fileInfo["fext"]) === false)
   {
     $fext = ".tmp";
-    if (($rpos = strrpos($origFilename, ".")) !== false)
-      $fext = substr($origFilename, $rpos);
+    if (($rpos = strrpos($orgFilename, ".")) !== false)
+      $fext = substr($orgFilename, $rpos);
   }
 
-  // Add file entry
-  if (!stAddFileEntry($origFilename, $fileSize, $userID,
-    ($uploadType == "entry") ? "file" : "preview", $entry, $fileID))
-    return FALSE;
-
-  // Set rest of the data ..
-  if (!stSetFileEntryFilename($fileID, $uploadType, $entry, $fext, $fileInfo["id"], $filename))
+  // Find current or add new file entry
+  if (($fentry = stFindOrAddFileEntry($entry, $uploadType, $orgFilename, $fileSize, $fileInfo, $userID)) === false)
     return FALSE;
 
   // Set permissions before moving the file
@@ -1210,10 +1193,10 @@
   }
 
   // Move file to its destination
-  $fullFile = stMakePath(FALSE, FALSE, array(stGetSetting("entryPath"), $compo["cpath"], $filename));
-  if (@move_uploaded_file($tmpFilename, $fullFile) === false)
+  $dstFilename = stMakePath(FALSE, array(stGetSetting("entryPath"), $compo["cpath"], $fentry["filename"]));
+  if (@move_uploaded_file($tmpFilename, $dstFilename) === false)
   {
-    error_log("Could not move uploaded file '".$tmpFilename."' to '".$fullFile."'.");
+    error_log("Could not move uploaded file '".$tmpFilename."' to '".$dstFilename."'.");
     return stError("Deploying uploaded file failed.");
   }