diff --git a/lib/api/attachments.php b/lib/api/attachments.php index c6eed65..436535f 100644 --- a/lib/api/attachments.php +++ b/lib/api/attachments.php @@ -1,198 +1,436 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ class kolab_api_attachments extends kolab_api { protected $model = 'attachment'; public function run() { $this->initialize_handler(); + // Load required attachments plugin (for uploads handling) + if (!class_exists('filesystem_attachments', false)) { + $this->plugins->load_plugin('filesystem_attachments', true); + } + $path = $this->input->path; $method = $this->input->method; - if ($path[0] && $path[1] && $method == 'POST') { + if ($path[0] == 'upload' && count($path) == 1 && $method == 'POST') { + $this->api_attachment_upload(); + } + else if ($path[0] && $path[1] && $method == 'POST') { $this->api_attachment_create(); } else if ($path[2]) { if ($method == 'GET') { if ($path[3] === 'get') { $this->api_attachment_body(); } else { $this->api_attachment_info(); } } else if ($method == 'PUT') { $this->api_attachment_update(); } else if ($method == 'HEAD') { $this->api_attachment_exists(); } else if ($method == 'DELETE') { $this->api_attachment_delete(); } } throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } /** * Fetch attachment info */ protected function api_attachment_info() { $folder = $this->input->path[0]; $object_uid = $this->input->path[1]; $attach_uid = $this->input->path[2]; $object = $this->backend->object_get($folder, $object_uid); $context = array( 'folder_uid' => $folder, 'object_uid' => $object_uid, 'object' => $object ); // get attachment part from the object $attachment = $this->get_attachment($object, $attach_uid); $this->output->send($attachment, $this->model, $context); } /** - * Create a attachment + * Create an attachment */ protected function api_attachment_create() { $folder = $this->input->path[0]; $object_uid = $this->input->path[1]; $object = $this->backend->object_get($folder, $object_uid); - $attachment = $this->input->input('attachment'); $context = array( 'folder_uid' => $folder, 'object_uid' => $object_uid, 'object' => $object ); -// @TODO -// $uid = $this->backend->attachment_add($folder, $object, $attachment); + // parse input, attach uploaded file, set input properties + $attachment = $this->handle_attachment_input(); + + // add the attachment to the message/object + $uid = $this->backend->attachment_create($object, $attachment); + + // @TODO: should we keep the uploaded file for longer? + if ($attachment->upload_id) { + unset($_SESSION['uploads'][$attachment->upload_id]); + } -// $this->output->send(array('uid' => $uid), $this->model, $context, array('uid')); + $this->output->send(array('uid' => $uid), $this->model, $context, array('uid')); } /** * Update specified attachment */ protected function api_attachment_update() { $folder = $this->input->path[0]; $object_uid = $this->input->path[1]; + $attach_uid = $this->input->path[2]; $object = $this->backend->object_get($folder, $object_uid); - $attachment = $this->input->input('attachment'); $context = array( 'folder_uid' => $folder, 'object_uid' => $object_uid, 'object' => $object ); -// @TODO - // merge old object's data with new properties -// $note = $this->merge_data($note, $object); + // get attachment part from the object + $old_attachment = $this->get_attachment($object, $attach_uid); + + // parse input, attach uploaded file, set input properties + $attachment = $this->handle_attachment_input(); -// $this->backend->object_update($folder, $note, 'note'); + // merge attachment properties + $modified = false; + $fields = array('path', 'data', 'size', 'filename', 'mimetype', + 'disposition', 'content_id', 'content_location'); -// $this->output->send(array('id' => $uid), $this->model, $folder); -// $this->output->send_status(kolab_api_output::STATUS_EMPTY); + foreach ($fields as $idx) { + if (isset($attachment->{$idx})) { + $old_attachment->{$idx} = $attachment->{$idx}; + $modified = true; + } + } + + if (!$modified) { + throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); + } + + // update the attachment + $uid = $this->backend->attachment_update($object, $old_attachment); + + // @TODO: should we keep the uploaded file for longer? + if ($attachment->upload_id) { + unset($_SESSION['uploads'][$atttachment->upload_id]); + } + + $this->output->send(array('uid' => $uid), $this->model, $context, array('uid')); } /** * Check if specified attachment exists */ protected function api_attachment_exists() { $folder = $this->input->path[0]; $object_uid = $this->input->path[1]; $attach_uid = $this->input->path[2]; $object = $this->backend->object_get($folder, $object_uid); // get attachment part from the object $attachment = $this->get_attachment($object, $attach_uid); $this->output->send_status(kolab_api_output::STATUS_OK); } /** * Remove specified attachment */ protected function api_attachment_delete() { $folder = $this->input->path[0]; $object_uid = $this->input->path[1]; $attach_uid = $this->input->path[2]; $object = $this->backend->object_get($folder, $object_uid); + $context = array( + 'folder_uid' => $folder, + 'object_uid' => $object_uid, + 'object' => $object + ); - $this->backend->attachment_delete($object, $attach_uid); + $uid = $this->backend->attachment_delete($object, $attach_uid); - $this->output->send_status(kolab_api_output::STATUS_EMPTY); + $this->output->send(array('uid' => $uid), $this->model, $context, array('uid')); } /** * Fetch attachment body */ protected function api_attachment_body() { $folder = $this->input->path[0]; $object_uid = $this->input->path[1]; $attach_uid = $this->input->path[2]; $object = $this->backend->object_get($folder, $object_uid); // get attachment part from the object $attachment = $this->get_attachment($object, $attach_uid); // @TODO: set headers // print attachment body $this->backend->attachment_get($object, $attach_uid, -1); exit; } + /** + * Upload attachment body + */ + protected function api_attachment_upload() + { + // Binary file content in POST body + if (strtolower(rcube_utils::request_header('Content-Type')) == 'application/octet-stream') { + $length = rcube_utils::request_header('Content-Length'); + $temp_dir = unslashify($this->config->get('temp_dir')); + $path = tempnam($temp_dir, 'kolabUpload'); + + // Create stream to copy input into a temp file + $input = fopen('php://input', 'r'); + $file = fopen($path, 'w'); + + if (!$input || !$file) { + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( + 'line' => __LINE__, + 'file' => __FILE__, + 'message' => "Failed opening input or temp file stream", + )); + } + + // Create temp file from the input + $copied = stream_copy_to_stream($input, $file); + + fclose($input); + fclose($file); + + if ($copied < $length) { + // @FIXME: can we distinguish reliably when size error should be displayed? + if ($maxsize = parse_bytes(ini_get('post_max_size'))) { + $error = "Maximum file size exceeded (" . $this->show_bytes($maxsize) . ")"; + throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST, null, $error); + } + + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( + 'line' => __LINE__, + 'file' => __FILE__, + 'message' => "Failed copying file upload into a temp file", + )); + } + + $name = rcube_utils::request_header('X-Filename') ?: $this->input->args['filename']; + + // Use Roundcube attachments functionality to give + // redundant_attachments/database_attachments plugins a chance + $attachment = array( + 'group' => 'kolab_upload', + 'name' => $name, + 'mimetype' => rcube_mime::file_content_type($path, $name), + 'path' => $path, + 'size' => filesize($path), + ); + + $attachment = $this->plugins->exec_hook('attachment_save', $attachment); + + if ($attachment['status']) { + unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']); + $_SESSION['uploads'][$id = $attachment['id']] = $attachment; + } + else { + @unlink($path); + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( + 'line' => __LINE__, + 'file' => __FILE__, + 'message' => "Failed handling file upload", + )); + } + } +/* + else if (($path = $_FILES['file']['tmp_name']) && is_string($path)) { + $err = $_FILES['file']['error']; + + if (!$err) { + $attachment = $this->plugins->exec_hook('attachment_upload', array( + 'path' => $path, + 'size' => $_FILES['file']['size'], + 'name' => $_FILES['file']['name'], + 'mimetype' => rcube_mime::file_content_type($path, $_FILES['file']['name'], $_FILES['file']['type']), + 'group' => 'kolab_upload', + )); + } + + if (!$err && $attachment['status']) { + $id = $attachment['id']; + + // store new attachment in session + unset($attachment['status'], $attachment['abort']); + $_SESSION['uploads'][$id] = $attachment; + } + else { // upload failed + if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) { + $maxsize = parse_bytes(ini_get('upload_max_filesize')); + $error = "Maximum file size exceeded (" . $this->show_bytes($maxsize) . ")"; + + throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST, null, $error); + } + + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( + 'line' => __LINE__, + 'file' => __FILE__, + 'message' => "Failed handling file upload", + )); + } + } + else { + // if filesize exceeds post_max_size then $_FILES array is empty, + // show filesizeerror instead of fileuploaderror + if ($maxsize = parse_bytes(ini_get('post_max_size'))) { + $error = "Maximum file size exceeded (" . $this->show_bytes($maxsize) . ")"; + throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST, null, $error); + } + + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( + 'line' => __LINE__, + 'file' => __FILE__, + 'message' => "Failed handling file upload", + )); + } +*/ + else { + throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); + } + + $this->output->send(array('upload-id' => $id), $this->model); + } + /** * Find attachment in an object/message */ protected function get_attachment($object, $id) { if ($object) { $attachments = (array) $this->get_object_attachments($object); foreach ($attachments as $attachment) { if ($attachment->mime_id == $id) { return $attachment; } } } throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } + + /** + * Create a human readable string for a number of bytes + * + * @param int Number of bytes + * + * @return string Byte string + */ + public static function show_bytes($bytes) + { + if ($bytes >= 1073741824) { + $gb = $bytes/1073741824; + $str = sprintf($gb >= 10 ? "%d " : "%.1f ", $gb) . 'GB'; + } + else if ($bytes >= 1048576) { + $mb = $bytes/1048576; + $str = sprintf($mb >= 10 ? "%d " : "%.1f ", $mb) . 'MB'; + } + else if ($bytes >= 1024) { + $str = sprintf("%d ", round($bytes/1024)) . 'KB'; + } + else { + $str = sprintf('%d ', $bytes) . 'B'; + } + + return $str; + } + + /** + * Handle attachment input data with uploads handling + */ + protected function handle_attachment_input() + { + $attachment = $this->input->input('attachment'); + + // if upload-id is specified check if it exists + $upload_id = $attachment->upload_id ?: 0; + $session = $_SESSION['uploads'][$upload_id]; + + if ($upload_id && empty($session)) { + $error = "Invalid file upload identifier"; + throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST, null, $error); + } + else if ($session) { + // get attachment from attachment storage + $session = $this->plugins->exec_hook('attachment_get', $session); + + $fallback_fields = array( + 'name' => 'filename', + 'mimetype' => 'mimetype', + ); + + foreach ($fallback_fields as $sess_idx => $attach_idx) { + if (!empty($session[$sess_idx])) { + $attachment->{$attach_idx} = $session[$sess_idx]; + } + } + + $fields = array('path', 'data', 'size'); + + foreach ($fields as $idx) { + $attachment->{$idx} = $session[$idx]; + } + } + + return $attachment; + } } diff --git a/lib/filter/mapistore.php b/lib/filter/mapistore.php index 34e2955..dbac3fe 100644 --- a/lib/filter/mapistore.php +++ b/lib/filter/mapistore.php @@ -1,407 +1,410 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ class kolab_api_filter_mapistore extends kolab_api_filter { protected $input; protected $attrs_filter; /** * Modify request path * * @param array (Exploded) request path */ public function path(&$path) { // handle differences between OpenChange API and Kolab API // here we do only very basic modifications, just to be able // to select apprioprate api action class if ($path[0] == 'calendars') { $path[0] = 'events'; } } /** * Executed before every api action * * @param kolab_api_input Request */ public function input(&$input) { $this->input = $input; $this->common_action = !in_array($input->action, array('folders', 'info')); // handle differences between OpenChange API and Kolab API switch ($input->action) { case 'folders': // in OpenChange folders/1/folders means get all folders if ($input->method == 'GET' && $input->path[0] === '1' && $input->path[1] == 'folders') { $input->path = array(); $type = 'folder'; } // in OpenChange folders/0/folders means get the hierarchy of the NON IPM Subtree // we should ignore/send empty request else if ($input->method == 'GET' && $input->path[0] === '0' && $input->path[1] == 'folders') { // @TODO throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } else if ($input->path[1] == 'messages') { $input->path[1] = 'objects'; if ($input->args['properties']) { $type = $input->api->backend->folder_type($input->path[0]); list($type, ) = explode('.', $type); } } else if ($input->path[1] == 'deletemessages') { $input->path[1] = 'deleteobjects'; } // properties filter, map MAPI attribute names to Kolab attributes if ($type && $input->args['properties']) { $this->attrs_filter = explode(',', $this->input->args['properties']); $properties = $this->attributes_filter($this->attrs_filter, $type); $input->args['properties'] = implode(',', $properties); } break; case 'notes': // Notes do not have attachments in Exchange if ($input->path[1] === 'attachments' || count($this->path) > 2) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } break; } // convert / to // or /// if ($this->common_action && ($uid = $input->path[0])) { list($folder, $msg, $attach) = self::uid_decode($uid); $path = array($folder, $msg); if ($attach) { $path[] = $attach; } array_splice($input->path, 0, 1, $path); } // convert parent_id into path on object create request if ($input->method == 'POST' && $this->common_action && !count($input->path)) { $data = $input->input(null, true); if ($data['parent_id']) { $input->path[0] = $data['parent_id']; } else { throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); } } // convert parent_id into path on object update request else if ($input->method == 'PUT' && $folder && count($input->path) == 2) { $data = $input->input(null, true); if ($data['parent_id'] && $data['parent_id'] != $folder) { $this->parent_change_handler($data); } } } /** * Executed when parsing request body * * @param string Request data * @param string Expected object type * @param string Original object data (set on update requests) */ public function input_body(&$data, $type = null, $original_object = null) { $input = $this->input; // handle differences between OpenChange API and Kolab API // Note: input->path is already modified by input() and path() above switch ($input->action) { case 'folders': // folders//deletemessages input if ($input->path[1] == 'deleteobjects') { // Kolab API expects just a list of identifiers, I.e.: // [{"id": "1"}, {"id": "2"}] => ["1", "2"] foreach ((array) $data as $idx => $element) { $data[$idx] = $element['id']; } } break; } switch ($type) { case 'attachment': case 'event': case 'note': case 'task': case 'contact': case 'mail': case 'folder': $model = $this->get_model_class($type); $data = $model->input($data, $original_object); break; } } /** * Apply filter on output data * * @param array Result data * @param string Object type * @param array Context (folder_uid, object_uid, object) * @param array Optional attributes filter */ public function output(&$result, $type, $context = null, $attrs_filter = array()) { // handle differences between OpenChange API and Kolab API $model = $this->get_model_class($type); if (!empty($this->attrs_filter)) { $attrs_filter = array_combine($this->attrs_filter, $this->attrs_filter); } else if (!empty($attrs_filter)) { $attrs_filter = $this->attributes_filter($attrs_filter, $type, true); $attrs_filter = array_combine($attrs_filter, $attrs_filter); } foreach ($result as $idx => $data) { if ($filtered = $model->output($data, $context)) { // apply properties filter (again) if (!empty($attrs_filter)) { $filtered = array_intersect_key($filtered, $attrs_filter); } $result[$idx] = $filtered; } else { unset($result[$idx]); $unset = true; } } if ($unset) { $result = array_values($result); } + + // cleanup + unset($_SESSION['uploads']['MAPIATTACH']); } /** * Executed for response headers * * @param array Response headers */ public function headers(&$headers) { // handle differences between OpenChange API and Kolab API foreach ($headers as $name => $value) { switch ($name) { case 'X-Count': $headers['X-mapistore-rowcount'] = $value; unset($headers[$name]); break; } } } /** * Executed for empty response status * * @param int Status code */ public function send_status(&$status) { // handle differences between OpenChange API and Kolab API if ($this->input->method == 'PUT' && !in_array($input->action, array('info'))) { // Mapistore expects 204 on object updates // however, we'd like to send modified UID of the object sometimes // $status = kolab_api_output::STATUS_EMPTY; } } /** * Converts kolab identifiers describind the object into * MAPI identifier that can be easily used in URL. * * @param string Folder UID * @param string Object UID * @param string Optional attachment identifier * * @return string Object identifier */ public static function uid_encode($folder_uid, $msg_uid, $attach_id = null) { $result = array($folder_uid, $msg_uid); if ($attach_id) { $result[] = $attach_id; } $result = array_map(array('kolab_api_filter_mapistore', 'uid_encode_item'), $result); return implode('.', $result); } /** * Converts back the MAPI identifier into kolab folder/object/attachment IDs * * @param string Object identifier * * @return array Object identifiers */ public static function uid_decode($uid) { $result = explode('.', $uid); $result = array_map(array('kolab_api_filter_mapistore', 'uid_decode_item'), $result); return $result; } /** * Encodes UID element */ protected static function uid_encode_item($str) { $fn = function($match) { return '_' . ord($match[1]); }; $str = preg_replace_callback('/([^0-9a-zA-Z-])/', $fn, $str); return $str; } /** * Decodes UID element */ protected static function uid_decode_item($str) { $fn = function($match) { return chr($match[1]); }; $str = preg_replace_callback('/_([0-9]{2})/', $fn, $str); return $str; } /** * Filter property names */ protected function attributes_filter($attrs, $type = null, $reverse = false) { $model = $this->get_model_class($type); return $model->attributes_filter($attrs, $reverse); } /** * Return instance of model class object */ protected function get_model_class($type) { $class = "kolab_api_filter_mapistore_$type"; return new $class($this); } /** * Convert DateTime object to MAPI date format */ public function date_php2mapi($date, $utc = true, $time = null) { // convert string to DateTime if (!is_object($date) && !empty($date)) { // convert date to datetime on 00:00:00 if (preg_match('/^([0-9]{4})-?([0-9]{2})-?([0-9]{2})$/', $date, $m)) { $date = $m[1] . '-' . $m[2] . '-' . $m[3] . 'T00:00:00+00:00'; } $date = new DateTime($date); } if (!is_object($date)) { return; } if ($utc) { $date->setTimezone(new DateTimeZone('UTC')); } if (!empty($time)) { $date->setTime((int) $time['hour'], (int) $time['minute'], (int) $time['second']); } // MAPI PTypTime is 64-bit integer representing the number // of 100-nanosecond intervals since January 1, 1601. // Mapistore format for this type is a float number // seconds since 1601-01-01 00:00:00 $seconds = floatval($date->format('U')) + 11644473600; /* if ($microseconds = intval($date->format('u'))) { $seconds += $microseconds/1000000; } */ return $seconds; } /** * Convert date-time from MAPI format to DateTime */ public function date_mapi2php($date) { $seconds = floatval(sprintf('%.0f', $date)); // assumes we're working with dates after 1970-01-01 $dt = new DateTime('@' . intval($seconds - 11644473600)); /* if ($microseconds = intval(($date - $seconds) * 1000000)) { $dt = new DateTime($dt->format('Y-m-d H:i:s') . '.' . $microseconds, $dt->getTimezone()); } */ return $dt; } /** * Handles object parent modification (move) */ protected function parent_change_handler($data) { $folder = $this->input->path[0]; $uid = $this->input->path[1]; $target = $data['parent_id']; $api = kolab_api::get_instance(); // move the object $api->backend->objects_move($folder, $target, array($uid)); // replace folder uid in input arguments $this->input->path[0] = $target; // exit if the rest of input is empty if (count($data) < 2) { $api->output->send_status(kolab_api_output::STATUS_EMPTY); } } } diff --git a/lib/filter/mapistore/attachment.php b/lib/filter/mapistore/attachment.php index da4c1dc..4981f6e 100644 --- a/lib/filter/mapistore/attachment.php +++ b/lib/filter/mapistore/attachment.php @@ -1,185 +1,197 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ class kolab_api_filter_mapistore_attachment extends kolab_api_filter_mapistore_common { protected $map = array( // general props (read-only) 'PidTagAccessLevel' => '', // 0 - read-only, 1 - modify 'PidTagObjectType' => '', 'PidTagRecordKey' => '', // PtypBinary // other props 'PidTagLastModificationTime' => '', 'PidTagCreationTime' => '', 'PidTagDisplayName' => 'filename', 'PidTagAttachSize' => 'size', 'PidTagAttachNumber' => '', // @TODO: unique attachment index within a message 'PidTagAttachDataBinary' => '', // PtypBinary 'PidTagAttachDataObject' => '', // PtypBinary 'PidTagAttachMethod' => '', 'PidTagAttachLongFilename' => 'filename', // filename with extension 'PidTagAttachFilename' => '', // filename in 8.3 form 'PidTagAttachExtension' => '', 'PidTagAttachLongPathname' => '', 'PidTagAttachPathname' => '', 'PidTagAttachTag' => '', // PtypBinary 'PidTagRenderingPosition' => '', 'PidTagAttachRendering' => '', // PtypBinary 'PidTagAttachFlags' => '', 'PidTagAttachTransportName' => '', 'PidTagAttachEncoding' => '', // PtypBinary 'PidTagAttachAdditionalInformation' => '', // PtypBinary 'PidTagAttachmentLinkId' => '', 'PidTagAttachmentFlags' => '', 'PidTagAttachmentHidden' => '', // PtypBoolean 'PidTagTextAttachmentChars' => 'charset', // MIME props 'PidTagAttachMimeTag' => 'mimetype', 'PidTagAttachContentId' => 'content-id', 'PidTagAttachContentLocation' => 'content-location', 'PidTagAttachContentBase' => '', 'PidTagAttachPayloadClass' => '', 'PidTagAttachPayloadProviderGuidString' => '', 'PidNameAttachmentMacContentType' => '', 'PidNameAttachmentMacInfo' => '', // PtypBinary ); /** * Methods for PidTagAttachMethod */ protected $methods = array( 'afNone' => 0x00000001, 'afByValue' => 0x00000001, 'afByReference' => 0x00000002, 'afByReferenceOnly' => 0x00000004, 'afEmbeddedMessage' => 0x00000005, 'afStorage' => 0x00000006, ); /** * Convert Kolab to MAPI * * @param array Data * @param array Context (folder_uid, object_uid, object) * * @return array Data */ public function output($data, $context = null) { $result = array( 'PidTagObjectType' => 0x00000007, // mapistore REST API specific properties 'collection' => 'attachments', ); // @TODO: Set PidTagAccessLevel depending if a message is in Drafts or not // or the attachment belongs to a kolab object in writeable folder? foreach ($this->map as $mapi_idx => $kolab_idx) { if (empty($kolab_idx)) { continue; } $value = $this->get_kolab_value($data, $kolab_idx); if ($value === null) { continue; } $result[$mapi_idx] = $value; } if (($pos = strrpos($data['filename'], '.')) !== false) { $result['PidTagAttachExtension'] = substr($data['filename'], $pos + 1); } // Store attachment body in base64 // @TODO: shouldn't we do this only in attachment.info request? $result['PidTagAttachDataBinary'] = $this->attachment_body($context['object'], $data, true); $result['PidTagAttachMethod'] = $this->methods['afByValue']; $this->parse_common_props($result, $data, $context); $result['id'] = kolab_api_filter_mapistore::uid_encode($context['folder_uid'], $context['object_uid'], $data['id']); return $result; } /** * Convert from MAPI to Kolab * * @param array Data * @param array Data of the object that is being updated * * @return array Data */ public function input($data, $object = null) { $result = array(); foreach ($this->map as $mapi_idx => $kolab_idx) { if (empty($kolab_idx)) { continue; } if (!array_key_exists($mapi_idx, $data)) { continue; } $value = $data[$mapi_idx]; $result[$kolab_idx] = $value; } + if ($data['PidTagAttachDataBinary']) { + $stream = base64_decode($data['PidTagAttachDataBinary']); + $result['upload-id'] = $sess_key = 'MAPIATTACH'; + $_SESSION['uploads'][$sess_key] = array( + 'group' => 'kolab_upload', + 'name' => $data['PidTagDisplayName'], + 'mimetype' => rcube_mime::file_content_type($stream, $data['PidTagDisplayName'], 'application/octet-stream', true), + 'data' => $stream, + 'size' => strlen($stream), + ); + } + return $result; } /** * Returns the attributes names mapping */ public function map() { $map = array_filter($this->map); $map['PidTagAttachExtension'] = 'filename'; return $map; } /** * Get attachment body */ protected function attachment_body($object, $attachment, $encoded = false) { if (empty($object)) { return; } $api = kolab_api::get_instance(); $body = $api->backend->attachment_get($object, $attachment['id']); return $encoded ? base64_encode($body) : $body; } } diff --git a/lib/input/json/attachment.php b/lib/input/json/attachment.php index 90cbdb0..b9ad213 100644 --- a/lib/input/json/attachment.php +++ b/lib/input/json/attachment.php @@ -1,72 +1,92 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ class kolab_api_input_json_attachment { - // map xml/json attributes into internal format - protected $field_map = array( - ); - /** * Convert attachment input array into an array that can * be handled by the API * - * @param array Request body - * @param array Original object data (on update) + * @param array Request body + * @param rcube_message_part Original object data (on update) */ public function input(&$data, $original = null) { if (empty($data) || !is_array($data)) { throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); } - foreach ($this->field_map as $kolab => $api) { - if (!array_key_exists($api, $data)) { + $result = new rcube_message_part; + $empty = true; + + // supported attachment data fields + $fields = array( +// 'id', + 'mimetype', +// 'size', + 'filename', + 'disposition', + 'content-id', + 'content-location', + 'upload-id', + ); + + // first unset rcube_message_part defaults + $result->mimetype = null; + $result->encoding = null; + + foreach ($fields as $field) { + if (!array_key_exists($field, $data)) { continue; } - $value = $data[$api]; + $value = $data[$field]; + $empty = false; - switch ($kolab) { - case 'sensitivity': -// $value = strtolower($value); + switch ($field) { + case 'content-id': + case 'content-location': + case 'upload-id': + $field = str_replace('-', '_', $field); break; } - $result[$kolab] = $value; - } + // add the value to the result + if ($value !== null && $value !== '' && (!is_array($value) || !empty($value))) { + // make sure we have utf-8 here + $value = rcube_charset::clean($value); + } - if (empty($result)) { - throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); + $result->{$field} = $value; } - if (!empty($original)) { - $result = array_merge($original, $result); + if ($empty) { + throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); } $data = $result; } } diff --git a/lib/kolab_api.php b/lib/kolab_api.php index 917eb57..db1e6aa 100644 --- a/lib/kolab_api.php +++ b/lib/kolab_api.php @@ -1,468 +1,469 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ class kolab_api extends rcube { const APP_NAME = 'Kolab REST API'; const VERSION = '0.1'; public $backend; public $filter; public $input; public $output; protected $model; /** * This implements the 'singleton' design pattern * * @return kolab_api The one and only instance */ public static function get_instance() { if (!self::$instance || !is_a(self::$instance, 'kolab_api')) { $path = kolab_api_input::request_path(); $request = array_shift($path); $class = 'kolab_api_' . $request; if (!$request || !class_exists($class)) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND, array( 'line' => __LINE__, 'file' => __FILE__, 'message' => "Invalid request method: $request" )); } self::$instance = new $class(); self::$instance->startup(); } return self::$instance; } /** * Initial startup function * to register session, create database and imap connections */ protected function startup() { $this->init(self::INIT_WITH_DB | self::INIT_WITH_PLUGINS); // Get list of plugins // WARNING: We can use only plugins that are prepared for this // e.g. are not using output or rcmail objects or // doesn't throw errors when using them $plugins = (array) $this->config->get('kolab_api_plugins', array('kolab_auth')); $plugins = array_unique(array_merge($plugins, array('libkolab'))); // this way we're compatible with Roundcube Framework 1.2 // we can't use load_plugins() here foreach ($plugins as $plugin) { $this->plugins->load_plugin($plugin, true); } } /** * Exception handler * * @param kolab_api_exception Exception */ public static function exception_handler($exception) { $code = $exception->getCode(); $message = $exception->getMessage(); if ($code == 401) { header('WWW-Authenticate: Basic realm="' . self::APP_NAME .'"'); } if (!$exception instanceof kolab_api_exception) { rcube::raise_error($exception, true, false); } header("HTTP/1.1 $code $message"); exit; } /** * Program execution handler */ protected function initialize_handler() { // Handle request input $this->input = kolab_api_input::factory($this); // Get input/output filter $this->filter = $this->input->filter; // Start session, validate it and authenticate the user if needed if (!$this->session_validate()) { $this->authenticate(); $authenticated = true; } // Initialize backend $this->backend = kolab_api_backend::get_instance(); // Filter the input, we want this after authentication if ($this->filter) { $this->filter->input($this->input); } // set response output class $this->output = kolab_api_output::factory($this); if ($authenticated) { $this->output->headers(array('X-Session-Token' => session_id())); } } /** * Script shutdown handler */ public function shutdown() { parent::shutdown(); // write performance stats to logs/console if ($this->config->get('devel_mode')) { if (function_exists('memory_get_peak_usage')) $mem = memory_get_peak_usage(); else if (function_exists('memory_get_usage')) $mem = memory_get_usage(); - $log = trim(kolab_api_input::request_uri() . ($mem ? sprintf(' [%.1f MB]', $mem/1024/1024) : '')); if (defined('KOLAB_API_START')) { rcube::print_timer(KOLAB_API_START, $log); } else { rcube::console($log); } } } /** * Validate the submitted session token */ protected function session_validate() { $sess_id = $this->input->request_header('X-Session-Token'); if (empty($sess_id)) { session_start(); return false; } session_id($sess_id); session_start(); // Session timeout $timeout = $this->config->get('kolab_api_session_timeout'); if ($timeout && $_SESSION['time'] && $_SESSION['time'] < time() - $timeout) { $_SESSION = array(); return false; } // update session time $_SESSION['time'] = time(); return true; } /** * Authentication request handler (HTTP Auth) */ protected function authenticate() { if (!empty($_SERVER['PHP_AUTH_USER'])) { $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; } // when used with (f)cgi no PHP_AUTH* variables are available without defining a special rewrite rule else if (!isset($_SERVER['PHP_AUTH_USER'])) { // "Basic didhfiefdhfu4fjfjdsa34drsdfterrde..." if (isset($_SERVER['REMOTE_USER'])) { $basicAuthData = base64_decode(substr($_SERVER['REMOTE_USER'], 6)); } else if (isset($_SERVER['REDIRECT_REMOTE_USER'])) { $basicAuthData = base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)); } else if (isset($_SERVER['Authorization'])) { $basicAuthData = base64_decode(substr($_SERVER['Authorization'], 6)); } else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { $basicAuthData = base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)); } if (isset($basicAuthData) && !empty($basicAuthData)) { list($username, $password) = explode(':', $basicAuthData); } } if (!empty($username)) { $backend = kolab_api_backend::get_instance(); $result = $backend->authenticate($username, $password); } if (empty($result)) { throw new kolab_api_exception(kolab_api_exception::UNAUTHORIZED); } $_SESSION['time'] = time(); } /** * Handle API request */ public function run() { $this->initialize_handler(); $path = $this->input->path; $method = $this->input->method; if (!$path[1] && $path[0] && $method == 'POST') { $this->api_object_create(); } else if ($path[1]) { switch (strtolower($path[2])) { case 'attachments': if ($method == 'HEAD') { $this->api_object_count_attachments(); } else if ($method == 'GET') { $this->api_object_list_attachments(); } break; case '': if ($method == 'GET') { $this->api_object_info(); } else if ($method == 'PUT') { $this->api_object_update(); } else if ($method == 'HEAD') { $this->api_object_exists(); } else if ($method == 'DELETE') { $this->api_object_delete(); } } } throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } /** * Fetch object info */ protected function api_object_info() { $folder = $this->input->path[0]; $uid = $this->input->path[1]; $object = $this->backend->object_get($folder, $uid); $context = array('folder_uid' => $folder, 'object' => $object); $this->output->send($object, $this->model, $context); } /** * Create an object */ protected function api_object_create() { $folder = $this->input->path[0]; $input = $this->input->input($this->model); $context = array('folder_uid' => $folder); $uid = $this->backend->object_create($folder, $input, $this->model); $this->output->send(array('uid' => $uid), $this->model, $context, array('uid')); } /** * Update specified object */ protected function api_object_update() { $folder = $this->input->path[0]; $uid = $this->input->path[1]; $object = $this->backend->object_get($folder, $uid); $context = array( 'folder_uid' => $folder, 'object_uid' => $uid, 'object' => $object, ); // parse input and merge with current data (result is in kolab_format/kolab_api_mail) $input = $this->input->input($this->model, false, $object); // update object on the backend $uid = $this->backend->object_update($folder, $input, $this->model); $this->output->send(array('uid' => $uid), $this->model, $context); } /** * Check if specified object exists */ protected function api_object_exists() { $folder = $this->input->path[0]; $uid = $this->input->path[1]; $object = $this->backend->object_get($folder, $uid); $this->output->send_status(kolab_api_output::STATUS_OK); } /** * Remove specified object */ protected function api_object_delete() { $folder = $this->input->path[0]; $uid = $this->input->path[1]; $object = $this->backend->object_get($folder, $uid); $this->backend->objects_delete($folder, array($uid)); $this->output->send_status(kolab_api_output::STATUS_EMPTY); } /** * Count object attachments */ protected function api_object_count_attachments() { $folder = $this->input->path[0]; $uid = $this->input->path[1]; $object = $this->backend->object_get($folder, $uid); $context = array( 'folder_uid' => $folder, 'object_uid' => $uid, 'object' => $object, ); $count = !empty($object['_attachments']) ? count($object['_attachments']) : 0; $this->output->headers(array('X-Count' => $count)); $this->output->send_status(kolab_api_output::STATUS_OK); } /** * List object attachments */ protected function api_object_list_attachments() { $folder = $this->input->path[0]; $uid = $this->input->path[1]; $object = $this->backend->object_get($folder, $uid); $props = $this->input->args['properties'] ? explode(',', $this->input->args['properties']) : null; $context = array( 'folder_uid' => $folder, 'object_uid' => $uid, 'object' => $object, ); // @TODO: currently Kolab format (libkolabxml) allows attachments // in events, tasks and notes. We should support them also in contacts $list = $this->get_object_attachments($object); $this->output->send($list, 'attachment-list', $context, $props); } /** * Extract attachments from the object, depending if it's * Kolab object or email message */ protected function get_object_attachments($object) { // this is a kolab_format object data if (is_array($object)) { $list = (array) $object['_attachments']; + foreach ($list as $idx => $att) { $attachment = new rcube_message_part; $attachment->mime_id = $att['id']; $attachment->filename = $att['name']; $attachment->mimetype = $att['mimetype']; $attachment->size = $att['size']; $attachment->disposition = 'attachment'; + $attachment->encoding = $att['encoding']; $list[$idx] = $attachment; } } // this is rcube_message(_header) else { $list = (array) $object->attachments; } return $list; } /** * Convert kolab_format object into API format * * @param array Object data in kolab_format * @param string Object type * * @return array Object data in API format */ public function get_object_data($object, $type) { $output = $this->output; if (!$this->output instanceof kolab_api_output_json) { $class = "kolab_api_output_json"; $output = new $class($this); } return $output->convert($object, $type); } /** * Returns RFC2822 formatted current date in user's timezone * * @return string Date */ public function user_date() { // get user's timezone try { $tz = new DateTimeZone($this->config->get('timezone')); $date = new DateTime('now', $tz); } catch (Exception $e) { $date = new DateTime(); } return $date->format('r'); } } diff --git a/lib/kolab_api_backend.php b/lib/kolab_api_backend.php index 459350a..8c18766 100644 --- a/lib/kolab_api_backend.php +++ b/lib/kolab_api_backend.php @@ -1,1249 +1,1344 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ class kolab_api_backend { /** * Singleton instace of kolab_api_backend * * @var kolab_api_backend */ static protected $instance; public $api; public $storage; public $username; public $password; public $user; public $delimiter; protected $icache = array(); /** * This implements the 'singleton' design pattern * * @return kolab_api_backend The one and only instance */ static function get_instance() { if (!self::$instance) { self::$instance = new kolab_api_backend; self::$instance->startup(); // init AFTER object was linked with self::$instance } return self::$instance; } /** * Class initialization */ public function startup() { $this->api = kolab_api::get_instance(); $this->storage = $this->api->get_storage(); // @TODO: reset cache? if we do this for every request the cache would be useless // There's no session here //$this->storage->clear_cache('mailboxes.', true); // set additional header used by libkolab $this->storage->set_options(array( // @TODO: there can be Roundcube plugins defining additional headers, // we maybe would need to add them here 'fetch_headers' => 'X-KOLAB-TYPE X-KOLAB-MIME-VERSION', 'skip_deleted' => true, 'threading' => false, )); // Disable paging $this->storage->set_pagesize(999999); $this->delimiter = $this->storage->get_hierarchy_delimiter(); if ($_SESSION['user_id']) { $this->user = new rcube_user($_SESSION['user_id']); $this->api->config->set_user_prefs((array)$this->user->get_prefs()); } } /** * Authenticate a user * * @param string Username * @param string Password * * @return bool */ public function authenticate($username, $password) { $host = $this->select_host($username); // use shared cache for kolab_auth plugin result (username canonification) $cache = $this->api->get_cache_shared('kolab_api_auth'); $cache_key = sha1($username . '::' . $host); if (!$cache || !($auth = $cache->get($cache_key))) { $auth = $this->api->plugins->exec_hook('authenticate', array( 'host' => $host, 'user' => $username, 'pass' => $password, )); if ($cache && !$auth['abort']) { $cache->set($cache_key, array( 'user' => $auth['user'], 'host' => $auth['host'], )); } // LDAP server failure... send 503 error if ($auth['kolab_ldap_error']) { throw new kolab_api_exception(kolab_api_exception::UNAVAILABLE); } } else { $auth['pass'] = $password; } // authenticate user against the IMAP server $user_id = $auth['abort'] ? 0 : $this->login($auth['user'], $auth['pass'], $auth['host'], $error); if ($user_id) { $this->username = $auth['user']; $this->password = $auth['pass']; $this->delimiter = $this->storage->get_hierarchy_delimiter(); return true; } // IMAP server failure... send 503 error if ($error == rcube_imap_generic::ERROR_BAD) { throw new kolab_api_exception(kolab_api_exception::UNAVAILABLE); } return false; } /** * Get list of folders * * @param string $type Folder type * * @return array|bool List of folders, False on backend failure */ public function folders_list($type = null) { $type_keys = array( kolab_storage::CTYPE_KEY_PRIVATE, kolab_storage::CTYPE_KEY, ); // get folder unique identifiers and types $uid_data = $this->folder_uids(); $type_data = $this->storage->get_metadata('*', $type_keys); $folders = array(); if (!is_array($type_data)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } foreach ($uid_data as $folder => $uid) { $path = strpos($folder, '&') === false ? $folder : rcube_charset::convert($folder, 'UTF7-IMAP'); if (strpos($path, $this->delimiter)) { $list = explode($this->delimiter, $path); $name = array_pop($list); $parent = implode($this->delimiter, $list); $parent_id = null; if ($folders[$parent]) { $parent_id = $folders[$parent]['uid']; } // parent folder does not exist add it to the list else { for ($i=0; $idelimiter, $parent_arr); if ($folders[$parent]) { $parent_id = $folders[$parent]['uid']; } else { $fid = $this->folder_name2uid(rcube_charset::convert($parent, RCUBE_CHARSET, 'UTF7-IMAP')); $folders[$parent] = array( 'name' => array_pop($parent_arr), 'fullpath' => $parent, 'uid' => $fid, 'parent' => $parent_id, ); $parent_id = $fid; } } } } else { $parent_id = null; $name = $path; } $data = array( 'name' => $name, 'fullpath' => $path, 'parent' => $parent_id, 'uid' => $uid, ); // folder type reset($type_keys); foreach ($type_keys as $key) { $data['type'] = $type_data[$folder][$key]; break; } if (empty($data['type'])) { $data['type'] = 'mail'; } $folders[$path] = $data; } // sort folders uksort($folders, array($this, 'sort_folder_comparator')); return $folders; } /** * Returns folder type * * @param string $uid Folder unique identifier * @param string $with_suffix Enable to not remove the subtype * * @return string Folder type */ public function folder_type($uid, $with_suffix = false) { $folder = $this->folder_uid2name($uid); $type = kolab_storage::folder_type($folder); if ($type === null) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } if (!$with_suffix) { list($type, ) = explode('.', $type); } return $type; } /** * Returns objects in a folder * * @param string $uid Folder unique identifier * * @return array Objects (of type rcube_message_header or kolab_format) * @throws kolab_api_exception */ public function objects_list($uid) { $type = $this->folder_type($uid); // use IMAP to fetch mail messages if ($type === 'mail') { $folder = $this->folder_uid2name($uid); $result = $this->storage->list_messages($folder, 1); foreach ($result as $idx => $mail) { $result[$idx] = new kolab_api_mail($mail); } } // otherwise use kolab_storage else { $folder = $this->folder_get_by_uid($uid, $type); $result = $folder->get_objects(); if ($result === null) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } } return $result; } /** * Counts objects in a folder * * @param string $uid Folder unique identifier * * @return int Objects count * @throws kolab_api_exception */ public function objects_count($uid) { $type = $this->folder_type($uid); // use IMAP to count mail messages if ($type === 'mail') { $folder = $this->folder_uid2name($uid); // @TODO: error checking requires changes in rcube_imap $result = $this->storage->count($folder, 'ALL'); } // otherwise use kolab_storage else { $folder = $this->folder_get_by_uid($uid, $type); $result = $folder->count(); } return $result; } /** * Delete objects in a folder * * @param string $uid Folder unique identifier * @param string|array $set List of object IDs or "*" for all * * @throws kolab_api_exception */ public function objects_delete($uid, $set) { $type = $this->folder_type($uid); if ($type === 'mail') { $is_mail = true; $folder = $this->folder_uid2name($uid); } // otherwise use kolab_storage else { $folder = $this->folder_get_by_uid($uid, $type); } // delete all if ($set === "*") { if ($is_mail) { $result = $this->storage->clear_folder($folder); } else { $result = $folder->delete_all(); } } else { if ($is_mail) { $result = $this->storage->delete_message($set, $folder); } else { foreach ($set as $uid) { $result = $folder->delete($uid); if ($result === false) { break; } } } } if ($result === false) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } } /** * Move objects into another folder * * @param string $uid Folder unique identifier * @param string $target_uid Target folder unique identifier * @param string|array $set List of object IDs or "*" for all * * @throws kolab_api_exception */ public function objects_move($uid, $target_uid, $set) { $type = $this->folder_type($uid); $target_type = $this->folder_type($target_uid); if ($type === 'mail') { $is_mail = true; $folder = $this->folder_uid2name($uid); $target = $this->folder_uid2name($uid); } // otherwise use kolab_storage else { $folder = $this->folder_get_by_uid($uid, $type); $target = $this->folder_get_by_uid($uid, $type); } if ($is_mail) { if ($set === "*") { $set = '1:*'; } $result = $this->storage->move_messages($set, $target, $folder); } else { if ($set === "*") { $set = $folder->get_uids(); } foreach ($set as $uid) { $result = $folder->move($uid, $target); if ($result === false) { break; } } } if ($result === false) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } } /** * Get object data * * @param string $folder_uid Folder unique identifier * @param string $uid Object identifier * * @return kolab_api_mail|array Object data * @throws kolab_api_exception */ public function object_get($folder_uid, $uid) { $type = $this->folder_type($folder_uid); if ($type === 'mail') { $folder = $this->folder_uid2name($folder_uid); $object = new rcube_message($uid, $folder); if (!$object || empty($object->headers)) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } $object = new kolab_api_mail($object); } // otherwise use kolab_storage else { $folder = $this->folder_get_by_uid($folder_uid, $type); if (!$folder || !$folder->valid) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } $object = $folder->get_object($uid); if (!$object) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } $old_categories = $object['categories']; } // @TODO: Use relations also for events if ($type != 'configuration' && $type != 'event') { // get object categories (tag-relations) $categories = $this->get_tags($object, $old_categories); if ($type === 'mail') { $object->categories = $categories; } else { $object['categories'] = $categories; } } return $object; } /** * Create an object * * @param string $folder_uid Folder unique identifier * @param mixed $data Object data (an array or kolab_api_mail) * @param string $type Object type * * @return string Object UID * @throws kolab_api_exception */ public function object_create($folder_uid, $data, $type) { $ftype = $this->folder_type($folder_uid); if ($type === 'mail') { if ($ftype !== 'mail') { throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); } $folder = $this->folder_uid2name($folder_uid); // @TODO: categories return $data->save($folder); } // otherwise use kolab_storage else { // @TODO: Use relations also for events if (!preg_match('/^(event|configuration)/', $type)) { // get object categories (tag-relations) $categories = (array) $data['categories']; $data['categories'] = array(); } $folder = $this->folder_get_by_uid($folder_uid, $type); if (!$folder || !$folder->valid) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } if (!$folder->save($data)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } // @TODO: Use relations also for events if (!empty($categories)) { // create/assign categories (tag-relations) $this->set_tags($data['uid'], $categories); } return $data['uid']; } } /** * Update an object * * @param string $folder_uid Folder unique identifier * @param mixed $data Object data (array or kolab_api_mail) * @param string $type Object type * * @return string Object UID (it can change) * @throws kolab_api_exception */ public function object_update($folder_uid, $data, $type) { $ftype = $this->folder_type($folder_uid); if ($type === 'mail') { if ($ftype != 'mail') { throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); } $folder = $this->folder_uid2name($folder_uid); return $data->save($folder); } // otherwise use kolab_storage else { // @TODO: Use relations also for events if (!preg_match('/^(event|configuration)/', $type)) { // get object categories (tag-relations) $categories = (array) $data['categories']; $data['categories'] = array(); } $folder = $this->folder_get_by_uid($folder_uid, $type); if (!$folder || !$folder->valid) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } if (!$folder->save($data)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } // @TODO: Use relations also for events if (array_key_exists('categories', $data)) { // create/assign categories (tag-relations) $this->set_tags($data['uid'], $categories); } return $data['uid']; } } /** * Get attachment body * * @param mixed $object Object data (from self::object_get()) * @param string $part_id Attachment part identifier * @param mixed $mode NULL to return a string, -1 to print body * or file pointer to save the body into * * @return string Attachment body if $fp=null * @throws kolab_api_exception */ public function attachment_get($object, $part_id, $mode = null) { // object is a mail message if ($object instanceof rcube_message) { return $object->get_part_body($part_id, false, 0, $mode); } // otherwise use kolab_storage else { return $this->storage->get_message_part($this->uid, $part_id, null, $mode === -1, is_resource($mode) ? $mode : null, true, 0, false); } } /** * Delete an attachment from the message * * @param mixed $object Object data (from self::object_get()) * @param string $id Attachment identifier * - * @return boolean|string True or message UID (if changed) + * @return string Message/Object UID * @throws kolab_api_exception */ public function attachment_delete($object, $id) { // object is a mail message - if ($object instanceof rcube_message) { - // @TODO + if (is_object($object)) { + $mail = new kolab_api_mail($message); + return $mail->attachment_delete($id); } // otherwise use kolab_storage else { $folder = kolab_storage::get_folder($object['_mailbox']); if (!$folder || !$folder->valid) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } $found = false; // unset the attachment foreach ((array) $object['_attachments'] as $idx => $att) { if ($att['id'] == $id) { $object['_attachments'][$idx] = false; $found = true; } } if (!$found) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } if (!$folder->save($data)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } - return true; + return $object['uid']; + } + } + + /** + * Create an attachment and add to a message/object + * + * @param mixed $object Object data (from self::object_get()) + * @param rcube_message_part $attach Attachment data + * + * @return string Message/Object UID + * @throws kolab_api_exception + */ + public function attachment_create($object, $attach) + { + // object is a mail message + if (is_object($object)) { + $mail = new kolab_api_mail($message); + return $mail->attachment_create($attach); + } + // otherwise use kolab_storage + else { + $folder = kolab_storage::get_folder($object['_mailbox']); + + if (!$folder || !$folder->valid) { + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); + } + + $object['_attachments'][] = array( + 'name' => $attachment->filename, + 'mimetype' => $attachment->mimetype, + 'path' => $attachment->path, + 'size' => $attachment->size, + 'content' => $attachment->data, + ); + + if (!$folder->save($object)) { + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); + } + + return $object['uid']; + } + } + + /** + * Update an attachment in a message/object + * + * @param mixed $object Object data (from self::object_get()) + * @param rcube_message_part $attach Attachment data + * + * @return string Message/Object UID + * @throws kolab_api_exception + */ + public function attachment_update($object, $attach) + { + // object is a mail message + if (is_object($object)) { + $mail = new kolab_api_mail($message); + return $mail->attachment_update($attach); + } + // otherwise use kolab_storage + else { + $folder = kolab_storage::get_folder($object['_mailbox']); + + if (!$folder || !$folder->valid) { + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); + } + + $found = false; + + // unset the attachment + foreach ((array) $object['_attachments'] as $idx => $att) { + if ($att['id'] == $attach->mime_id) { + $object['_attachments'][$idx] = false; + $found = true; + } + } + + if (!$found) { + throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); + } + + $object['_attachments'][] = array( + 'name' => $attachment->filename, + 'mimetype' => $attachment->mimetype, + 'path' => $attachment->path, + 'size' => $attachment->size, + 'content' => $attachment->data, + ); + + if (!$folder->save($object)) { + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); + } + + return $object['uid']; } } /** * Creates a folder * * @param string $name Folder name (UTF-8) * @param string $parent Parent folder identifier * @param string $type Folder type * * @return bool Folder identifier on success */ public function folder_create($name, $parent = null, $type = null) { $name = rcube_charset::convert($name, RCUBE_CHARSET, 'UTF7-IMAP'); if ($parent) { $parent = $this->folder_uid2name($parent); $name = $parent . $this->delimiter . $name; } if ($this->storage->folder_exists($name)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } $created = kolab_storage::folder_create($name, $type, false, false); if ($created) { $created = $this->folder_name2uid($name); } return $created; } /** * Subscribes a folder * * @param string $uid Folder identifier * @param array $updates Updates (array with keys type, subscribed, active) * * @throws kolab_api_exception */ public function folder_update($uid, $updates) { $folder = $this->folder_uid2name($uid); if (isset($updates['type'])) { $result = kolab_storage::set_folder_type($folder, $updates['type']); if (!$result) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } } if (isset($updates['subscribed'])) { if ($updates['subscribed']) { $result = $this->storage->subscribe($folder); } else { $result = $this->storage->unsubscribe($folder); } if (!$result) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } } // @TODO: active state } /** * Renames a folder * * @param string $old_name Folder name (UTF-8) * @param string $new_name New folder name (UTF-8) * * @throws kolab_api_exception */ public function folder_rename($old_name, $new_name) { $old_name = rcube_charset::convert($old_name, RCUBE_CHARSET, 'UTF7-IMAP'); $new_name = rcube_charset::convert($new_name, RCUBE_CHARSET, 'UTF7-IMAP'); if (!strlen($old_name) || !strlen($new_name) || $old_name === $new_name) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } if ($this->storage->folder_exists($new_name)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } // don't use kolab_storage for moving mail folders if (preg_match('/^mail/', $type)) { $result = $this->storage->rename_folder($old_name, $new_name); } else { $result = kolab_storage::folder_rename($old_name, $new_name); } if (!$result) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } } /** * Deletes folder * * @param string $uid Folder UID * * @return bool True on success, False on failure * @throws kolab_api_exception */ public function folder_delete($uid) { $folder = $this->folder_uid2name($uid); $type = $this->folder_type($uid); // don't use kolab_storage for mail folders if ($type === 'mail') { $status = $this->storage->delete_folder($folder); } else { $status = kolab_storage::folder_delete($folder); } if (!$status) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } } /** * Folder info * * @param string $uid Folder UID * * @return array Folder information * @throws kolab_api_exception */ public function folder_info($uid) { $folder = $this->folder_uid2name($uid); // get IMAP folder info $info = $this->storage->folder_info($folder); // get IMAP folder data $data = $this->storage->folder_data($folder); $info['exists'] = $data['EXISTS']; $info['unseen'] = $data['UNSEEN']; $info['modseq'] = $data['HIGHESTMODSEQ']; // add some more parameters (used in folders list response) $path = strpos($folder, '&') === false ? $folder : rcube_charset::convert($folder, 'UTF7-IMAP'); $path = explode($this->delimiter, $path); $info['name'] = array_pop($path); $info['fullpath'] = implode($this->delimiter, $path); $info['uid'] = $uid; $info['type'] = kolab_storage::folder_type($folder, true) ?: 'mail'; if ($info['fullpath'] !== '') { $parent = $this->folder_name2uid(rcube_charset::convert($info['fullpath'], RCUBE_CHARSET, 'UTF7-IMAP')); $info['parent'] = $parent; } // convert some info to be more compact if (!empty($info['rights'])) { $info['rights'] = implode('', $info['rights']); } // @TODO: subscription status, active state // some info is not very interesting here ;) unset($info['attributes']); return $info; } /** * Returns IMAP folder name with full path * * @param string $uid Folder identifier * * @return string Folder full path (UTF-8) */ public function folder_uid2path($uid) { $folder = $this->folder_uid2name($uid); return strpos($folder, '&') === false ? $folder : rcube_charset::convert($folder, 'UTF7-IMAP'); } /** * Returns IMAP folder name * * @param string $uid Folder identifier * * @return string Folder name (UTF7-IMAP) */ protected function folder_uid2name($uid) { if ($uid === null || $uid === '') { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } // we store last folder in-memory if (isset($this->icache["folder:$uid"])) { return $this->icache["folder:$uid"]; } $uids = $this->folder_uids(); foreach ($uids as $folder => $_uid) { if ($uid === $_uid) { return $this->icache["folder:$uid"] = $folder; } } // slowest method, but we need to try it, the full folders list // might contain non-existing folder (not in folder_uids() result) foreach ($this->folders_list() as $folder) { if ($folder['uid'] === $uid) { return rcube_charset::convert($folder['fullpath'], RCUBE_CHARSET, 'UTF7-IMAP'); } } throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } /** * Helper method to get folder UID * * @param string $folder Folder name (UTF7-IMAP) * * @return string Folder's UID */ protected function folder_name2uid($folder) { $uid_keys = array( kolab_storage::UID_KEY_CYRUS, ); // get folder identifiers $metadata = $this->storage->get_metadata($folder, $uid_keys); if (!is_array($metadata) && $this->storage->get_error_code() != rcube_imap_generic::ERROR_NO) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } /* // above we assume that cyrus built-in unique identifiers are available // however, if they aren't we'll try kolab folder UIDs if (empty($metadata)) { $uid_keys = array( kolab_storage::UID_KEY_PRIVATE, kolab_storage::UID_KEY_SHARED, ); // get folder identifiers $metadata = $this->storage->get_metadata($folder, $uid_keys); if (!is_array($metadata) && $this->storage->get_error_code() != rcube_imap_generic::ERROR_NO) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } } */ if (!empty($metadata[$folder])) { foreach ($uid_keys as $key) { if ($uid = $metadata[$folder][$key]) { return $uid; } } } return md5($folder); /* // @TODO: // make sure folder exists // generate a folder UID and set it to IMAP $uid = rtrim(chunk_split(md5($folder . $this->get_owner() . uniqid('-', true)), 12, '-'), '-'); if (!$this->storage->set_metadata($folder, array(kolab_storage::UID_KEY_SHARED => $uid))) { if ($this->storage->set_metadata($folder, array(kolab_storage::UID_KEY_PRIVATE => $uid))) { return $uid; } } // create hash from folder name if we can't write the UID metadata return md5($folder . $this->get_owner()); */ } /** * Callback for uasort() that implements correct * locale-aware case-sensitive sorting */ protected function sort_folder_comparator($str1, $str2) { $path1 = explode($this->delimiter, $str1); $path2 = explode($this->delimiter, $str2); foreach ($path1 as $idx => $folder1) { $folder2 = $path2[$idx]; if ($folder1 === $folder2) { continue; } return strcoll($folder1, $folder2); } } /** * Return UIDs of all folders * * @return array Folder name to UID map */ protected function folder_uids() { $uid_keys = array( kolab_storage::UID_KEY_CYRUS, ); // get folder identifiers $metadata = $this->storage->get_metadata('*', $uid_keys); if (!is_array($metadata)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } /* // above we assume that cyrus built-in unique identifiers are available // however, if they aren't we'll try kolab folder UIDs if (empty($metadata)) { $uid_keys = array( kolab_storage::UID_KEY_PRIVATE, kolab_storage::UID_KEY_SHARED, ); // get folder identifiers $metadata = $this->storage->get_metadata('*', $uid_keys); if (!is_array($metadata)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } } */ $lambda = function(&$item, $key, $keys) { reset($keys); foreach ($keys as $key) { $item = $item[$key]; return; } }; array_walk($metadata, $lambda, $uid_keys); return $metadata; } /** * Get folder by UID (use only for non-mail folders) * * @param string $uid Folder UID * @param string $type Folder type * * @return kolab_storage_folder Folder object * @throws kolab_api_exception */ protected function folder_get_by_uid($uid, $type = null) { $folder = $this->folder_uid2name($uid); $folder = kolab_storage::get_folder($folder, $type); if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } // Check the given storage folder instance for validity and throw // the right exceptions according to the error state. if (!$folder->valid || ($error = $folder->get_error())) { if ($error === kolab_storage::ERROR_IMAP_CONN) { throw new kolab_api_exception(kolab_api_exception::UNAVAILABLE); } else if ($error === kolab_storage::ERROR_CACHE_DB) { throw new kolab_api_exception(kolab_api_exception::UNAVAILABLE); } else if ($error === kolab_storage::ERROR_NO_PERMISSION) { throw new kolab_api_exception(kolab_api_exception::FORBIDDEN); } else if ($error === kolab_storage::ERROR_INVALID_FOLDER) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } return $folder; } /** * Storage host selection */ protected function select_host($username) { // Get IMAP host $host = $this->api->config->get('default_host', 'localhost'); if (is_array($host)) { list($user, $domain) = explode('@', $username); // try to select host by mail domain if (!empty($domain)) { foreach ($host as $storage_host => $mail_domains) { if (is_array($mail_domains) && in_array_nocase($domain, $mail_domains)) { $host = $storage_host; break; } else if (stripos($storage_host, $domain) !== false || stripos(strval($mail_domains), $domain) !== false) { $host = is_numeric($storage_host) ? $mail_domains : $storage_host; break; } } } // take the first entry if $host is not found if (is_array($host)) { list($key, $val) = each($default_host); $host = is_numeric($key) ? $val : $key; } } return rcube_utils::parse_host($host); } /** * Authenticates a user in IMAP and returns Roundcube user ID. */ protected function login($username, $password, $host, &$error = null) { if (empty($username)) { return null; } $login_lc = $this->api->config->get('login_lc'); $default_port = $this->api->config->get('default_port', 143); // parse $host $a_host = parse_url($host); if ($a_host['host']) { $host = $a_host['host']; $ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null; if (!empty($a_host['port'])) { $port = $a_host['port']; } else if ($ssl && $ssl != 'tls' && (!$default_port || $default_port == 143)) { $port = 993; } } if (!$port) { $port = $default_port; } // Convert username to lowercase. If storage backend // is case-insensitive we need to store always the same username if ($login_lc) { if ($login_lc == 2 || $login_lc === true) { $username = mb_strtolower($username); } else if (strpos($username, '@')) { // lowercase domain name list($local, $domain) = explode('@', $username); $username = $local . '@' . mb_strtolower($domain); } } // Here we need IDNA ASCII // Only rcube_contacts class is using domain names in Unicode $host = rcube_utils::idn_to_ascii($host); $username = rcube_utils::idn_to_ascii($username); // user already registered? if ($user = rcube_user::query($username, $host)) { $username = $user->data['username']; } // authenticate user in IMAP if (!$this->storage->connect($host, $username, $password, $port, $ssl)) { $error = $this->storage->get_error_code(); return null; } // No user in database, but IMAP auth works if (!is_object($user)) { if ($this->api->config->get('auto_create_user')) { // create a new user record $user = rcube_user::create($username, $host); if (!$user) { rcube::raise_error(array( 'code' => 620, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Failed to create a user record", ), true, false); return null; } } else { rcube::raise_error(array( 'code' => 620, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Access denied for new user $username. 'auto_create_user' is disabled", ), true, false); return null; } } // overwrite config with user preferences $this->user = $user; $this->api->config->set_user_prefs((array)$this->user->get_prefs()); $_SESSION['user_id'] = $this->user->ID; $_SESSION['username'] = $this->user->data['username']; $_SESSION['storage_host'] = $host; $_SESSION['storage_port'] = $port; $_SESSION['storage_ssl'] = $ssl; $_SESSION['password'] = $this->api->encrypt($password); $_SESSION['login_time'] = time(); setlocale(LC_ALL, 'en_US.utf8', 'en_US.UTF-8'); return $user->ID; } /** * Returns list of tag-relation names assigned to kolab object */ protected function get_tags($object, $categories = null) { // Kolab object if (is_array($object)) { $ident = $object['uid']; } // Mail message else if (is_object($object)) { // support only messages with message-id $ident = $object->headers->get('message-id', false); $folder = $message->folder; $uid = $message->uid; } if (empty($ident)) { return array(); } $config = kolab_storage_config::get_instance(); $tags = $config->get_tags($ident); $delta = 300; // resolve members if it wasn't done recently if ($uid) { foreach ($tags as $idx => $tag) { $force = empty($this->tag_rts[$tag['uid']]) || $this->tag_rts[$tag['uid']] <= time() - $delta; $members = $config->resolve_members($tag, $force); if (empty($members[$folder]) || !in_array($uid, $members[$folder])) { unset($tags[$idx]); } if ($force) { $this->tag_rts[$tag['uid']] = time(); } } // make sure current folder is set correctly again $this->storage->set_folder($folder); } $tags = array_filter(array_map(function($v) { return $v['name']; }, $tags)); // merge result with old categories if (!empty($categories)) { $tags = array_unique(array_merge($tags, (array) $categories)); } return $tags; } /** * Set tag-relations to kolab object */ protected function set_tags($uid, $tags) { // @TODO: set_tags() for email $config = kolab_storage_config::get_instance(); $config->save_tags($uid, $tags); } } diff --git a/lib/kolab_api_mail.php b/lib/kolab_api_mail.php index 12894f1..440d01f 100644 --- a/lib/kolab_api_mail.php +++ b/lib/kolab_api_mail.php @@ -1,1040 +1,1195 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ class kolab_api_mail { /** * List of supported header fields * * @var array */ public static $header_fields = array( 'uid', 'subject', 'from', 'sender', 'to', 'cc', 'bcc', 'reply-to', 'in-reply-to', 'message-id', 'references', 'date', 'internaldate', 'content-type', 'priority', 'size', 'flags', 'categories', ); /** * Original message * * @var rcube_message */ protected $message; /** * Modified properties * * @var array */ protected $data = array(); /** * Validity status * * @var bool */ protected $valid = true; /** * Headers-only mode flag * * @var bool */ protected $is_header = false; /** * Line separator * * @var string */ protected $endln = "\r\n"; protected $body_text; protected $body_html; protected $boundary; - protected $recipients = array(); + protected $attach_data = array(); + protected $recipients = array(); protected $from_address; /** * Object constructor * * @param rcube_message|rcube_message_header Original message */ public function __construct($message = null) { $this->message = $message; $this->is_header = $this->message instanceof rcube_message_header; } /** * Properties setter * * @param string $name Property name * @param mixed $value Property value */ public function __set($name, $value) { switch ($name) { case 'flags': $value = (array) $value; break; case 'priority': $value = (int) $value; /* values: 1, 2, 4, 5 */ break; case 'date': case 'subject': case 'from': case 'sender': case 'to': case 'cc': case 'bcc': case 'reply-to': case 'in-reply-to': case 'references': case 'categories': case 'message-id': case 'text': case 'html': // make sure the value is utf-8 if ($value !== null && $value !== '' && (!is_array($value) || !empty($value))) { // make sure we have utf-8 here $value = rcube_charset::clean($value); } break; case 'uid': case 'internaldate': case 'content-type': case 'size': // ignore return; default: // unsupported property, log error? return; } if (!$changed && in_array($name, self::$header_fields)) { $changed = $this->{$name} !== $value; } else { $changed = true; } if ($changed) { $this->data[$name] = $value; } } /** * Properties getter * * @param string $name Property name * * @param mixed Property value */ public function __get($name) { if (array_key_exists($name, $this->data)) { return $this->data[$name]; } if (empty($this->message)) { return; } $headers = $this->is_header ? $this->message : $this->message->headers; $value = null; switch ($name) { case 'uid': return (string) $headers->uid; break; case 'priority': case 'size': if (isset($headers->{$name})) { $value = (int) $headers->{$name}; } break; case 'content-type': $value = $headers->ctype; break; case 'date': case 'internaldate': $value = $headers->{$name}; break; case 'subject': $value = trim(rcube_mime::decode_header($headers->subject, $headers->charset)); break; case 'flags': $value = array_change_key_case((array) $headers->flags); $value = array_filter($value); $value = array_keys($value); break; case 'from': case 'sender': case 'to': case 'cc': case 'bcc': case 'reply-to': $addresses = $headers->{$name == 'reply-to' ? 'replyto' : $name}; $addresses = rcube_mime::decode_address_list($addresses, null, true, $headers->charset); $value = array(); foreach ((array) $addresses as $addr) { $idx = count($value); if ($addr['mailto']) { $value[$idx]['address'] = $addr['mailto']; } if ($addr['name']) { $value[$idx]['name'] = $addr['name']; } } if ($name == 'from' && !empty($value)) { $value = $value[0]; } break; case 'categories': $value = (array) $headers->categories; break; case 'references': case 'in-reply-to': case 'message-id': $value = $headers->get($name); break; case 'text': case 'html': $value = $this->body($name == 'html'); break; } // add the value to the result if ($value !== null && $value !== '' && (!is_array($value) || !empty($value))) { // make sure we have utf-8 here $value = rcube_charset::clean($value); } return $value; } /** * Return message data as an array * * @param array $filetr Optional properties filter * * @return array Message/headers data */ public function data($filter = array()) { $result = array(); $fields = self::$header_fields; if (!empty($filter)) { $fields = array_intersect($fields, $filter); } foreach ($fields as $field) { $value = $this->{$field}; // add the value to the result if ($value !== null && $value !== '') { $result[$field] = $value; } } // complete rcube_message object, we can set more props, e.g. body content if (!$this->is_header) { foreach (array('text', 'html') as $prop) { if ($value = $this->{$prop}) { $result[$prop] = $value; } } } return $result; } /** * Check if the original message has been modified * * @return bool True if the message has been modified * since the object creation */ public function changed() { return !empty($this->data); } /** * Check object validity * * @return bool True if the object is valid */ public function valid() { if (empty($this->message)) { // @TODO: check required properties of a new message? } return $this->valid; } /** * Save the message in specified folder * * @param string $folder IMAP folder name * * @return string New message UID * @throws kolab_api_exception */ public function save($folder = null) { if (empty($this->data)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( 'file' => __FILE__, 'line' => __LINE__, 'message' => 'Nothing to save. Did you use kolab_api_mail::changed()?' )); } $message = $this->get_message(); $api = kolab_api::get_instance(); if (empty($message) && !strlen($folder)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( 'file' => __FILE__, 'line' => __LINE__, 'message' => 'Folder not specified' )); } // Create message content $stream = $this->create_message_stream(); // Save the message $uid = $this->save_message($stream, $folder ?: $message->folder); // IMAP flags change requested if (array_key_exists('flags', $this->data)) { $old_flags = $this->flags; // set new flags foreach ((array) $this->data['flags'] as $flag) { if (($key = array_search($flag, $old_flags)) !== false) { unset($old_flags[$key]); } else { $flag = strtoupper($flag); $api->backend->storage->set_flag($uid, $flag, $message->folder); } } // unset remaining old flags foreach ($old_flags as $flag) { $flag = 'UN' . strtoupper($flag); $api->backend->storage->set_flag($uid, $flag, $message->folder); } } return $uid; } /** * Send the message * * @return bool True on success * @throws kolab_api_exception */ public function send() { // Create message content $stream = $this->create_message_stream(true); if (empty($this->from_address)) { throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST, null, "No sender found"); } if (empty($this->recipients)) { throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST, null, "No recipients found"); } $this->send_message_stream($stream); return true; } /** - * Add attachment to the message + * Add an attachment to the message * - * @return bool True on success, False on failure + * @param rcube_message_part $attachment Attachment data + * + * @return string New message UID on success * @throws kolab_api_exception */ - public function attachment_add() + public function attachment_add($attachment) { - // @TODO if (!($message = $this->get_message())) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } + + $this->attach_data['create'][] = $attachment; + + // Create message content + $stream = $this->create_message_stream(); + + // Save the message + return $this->save_message($stream, $message->folder); } /** * Remove attachment from the message * - * @return bool True on success, False on failure + * @param string $id Attachment id + * + * @return string New message UID on success * @throws kolab_api_exception */ - public function attachment_remove() + public function attachment_delete($id) { - // @TODO if (!($message = $this->get_message())) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } + + foreach ((array) $message->attachments as $attach) { + if ($attach->mime_id == $id) { + $attachment = $attach; + } + } + + if (empty($attachment)) { + throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); + } + + $this->attach_data['delete'][] = $attachment; + + // Create message content + $stream = $this->create_message_stream(); + + // Save the message + return $this->save_message($stream, $message->folder); } /** - * Update attachment in the message + * Update specified attachment in the message + * + * @param rcube_message_part $attachment Attachment data * - * @return bool True on success, False on failure + * @return string New message UID on success * @throws kolab_api_exception */ - public function attachment_update() + public function attachment_update($attachment) { - // @TODO if (!($message = $this->get_message())) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } + + $this->attach_data['update'][] = $attachment; + + // Create message content + $stream = $this->create_message_stream(); + + // Save the message + return $this->save_message($stream, $message->folder); } /** * Create message stream */ protected function create_message_stream($send_mode = false) { $api = kolab_api::get_instance(); $message = $this->get_message(); $specials = array('flags', 'categories'); $diff = array_diff($this->data, $specials); $headers = array(); $endln = $this->endln; + $body_mod = $message && (!empty($diff) || !empty($this->attach_data)); // header change requested, get old headers - if (!empty($diff) && $message) { + if ($body_mod) { $api->backend->storage->set_folder($message->folder); $headers = $api->backend->storage->get_raw_headers($message->uid); $headers = self::parse_headers($headers); } foreach ($this->data as $name => $value) { $normalized = self::normalize_header_name($name); unset($headers[$normalized]); switch ($name) { case 'priority': unset($headers['X-Priority']); $priority = intval($value); $priorities = array(1 => 'highest', 2 => 'high', 4 => 'low', 5 => 'lowest'); if ($str_priority = $priorities[$priority]) { $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority)); } break; case 'date': // @TODO: date-time format $headers['Date'] = $value; break; case 'from': if (!empty($value)) { if (empty($value['address']) || !strpos($value['address'], '@')) { throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); } $value = format_email_recipient($value['address'], $value['name']); } $headers[$normalized] = $value; break; case 'to': case 'cc': case 'bcc': case 'reply-to': $recipients = array(); foreach ((array) $value as $adr) { if (!is_array($adr) || empty($adr['address']) || !strpos($adr['address'], '@')) { throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); } $recipients[] = format_email_recipient($adr['address'], $adr['name']); } $headers[$normalized] = implode(',', $recipients); break; case 'references': case 'in-reply-to': case 'message-id': case 'subject': if ($value) { $headers[$normalized] = $value; } break; } } // Prepare message body $body_mod = $this->prepare_body($headers); // We're going to send this message, we need more data/checks if ($send_mode) { if (empty($headers['From'])) { // get From: address from default identity of the user? if ($identity = $api->backend->user->get_identity()) { $headers['From'] = format_email_recipient( format_email($identity['email']), $identity['name']); } } $addresses = rcube_mime::decode_address_list($headers['From'], null, false, null, true); $this->from_address = array_shift($addresses); // extract mail recipients foreach (array('To', 'Cc', 'Bcc') as $idx) { if ($headers[$idx]) { $addresses = rcube_mime::decode_address_list($headers[$idx], null, false, null, true); $this->recipients = array_merge($this->recipients, $addresses); } } $this->recipients = array_unique($this->recipients); unset($headers['Bcc']); $headers['Date'] = $api->user_date(); /* if ($mdn_enabled) { $headers['Return-Receipt-To'] = $this->from_address; $headers['Disposition-Notification-To'] = $this->from_address; } */ } // Write message headers to the stream if (!empty($headers) || empty($message) || $body_mod) { // Place Received: headers at the beginning of the message // Spam detectors often flag messages with it after the Subject: as spam if (!empty($headers['Received'])) { $received = $headers['Received']; unset($headers['Received']); $headers = array('Received' => $received) + $headers; } if (empty($headers['MIME-Version'])) { $headers['MIME-Version'] = '1.0'; } // always add User-Agent header if (empty($headers['User-Agent'])) { $headers['User-Agent'] .= kolab_api::APP_NAME . ' ' . kolab_api::VERSION; if ($agent = $api->config->get('useragent')) { $headers['User-Agent'] .= '/' . $agent; } } if (empty($headers['Message-ID'])) { $headers['Message-ID'] = $this->gen_message_id(); } // create new message header if ($stream = fopen('php://temp/maxmemory:10240000', 'r+')) { foreach ($headers as $header_name => $header_value) { if (strlen($header_value)) { $header_value = $this->encode_header($header_name, $header_value); fwrite($stream, $header_name . ": " . $header_value . $endln); } } fwrite($stream, $endln); } else { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( 'file' => __FILE__, 'line' => __LINE__, 'message' => 'Failed to open file stream for mail message' )); } } // Save/update the message body into the stream - $this->write_body($stream, $headers, $text, $html); + $this->write_body($stream, $headers); return $stream; } /** * Send the message stream using configured method */ protected function send_message_stream($stream) { $api = kolab_api::get_instance(); // send thru SMTP server using custom SMTP library if ($api->config->get('smtp_server')) { // send message if (!is_object($api->smtp)) { $api->smtp_init(true); } rewind($stream); $headers = null; $sent = $api->smtp->send_mail( $this->from_address, $this->recipients, $headers, $stream, $smtp_opts); // log error if (!$sent) { $smtp_response = $api->smtp->get_response(); // $smtp_error = $api->smtp->get_error(); throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( 'line' => __LINE__, 'file' => __FILE__, 'code' => 800, 'type' => 'smtp', 'message' => "SMTP error: " . join("\n", $smtp_response), )); } } else { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( 'line' => __LINE__, 'file' => __FILE__, 'code' => 800, 'type' => 'smtp', 'message' => "SMTP server not configured. Really need smtp_server option to be set.", )); } // $api->plugins->exec_hook('message_sent', array('headers' => array(), 'body' => $stream)); if ($api->config->get('smtp_log')) { rcube::write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s", $api->get_user_name(), $_SERVER['REMOTE_ADDR'], implode(',', $this->recipients), !empty($smtp_response) ? join('; ', $smtp_response) : '')); } return true; } /** * Prepare message body and content headers */ protected function prepare_body(&$headers) { $message = $this->get_message(); - $body_mod = array_key_exists('text', $this->data) || array_key_exists('html', $this->data); + $body_mod = array_key_exists('text', $this->data) + || array_key_exists('html', $this->data) + || !empty($this->attach_data); if (!$body_mod) { return false; } - $ctype = $this->data['html'] ? 'multipart/alternative' : 'text/plain'; + if (!empty($this->attach_data['create']) || !empty($this->attach_data['update'])) { + $ctype = 'multipart/mixed'; + } + else { + $ctype = $this->data['html'] ? 'multipart/alternative' : 'text/plain'; + } // Get/set Content-Type header of the modified message if ($old_ctype = $headers['Content-Type']) { if (preg_match('/boundary="?([a-z0-9-\'\(\)+_\,\.\/:=\? ]+)"?/i', $old_ctype, $matches)) { $boundary = $matches[1]; } if ($pos = strpos($old_ctype, ';')) { $old_ctype = substr($old_ctype, 0, $pos); } if ($old_ctype == 'multipart/mixed') { // replace first part (if it is text/plain or multipart/alternative) $ctype = $old_ctype; } } $headers['Content-Type'] = $ctype; if ($ctype == 'text/plain') { $headers['Content-Type'] .= '; charset=' . RCUBE_CHARSET; } else if (!$boundary) { $boundary = '_' . md5(rand() . microtime()); } if ($boundary) { $headers['Content-Type'] .= ';' . $this->endln . " boundary=\"$boundary\""; } // create message body if ($html = $this->data['html']) { $text = $this->data['text']; if ($text === null) { $h2t = new rcube_html2text($html); $text = $h2t->get_text(); } $this->body_text = quoted_printable_encode($text); $this->body_html = quoted_printable_encode($html); } else if ($text = $this->data['text']) { $headers['Content-Transfer-Encoding'] = 'quoted-printable'; $this->body_text = quoted_printable_encode($text); } $this->boundary = $boundary; // make sure all line endings are CRLF $this->body_text = preg_replace('/\r?\n/', $this->endln, $this->body_text); $this->body_html = preg_replace('/\r?\n/', $this->endln, $this->body_html); return true; } /** * Write message body to the stream */ protected function write_body($stream, $headers) { $api = kolab_api::get_instance(); $endln = $this->endln; $message = $this->get_message(); - $modified = array_key_exists('text', $this->data) || array_key_exists('html', $this->data); + $body_mod = array_key_exists('text', $this->data) || array_key_exists('html', $this->data); + $modified = $body_mod || !empty($this->attach_data); // @TODO: related parts for inline images - // @TODO: attachment parts // nothing changed in the modified message body... if (!$modified && !empty($message)) { // just copy the content to the output stream $api->backend->storage->get_raw_body($message->uid, $stream, 'TEXT'); } // new message creation, or the message does not have any attachments - else if (empty($message) || $message->headers->ctype != 'multipart/mixed') { + else if (empty($message) || ($message->headers->ctype != 'multipart/mixed' && empty($this->attach_data))) { // Here we do not have attachments yet, so we only have two // simple options: multipart/alternative or text/plain $this->write_body_content($stream, $this->boundary); } - // body changed, multipart/mixed message + // body changed or attachments added, non-multipart message + else if ($message->headers->ctype != 'multipart/mixed') { + fwrite($stream, '--' . $this->boundary . $endln); + // write body + if (array_key_exists('text', $this->data) || array_key_exists('html', $this->data)) { + // new body + $this->write_body_content($stream, $this->boundary); + } + else { + // existing body, just copy old content to the stream + $api->backend->storage->get_raw_body($message->uid, $stream, 'TEXT'); + } + + fwrite($stream, $endln); + + // write attachments, here we can only have new attachments + foreach ((array) $this->attach_data['create'] as $attachment) { + fwrite($stream, '--' . $this->boundary . $endln); + $this->write_attachment($stream, $attachment); + } + + fwrite($stream, $endln . '--' . $this->boundary . '--' . $endln); + } + // body or attachments changed, multipart/mixed message else { // get old TEXT of the message $body_stream = fopen('php://temp/maxmemory:10240000', 'r+'); $api->backend->storage->get_raw_body($message->uid, $body_stream, 'TEXT'); rewind($body_stream); - $inside = false; - $done = false; + $num = 0; + $ignore = false; $regexp = '/^--' . preg_quote($this->boundary, '/') . '(--|)\r?\n$/'; // Go and replace bodies... while (($line = fgets($body_stream, 4096)) !== false) { // boundary line if ($line[0] === '-' && $line[1] === '-' && preg_match($regexp, $line, $m)) { - if ($inside) { - $headers = null; - $inside = false; - } - else if (!$done) { - $headers = ''; - $inside = true; + // this is the end of the message, add new attachment(s) here + if ($m[1] == '--') { + foreach ((array) $this->attach_data['create'] as $attachment) { + fwrite($stream, '--' . $this->boundary . $endln); + $this->write_attachment($stream, $attachment); + } + + fwrite($stream, $line); + break; } - } - else if ($inside) { - if ($headers !== null) { - // parse headers - if (!strlen(rtrim($line, "\r\n"))) { -// $a_headers = self::parse_headers($headers); - $boundary = '_' . md5(rand() . microtime()); - $this->write_body_content($stream, $boundary, true); - - $headers = null; - $done = true; + + $num++; + $ignore = false; + + // delete this part + foreach ((array) $this->attach_data['delete'] as $attachment) { + if ($attachment->mime_id == $num) { + $ignore = true; + continue 2; } - else { - $headers .= $line; + } + + // update this part + foreach ((array) $this->attach_data['update'] as $attachment) { + if ($attachment->mime_id == $num) { + fwrite($stream, $line); + $this->write_attachment($stream, $attachment); + $ignore = true; + continue 2; } } + // find the first part (expected to be the text or alternative + if ($num == 1 && $body_mod) { + $ignore = true; + $boundary = '_' . md5(rand() . microtime()); + fwrite($stream, $line); + $this->write_body_content($stream, $boundary, true); + continue; + } + } + else if ($ignore) { continue; } fwrite($stream, $line); } fclose($body_stream); } } /** * Write configured text/plain or multipart/alternative * part content into message stream */ protected function write_body_content($stream, $boundary, $with_headers = false) { $endln = $this->endln; // multipart/alternative if (strlen($this->body_html)) { if ($with_headers) { fwrite($stream, 'Content-Type: multipart/alternative;' . $endln . " boundary=\"$boundary\"" . $endln . $endln); } fwrite($stream, '--' . $boundary . $endln . 'Content-Transfer-Encoding: quoted-printable' . $endln . 'Content-Type: text/plain; charset=UTF-8' . $endln . $endln); fwrite($stream, $this->body_text); fwrite($stream, $endln . '--' . $boundary . $endln . 'Content-Transfer-Encoding: quoted-printable' . $endln . 'Content-Type: text/html; charset=UTF-8' . $endln . $endln); fwrite($stream, $this->body_html); fwrite($stream, $endln . '--' . $boundary . '--' . $endln); } // text/plain else if (strlen($this->body_text)) { if ($with_headers) { fwrite($stream, 'Content-Transfer-Encoding: quoted-printable' . $endln . 'Content-Type: text/plain; charset=UTF-8' . $endln . $endln); } // make sure all line endings are CRLF $plainTextPart = preg_replace('/\r?\n/', "\r\n", $plainTextPart); fwrite($stream, $this->body_text); } } /** * Get rcube_message object of the assigned message */ protected function get_message() { if ($this->message && !($this->message instanceof rcube_message)) { $this->message = new rcube_message($this->message->uid, $this->message->folder); if (empty($this->message->headers)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } } return $this->message; } /** * Parse message source with headers */ protected static function parse_headers($headers) { // Parse headers $headers = str_replace("\r\n", "\n", $headers); $headers = explode("\n", trim($headers)); $ln = 0; $lines = array(); foreach ($headers as $line) { if (ord($line[0]) <= 32) { $lines[$ln] .= (empty($lines[$ln]) ? '' : "\r\n") . $line; } else { $lines[++$ln] = trim($line); } } // Unify char-case of header names $headers = array(); foreach ($lines as $line) { list($field, $string) = explode(':', $line, 2); if ($field = self::normalize_header_name($field)) { $headers[$field] = trim($string); } } return $headers; } /** * Normalize (fix) header names */ protected static function normalize_header_name($name) { $headers_map = array( 'subject' => 'Subject', 'from' => 'From', 'to' => 'To', 'cc' => 'Cc', 'bcc' => 'Bcc', 'date' => 'Date', 'reply-to' => 'Reply-To', 'in-reply-to' => 'In-Reply-To', 'x-priority' => 'X-Priority', 'message-id' => 'Message-ID', 'references' => 'References', 'content-type' => 'Content-Type', 'content-transfer-encoding' => 'Content-Transfer-Encoding', ); $name_lc = strtolower($name); return isset($headers_map[$name_lc]) ? $headers_map[$name_lc] : $name; } /** * Save the message into IMAP folder and delete the old one */ protected function save_message($stream, $folder) { $api = kolab_api::get_instance(); $message = $this->get_message(); // save the message $saved = $api->backend->storage->save_message($folder, array($stream)); if (empty($saved)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, array( 'file' => __FILE__, 'line' => __LINE__, 'message' => 'Failed to save the message in storage' )); } // delete the old message if ($saved && $message && $message->uid) { $api->backend->storage->delete_message($message->uid, $folder); } return $saved; } /** * Return message body (in specified format, html or text) */ protected function body($html = true) { if ($message = $this->get_message()) { if ($html) { $html = $message->first_html_part($part, true); if ($html) { // charset was converted to UTF-8 in rcube_storage::get_message_part(), // change/add charset specification in HTML accordingly $meta = ''; // remove old meta tag and add the new one, making sure // that it is placed in the head $html = preg_replace('/]+charset=[a-z0-9-_]+[^>]*>/Ui', '', $html); $html = preg_replace('/(]*>)/Ui', '\\1' . $meta, $html, -1, $rcount); if (!$rcount) { $html = '' . $meta . '' . $html; } } return $html; } $plain = $message->first_text_part($part, true); if ($part === null && $message->body) { $plain = $message->body; } else if ($part->ctype_secondary == 'plain' && $part->ctype_parameters['format'] == 'flowed') { $plain = rcube_mime::unfold_flowed($plain); } return $plain; } } /** * Encode header value */ protected function encode_header($name, $value) { $mime_part = new Mail_mimePart; return $mime_part->encodeHeader($name, $value, RCUBE_CHARSET, 'quoted-printable', $this->endln); } /** * Unique Message-ID generator. * * @return string Message-ID */ public function gen_message_id() { $api = kolab_api::get_instance(); $local_part = md5(uniqid('kolab'.mt_rand(), true)); $domain_part = $api->backend->user->get_username('domain'); // Try to find FQDN, some spamfilters doesn't like 'localhost' (#1486924) if (!preg_match('/\.[a-z]+$/i', $domain_part)) { foreach (array($_SERVER['HTTP_HOST'], $_SERVER['SERVER_NAME']) as $host) { $host = preg_replace('/:[0-9]+$/', '', $host); if ($host && preg_match('/\.[a-z]+$/i', $host)) { $domain_part = $host; } } } return sprintf('<%s@%s>', $local_part, $domain_part); } + + /** + * Write attachment body with headers into the output stream + */ + protected function write_attachment($stream, $attachment) + { + $api = kolab_api::get_instance(); + $message = $this->get_message(); + $temp_dir = $api->config->get('temp_dir'); + + // use Mail_mimePart functionality for simplicity + $params = array( + 'eol' => $this->endln, + 'encoding' => $attachment->mimetype == 'message/rfc822' ? '8bit' : 'base64', + 'content_type' => $attachment->mimetype, + 'body_file' => $attachment->path, + 'disposition' => 'attachment', + 'filename' => $attachment->filename, + 'name_encoding' => 'quoted-printable', + 'headers_charset' => RCUBE_CHARSET, + ); + + if ($attachment->content_id) { + $params['cid'] = rtrim($attachment->content_id, '<>'); + } + + if ($attachment->content_location) { + $params['location'] = $attachment->content_location; + } + + // Get attachment body if both 'path' and 'data' are NULL + // this is the case when we modify only attachment metadata, e.g. filename + if (empty($attachment->path) && $attachment->data === null + && !empty($message) && !empty($attachment->mime_id) + ) { + // @TODO: do this with temp files + $api->backend->storage->set_folder($message->folder); + $body = $api->backend->storage->get_raw_body($message->uid, null, $attachment->mime_id . '.TEXT'); + + if ($attachment->encoding == 'base64') { + $body = base64_decode($body); + } + else if ($attachment->encoding == 'quoted-printable') { + $body = quoted_printable_decode($body); + } + + $attachment->data = $body; + } + + $mime = new Mail_mimePart($attachment->data, $params); + $temp_file = tempnam($temp_dir, 'msgPart'); + + // @TODO: implement encodeToStream() + $result = $mime->encodeToFile($temp_file); + + if ($result instanceof PEAR_Error) { + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR, $result); + } + + if ($fd = fopen($temp_file, 'r')) { + stream_copy_to_stream($fd, $stream); + fwrite($stream, $this->endln); + fclose($fd); + @unlink($temp_file); + } + else { + throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); + } + } } diff --git a/lib/output/json/attachment.php b/lib/output/json/attachment.php index 167242b..c7c160c 100644 --- a/lib/output/json/attachment.php +++ b/lib/output/json/attachment.php @@ -1,100 +1,105 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ class kolab_api_output_json_attachment { protected $output; /** * Object constructor * * @param kolab_api_output Output object */ public function __construct($output) { $this->output = $output; } /** * Convert message data into an array * * @param rcube_message_part Attachment data * @param array Optional attributes filter * * @return array Data */ public function element($data, $attrs_filter = array()) { + // File upload case + if (is_array($data)) { + return $data; + } + $result = array(); // supported attachment data fields $fields = array( 'id', 'mimetype', 'size', 'filename', 'disposition', 'content-id', 'content-location', ); if (!empty($attrs_filter)) { $header_fields = array_intersect($header_fields, $attrs_filter); } foreach ($fields as $field) { $value = null; switch ($field) { case 'id': $value = (string) $data->mime_id; break; case 'mimetype': case 'filename': case 'disposition': case 'content-id': case 'content-location': $value = $data->{str_replace('-', '_', $field)}; break; case 'size': $value = (int) $data->size; break; } // add the value to the result if ($value !== null && $value !== '' && (!is_array($value) || !empty($value))) { // make sure we have utf-8 here $value = rcube_charset::clean($value); $result[$field] = $value; } } return $result; } } diff --git a/tests/API/Attachments.php b/tests/API/Attachments.php index ceb3b3e..a4edbd1 100644 --- a/tests/API/Attachments.php +++ b/tests/API/Attachments.php @@ -1,232 +1,352 @@ head('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6/2'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); // and non-existing attachment self::$api->head('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6/2345'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); // test attachments of non-mail objects self::$api->head('attachments/' . kolab_api_tests::folder_uid('Calendar') . '/100-100-100-100/3'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); } /** * Test attachment info */ function test_attachment_info() { self::$api->get('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6/2'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame('2', $body['id']); $this->assertSame('text/plain', $body['mimetype']); $this->assertSame('test.txt', $body['filename']); $this->assertSame(4, $body['size']); // and non-existing attachment self::$api->get('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6/2345'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); // test attachments of kolab objects self::$api->get('attachments/' . kolab_api_tests::folder_uid('Calendar') . '/100-100-100-100/3'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame('3', $body['id']); $this->assertSame('image/jpeg', $body['mimetype']); $this->assertSame('photo-mini.jpg', $body['filename']); $this->assertSame('attachment', $body['disposition']); $this->assertSame(793, $body['size']); } /** * Test attachment body */ function test_attachment_get() { // mail attachment self::$api->get('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6/3/get'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame(793, strlen($body)); $this->assertSame('/9j/4AAQSkZJRgAB', substr(base64_encode($body), 0, 16)); // @TODO: headers // test attachments of kolab objects self::$api->get('attachments/' . kolab_api_tests::folder_uid('Tasks') . '/10-10-10-10/3/get'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame(4, strlen($body)); $this->assertSame('test', $body); } + /** + * Test attachment uploads + */ + function test_attachment_upload() + { + // do many uploads that we use later in create/update tests + $post = 'Some text file'; + self::$api->post('attachments/upload', array(), $post, 'application/octet-stream'); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + $body = json_decode($body, true); + + $this->assertEquals(200, $code); + $this->assertCount(1, $body); + $this->assertTrue(!empty($body['upload-id'])); + + self::$uploaded[] = $body['upload-id']; + + $post = 'Some text file'; + + self::$api->post('attachments/upload', array('filename' => 'some.txt'), $post, 'application/octet-stream'); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + $body = json_decode($body, true); + + $this->assertEquals(200, $code); + $this->assertCount(1, $body); + $this->assertTrue(!empty($body['upload-id'])); + + self::$uploaded[] = $body['upload-id']; + + $post = base64_decode('R0lGODlhDwAPAIAAAMDAwAAAACH5BAEAAAAALAAAAAAPAA8AQAINhI+py+0Po5y02otnAQA7'); + self::$api->post('attachments/upload', array(), $post, 'application/octet-stream'); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + $body = json_decode($body, true); + + $this->assertEquals(200, $code); + $this->assertCount(1, $body); + $this->assertTrue(!empty($body['upload-id'])); + + self::$uploaded[] = $body['upload-id']; + + $post = base64_decode('R0lGODlhDwAPAIAAAMDAwAAAACH5BAEAAAAALAAAAAAPAA8AQAINhI+py+0Po5y02otnAQA7'); + self::$api->post('attachments/upload', array('filename' => 'empty.gif'), $post, 'application/octet-stream'); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + $body = json_decode($body, true); + + $this->assertEquals(200, $code); + $this->assertCount(1, $body); + $this->assertTrue(!empty($body['upload-id'])); + + self::$uploaded[] = $body['upload-id']; + } + /** * Test attachment create */ function test_attachment_create() { -return; // @TODO + // attach text file to a calendar event $post = json_encode(array( - 'filename' => 'test.txt', - 'mimetype' => 'text/plain' + 'upload-id' => self::$uploaded[0], + 'filename' => 'test.txt', + 'mimetype' => 'text/plain' )); - self::$api->post('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6', array(), $post); + self::$api->post('attachments/' . kolab_api_tests::folder_uid('Calendar') . '/100-100-100-100', array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(1, $body); $this->assertTrue(!empty($body['uid'])); - // folder does not exists - $post = json_encode(array( - 'summary' => 'Test summary 2', - )); - self::$api->post('attachments/' . kolab_api_tests::folder_uid('non-existing') . '/1234', array(), $post); + self::$api->get('events/' . kolab_api_tests::folder_uid('Calendar') . '/100-100-100-100/attachments'); $code = self::$api->response_code(); - $this->assertEquals(404, $code); + $body = self::$api->response_body(); + $body = json_decode($body, true); - // invalid object data + $this->assertEquals(200, $code); + $this->assertCount(2, $body); + $this->assertSame('4', $body[1]['id']); + $this->assertSame('text/plain', $body[1]['mimetype']); + $this->assertSame('test.txt', $body[1]['filename']); + $this->assertSame('attachment', $body[1]['disposition']); + $this->assertSame(14, $body[1]['size']); + + // attach text file to a mail message $post = json_encode(array( - 'test' => 'Test 2', + 'upload-id' => self::$uploaded[1], )); self::$api->post('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6', array(), $post); $code = self::$api->response_code(); - $this->assertEquals(422, $code); + $body = self::$api->response_body(); + $body = json_decode($body, true); + + $this->assertEquals(200, $code); + $this->assertCount(1, $body); + $this->assertTrue(!empty($body['uid']) && $body['uid'] != 6); + + self::$modified = $body['uid']; + + self::$api->get('mails/' . kolab_api_tests::folder_uid('INBOX') . '/' . $body['uid'] . '/attachments'); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + $body = json_decode($body, true); + + $this->assertEquals(200, $code); + $this->assertCount(3, $body); + $this->assertSame('4', $body[2]['id']); + $this->assertSame('text/plain', $body[2]['mimetype']); + $this->assertSame('some.txt', $body[2]['filename']); + $this->assertSame('attachment', $body[2]['disposition']); + $this->assertSame(14, $body[2]['size']); } /** * Test attachment update */ function test_attachment_update() { -return; // @TODO $post = json_encode(array( - 'filename' => 'modified.txt', + 'upload-id' => self::$uploaded[2], )); - self::$api->put('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6/2', array(), $post); + self::$api->put('attachments/' . kolab_api_tests::folder_uid('Calendar') . '/100-100-100-100/4', array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); + $body = json_decode($body, true); - $this->assertEquals(204, $code); - $this->assertSame('', $body); + $this->assertEquals(200, $code); + $this->assertCount(1, $body); + $this->assertTrue(!empty($body['uid'])); - self::$api->get('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6/2'); + self::$api->get('attachments/' . kolab_api_tests::folder_uid('Calendar') . '/100-100-100-100/4'); + $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); - $this->assertSame('modified.txt', $body['filename']); + $this->assertEquals(200, $code); + $this->assertSame('4', $body['id']); + $this->assertSame('image/gif', $body['mimetype']); + $this->assertSame(null, $body['filename']); + $this->assertSame(54, $body['size']); + + // just rename the existing attachment + $post = json_encode(array( + 'filename' => 'changed.gif', + )); + self::$api->put('attachments/' . kolab_api_tests::folder_uid('Calendar') . '/100-100-100-100/4', array(), $post); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + $body = json_decode($body, true); + + $this->assertEquals(200, $code); + $this->assertCount(1, $body); + $this->assertTrue(!empty($body['uid'])); + + self::$api->get('attachments/' . kolab_api_tests::folder_uid('Calendar') . '/100-100-100-100/4'); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + $body = json_decode($body, true); + + $this->assertEquals(200, $code); + $this->assertSame('changed.gif', $body['filename']); + $this->assertSame(54, $body['size']); } /** * Test attachment delete */ function test_attachment_delete() { // delete existing attachment self::$api->delete('attachments/' . kolab_api_tests::folder_uid('Tasks') . '/10-10-10-10/3'); $code = self::$api->response_code(); $body = self::$api->response_body(); + $body = json_decode($body, true); - $this->assertEquals(204, $code); - $this->assertSame('', $body); + $this->assertEquals(200, $code); + $this->assertCount(1, $body); + $this->assertTrue(!empty($body['uid']) && $body['uid'] == '10-10-10-10'); // delete non-existing attachment in an existing object self::$api->delete('attachments/' . kolab_api_tests::folder_uid('Tasks') . '/10-10-10-10/3'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); -/* - @TODO: the same for e-mail // delete existing attachment - self::$api->delete('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6/2'); + self::$api->delete('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/7/2'); $code = self::$api->response_code(); $body = self::$api->response_body(); + $body = json_decode($body, true); - $this->assertEquals(204, $code); - $this->assertSame('', $body); + $this->assertEquals(200, $code); + $this->assertCount(1, $body); + $this->assertTrue(!empty($body['uid']) && $body['uid'] != 7); // and non-existing attachment - self::$api->delete('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/6/2345'); + self::$api->delete('attachments/' . kolab_api_tests::folder_uid('INBOX') . '/7/20'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); -*/ } } diff --git a/tests/API/Folders.php b/tests/API/Folders.php index 04e34eb..695e0f1 100644 --- a/tests/API/Folders.php +++ b/tests/API/Folders.php @@ -1,372 +1,372 @@ get('folders/test'); $code = self::$api->response_code(); $this->assertEquals(404, $code); // non-existing action self::$api->get('folders/' . kolab_api_tests::folder_uid('INBOX') . '/test'); $code = self::$api->response_code(); $this->assertEquals(404, $code); // existing action and folder, but wrong method self::$api->get('folders/' . kolab_api_tests::folder_uid('Mail-Test') . '/empty'); $code = self::$api->response_code(); $this->assertEquals(404, $code); } /** * Test listing all folders */ function test_folder_list_folders() { // get all folders self::$api->get('folders'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(15, $body); $this->assertSame('Calendar', $body[0]['fullpath']); $this->assertSame('event.default', $body[0]['type']); $this->assertSame(kolab_api_tests::folder_uid('Calendar'), $body[0]['uid']); $this->assertNull($body[0]['parent']); // test listing subfolders of specified folder self::$api->get('folders/' . kolab_api_tests::folder_uid('Calendar') . '/folders'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(1, $body); $this->assertSame('Calendar/Personal Calendar', $body[0]['fullpath']); $this->assertSame(kolab_api_tests::folder_uid('Calendar'), $body[0]['parent']); // get all folders with properties filter self::$api->get('folders', array('properties' => 'uid')); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(1, $body[0]); $this->assertSame(kolab_api_tests::folder_uid('Calendar'), $body[0]['uid']); } /** * Test folder delete */ function test_folder_delete() { // delete existing folder self::$api->delete('folders/' . kolab_api_tests::folder_uid('Mail-Test')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(204, $code); $this->assertSame('', $body); // and non-existing folder self::$api->delete('folders/12345'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); } /** * Test folder existence */ function test_folder_exists() { self::$api->head('folders/' . kolab_api_tests::folder_uid('INBOX')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); // and non-existing folder - deleted in test_folder_delete() self::$api->head('folders/' . kolab_api_tests::folder_uid('Mail-Test')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); } /** * Test folder update */ function test_folder_update() { $post = json_encode(array( 'name' => 'Mail-Test22', 'type' => 'mail' )); self::$api->put('folders/' . kolab_api_tests::folder_uid('Mail-Test2'), array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(kolab_api_tests::folder_uid('Mail-Test2'), $body['uid']); // move into an existing folder $post = json_encode(array( 'name' => 'Trash', )); self::$api->put('folders/' . kolab_api_tests::folder_uid('Mail-Test22'), array(), $post); $code = self::$api->response_code(); $this->assertEquals(500, $code); // change parent to an existing folder $post = json_encode(array( 'parent' => kolab_api_tests::folder_uid('Trash'), )); self::$api->put('folders/' . kolab_api_tests::folder_uid('Mail-Test22'), array(), $post); $code = self::$api->response_code(); $this->assertEquals(200, $code); } /** * Test folder create */ function test_folder_create() { $post = json_encode(array( 'name' => 'Test-create', 'type' => 'mail' )); self::$api->post('folders', array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(kolab_api_tests::folder_uid('Test-create'), $body['uid']); // folder already exists $post = json_encode(array( 'name' => 'Test-create', )); self::$api->post('folders', array(), $post); $code = self::$api->response_code(); $this->assertEquals(500, $code); // create a subfolder $post = json_encode(array( 'name' => 'Test', 'parent' => kolab_api_tests::folder_uid('Test-create'), 'type' => 'mail' )); self::$api->post('folders', array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(kolab_api_tests::folder_uid('Test-create/Test'), $body['uid']); // parent folder does not exists $post = json_encode(array( 'name' => 'Test-create-2', 'parent' => '123456789', )); self::$api->post('folders', array(), $post); $code = self::$api->response_code(); $this->assertEquals(404, $code); } /** * Test folder info */ function test_folder_info() { self::$api->get('folders/' . kolab_api_tests::folder_uid('INBOX')); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame('INBOX', $body['name']); $this->assertSame(kolab_api_tests::folder_uid('INBOX'), $body['uid']); } /** * Test folder create */ function test_folder_delete_objects() { $post = json_encode(array('10')); self::$api->post('folders/' . kolab_api_tests::folder_uid('Notes') . '/deleteobjects', array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); } /** * Test folder create */ function test_folder_empty() { self::$api->post('folders/' . kolab_api_tests::folder_uid('Trash') . '/empty'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); } /** * Test listing folder content */ function test_folder_list_objects() { self::$api->get('folders/' . kolab_api_tests::folder_uid('Calendar/Personal Calendar') . '/objects'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(array(), $body); // get all objects with properties filter self::$api->get('folders/' . kolab_api_tests::folder_uid('Notes') . '/objects', array('properties' => 'uid')); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(2, $body); $this->assertCount(1, $body[0]); $this->assertSame('1-1-1-1', $body[0]['uid']); } /** * Test counting folder content */ function test_folder_count_objects() { self::$api->head('folders/' . kolab_api_tests::folder_uid('INBOX') . '/objects'); $code = self::$api->response_code(); $body = self::$api->response_body(); $count = self::$api->response_header('X-Count'); $this->assertEquals(200, $code); $this->assertSame('', $body); - $this->assertSame(4, (int) $count); + $this->assertSame(5, (int) $count); // folder emptied in test_folder_empty() self::$api->head('folders/' . kolab_api_tests::folder_uid('Trash') . '/objects'); $count = self::$api->response_header('X-Count'); $this->assertSame(0, (int) $count); // one item removed in test_folder_delete_objects() self::$api->head('folders/' . kolab_api_tests::folder_uid('Notes') . '/objects'); $count = self::$api->response_header('X-Count'); $this->assertSame(2, (int) $count); } /** * Test moving objects from one folder to another */ function test_folder_move_objects() { $post = json_encode(array('100-100-100-100')); // invalid request: target == source self::$api->post('folders/' . kolab_api_tests::folder_uid('Calendar') . '/move/' . kolab_api_tests::folder_uid('Calendar'), array(), $post); $code = self::$api->response_code(); $this->assertEquals(422, $code); // move one object self::$api->post('folders/' . kolab_api_tests::folder_uid('Calendar') . '/move/' . kolab_api_tests::folder_uid('Calendar/Personal Calendar'), array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); self::$api->get('folders/' . kolab_api_tests::folder_uid('Calendar/Personal Calendar') . '/objects'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(1, $body); $this->assertSame('100-100-100-100', $body[0]['uid']); self::$api->get('folders/' . kolab_api_tests::folder_uid('Calendar') . '/objects'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(1, $body); $this->assertSame('101-101-101-101', $body[0]['uid']); // @TODO: the same for mail } } diff --git a/tests/API/Mails.php b/tests/API/Mails.php index 1271fec..00bd267 100644 --- a/tests/API/Mails.php +++ b/tests/API/Mails.php @@ -1,331 +1,331 @@ get('folders/' . kolab_api_tests::folder_uid('INBOX') . '/objects'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); - $this->assertSame(4, count($body)); + $this->assertSame(5, count($body)); $this->assertSame('1', $body[0]['uid']); $this->assertSame('"test" wurde aktualisiert', $body[0]['subject']); $this->assertSame('2', $body[1]['uid']); $this->assertSame('Re: dsda', $body[1]['subject']); } /** * Test mail existence check */ function test_mail_exists() { self::$api->head('mails/' . kolab_api_tests::folder_uid('INBOX') . '/1'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); // and non-existing mail self::$api->head('mails/' . kolab_api_tests::folder_uid('INBOX') . '/12345'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); } /** * Test mail info */ function test_mail_info() { self::$api->get('mails/' . kolab_api_tests::folder_uid('INBOX') . '/1'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame('1', $body['uid']); $this->assertSame('"test" wurde aktualisiert', $body['subject']); $this->assertSame(624, $body['size']); self::$api->get('mails/' . kolab_api_tests::folder_uid('INBOX') . '/6'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame('6', $body['uid']); } /** * Test counting mail attachments */ function test_count_attachments() { self::$api->head('mails/' . kolab_api_tests::folder_uid('INBOX') . '/2/attachments'); $code = self::$api->response_code(); $body = self::$api->response_body(); $count = self::$api->response_header('X-Count'); $this->assertEquals(200, $code); $this->assertSame('', $body); $this->assertSame(0, (int) $count); self::$api->head('mails/' . kolab_api_tests::folder_uid('INBOX') . '/6/attachments'); $code = self::$api->response_code(); $body = self::$api->response_body(); $count = self::$api->response_header('X-Count'); $this->assertEquals(200, $code); $this->assertSame('', $body); $this->assertSame(2, (int) $count); } /** * Test listing mail attachments */ function test_list_attachments() { self::$api->get('mails/' . kolab_api_tests::folder_uid('INBOX') . '/2/attachments'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(array(), $body); self::$api->get('mails/' . kolab_api_tests::folder_uid('INBOX') . '/6/attachments'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(2, $body); $this->assertSame('2', $body[0]['id']); $this->assertSame('text/plain', $body[0]['mimetype']); $this->assertSame('test.txt', $body[0]['filename']); $this->assertSame('attachment', $body[0]['disposition']); $this->assertSame(4, $body[0]['size']); } /** * Test mail create */ function test_mail_create() { $post = json_encode(array( 'subject' => 'Test summary', 'text' => 'This is the body.', )); self::$api->post('mails/' . kolab_api_tests::folder_uid('INBOX'), array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(1, $body); $this->assertTrue(!empty($body['uid'])); self::$created = $body['uid']; self::$api->get('mails/' . kolab_api_tests::folder_uid('INBOX') . '/' . self::$created); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame('Test summary', $body['subject']); $this->assertSame('This is the body.', $body['text']); // folder does not exists $post = json_encode(array( 'subject' => 'Test summary 2', )); self::$api->post('mails/' . kolab_api_tests::folder_uid('non-existing'), array(), $post); $code = self::$api->response_code(); $this->assertEquals(404, $code); // invalid object data $post = json_encode(array( 'test' => 'Test summary 2', )); self::$api->post('mails/' . kolab_api_tests::folder_uid('INBOX'), array(), $post); $code = self::$api->response_code(); $this->assertEquals(422, $code); // test HTML message creation $post = json_encode(array( 'subject' => 'HTML', 'html' => 'now it iÅ› HTML', )); self::$api->post('mails/' . kolab_api_tests::folder_uid('INBOX'), array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertTrue(!empty($body['uid'])); self::$api->get('mails/' . kolab_api_tests::folder_uid('INBOX') . '/' . $body['uid']); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame('HTML', $body['subject']); $this->assertRegexp('|now it iÅ› HTML|', (string) $body['html']); } /** * Test mail update */ function test_mail_update() { $post = json_encode(array( 'subject' => 'Modified summary', 'html' => 'now it is HTML', )); self::$api->put('mails/' . kolab_api_tests::folder_uid('INBOX') . '/' . self::$created, array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertTrue(!empty($body['uid'])); self::$api->get('mails/' . kolab_api_tests::folder_uid('INBOX') . '/' . $body['uid']); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame('Modified summary', $body['subject']); $this->assertRegexp('|now it is HTML|', (string) $body['html']); $this->assertSame('now it is HTML', trim($body['text'])); // test replacing message body in multipart/mixed message $post = json_encode(array( 'html' => 'now it is HTML', 'priority' => 5, )); self::$api->put('mails/' . kolab_api_tests::folder_uid('INBOX') . '/6', array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); self::$api->get('mails/' . kolab_api_tests::folder_uid('INBOX') . '/' . $body['uid']); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertRegexp('|now it is HTML|', (string) $body['html']); $this->assertSame('now it is HTML', trim($body['text'])); $this->assertSame(5, $body['priority']); } /** * Test mail submit */ function test_mail_submit() { // send the message to self $post = json_encode(array( 'subject' => 'Test summary', 'text' => 'This is the body.', 'from' => array( 'name' => "Test' user", 'address' => self::$api->username, ), 'to' => array( array( 'name' => "Test' user", 'address' => self::$api->username, ), ), )); self::$api->post('mails/submit', array(), $post); $code = self::$api->response_code(); $this->assertEquals(204, $code); // @TODO: test submitting an existing message } /** * Test mail delete */ function test_mail_delete() { // delete existing mail self::$api->delete('mails/' . kolab_api_tests::folder_uid('INBOX') . '/1'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(204, $code); $this->assertSame('', $body); // and non-existing mail self::$api->delete('mails/' . kolab_api_tests::folder_uid('INBOX') . '/12345'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); } } diff --git a/tests/Mapistore/Attachments.php b/tests/Mapistore/Attachments.php index c0d4003..ed98978 100644 --- a/tests/Mapistore/Attachments.php +++ b/tests/Mapistore/Attachments.php @@ -1,138 +1,181 @@ head('attachments/' . kolab_api_tests::mapi_uid('INBOX', true, 6, 2)); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); // and non-existing attachment self::$api->head('attachments/' . kolab_api_tests::mapi_uid('INBOX', true, 6, 2345)); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); // test attachments of non-mail objects self::$api->head('attachments/' . kolab_api_tests::mapi_uid('Calendar', true, '100-100-100-100', 3)); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); } /** * Test attachment info */ function test_attachment_info() { self::$api->get('attachments/' . kolab_api_tests::mapi_uid('INBOX', true, 6, 2)); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(kolab_api_tests::mapi_uid('INBOX', true, 6, 2), $body['id']); $this->assertSame('text/plain', $body['PidTagAttachMimeTag']); $this->assertSame('test.txt', $body['PidTagDisplayName']); $this->assertSame(4, $body['PidTagAttachSize']); $this->assertSame(1, $body['PidTagAttachMethod']); $this->assertSame('test', base64_decode($body['PidTagAttachDataBinary'])); // and non-existing attachment self::$api->get('attachments/' . kolab_api_tests::mapi_uid('INBOX', true, 6, 2345)); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); // test attachments of kolab objects self::$api->get('attachments/' . kolab_api_tests::mapi_uid('Calendar', true, '100-100-100-100', 3)); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(kolab_api_tests::mapi_uid('Calendar', true, '100-100-100-100', 3), $body['id']); $this->assertSame('image/jpeg', $body['PidTagAttachMimeTag']); $this->assertSame('photo-mini.jpg', $body['PidTagDisplayName']); $this->assertSame(793, $body['PidTagAttachSize']); $this->assertSame(1, $body['PidTagAttachMethod']); $this->assertSame('/9j/4AAQSkZJRgAB', substr($body['PidTagAttachDataBinary'], 0, 16)); } /** * Test attachment create */ function test_attachment_create() { - $this->markTestIncomplete('TODO'); + $post = json_encode(array( + 'PidTagAttachDataBinary' => 'R0lGODlhDwAPAIAAAMDAwAAAACH5BAEAAAAALAAAAAAPAA8AQAINhI+py+0Po5y02otnAQA7', + 'PidTagDisplayName' => 'image.gif', + )); + self::$api->post('attachments/' . kolab_api_tests::mapi_uid('Calendar', true, '100-100-100-100'), array(), $post); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + + $this->assertEquals(200, $code); + + self::$api->get('attachments/' . kolab_api_tests::mapi_uid('Calendar', true, '100-100-100-100', 4)); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + $body = json_decode($body, true); + + $this->assertSame(kolab_api_tests::mapi_uid('Calendar', true, '100-100-100-100', 4), $body['id']); + $this->assertSame('image/gif', $body['PidTagAttachMimeTag']); + $this->assertSame('image.gif', $body['PidTagDisplayName']); + $this->assertSame(54, $body['PidTagAttachSize']); + $this->assertSame(1, $body['PidTagAttachMethod']); + $this->assertSame('R0lGODlhDwAPAIAAAMDAwAAAACH5BAEAAAAALAAAAAAPAA8AQAINhI+py+0Po5y02otnAQA7', $body['PidTagAttachDataBinary']); } /** * Test attachment update */ function test_attachment_update() { - $this->markTestIncomplete('TODO'); + $post = json_encode(array( + 'PidTagAttachDataBinary' => base64_encode('test text file'), + 'PidTagDisplayName' => 'test.txt', + )); + self::$api->put('attachments/' . kolab_api_tests::mapi_uid('Calendar', true, '100-100-100-100', 4), array(), $post); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + + $this->assertEquals(200, $code); + + self::$api->get('attachments/' . kolab_api_tests::mapi_uid('Calendar', true, '100-100-100-100', 4)); + + $code = self::$api->response_code(); + $body = self::$api->response_body(); + $body = json_decode($body, true); + + $this->assertSame(kolab_api_tests::mapi_uid('Calendar', true, '100-100-100-100', 4), $body['id']); + $this->assertSame('text/plain', $body['PidTagAttachMimeTag']); + $this->assertSame('test.txt', $body['PidTagDisplayName']); + $this->assertSame(14, $body['PidTagAttachSize']); + $this->assertSame(1, $body['PidTagAttachMethod']); + $this->assertSame('test text file', base64_decode($body['PidTagAttachDataBinary'])); } /** * Test attachment delete */ function test_attachment_delete() { // delete existing attachment self::$api->delete('attachments/' . kolab_api_tests::mapi_uid('Tasks', true, '10-10-10-10', '3')); $code = self::$api->response_code(); $body = self::$api->response_body(); - $this->assertEquals(204, $code); - $this->assertSame('', $body); + $this->assertEquals(200, $code); // delete non-existing attachment in an existing object self::$api->delete('attachments/' . kolab_api_tests::mapi_uid('Tasks', true, '10-10-10-10', '3')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); } } diff --git a/tests/Mapistore/Folders.php b/tests/Mapistore/Folders.php index f2a31ae..8ce1bae 100644 --- a/tests/Mapistore/Folders.php +++ b/tests/Mapistore/Folders.php @@ -1,296 +1,296 @@ get('folders/1/folders'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(12, $body); $this->assertSame(kolab_api_tests::folder_uid('Calendar'), $body[0]['id']); $this->assertSame(kolab_api_tests::folder_uid('Calendar'), $body[1]['parent_id']); $this->assertNull($body[0]['parent_id']); $this->assertSame('IPF.Appointment', $body[0]['PidTagContainerClass']); $this->assertSame('IPF.Task', $body[10]['PidTagContainerClass']); // test listing subfolders of specified folder self::$api->get('folders/' . kolab_api_tests::folder_uid('Calendar') . '/folders'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(1, $body); $this->assertSame(kolab_api_tests::folder_uid('Calendar'), $body[0]['parent_id']); // get all folders with properties filter self::$api->get('folders/1/folders', array('properties' => 'id')); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(array('id' => kolab_api_tests::folder_uid('Calendar')), $body[0]); } /** * Test folder delete */ function test_folder_delete() { // delete existing folder self::$api->delete('folders/' . kolab_api_tests::folder_uid('Mail-Test')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(204, $code); $this->assertSame('', $body); // and non-existing folder self::$api->get('folders/12345'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); } /** * Test folder existence */ function test_folder_exists() { self::$api->head('folders/' . kolab_api_tests::folder_uid('INBOX')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); // and non-existing folder - deleted in test_folder_delete() self::$api->get('folders/' . kolab_api_tests::folder_uid('Mail-Test')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); } /** * Test folder update */ function test_folder_update() { $post = json_encode(array( 'PidTagDisplayName' => 'Mail-Test22', )); self::$api->put('folders/' . kolab_api_tests::folder_uid('Mail-Test2'), array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); // move into an existing folder $post = json_encode(array( 'PidTagDisplayName' => 'Trash', )); self::$api->put('folders/' . kolab_api_tests::folder_uid('Mail-Test22'), array(), $post); $code = self::$api->response_code(); $this->assertEquals(500, $code); // change parent to an existing folder $post = json_encode(array( 'parent_id' => kolab_api_tests::folder_uid('Trash'), )); self::$api->put('folders/' . kolab_api_tests::folder_uid('Mail-Test22'), array(), $post); $code = self::$api->response_code(); $this->assertEquals(200, $code); } /** * Test folder create */ function test_folder_create() { $post = json_encode(array( 'PidTagDisplayName' => 'Test-create', )); self::$api->post('folders', array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(kolab_api_tests::folder_uid('Test-create'), $body['id']); // folder already exists $post = json_encode(array( 'PidTagDisplayName' => 'Test-create', )); self::$api->post('folders', array(), $post); $code = self::$api->response_code(); $this->assertEquals(500, $code); // create a subfolder $post = json_encode(array( 'PidTagDisplayName' => 'Test', 'parent_id' => kolab_api_tests::folder_uid('Test-create'), )); self::$api->post('folders', array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(kolab_api_tests::folder_uid('Test-create/Test'), $body['id']); // parent folder does not exists $post = json_encode(array( 'PidTagDisplayName' => 'Test-create-2', 'parent_id' => '123456789', )); self::$api->post('folders', array(), $post); $code = self::$api->response_code(); $this->assertEquals(404, $code); } /** * Test folder info */ function test_folder_info() { self::$api->get('folders/' . kolab_api_tests::folder_uid('INBOX')); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame('INBOX', $body['PidTagDisplayName']); $this->assertSame(kolab_api_tests::folder_uid('INBOX'), $body['id']); } /** * Test folder create */ function test_folder_delete_objects() { $post = json_encode(array(array('id' => '10'))); self::$api->post('folders/' . kolab_api_tests::folder_uid('Notes') . '/deletemessages', array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); } /** * Test folder create */ function test_folder_empty() { self::$api->post('folders/' . kolab_api_tests::folder_uid('Trash') . '/empty'); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); } /** * Test listing folder content */ function test_folder_list_objects() { self::$api->get('folders/' . kolab_api_tests::folder_uid('Calendar/Personal Calendar') . '/messages'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(array(), $body); // get all objects with properties filter self::$api->get('folders/' . kolab_api_tests::folder_uid('Notes') . '/messages', array('properties' => 'id,collection')); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(2, $body[0]); $this->assertTrue(!empty($body[0]['id'])); $this->assertSame('notes', $body[0]['collection']); } /** * Test counting folder content */ function test_folder_count_objects() { self::$api->head('folders/' . kolab_api_tests::folder_uid('INBOX') . '/messages'); $code = self::$api->response_code(); $body = self::$api->response_body(); $count = self::$api->response_header('X-mapistore-rowcount'); $this->assertEquals(200, $code); $this->assertSame('', $body); - $this->assertSame(4, (int) $count); + $this->assertSame(5, (int) $count); // folder emptied in test_folder_empty() self::$api->head('folders/' . kolab_api_tests::folder_uid('Trash') . '/mssages'); $count = self::$api->response_header('X-mapistore-rowcount'); $this->assertSame(0, (int) $count); // one item removed in test_folder_delete_objects() self::$api->head('folders/' . kolab_api_tests::folder_uid('Notes') . '/messages'); $count = self::$api->response_header('X-mapistore-rowcount'); $this->assertSame(2, (int) $count); } } diff --git a/tests/Mapistore/Mails.php b/tests/Mapistore/Mails.php index d94e873..331f42a 100644 --- a/tests/Mapistore/Mails.php +++ b/tests/Mapistore/Mails.php @@ -1,277 +1,277 @@ get('folders/' . kolab_api_tests::folder_uid('INBOX') . '/messages'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); - $this->assertSame(4, count($body)); + $this->assertSame(5, count($body)); $this->assertSame(kolab_api_tests::mapi_uid('INBOX', true, '1'), $body[0]['id']); $this->assertSame(kolab_api_tests::folder_uid('INBOX'), $body[0]['parent_id']); $this->assertSame('mails', $body[0]['collection']); $this->assertSame('IPM.Note', $body[0]['PidTagMessageClass']); $this->assertSame('"test" wurde aktualisiert', $body[0]['PidTagSubject']); $this->assertSame(kolab_api_tests::mapi_uid('INBOX', true, '2'), $body[1]['id']); $this->assertSame(kolab_api_tests::folder_uid('INBOX'), $body[1]['parent_id']); $this->assertSame('IPM.Note', $body[1]['PidTagMessageClass']); $this->assertSame('Re: dsda', $body[1]['PidTagSubject']); // get all messages with properties filter self::$api->get('folders/' . kolab_api_tests::folder_uid('INBOX') . '/messages', array('properties' => 'id')); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(array('id' => kolab_api_tests::mapi_uid('INBOX', true, '1')), $body[0]); } /** * Test mail existence check */ function test_mail_exists() { self::$api->head('mails/' . kolab_api_tests::mapi_uid('INBOX', true, '1')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(200, $code); $this->assertSame('', $body); // and non-existing note self::$api->get('mails/' . kolab_api_tests::mapi_uid('INBOX', true, '12345')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); } /** * Test mail info */ function test_mail_info() { self::$api->get('mails/' . kolab_api_tests::mapi_uid('INBOX', true, '1')); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(kolab_api_tests::mapi_uid('INBOX', true, '1'), $body['id']); $this->assertSame(kolab_api_tests::folder_uid('INBOX'), $body['parent_id']); $this->assertSame('"test" wurde aktualisiert', $body['PidTagSubject']); $this->assertSame(624, $body['PidTagMessageSize']); $this->assertSame('IPM.Note', $body['PidTagMessageClass']); } /** * Test mail attachments count */ function test_count_attachments() { self::$api->head('mails/' . kolab_api_tests::mapi_uid('INBOX', true, '2') . '/attachments'); $code = self::$api->response_code(); $body = self::$api->response_body(); $count = self::$api->response_header('X-mapistore-rowcount'); $this->assertEquals(200, $code); $this->assertSame('', $body); $this->assertSame(0, (int) $count); self::$api->head('mails/' . kolab_api_tests::mapi_uid('INBOX', true, '6') . '/attachments'); $code = self::$api->response_code(); $body = self::$api->response_body(); $count = self::$api->response_header('X-mapistore-rowcount'); $this->assertEquals(200, $code); $this->assertSame('', $body); $this->assertSame(2, (int) $count); } /** * Test listing mail attachments */ function test_list_attachments() { self::$api->get('mails/' . kolab_api_tests::mapi_uid('INBOX', true, '2') . '/attachments'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertSame(array(), $body); self::$api->get('mails/' . kolab_api_tests::mapi_uid('INBOX', true, '6') . '/attachments'); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(2, $body); $this->assertSame(kolab_api_tests::mapi_uid('INBOX', true, '6', '2'), $body[0]['id']); $this->assertSame('attachments', $body[0]['collection']); $this->assertSame('text/plain', $body[0]['PidTagAttachMimeTag']); $this->assertSame('test.txt', $body[0]['PidTagDisplayName']); $this->assertSame('txt', $body[0]['PidTagAttachExtension']); $this->assertSame(4, $body[0]['PidTagAttachSize']); } /** * Test mail create */ function test_mail_create() { $post = json_encode(array( 'PidTagSubject' => 'Test summary', 'PidTagBody' => 'Test description' )); self::$api->post('mails/' . kolab_api_tests::folder_uid('INBOX'), array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertCount(1, $body); $this->assertTrue(!empty($body['id'])); // folder does not exist $post = json_encode(array( 'PidTagSubject' => 'Test summary 2', )); self::$api->post('mails/' . md5('non-existing'), array(), $post); $code = self::$api->response_code(); $this->assertEquals(404, $code); // invalid object data $post = json_encode(array( 'test' => 'Test summary 2', )); self::$api->post('mails/' . kolab_api_tests::folder_uid('INBOX'), array(), $post); $code = self::$api->response_code(); $this->assertEquals(422, $code); } /** * Test mail update */ function test_mail_update() { $post = json_encode(array( 'PidTagSubject' => 'Modified summary', 'PidTagBody' => 'Modified description' )); self::$api->put('mails/' . kolab_api_tests::mapi_uid('INBOX', true, '2'), array(), $post); $code = self::$api->response_code(); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertEquals(200, $code); $this->assertTrue(!empty($body['id'])); self::$api->get('mails/' . $body['id']); $body = self::$api->response_body(); $body = json_decode($body, true); $this->assertSame('Modified summary', $body['PidTagSubject']); $this->assertSame('Modified description', $body['PidTagBody']); } /** * Test mail submit */ function test_mail_submit() { // send the message to self $post = json_encode(array( 'PidTagSubject' => 'Test summary', 'PidTagBody' => 'This is the body.', /* 'from' => array( 'name' => "Test' user", 'address' => self::$api->username, ), */ 'recipients' => array( array( 'PidTagRecipientType' => 1, 'PidTagDisplayName' => "Test user", 'PidTagSmtpAddress' => self::$api->username, ), ), )); self::$api->post('mails/submit', array(), $post); $code = self::$api->response_code(); $this->assertEquals(204, $code); } /** * Test mail delete */ function test_mail_delete() { // delete existing note self::$api->delete('mails/' . kolab_api_tests::mapi_uid('INBOX', true, '1')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(204, $code); $this->assertSame('', $body); // and non-existing note self::$api->get('mails/' . kolab_api_tests::mapi_uid('INBOX', true, '12345')); $code = self::$api->response_code(); $body = self::$api->response_body(); $this->assertEquals(404, $code); $this->assertSame('', $body); } } diff --git a/tests/data/data.json b/tests/data/data.json index 2bd546e..a295db4 100644 --- a/tests/data/data.json +++ b/tests/data/data.json @@ -1,72 +1,72 @@ { "folders": { "INBOX": { "type": "mail.inbox", - "items": ["1","2","5","6"] + "items": ["1","2","5","6","7"] }, "Trash": { "type": "mail.wastebasket", "items": ["3","4"] }, "Drafts": { "type": "mail.drafts" }, "Sent": { "type": "mail.sentitems" }, "Junk": { "type": "mail.junkemail" }, "Calendar": { "type": "event.default", "items": ["100-100-100-100","101-101-101-101"] }, "Calendar/Personal Calendar": { "type": "event" }, "Contacts": { "type": "contact.default", "items": ["a-b-c-d"] }, "Files": { "type": "file.default" }, "Files2": { "type": "file" }, "Notes": { "type": "note.default", "items": ["1-1-1-1","2-2-2-2"] }, "Tasks": { "type": "task.default", "items":["10-10-10-10","20-20-20-20"] }, "Configuration": { "type": "configuration", "items": ["98-98-98-98","99-99-99-99"] }, "Mail-Test": { "type": "mail" }, "Mail-Test2": { "type": "mail" } }, "tags": { "tag1": { "members": ["1", "10-10-10-10", "1-1-1-1", "a-b-c-d"] }, "tag2": { } } } diff --git a/tests/data/mail/7 b/tests/data/mail/7 new file mode 100644 index 0000000..f1105b0 --- /dev/null +++ b/tests/data/mail/7 @@ -0,0 +1,48 @@ +MIME-Version: 1.0 +Content-Type: multipart/mixed; + boundary="=_d96d550b5c171a1ae50c82ddcb6adb65" +Date: Wed, 06 May 2015 13:16:49 +0200 +From: "German, Mark" +To: "Manager, Jane" +Subject: plain text with attachments +Message-ID: <2f517a3f9004aedb70de32d54b0451e7@example.org> +X-Sender: mark.german@example.org + +--=_d96d550b5c171a1ae50c82ddcb6adb65 +Content-Transfer-Encoding: 7bit +Content-Type: text/plain; charset=US-ASCII; + format=flowed + +test content +--=_d96d550b5c171a1ae50c82ddcb6adb65 +Content-Transfer-Encoding: base64 +Content-Type: text/plain; + name=test.txt +Content-Disposition: attachment; + filename=test.txt; + size=4 + +dGVzdA== +--=_d96d550b5c171a1ae50c82ddcb6adb65 +Content-Transfer-Encoding: base64 +Content-Type: image/jpeg; + name=photo-mini.jpg +Content-Disposition: attachment; + filename=photo-mini.jpg; + size=793 + +/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAoHBwkHBgoJCAkLCwoMDxkQDw4ODx4WFxIZJCAmJSMg +IyIoLTkwKCo2KyIjMkQyNjs9QEBAJjBGS0U+Sjk/QD3/2wBDAQsLCw8NDx0QEB09KSMpPT09PT09 +PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT3/wgARCAAYABgDAREA +AhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAABAUD/8QAFgEBAQEAAAAAAAAAAAAAAAAAAwIB/9oA +DAMBAAIQAxAAAAGjlGNp6hVmsTcdm6jmSrLH/8QAGxAAAwACAwAAAAAAAAAAAAAAAQIDABESISP/ +2gAIAQEAAQUCqOQaA0GJlUFs7c00q1bznQK1oFp//8QAGREAAwEBAQAAAAAAAAAAAAAAAAERAgMS +/9oACAEDAQE/Acqs8ZJGYIdJROC2h6rp/8QAGhEAAwADAQAAAAAAAAAAAAAAAAERAhAxEv/aAAgB +AgEBPwFuHplqHrHh0aYsYj//xAAgEAABBAEEAwAAAAAAAAAAAAAAAQIREjEQIjIzQVFh/9oACAEB +AAY/Aq+zzI62UlBKuqp2YH/dIRjpNvI//8QAHBABAQEAAwADAAAAAAAAAAAAAREAITFBUXGR/9oA +CAEBAAE/IZNdtXiPkOK/UY5yPZdCtQFD3GF3S/mg+36zcxM67zxjhyXf/9oADAMBAAIAAwAAABAU +fgX/AP/EABgRAQEBAQEAAAAAAAAAAAAAAAERACEx/9oACAEDAQE/EONrEmeHFVDDY4AT2624BQmP +b//EABkRAQEBAQEBAAAAAAAAAAAAAAERADEQQf/aAAgBAgEBPxCC5Bt3R5fpm1cnGUzLHf/EAB8Q +AQEAAgIDAAMAAAAAAAAAAAERACExQVFxgZGhsf/aAAgBAQABPxAtWaL2BtT9H3BdmhtH1x8w1QFB +woc5u4oJcpqPrBACtyKVdfzHhmnXZYygBKAJFrNTveSICmoJy9LdauUhKVIN8L41+c//2Q== +--=_d96d550b5c171a1ae50c82ddcb6adb65-- diff --git a/tests/lib/kolab_api_backend.php b/tests/lib/kolab_api_backend.php index 39518ab..107292c 100644 --- a/tests/lib/kolab_api_backend.php +++ b/tests/lib/kolab_api_backend.php @@ -1,909 +1,1028 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ class kolab_api_backend { /** * Singleton instace of kolab_api_backend * * @var kolab_api_backend */ static protected $instance; public $delimiter = '/'; public $username = 'user@example.org'; public $storage; public $user; + public $db = array(); - protected $db = array(); protected $folder = array(); protected $data = array(); /** * This implements the 'singleton' design pattern * * @return kolab_api_backend The one and only instance */ static function get_instance() { if (!self::$instance) { self::$instance = new kolab_api_backend; self::$instance->startup(); // init AFTER object was linked with self::$instance } return self::$instance; } /** * Class initialization */ public function startup() { $api = kolab_api::get_instance(); $db_file = $api->config->get('temp_dir') . '/tests.db'; if (file_exists($db_file)) { $db = file_get_contents($db_file); $this->db = unserialize($db); } $json = file_get_contents(__DIR__ . '/../data/data.json'); $this->data = json_decode($json, true); $this->folders = $this->parse_folders_list($this->data['folders']); if (!array_key_exists('tags', $this->db)) { $this->db['tags'] = $this->data['tags']; } $this->user = new kolab_api_user; $this->storage = $this; } /** * Authenticate a user * * @param string Username * @param string Password * * @return bool */ public function authenticate($username, $password) { return true; } /** * Get list of folders * * @param string $type Folder type * * @return array|bool List of folders, False on backend failure */ public function folders_list($type = null) { return array_values($this->folders); } /** * Returns folder type * * @param string $uid Folder unique identifier * @param string $with_suffix Enable to not remove the subtype * * @return string Folder type */ public function folder_type($uid, $with_suffix = false) { $folder = $this->folders[$uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } $type = $folder['type'] ?: 'mail'; if (!$with_suffix) { list($type, ) = explode('.', $type); } return $type; } /** * Returns objects in a folder * * @param string $uid Folder unique identifier * * @return array Objects (of type kolab_api_mail or array) * @throws kolab_api_exception */ public function objects_list($uid) { $folder = $this->folders[$uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } $result = array(); $is_mail = empty($folder['type']) || preg_match('/^mail/', $folder['type']); foreach ((array) $folder['items'] as $id) { $object = $this->object_get($uid, $id); if ($is_mail) { $object = new kolab_api_message($object->headers, array('is_header' => true)); } $result[] = $object; } return $result; } /** * Counts objects in a folder * * @param string $uid Folder unique identifier * * @return int Objects count * @throws kolab_api_exception */ public function objects_count($uid) { $folder = $this->folders[$uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } return count($folder['items']); } /** * Delete objects in a folder * * @param string $uid Folder unique identifier * @param string|array $set List of object IDs or "*" for all * * @throws kolab_api_exception */ public function objects_delete($uid, $set) { $folder = $this->folders[$uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } if ($set === '*') { foreach ((array) $this->folders[$uid]['items'] as $i) { unset($this->db['messages'][$i]); } $this->folders[$uid]['items'] = array(); $this->db['items'][$uid] = array(); } else { $this->folders[$uid]['items'] = array_values(array_diff($this->folders[$uid]['items'], $set)); foreach ($set as $i) { unset($this->db['items'][$uid][$i]); unset($this->db['messages'][$i]); } } $this->db['folders'][$uid]['items'] = $this->folders[$uid]['items']; $this->save_db(); } /** * Move objects into another folder * * @param string $uid Folder unique identifier * @param string $target_uid Target folder unique identifier * @param string|array $set List of object IDs or "*" for all * * @throws kolab_api_exception */ public function objects_move($uid, $target_uid, $set) { $folder = $this->folders[$uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } $target = $this->folders[$target_uid]; if (!$target) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } if ($set === "*") { $set = $this->folders[$uid]['items']; } // @TODO: we should check if all objects from the set exist $diff = array_values(array_diff($this->folders[$uid]['items'], $set)); $this->folders[$uid]['items'] = $diff; $this->db['folders'][$uid]['items'] = $diff; $diff = array_values(array_merge((array) $this->folders[$target_uid]['items'], $set)); $this->folders[$target_uid]['items'] = $diff; $this->db['folders'][$target_uid]['items'] = $diff; foreach ($set as $i) { if ($this->db['items'][$uid][$i]) { $this->db['items'][$target_uid][$i] = $this->db['items'][$uid][$i]; unset($this->db['items'][$uid][$i]); } } $this->save_db(); } /** * Get object data * * @param string $folder_uid Folder unique identifier * @param string $uid Object identifier * * @return kolab_api_mail|array Object data * @throws kolab_api_exception */ public function object_get($folder_uid, $uid) { $folder = $this->folders[$folder_uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } if (!in_array($uid, (array) $folder['items'])) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } if ($data = $this->db['items'][$folder_uid][$uid]) { return $data; } list($type,) = explode('.', $folder['type']); $file = $this->get_file_content($uid, $type); if (empty($file)) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } // get message content and parse it $file = str_replace("\r?\n", "\r\n", $file); $params = array('uid' => $uid, 'folder' => $folder_uid); $object = new kolab_api_message($file, $params); // get assigned tag-relations $tags = array(); foreach ($this->db['tags'] as $tag_name => $tag) { if (in_array($uid, (array) $tag['members'])) { $tags[] = $tag_name; } } if ($type != 'mail') { $object = $object->to_array($type); $object['categories'] = $tags; } else { $object = new kolab_api_message($object); $object->categories = $tags; } return $object; } /** * Create an object * * @param string $folder_uid Folder unique identifier * @param string $data Object data * @param string $type Object type * * @throws kolab_api_exception */ public function object_create($folder_uid, $data, $type) { $folder = $this->folders[$folder_uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } /* if (strpos($folder['type'], $type) !== 0) { throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); } */ $uid = microtime(true); if (is_array($data)) { $categories = $data['categories']; $data['uid'] = $uid; $this->db['items'][$folder_uid][$uid] = $data; } else { $categories = $data->categories; $uid = $data->save($folder['fullpath']); } if (!empty($categories)) { foreach ($categories as $cat) { if (!$this->db['tags'][$cat]) { $this->db['tags'][$cat] = array(); } if (!in_array($uid, (array) $this->db['tags'][$cat]['members'])) { $this->db['tags'][$cat]['members'][] = $uid; } } } $this->folders[$folder_uid]['items'][] = $uid; $this->db['folders'][$folder_uid]['items'] = $this->folders[$folder_uid]['items']; $this->save_db(); return $uid; } /** * Update an object * * @param string $folder_uid Folder unique identifier * @param string $data Object data * @param string $type Object type * * @throws kolab_api_exception */ public function object_update($folder_uid, $data, $type) { $folder = $this->folders[$folder_uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } /* if (strpos($folder['type'], $type) !== 0) { throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); } */ - if (is_array($data)) { $uid = $data['uid']; if (array_key_exists('categories', $data)) { foreach ($this->db['tags'] as $tag_name => $tag) { if (($idx = array_search($tag_name, (array) $data['categories'])) !== false) { unset($data['categories'][$idx]); continue; } $this->db['tags'][$tag_name]['members'] = array_diff((array)$this->db['tags'][$tag_name]['members'], array($data['uid'])); } foreach ((array) $data['categories'] as $cat) { $this->db['tags'][$cat] = array('members' => array($data['uid'])); } } // remove _formatobj which is problematic in serialize/unserialize unset($data['_formatobj']); $this->db['items'][$folder_uid][$uid] = $data; $this->save_db(); } else { $uid = $data->save($folder['fullpath']); $this->folders[$folder_uid]['items'][] = $uid; $this->db['folders'][$folder_uid]['items'] = $this->folders[$folder_uid]['items']; $this->save_db(); } return $uid; } /** * Get attachment body * * @param mixed $object Object data (from self::object_get()) * @param string $part_id Attachment part identifier * @param mixed $mode NULL to return a string, -1 to print body * or file pointer to save the body into * * @return string Attachment body if $mode=null * @throws kolab_api_exception */ public function attachment_get($object, $part_id, $mode = null) { $msg_uid = is_array($object) ? $object['uid'] : $object->uid; // object is a mail message if (!($object instanceof kolab_api_message)) { $object = $object['_message']; } - // check if it's not deleted - if (in_array($msg_uid . ":" . $part_id, (array) $this->db['deleted_attachments'])) { - throw new kolab_api_exception(kolab_api_exception::INVALID_REQUEST); - } - $body = $object->get_part_body($part_id); if (!$mode) { return $body; } else if ($mode === -1) { echo $body; } } /** * Delete an attachment from the message * * @param mixed $object Object data (from self::object_get()) * @param string $id Attachment identifier * - * @return boolean|string True or message UID (if changed) + * @return string Message/object UID * @throws kolab_api_exception */ public function attachment_delete($object, $id) { $msg_uid = is_array($object) ? $object['uid'] : $object->uid; $key = $msg_uid . ":" . $part_id; - // check if it's not deleted - if (in_array($key, (array) $this->db['deleted_attachments'])) { + // object is a mail message + if (!($object instanceof kolab_api_message)) { + $object = $object['_message']; + } + + if ($object->get_part_body($id) === null) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } + $uid = $object->attachment_delete($id); + + // change UID only for mail messages + if (!is_numeric($msg_uid)) { + $this->db['messages'][$msg_uid] = $this->db['messages'][$uid]; + unset($this->db['messages'][$uid]); + $this->save_db(); + $uid = $msg_uid; + } + + if ($msg_uid != $uid) { + $folder_uid = $object->folder; + $this->folders[$folder_uid]['items'][] = $uid; + $this->db['folders'][$folder_uid]['items'] = $this->folders[$folder_uid]['items']; + $this->save_db(); + } + + return $uid; + } + + /** + * Create an attachment and add to a message/object + * + * @param mixed $object Object data (from self::object_get()) + * @param rcube_message_part $attachment Attachment data + * + * @return string Message/object UID + * @throws kolab_api_exception + */ + public function attachment_create($object, $attachment) + { + $msg_uid = is_array($object) ? $object['uid'] : $object->uid; + // object is a mail message if (!($object instanceof kolab_api_message)) { $object = $object['_message']; } - if ($object->get_part_body($id) === null) { - throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); + $uid = $object->attachment_add($attachment); + $folder_uid = $object->folder; + + // change UID only for mail messages + if (!is_numeric($msg_uid)) { + $this->db['messages'][$msg_uid] = $this->db['messages'][$uid]; + unset($this->db['messages'][$uid]); + + $params = array('uid' => $msg_uid, 'folder' => $folder_uid); + $object = new kolab_api_message(base64_decode($this->db['messages'][$msg_uid]), $params); + $object = $object->to_array($this->folders[$folder_uid]['type']); +// $object['categories'] = $tags; + unset($object['_formatobj']); + $this->db['items'][$folder_uid][$msg_uid] = $object; + + $this->save_db(); + $uid = $msg_uid; } - $this->db['deleted_attachments'][] = $key; - $this->save_db(); + if ($msg_uid != $uid) { + $this->folders[$folder_uid]['items'][] = $uid; + $this->db['folders'][$folder_uid]['items'] = $this->folders[$folder_uid]['items']; + $this->save_db(); + } + + return $uid; + } + + /** + * Update an attachment in a message/object + * + * @param mixed $object Object data (from self::object_get()) + * @param rcube_message_part $attachment Attachment data + * + * @return string Message/object UID + * @throws kolab_api_exception + */ + public function attachment_update($object, $attachment) + { + $msg_uid = is_array($object) ? $object['uid'] : $object->uid; + + // object is a mail message + if (!($object instanceof kolab_api_message)) { + $object = $object['_message']; + } + + $uid = $object->attachment_update($attachment); + $folder_uid = $object->folder; + + // change UID only for mail messages + if (!is_numeric($msg_uid)) { + $this->db['messages'][$msg_uid] = $this->db['messages'][$uid]; + unset($this->db['messages'][$uid]); + + $params = array('uid' => $msg_uid, 'folder' => $folder_uid); + $object = new kolab_api_message(base64_decode($this->db['messages'][$msg_uid]), $params); + $object = $object->to_array($this->folders[$folder_uid]['type']); +// $object['categories'] = $tags; + unset($object['_formatobj']); + $this->db['items'][$folder_uid][$msg_uid] = $object; + + $this->save_db(); + $uid = $msg_uid; + } + + if ($msg_uid != $uid) { + $this->folders[$folder_uid]['items'][] = $uid; + $this->db['folders'][$folder_uid]['items'] = $this->folders[$folder_uid]['items']; + $this->save_db(); + } + + return $uid; } /** * Creates a folder * * @param string $name Folder name (UTF-8) * @param string $parent Parent folder identifier * @param string $type Folder type * * @return bool Folder identifier on success */ public function folder_create($name, $parent = null, $type = null) { $folder = $name; if ($parent) { $parent_folder = $this->folders[$parent]; if (!$parent_folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } $folder = $parent_folder['fullpath'] . $this->delimiter . $folder; } $uid = kolab_api_tests::folder_uid($folder, false); // check if folder exists if ($this->folders[$uid]) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } $this->folders[$uid] = array( 'name' => $name, 'fullpath' => $folder, 'parent' => $parent ? kolab_api_tests::folder_uid($parent, false) : null, 'uid' => $uid, 'type' => $type ? $type : 'mail', ); $this->db['folders'][$uid] = $this->folders[$uid]; $this->save_db(); return $uid; } /** * Updates a folder * * @param string $uid Folder identifier * @param array $updates Updates (array with keys type, subscribed, active) * * @throws kolab_api_exception */ public function folder_update($uid, $updates) { $folder = $this->folders[$uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } foreach ($updates as $idx => $value) { $this->db['folders'][$uid][$idx] = $value; $this->folders[$uid][$idx] = $value; } $this->save_db(); } /** * Renames/moves a folder * * @param string $old_name Folder name (UTF8) * @param string $new_name New folder name (UTF8) * * @throws kolab_api_exception */ public function folder_rename($old_name, $new_name) { $old_uid = kolab_api_tests::folder_uid($old_name, false); $new_uid = kolab_api_tests::folder_uid($new_name, false); $folder = $this->folders[$old_uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } if ($this->folders[$new_uid]) { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } $path = explode($this->delimiter, $new_name); $folder['fullpath'] = $new_name; $folder['name'] = array_pop($path); unset($this->folders[$old_uid]); $this->folders[$new_uid] = $folder; $this->db['folders'][$new_uid] = $folder; $this->db['deleted'][] = $old_uid; $this->save_db(); } /** * Deletes folder * * @param string $uid Folder UID * * @return bool True on success, False on failure * @throws kolab_api_exception */ public function folder_delete($uid) { $folder = $this->folders[$uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } unset($this->folders[$uid]); $this->db['deleted'][] = $uid; $this->save_db(); } /** * Folder info * * @param string $uid Folder UID * * @return array Folder information * @throws kolab_api_exception */ public function folder_info($uid) { $folder = $this->folders[$uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } // some info is not very interesting here ;) unset($folder['items']); return $folder; } /** * Returns IMAP folder name with full path * * @param string $uid Folder identifier * * @return string Folder full path (UTF-8) */ public function folder_uid2path($uid) { if ($uid === null || $uid === '') { throw new kolab_api_exception(kolab_api_exception::SERVER_ERROR); } $folder = $this->folders[$uid]; if (!$folder) { throw new kolab_api_exception(kolab_api_exception::NOT_FOUND); } return $folder['fullpath']; } /** * Parse folders list into API format */ protected function parse_folders_list($list) { $folders = array(); foreach ($list as $path => $folder) { $uid = kolab_api_tests::folder_uid($path, false); if (!empty($this->db['deleted']) && in_array($uid, $this->db['deleted'])) { continue; } if (strpos($path, $this->delimiter)) { $list = explode($this->delimiter, $path); $name = array_pop($list); $parent = implode($this->delimiter, $list); $parent_id = kolab_api_tests::folder_uid($parent, false); } else { $parent_id = null; $name = $path; } $data = array( 'name' => $name, 'fullpath' => $path, 'parent' => $parent_id, 'uid' => $uid, ); if (!empty($this->db['folders']) && !empty($this->db['folders'][$uid])) { $data = array_merge($data, $this->db['folders'][$uid]); } $folders[$uid] = array_merge($folder, $data); } foreach ((array) $this->db['folders'] as $uid => $folder) { if (!$folders[$uid]) { $folders[$uid] = $folder; } } // sort folders uasort($folders, array($this, 'sort_folder_comparator')); return $folders; } /** * Callback for uasort() that implements correct * locale-aware case-sensitive sorting */ protected function sort_folder_comparator($str1, $str2) { $path1 = explode($this->delimiter, $str1['fullpath']); $path2 = explode($this->delimiter, $str2['fullpath']); foreach ($path1 as $idx => $folder1) { $folder2 = $path2[$idx]; if ($folder1 === $folder2) { continue; } return strcoll($folder1, $folder2); } } /** * Save current database state */ - protected function save_db() + public function save_db() { $api = kolab_api::get_instance(); $db_file = $api->config->get('temp_dir') . '/tests.db'; $db = serialize($this->db); file_put_contents($db_file, $db); } /** * Wrapper for rcube_imap::set_flag() */ public function set_flag($uid, $flag) { $flag = strtoupper($flag); $folder_uid = $this->folder_uid($folder); $flags = (array) $this->db['flags'][$uid]; if (strpos($flag, 'UN') === 0) { $flag = substr($flag, 3); $flags = array_values(array_diff($flags, array($flag))); } else { $flags[] = $flag; $flags = array_unique($flags); } $this->db['flags'][$uid] = $flags; $this->save_db(); return true; } /** * Wrapper for rcube_imap::save_message() */ public function save_message($folder, $streams) { $folder_uid = $this->folder_uid($folder); $uid = '3' . count($this->db['messages']) . preg_replace('/^[0-9]+\./', '', microtime(true)); $content = ''; foreach ($streams as $stream) { rewind($stream); $content .= stream_get_contents($stream); } $this->db['messages'][$uid] = base64_encode($content); $this->save_db(); return $uid; } /** * Wrapper for rcube_imap::delete_message() */ public function delete_message($uid, $folder) { $folder_uid = $this->folder_uid($folder); - $this->folders[$folder_uid]['items'] = array_values(array_diff($this->folders[$folder_uid]['items'], array($uid))); + $this->folders[$folder_uid]['items'] = array_values(array_diff((array)$this->folders[$folder_uid]['items'], array($uid))); unset($this->db['items'][$folder_uid][$uid]); unset($this->db['messages'][$uid]); $this->db['folders'][$folder_uid]['items'] = $this->folders[$folder_uid]['items']; $this->save_db(); return true; } /** * Wrapper for rcube_imap::get_raw_body */ public function get_raw_body($uid, $fp = null, $part = null) { - $file = $this->get_file_content($uid, 'mail'); + $file = $this->get_file_content($uid); $file = explode("\r\n\r\n", $file, 2); - // we assume $part=TEXT + if (stripos($part, 'TEXT') !== false) { + $body = $file[1]; + + if (preg_match('/^([0-9]+)/', $part, $m)) { + if (preg_match('/boundary="?([^"]+)"?/', $file[0], $mm)) { + $parts = explode('--' . $mm[1], $body); + $parts = explode("\r\n\r\n", $parts[$m[1]], 2); + $body = $parts[1]; + } + else { + $body = ''; + } + } + } if ($fp) { - fwrite($fp, $file[1]); + fwrite($fp, $body); return true; } else { - echo $file[1]; + return $body; } } /** * Wrapper for rcube_imap::get_raw_headers */ public function get_raw_headers($uid) { - $file = $this->get_file_content($uid, 'mail'); + $file = $this->get_file_content($uid); $file = explode("\r\n\r\n", $file, 2); return $file[0]; } /** * Wrapper for rcube_imap::set_folder */ public function set_folder($folder) { // do nothing } /** * Find folder UID by its name */ protected function folder_uid($name) { foreach ($this->folders as $uid => $folder) { if ($folder['fullpath'] == $name) { return $uid; } } } /** * Get sample message from tests/data dir */ - protected function get_file_content($uid, $type) + protected function get_file_content($uid, $type = null) { if ($file = $this->db['messages'][$uid]) { $file = base64_decode($file); } else { + if (empty($type)) { + foreach (array('mail', 'event', 'task', 'note', 'contact') as $t) { + $file = __DIR__ . '/../data/' . $t . '/' . $uid; + if (file_exists($file)) { + $type = $t; break; + } + } + } + $file = file_get_contents(__DIR__ . '/../data/' . $type . '/' . $uid); } return $file; } } /** * Dummy class imitating rcube_user */ class kolab_api_user { public function get_username($type) { $api = kolab_api_backend::get_instance(); list($local, $domain) = explode('@', $api->username); if ($type == 'domain') { return $domain; } else if ($type == 'local') { return $local; } return $api->username; } public function get_user_id() { return 10; } public function get_identity() { return array( 'email' => 'user@example.org', 'name' => 'Test User', ); } } diff --git a/tests/lib/kolab_api_message.php b/tests/lib/kolab_api_message.php index 0ace403..047025d 100644 --- a/tests/lib/kolab_api_message.php +++ b/tests/lib/kolab_api_message.php @@ -1,238 +1,256 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ /** * Mock class emulating rcube_message and kolab_api_mail * With some additional functionality for testing */ class kolab_api_message extends kolab_api_mail { public $attachments = array(); public $parts = array(); public $mime_parts = array(); public $folder; public $uid; public $headers; /** * Class initialization */ public function __construct($content = null, $params = array()) { // kolab_api_mail mode if (is_object($content)) { $this->message = $content; $this->headers = $content->headers; $this->mime_parts = $content->mime_parts; $params['folder'] = $content->folder ?: $content->headers->folder; $params['uid'] = $content->uid ?: $content->headers->uid; } // rcube_message mode else if ($content) { $this->message = rcube_mime::parse_message($content); $this->headers = rcube_message_header::from_array($this->message->headers); - $this->headers->ctype = $this->message->mimetype; + + $this->message->headers = $this->headers; + $this->headers->ctype = $this->message->mimetype; foreach ((array) $params as $idx => $val) { $this->headers->{$idx} = $val; } $this->headers->size = strlen($content); $this->set_mime_parts($this->message); } if ($this->message) { foreach ((array) $this->message->parts as $part) { - if ($part->filename) { + if ($part->filename || $part->disposition == 'attachment') { $this->attachments[] = $part; } $this->parts[$part->mime_id] = $part; } + + $this->message->attachments = $this->attachments; } foreach ((array) $params as $idx => $val) { $this->{$idx} = $val; + $this->message->{$idx} = $val; } } /** * Returns body of the message part */ - public function get_part_body($id) + public function get_part_body($id, $formatted = false, $max_bytes = 0, $mode = null) { if (!$id) { - return $this->message->body; + $body = $this->message->body; + } + else { + $body = $this->mime_parts[$id]->body; } - return $this->mime_parts[$id]->body; + if (is_resource($mode)) { + fwrite($mode, $body); + } + else { + return $body; + } } /** * Convert message into Kolab object * * @return array Kolab object */ public function to_array() { $object_type = kolab_format::mime2object_type($this->headers->others['x-kolab-type']); $content_type = kolab_format::KTYPE_PREFIX . $object_type; $attachments = array(); // get XML part foreach ((array)$this->attachments as $part) { if (!$xml && ($part->mimetype == $content_type || preg_match('!application/([a-z.]+\+)?xml!', $part->mimetype))) { $xml = $this->get_part_body($part->mime_id); } - else if ($part->filename || $part->content_id) { + else if ($part->filename || $part->content_id || $part->disposition == 'attachment') { $key = $part->content_id ? trim($part->content_id, '<>') : $part->filename; $size = null; // Use Content-Disposition 'size' as for the Kolab Format spec. if (isset($part->d_parameters['size'])) { $size = $part->d_parameters['size']; } // we can trust part size only if it's not encoded else if ($part->encoding == 'binary' || $part->encoding == '7bit' || $part->encoding == '8bit') { $size = $part->size; } // looks like MimeDecode does not support d_parameters (?) else if (preg_match('/size=([0-9]+)/', $part->headers['content-disposition'], $m)) { $size = $m[1]; } + if (!$key) { + $key = $part->mime_id; + } + $attachments[$key] = array( 'id' => $part->mime_id, 'name' => $part->filename, 'mimetype' => $part->mimetype, + 'encoding' => $part->encoding, 'size' => $size, ); } } // check kolab format version $format_version = $this->headers->others['x-kolab-mime-version']; if (empty($format_version)) { list($xmltype, $subtype) = explode('.', $object_type); $xmlhead = substr($xml, 0, 512); // detect old Kolab 2.0 format if (strpos($xmlhead, '<' . $xmltype) !== false && strpos($xmlhead, 'xmlns=') === false) $format_version = '2.0'; else $format_version = '3.0'; // assume 3.0 } // get Kolab format handler for the given type $format = kolab_format::factory($object_type, $format_version, $xml); if (is_a($format, 'PEAR_Error')) { return false; } // load Kolab object from XML part $format->load($xml); if ($format->is_valid()) { $object = $format->to_array(array('_attachments' => $attachments)); $object['_formatobj'] = $format; $object['_type'] = $object_type; $object['_attachments'] = $attachments; $object['_message'] = $this; // $object['_msguid'] = $msguid; // $object['_mailbox'] = $this->name; return $object; } return false; } /** * Send the message stream using configured method */ protected function send_message_stream($stream) { return true; } /** * Get rcube_message object of the assigned message */ protected function get_message() { return $this->message; } /** * rcube_message::first_html_part() emulation. */ public function first_html_part(&$part = null, $enriched = false) { foreach ((array) $this->mime_parts as $part) { if (!$part->filename && $part->mimetype == 'text/html') { return $this->get_part_body($part->mime_id, true); } } $part = null; } /** * rcube_message::first_text_part() emulation. */ public function first_text_part(&$part = null, $strict = false) { // no message structure, return complete body if (empty($this->mime_parts)) { return $this->message->body; } foreach ((array) $this->mime_parts as $part) { if (!$part->filename && $part->mimetype == 'text/plain') { return $this->get_part_body($part->mime_id, true); } } $part = null; } /** * Fill aflat array with references to all parts, indexed by part numbers */ private function set_mime_parts(&$part) { if (strlen($part->mime_id)) { $this->mime_parts[$part->mime_id] = &$part; } if (is_array($part->parts)) { for ($i = 0; $i < count($part->parts); $i++) { $this->set_mime_parts($part->parts[$i]); } } } } diff --git a/tests/lib/kolab_api_request.php b/tests/lib/kolab_api_request.php index f34c3b3..c090dff 100644 --- a/tests/lib/kolab_api_request.php +++ b/tests/lib/kolab_api_request.php @@ -1,228 +1,233 @@ | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak | +--------------------------------------------------------------------------+ */ class kolab_api_request { public $username; public $token_header = 'X-Session-Token'; private $request; private $base_url; /** * Class initialization */ public function __construct($base_url, $user, $pass) { require_once 'HTTP/Request2.php'; $this->base_url = $base_url; $this->request = new HTTP_Request2(); $this->username = $user; $this->request->setConfig(array( 'ssl_verify_peer' => false, 'ssl_verify_host' => false, )); $this->request->setAuth($user, $pass); } /** * Set request header */ public function set_header($name, $value) { $this->request->setHeader($name, $value); } /** * API's GET request. * * @param string URL * @param array URL arguments * * @return HTTP_Request2_Response Response object */ public function get($url, $args = array()) { $url = $this->build_url($url, $args); $this->reset(); $this->request->setMethod(HTTP_Request2::METHOD_GET); return $this->get_response($url); } /** * API's HEAD request. * * @param string URL * @param array URL arguments * * @return HTTP_Request2_Response Response object */ public function head($url, $args = array()) { $url = $this->build_url($url, $args); $this->reset(); $this->request->setMethod(HTTP_Request2::METHOD_HEAD); return $this->get_response($url); } /** * API's DELETE request. * * @param string URL * @param array URL arguments * * @return HTTP_Request2_Response Response object */ public function delete($url, $args = array()) { $url = $this->build_url($url, $args); $this->reset(); $this->request->setMethod(HTTP_Request2::METHOD_DELETE); return $this->get_response($url); } /** * API's POST request. * * @param string URL * @param array URL arguments * @param string POST body + * @param string Request Content-Type (for file uploads testing) * * @return HTTP_Request2_Response Response object */ - public function post($url, $url_args = array(), $post = '') + public function post($url, $url_args = array(), $post = '', $ctype = '') { $url = $this->build_url($url, $url_args); $this->reset(); $this->request->setMethod(HTTP_Request2::METHOD_POST); $this->request->setBody($post); + if ($ctype) { + $this->request->setHeader('Content-Type', $ctype); + } + return $this->get_response($url); } /** * API's PUT request. * * @param string URL * @param array URL arguments * @param string PUT body * * @return HTTP_Request2_Response Response object */ public function put($url, $url_args = array(), $post = '') { $url = $this->build_url($url, $url_args); $this->reset(); $this->request->setMethod(HTTP_Request2::METHOD_PUT); $this->request->setBody($post); return $this->get_response($url); } public function response_code() { return $this->response->getStatus(); } public function response_header($name) { return $this->response->getHeader($name); } public function response_body() { return $this->response->getBody(); } /** * @param string Action URL * @param array GET parameters (hash array: name => value) * * @return Net_URL2 URL object */ private function build_url($action, $args) { $url = $this->base_url; if ($action) { $url .= '/' . $action; } $url = new Net_URL2($url); if (!empty($args)) { $url->setQueryVariables($args); } return $url; } /** * Reset old request data */ private function reset() { // reset old body $this->request->setBody(''); unset($this->response); } /** * HTTP Response handler. * * @param Net_URL2 URL object * * @return HTTP_Request2_Response Response object */ private function get_response($url) { $this->request->setUrl($url); if ($this->session_token) { $this->request->setHeader($this->token_header, $this->session_token); } $this->response = $this->request->send(); if ($token = $this->response->getHeader($this->token_header)) { $this->session_token = $token; } return $this->response; } }