Add additional check to prevent sending direct uploads with JSON requests
[shpub.git] / src / shpub / Request.php
index 3a4512e3bca75f666c38569bb32a68265be890ea..07138720c26cf7a4cc3f4139547d66a00746f69a 100644 (file)
@@ -56,7 +56,7 @@ class Request
                 $data['url'] = $this->url;
             }
             if ($this->type !== null) {
-                $data['type'] = 'h-' . $this->type;
+                $data['type'] = array('h-' . $this->type);
             }
             if (count($this->properties)) {
                 $data['properties'] = $this->properties;
@@ -96,15 +96,37 @@ class Request
         $res = $this->req->send();
 
         if (intval($res->getStatus() / 100) != 2) {
-            Log::err(
-                'Server returned an error status code ' . $res->getStatus()
-            );
-            Log::err($res->getBody());
-            exit(11);
+            $this->displayErrorResponse($res);
         }
         return $res;
     }
 
+    protected function displayErrorResponse($res)
+    {
+        Log::err(
+            'Server returned an error status code ' . $res->getStatus()
+        );
+
+        $shown = false;
+        if ($res->getHeader('content-type') == 'application/json') {
+            $errData = json_decode($res->getBody());
+            if (!isset($errData->error)) {
+                Log::err('Error response does not contain "error" property');
+            } else if (isset($errData->error_description)) {
+                Log::err($errData->error . ': ' . $errData->error_description);
+                $shown = true;
+            } else {
+                Log::err($errData->error);
+                $shown = true;
+            }
+        }
+
+        if (!$shown) {
+            Log::err($res->getBody());
+        }
+        exit(11);
+    }
+
     public function setAction($action)
     {
         $this->action = $action;
@@ -126,6 +148,12 @@ class Request
      */
     public function addUpload($fieldName, $fileNames)
     {
+        if ($this->directUpload && $this->sendAsJson) {
+            throw new \Exception(
+                'Cannot do direct upload with JSON requests'
+            );
+        }
+
         if ($this->host->endpoints->media === null
             || $this->directUpload
         ) {
@@ -154,7 +182,7 @@ class Request
     /**
      * @return string URL at media endpoint
      */
-    protected function uploadToMediaEndpoint($fileName)
+    public function uploadToMediaEndpoint($fileName)
     {
         $httpReq = $this->getHttpRequest(
             $this->host->endpoints->media, $this->host->token