fix bug #10: error when nothing submitted
[phorkie.git] / src / phorkie / Repository / Post.php
index 438bf5a3647bb2d06dc2a547a55c0f07f23a4c27..fe2372f67a1f80a50c60fa2ae12484966024c29d 100644 (file)
@@ -20,6 +20,9 @@ class Repository_Post
         if (!isset($postData['files'])) {
             return false;
         }
+        if (!$this->hasContent($postData)) {
+            return false;
+        }
 
         if (!$this->repo) {
             $this->repo = $this->createRepo();
@@ -48,6 +51,11 @@ class Repository_Post
             $orignalName = Tools::sanitizeFilename($arFile['original_name']);
             $name        = Tools::sanitizeFilename($arFile['name']);
 
+            if ($arFile['type'] == '_auto_') {
+                //FIXME: upload
+                $arFile['type'] = $this->getType($arFile['content']);
+            }
+
             if ($name == '') {
                 if ($bUpload) {
                     $name = Tools::sanitizeFilename($_FILES['files']['name'][$num]['upload']);
@@ -132,6 +140,19 @@ class Repository_Post
         return true;
     }
 
+    protected function hasContent($postData)
+    {
+        foreach ($postData['files'] as $num => $arFile) {
+            if ($_FILES['files']['error'][$num]['upload'] == 0) {
+                return true;
+            }
+            if ($arFile['content'] != '') {
+                return true;
+            }
+        }
+        return false;
+    }
+
     public function createRepo()
     {
         $rs = new Repositories();
@@ -163,6 +184,28 @@ class Repository_Post
 
         return $prefix . $num;
     }
+
+    protected function getType($content)
+    {
+        $tmp = tempnam(sys_get_temp_dir(), 'phorkie-autodetect-');
+        file_put_contents($tmp, $content);
+        $type = \MIME_Type_PlainDetect::autoDetect($tmp);
+        unlink($tmp);
+
+        return $this->findExtForType($type);
+    }
+
+    protected function findExtForType($type)
+    {
+        $ext = 'text/plain';
+        foreach ($GLOBALS['phorkie']['languages'] as $lext => $arLang) {
+            if ($arLang['mime'] == $type) {
+                $ext = $lext;
+                break;
+            }
+        }
+        return $ext;
+    }
 }
 
 ?>