/**
 * @param string $message
 * @param array $_course
 * @param int $group_id
 * @param int $session_id
 * @param bool $preview
 */
function saveMessage($message, $userId, $_course, $session_id, $group_id, $preview = true)
{
    $userInfo = api_get_user_info($userId);
    $fullName = $userInfo['complete_name'];
    $isMaster = (bool) api_is_course_admin();
    $document_path = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document';
    if (!empty($group_id)) {
        $group_info = GroupManager::get_group_properties($group_id);
        $basepath_chat = $group_info['directory'] . '/chat_files';
    } else {
        $basepath_chat = '/chat_files';
    }
    $chat_path = $document_path . $basepath_chat . '/';
    if (!is_dir($chat_path)) {
        if (is_file($chat_path)) {
            @unlink($chat_path);
        }
    }
    $date_now = date('Y-m-d');
    $message = trim($message);
    $timeNow = date('d/m/y H:i:s');
    if (!empty($group_id)) {
        $basename_chat = 'messages-' . $date_now . '_gid-' . $group_id;
    } elseif (!empty($session_id)) {
        $basename_chat = 'messages-' . $date_now . '_sid-' . $session_id;
    } else {
        $basename_chat = 'messages-' . $date_now;
    }
    if (!api_is_anonymous()) {
        if (!empty($message)) {
            Emojione\Emojione::$imagePathPNG = api_get_path(WEB_LIBRARY_PATH) . 'javascript/emojione/png/';
            Emojione\Emojione::$ascii = true;
            // Parsing emojis
            $message = Emojione\Emojione::toImage($message);
            // Parsing text to understand markdown (code highlight)
            $message = MarkdownExtra::defaultTransform($message);
            // Security XSS
            $message = Security::remove_XSS($message);
            if ($preview == true) {
                return $message;
            }
            if (!file_exists($chat_path . $basename_chat . '.log.html')) {
                $doc_id = add_document($_course, $basepath_chat . '/' . $basename_chat . '.log.html', 'file', 0, $basename_chat . '.log.html');
                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $userId, $group_id, null, null, null, $session_id);
                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $userId, $group_id, null, null, null, $session_id);
                item_property_update_on_folder($_course, $basepath_chat, $userId);
            } else {
                $doc_id = DocumentManager::get_document_id($_course, $basepath_chat . '/' . $basename_chat . '.log.html');
            }
            $fp = fopen($chat_path . $basename_chat . '.log.html', 'a');
            $userPhoto = Usermanager::getUserPicture($userId, USER_IMAGE_SIZE_MEDIUM);
            $filePhoto = '<img class="chat-image" src="' . $userPhoto . '"/>';
            if ($isMaster) {
                fputs($fp, '<div class="message-teacher"><div class="content-message"><div class="chat-message-block-name">' . $fullName . '</div><div class="chat-message-block-content">' . $message . '</div><div class="message-date">' . $timeNow . '</div></div><div class="icon-message"></div>' . $filePhoto . '</div>' . "\n");
            } else {
                fputs($fp, '<div class="message-student">' . $filePhoto . '<div class="icon-message"></div><div class="content-message"><div class="chat-message-block-name">' . $fullName . '</div><div class="chat-message-block-content">' . $message . '</div><div class="message-date">' . $timeNow . '</div></div></div>' . "\n");
            }
            fclose($fp);
            $chat_size = filesize($chat_path . $basename_chat . '.log.html');
            update_existing_document($_course, $doc_id, $chat_size);
            item_property_update_on_folder($_course, $basepath_chat, $userId);
        }
    }
}
Beispiel #2
0
/**
 * 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;
            }
        }
    }
}
Beispiel #3
0
         $basename_chat = 'messages-' . $date_now;
     }
 }
 if ($reset && $isMaster) {
     $i = 1;
     while (file_exists($chat_path . $basename_chat . '-' . $i . '.log.html')) {
         $i++;
     }
     @rename($chat_path . $basename_chat . '.log.html', $chat_path . $basename_chat . '-' . $i . '.log.html');
     @fclose(fopen($chat_path . $basename_chat . '.log.html', 'w'));
     $doc_id = add_document($_course, $basepath_chat . '/' . $basename_chat . '-' . $i . '.log.html', 'file', filesize($chat_path . $basename_chat . '-' . $i . '.log.html'), $basename_chat . '-' . $i . '.log.html');
     api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $userId, $group_id, null, null, null, $session_id);
     api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $userId, $group_id, null, null, null, $session_id);
     item_property_update_on_folder($_course, $basepath_chat, $userId);
     $doc_id = DocumentManager::get_document_id($_course, $basepath_chat . '/' . $basename_chat . '.log.html');
     update_existing_document($_course, $doc_id, 0);
 }
 $remove = 0;
 $content = array();
 if (file_exists($chat_path . $basename_chat . '.log.html')) {
     $content = file($chat_path . $basename_chat . '.log.html');
     $nbr_lines = sizeof($content);
     $remove = $nbr_lines - 100;
 }
 if ($remove < 0) {
     $remove = 0;
 }
 array_splice($content, 0, $remove);
 require 'header_frame.inc.php';
 if (isset($_GET['origin']) && $_GET['origin'] == 'whoisonline') {
     //the caller
//add new document to disk
file_put_contents($documentPath, $contents);
if ($currentTool == 'document/createdraw') {
    //add document to database
    $doc_id = add_document($_course, $relativeUrlPath . '/' . $drawFileName, 'file', filesize($documentPath), $title);
    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
} elseif ($currentTool == 'document/editdraw') {
    //check path
    if (!isset($_SESSION['draw_file'])) {
        api_not_allowed();
        //from Chamilo
        die;
    }
    if ($_SESSION['draw_file'] == $drawFileName) {
        $document_id = DocumentManager::get_document_id($_course, $relativeUrlPath . '/' . $drawFileName);
        update_existing_document($_course, $document_id, filesize($documentPath), null);
        api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $_user['user_id'], $groupId, null, null, null, $current_session_id);
    } else {
        //add a new document
        $doc_id = add_document($_course, $relativeUrlPath . '/' . $drawFileName, 'file', filesize($documentPath), $title);
        api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
    }
}
//clean sessions and add messages and return to current document list
unset($_SESSION['draw_dir']);
unset($_SESSION['draw_file']);
unset($_SESSION['whereami']);
if ($suffix != 'png') {
    if ($relativeUrlPath == '') {
        $relativeUrlPath = '/';
    }
                            header('Location: document.php?id=' . $document_data['parent_id'] . '&' . api_get_cidreq() . ($is_certificate_mode ? '&curdirpath=/certificates&selectcat=1' : ''));
                            exit;
                        } else {
                            Display::addFlash(Display::return_message(get_lang('Impossible'), 'warning'));
                        }
                    } else {
                        Display::addFlash(Display::return_message(get_lang('Impossible'), 'warning'));
                    }
                } else {
                    if ($document_id) {
                        update_existing_document($_course, $document_id, $file_size, $read_only_flag);
                    }
                }
            } else {
                if ($document_id) {
                    update_existing_document($_course, $document_id, $file_size, $read_only_flag);
                }
            }
        }
    }
}
// Replace relative paths by absolute web paths (e.g. './' => 'http://www.chamilo.org/courses/ABC/document/')
$content = null;
$extension = null;
$filename = null;
if (file_exists($document_data['absolute_path'])) {
    $path_info = pathinfo($document_data['absolute_path']);
    $filename = $path_info['filename'];
    if (is_file($document_data['absolute_path'])) {
        $extension = $path_info['extension'];
        if (in_array($extension, array('html', 'htm'))) {
Beispiel #6
0
                // view user picture
                $userImage = UserManager::get_user_picture_path_by_id($user_id, 'web', false, true);
                if (substr($userImage['file'], 0, 7) != 'unknown') {
                    $userPhoto = $userImage['dir'] . 'medium_' . $userImage['file'];
                } else {
                    $userPhoto = $userImage['dir'] . $userImage['file'];
                }
                $filePhoto = '<img class="chat-image" src="' . $userPhoto . '"/>';
                if ($isMaster) {
                    fputs($fp, '<div class="message-teacher"><div class="content-message"><div>' . $message . '</div><div class="message-date">' . $timeNow . '</div></div><div class="icon-message"></div>' . $filePhoto . '</div>' . "\n");
                } else {
                    fputs($fp, '<div class="message-student">' . $filePhoto . '<div class="icon-message"></div><div class="content-message"><div>' . $message . '</div><div class="message-date">' . $timeNow . '</div></div></div>' . "\n");
                }
                fclose($fp);
                $chat_size = filesize($chat_path . $basename_chat . '.log.html');
                update_existing_document($_course, $doc_id, $chat_size);
                item_property_update_on_folder($_course, $basepath_chat, $_user['user_id']);
            }
        }
    }
    ?>
	<form name="formMessage" method="post" action="<?php 
    echo api_get_self() . '?' . api_get_cidreq();
    ?>
" onsubmit="javascript: if(document.formMessage.message.value == '') { alert('<?php 
    echo addslashes(api_htmlentities(get_lang('TypeMessage'), ENT_QUOTES));
    ?>
'); document.formMessage.message.focus(); return false; }" autocomplete="off">
	<input type="hidden" name="sent" value="1">
	<div class="message-form-chat">
	<table border="0" cellpadding="5" cellspacing="0" width="100%">