public function generate_image($type, $filter_chain) { try { $original = new midcom_db_attachment($this->attachment); } catch (midcom_error $e) { $e->log(); return false; } $found_derived = false; try { $derived = new midcom_db_attachment($this->{$type}); $found_derived = true; } catch (midcom_error $e) { $derived = new midcom_db_attachment(); $derived->parentguid = $original->parentguid; $derived->title = $original->title; $derived->mimetype = $original->mimetype; $derived->name = $type . '_' . $original->name; } $imagefilter = new midcom_helper_imagefilter($original); if (!$imagefilter->process_chain($filter_chain)) { throw new midcom_error('Image processing failed'); } if (!$found_derived) { if (!$derived->create()) { throw new midcom_error('Failed to create derived image: ' . midcom_connection::get_error_string()); } $this->{$type} = $derived->id; $this->update(); } return $imagefilter->write($derived); }
/** * Handler method for confirming file deleting for the requested file * * @param string $handler_id Name of the used handler * @param mixed $args Array containing the variable arguments passed to the handler * @param mixed &$data Data passed to the show method * @return boolean Indicating successful request */ public function _handler_delete($handler_id, array $args, array &$data) { $this->_object = midcom::get('dbfactory')->get_object_by_guid($args[0]); $this->_object->require_do('midgard:update'); $this->_object->require_do('midgard:attachments'); midcom::get('auth')->require_user_do('midgard.admin.asgard:manage_objects', null, 'midgard_admin_asgard_plugin'); $data['filename'] = $args[1]; $this->_file = $this->_get_file($data['filename']); if (!$this->_file) { throw new midcom_error_notfound("Attachment '{$data['filename']}' of object {$this->_object->guid} was not found."); } // Require delete privilege $this->_file->require_do('midgard:delete'); if (isset($_POST['f_cancel'])) { midcom::get('uimessages')->add(midcom::get('i18n')->get_string('midgard.admin.asgard', 'midgard.admin.asgard'), midcom::get('i18n')->get_string('delete cancelled', 'midgard.admin.asgard')); return new midcom_response_relocate("__mfa/asgard/object/attachments/{$this->_object->guid}/{$data['filename']}/"); } if (isset($_POST['f_confirm'])) { if ($this->_file->delete()) { midcom::get('uimessages')->add(midcom::get('i18n')->get_string('midgard.admin.asgard', 'midgard.admin.asgard'), sprintf(midcom::get('i18n')->get_string('file %s deleted', 'midgard.admin.asgard'), $data['filename'])); return new midcom_response_relocate("__mfa/asgard/object/attachments/{$this->_object->guid}/"); } } midgard_admin_asgard_plugin::bind_to_object($this->_object, $handler_id, $data); }
/** * Creates a new attachment at the current object and returns it for usage. * * @param midcom_core_dbaobject $object The DBA object we're working on * @param string $name The name of the attachment. * @param string $title The title of the attachment. * @param string $mimetype The MIME-Type of the attachment. * @return midcom_db_attachment The created attachment or false on failure. */ public static function create_attachment(midcom_core_dbaobject $object, $name, $title, $mimetype) { if (!$object->id) { debug_add('Cannot create attachments on a non-persistant object.', MIDCOM_LOG_WARN); return false; } if (!$object->can_do('midgard:update') || !$object->can_do('midgard:attachments')) { debug_add("Failed to set parameters, midgard:update or midgard:attachments on the " . get_class($object) . " {$object->guid} not granted for the current user.", MIDCOM_LOG_ERROR); return false; } $attachment = new midcom_db_attachment(); $attachment->name = $name; $attachment->title = $title; $attachment->mimetype = $mimetype; $attachment->parentguid = $object->guid; $result = $attachment->create(); if (!$result || !$attachment->id) { debug_add("Could not create the attachment '{$name}' for " . get_class($object) . " {$object->guid}: " . midcom_connection::get_error_string(), MIDCOM_LOG_INFO); debug_add('Return code was: ' . $result); return false; } return $attachment; }
/** * Update an existing attachment with a new file (this keeps GUIDs stable). * * @param string $identifier The identifier of the attachment to update. * @param string $tmpname The name of the source file. * @param string $filename The filename to use after processing. * @param string $title The new title of the attachment, set this to null to * keep the original title unchanged. * @param string $mimetype The new MIME Type of the file, set this to null to * keep the original title unchanged. If you are unsure of the mime type, * set this to '' not null, this will enforce a redetection. * @param boolean $autodelete Set this to true (the default) to automatically delete the * file after successful processing. * @return boolean Indicating success. */ function update_attachment($identifier, $filename, $title, $mimetype, $tmpname, $autodelete = true) { if (!file_exists($tmpname)) { debug_add("Cannot add attachment, the file {$tmpname} was not found.", MIDCOM_LOG_INFO); return false; } if (!$this->file_sanity_checks($tmpname, $filename)) { // the method will log errors and raise uimessages as needed return false; } $filename = midcom_db_attachment::safe_filename($filename, false); $handle = @fopen($tmpname, 'r'); if (!$handle) { debug_add("Cannot add attachment, could not open {$tmpname} for reading.", MIDCOM_LOG_INFO); if (isset($php_errormsg)) { debug_add("Last PHP error was: {$php_errormsg}", MIDCOM_LOG_INFO); } return false; } if (!$this->update_attachment_by_handle($identifier, $filename, $title, $mimetype, $handle, true, $tmpname)) { debug_add('Failed to create attachment, see above for details.'); return false; } if ($autodelete) { if (!@unlink($tmpname)) { debug_add('Failed to automatically delete the source file, ignoring silently.', MIDCOM_LOG_WARN); if (isset($php_errormsg)) { debug_add("Last PHP error was: {$php_errormsg}", MIDCOM_LOG_WARN); } } } return true; }
/** * Automatically convert the uploaded file to a web-compatible type. Uses * only the first image of multi-page uploads (like PDFs) and populates the * _target_mimetype member accordingly. The original_tmpname file is manipulated * directly. * * Uploaded GIF, PNG and JPEG files are left untouched. * * In case of any conversions being done, the new extension will be appended * to the uploaded file. * * @return boolean Indicating success */ function _auto_convert_to_web_type() { debug_add("\$this->_original_mimetype: {$this->_original_mimetype}"); switch (preg_replace('/;.+$/', '', $this->_original_mimetype)) { case 'image/png': case 'image/gif': case 'image/jpeg': debug_add('No conversion necessary we already have a web mime type'); return true; case 'application/postscript': case 'application/pdf': $this->_target_mimetype = 'image/png'; $conversion = 'png'; break; default: $this->_target_mimetype = 'image/jpeg'; $conversion = 'jpg'; break; } debug_add("\$conversion={$conversion}"); if (!$this->imagemagick_available()) { throw new midcom_error('DM2 type image requires ImageMagick for manipulation operations, see debug log for details'); } // Prevent double .jpg.jpg in case of trouble file the get_mimetype() if (!preg_match("/\\.{$conversion}\$/", $this->_filename)) { $this->_filename .= ".{$conversion}"; // Make sure there is only one extension on the file ?? $this->_filename = midcom_db_attachment::safe_filename($this->_filename, true); } if ($this->_filter) { return $this->_filter->convert($conversion); } }
/** * Include all text/css attachments of current style to MidCOM headers */ function add_database_head_elements() { static $called = false; if ($called) { return; } $style = $this->get_style(); $mc = midcom_db_attachment::new_collector('parentguid', $style->guid); $mc->add_constraint('mimetype', '=', 'text/css'); $attachments = $mc->get_values('name'); foreach ($attachments as $filename) { // TODO: Support media types midcom::get('head')->add_stylesheet(midcom_connection::get_url('self') . "midcom-serveattachmentguid-{$guid}/{$filename}"); } $called = true; }
private function _upload_image(array $file, org_openpsa_slideshow_image_dba $image) { $attachment = new midcom_db_attachment(); $attachment->name = midcom_db_attachment::safe_filename($file['name']); $attachment->title = $_POST['title']; $attachment->mimetype = $file['type']; $attachment->parentguid = $image->guid; if (!$attachment->create() || !$attachment->copy_from_file($file['tmp_name'])) { throw new midcom_error('Failed to create attachment: ' . midcom_connection::get_error_string()); } $this->_response->filename = $attachment->name; $image->attachment = $attachment->id; $image->generate_image('thumbnail', $this->_config->get('thumbnail_filter')); $image->generate_image('image', $this->_config->get('image_filter')); $image->update(); }
private function _process_serveattachmentguid($value) { if ($this->_context->parser->argc > 1) { debug_add('Too many arguments remaining for serve_attachment.', MIDCOM_LOG_ERROR); } $attachment = new midcom_db_attachment($value); if (!$attachment->can_do('midgard:autoserve_attachment')) { throw new midcom_error_notfound('Failed to access attachment: Autoserving denied.'); } $this->serve_attachment($attachment); midcom::get()->finish(); _midcom_stop_request(); }
public static function render_fileinfo($object, $field) { $output = ''; $identifiers = explode(',', $object->get_parameter('midcom.helper.datamanager2.type.blobs', 'guids_' . $field)); if (empty($identifiers)) { return $output; } $host_prefix = midcom::get()->get_host_prefix(); foreach ($identifiers as $identifier) { $parts = explode(':', $identifier); if (sizeof($parts) != 2) { continue; } $guid = $parts[1]; try { $attachment = new midcom_db_attachment($guid); $url = $host_prefix . '/midcom-serveattachmentguid-' . $attachment->guid . '/' . $attachment->name; $stat = $attachment->stat(); $filesize = midcom_helper_misc::filesize_to_string($stat[7]); $mimetype = org_openpsa_documents_document_dba::get_file_type($attachment->mimetype); $mimetype_icon = midcom_helper_misc::get_mime_icon($attachment->mimetype); $output .= '<span class="org_openpsa_helpers_fileinfo">'; $output .= '<a href="' . $url . '" class="icon"><img src="' . $mimetype_icon . '" alt="' . $mimetype . '" /></a>'; $output .= '<a href="' . $url . '" class="filename">' . $attachment->name . '</a>'; $output .= '<span class="mimetype">' . $mimetype . '</span>'; $output .= '<span class="filesize">' . $filesize . '</span>'; $output .= "</span>\n"; } catch (midcom_error $e) { $e->log(); continue; } $output .= ''; } return $output; }
/** * Return next object in URL path */ public function get_object() { if ($this->argc == 0) { // No arguments left return false; } if (empty($this->url)) { $object_url = "{$this->argv[0]}/"; } else { $object_url = "{$this->url}/{$this->argv[0]}/"; } if (array_key_exists($object_url, $this->objects)) { // Remove this component from path $this->argc -= 1; array_shift($this->argv); // Set as current object $this->url = $object_url; $this->current_object = $this->objects[$object_url]; return $this->objects[$object_url]; } $qb = midcom_db_topic::new_query_builder(); $qb->add_constraint('name', '=', $this->argv[0]); $qb->add_constraint('up', '=', $this->current_object->id); if ($qb->count() == 0) { //last load returned ACCESS DENIED, no sense to dig deeper if ($qb->denied > 0) { midcom_connection::set_error(MGD_ERR_ACCESS_DENIED); return false; } // No topics matching path, check for attachments $att_qb = midcom_db_attachment::new_query_builder(); $att_qb->add_constraint('name', '=', $this->argv[0]); $att_qb->add_constraint('parentguid', '=', $this->current_object->guid); if ($att_qb->count() == 0) { // allow for handler switches to work return false; } $atts = $att_qb->execute(); // Remove this component from path $this->argc -= 1; array_shift($this->argv); // Set as current object $this->url = $object_url; $this->current_object = $atts[0]; $this->objects[$object_url] = $this->current_object; return $this->objects[$object_url]; } $topics = $qb->execute(); // Set to current topic $this->current_object = $topics[0]; $this->objects[$object_url] = $this->current_object; if ($GLOBALS['midcom_config']['symlinks'] && !empty($this->current_object->symlink)) { try { $topic = midcom_db_topic::get_cached($this->current_object->symlink); $this->current_object = $topic; } catch (midcom_error $e) { debug_add("Could not get target for symlinked topic #{$this->current_object->id}: " . $e->getMessage(), MIDCOM_LOG_ERROR); } } // TODO: Remove $this->check_style_inheritance($this->current_object); // Remove this component from path $this->argc -= 1; array_shift($this->argv); $this->url .= $this->objects[$object_url]->name . '/'; return $this->objects[$object_url]; }
/** * @dataProvider provider_safe_filename */ public function test_safe_filename($input, $extension, $output) { $converted = midcom_db_attachment::safe_filename($input, $extension); $this->assertEquals($converted, $output); }
public function write(midcom_db_attachment $target) { $src = fopen($this->_filename, 'r'); if (!$src) { debug_add("Could not open file '{$this->_filename}' for reading", MIDCOM_LOG_ERROR); return false; } if (!$target->copy_from_handle($src)) { debug_add("copy_from_handle() failed", MIDCOM_LOG_ERROR); fclose($src); return false; } fclose($src); return true; }
<?php $nap = new midcom_helper_nav(); ?> <ul class="slideshow-subfolders"> <?php foreach ($data['subfolders'] as $i => $folder) { $napdata = $nap->get_node($folder->id); echo '<li>'; echo '<a href="' . $napdata[MIDCOM_NAV_ABSOLUTEURL] . '">'; if (null !== $data['thumbnails'][$i]) { $thumbnail = new midcom_db_attachment($data['thumbnails'][$i]->thumbnail); echo '<img src="' . midcom_db_attachment::get_url($thumbnail) . '" alt="' . $folder->title . '"/>'; } echo '<span class="subfolder-title">' . $folder->extra . "</span>\n"; echo "</a>\n"; echo "</li>\n"; } ?> </ul>
private function _run_search(&$data) { $qb = midcom_db_attachment::new_query_builder(); $query = str_replace('*', '%', $data['query']); $qb->begin_group('OR'); $qb->add_constraint('name', 'LIKE', $query); $qb->add_constraint('title', 'LIKE', $query); $qb->add_constraint('mimetype', 'LIKE', $query); $qb->end_group(); $this->_search_results = $qb->execute(); midcom::get('head')->add_jsonload("jQuery('.midcom_helper_imagepopup_search_result_item').dm2ImagePopupConvert();"); }
/** * Adds the image to the type. Loads and processes the $tmpname file on disk. * * @param string $filename The name of the image attachment to be created. * @param string $tmpname The file to load. * @param string $title The title of the image. * @param boolean $autodelete If this is true (the default), the temporary file will * be deleted after postprocessing and attachment-creation. * @return boolean Indicating success. */ function set_image($filename, $tmpname, $title, $autodelete = true) { // Ensure that the filename is URL safe and contains only one extension $filename = midcom_db_attachment::safe_filename($filename, true); $this->_pending_attachments = $this->attachments; // Prepare Internal Members $this->title = $title; $this->_filename = $filename; $this->_original_tmpname = $tmpname; $this->_original_mimetype = midcom_helper_misc::get_mimetype($this->_original_tmpname); $this->_filter = new midcom_helper_imagefilter(); if (array_key_exists('archival', $this->_pending_attachments)) { // We never touch the archival version after it has been uploaded unset($this->_pending_attachments['archival']); } else { if (!$this->save_archival_image()) { debug_add("Failed to store the archival image for the uploaded file {$filename} in {$tmpname}, aborting type processing.", MIDCOM_LOG_ERROR); // Could not store even the archival image properly, clean up and abort $this->delete_all_attachments(); return false; } } if (!$this->_filter->set_file($this->_original_tmpname)) { debug_add("this->_filter->set_file('{$this->_original_tmpname}') returned failure, aborting type processing.", MIDCOM_LOG_ERROR); // NOTE: absense of delete_all_attachments is intentional return false; } $this->_preprocess_raw(); if (!$this->_auto_convert_to_web_type()) { debug_add("failed to convert to web type, aborting type processing.", MIDCOM_LOG_ERROR); // NOTE: absense of delete_all_attachments is intentional return false; } $this->_add_thumbnail_to_derived_images(); if (!$this->_save_main_image()) { debug_add("failed to save 'main' image, aborting type processing.", MIDCOM_LOG_ERROR); // NOTE: absense of delete_all_attachments is intentional return false; } if (!$this->_save_derived_images()) { debug_add("failed to save derived images, aborting type processing.", MIDCOM_LOG_ERROR); // NOTE: absense of delete_all_attachments is intentional return false; } // Clear up all attachments no longer in use $this->_clean_pending_attachments(); if ($autodelete) { unlink($this->_original_tmpname); } return true; }
echo sprintf($data['l10n_midcom']->get('edit %s'), $data['l10n']->get('slideshow')); ?> </h1> <input type="file" multiple="multiple" id="upload_field" /> <input type="button" id="reverse" value="<?php echo $data['l10n']->get('reverse order'); ?> " /> <div id="item_container"> <?php foreach ($data['images'] as $image) { try { $attachment = new midcom_db_attachment($image->thumbnail); $url = midcom_db_attachment::get_url($attachment); $original = new midcom_db_attachment($image->attachment); $name = $original->name; } catch (midcom_error $e) { $url = MIDCOM_STATIC_URL . '/stock-icons/mime/gnome-text-blank.png'; $name = $data['l10n']->get('attachment missing'); } ?> <div class="entry existing-entry" id="image-&(image.guid);"> <div class="thumbnail"> <img src="&(url);" alt="&(name);" /> </div> <div class="details"> <span class="controls"> <span class="action image-delete"></span> <span class="action image-cancel-delete"></span>
public static function render_and_attach_pdf(org_openpsa_invoices_invoice_dba $invoice) { if ($invoice->date == 0 || $invoice->deliverydate == 0) { $time = time(); if ($invoice->date == 0) { $invoice->date = $time; } if ($invoice->deliverydate == 0) { $invoice->deliverydate = $time; } $invoice->update(); } // renders the pdf and attaches it to the invoice $client_class = midcom_baseclasses_components_configuration::get('org.openpsa.invoices', 'config')->get('invoice_pdfbuilder_class'); if (!class_exists($client_class)) { debug_add('Could not find PDF renderer, aborting silently', MIDCOM_LOG_INFO); return false; } $pdf_builder = new $client_class($invoice); // tmp filename $tmp_dir = $GLOBALS["midcom_config"]["midcom_tempdir"]; $title = str_replace("#", "", $invoice->get_label()); $tmp_file = $tmp_dir . "/" . $title . ".pdf"; // render pdf to tmp filename $render = $pdf_builder->render($tmp_file); // cleanup old attachments $pdf_files = org_openpsa_helpers::get_attachment_urls($invoice, "pdf_file"); if (count($pdf_files) > 0) { foreach ($pdf_files as $guid => $url) { $attachment = new midcom_db_attachment($guid); $attachment->delete(); } } $attachment = $invoice->create_attachment($title . '.pdf', $title, "application/pdf"); if (!$attachment) { debug_add("Failed to create invoice attachment for pdf", MIDCOM_LOG_ERROR); return false; } $copy = $attachment->copy_from_file($tmp_file); if (!$copy) { debug_add("Failed to copy pdf from " . $tmp_file . " to attachment", MIDCOM_LOG_ERROR); return false; } // set parameter for datamanager to find the pdf if (!$invoice->set_parameter("midcom.helper.datamanager2.type.blobs", "guids_pdf_file", $attachment->guid . ":" . $attachment->guid) || !$attachment->set_parameter('org.openpsa.invoices', 'auto_generated', md5_file($tmp_file))) { debug_add("Failed to create attachment parameters, last midgard error was: " . midcom_connection::get_error_string(), MIDCOM_LOG_ERROR); return false; } return true; }
/** * Deleted callback, triggers watches on the parent(!) object. */ public function _on_deleted() { if ($GLOBALS['midcom_config']['attachment_cache_enabled']) { // Remove attachment cache $filename = midcom_db_attachment::get_cache_path($this, false); if (!is_null($filename) && file_exists($filename)) { @unlink($filename); } } $object = $this->get_parent(); if ($object !== null) { midcom::get('componentloader')->trigger_watches(MIDCOM_OPERATION_DBA_UPDATE, $object); } }
function set_video($filename, $tmpname, $title, $autodelete = true) { if (empty($filename)) { debug_add("filename must not be empty", MIDCOM_LOG_ERROR); return false; } // Ensure that the filename is URL safe and contains only one extension $filename = midcom_db_attachment::safe_filename($filename, true); return $this->_set_video($filename, $tmpname, $title, $autodelete); }
<?php midcom::get('auth')->require_admin_user(); midcom::get()->disable_limits(); $qb = midcom_db_attachment::new_query_builder(); $qb->add_order('metadata.created', 'DESC'); echo "<p>STARTING...</p>\n"; $atts = $qb->execute_unchecked(); echo "<p>" . count($atts) . " attachments to process...</p>\n"; foreach ($atts as $att) { $att->file_to_cache(); } echo "<p>DONE</p>\n";