/** * Given the full path of a file, try to find the user the file * corresponds to and assign him/her this file as his/her picture. * Make extensive checks to make sure we don't open any security holes * and report back any success/error. * * @param string $file the full path of the file to process * @param string $userfield the prefix_user table field to use to * match picture files to users. * @param bool $overwrite overwrite existing picture or not. * * @return integer either PIX_FILE_UPDATED, PIX_FILE_ERROR or * PIX_FILE_SKIPPED */ function process_file($file, $userfield, $overwrite) { // Add additional checks on the filenames, as they are user // controlled and we don't want to open any security holes. $path_parts = pathinfo(cleardoubleslashes($file)); $basename = $path_parts['basename']; $extension = $path_parts['extension']; if ($basename != clean_param($basename, PARAM_CLEANFILE)) { // The original picture file name has invalid characters notify(get_string('uploadpicture_invalidfilename', 'admin', clean_param($basename, PARAM_CLEANHTML))); return PIX_FILE_ERROR; } // The picture file name (without extension) must match the // userfield attribute. $uservalue = substr($basename, 0, strlen($basename) - strlen($extension) - 1); // userfield names are safe, so don't quote them. if (!($user = get_record('user', $userfield, addslashes($uservalue)))) { $a = new Object(); $a->userfield = clean_param($userfield, PARAM_CLEANHTML); $a->uservalue = clean_param($uservalue, PARAM_CLEANHTML); notify(get_string('uploadpicture_usernotfound', 'admin', $a)); return PIX_FILE_ERROR; } $haspicture = get_field('user', 'picture', 'id', $user->id); if ($haspicture && !$overwrite) { notify(get_string('uploadpicture_userskipped', 'admin', $user->username)); return PIX_FILE_SKIPPED; } if (my_save_profile_image($user->id, $file)) { set_field('user', 'picture', 1, 'id', $user->id); notify(get_string('uploadpicture_userupdated', 'admin', $user->username)); return PIX_FILE_UPDATED; } else { notify(get_string('uploadpicture_cannotsave', 'admin', $user->username)); return PIX_FILE_ERROR; } }
/** * Zip an array of files/dirs to a destination zip file * Both parameters must be FULL paths to the files/dirs * * @global object * @param array $originalfiles Files to zip * @param string $destination The destination path * @return bool Outcome */ function zip_files ($originalfiles, $destination) { global $CFG; //Extract everything from destination $path_parts = pathinfo(cleardoubleslashes($destination)); $destpath = $path_parts["dirname"]; //The path of the zip file $destfilename = $path_parts["basename"]; //The name of the zip file $extension = $path_parts["extension"]; //The extension of the file //If no file, error if (empty($destfilename)) { return false; } //If no extension, add it if (empty($extension)) { $extension = 'zip'; $destfilename = $destfilename.'.'.$extension; } //Check destination path exists if (!is_dir($destpath)) { return false; } //Check destination path is writable. TODO!! //Clean destination filename $destfilename = clean_filename($destfilename); //Now check and prepare every file $files = array(); $origpath = NULL; foreach ($originalfiles as $file) { //Iterate over each file //Check for every file $tempfile = cleardoubleslashes($file); // no doubleslashes! //Calculate the base path for all files if it isn't set if ($origpath === NULL) { $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/"); } //See if the file is readable if (!is_readable($tempfile)) { //Is readable continue; } //See if the file/dir is in the same directory than the rest if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) { continue; } //Add the file to the array $files[] = $tempfile; } $zipfiles = array(); $start = strlen($origpath)+1; foreach($files as $file) { $zipfiles[substr($file, $start)] = $file; } $packer = get_file_packer('application/zip'); return $packer->archive_to_pathname($zipfiles, $destpath . '/' . $destfilename); }
} else { displaydir($wdir); } html_footer(); break; case "restore": html_header($course, $wdir); if ($file != '' and confirm_sesskey()) { echo "<p align=\"center\">" . get_string("youaregoingtorestorefrom") . ":</p>"; print_simple_box_start("center"); echo $file; print_simple_box_end(); echo "<br />"; echo "<p align=\"center\">" . get_string("areyousuretorestorethisinfo") . "</p>"; $restore_path = "{$CFG->wwwroot}/backup/restore.php"; notice_yesno(get_string("areyousuretorestorethis"), $restore_path . "?id=" . $id . "&file=" . cleardoubleslashes($id . $wdir . "/" . $file) . "&method=manual", "index.php?id={$id}&wdir={$wdir}&action=cancel"); } else { displaydir($wdir); } html_footer(); break; case "cancel": clearfilelist(); default: html_header($course, $wdir); displaydir($wdir); html_footer(); break; } /// FILE FUNCTIONS /////////////////////////////////////////////////////////// function setfilelist($VARS)
function backup_zip($preferences) { global $CFG; $status = true; //Base dir where everything happens $basedir = cleardoubleslashes($CFG->dataroot . "/temp/backup/" . $preferences->backup_unique_code); //Backup zip file name $name = $preferences->backup_name; //List of files and directories $filelist = list_directories_and_files($basedir); //Convert them to full paths $files = array(); foreach ($filelist as $file) { $files[] = "{$basedir}/{$file}"; } $status = zip_files($files, "{$basedir}/{$name}"); //echo "<br/>Status: ".$status; //Debug return $status; }
function fm_view_zipped($file, $groupid) { global $CFG, $USER; if ($file->folder == 0) { if ($groupid == 0) { $ziploc = $CFG->dataroot . "/" . fm_get_user_dir_space(); //."/".$file->link; } else { $ziploc = $CFG->dataroot . "/" . fm_get_group_dir_space($groupid); //."/".$file->link; } } else { if ($groupid == 0) { $ziploc = $CFG->dataroot . "/" . fm_get_user_dir_space() . fm_get_folder_path($file->folder, false, $goupid); //."/".$file->link; } else { $ziploc = $CFG->dataroot . "/" . fm_get_group_dir_space($groupid) . fm_get_folder_path($file->folder, false, $goupid); //."/".$file->link; } } /*$filelist = array(); $zip = zip_open($ziploc); if ($zip) { $count = 0; while ($zip_entry = zip_read($zip)) { $filelist[$count]->name = zip_entry_name($zip_entry); $filelist[$count]->actualsize = zip_entry_filesize($zip_entry); $filelist[$count]->compsize = zip_entry_compressedsize($zip_entry); $count++; } zip_close($zip); }*/ include_once "{$CFG->libdir}/pclzip/pclzip.lib.php"; $archive = new PclZip(cleardoubleslashes("{$ziploc}/{$file->link}")); if (!($zip = $archive->listContent(cleardoubleslashes("{$ziploc}")))) { notify($archive->errorInfo(true)); } else { $count = 0; foreach ($zip as $file) { $filelist[$count]->name = $file['filename']; $filelist[$count]->actualsize = $file['size']; $filelist[$count]->compsize = $file['compressed_size']; $count++; } } return $filelist; }
/** * Function to check if a directory exists and optionally create it. * * @param string absolute directory path (must be under $CFG->dataroot) * @param boolean create directory if does not exist * @param boolean create directory recursively * * @return boolean true if directory exists or created */ function check_dir_exists($dir, $create = false, $recursive = false) { global $CFG; if (strstr(cleardoubleslashes($dir), cleardoubleslashes($CFG->dataroot . '/')) === false) { debugging('Warning. Wrong call to check_dir_exists(). $dir must be an absolute path under $CFG->dataroot ("' . $dir . '" is incorrect)', DEBUG_DEVELOPER); } $status = true; if (!is_dir($dir)) { if (!$create) { $status = false; } else { umask(00); if ($recursive) { /// We are going to make it recursive under $CFG->dataroot only /// (will help sites running open_basedir security and others) $dir = str_replace(cleardoubleslashes($CFG->dataroot . '/'), '', cleardoubleslashes($dir)); /// PHP 5.0 has recursive mkdir parameter, but 4.x does not :-( $dirs = explode('/', $dir); /// Extract path parts /// Iterate over each part with start point $CFG->dataroot $dir = $CFG->dataroot . '/'; foreach ($dirs as $part) { if ($part == '') { continue; } $dir .= $part . '/'; if (!is_dir($dir)) { if (!mkdir($dir, $CFG->directorypermissions)) { $status = false; break; } } } } else { $status = mkdir($dir, $CFG->directorypermissions); } } } return $status; }
/** * This function shows the results of the unzip execution * depending of the value of the $CFG->zip, results will be * text or an array of files. */ function unzip_show_status($list, $removepath) { global $CFG; if (empty($CFG->unzip)) { // Use built-in php-based zip function $strname = get_string("name"); $strsize = get_string("size"); $strmodified = get_string("modified"); $strstatus = get_string("status"); echo "<table cellpadding=\"4\" cellspacing=\"2\" border=\"0\" width=\"640\">"; echo "<tr><th class=\"header\" align=\"left\">{$strname}</th>"; echo "<th class=\"header\" align=\"right\">{$strsize}</th>"; echo "<th class=\"header\" align=\"right\">{$strmodified}</th>"; echo "<th class=\"header\" align=\"right\">{$strstatus}</th></tr>"; foreach ($list as $item) { echo "<tr>"; $item['filename'] = str_replace(cleardoubleslashes($removepath) . '/', "", $item['filename']); print_cell("left", $item['filename']); if (!$item['folder']) { print_cell("right", display_size($item['size'])); } else { echo "<td> </td>"; } $filedate = userdate($item['mtime'], get_string("strftimedatetime")); print_cell("right", $filedate); print_cell("right", $item['status']); echo "</tr>"; } echo "</table>"; } else { // Use external zip program print_simple_box_start("center"); echo "<pre>"; foreach ($list as $item) { echo str_replace(cleardoubleslashes($removepath . '/'), '', $item) . '<br />'; } echo "</pre>"; print_simple_box_end(); } }
/** * Given the full path of a file, try to find the user the file * corresponds to and assign him/her this file as his/her picture. * Make extensive checks to make sure we don't open any security holes * and report back any success/error. * * @param string $file the full path of the file to process * @param string $userfield the prefix_user table field to use to * match picture files to users. * @param bool $overwrite overwrite existing picture or not. * * @return integer either PIX_FILE_UPDATED, PIX_FILE_ERROR or * PIX_FILE_SKIPPED */ function process_file($file, $userfield, $overwrite) { global $DB, $OUTPUT; // Add additional checks on the filenames, as they are user // controlled and we don't want to open any security holes. $path_parts = pathinfo(cleardoubleslashes($file)); $basename = $path_parts['basename']; $extension = $path_parts['extension']; // The picture file name (without extension) must match the // userfield attribute. $uservalue = substr($basename, 0, strlen($basename) - strlen($extension) - 1); // userfield names are safe, so don't quote them. if (!($user = $DB->get_record('user', array($userfield => $uservalue, 'deleted' => 0)))) { $a = new stdClass(); $a->userfield = clean_param($userfield, PARAM_CLEANHTML); $a->uservalue = clean_param($uservalue, PARAM_CLEANHTML); echo $OUTPUT->notification(get_string('uploadpicture_usernotfound', 'tool_uploaduser', $a)); return PIX_FILE_ERROR; } $haspicture = $DB->get_field('user', 'picture', array('id' => $user->id)); if ($haspicture && !$overwrite) { echo $OUTPUT->notification(get_string('uploadpicture_userskipped', 'tool_uploaduser', $user->username)); return PIX_FILE_SKIPPED; } if ($newrev = my_save_profile_image($user->id, $file)) { $DB->set_field('user', 'picture', $newrev, array('id' => $user->id)); echo $OUTPUT->notification(get_string('uploadpicture_userupdated', 'tool_uploaduser', $user->username), 'notifysuccess'); return PIX_FILE_UPDATED; } else { echo $OUTPUT->notification(get_string('uploadpicture_cannotsave', 'tool_uploaduser', $user->username)); return PIX_FILE_ERROR; } }
function unzip_show_status($list, $removepath) { //This function shows the results of the unzip execution //depending of the value of the $CFG->zip, results will be //text or an array of files. global $CFG; if (empty($CFG->unzip)) { // Use built-in php-based zip function $strname = get_string("name"); $strsize = get_string("size"); $strmodified = get_string("modified"); $strstatus = get_string("status"); echo "<table width=\"640\">"; echo "<tr><th class=\"header\" scope=\"col\">{$strname}</th>"; echo "<th class=\"header\" align=\"right\" scope=\"col\">{$strsize}</th>"; echo "<th class=\"header\" align=\"right\" scope=\"col\">{$strmodified}</th>"; echo "<th class=\"header\" align=\"right\" scope=\"col\">{$strstatus}</th></tr>"; foreach ($list as $item) { echo "<tr>"; $item['filename'] = str_replace(cleardoubleslashes($removepath) . '/', "", $item['filename']); print_cell("left", s($item['filename'])); if (!$item['folder']) { print_cell("right", display_size($item['size'])); } else { echo "<td> </td>"; } $filedate = userdate($item['mtime'], get_string("strftimedatetime")); print_cell("right", $filedate); print_cell("right", $item['status']); echo "</tr>"; } echo "</table>"; } else { // Use external zip program print_simple_box_start("center"); echo "<pre>"; foreach ($list as $item) { echo s(str_replace(cleardoubleslashes($removepath . '/'), '', $item)) . '<br />'; } echo "</pre>"; print_simple_box_end(); } }
case "listzip": html_header($course, $wdir); if (!empty($file) and confirm_sesskey()) { $strname = get_string("name"); $strsize = get_string("size"); $strmodified = get_string("modified"); $strok = get_string("ok"); $strlistfiles = get_string("listfiles", "", $file); $prop = null; $prop->class = "textcenter"; wiki_div($strlistfiles . ":", $prop); wiki_br(); $file = basename($file); include_once "{$CFG->libdir}/pclzip/pclzip.lib.php"; $archive = new PclZip(cleardoubleslashes("{$basedir}/{$wdir}/{$file}")); if (!($list = $archive->listContent(cleardoubleslashes("{$basedir}/{$wdir}")))) { notify($archive->errorInfo(true)); } else { $prop = null; $prop->border = "0"; $prop->spacing = "2"; $prop->padding = "4"; $prop->width = "640"; $prop->class = "files"; $prop->header = true; $prop->alignth = "left"; $prop->classth = "header name"; wiki_table_start($prop); echo $strname; $prop = null; $prop->header = true;
/** * Function to check if a directory exists and optionally create it. * * @param string absolute directory path (must be under $CFG->dataroot) * @param boolean create directory if does not exist * @param boolean create directory recursively * @return boolean true if directory exists or created */ function check_dir_exists($dir, $create = false, $recursive = false) { global $CFG; if (strstr(cleardoubleslashes($dir), cleardoubleslashes($CFG->dataroot . '/')) === false) { debugging('Warning. Wrong call to check_dir_exists(). $dir must be an absolute path under $CFG->dataroot ("' . $dir . '" is incorrect)', DEBUG_DEVELOPER); } $status = true; if (!is_dir($dir)) { if (!$create) { $status = false; } else { $status = mkdir($dir, $CFG->directorypermissions, $recursive); } } return $status; }
$filepath = $CFG->dataroot . '/temp/alfresco/' . $filename; /// Write the file contents to a temporary file (if needed). if (!file_exists($filepath)) { if (($filedata = $repo->read_file($uuid, $filepath)) == false) { print_error('couldnotgetfiledataforuuid', 'repository_alfresco', '', $uuid); } } $strname = get_string("name"); $strsize = get_string("size"); $strmodified = get_string("modified"); $strok = get_string("ok"); $strlistfiles = get_string("listfiles", "", $file); echo "<p align=\"center\">{$strlistfiles}:</p>"; include_once $CFG->libdir . '/pclzip/pclzip.lib.php'; $archive = new PclZip(cleardoubleslashes($filepath)); if (!($list = $archive->listContent(cleardoubleslashes($filepath)))) { debugging($archive->errorInfo(true)); } else { echo "<table cellpadding=\"4\" cellspacing=\"2\" border=\"0\">\n"; echo "<tr>\n<th align=\"left\" scope=\"col\">{$strname}</th><th align=\"right\" scope=\"col\">{$strsize}</th><th align=\"right\" scope=\"col\">{$strmodified}</th></tr>"; foreach ($list as $item) { echo "<tr>"; print_cell("left", $item['filename']); if (!$item['folder']) { print_cell("right", display_size($item['size'])); } else { echo "<td> </td>\n"; } $filedate = userdate($item['mtime'], get_string("strftimedatetime")); print_cell("right", $filedate); echo "</tr>\n";
function extract_to_temp($source) { global $id, $CFG; // Make temp dir $temp_dir = $CFG->dataroot . '/temp/anti_plagiarism/' . $id . '/'; fulldelete($temp_dir); if (!check_dir_exists($temp_dir, true, true)) { error("Can't mkdir " . $temp_dir); } if ($files = get_directory_list($source)) { foreach ($files as $key => $file) { $dir = $temp_dir . dirname($file); if (!check_dir_exists($dir, true, true)) { error("Can't mkdir " . $dir); } $path_parts = pathinfo(cleardoubleslashes($file)); $ext = $path_parts["extension"]; //The extension of the file if ($ext === 'rar' && !empty($CFG->block_antipla_unrar_path)) { $command = "export LC_ALL={$CFG->locale} ; {$CFG->block_antipla_unrar_path} e -y {$source}{$file} {$temp_dir}" . dirname($file) . '/ >/dev/null'; system($command); } else { if ($ext === 'zip') { unzip_file($source . $file, $temp_dir . dirname($file), false); //Move all files to its home root $basedir = $temp_dir . dirname($file) . '/'; if ($fs = get_directory_list($basedir)) { foreach ($fs as $k => $f) { rename($basedir . $f, $basedir . basename($f)); } } } else { if ($ext === 'gz') { $command = "tar zxf {$source}{$file} -C {$temp_dir}" . dirname($file); system($command); //Move all files to its home root $basedir = $temp_dir . dirname($file) . '/'; if ($fs = get_directory_list($basedir)) { foreach ($fs as $k => $f) { rename($basedir . $f, $basedir . basename($f)); } } } else { if (!copy($source . $file, $temp_dir . $file)) { error('Can\'t copy file'); } } } } } } return $temp_dir; }
function referentiel_copy_document_file($referentiel_referentiel_id, $user_creator, $userid, $file_uri) { // Moodle 1.9 :: $file_uri= 2/moddata/referentiel/1/3/arrete-C2i2eVDef.pdf // Moodle 2.x :: $file_uri= /contextid/mod_referentiel/document/ID/arrete-C2i2eVDef.pdf // /153/mod_referentiel/document/4/referentiel-epc.csv global $CFG; require_once $CFG->libdir . '/filelib.php'; $status = 0; //First we check that "user_files" exists and create it if necessary //in temp/archive/$backup_code dir if (referentiel_check_and_create_document_files_dir($referentiel_referentiel_id, $user_creator, $userid)) { $fullpath = $file_uri; // Traitement de $fullpath if ($fullpath && preg_match('/\\//', $fullpath)) { $t_fullpath = explode('/', $fullpath, 6); if (!empty($t_fullpath) && empty($t_fullpath[0])) { $garbage = array_shift($t_fullpath); } if (!empty($t_fullpath)) { list($contextid, $component, $filearea, $itemid, $path) = $t_fullpath; if ($path) { if (preg_match('/\\//', $path)) { $filename = substr($path, strrpos($path, '/') + 1); $path = '/' . substr($path, 0, strrpos($path, '/') + 1); } else { $filename = $path; $path = '/'; } } } } // echo "<br />DEBUG :: lib.php :: Ligne 5918 ::<br /> $contextid, $component, $filearea, $itemid, $path, $filename\n"; // devrait afficher cas 0 :: 0, mod_referentiel, referentiel, 0, /, jf44.png // devrait afficher cas 1 :: 30, mod_referentiel, referentiel, 0, /rep1/rep2/, jf44.png // devrait afficher cas 2 :: 51, mod_referentiel, referentiel, 12, /, jf44.png $fs = get_file_storage(); // Get file $file = $fs->get_file($contextid, $component, $filearea, $itemid, $path, $filename); if ($file) { // DEBUG // echo "<br />DEBUG :: 220 :: $filename\n"; // print_object($file); // echo "<br />CONTENU\n"; $contents = $file->get_content(); // echo htmlspecialchars($contents); // $filesize = $file->get_filesize(); // $filename = $file->get_filename(); // $mimetype = $file->get_mimetype(); // $timecreated = userdate($file->get_timecreated(),"%Y/%m/%d-%H:%M",99,false); // $timemodified = userdate($file->get_timemodified(),"%Y/%m/%d-%H:%M",99,false); // $link= new moodle_url($CFG->wwwroot.'/pluginfile.php/'.$contextid.'/mod_referentiel/'.$filearea.'/'.$itemid.'/'.$filename); // $url='<a href="'.$link.'" target="_blank">'.$filename.'</a><br />'."\n"; $file_dest_path_name = "document_files/" . $userid . "/" . $filename; //exit; // Moodle 2.0 // $f=fopen($CFG->dataroot."/temp/archive/".$referentiel_referentiel_id."/".$user_creator."/".$file_dest_path_name,"w"); // Moodle 22 $path_temp = cleardoubleslashes(get_string('archivetemp', 'referentiel') . '/' . $referentiel_referentiel_id . '/' . $user_creator); // Moodle 2.2 $temp_dir = make_temp_directory($path_temp); $f = fopen(cleardoubleslashes($temp_dir . "/" . $file_dest_path_name), "w"); $status = fwrite($f, $contents); fclose($f); } } if ($status) { return $file_dest_path_name; } else { return ''; } }
/** * Do an post-processing that may be required * @return boolean success */ function exportpostprocess($archive_name) { // ici realiser la compression ZIP global $CFG; $archive_name .= '.zip'; // Moodle 2 : $fullpath = cleardoubleslashes($CFG->dataroot . '/' . $this->context->id . '/mod_referentiel/archive/' . $this->get_export_dir() . '/' . $archive_name); // echo "<br />DEBUG :: format.php/exportpostprocess :: 3281 :: FILENAME : $archive_name<br />FULNAME : $fullpath\n"; if (referentiel_backup_zip($this->rreferentiel->id, $this->user_creator, $archive_name)) { // deplacer vers le dossier // Moodle 2 // $from_file = cleardoubleslashes($CFG->dataroot.'/'.$this->get_temp_dir().'/'.$archive_name); $from_file = cleardoubleslashes($this->get_temp_dir() . '/' . $archive_name); // echo "<br />DEBUG :: format.php/exportpostprocess :: 3288 :: FROM_FILE :$from_file\n"; if (referentiel_copy_file_moodle2_api($from_file, $this->get_export_dir(), $archive_name, $this->context)) { // supprimer le dossier temporaire // remove_dir($CFG->dataroot.'/'.$this->get_temp_dir(), true); remove_dir($this->get_temp_dir(), true); return true; } } return false; }