function testElggGetFileSimpletype() { $tests = array('x-world/x-svr' => 'general', 'application/msword' => 'document', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'document', 'application/vnd.oasis.opendocument.text' => 'document', 'application/pdf' => 'document', 'application/ogg' => 'audio', 'text/css' => 'document', 'text/plain' => 'document', 'audio/midi' => 'audio', 'audio/mpeg' => 'audio', 'image/jpeg' => 'image', 'image/bmp' => 'image', 'video/mpeg' => 'video', 'video/quicktime' => 'video'); foreach ($tests as $mime_type => $simple_type) { $this->assertEqual($simple_type, elgg_get_file_simple_type($mime_type)); } }
/** * Returns the category of a file from its MIME type * * @param string $mime_type The MIME type * * @return string 'document', 'audio', 'video', or 'general' if the MIME type is unrecognized * @deprecated 1.10 Use elgg_get_file_simple_type() */ function file_get_general_file_type($mime_type) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use elgg_get_file_simple_type()', '1.10'); return elgg_get_file_simple_type($mime_type); }
/** * Writes contents of the uploaded file to an instance of ElggFile * * @note Note that this function moves the file and populates properties, * but does not call ElggFile::save(). * * @note This method will automatically assign a filename on filestore based * on the upload time and filename. By default, the file will be written * to /file directory on owner's filestore. You can change this directory, * by setting 'filestore_prefix' property of the ElggFile instance before * calling this method. * * @param UploadedFile $upload Uploaded file object * @return bool */ public function acceptUploadedFile(UploadedFile $upload) { if (!$upload->isValid()) { return false; } $old_filestorename = ''; if ($this->exists()) { $old_filestorename = $this->getFilenameOnFilestore(); } $originalfilename = $upload->getClientOriginalName(); $this->originalfilename = $originalfilename; if (empty($this->title)) { $this->title = htmlspecialchars($this->originalfilename, ENT_QUOTES, 'UTF-8'); } $this->upload_time = time(); $prefix = $this->filestore_prefix ?: 'file'; $prefix = trim($prefix, '/'); $filename = elgg_strtolower("{$prefix}/{$this->upload_time}{$this->originalfilename}"); $this->setFilename($filename); $this->filestore_prefix = $prefix; $hook_params = ['file' => $this, 'upload' => $upload]; $uploaded = _elgg_services()->hooks->trigger('upload', 'file', $hook_params); if ($uploaded !== true && $uploaded !== false) { $filestorename = $this->getFilenameOnFilestore(); try { $uploaded = $upload->move(pathinfo($filestorename, PATHINFO_DIRNAME), pathinfo($filestorename, PATHINFO_BASENAME)); } catch (FileException $ex) { _elgg_services()->logger->error($ex->getMessage()); $uploaded = false; } } if ($uploaded) { if ($old_filestorename && $old_filestorename != $this->getFilenameOnFilestore()) { // remove old file unlink($old_filestorename); } $mime_type = $this->detectMimeType(null, $upload->getClientMimeType()); $this->setMimeType($mime_type); $this->simpletype = elgg_get_file_simple_type($mime_type); _elgg_services()->events->triggerAfter('upload', 'file', $this); return true; } return false; }
/** * Populates entity doc with default index fields * * @param DocumentInterface $doc Solr document * @param ElggEntity $entity Elgg entity * @return DocumentInterface */ function elgg_solr_prepare_entity_doc(DocumentInterface $doc, ElggEntity $entity) { $doc->id = $entity->guid; $doc->type = $entity->type; $doc->subtype = (string) $entity->getSubtype(); $doc->owner_guid = $entity->owner_guid; $doc->container_guid = $entity->container_guid; $doc->access_id = $entity->access_id; $doc->title = elgg_strip_tags($entity->title); $doc->name = elgg_strip_tags($entity->name); $doc->description = elgg_strip_tags($entity->description); $doc->time_created = $entity->time_created; $doc->time_updated_i = $entity->time_updated; $doc = elgg_solr_add_tags($doc, $entity); $doc->enabled = $entity->enabled; if (is_callable([$entity, 'hasIcon'])) { $doc->has_icon_b = $entity->hasIcon('small'); } else { $doc->has_icon_b = (bool) $entity->icontime; } if ($entity instanceof ElggFile) { $mimetype = (string) $entity->getMimeType(); $doc->simpletype_s = (string) elgg_get_file_simple_type($mimetype); $doc->mimetype_s = $mimetype; $doc->originalfilename_s = $entity->originalfilename; if ($entity->exists()) { $doc->exists_b = true; $doc->filestorename_s = $entity->getFilenameOnFilestore(); $doc->filesize_i = (int) $entity->getSize(); } else { $doc->exists_b = false; } } // Store comment/reply thread information to allow grouping if ($entity instanceof ElggComment) { $container = $entity->getContainerEntity(); while ($container instanceof ElggComment) { $container = $container->getContainerEntity(); } $doc->responses_thread_i = $container->guid; } else { $doc->responses_thread_i = $entity->guid; } // Store comment/reply guids $responses = []; $responses_batch = new ElggBatch('elgg_get_entities', ['types' => 'object', 'subtypes' => ['comment', 'discussion_reply'], 'container_guid' => $entity->guid, 'limit' => 0, 'callback' => false]); foreach ($responses_batch as $response) { $responses[] = $response->guid; } $doc->responses_is = $responses; $doc->responses_count_i = count($responses); $doc->likes_i = $entity->countAnnotations('likes'); $params = array('entity' => $entity); $doc = elgg_trigger_plugin_hook('elgg_solr:index', $entity->type, $params, $doc); if ($entity->getSubtype()) { $doc = elgg_trigger_plugin_hook('elgg_solr:index', "{$entity->type}:{$entity->getSubtype()}", $params, $doc); } return $doc; }
<?php $file_input = elgg_extract('file', $_FILES); $filename = $file_input['name']; if (empty($filename) || elgg_extract('error', $file_input) !== 0) { register_error(elgg_echo('upload:error:unknown')); forward(REFERER); } $file = new \AssetFile(); $file->setFilename('asset_library/' . $filename); $file->open('write'); $file->write(get_uploaded_file('file')); $file->close(); $file->save(); $file->mimetype = (new \Elgg\Filesystem\MimeTypeDetector())->getType($file->getFilenameOnFilestore(), $file->getMimeType()); $file->simpletype = elgg_get_file_simple_type($file->mimetype); $file->save(); forward(REFERER);
/** * Parses simple type of the upload * @return string */ public function parseSimpleType() { return elgg_get_file_simple_type($this->detectMimeType()); }
/** * Parses simple type of the upload * @return string */ public function parseSimpleType() { if (is_callable('elgg_get_file_simple_type')) { return elgg_get_file_simple_type($this->detectMimeType()); } $mime_type = $this->detectMimeType(); switch ($mime_type) { case "application/msword": case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": case "application/pdf": return "document"; case "application/ogg": return "audio"; } if (preg_match('~^(audio|image|video)/~', $mime_type, $m)) { return $m[1]; } if (0 === strpos($mime_type, 'text/') || false !== strpos($mime_type, 'opendocument')) { return "document"; } // unrecognized MIME return "general"; }
/** * Save uploaded files * * @param string $input_name Form input name * @param array $attributes File attributes * @return ElggFile[] */ protected function saveUploadedFiles($input_name, array $attributes = []) { $files = []; $uploaded_files = $this->getUploadedFiles($input_name); $subtype = elgg_extract('subtype', $attributes, 'file', false); unset($attributes['subtype']); $class = get_subtype_class('object', $subtype); if (!$class || !class_exists($class) || !is_subclass_of($class, ElggFile::class)) { $class = ElggFile::class; } foreach ($uploaded_files as $upload) { if (!$upload->isValid()) { $error = new \stdClass(); $error->error = elgg_get_friendly_upload_error($upload->getError()); $files[] = $error; continue; } $file = new $class(); $file->subtype = $subtype; foreach ($attributes as $key => $value) { $file->{$key} = $value; } $old_filestorename = ''; if ($file->exists()) { $old_filestorename = $file->getFilenameOnFilestore(); } $originalfilename = $upload->getClientOriginalName(); $file->originalfilename = $originalfilename; if (empty($file->title)) { $file->title = htmlspecialchars($file->originalfilename, ENT_QUOTES, 'UTF-8'); } $file->upload_time = time(); $prefix = $file->filestore_prefix ?: 'file'; $prefix = trim($prefix, '/'); $filename = elgg_strtolower("{$prefix}/{$file->upload_time}{$file->originalfilename}"); $file->setFilename($filename); $file->filestore_prefix = $prefix; $hook_params = ['file' => $file, 'upload' => $upload]; $uploaded = _elgg_services()->hooks->trigger('upload', 'file', $hook_params); if ($uploaded !== true && $uploaded !== false) { $filestorename = $file->getFilenameOnFilestore(); try { $uploaded = $upload->move(pathinfo($filestorename, PATHINFO_DIRNAME), pathinfo($filestorename, PATHINFO_BASENAME)); } catch (FileException $ex) { elgg_log($ex->getMessage(), 'ERROR'); $uploaded = false; } } if (!$uploaded) { $error = new \stdClass(); $error->error = elgg_echo('dropzone:file_not_entity'); $files[] = $error; continue; } if ($old_filestorename && $old_filestorename != $file->getFilenameOnFilestore()) { // remove old file unlink($old_filestorename); } $mime_type = $file->detectMimeType(null, $upload->getClientMimeType()); $file->setMimeType($mime_type); $file->simpletype = elgg_get_file_simple_type($mime_type); _elgg_services()->events->triggerAfter('upload', 'file', $file); if (!$file->save() || !$file->exists()) { $file->delete(); $error = new \stdClass(); $error->error = elgg_echo('dropzone:file_not_entity'); $files[] = $error; continue; } if ($file->saveIconFromElggFile($file)) { $file->thumbnail = $file->getIcon('small')->getFilename(); $file->smallthumb = $file->getIcon('medium')->getFilename(); $file->largethumb = $file->getIcon('large')->getFilename(); } $success = new \stdClass(); $success->file = $file; $files[] = $success; } return $files; }
/** * @param $title * @param $description * @param $username * @param $access * @param $tags * @return array * @throws InvalidParameterException * @internal param $guid * @internal param $size */ function file_save_post($title, $description, $username, $access, $tags) { $return = array(); if (!$username) { $user = elgg_get_logged_in_user_entity(); } else { $user = get_user_by_username($username); if (!$user) { throw new InvalidParameterException('registration:usernamenotvalid'); } } $loginUser = elgg_get_logged_in_user_entity(); $container_guid = $loginUser->guid; if ($access == 'ACCESS_FRIENDS') { $access_id = -2; } elseif ($access == 'ACCESS_PRIVATE') { $access_id = 0; } elseif ($access == 'ACCESS_LOGGED_IN') { $access_id = 1; } elseif ($access == 'ACCESS_PUBLIC') { $access_id = 2; } else { $access_id = -2; } $file = $_FILES["upload"]; if (empty($file)) { $response['status'] = 1; $response['result'] = elgg_echo("file:blank"); return $response; } $new_file = true; if ($new_file) { $file = new ElggFile(); $file->subtype = "file"; // if no title on new upload, grab filename if (empty($title)) { $title = htmlspecialchars($_FILES['upload']['name'], ENT_QUOTES, 'UTF-8'); } } $file->title = $title; $file->description = $description; $file->access_id = $access_id; $file->container_guid = $container_guid; $file->tags = string_to_tag_array($tags); // we have a file upload, so process it if (isset($_FILES['upload']['name']) && !empty($_FILES['upload']['name'])) { $prefix = "file/"; $filestorename = elgg_strtolower(time() . $_FILES['upload']['name']); $file->setFilename($prefix . $filestorename); $file->originalfilename = $_FILES['upload']['name']; $mime_type = $file->detectMimeType($_FILES['upload']['tmp_name'], $_FILES['upload']['type']); $file->setMimeType($mime_type); $file->simpletype = elgg_get_file_simple_type($mime_type); // Open the file to guarantee the directory exists $file->open("write"); $file->close(); move_uploaded_file($_FILES['upload']['tmp_name'], $file->getFilenameOnFilestore()); $fileSaved = $file->save(); // if image, we need to create thumbnails (this should be moved into a function) if ($fileSaved && $file->simpletype == "image") { $file->icontime = time(); $thumbnail = get_resized_image_from_existing_file($file->getFilenameOnFilestore(), 60, 60, true); if ($thumbnail) { $thumb = new ElggFile(); $thumb->setMimeType($_FILES['upload']['type']); $thumb->setFilename($prefix . "thumb" . $filestorename); $thumb->open("write"); $thumb->write($thumbnail); $thumb->close(); $file->thumbnail = $prefix . "thumb" . $filestorename; unset($thumbnail); } $thumbsmall = get_resized_image_from_existing_file($file->getFilenameOnFilestore(), 153, 153, true); if ($thumbsmall) { $thumb->setFilename($prefix . "smallthumb" . $filestorename); $thumb->open("write"); $thumb->write($thumbsmall); $thumb->close(); $file->smallthumb = $prefix . "smallthumb" . $filestorename; unset($thumbsmall); } $thumblarge = get_resized_image_from_existing_file($file->getFilenameOnFilestore(), 600, 600, false); if ($thumblarge) { $thumb->setFilename($prefix . "largethumb" . $filestorename); $thumb->open("write"); $thumb->write($thumblarge); $thumb->close(); $file->largethumb = $prefix . "largethumb" . $filestorename; unset($thumblarge); } } elseif ($file->icontime) { // if it is not an image, we do not need thumbnails unset($file->icontime); $thumb = new ElggFile(); $thumb->setFilename($prefix . "thumb" . $filestorename); $thumb->delete(); unset($file->thumbnail); $thumb->setFilename($prefix . "smallthumb" . $filestorename); $thumb->delete(); unset($file->smallthumb); $thumb->setFilename($prefix . "largethumb" . $filestorename); $thumb->delete(); unset($file->largethumb); } } else { // not saving a file but still need to save the entity to push attributes to database $fileSaved = $file->save(); } // handle results differently for new files and file updates if ($new_file) { if ($fileSaved) { elgg_create_river_item(array('view' => 'river/object/file/create', 'action_type' => 'create', 'subject_guid' => elgg_get_logged_in_user_guid(), 'object_guid' => $file->guid)); $return['guid'] = $file->guid; $return['message'] = 'success'; } else { // failed to save file object - nothing we can do about this $return['guid'] = 0; $return['message'] = elgg_echo("file:uploadfailed"); } } else { $return['guid'] = 0; $return['message'] = elgg_echo("file:uploadfailed"); } return $return; }
/** * Saves icons using a file located in the data store as the source. * * @param ElggEntity $entity Entity to own the icons * @param ElggFile $file An ElggFile instance * @param string $type The name of the icon. e.g., 'icon', 'cover_photo' * @param array $coords An array of cropping coordinates x1, y1, x2, y2 * @return bool * @throws InvalidParameterException */ public function saveIconFromElggFile(ElggEntity $entity, ElggFile $file, $type = 'icon', array $coords = array()) { if (!$file->exists()) { throw new InvalidParameterException(__METHOD__ . ' expects an instance of ElggFile with an existing file on filestore'); } $tmp_filename = time() . pathinfo($file->getFilenameOnFilestore(), PATHINFO_BASENAME); $tmp = new ElggFile(); $tmp->owner_guid = $entity->guid; $tmp->setFilename("tmp/{$tmp_filename}"); $tmp->open('write'); $tmp->close(); copy($file->getFilenameOnFilestore(), $tmp->getFilenameOnFilestore()); $tmp->mimetype = (new MimeTypeDetector())->getType($tmp->getFilenameOnFilestore(), $file->getMimeType()); $tmp->simpletype = elgg_get_file_simple_type($tmp->mimetype); $result = $this->saveIcon($entity, $tmp, $type, $coords); $tmp->delete(); return $result; }
/** * Unzip an uploaded zip file * * @param array $file the $_FILES information * @param int $container_guid the container to put the files/folders under * @param int $parent_guid the parrent folder * * @return bool */ function file_tools_unzip($file, $container_guid, $parent_guid = 0) { $extracted = false; if (!empty($file) && !empty($container_guid)) { $allowed_extensions = file_tools_allowed_extensions(); $zipfile = elgg_extract("tmp_name", $file); $container_entity = get_entity($container_guid); $access_id = get_input("access_id", false); if ($access_id === false) { if (!empty($parent_guid) && ($parent_folder = get_entity($parent_guid)) && elgg_instanceof($parent_folder, "object", FILE_TOOLS_SUBTYPE)) { $access_id = $parent_folder->access_id; } else { if (elgg_instanceof($container_entity, "group")) { $access_id = $container_entity->group_acl; } else { $access_id = get_default_access($container_entity); } } } // open the zip file $zip = zip_open($zipfile); while ($zip_entry = zip_read($zip)) { // open the zip entry zip_entry_open($zip, $zip_entry); // set some variables $zip_entry_name = zip_entry_name($zip_entry); $filename = basename($zip_entry_name); // check for folder structure if (strlen($zip_entry_name) != strlen($filename)) { // there is a folder structure, check it and create missing items file_tools_create_folders($zip_entry, $container_guid, $parent_guid); } // extract the folder structure from the zip entry $folder_array = explode("/", $zip_entry_name); $parent = $parent_guid; foreach ($folder_array as $folder) { $folder = utf8_encode($folder); if ($entity = file_tools_check_foldertitle_exists($folder, $container_guid, $parent)) { $parent = $entity->getGUID(); } else { if ($folder == end($folder_array)) { $prefix = "file/"; $extension_array = explode('.', $folder); $file_extension = end($extension_array); if (in_array(strtolower($file_extension), $allowed_extensions)) { $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); // create the file $filehandler = new ElggFile(); $filehandler->setFilename($prefix . $folder); $filehandler->title = $folder; $filehandler->originalfilename = $folder; $filehandler->owner_guid = elgg_get_logged_in_user_guid(); $filehandler->container_guid = $container_guid; $filehandler->access_id = $access_id; $filehandler->open("write"); $filehandler->write($buf); $filehandler->close(); $mime_type = $filehandler->detectMimeType($filehandler->getFilenameOnFilestore()); // hack for Microsoft zipped formats $info = pathinfo($folder); $office_formats = array("docx", "xlsx", "pptx"); if ($mime_type == "application/zip" && in_array($info["extension"], $office_formats)) { switch ($info["extension"]) { case "docx": $mime_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break; case "xlsx": $mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break; case "pptx": $mime_type = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; break; } } // check for bad ppt detection if ($mime_type == "application/vnd.ms-office" && $info["extension"] == "ppt") { $mime_type = "application/vnd.ms-powerpoint"; } $simple_type = elgg_get_file_simple_type($mime_type); $filehandler->setMimeType($mime_type); $filehandler->simpletype = $simple_type; if ($simple_type == "image") { $filestorename = elgg_strtolower(time() . $folder); $thumb = new ElggFile(); $thumb->owner_guid = elgg_get_logged_in_user_guid(); $thumbnail = get_resized_image_from_existing_file($filehandler->getFilenameOnFilestore(), 60, 60, true); if ($thumbnail) { $thumb->setFilename($prefix . "thumb" . $filestorename); $thumb->open("write"); $thumb->write($thumbnail); $thumb->close(); $filehandler->thumbnail = $prefix . "thumb" . $filestorename; unset($thumbnail); } $thumbsmall = get_resized_image_from_existing_file($filehandler->getFilenameOnFilestore(), 153, 153, true); if ($thumbsmall) { $thumb->setFilename($prefix . "smallthumb" . $filestorename); $thumb->open("write"); $thumb->write($thumbsmall); $thumb->close(); $filehandler->smallthumb = $prefix . "smallthumb" . $filestorename; unset($thumbsmall); } $thumblarge = get_resized_image_from_existing_file($filehandler->getFilenameOnFilestore(), 600, 600, false); if ($thumblarge) { $thumb->setFilename($prefix . "largethumb" . $filestorename); $thumb->open("write"); $thumb->write($thumblarge); $thumb->close(); $filehandler->largethumb = $prefix . "largethumb" . $filestorename; unset($thumblarge); } unset($thumb); } set_input('folder_guid', $parent); $filehandler->save(); $extracted = true; if (!empty($parent)) { add_entity_relationship($parent, FILE_TOOLS_RELATIONSHIP, $filehandler->getGUID()); } } } } } zip_entry_close($zip_entry); } zip_close($zip); } return $extracted; }
/** * {@inheritdoc} */ public function put(ParameterBag $params) { $decoded = ""; if ($params->contents) { if (empty($params->filename) || empty($params->mimetype)) { throw new GraphException("You need to provide a filename and content type with encoded file contents", HttpResponse::HTTP_BAD_REQUEST); } for ($i = 0; $i < ceil(strlen($params->contents) / 256); $i++) { $decoded = $decoded . base64_decode(substr($params->contents, $i * 256, 256)); } if (!$decoded) { throw new GraphException("File contents can not be empty and must be encoded with base64", HttpResponse::HTTP_BAD_REQUEST); } if (empty($params->checksum) || md5($decoded) != $params->checksum) { throw new GraphException("Checksum mismatch", HttpResponse::HTTP_BAD_REQUEST); } } $owner_guid = $params->owner_guid ?: elgg_get_logged_in_user_guid(); $owner = get_entity($owner_guid); if (!$owner->canEdit()) { throw new GraphException("You are not allowed to upload files on users's behalf", HttpResponse::HTTP_FORBIDDEN); } $container_guid = $params->container_guid ?: elgg_get_logged_in_user_guid(); $container = get_entity($container_guid); if (!$container->canWriteToContainer($owner->guid, 'object', 'file')) { throw new GraphException("You are not allowed to upload files to this container", HttpResponse::HTTP_FORBIDDEN); } $file_guid = $params->guid ?: 0; if ($file_guid) { $file = get_entity($file_guid); } else { if ($decoded) { $file = new ElggFile(); $file->subtype = 'file'; $file->owner_guid = $owner->guid; $file->container_guid = $container->guid; $file->title = $params->title ?: $params->filename; $file->access_id = ACCESS_PRIVATE; $file->origin = 'graph'; } } $attrs = array('title', 'description', 'access_id'); foreach ($attrs as $attr) { if (isset($params->{$attr}) && $this->request->get($attr) !== null) { $file->{$attr} = $params->{$attr}; } } if (!$file instanceof \ElggFile) { throw new GraphException("Unable to load or create a file entity"); } if ($decoded) { $file->setFilename("file/{$params->filename}"); if (!$file->exists()) { $file->open('write'); $file->close(); } file_put_contents($file->getFilenameOnFilestore(), $decoded); $file->originalfilename = $params->filename; $mimetype = $file->detectMimeType(null, $params->mimetype); $file->setMimeType($mimetype); $file->simpletype = elgg_get_file_simple_type($mimetype); } $guid = $file->save(); if (!$guid) { $file->delete(); throw new GraphException("File could not be saved with given parameters", HttpResponse::HTTP_BAD_REQUEST); } if ($file->simpletype == 'image') { IconHandler::makeIcons($file); } return array('nodes' => array($file)); }