Skip to content
Snippets Groups Projects
ajax.draft.php 13.07 KiB
<?php

if(!defined('INCLUDE_DIR')) die('!');

require_once(INCLUDE_DIR.'class.draft.php');

class DraftAjaxAPI extends AjaxController {

    function _createDraft($vars) {
        if (false === ($vars['body'] = self::_findDraftBody($_POST)))
            return JsonDataEncoder::encode(array(
                'error' => __("Draft body not found in request"),
                'code' => 422,
                ));

        if (!($draft = Draft::create($vars)) || !$draft->save())
            Http::response(500, 'Unable to create draft');

        echo JsonDataEncoder::encode(array(
            'draft_id' => $draft->getId(),
        ));
    }

    function _getDraft($draft) {
        if (!$draft || !$draft instanceof Draft)
            Http::response(205, "Draft not found. Create one first");

        $body = Format::viewableImages($draft->getBody());

        echo JsonDataEncoder::encode(array(
            'body' => $body,
            'draft_id' => $draft->getId(),
        ));
    }

    function _updateDraft($draft) {
        if (false === ($body = self::_findDraftBody($_POST)))
            return JsonDataEncoder::encode(array(
                'error' => array(
                    'message' => "Draft body not found in request",
                    'code' => 422,
                )
            ));

        if (!$draft->setBody($body))
            return Http::response(500, "Unable to update draft body");

        echo "{}";
    }

    function _uploadInlineImage($draft) {
        global $cfg;

        if (!isset($_POST['data']) && !isset($_FILES['file']))
            Http::response(422, "File not included properly");

        # Fixup for expected multiple attachments
        if (isset($_FILES['file'])) {
            foreach ($_FILES['file'] as $k=>$v)
                $_FILES['image'][$k] = array($v);
            unset($_FILES['file']);

            $file = AttachmentFile::format($_FILES['image']);
            # Allow for data-uri uploaded files
            $fp = fopen($file[0]['tmp_name'], 'rb');
            if (fread($fp, 5) == 'data:') {
                $data = 'data:';
                while ($block = fread($fp, 8192))
                  $data .= $block;
                $file[0] = Format::parseRfc2397($data);