Пример #1
0
function SanitizeFileName($sNewFileName, $sMimeType = null)
{
    global $Config;
    if (empty($sMimeType)) {
        $sNewFileName = stripslashes($sNewFileName);
    } else {
        $sNewFileName = add_ext_on_mime(stripslashes($sNewFileName), $sMimeType);
    }
    // Replace dots in the name with underscores (only one dot can be there... security issue).
    if ($Config['ForceSingleExtension']) {
        $sNewFileName = preg_replace('/\\.(?![^.]*$)/', '_', $sNewFileName);
    }
    // Remove \ / | : ? * " < >
    //$sNewFileName = preg_replace( '/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFileName ) ;
    $sNewFileName = replace_dangerous_char($sNewFileName, 'strict');
    $sNewFileName = php2phps($sNewFileName);
    return $sNewFileName;
}
Пример #2
0
function process_extracted_file($p_event, &$p_header)
{
    global $uploadPath, $realFileSize, $basedir, $course_id, $subsystem, $subsystem_id, $uploadPath, $group_sql;
    $replace = isset($_POST['replace']);
    if (!isset($uploadPath)) {
        $uploadPath = '';
    }
    $file_category = isset($_POST['file_category']) ? $_POST['file_category'] : 0;
    $file_creator = isset($_POST['file_creator']) ? $_POST['file_creator'] : '';
    $file_author = isset($_POST['file_author']) ? $_POST['file_author'] : '';
    $file_subject = isset($_POST['file_subject']) ? $_POST['file_subject'] : '';
    $file_language = isset($_POST['file_language']) ? $_POST['file_language'] : '';
    $file_copyrighted = isset($_POST['file_copyrighted']) ? $_POST['file_copyrighted'] : '';
    $file_comment = isset($_POST['file_comment']) ? $_POST['file_comment'] : '';
    $file_description = isset($_POST['file_description']) ? $_POST['file_description'] : '';
    $realFileSize += $p_header['size'];
    $stored_filename = $p_header['stored_filename'];
    if (invalid_utf8($stored_filename)) {
        $stored_filename = cp737_to_utf8($stored_filename);
    }
    $path_components = explode('/', $stored_filename);
    $filename = php2phps(array_pop($path_components));
    if (unwanted_file($filename)) {
        $filename .= '.bin';
    }
    $file_date = date("Y\\-m\\-d G\\:i\\:s", $p_header['mtime']);
    $path = make_path($uploadPath, $path_components);
    if ($p_header['folder']) {
        // Directory has been created by make_path(),
        // only need to update the index
        $r = Database::get()->querySingle("SELECT id FROM document WHERE {$group_sql} AND path = ?s", $path);
        Indexer::queueAsync(Indexer::REQUEST_STORE, Indexer::RESOURCE_DOCUMENT, $r->id);
        return 0;
    } else {
        // Check if file already exists
        $result = Database::get()->querySingle("SELECT id, path, visible FROM document\n                                           WHERE {$group_sql} AND\n                                                 path REGEXP ?s AND\n                                                 filename = ?s LIMIT 1", "^{$path}/[^/]+\$", $filename);
        $format = get_file_extension($filename);
        if ($result) {
            $old_id = $result->id;
            $file_path = $result->path;
            $vis = $result->visible;
            if ($replace) {
                // Overwrite existing file
                $p_header['filename'] = $basedir . $file_path;
                Database::get()->query("UPDATE document\n                                                 SET date_modified = ?t\n                                                 WHERE {$group_sql} AND\n                                                       id = ?d", $file_date, $old_id);
                return 1;
            } else {
                // Rename existing file
                $backup_n = 1;
                do {
                    $backup = preg_replace('/\\.[a-zA-Z0-9_-]+$/', '', $filename) . '_backup_' . $backup_n . '.' . $format;
                    $n = Database::get()->querySingle("SELECT COUNT(*) as count FROM document\n                                                              WHERE {$group_sql} AND\n                                                                    path REGEXP ?s AND\n                                                                    filename = ?s LIMIT 1", "^{$path}/[^/]+\$", $backup)->count;
                    $backup_n++;
                } while ($n > 0);
                Database::get()->query("UPDATE document SET filename = ?s\n                                                 WHERE {$group_sql} AND\n                                                       path = ?s", $backup, $file_path);
                Indexer::queueAsync(Indexer::REQUEST_STORE, Indexer::RESOURCE_DOCUMENT, $old_id);
            }
        }
        $path .= '/' . safe_filename($format);
        $id = Database::get()->query("INSERT INTO document SET\n                                 course_id = ?d,\n                                 subsystem = ?d,\n                                 subsystem_id = ?d,\n                                 path = ?s,\n                                 filename = ?s,\n                                 visible = 1,\n                                 comment = ?s,\n                                 category = ?d,\n                                 title = '',\n                                 creator = ?s,\n                                 date = ?t,\n                                 date_modified = ?t,\n                                 subject = ?s,\n                                 description = ?s,\n                                 author = ?s,\n                                 format = ?s,\n                                 language = ?s,\n                                 copyrighted = ?d", $course_id, $subsystem, $subsystem_id, $path, $filename, $file_comment, $file_category, $file_creator, $file_date, $file_date, $file_subject, $file_description, $file_author, $format, $file_language, $file_copyrighted)->lastInsertID;
        // Logging
        Indexer::queueAsync(Indexer::REQUEST_STORE, Indexer::RESOURCE_DOCUMENT, $id);
        Log::record($course_id, MODULE_ID_DOCS, LOG_INSERT, array('id' => $id, 'filepath' => $path, 'filename' => $filename, 'comment' => $file_comment));
        // File will be extracted with new encoded filename
        $p_header['filename'] = $basedir . $path;
        return 1;
    }
}
Пример #3
0
/**
 * This function executes our safety precautions
 * more functions can be added
 *
 * @param string $filename
 * @return string
 * @see php2phps()
 * @see htaccess2txt()
 */
function disable_dangerous_file($filename)
{
    return htaccess2txt(php2phps($filename));
}
Пример #4
0
/**
 * Renames a file or a directory
 *
 * @author - Hugues Peeters <*****@*****.**>
 * @param  - $file_path (string) - complete path of the file or the directory
 * @param  - $new_file_name (string) - new name for the file or the directory
 * @return - boolean - true if succeed
 *         - boolean - false otherwise
 * @see    - rename() uses the check_name_exist() and php2phps() functions
 */
function my_rename($file_path, $new_file_name)
{
    $save_dir = getcwd();
    $path = dirname($file_path);
    $old_file_name = basename($file_path);
    $new_file_name = api_replace_dangerous_char($new_file_name);
    // If no extension, take the old one
    if (strpos($new_file_name, '.') === false && ($dotpos = strrpos($old_file_name, '.'))) {
        $new_file_name .= substr($old_file_name, $dotpos);
    }
    // Note: still possible: 'xx.yy' -rename-> '.yy' -rename-> 'zz'
    // This is useful for folder names, where otherwise '.' would be sticky
    // Extension PHP is not allowed, change to PHPS
    $new_file_name = php2phps($new_file_name);
    if ($new_file_name == $old_file_name) {
        return $old_file_name;
    }
    if (strtolower($new_file_name) != strtolower($old_file_name) && check_name_exist($path . '/' . $new_file_name)) {
        return false;
    }
    // On a Windows server, it would be better not to do the above check
    // because it succeeds for some new names resembling the old name.
    // But on Unix/Linux the check must be done because rename overwrites.
    chdir($path);
    $res = rename($old_file_name, $new_file_name) ? $new_file_name : false;
    chdir($save_dir);
    return $res;
}
/**
 * @return array|null|string
 */
function store_add_dropbox()
{
    $_course = api_get_course_info();
    $_user = api_get_user_info();
    $dropbox_cnf = getDropboxConf();
    // Validating the form data
    // there are no recipients selected
    if (!isset($_POST['recipients']) || count($_POST['recipients']) <= 0) {
        return get_lang('YouMustSelectAtLeastOneDestinee');
    } else {
        // Check if all the recipients are valid
        $thisIsAMailing = false;
        $thisIsJustUpload = false;
        foreach ($_POST['recipients'] as $rec) {
            if ($rec == 'mailing') {
                $thisIsAMailing = true;
            } elseif ($rec == 'upload') {
                $thisIsJustUpload = true;
            } elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_')))) {
                return get_lang('InvalideUserDetected');
            } elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0) {
                return get_lang('InvalideGroupDetected');
            }
        }
    }
    // we are doing a mailing but an additional recipient is selected
    if ($thisIsAMailing && count($_POST['recipients']) != 1) {
        return get_lang('MailingSelectNoOther');
    }
    // we are doing a just upload but an additional recipient is selected.
    // note: why can't this be valid? It is like sending a document to yourself AND to a different person (I do this quite often with my e-mails)
    if ($thisIsJustUpload && count($_POST['recipients']) != 1) {
        return get_lang('MailingJustUploadSelectNoOther');
    }
    if (empty($_FILES['file']['name'])) {
        $error = true;
        return get_lang('NoFileSpecified');
    }
    // are we overwriting a previous file or sending a new one
    $dropbox_overwrite = false;
    if (isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']) {
        $dropbox_overwrite = true;
    }
    // doing the upload
    $dropbox_filename = $_FILES['file']['name'];
    $dropbox_filesize = $_FILES['file']['size'];
    $dropbox_filetype = $_FILES['file']['type'];
    $dropbox_filetmpname = $_FILES['file']['tmp_name'];
    // check if the filesize does not exceed the allowed size.
    if ($dropbox_filesize <= 0 || $dropbox_filesize > $dropbox_cnf['maxFilesize']) {
        return get_lang('DropboxFileTooBig');
        // TODO: The "too big" message does not fit in the case of uploading zero-sized file.
    }
    // check if the file is actually uploaded
    if (!is_uploaded_file($dropbox_filetmpname)) {
        // check user fraud : no clean error msg.
        return get_lang('TheFileIsNotUploaded');
    }
    $upload_ok = process_uploaded_file($_FILES['file'], true);
    if (!$upload_ok) {
        return null;
    }
    // Try to add an extension to the file if it hasn't got one
    $dropbox_filename = add_ext_on_mime($dropbox_filename, $dropbox_filetype);
    // Replace dangerous characters
    $dropbox_filename = replace_dangerous_char($dropbox_filename);
    // Transform any .php file in .phps fo security
    $dropbox_filename = php2phps($dropbox_filename);
    //filter extension
    if (!filter_extension($dropbox_filename)) {
        return get_lang('UplUnableToSaveFileFilteredExtension');
    }
    // set title
    $dropbox_title = $dropbox_filename;
    // set author
    if (!isset($_POST['authors'])) {
        $_POST['authors'] = getUserNameFromId($_user['user_id']);
    }
    // note: I think we could better migrate everything from here on to separate functions: store_new_dropbox, store_new_mailing, store_just_upload
    if ($dropbox_overwrite) {
        $dropbox_person = new Dropbox_Person($_user['user_id'], api_is_course_admin(), api_is_course_tutor());
        foreach ($dropbox_person->sentWork as $w) {
            if ($w->title == $dropbox_filename) {
                if ($w->recipients[0]['id'] > dropbox_cnf('mailingIdBase') xor $thisIsAMailing) {
                    return get_lang('MailingNonMailingError');
                }
                if ($w->recipients[0]['id'] == $_user['user_id'] xor $thisIsJustUpload) {
                    return get_lang('MailingJustUploadSelectNoOther');
                }
                $dropbox_filename = $w->filename;
                $found = true;
                // note: do we still need this?
                break;
            }
        }
    } else {
        // rename file to login_filename_uniqueId format
        $dropbox_filename = getLoginFromId($_user['user_id']) . "_" . $dropbox_filename . "_" . uniqid('');
    }
    // creating the array that contains all the users who will receive the file
    $new_work_recipients = array();
    foreach ($_POST['recipients'] as $rec) {
        if (strpos($rec, 'user_') === 0) {
            $new_work_recipients[] = substr($rec, strlen('user_'));
        } elseif (strpos($rec, 'group_') === 0) {
            $userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_')));
            foreach ($userList as $usr) {
                if (!in_array($usr['user_id'], $new_work_recipients) && $usr['user_id'] != $_user['user_id']) {
                    $new_work_recipients[] = $usr['user_id'];
                }
            }
        }
    }
    @move_uploaded_file($dropbox_filetmpname, dropbox_cnf('sysPath') . '/' . $dropbox_filename);
    $b_send_mail = api_get_course_setting('email_alert_on_new_doc_dropbox');
    if ($b_send_mail) {
        foreach ($new_work_recipients as $recipient_id) {
            $recipent_temp = UserManager::get_user_info_by_id($recipient_id);
            $additionalParameters = array('smsType' => ClockworksmsPlugin::NEW_FILE_SHARED_COURSE_BY, 'userId' => $recipient_id, 'courseTitle' => $_course['title'], 'userUsername' => $recipent_temp['username']);
            api_mail_html(api_get_person_name($recipent_temp['firstname'] . ' ' . $recipent_temp['lastname'], null, PERSON_NAME_EMAIL_ADDRESS), $recipent_temp['email'], get_lang('NewDropboxFileUploaded'), get_lang('NewDropboxFileUploadedContent') . ' ' . api_get_path(WEB_CODE_PATH) . 'dropbox/index.php?cidReq=' . $_course['sysCode'] . "\n\n" . api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS) . "\n" . get_lang('Email') . " : " . $_user['mail'], api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS), $_user['mail'], null, null, null, $additionalParameters);
        }
    }
    new Dropbox_SentWork($_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $new_work_recipients);
    Security::clear_token();
    return get_lang('FileUploadSucces');
}
Пример #6
0
/**
 * @param array $my_folder_data
 * @param array $_course
 * @return array
 */
function uploadWork($my_folder_data, $_course)
{
    if (empty($_FILES['file']['size'])) {
        return array('error' => Display :: return_message(get_lang('UplUploadFailedSizeIsZero'), 'error'));
    }
    $updir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/work/'; //directory path to upload

    // Try to add an extension to the file if it has'nt one
    $filename = add_ext_on_mime(stripslashes($_FILES['file']['name']), $_FILES['file']['type']);

    // Replace dangerous characters
    $filename = replace_dangerous_char($filename, 'strict');

    // Transform any .php file in .phps fo security
    $filename = php2phps($filename);
    $filesize = filesize($_FILES['file']['tmp_name']);

    if (empty($filesize)) {
        return array('error' => Display :: return_message(get_lang('UplUploadFailedSizeIsZero'), 'error'));
    } elseif (!filter_extension($new_file_name)) {
        return array('error' => Display :: return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error'));
    }

    $totalSpace = DocumentManager::documents_total_space($_course['real_id']);
    $course_max_space = DocumentManager::get_course_quota($_course['code']);
    $total_size = $filesize + $totalSpace;

    if ($total_size > $course_max_space) {
        return array(
            'error' => Display :: return_message(get_lang('NoSpace'), 'error')
        );
    }

    // Compose a unique file name to avoid any conflict
    $new_file_name = api_get_unique_id();
    $curdirpath = basename($my_folder_data['url']);

    // If we come from the group tools the groupid will be saved in $work_table
    if (is_dir($updir.$curdirpath) || empty($curdirpath)) {
        $result = move_uploaded_file(
            $_FILES['file']['tmp_name'],
            $updir.$curdirpath.'/'.$new_file_name
        );
    } else {
        return array(
            'error' => Display :: return_message(
                get_lang('FolderDoesntExistsInFileSystem'),
                'error'
            )
        );
    }

    $url = null;
    if ($result) {
        $url = 'work/'.$curdirpath.'/'.$new_file_name;
    }

    return array(
        'url' => $url,
        'filename' => $filename,
        'error' => null
    );
}
Пример #7
0
function claro_rename_file($oldFilePath, $newFilePath)
{
    if (realpath($oldFilePath) == realpath($newFilePath)) {
        return true;
    }
    /* CHECK IF THE NEW NAME HAS AN EXTENSION */
    if (!preg_match('/[[:print:]]+\\.[[:alnum:]]+$/', $newFilePath) and preg_match('/[[:print:]]+\\.([[:alnum:]]+)$/', $oldFilePath, $extension)) {
        $newFilePath .= '.' . $extension[1];
    }
    /* PREVENT FILE NAME WITH PHP EXTENSION */
    $newFilePath = php2phps($newFilePath);
    /* REPLACE CHARACTER POTENTIALY DANGEROUS FOR THE SYSTEM */
    $newFilePath = dirname($newFilePath) . '/' . replace_dangerous_char(my_basename($newFilePath));
    if (check_name_exist($newFilePath) && $newFilePath != $oldFilePath) {
        return false;
    } else {
        if (rename($oldFilePath, $newFilePath)) {
            return $newFilePath;
        } else {
            return false;
        }
    }
}
/**
 * Rename a file or a directory
 * 
 * @author - Hugues Peeters <*****@*****.**>
 * @param  - $filePath (string) - complete path of the file or the directory
 * @param  - $newFileName (string) - new name for the file or the directory
 * @return - boolean - true if succeed
 *         - boolean - false otherwise
 * @see    - rename() uses the check_name_exist() and php2phps() functions
 */
function my_rename($filePath, $newFileName)
{
    $path = $baseWorkDir . dirname($filePath);
    $oldFileName = basename($filePath);
    if (check_name_exist($path . '/' . $newFileName) && $newFileName != $oldFileName) {
        return false;
    } else {
        /*** check if the new name has an extension ***/
        if (!ereg("[[:print:]]+\\.[[:alnum:]]+\$", $newFileName) && ereg("[[:print:]]+\\.([[:alnum:]]+)\$", $olFileName, $extension)) {
            $newFileName .= '.' . $extension[1];
        }
        /*** Prevent file name with php extension ***/
        $newFileName = php2phps($newFileName);
        $newFileName = replace_dangerous_char($newFileName);
        chdir($path);
        rename($oldFileName, $newFileName);
        return true;
    }
}
Пример #9
0
             $recipients[] = $r;
         }
     }
     $recipients = array_unique($recipients);
     if (isset($_POST['message_title']) and $_POST['message_title'] != '') {
         $subject = $_POST['message_title'];
     } else {
         $subject = $langMessage;
     }
     $msg = new Msg($uid, $cid, $subject, $_POST['body'], $recipients, $filename, $real_filename, $filesize);
 } else {
     $cwd = getcwd();
     if (is_dir($dropbox_dir)) {
         $dropbox_space = dir_total_space($dropbox_dir);
     }
     $filename = php2phps($_FILES['file']['name']);
     $filesize = $_FILES['file']['size'];
     $filetype = $_FILES['file']['type'];
     $filetmpname = $_FILES['file']['tmp_name'];
     validateUploadedFile($_FILES['file']['name'], 1);
     if ($filesize + $dropbox_space > $diskQuotaDropbox) {
         $errormsg = $langNoSpace;
         $error = TRUE;
     } elseif (!is_uploaded_file($filetmpname)) {
         // check user found : no clean error msg
         die($langBadFormData);
     }
     // set title
     if (isset($_POST['message_title']) and $_POST['message_title'] != '') {
         $subject = $_POST['message_title'];
     } else {
Пример #10
0
function upload_images($new_theme_id = null) {
    global $webDir, $theme, $theme_id;
    if (isset($new_theme_id)) $theme_id = $new_theme_id;
    if(!is_dir("$webDir/courses/theme_data/$theme_id")) {
        mkdir("$webDir/courses/theme_data/$theme_id", 0755);
    }
    $images = array('bgImage','imageUpload','imageUploadSmall','loginImg');
    foreach($images as $image) {
        if (isset($_FILES[$image]) && is_uploaded_file($_FILES[$image]['tmp_name'])) {
            $file_name = $_FILES[$image]['name'];
            validateUploadedFile($file_name, 2);
            $i=0;
            while (is_file("$webDir/courses/theme_data/$theme_id/$file_name")) {
                $i++;
                $name = pathinfo($file_name, PATHINFO_FILENAME);
                $ext =  get_file_extension($file_name);
                $file_name = "$name-$i.$ext";
            }
            $file_name = php2phps($file_name);
            move_uploaded_file($_FILES[$image]['tmp_name'], "$webDir/courses/theme_data/$theme_id/$file_name");
            $_POST[$image] = $file_name;
        }
    }
}
Пример #11
0
         $cloudfile = CloudFile::fromJSON($_POST['fileCloudInfo']);
         $file_name = $cloudfile->name();
     } else if (isset($_FILES['userFile']) && is_uploaded_file($_FILES['userFile']['tmp_name'])) { // upload local file
         $file_name = $_FILES['userFile']['name'];
         if ($diskUsed + @$_FILES['userFile']['size'] > $diskQuotaVideo) {
             $tool_content .= "<div class='alert alert-danger'>$langNoSpace<br>
                                             <a href='$_SERVER[SCRIPT_NAME]?course=$course_code'>$langBack</a></div><br>";
             draw($tool_content, $menuTypeID, null, $head_content);
             exit;
         } else {
             $tmpfile = $_FILES['userFile']['tmp_name'];
         }
     }
     validateUploadedFile($file_name, $menuTypeID);
     // convert php file in phps to protect the platform against malicious codes
     $file_name = php2phps($file_name);                    
     $file_name = str_replace(" ", "%20", $file_name);
     $file_name = str_replace("%20", "", $file_name);
     $file_name = str_replace("\'", "", $file_name);
     $uploaded = true;
 if ($uploaded) {
     $safe_filename = sprintf('%x', time()) . randomkeys(16) . "." . get_file_extension($file_name);
     if (isset($cloudfile)) {
         $iscopy = ($cloudfile->storeToLocalFile("$updir/$safe_filename") == CloudDriveResponse::OK);                    
     } else {                    
         $iscopy = copy("$tmpfile", "$updir/$safe_filename");
     }
     if (!$iscopy) {
         $tool_content .= "<div class='alert alert-success'>$langFileNot<br>
                                     <a href='$_SERVER[SCRIPT_NAME]?course=$course_code'>$langBack</a></div>";
         draw($tool_content, $menuTypeID, null, $head_content);
Пример #12
0
 if ($student_can_edit_in_session && $check) {
     // Check the token inserted into the form
     if (isset($_POST['submitWork'])) {
         $url = null;
         $contains_file = 0;
         $title = isset($_POST['title']) ? $_POST['title'] : null;
         $description = isset($_POST['description']) ? $_POST['description'] : null;
         if ($_POST['contains_file'] && !empty($_FILES['file']['size'])) {
             $updir = $currentCourseRepositorySys . 'work/';
             //directory path to upload
             // Try to add an extension to the file if it has'nt one
             $new_file_name = add_ext_on_mime(stripslashes($_FILES['file']['name']), $_FILES['file']['type']);
             // Replace dangerous characters
             $new_file_name = replace_dangerous_char($new_file_name, 'strict');
             // Transform any .php file in .phps fo security
             $new_file_name = php2phps($new_file_name);
             $filesize = filesize($_FILES['file']['tmp_name']);
             if (empty($filesize)) {
                 $error_message .= Display::return_message(get_lang('UplUploadFailedSizeIsZero'), 'error');
                 $succeed = false;
             } elseif (!filter_extension($new_file_name)) {
                 //filter extension
                 $error_message .= Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error');
                 $succeed = false;
             }
             if (!$title) {
                 $title = $_FILES['file']['name'];
             }
             // Compose a unique file name to avoid any conflict
             $new_file_name = api_get_unique_id();
             $curdirpath = basename($my_folder_data['url']);
Пример #13
0
            if ($filesize + $dropbox_space > $diskQuotaDropbox) {
                $errormsg = $langNoSpace;
                $error = TRUE;
            } elseif (!is_uploaded_file($filetmpname)) { // check user found : no clean error msg
                die($langBadFormData);
            }
            // set title
            if (isset($_POST['message_title']) and $_POST['message_title'] != '') {
                $subject = $_POST['message_title'];
            } else {
                $subject = $langMessage;
            }
            $format = get_file_extension($filename);
            $real_filename = $filename;
            $filename = safe_filename($format);
            $filename = php2phps($filename);
            $recipients = $_POST["recipients"];
            //After uploading the file, create the db entries
            if (!$error) {
                $filename_final = $dropbox_dir . '/' . $filename;
                move_uploaded_file($filetmpname, $filename_final) or die($langUploadError);
                @chmod($filename_final, 0644);

                $msg = new Msg($uid, $cid, $subject, $_POST['body'], $recipients, $filename, $real_filename, $filesize);
            }
            chdir($cwd);
        }
        $msgURL = $urlServer . 'modules/dropbox/index.php?mid=' . $msg->id;
        if (isset($_POST['mailing']) and $_POST['mailing']) { // send mail to recipients of dropbox file
            if ($course_id != 0 || isset($_POST['course'])) {//message in course context
                $c = course_id_to_title($cid);
Пример #14
0
/**
 *
 *
 * @author Hugues Peeters <*****@*****.**>
 * @param array $uploadedFileCollection - follows the $_FILES Structure
 * @param  string $destPath
 * @return string $destPath
 */
function move_uploaded_file_collection_into_directory($uploadedFileCollection, $destPath)
{
    $uploadedFileNb = count($uploadedFileCollection['name']);
    $newFileList = array();
    for ($i = 0; $i < $uploadedFileNb; $i++) {
        if (!empty($uploadedFileCollection['name'])) {
            if (is_uploaded_file($uploadedFileCollection['tmp_name'][$i])) {
                if (move_uploaded_file($uploadedFileCollection['tmp_name'][$i], $destPath . '/' . php2phps($uploadedFileCollection['name'][$i]))) {
                    $newFileList[$i] = basename($destPath) . '/' . $uploadedFileCollection['name'][$i];
                } else {
                    // FIXME use clro_die or a better error reporting system
                    die('<center>can not move uploaded file</center>');
                }
            }
        }
    }
    return $newFileList;
}
Пример #15
0
 $dropbox_filetmpname = $_FILES['file']['tmp_name'];
 if ($dropbox_filesize <= 0 || $dropbox_filesize > dropbox_cnf('maxFilesize')) {
     $errormsg = get_lang('TooBig');
     // TODO: The "too big" message does not fit in the case of uploading zero-sized file.
     $error = true;
 } elseif (!is_uploaded_file($dropbox_filetmpname)) {
     // check user fraud : no clean error msg.
     die(get_lang('BadFormData') . ' (code 403)');
 }
 if (!$error) {
     // Try to add an extension to the file if it hasn't got one
     $dropbox_filename = add_ext_on_mime($dropbox_filename, $dropbox_filetype);
     // Replace dangerous characters
     $dropbox_filename = api_replace_dangerous_char($dropbox_filename);
     // Transform any .php file in .phps fo security
     $dropbox_filename = php2phps($dropbox_filename);
     if (!filter_extension($dropbox_filename)) {
         $error = true;
         $errormsg = get_lang('UplUnableToSaveFileFilteredExtension');
     } else {
         // set title
         $dropbox_title = $dropbox_filename;
         // set author
         if ($_POST['authors'] == '') {
             $_POST['authors'] = getUserNameFromId($_user['user_id']);
         }
         if ($dropbox_overwrite) {
             $dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
             foreach ($dropbox_person->sentWork as $w) {
                 if ($w->title == $dropbox_filename) {
                     if ($w->recipients[0]['id'] > dropbox_cnf('mailingIdBase') xor $thisIsAMailing) {
Пример #16
0
             $vis = $result->visible;
             Database::get()->query("DELETE FROM document WHERE\n                                                 {$group_sql} AND\n                                                 path = ?s", $file_path);
         } else {
             $error = $langFileExists;
         }
     }
 }
 if ($error) {
     $action_message .= "<div class='alert alert-danger'>{$error}</div><br>";
 } elseif ($uploaded) {
     // No errors, so proceed with upload
     // File date is current date
     $file_date = date("Y\\-m\\-d G\\:i\\:s");
     // Try to add an extension to files witout extension,
     // change extension of PHP files
     $fileName = php2phps(add_ext_on_mime($fileName));
     // File name used in file system and path field
     $safe_fileName = safe_filename(get_file_extension($fileName));
     if ($uploadPath == '.') {
         $file_path = '/' . $safe_fileName;
     } else {
         $file_path = $uploadPath . '/' . $safe_fileName;
     }
     if ($extra_path or isset($userFile) and @copy($userFile, $basedir . $file_path)) {
         $vis = 1;
         $file_format = get_file_extension($fileName);
         $id = Database::get()->query("INSERT INTO document SET\n                                        course_id = ?d,\n                                        subsystem = ?d,\n                                        subsystem_id = ?d,\n                                        path = ?s,\n                                        extra_path = ?s,\n                                        filename = ?s,\n                                        visible = ?d,\n                                        comment = ?s,\n                                        category = ?d,\n                                        title = ?s,\n                                        creator = ?s,\n                                        date = ?t,\n                                        date_modified = ?t,\n                                        subject = ?s,\n                                        description = ?s,\n                                        author = ?s,\n                                        format = ?s,\n                                        language = ?s,\n                                        copyrighted = ?d", $course_id, $subsystem, $subsystem_id, $file_path, $extra_path, $fileName, $vis, $_POST['file_comment'], $_POST['file_category'], $_POST['file_title'], $_POST['file_creator'], $file_date, $file_date, $_POST['file_subject'], $_POST['file_description'], $_POST['file_author'], $file_format, $_POST['file_language'], $_POST['file_copyrighted'])->lastInsertID;
         Indexer::queueAsync(Indexer::REQUEST_STORE, Indexer::RESOURCE_DOCUMENT, $id);
         // Logging
         Log::record($course_id, MODULE_ID_DOCS, LOG_INSERT, array('id' => $id, 'filepath' => $file_path, 'filename' => $fileName, 'comment' => $_POST['file_comment'], 'title' => $_POST['file_title']));
         Session::Messages($langDownloadEnd, 'alert-success');
Пример #17
0
 $docId = $result->id;
 $oldpath = $result->path;
 $oldformat = $result->format;
 $curDirPath = my_dirname($_POST['replacePath']);
 // check for disk quota
 if ($diskUsed - filesize($basedir . $oldpath) + $_FILES['newFile']['size'] > $diskQuotaDocument) {
     Session::Messages($langNoSpace, 'alert-danger');
     redirect_to_current_dir();
 } elseif (unwanted_file($_FILES['newFile']['name'])) {
     Session::Messages($langUnwantedFiletype . ": " . q($_FILES['newFile']['name']), 'alert-danger');
     redirect_to_current_dir();
 } else {
     $newformat = get_file_extension($_FILES['newFile']['name']);
     $newpath = preg_replace("/\\.$oldformat$/", '', $oldpath) .
             (empty($newformat) ? '' : '.' . $newformat);
     $newpath = php2phps($newpath);
     my_delete($basedir . $oldpath);
     $affectedRows = Database::get()->query("UPDATE document SET path = ?s, format = ?s, filename = ?s, date_modified = NOW()
               WHERE $group_sql AND path = ?s"
                     , $newpath, $newformat, ($_FILES['newFile']['name']), $oldpath)->affectedRows;
     if (!copy($_FILES['newFile']['tmp_name'], $basedir . $newpath) or $affectedRows == 0) {
         Session::Messages($langGeneralError, 'alert-danger');
         redirect_to_current_dir();
     } else {
         if (hasMetaData($oldpath, $basedir, $group_sql)) {
             rename($basedir . $oldpath . ".xml", $basedir . $newpath . ".xml");
             Database::get()->query("UPDATE document SET path = ?s, filename=?s WHERE $group_sql AND path = ?s"
                     , ($newpath . ".xml"), ($_FILES['newFile']['name'] . ".xml"), ($oldpath . ".xml"));
         }
         $session->setDocumentTimestamp($course_id);
         Indexer::queueAsync(Indexer::REQUEST_STORE, Indexer::RESOURCE_DOCUMENT, $docId);