require "init.inc.php"; $smarty->assign('PAGETITLE', $page->getlocalized('manage_files')); $page->popup = true; $page->forceLogin(); // upload to my files $upload = sotf_Utils::getParameter('upload'); //-------- mod by buddhafly/wolfi_fhstp 05-08-31 if ($upload) { $userDir = $user->getUserDir() . '/'; $filename = $_FILES['userfile']['name']; $extension = substr($filename, strrpos($filename, '.') + 1); $restname = substr($filename, 0, -1 * (strlen($extension) + 1)); $newname = convert_special_chars(utf8_decode($restname)); //UTF-Module for PHP REQUIRED!!! $file = $userDir . $newname . "." . $extension; moveUploadedFile('userfile', $file); $page->redirect("manageFiles.php"); exit; } //--------- // delete files $del = sotf_Utils::getParameter('del'); if ($del) { reset($_POST); while (list($k, $fname) = each($_POST)) { debug("P", $k); if (substr($k, 0, 4) == 'sel_') { if (!unlink($user->getUserDir() . '/' . $fname)) { addError("Could not delete: {$fname}"); } }
/** * Save the extra fields values * In order to save this function needs a item_id (user id, course id, etc) * This function is used with $extraField->addElements() * @param array $params array for the insertion into the *_field_values table * * @return mixed false on empty params, void otherwise * @assert (array()) === false */ public function saveFieldValues($params) { foreach ($params as $key => $value) { $found = strpos($key, '__persist__'); if ($found) { $tempKey = str_replace('__persist__', '', $key); if (!isset($params[$tempKey])) { $params[$tempKey] = array(); } } } if (empty($params['item_id'])) { return false; } $type = $this->getExtraField()->getExtraFieldType(); // Parse params. foreach ($params as $key => $value) { if (substr($key, 0, 6) == 'extra_' || substr($key, 0, 7) == '_extra_') { // An extra field. $field_variable = substr($key, 6); $extraFieldInfo = $this->getExtraField()->get_handler_field_info_by_field_variable($field_variable); if ($extraFieldInfo) { $commentVariable = 'extra_' . $field_variable . '_comment'; $comment = isset($params[$commentVariable]) ? $params[$commentVariable] : null; switch ($extraFieldInfo['field_type']) { case ExtraField::FIELD_TYPE_TAG: if ($type == EntityExtraField::USER_FIELD_TYPE) { UserManager::delete_user_tags($params['item_id'], $extraFieldInfo['id']); UserManager::process_tags($value, $params['item_id'], $extraFieldInfo['id']); } else { $em = Database::getManager(); $tagValues = is_array($value) ? $value : [$value]; $tags = []; foreach ($tagValues as $tagValue) { $tagsResult = $em->getRepository('ChamiloCoreBundle:Tag')->findBy(['tag' => $tagValue, 'fieldId' => $extraFieldInfo['id']]); if (empty($tagsResult)) { $tag = new \Chamilo\CoreBundle\Entity\Tag(); $tag->setCount(0); $tag->setFieldId($extraFieldInfo['id']); $tag->setTag($tagValue); $tags[] = $tag; } else { $tags = array_merge($tags, $tagsResult); } } foreach ($tags as $tag) { $fieldTags = $em->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')->findBy(['fieldId' => $extraFieldInfo['id'], 'itemId' => $params['item_id'], 'tagId' => $tag->getId()]); foreach ($fieldTags as $fieldTag) { $em->remove($fieldTag); $tag->setCount($tag->getCount() - 1); $em->persist($tag); $em->flush(); } $tag->setCount($tag->getCount() + 1); $em->persist($tag); $em->flush(); $fieldRelTag = new Chamilo\CoreBundle\Entity\ExtraFieldRelTag(); $fieldRelTag->setFieldId($extraFieldInfo['id']); $fieldRelTag->setItemId($params['item_id']); $fieldRelTag->setTagId($tag->getId()); $em->persist($fieldRelTag); $em->flush(); } } break; case ExtraField::FIELD_TYPE_FILE_IMAGE: $dirPermissions = api_get_permissions_for_new_directories(); switch ($this->type) { case 'course': $fileDir = api_get_path(SYS_UPLOAD_PATH) . "courses/"; $fileDirStored = "courses/"; break; case 'session': $fileDir = api_get_path(SYS_UPLOAD_PATH) . "sessions/"; $fileDirStored = "sessions/"; break; case 'user': $fileDir = UserManager::getUserPathById($params['item_id'], 'system'); $fileDirStored = UserManager::getUserPathById($params['item_id'], 'last'); break; } $fileName = ExtraField::FIELD_TYPE_FILE_IMAGE . "_{$params['item_id']}.png"; if (!file_exists($fileDir)) { mkdir($fileDir, $dirPermissions, true); } if ($value['error'] == 0) { $imageExtraField = new Image($value['tmp_name']); $imageExtraField->send_image($fileDir . $fileName, -1, 'png'); $newParams = array('item_id' => $params['item_id'], 'field_id' => $extraFieldInfo['id'], 'value' => $fileDirStored . $fileName, 'comment' => $comment); self::save($newParams); } break; case ExtraField::FIELD_TYPE_FILE: $dirPermissions = api_get_permissions_for_new_directories(); switch ($this->type) { case 'course': $fileDir = api_get_path(SYS_UPLOAD_PATH) . "courses/"; $fileDirStored = "courses/"; break; case 'session': $fileDir = api_get_path(SYS_UPLOAD_PATH) . "sessions/"; $fileDirStored = "sessions/"; break; case 'user': $fileDir = UserManager::getUserPathById($params['item_id'], 'system'); $fileDirStored = UserManager::getUserPathById($params['item_id'], 'last'); break; } $cleanedName = api_replace_dangerous_char($value['name']); $fileName = ExtraField::FIELD_TYPE_FILE . "_{$params['item_id']}_{$cleanedName}"; if (!file_exists($fileDir)) { mkdir($fileDir, $dirPermissions, true); } if ($value['error'] == 0) { moveUploadedFile($value, $fileDir . $fileName); $new_params = array('item_id' => $params['item_id'], 'field_id' => $extraFieldInfo['id'], 'value' => $fileDirStored . $fileName); if ($this->type !== 'session' && $this->type !== 'course') { $new_params['comment'] = $comment; } self::save($new_params); } break; default: $newParams = array('item_id' => $params['item_id'], 'field_id' => $extraFieldInfo['id'], 'value' => $value, 'comment' => $comment); self::save($newParams); } } } } }
/** * This function does the save-work for the documents. * It handles the uploaded file and adds the properties to the database * If unzip=1 and the file is a zipfile, it is extracted * If we decide to save ALL kinds of documents in one database, * we could extend this with a $type='document', 'scormdocument',... * * @param array $courseInfo * @param array $uploadedFile ($_FILES) * array( * 'name' => 'picture.jpg', * 'tmp_name' => '...', // absolute path * ); * @param string $documentDir Example: /var/www/chamilo/courses/ABC/document * @param string $uploadPath Example: /folder1/folder2/ * @param int $userId * @param int $groupId, 0 for everybody * @param int $toUserId, NULL for everybody * @param int $unzip 1/0 * @param string $whatIfFileExists overwrite, rename or warn if exists (default) * @param boolean $output Optional output parameter. * @param bool $onlyUploadFile * @param string $comment * @param int $sessionId * * So far only use for unzip_uploaded_document function. * If no output wanted on success, set to false. * @param string $comment * @return string path of the saved file */ function handle_uploaded_document($courseInfo, $uploadedFile, $documentDir, $uploadPath, $userId, $groupId = 0, $toUserId = null, $unzip = 0, $whatIfFileExists = '', $output = true, $onlyUploadFile = false, $comment = null, $sessionId = null) { if (!$userId) { return false; } $userInfo = api_get_user_info(); $uploadedFile['name'] = stripslashes($uploadedFile['name']); // Add extension to files without one (if possible) $uploadedFile['name'] = add_ext_on_mime($uploadedFile['name'], $uploadedFile['type']); if (empty($sessionId)) { $sessionId = api_get_session_id(); } else { $sessionId = intval($sessionId); } // Just in case process_uploaded_file is not called $maxSpace = DocumentManager::get_course_quota(); // Check if there is enough space to save the file if (!DocumentManager::enough_space($uploadedFile['size'], $maxSpace)) { if ($output) { Display::display_error_message(get_lang('UplNotEnoughSpace')); } return false; } // If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploadedFile['name']))) { return unzip_uploaded_document($courseInfo, $userInfo, $uploadedFile, $uploadPath, $documentDir, $maxSpace, $sessionId, $groupId, $output); } elseif ($unzip == 1 && !preg_match('/.zip$/', strtolower($uploadedFile['name']))) { // We can only unzip ZIP files (no gz, tar,...) if ($output) { Display::display_error_message(get_lang('UplNotAZip') . " " . get_lang('PleaseTryAgain')); } return false; } else { // Clean up the name, only ASCII characters should stay. (and strict) $cleanName = api_replace_dangerous_char($uploadedFile['name'], 'strict'); // No "dangerous" files $cleanName = disable_dangerous_file($cleanName); // Checking file extension if (!filter_extension($cleanName)) { if ($output) { Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension')); } return false; } else { // If the upload path differs from / (= root) it will need a slash at the end if ($uploadPath != '/') { $uploadPath = $uploadPath . '/'; } // Full path to where we want to store the file with trailing slash $whereToSave = $documentDir . $uploadPath; // At least if the directory doesn't exist, tell so if (!is_dir($whereToSave)) { if (!mkdir($whereToSave, api_get_permissions_for_new_directories())) { if ($output) { Display::display_error_message(get_lang('DestDirectoryDoesntExist') . ' (' . $uploadPath . ')'); } return false; } } // Just upload the file "as is" if ($onlyUploadFile) { $errorResult = moveUploadedFile($uploadedFile, $whereToSave . $cleanName); if ($errorResult) { return $whereToSave . $cleanName; } else { return $errorResult; } } /* Based in the clean name we generate a new filesystem name Using the session_id and group_id if values are not empty */ /*$fileExists = DocumentManager::documentExists( $uploadPath.$cleanName, $courseInfo, $sessionId, $groupId );*/ $fileSystemName = DocumentManager::fixDocumentName($cleanName, 'file', $courseInfo, $sessionId, $groupId); // Name of the document without the extension (for the title) $documentTitle = get_document_title($uploadedFile['name']); // Size of the uploaded file (in bytes) $fileSize = $uploadedFile['size']; // File permissions $filePermissions = api_get_permissions_for_new_files(); // Example: /var/www/chamilo/courses/xxx/document/folder/picture.jpg $fullPath = $whereToSave . $fileSystemName; // Example: /folder/picture.jpg $filePath = $uploadPath . $fileSystemName; $docId = DocumentManager::get_document_id($courseInfo, $filePath, $sessionId); $documentList = DocumentManager::getDocumentByPathInCourse($courseInfo, $filePath); // This means that the path already exists in this course. if (!empty($documentList) && $whatIfFileExists != 'overwrite') { //$found = false; // Checking if we are talking about the same course + session /*foreach ($documentList as $document) { if ($document['session_id'] == $sessionId) { $found = true; break; } }*/ //if ($found == false) { $whatIfFileExists = 'rename'; //} } // What to do if the target file exists switch ($whatIfFileExists) { // Overwrite the file if it exists case 'overwrite': // Check if the target file exists, so we can give another message $fileExists = file_exists($fullPath); if (moveUploadedFile($uploadedFile, $fullPath)) { chmod($fullPath, $filePermissions); if ($fileExists && $docId) { // UPDATE DATABASE $documentId = DocumentManager::get_document_id($courseInfo, $filePath); if (is_numeric($documentId)) { // Update file size update_existing_document($courseInfo, $documentId, $uploadedFile['size']); // Update document item_property api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentUpdated', $userId, $groupId, $toUserId, null, null, $sessionId); // Redo visibility api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo); } else { // There might be cases where the file exists on disk but there is no registration of that in the database // In this case, and if we are in overwrite mode, overwrite and create the db record $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId); if ($documentId) { // Put the document in item_property update api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId); // Redo visibility api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo); } } // If the file is in a folder, we need to update all parent folders item_property_update_on_folder($courseInfo, $uploadPath, $userId); // Display success message with extra info to user if ($output) { Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle . ' ' . get_lang('UplFileOverwritten'), false); } return $filePath; } else { // Put the document data in the database $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId); if ($documentId) { // Put the document in item_property update api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId); // Redo visibility api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo); } // If the file is in a folder, we need to update all parent folders item_property_update_on_folder($courseInfo, $uploadPath, $userId); // Display success message to user if ($output) { Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle, false); } return $filePath; } } else { if ($output) { Display::display_error_message(get_lang('UplUnableToSaveFile')); } return false; } break; // Rename the file if it exists // Rename the file if it exists case 'rename': // Always rename. $cleanName = DocumentManager::getUniqueFileName($uploadPath, $cleanName, $courseInfo, $sessionId, $groupId); $fileSystemName = DocumentManager::fixDocumentName($cleanName, 'file', $courseInfo, $sessionId, $groupId); $documentTitle = get_document_title($cleanName); $fullPath = $whereToSave . $fileSystemName; $filePath = $uploadPath . $fileSystemName; if (moveUploadedFile($uploadedFile, $fullPath)) { chmod($fullPath, $filePermissions); // Put the document data in the database $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId); if ($documentId) { // Update document item_property api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId); // Redo visibility api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo); } // If the file is in a folder, we need to update all parent folders item_property_update_on_folder($courseInfo, $uploadPath, $userId); // Display success message to user if ($output) { Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . get_lang('UplFileSavedAs') . ' ' . $documentTitle, false); } return $filePath; } else { if ($output) { Display::display_error_message(get_lang('UplUnableToSaveFile')); } return false; } break; default: // Only save the file if it doesn't exist or warn user if it does exist if (file_exists($fullPath) && $docId) { if ($output) { Display::display_error_message($cleanName . ' ' . get_lang('UplAlreadyExists')); } } else { if (moveUploadedFile($uploadedFile, $fullPath)) { chmod($fullPath, $filePermissions); // Put the document data in the database $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId); if ($documentId) { // Update document item_property api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId); // Redo visibility api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo); } // If the file is in a folder, we need to update all parent folders item_property_update_on_folder($courseInfo, $uploadPath, $userId); // Display success message to user if ($output) { Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle, false); } return $filePath; } else { if ($output) { Display::display_error_message(get_lang('UplUnableToSaveFile')); } return false; } } break; } } } }