<?php // $Id$

// (Shirai014): 更新日時／ファイルサイズで並べ替え (2008/1/14)
// (Shirai014): ここから追加
//  $sortorderfilelist is 
//    1=asort(filename),  2=arsort(filename)
//    3=ksort(filemtime), 4=krsort(filemtime)
//    5=ksort(filesize),  6=krsort(filesize)
    $sortorderfilelist = optional_param('sortorderfilelist', 0, PARAM_INT);
    if ($sortorderfilelist < 1) {
        if (isset($_SESSION['sortorderfilelist'])) $sortorderfilelist = $_SESSION['sortorderfilelist'];
            else $sortorderfilelist = 1; 
    } else $_SESSION['sortorderfilelist'] = $sortorderfilelist;
// (Shirai014): ここまで追加
class resource_directory extends resource_base {

function resource_directory($cmid=0) {
    parent::resource_base($cmid);
}

function add_instance($resource) {
    $this->_postprocess($resource);
    return parent::add_instance($resource);
}

function update_instance($resource) {
    $this->_postprocess($resource);
    return parent::update_instance($resource);
}

function _postprocess(&$resource) {
    if($resource->reference=='0')
        $resource->reference = '';
// (Shirai006): リソースの追加／フォルダの表示でフォルダの作成＋選択を可能とする改良
// (Shirai006): 以下１行を追加
    if (!empty($resource->reference2)) $resource->reference = $resource->reference2;
// (Shirai006): ここまで追加

    $resource->popup = '';
    $resource->alltext = '';
}

function display() {
    global $CFG;
// (Shirai014): 更新日時／ファイルサイズで並べ替え (2008/1/14)
// (Shirai014): 以下一行を追加
    global $sortorderfilelist;
// (Shirai014): ここまで

/// Set up generic stuff first, including checking for access
    parent::display();

/// Set up some shorthand variables
    $cm = $this->cm;
    $course = $this->course;
    $resource = $this->resource;

    require_once($CFG->libdir.'/filelib.php');

    $subdir = optional_param('subdir','', PARAM_PATH);
    $resource->reference = clean_param($resource->reference, PARAM_PATH);

    $formatoptions = new object();
    $formatoptions->noclean = true;
    $formatoptions->para = false; // MDL-12061, <p> in html editor breaks xhtml strict

    add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id);

    if ($resource->reference) {
        $relativepath = "{$course->id}/{$resource->reference}";
    } else {
        $relativepath = "{$course->id}";
    }

    if ($subdir) {
        $relativepath = "$relativepath$subdir";
        if (stripos($relativepath, 'backupdata') !== FALSE or stripos($relativepath, $CFG->moddata) !== FALSE) {
            error("Access not allowed!");
        }

        $subs = explode('/', $subdir);
        array_shift($subs);
        $countsubs = count($subs);
        $count = 0;
        $backsub = '';

        foreach ($subs as $sub) {
            $count++;
            if ($count < $countsubs) {
                $backsub .= "/$sub";
                
                $this->navlinks[] = array('name' => $sub, 'link' => "view.php?id={$cm->id}", 'type' => 'title');
            } else {
                $this->navlinks[] = array('name' => $sub, 'link' => '', 'type' => 'title');
            }
        }
    }

    $pagetitle = strip_tags($course->shortname.': '.format_string($resource->name));

    $update = update_module_button($cm->id, $course->id, $this->strresource);
    if (has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $course->id))) {
        $options = array('id'=>$course->id, 'wdir'=>'/'.$resource->reference.$subdir);
        $editfiles = print_single_button("$CFG->wwwroot/files/index.php", $options, get_string("editfiles"), 'get', '', true);
        $update = $editfiles.$update;
    }
    $navigation = build_navigation($this->navlinks, $cm);
    print_header($pagetitle, $course->fullname, $navigation,
            "", "", true, $update,
            navmenu($course, $cm));


    if (trim(strip_tags($resource->summary))) {
        print_simple_box(format_text($resource->summary, FORMAT_MOODLE, $formatoptions, $course->id), "center");
        print_spacer(10,10);
    }

// (Shirai014): 更新日時／ファイルサイズで並べ替え (2008/1/14)
// (Shirai014): ここからコメントアウト
//  $files = get_directory_list("$CFG->dataroot/$relativepath", array($CFG->moddata, 'backupdata'), false, true, true);
// (Shirai014): ここから追加
    $dirs = get_directory_list("$CFG->dataroot/$relativepath", array($CFG->moddata, 'backupdata'), false, true, false);
    $files = get_directory_list("$CFG->dataroot/$relativepath", array($CFG->moddata, 'backupdata'), false, false, true);
    $dirlist = $filelist = array();
    foreach ($dirs as $file) {
        switch ($sortorderfilelist) {
          case 3: case 4:
            $sortkeystr = strftime('%Y%m%d%H%M%S', fs_filemtime("$CFG->dataroot/$relativepath/$file"));
            break;
          case 5: case 6:
            $sortkeystr = strval(get_directory_size("$CFG->dataroot/$relativepath/$file"));
            break;
          case 1: case 2: default:
            $sortkeystr = $file;
            break;
		}
        $dirlist['0'.$file] = $sortkeystr;  
        // $dirlist["0"]が$dirlist[0]になってしまうため'0'を付けて$dirlist["00"]とする．
    }
    foreach ($files as $file) {
        switch ($sortorderfilelist) {
          case 3: case 4:
            $sortkeystr = strftime('%Y%m%d%H%M%S', fs_filemtime("$CFG->dataroot/$relativepath/$file"));
            break;
          case 5: case 6:
            $sortkeystr = strval(fs_filesize("$CFG->dataroot/$relativepath/$file"));
            break;
          default:
            $sortkeystr = $file; break;
		}
        $filelist['0'.$file] = $sortkeystr;
        // $filelist["0"]が$filelist[0]になってしまうため'0'を付けて$filelist["00"]とする．
    }
// (Shirai014): ここまで追加


// (Shirai014): 更新日時／ファイルサイズで並べ替え (2008/1/14)
//  if (!$files) {  
    if (empty($dirlist) && empty($filelist)) {
// (Shirai014): ここまで
        print_heading(get_string("nofilesyet"));
        print_footer($course);
        exit;
    }

    print_simple_box_start("center", "", "", '0' );

    $strftime = get_string('strftimedatetime');
    $strname = get_string("name");
    $strsize = get_string("size");
    $strmodified = get_string("modified");
    $strfolder = get_string("folder");
    $strfile = get_string("file");
// (Shirai014): 更新日時／ファイルサイズで並べ替え (2008/1/14)
// (Shirai014): ここから追加
    $reloadurl = "<a href=\"view.php?id={$cm->id}&amp;subdir=".rawurlencode($subdir)."&amp;";
    $strname .= "&nbsp(";
    $strname .= $sortorderfilelist == 1 ? "&#x25B2;/" : $reloadurl."sortorderfilelist=1\">&#x25B2;</a>/";
    $strname .= $sortorderfilelist == 2 ? "&#x25BC;)" : $reloadurl."sortorderfilelist=2\">&#x25BC;</a>)";
    $strmodified .= "&nbsp(";
    $strmodified .= $sortorderfilelist == 3 ? "&#x25B2;/" : $reloadurl."sortorderfilelist=3\">&#x25B2;</a>/";
    $strmodified .= $sortorderfilelist == 4 ? "&#x25BC;)" : $reloadurl."sortorderfilelist=4\">&#x25BC;</a>)";
    $strsize .= "&nbsp(";
    $strsize .= $sortorderfilelist == 5 ? "&#x25B2;/" : $reloadurl."sortorderfilelist=5\">&#x25B2;</a>/";
    $strsize .= $sortorderfilelist == 6 ? "&#x25BC;)" : $reloadurl."sortorderfilelist=6\">&#x25BC;</a>)";
// (Shirai014): ここまで追加

    echo '<table cellpadding="4" cellspacing="1" class="files" summary="">';
    echo "<tr><th class=\"header name\" scope=\"col\">$strname</th>".
         "<th align=\"right\" colspan=\"2\" class=\"header size\" scope=\"col\">$strsize</th>".
         "<th align=\"right\" class=\"header date\" scope=\"col\">$strmodified</th>".
         "</tr>";
// (Shirai014): 更新日時／ファイルサイズで並べ替え (2008/1/14)
// (Shirai014): ここからコメントアウト
//  foreach ($files as $file) {
// (Shirai014): ここから追加
    switch ($sortorderfilelist) {
      case 2:  case 4: case 6:  arsort($dirlist); arsort($filelist); break;
      case 3:  case 5: default: asort($dirlist);  asort($filelist);  break;
    }
    $files = $dirlist + $filelist;  // 同名のフォルダとファイルは作成不可なので重複してもＯＫ
    foreach ($files as $file => $dummy) {
        $file = substr($file, 1);  // 頭のダミーの'0'を取り除く
// (Shirai014): ここまで追加
// (FS_CONVERTER): ここから
//      if (is_dir("$CFG->dataroot/$relativepath/$file")) {          // Must be a directory
        if (fs_is_dir("$CFG->dataroot/$relativepath/$file")) {          // Must be a director
// (FS_CONVERTER): ここまで
            $icon = "folder.gif";
            $relativeurl = "/view.php?blah";
            $filesize = display_size(get_directory_size("$CFG->dataroot/$relativepath/$file"));

        } else {
            $icon = mimeinfo("icon", $file);
            $relativeurl = get_file_url("$relativepath/$file");
// (FS_CONVERTER): ここから
//          $filesize = display_size(filesize("$CFG->dataroot/$relativepath/$file"));
            $filesize = display_size(fs_filesize("$CFG->dataroot/$relativepath/$file"));
// (FS_CONVERTER): ここまで
        }

        if ($icon == 'folder.gif') {
            echo '<tr class="folder">';
            echo '<td class="name">';
// (IE_Problem014): ＩＥでサブディレクトリに移動できない
//          echo "<a href=\"view.php?id={$cm->id}&amp;subdir=$subdir/$file\">";
            echo "<a href=\"view.php?id={$cm->id}&amp;subdir=".fs_rawurlencode("$subdir/$file")."\">";
// (IE_Problem014): ここまで
            echo "<img src=\"$CFG->pixpath/f/$icon\" class=\"icon\" alt=\"$strfolder\" />&nbsp;$file</a>";
        } else {
            echo '<tr class="file">';
            echo '<td class="name">';
            link_to_popup_window($relativeurl, "resourcedirectory{$resource->id}", "<img src=\"$CFG->pixpath/f/$icon\" class=\"icon\" alt=\"$strfile\" />&nbsp;$file", 450, 600, '');
        }
        echo '</td>';
        echo '<td>&nbsp;</td>';
        echo '<td align="right" class="size">';
        echo $filesize;
        echo '</td>';
        echo '<td align="right" class="date">';
// (FS_CONVERTER): ここから
//      echo userdate(filemtime("$CFG->dataroot/$relativepath/$file"), $strftime);
        echo userdate(fs_filemtime("$CFG->dataroot/$relativepath/$file"), $strftime);
// (FS_CONVERTER): ここまで
        echo '</td>';
        echo '</tr>';
    }
    echo '</table>';

    print_simple_box_end();

    print_footer($course);

}


function setup($form) {
    global $CFG;

    parent::setup($form);

    $rawdirs = get_directory_list("$CFG->dataroot/{$this->course->id}", array($CFG->moddata, 'backupdata'), true, true, false);
    $dirs = array();
    foreach ($rawdirs as $rawdir) {
        $dirs[$rawdir] = $rawdir;
    }

    include("$CFG->dirroot/mod/resource/type/directory/directory.html");

    parent::setup_end();
}

function setup_elements(&$mform) {
    global $CFG;

    $rawdirs = get_directory_list($CFG->dataroot.'/'.$this->course->id, array($CFG->moddata, 'backupdata'), true, true, false);
    $dirs = array();
    $dirs[0]=get_string('maindirectory', 'resource');
    foreach ($rawdirs as $rawdir) {
        $dirs[$rawdir] = $rawdir;
    }

// (Shirai006): リソースの追加／フォルダの表示でフォルダの作成＋選択を可能とする改良
// (Shirai006): 以下の２行をコメントアウト
//  $mform->addElement('select', 'reference', get_string('resourcetypedirectory', 'resource'), $dirs);
//  $mform->setDefault('windowpopup', 0);
// (Shirai006): ここから追加
    $mform->addElement('select', 'reference', '(1) 既存フォルダのリストから選択', $dirs);
    $mform->setDefault('windowpopup', 0);
    $mform->addElement('choosecoursefile', 'reference2', '(2) ファイルエディタで作成・選択');
//  $mform->setDefault('reference2', $CFG->resource_defaulturl); // 現在の設定値が分かるならばここにセットできる．
    $mform->addRule('name', null, 'required', null, 'client');
// (Shirai006): ここまで追加

}


}

?>
