File:  [LON-CAPA] / loncom / publisher / lonpubdir.pm
Revision 1.170: download - view: text, annotated - select for diffs
Wed Nov 30 18:38:48 2016 UTC (7 years, 6 months ago) by damieng
Branches: MAIN
CVS tags: HEAD
fixed bug 6835

    1: # The LearningOnline Network with CAPA
    2: # Authoring Space Directory Lister
    3: #
    4: # $Id: lonpubdir.pm,v 1.170 2016/11/30 18:38:48 damieng Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonpubdir;
   31: 
   32: use strict;
   33: use Apache::File;
   34: use File::Copy;
   35: use Apache::Constants qw(:common :http :methods);
   36: use Apache::loncommon();
   37: use Apache::lonhtmlcommon();
   38: use Apache::londiff();
   39: use Apache::lonlocal;
   40: use Apache::lonmsg;
   41: use Apache::lonmenu;
   42: use Apache::lonnet;
   43: use LONCAPA qw(:DEFAULT :match);
   44: 
   45: sub handler {
   46: 
   47:     my $r=shift;
   48: 
   49:     # Validate access to the construction space and get username:domain.
   50: 
   51:     my ($uname,$udom)=&Apache::lonnet::constructaccess($r->uri); 
   52:     unless (($uname) && ($udom)) {
   53:         return HTTP_NOT_ACCEPTABLE;
   54:     }
   55: 
   56: # ----------------------------------------------------------- Start page output
   57: 
   58:     my $fn=$r->filename;
   59:     $fn=~s/\/$//;
   60:     my $thisdisfn=$fn;
   61: 
   62:     my $docroot=$r->dir_config('lonDocRoot');     # Apache  londocument root.
   63:     if ($thisdisfn eq "$docroot/priv/$udom") {
   64:         if ((-d "/home/$uname/public_html/") && (!-e "$docroot/priv/$udom/$uname")) {
   65:             my ($version) = ($r->dir_config('lonVersion') =~ /^\'?(\d+\.\d+)\./);
   66:             &Apache::loncommon::content_type($r,'text/html');
   67:             $r->send_http_header;
   68: 
   69:             &Apache::lonhtmlcommon::clear_breadcrumbs();
   70:             my $js = '<script type="text/javascript" 
   71:                         src="/res/adm/includes/file_upload.js"></script>';
   72:             $r->print(&Apache::loncommon::start_page('Authoring Space', $js).
   73:                       '<div class="LC_error">'.
   74:                       '<br /><p>'.
   75:                       &mt('Your Authoring Space is currently in the location used by LON-CAPA version 2.10 and older, but your domain is using a newer LON-CAPA version ([_1]).',$version).'</p>'.
   76:                       '<p>'.
   77:                       &mt('Please ask your Domain Coordinator to move your Authoring Space to the new location.').
   78:                       '</p>'.
   79:                       '</div>'.
   80:                       &Apache::loncommon::end_page());
   81:             return OK;
   82:         }
   83:     }
   84:     $thisdisfn=~s/^\Q$docroot\E\/priv//;
   85: 
   86:     my $resdir=$docroot.'/res'.$thisdisfn; # Resource directory
   87:     my $targetdir='/res'.$thisdisfn; # Publication target directory.
   88:     my $linkdir='/priv'.$thisdisfn;      # Full URL name of constr space.
   89: 
   90:     my $cstr = 'author';
   91:     my ($crsauthor,$crstype);
   92:     if ($env{'request.course.id'}) {
   93:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
   94:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
   95:         if ($thisdisfn =~ m{^/\Q$cdom/$cnum\E}) {
   96:             $crsauthor = 1;
   97:             $cstr = 'course';
   98:             $crstype = &Apache::loncommon::course_type();
   99:         }
  100:     }
  101: 
  102:     my %bombs=&Apache::lonmsg::all_url_author_res_msg($uname,$udom);
  103: 
  104:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
  105:     my $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,
  106:                                 "$londocroot/priv/$udom/$uname"); # expressed in kB
  107:     my $disk_quota = &Apache::loncommon::get_user_quota($uname,$udom,
  108:                                                  $cstr,$crstype); # expressed in MB
  109: 
  110:     # Put out the start of page.
  111:     &startpage($r, $uname, $udom, $thisdisfn, $current_disk_usage, $disk_quota, $crsauthor); 
  112: 
  113:     if (!-d $fn) {
  114:         if (-e $fn) {
  115:             $r->print('<p class="LC_info">'.&mt('Requested item is a file not a directory.').'</p>');
  116:         } else {
  117:             $r->print('<p class="LC_info">'.&mt('The requested subdirectory does not exist.').'</p>');
  118:         }
  119:         $r->print(&Apache::loncommon::end_page());
  120:         return OK;
  121:     }
  122:     my @files;
  123:     if (opendir(DIR,$fn)) {
  124:         @files = grep(!/^\.+$/,readdir(DIR));
  125:         closedir(DIR);
  126:     } else {
  127:         $r->print('<p class="LC_error">'.&mt('Could not open directory.').'</p>');
  128:         $r->print(&Apache::loncommon::end_page());
  129:         return OK;
  130:     }
  131: 
  132:     # Put out actions for directory, browse/upload + new file page.
  133:     &dircontrols($r,$uname,$udom,$thisdisfn, $current_disk_usage, $disk_quota);
  134:     &resourceactions($r,$uname,$udom,$thisdisfn); # Put out form used for printing/deletion etc.
  135: 
  136:     my $numdir = 0;
  137:     my $numres = 0;
  138:   
  139:     if ((@files == 0) && ($thisdisfn =~ m{^/$match_domain/$match_username})) {
  140:         if ($thisdisfn =~ m{^/$match_domain/$match_username$}) {
  141:             $r->print('<p class="LC_info">'.&mt('This Authoring Space is currently empty.').'</p>');
  142:         } else {
  143:             $r->print('<p class="LC_info">'.&mt('This subdirectory is currently empty.').'</p>');
  144:         }
  145:         $r->print(&Apache::loncommon::end_page());
  146:         return OK;
  147:     }
  148: 
  149:     # Retrieving value for "sortby" and "sortorder" from QUERY_STRING
  150:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  151:         ['sortby','sortorder']);
  152: 
  153:     # Sort by name as default, not reversed
  154:     if (! exists($env{'form.sortby'})) { $env{'form.sortby'} = 'filename' }
  155:     if (! exists($env{'form.sortorder'})) { $env{'form.sortorder'} = '' }
  156:     my $sortby = $env{'form.sortby'};
  157:     my $sortorder = $env{'form.sortorder'};
  158: 
  159:     # Order in which columns are displayed from left to right
  160:     my @order = ('filetype','actions','filename','title',
  161:                     'pubstatus','cmtime','size');
  162: 
  163:     # Up and down arrows to indicate sort order
  164:     my @arrows = ('&nbsp;&#9650;','&nbsp;&#9660;','');
  165: 
  166:     # Default sort order and column title
  167:     my %columns = (
  168:         filetype =>     {
  169:                             order => 'ascending',
  170:                             text  => &mt('Type'),
  171:                         },
  172:         actions =>      {
  173:                             # Not sortable
  174:                             text  => &mt('Actions'),
  175:                         },
  176:         filename =>     {
  177:                             order => 'ascending',
  178:                             text  => &mt('Name'),
  179:                         },
  180:         title =>        {
  181:                             order => 'ascending',
  182:                             text  => &mt('Title'),
  183:                         },
  184:         pubstatus =>    {
  185:                             order => 'ascending',
  186:                             text  => &mt('Status'),
  187:                             colspan => '2',
  188:                         },
  189:         cmtime =>       {
  190:                             order => 'descending',
  191:                             text  => &mt('Last Modified'),
  192:                         },
  193:         size =>         {
  194:                             order => 'ascending',
  195:                             text  => &mt('Size').' (kB)',
  196:                         },
  197:     ); 
  198: 
  199:     # Print column headers
  200:     my $output = '';
  201:     foreach my $key (@order) {
  202:         my $idx;
  203:         # Append an up or down arrow to sorted column
  204:         if ($sortby eq $key) {
  205:             $idx = ($columns{$key}{order} eq 'ascending') ? 0:1;
  206:             if ($sortorder eq 'rev') { $idx ++; }
  207:             $idx = $idx%2;
  208:         } else { $idx = 2; } # No arrow if column is not sorted
  209:         $output .= (($columns{$key}{order}) ?
  210:             '<th'.($columns{$key}{colspan} ? ' colspan="'.$columns{$key}{colspan}.'"' : '')
  211:             .'><a href="'.$linkdir.'/?sortby='.$key.'&amp;sortorder='
  212:             .((($sortby eq $key) && ($sortorder ne 'rev')) ? 'rev' : '').'">'
  213:             .$columns{$key}{text}.$arrows[$idx].'</a></th>' :
  214:             '<th>'.$columns{$key}{text}.'</th>');
  215:     }
  216: 
  217: my $result = "<script type=\"text/javascript\">
  218:     sessionStorage.setItem('CSTRcache','".&prepareJsonData($uname,$udom,$thisdisfn)."');
  219:     localStorage.setItem('CSTRtrans', '".&prepareJsonTranslations()."');
  220: </script>";
  221:     $r->print($result);
  222: 
  223:     $r->print('<div id="currentFolder">'.&Apache::loncommon::start_data_table()
  224:         .'<tr><th colspan="8" id="searchtitle" style="display:none"></th></tr>'
  225:         .&Apache::loncommon::start_data_table_header_row() . $output
  226:         .&Apache::loncommon::end_data_table_header_row()
  227:     );
  228: 
  229:     my $dirptr=16384;		# Mask indicating a directory in stat.cmode.
  230:     my $filehash = {};
  231:     foreach my $filename (@files) {
  232:         # Skip .DS_Store, .DAV and hidden files
  233:         my ($extension) = ($filename=~/\.(\w+)$/);
  234:         next if (($filename eq '.DS_Store')
  235:                 || ($filename eq '.DAV')
  236:                 || (&Apache::loncommon::fileembstyle($extension) eq 'hdn')
  237:                 || ($filename =~ /^\._/));
  238: 
  239:         my ($cmode,$csize,$cmtime)=(stat($fn.'/'.$filename))[2,7,9];
  240:         my $linkfilename = &HTML::Entities::encode('/priv'.$thisdisfn.'/'.$filename,'<>&"');
  241:         # Identify type of file according to icon used
  242:         my ($filetype) = (&Apache::loncommon::icon($filename) =~ m{/(\w+).gif$}); 
  243:         my $cstr_dir = $r->dir_config('lonDocRoot').'/priv'.$thisdisfn;
  244:         my $meta_same = &isMetaSame($cstr_dir, $resdir, $filename);
  245:         
  246:         # Store size, title, and status for files but not directories
  247:         my $size = (!($cmode&$dirptr)) ? $csize/1024. : 0;
  248:         my ($status, $pubstatus, $title, $fulltitle);
  249:         if (!($cmode&$dirptr)) {
  250:             ($status, $pubstatus) = &getStatus($resdir, $targetdir, $cstr_dir, 
  251:                 $filename, $linkfilename, $cmtime, $meta_same);
  252:             ($fulltitle, $title) = &getTitle($resdir, $targetdir, $filename, 
  253:                                         $linkfilename, $meta_same, \%bombs);
  254:         } else {
  255:             ($status, $pubstatus) = ('','');
  256:             ($fulltitle, $title) = ('','');
  257:         }
  258: 
  259:         # This hash will allow sorting
  260:         $filehash->{ $filename } = {
  261:             "cmtime"            => $cmtime,
  262:             "size"              => $size,
  263:             "cmode"             => $cmode,
  264:             "filetype"          => $filetype,
  265:             "title"             => $title,
  266:             "fulltitle"         => $fulltitle,
  267:             "status"            => $status,
  268:             "pubstatus"         => $pubstatus,
  269:             "linkfilename"      => $linkfilename,
  270:         }
  271:     }
  272:    
  273:     my @sorted_files;
  274:     # Sorting by something other than "Name".  Name is the secondary key.
  275:     if ($sortby =~ m{cmtime|size}) {    # Numeric fields
  276:         # First check if order should be reversed
  277:         if ($sortorder eq "rev") {
  278:             @sorted_files = sort {
  279:                 $filehash->{$a}->{$sortby} <=> $filehash->{$b}->{$sortby}
  280:                     or
  281:                 uc($a) cmp uc($b)
  282:             } (keys(%{$filehash}));
  283:         } else {
  284:             @sorted_files = sort {
  285:                 $filehash->{$b}->{$sortby} <=> $filehash->{$a}->{$sortby}
  286:                     or
  287:                 uc($a) cmp uc($b)
  288:             } (keys(%{$filehash}));
  289:         }
  290:     } elsif ($sortby =~ m{filetype|title|status}) {     # String fields
  291:         if ($sortorder eq "rev") {
  292:             @sorted_files = sort {
  293:                 $filehash->{$b}->{$sortby} cmp $filehash->{$a}->{$sortby}
  294:                     or
  295:                 uc($a) cmp uc($b)
  296:             } (keys(%{$filehash}));
  297:         } else {
  298:             @sorted_files = sort {
  299:                 $filehash->{$a}->{$sortby} cmp $filehash->{$b}->{$sortby}
  300:                     or
  301:                 uc($a) cmp uc($b)
  302:             } (keys(%{$filehash}));
  303:         }
  304: 
  305:     # Sort by "Name" is the default
  306:     } else { 
  307:         if ($sortorder eq "rev") {
  308:             @sorted_files = sort {uc($b) cmp uc($a)} (keys(%{$filehash}));
  309:         } else {
  310:             @sorted_files = sort {uc($a) cmp uc($b)} (keys(%{$filehash}));
  311:         }
  312:     }
  313: 
  314:     # Print the sorted resources
  315:     foreach my $filename (@sorted_files) {
  316:         if ($filehash->{$filename}->{"cmode"}&$dirptr) {        # Directories
  317:             &putdirectory($r, $thisdisfn, $linkdir, $filename, 
  318:                 $filehash->{$filename}->{"cmtime"}, 
  319:                 $targetdir, \%bombs, \$numdir);
  320:         } else {                                                # Files
  321:             &putresource($r, $udom, $uname, $filename, $thisdisfn, $resdir,
  322:                 $targetdir, $linkdir, $filehash->{$filename}->{"cmtime"}, 
  323:                 $filehash->{$filename}->{"size"}, \$numres, 
  324:                 $filehash->{$filename}->{"linkfilename"},
  325:                 $filehash->{$filename}->{"fulltitle"},
  326:                 $filehash->{$filename}->{"status"},
  327:                 $filehash->{$filename}->{"pubstatus"});
  328:         }
  329:     }
  330: 
  331:   $r->print(&Apache::loncommon::end_data_table()
  332:            .'</div><div id="otherplaces" style="display:none">'
  333:            .&Apache::loncommon::start_data_table()
  334:            .'<tr><th colspan="7">'.&mt('Results in other directories:').'</th></tr>'
  335:            .'<tr class="LC_header_row" id="otherplacestable">'
  336:            .'<th>'.&mt('Type').'</th>'
  337:            .'<th>'.&mt('Directory').'</th>'
  338:            .'<th>'.&mt('Name').'</th>'
  339:            .'<th>'.&mt('Title').'</th>'
  340:            .'<th colspan="2">'.&mt('Status').'</th>'
  341:            .'<th>'.&mt('Last Modified').'</th>'
  342:            .'</tr>'
  343:            .&Apache::loncommon::end_data_table()
  344:            .'</div>'
  345:            .&Apache::loncommon::end_page()
  346:   );
  347:   return OK;  
  348: }
  349: 
  350: 
  351: 
  352: #   Output the header of the page.  This includes:
  353: #   - The HTML header 
  354: #   - The H1/H3  stuff which includes the directory.
  355: #
  356: #     startpage($r, $uame, $udom, $thisdisfn, $current_disk_usage, $disk_quota);
  357: #      $r     - The apache request object.
  358: #      $uname - User name.
  359: #      $udom  - Domain name the user is logged in under.
  360: #      $thisdisfn - Displayable version of the filename.
  361: #      $current_disk_usage - User's current disk usage (in kB).
  362: #      $disk_quota - Disk quota for user's authoring space (in MB).
  363: #      $crstype - Course type, if this is for "course author"
  364: 
  365: sub startpage {
  366:     my ($r, $uname, $udom, $thisdisfn, $current_disk_usage, $disk_quota, $crsauthor) = @_;
  367:     &Apache::loncommon::content_type($r,'text/html');
  368:     $r->send_http_header;
  369: 
  370:     my $formaction='/priv'.$thisdisfn.'/';
  371:     $formaction=~s|/+|/|g;
  372: 
  373:     my $title;
  374:     if ($crsauthor) {
  375:         $title = 'Course Authoring';
  376:     } else {
  377:         $title = 'Authoring Space';
  378:         &Apache::lonhtmlcommon::store_recent('construct',$formaction,$formaction);
  379:     }
  380: 
  381:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  382:     &Apache::lonhtmlcommon::add_breadcrumb({
  383:         'text'  => $title,
  384:         'href'  => &Apache::loncommon::authorspace($formaction),
  385:     });
  386:     # breadcrumbs (and tools) will be created 
  387:     # in start_page->bodytag->innerregister
  388: 
  389:     $env{'request.noversionuri'}=$formaction;
  390:     my $js = '<script type="text/javascript" 
  391:                 src="/res/adm/includes/file_upload.js"></script>';
  392:     $r->print(&Apache::loncommon::start_page($title, $js));
  393: 
  394:     $disk_quota = 1024 * $disk_quota; # convert from MB to kB
  395: 
  396:     $r->print(&Apache::loncommon::head_subbox(
  397:                      '<div style="float:right;padding-top:0;margin-top;0">'
  398:                     .&Apache::lonhtmlcommon::display_usage($current_disk_usage,
  399:                                                            $disk_quota,'authoring')
  400:                     .'</div>'
  401:                     .&Apache::loncommon::CSTR_pageheader()));
  402: 
  403:     my $esc_thisdisfn = &Apache::loncommon::escape_single($thisdisfn);
  404:     my $doctitle = 'LON-CAPA '.&mt($title);
  405:     my $newname = &mt('New Name');
  406:     my $pubdirscript=(<<ENDPUBDIRSCRIPT);
  407: <script type="text/javascript">
  408: top.document.title = '$esc_thisdisfn/ - $doctitle';
  409: // Store directory location for menu bar to find
  410: 
  411: parent.lastknownpriv='/priv$esc_thisdisfn/';
  412: 
  413: // Confirmation dialogues
  414: 
  415:     function currdiract(theform) {
  416:         if (theform.dirtask.options[theform.dirtask.selectedIndex].value == 'publish') {
  417:             document.publishdir.filename.value = theform.filename.value;
  418: 	    document.publishdir.submit();
  419:         }
  420:         if (theform.dirtask.options[theform.dirtask.selectedIndex].value == 'editmeta') {
  421:             top.location=theform.filename.value+'default.meta'
  422:         }
  423:         if (theform.dirtask.options[theform.dirtask.selectedIndex].value == 'printdir' ) {
  424:             document.printdir.postdata.value=theform.filename.value
  425:             document.printdir.submit();
  426:         }
  427:         if (theform.dirtask.options[theform.dirtask.selectedIndex].value == "delete") {
  428:               var delform = document.delresource
  429:               delform.filename.value = theform.filename.value
  430:               delform.submit()
  431:         }
  432:     }
  433:   
  434:     function checkUpload(theform) {
  435:         if (theform.file == '') {
  436:             alert("Please use 'Browse..' to choose a file first, before uploading")
  437:             return 
  438:         }
  439:         theform.submit()  
  440:     }
  441: 
  442:     function SetPubDir(theform,printForm) {
  443:         if (theform.diraction.options[theform.diraction.selectedIndex].value == "open") {
  444:             top.location = theform.openname.value
  445:             return
  446:         }
  447:         if (theform.diraction.options[theform.diraction.selectedIndex].value == "publish") {
  448:             theform.submit();
  449:         }
  450:         if (theform.diraction.options[theform.diraction.selectedIndex].value == "editmeta") {
  451:             top.location=theform.filename.value+'default.meta'
  452:         }
  453:         if (theform.diraction.options[theform.diraction.selectedIndex].value == "printdir") {
  454:             theform.action = '/adm/printout'
  455:             theform.postdata.value = theform.filename.value
  456:             theform.submit()
  457:         }
  458:         if (theform.diraction.options[theform.diraction.selectedIndex].value == "delete") {
  459:               var delform = document.delresource
  460:               delform.filename.value = theform.filename.value
  461:               delform.submit()
  462:         }
  463:         return
  464:     }
  465:     function SetResChoice(theform) {
  466:       var activity = theform.reschoice.options[theform.reschoice.selectedIndex].value
  467:       if ((activity == 'rename') || (activity == 'copy') || (activity == 'move')) {
  468:           changename(theform,activity)
  469:       }
  470:       if (activity == 'publish') {
  471:           var pubform = document.pubresource
  472:           pubform.filename.value = theform.filename.value
  473:           pubform.submit()
  474:       }
  475:       if (activity == 'delete') {
  476:           var delform = document.delresource
  477:           delform.filename.value = theform.filename.value
  478:           delform.submit()
  479:       }
  480:       if (activity == 'obsolete') {
  481:           var pubform = document.pubresource
  482:           pubform.filename.value = theform.filename.value
  483:           pubform.makeobsolete.value=1;
  484:           pubform.submit()
  485:       }
  486:       if (activity == 'print') {
  487:           document.printresource.postdata.value = theform.filename.value
  488:           document.printresource.submit()
  489:       }
  490:       if (activity == 'retrieve') {
  491:           document.retrieveres.filename.value = theform.filename.value
  492:           document.retrieveres.submit()
  493:       }
  494:       if (activity == 'cleanup') {
  495:           document.cleanup.filename.value = theform.filename.value
  496:           document.cleanup.submit()
  497:       }
  498:       return
  499:     }
  500:     function changename(theform,activity) {
  501:         var oldname=theform.dispfilename.value;
  502:         var newname=prompt('$newname',oldname);
  503:         if (newname == "" || !newname || newname == oldname)  {
  504:             return
  505:         }
  506:         document.moveresource.newfilename.value = newname
  507:         document.moveresource.filename.value = theform.filename.value
  508:         document.moveresource.action.value = activity
  509:         document.moveresource.submit();
  510:     }
  511: </script>
  512: ENDPUBDIRSCRIPT
  513:     $r->print($pubdirscript);
  514: }
  515: 
  516: sub dircontrols {
  517:     my ($r,$uname,$udom,$thisdisfn, $current_disk_usage, $disk_quota) = @_;
  518:     my %lt=&Apache::lonlocal::texthash(
  519:                                        cnpd => 'Cannot publish directory',
  520:                                        cnrd => 'Cannot retrieve directory',
  521:                                        mcdi => 'Must create new subdirectory inside a directory',
  522:                                        pubr => 'Publish this Resource',
  523:                                        pubd => 'Publish this Directory',
  524:                                        dedr => 'Delete Directory',
  525:                                        rtrv => 'Retrieve Old Version',
  526:                                        list => 'List Directory',
  527:                                        uplo => 'Upload file',  
  528:                                        dele => 'Delete',
  529:                                        edit => 'Edit Metadata', 
  530:                                        sela => 'Select Action',
  531:                                        nfil => 'New file',
  532:                                        nhtm => 'New HTML file',
  533:                                        nprb => 'New problem',
  534:                                        npag => 'New assembled page',
  535:                                        nseq => 'New assembled sequence',
  536:                                        ncrf => 'New custom rights file',
  537:                                        nsty => 'New style file',
  538:                                        nlib => 'New library file',
  539:                                        nbt  => 'New bridgetask file',
  540:                                        nsub => 'New subdirectory',
  541:                                        renm => 'Rename current file to',
  542:                                        move => 'Move current file to',
  543:                                        copy => 'Copy current file to',
  544:                                        type => 'Type Name Here',
  545:                                        go   => 'Go',
  546:                                        prnt => 'Print contents of directory',
  547:                                        crea => 'Create a new directory or LON-CAPA document',
  548:                                        qs   => 'Quick Search',
  549:                                        cs   => 'Case Sensitive',
  550:                                        re   => 'Regular Expression',
  551: 				       acti => 'Actions for current directory',
  552: 				       updc => 'Upload a new document',
  553: 				       pick => 'Please select an action to perform using the new filename',
  554:                                       );
  555:     my $mytype = $lt{'type'}; # avoid conflict with " and ' in javascript
  556:     # Calculate free space in bytes.
  557:     # $disk_quota is in MB and $current_disk_usage is in kB
  558:     my $free_space = 1024 * ((1024 * $disk_quota) - $current_disk_usage);
  559:     $r->printf(<<END,&Apache::loncommon::help_open_topic('Quicksearch'));
  560: <div class="LC_columnSection">
  561:   <div>
  562:     <form name="curractions" method="post" action="">
  563:       <fieldset>
  564:         <legend>$lt{'acti'}</legend>
  565:         <select name="dirtask" onchange="currdiract(this.form)">
  566:             <option>$lt{'sela'}</option>
  567:             <option value="publish">$lt{'pubd'}</option>
  568:             <option value="editmeta">$lt{'edit'}</option>
  569:             <option value="printdir">$lt{'prnt'}</option>
  570:             <option value="delete">$lt{'dedr'}</option>
  571:         </select>
  572:         <input type="hidden" name="filename" value="/priv$thisdisfn/" />
  573:       </fieldset>
  574:     </form>
  575:     <form name="publishdir" method="post" action="/adm/publish" target="_parent">
  576:       <input type="hidden" name="pubrec" value="" />
  577:       <input type="hidden" name="filename" value="" />
  578:     </form>
  579:     <form name="printdir" method="post" action="/adm/printout" target="_parent">
  580:       <input type="hidden" name="postdata" value="" />
  581:     </form>
  582:   </div>
  583: 
  584:   <div style="padding-bottom: 2px">
  585:     <form name="upublisher" enctype="multipart/form-data" method="post" action="/adm/upload" target="_parent">
  586:       <fieldset>
  587:         <legend>$lt{'updc'}</legend>
  588:         <input type="hidden" name="filename" value="/priv$thisdisfn/" />
  589:         <input type="file" name="upfile" class="flUpload testclass" size="20" />
  590:         <input type="hidden" id="free_space" value=$free_space />
  591:         <input type="button" value="$lt{'uplo'}"  onclick="checkUpload(this.form)" />
  592:       </fieldset>
  593:     </form>
  594:   </div>
  595: 
  596:   <div>
  597:     <form name="fileaction" method="post" action="/adm/cfile" target="_parent">
  598:       <fieldset>
  599:               <legend>$lt{'crea'}</legend>
  600: 	      <span class="LC_nobreak">
  601: 		<input type="hidden" name="filename" value="/priv$thisdisfn/" />
  602:                   <script type="text/javascript">
  603:                     function validate_go() {
  604:                         var selected = document.fileaction.action.selectedIndex;
  605:                         if (selected == 0) {
  606:                             alert('$lt{'pick'}');
  607:                         } else {
  608:                             document.fileaction.submit();
  609:                         }
  610:                     }
  611:                   </script>
  612: 		  <select name="action">
  613: 		    <option value="none">$lt{'sela'}</option>
  614: 		    <option value="newfile">$lt{'nfil'}:</option>
  615: 		    <option value="newhtmlfile">$lt{'nhtm'}:</option>
  616: 		    <option value="newproblemfile">$lt{'nprb'}:</option>
  617:                     <option value="newpagefile">$lt{'npag'}:</option>
  618:                     <option value="newsequencefile">$lt{'nseq'}:</option>
  619:                     <option value="newrightsfile">$lt{'ncrf'}:</option>
  620:                     <option value="newstyfile">$lt{'nsty'}:</option>
  621:                     <option value="newtaskfile">$lt{'nbt'}:</option>
  622:                     <option value="newlibraryfile">$lt{'nlib'}:</option>
  623: 	            <option value="newdir">$lt{'nsub'}:</option>
  624: 		  </select>&nbsp;<input type="text" name="newfilename" placeholder="$lt{'type'}" value="" onfocus="if (this.value == is.empty()) this.value=''" />&nbsp;<input type="button" value="Go" onclick="validate_go();" />
  625: 		<br />
  626:                 <span>Quickactions:
  627:                  <input type="hidden" name="mode"/>
  628:                  <a href="javascript:void(0)" onclick="javascript:validate_action('blank')">
  629: 		    <img src="/adm/lonIcons/unknown.gif" title="Create blank problem file"></a>
  630:                  <a href="javascript:void(0)" onclick="javascript:validate_action('problemtempl')"> 
  631:                     <img src="/adm/lonIcons/problem.gif" title="Create new problem from template"></a>
  632:                  <a href="javascript:void(0)" onclick="javascript:validate_action('blankhtml')"> 
  633:                     <img src="/adm/lonIcons/html.gif" title="Create new blank HTML file"></a>
  634:                  <a href="javascript:void(0)" onclick="javascript:validate_action('folder')"> 
  635: 		    <img src="/adm/lonIcons/navmap.folder.closed.gif" title="Create new subdirectory"></a>
  636:                 </span>
  637:                  <script type="text/javascript">
  638:                      function validate_action(action){
  639: 
  640:                          if (document.getElementsByName(\'newfilename\')[0].value != \'\'){
  641:                              if (action == "blank") {
  642: 								 document.fileaction.action.value=\'newproblemfile\';
  643: 								 document.fileaction.mode.value=\'blank\';
  644: 							 } else if (action == "problemtempl") {
  645: 								 document.fileaction.action.value=\'newproblemfile\';
  646:                                  validate_go();
  647:                              } else if (action == "blankhtml") {
  648:                                  document.fileaction.action.value=\'newhtmlfile\';
  649:                                  validate_go();
  650:                              } else if (action == "folder") {
  651:                                  document.fileaction.action.value=\'newdir\';
  652:                                  document.fileaction.mode.value=\'folder\';
  653:                              }
  654:                              fileaction.submit();
  655:                          } else {
  656:                              alert(\'Please specify file name.\');
  657:                              // TODO: ask for filename? if so, do some refactoring
  658: 
  659:                          }
  660:                      }
  661:                  </script>
  662: 		 </span>
  663:       </fieldset>
  664:     </form>
  665:     </div>
  666:     <div>
  667:       <fieldset style="display:inline">
  668:             <legend>$lt{'qs'}</legend>
  669:                 <script type="text/javascript" src="/adm/quicksearch/quicksearch.js"></script>
  670:                 <input type="text" id="quickfilter" placeholder="Enter search term" onkeyup="applyFilter()"/>
  671:                 <input type="button" value="Clear" onclick="document.getElementById(\'quickfilter\').value=\'\'; applyFilter()" />
  672:                 %s
  673:                 <br />
  674:                 <label><input type="checkbox" id="casesens" onchange="applyFilter()"/>$lt{'cs'}&nbsp;&nbsp;</label>
  675:                 <label><input type="checkbox" id="regex" onchange="applyFilter()"/>$lt{'re'}&nbsp;&nbsp;</label>
  676:         </fieldset>
  677:   </div>
  678: </div>
  679: END
  680: }
  681: 
  682: sub resourceactions {
  683:     my ($r,$uname,$udom,$thisdisfn) = @_;
  684:     $r->print(<<END);
  685:        <form name="moveresource" action="/adm/cfile" target="_parent" method="post">
  686:          <input type="hidden" name="filename" value="" />
  687:          <input type="hidden" name="newfilename" value="" />
  688:          <input type="hidden" name="action" value="" />
  689:        </form>
  690:        <form name="delresource" action="/adm/cfile" target="_parent" method="post">
  691:          <input type="hidden" name="filename" value="" />
  692:          <input type="hidden" name="action" value="delete" />
  693:        </form>
  694:        <form name="pubresource" action="/adm/publish" target="_parent" method="post">
  695:          <input type="hidden" name="filename" value="" />
  696:          <input type="hidden" name="makeobsolete" value="0" />
  697:        </form>
  698:        <form name="printresource" action="/adm/printout" target="_parent" method="post">
  699:            <input type="hidden" name="postdata" value="" />
  700:        </form>
  701:        <form name="retrieveres" action="/adm/retrieve" target="_parent" method="post">
  702:            <input type="hidden" name="filename" value="" />
  703:        </form>
  704:        <form name="cleanup" action="/adm/cleanup" target="_parent" method="post">
  705:            <input type="hidden" name="filename" value="" />
  706:        </form>
  707: END
  708: }
  709: 
  710: #
  711: #   Get the title string or "[untitled]" if the file has no title metadata:
  712: #   Without the latter substitution, it's impossible to examine metadata for
  713: #   untitled resources.  Resources may be legitimately untitled, to prevent
  714: #   searches from locating them.
  715: #
  716: #   $str = getTitleString($fullname);
  717: #       $fullname - Fully qualified filename to check.
  718: #
  719: sub getTitleString {
  720:     my $fullname = shift;
  721:     my $title    = &Apache::lonnet::metadata($fullname, 'title');
  722: 
  723:     unless ($title) {
  724: 	$title = "[".&mt('untitled')."]";
  725:     }
  726:     return $title;
  727: }
  728: 
  729: sub getCopyRightString {
  730:     my $fullname = shift;
  731:     return &Apache::lonnet::metadata($fullname, 'copyright');
  732: }
  733: 
  734: sub getSourceRightString {
  735:     my $fullname = shift;
  736:     return &Apache::lonnet::metadata($fullname, 'sourceavail');
  737: }
  738: #
  739: #  Put out a directory table row:
  740: #    putdirectory(r, base, here, dirname, modtime, targetdir, bombs, numdir)
  741: #      r         - Apache request object.
  742: #      reqfile   - File in request.
  743: #      here      - Where we are in directory tree.
  744: #      dirname   - Name of directory special file.
  745: #      modtime   - Encoded modification time.
  746: #      targetdir - Publication target directory.
  747: #      bombs     - Reference to hash of URLs with runtime error messages.
  748: #      numdir    - Reference to scalar used to track number of sub-directories
  749: #                  in directory (used in form name for each "actions" dropdown).
  750: #
  751: sub putdirectory {
  752:     my ($r, $reqfile, $here, $dirname, $modtime, $targetdir, $bombs, $numdir) = @_;
  753: 
  754: # construct the display filename: the directory name unless ..:
  755:    
  756:     my $actionitem;
  757:  
  758:     my $disfilename = $dirname;
  759: # Don't display directory itself, and there is no way up from root directory
  760:     unless ((($dirname eq '..') && ($reqfile=~/^\/[^\/]+\/[^\/]+$/)) || ($dirname eq '.')) {
  761:         my $kaputt=0;
  762:         if (ref($bombs) eq 'HASH') {
  763:             foreach my $key (keys(%{$bombs})) {
  764:                 my $currentdir = &Apache::lonnet::declutter("$targetdir/$disfilename");
  765:                 if (($key) =~ m{^\Q$currentdir\E/}) { $kaputt=1; last; }
  766:             }
  767:         }
  768: #
  769: # Get the metadata from that directory's default.meta to display titles
  770: #
  771: 	%Apache::lonpublisher::metadatafields=();
  772: 	%Apache::lonpublisher::metadatakeys=();
  773: 	&Apache::lonpublisher::metaeval(
  774:                  &Apache::lonnet::getfile($r->dir_config('lonDocRoot').$here.'/'.$dirname.'/default.meta')
  775:                                        );
  776:         if ($dirname eq '..') {
  777:             $actionitem = &mt('Go to ...');
  778:             $disfilename = '<i>'.&mt('Parent Directory').'</i>';
  779:         } else {
  780:             $actionitem = 
  781:                     '<form name="dirselect_'.$$numdir.
  782:                     '" action="/adm/publish" target="_parent">'.
  783:                     '<select name="diraction" onchange="SetPubDir(this.form,document)">'.
  784:                       '<option selected="selected">'.&mt('Select action').'</option>'.
  785:                       '<option value="open">'.&mt('Open').'</option>'.
  786:                       '<option value="publish">'.&mt('Publish').'</option>'.
  787:                       '<option value="editmeta">'.&mt('Edit Metadata').'</option>'.
  788:                       '<option value="printdir">'.&mt('Print directory').'</option>'.
  789:                       '<option value="delete">'.&mt('Delete directory').'</option>'.
  790:                     '</select>'.
  791:                      '<input type="hidden" name="filename" value="'.&HTML::Entities::encode($here.'/'.$dirname,'<>&"').'/" />'.
  792:                      '<input type="hidden" name="openname" value="'.$here.'/'.$dirname.'/" />'.
  793:                      '<input type="hidden" name="postdata" value="" />'.
  794:                    '</form>';
  795:             $$numdir ++;
  796:         }
  797: 	$r->print('<tr class="LC_browser_folder">'.
  798: 		  '<td><img src="'.
  799: 		  $Apache::lonnet::perlvar{'lonIconsURL'}.'/navmap.folder.closed.gif" alt="folder" /></td>'.
  800: 		  '<td>'.$actionitem.'</td>'.
  801: 		  '<td><span class="LC_filename"><a href="'.&HTML::Entities::encode($here.'/'.$dirname,'<>&"').'/" target="_parent">'.
  802: 		  $disfilename.'</a></span></td>'.
  803: 		        '<td colspan="3">'.($kaputt?&Apache::lonhtmlcommon::authorbombs($targetdir.'/'.$disfilename.'/'):'').$Apache::lonpublisher::metadatafields{'title'});
  804: 	if ($Apache::lonpublisher::metadatafields{'subject'} ne '') {
  805: 	    $r->print(' <i>'.
  806: 		      $Apache::lonpublisher::metadatafields{'subject'}.
  807: 		      '</i> ');
  808: 	}
  809: 	$r->print($Apache::lonpublisher::metadatafields{'keywords'}.'</td>'.
  810: 		  '<td>'.&Apache::lonlocal::locallocaltime($modtime).'</td>'.
  811: 	          '<td></td>'.
  812: 		  "</tr>\n");
  813:     }
  814:     return;
  815: }
  816: 
  817: sub getTitle {
  818:     my ($resdir, $targetdir, $filename, $linkfilename, $meta_same, $bombs) = @_;
  819:     my $title='';
  820:     my $titleString = &getTitleString($targetdir.'/'.$filename);
  821:     if (-e $resdir.'/'.$filename) {
  822: 	$title = '<a href="'.$targetdir.'/'.$filename.
  823: 	    '.meta" target="cat">'.$titleString.'</a>';
  824:         if (!$meta_same) {
  825: 	    $title = &mt('Metadata Modified').'<br />'.$title.
  826: 		'<br />'.
  827:                 &Apache::loncommon::modal_link(
  828:                     '/adm/diff?filename='.$linkfilename.'.meta'.'&amp;versiontwo=priv',
  829:                     &mt('Metadata Diffs'),600,500);
  830: 	    $title.="\n".'<br />'.
  831:                 &Apache::loncommon::modal_link(
  832:                     '/adm/retrieve?filename='.$linkfilename.'.meta&amp;inhibitmenu=yes&amp;add_modal=yes',
  833:                     &mt('Retrieve Metadata'),600,500);
  834:         } 
  835:     }
  836:     # Allow editing metadata of published and unpublished resources
  837:     $title .= "\n".'<br />' if ($title);
  838:     $title .= '<a href="'.$linkfilename.'.meta">'.
  839:               ($$bombs{&Apache::lonnet::declutter($targetdir.'/'.$filename)}?
  840:                   '<img src="/adm/lonMisc/bomb.gif" border="0" alt="'.&mt('bomb').'" />':
  841:                   &mt('Edit Metadata')).
  842:               '</a>';
  843: 
  844:     return ($title, $titleString);
  845: }
  846: 
  847: 
  848: sub isMetaSame {
  849:     my ($cstr_dir, $resdir, $filename) = @_;
  850:     my $meta_cmtime = (stat($cstr_dir.'/'.$filename.'.meta'))[9];
  851:     my $meta_rmtime = (stat($resdir.'/'.$filename.'.meta'))[9];
  852:     return (&Apache::londiff::are_different_files($resdir.'/'.$filename.'.meta',
  853:             $cstr_dir.'/'.$filename.'.meta') && $meta_rmtime < $meta_cmtime) 
  854:         ? 0 : 1;
  855: }
  856:     
  857: 
  858: sub getStatus {    
  859:     my ($resdir, $targetdir, $cstr_dir, $filename,  
  860:             $linkfilename, $cmtime, $meta_same) = @_;
  861:     my $pubstatus = 'unpublished';
  862:     my $status = &mt('Unpublished');
  863: 
  864:     if (-e $resdir.'/'.$filename) {
  865:         my $same = 0;
  866:         if ((stat($resdir.'/'.$filename))[9] >= $cmtime) {
  867:             $same = 1;
  868:         } else {
  869:            if (&Apache::londiff::are_different_files($resdir.'/'.$filename,
  870: 						     $cstr_dir.'/'.$filename)) {
  871:               $same = 0;
  872:            } else {
  873:               $same = 1;
  874:            }
  875:         }
  876: 
  877:         my $rights_status =
  878:             &mt(&getCopyRightString($targetdir.'/'.$filename)).', ';
  879: 
  880:         my %lt_SourceRight = &Apache::lonlocal::texthash(
  881:                'open'   => 'Source: open',
  882:                'closed' => 'Source: closed',
  883:         );
  884:         $rights_status .=
  885:             $lt_SourceRight{&getSourceRightString($targetdir.'/'.$filename)};
  886: 
  887: 	if ($same) {
  888: 	    if (&Apache::lonnet::metadata($targetdir.'/'.$filename,'obsolete')) {
  889:                 $pubstatus = 'obsolete';
  890: 		$status=&mt('Obsolete');
  891:             } else {
  892: 		if (!$meta_same) {
  893: 		    $pubstatus = 'metamodified';
  894: 		} else {
  895: 		    $pubstatus = 'published';
  896: 		}
  897: 		$status=&mt('Published').
  898: 		    '<br />'. $rights_status;
  899: 	    }
  900: 	} else {
  901:             $pubstatus = 'modified';
  902: 	    $status=&mt('Modified').
  903: 		'<br />'. $rights_status;
  904: 	    if (&Apache::loncommon::fileembstyle(($filename=~/\.(\w+)$/)) eq 'ssi') {
  905: 		$status.='<br />'.
  906:                          &Apache::loncommon::modal_link(
  907:                              '/adm/diff?filename='.$linkfilename.'&amp;versiontwo=priv',
  908:                              &mt('Diffs'),600,500);
  909: 	    }
  910: 	} 
  911: 
  912: 	$status.="\n".'<br />'.
  913:              &Apache::loncommon::modal_link(
  914:                  '/adm/retrieve?filename='.$linkfilename.'&amp;inhibitmenu=yes&amp;add_modal=yes',&mt('Retrieve'),600,500);
  915:     }
  916: 
  917:     return ($status, $pubstatus);
  918: }
  919: 
  920: 
  921: #
  922: #   Put a table row for a file resource.
  923: #
  924: sub putresource {
  925:     my ($r, $udom, $uname, $filename, $thisdisfn, $resdir, $targetdir, 
  926:             $linkdir, $cmtime, $size, $numres, $linkfilename, $title, 
  927:             $status, $pubstatus) = @_;
  928:     &Apache::lonnet::devalidate_cache_new('meta',$targetdir.'/'.$filename);
  929: 
  930:     my $editlink='';
  931:     my $editlink2='';
  932:     if ($filename=~/\.(xml|html|htm|xhtml|xhtm|sty)$/) {
  933: 	$editlink=' <br />(<a href="'.$linkdir.'/'.$filename.'?editmode=Edit&amp;problemmode=edit">'.&mt('Edit').'</a>)';
  934:     }
  935:     if ($filename=~/$LONCAPA::assess_re/) {
  936: 	$editlink=' (<a href="'.$linkdir.'/'.$filename.'?editmode=Edit&amp;problemmode=editxml">'.&mt('EditXML').'</a>)';
  937: 	$editlink2=' <br />(<a href="'.$linkdir.'/'.$filename.'?editmode=Edit&amp;problemmode=edit">'.&mt('Edit').'</a>)';
  938:     }
  939:     if ($filename=~/\.(xml|html|htm|xhtml|xhtm)$/ || $filename=~/$LONCAPA::assess_re/) {
  940:         if ($env{'browser.type'} ne 'explorer' || $env{'browser.version'} > 9) {
  941:             my $daxeurl = '/daxepage'.$linkdir.'/'.$filename;
  942:             $editlink .= ' (<a href="'.$daxeurl.'" target="_blank">Daxe</a>)';
  943:         }
  944:     }
  945:     if ($filename=~/\.(problem|exam|quiz|assess|survey|form|library|xml|html|htm|xhtml|xhtm|sty)$/) {
  946: 	$editlink.=' (<a href="/adm/cleanup?filename='.$linkfilename.'" target="_parent">'.&mt('Clean Up').')</a>';
  947:     }
  948:     if ($filename=~/\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
  949: 	$editlink=' (<a target="_parent" href="/adm/cfile?decompress='.$linkfilename.'">'.&mt('Decompress').'</a>)';
  950:     }
  951:     my $publish_button = (-e $resdir.'/'.$filename) ? &mt('Re-publish') : &mt('Publish');
  952:     my $pub_select = '';
  953:     &create_pubselect($r,\$pub_select,$udom,$uname,$thisdisfn,$filename,$resdir,$pubstatus,$publish_button,$numres);
  954:     $r->print(&Apache::loncommon::start_data_table_row().
  955: 	      '<td>'.($filename=~/[\#\~]$/?'&nbsp;':
  956: 		      '<img src="'.&Apache::loncommon::icon($filename).'" alt="" />').'</td>'.
  957:               '<td>'.$pub_select.'</td>'.
  958: 	      '<td><span class="LC_filename">'.
  959: 	      '<a href="'.$linkdir.'/'.$filename.'" target="_parent">'.
  960:                $filename.'</a></span>'.$editlink2.$editlink.
  961: 	      '</td>'.
  962: 	      '<td>'.$title.'</td>'.
  963:               '<td class="LC_browser_file_'.$pubstatus.'">&nbsp;&nbsp;</td>'. # Display publication status
  964:               '<td>'.$status.'</td>'.
  965: 	      '<td>'.&Apache::lonlocal::locallocaltime($cmtime).'</td>'.
  966: 	      '<td>'.sprintf("%.1f",$size).'</td>'.
  967: 	      &Apache::loncommon::end_data_table_row()
  968:     );
  969:     return;
  970: }
  971: 
  972: sub create_pubselect {
  973:     my ($r,$pub_select,$udom,$uname,$thisdisfn,$filename,$resdir,$pubstatus,$publish_button,$numres) = @_;
  974:     $$pub_select = '
  975: <form name="resselect_'.$$numres.'" action="">
  976: <select name="reschoice"  onchange="SetResChoice(this.form)">
  977: <option>'.&mt('Select action').'</option>'.
  978: '<option value="copy">'.&mt('Copy').'</option>';
  979:     if ($pubstatus eq 'obsolete' || $pubstatus eq 'unpublished') {
  980:         $$pub_select .= 
  981: '<option value="rename">'.&mt('Rename').'</option>'.
  982: '<option value="move">'.&mt('Move').'</option>'.
  983: '<option value="delete">'.&mt('Delete').'</option>';
  984:     } else {
  985:         $$pub_select .= '
  986: <option value="obsolete">'.&mt('Mark obsolete').'</option>';
  987:     }
  988: # check for versions
  989:     my $versions = &check_for_versions($r,'/'.$filename,$udom,$uname);
  990:     if ($versions > 0) {
  991:         $$pub_select .='
  992: <option value="retrieve">'.&mt('Retrieve old version').'</option>';
  993:     }
  994:     $$pub_select .= '
  995: <option value="publish">'.$publish_button.'</option>'.
  996: '<option value="cleanup">'.&mt('Clean up').'</option>'.
  997: '<option value="print">'.&mt('Print').'</option>'.
  998: '</select>
  999: <input type="hidden" name="filename" value="/priv'.
 1000:  &HTML::Entities::encode($thisdisfn.'/'.$filename,'<>&"').'" />
 1001:  <input type="hidden" name="dispfilename" value="'.
 1002:  &HTML::Entities::encode($filename).'" /></form>';
 1003:     $$numres ++;
 1004: }
 1005: 
 1006: sub check_for_versions {
 1007:     my ($r,$fn,$udom,$uname) = @_;
 1008:     my $versions = 0;
 1009:     my $docroot=$r->dir_config('lonDocRoot');
 1010:     my $resfn=$docroot.'/res/'.$udom.'/'.$uname.$fn;
 1011:     my $resdir=$resfn;
 1012:     $resdir=~s/\/[^\/]+$/\//;
 1013:     $fn=~/\/([^\/]+)\.(\w+)$/;
 1014:     my $main=$1;
 1015:     my $suffix=$2;
 1016:     opendir(DIR,$resdir);
 1017:     while (my $filename=readdir(DIR)) {
 1018:         if ($filename=~/^\Q$main\E\.(\d+)\.\Q$suffix\E$/) {
 1019:             $versions ++;        
 1020:         }
 1021:     }
 1022:     closedir(DIR);
 1023:     return $versions;
 1024: }
 1025: 
 1026: sub prepareJsonTranslations {
 1027:     my $json = 
 1028:         '{"translations":{'.
 1029:             '"edit":"'.&mt('Edit').'",'.
 1030:             '"editxml":"'.&mt('EditXML').'",'.
 1031:             '"editmeta":"'.&mt('Edit Metadata').'",'.
 1032:             '"obsolete":"'.&mt('Obsolete').'",'.
 1033:             '"modified":"'.&mt('Modified').'",'.
 1034:             '"published":"'.&mt('Published').'",'.
 1035:             '"unpublished":"'.&mt('Unpublished').'",'.
 1036:             '"diff":"'.&mt('Diff').'",'.
 1037:             '"retrieve":"'.&mt('Retrieve').'",'.
 1038:             '"directory":"'.&mt('Directory').'",'.
 1039:             '"results":"'.&mt('Show results for keyword:').'"'.
 1040:         '}}';
 1041: }
 1042: 
 1043: # gathers all files in the working directory except the ones that are already on screen
 1044: sub prepareJsonData {
 1045:     my ($uname, $udom, $pathToSkip) = @_;
 1046:     my $path = "/home/httpd/html/priv/$udom/$uname/";
 1047: 
 1048:     # maximum number of entries, to limit workload and required storage space
 1049:     my $entries = 100;
 1050:     my $firstfile = 1;
 1051:     my $firstdir = 1;
 1052: 
 1053:     my $json = '{"resources":[';
 1054:     $json .= &prepareJsonData_rec($path, \$entries, \$firstfile, \$firstdir, $pathToSkip);
 1055:     $json .= ']}';
 1056: 
 1057:     # if the json string is invalid the whole search breaks.
 1058:     # so we want to make sure that the string is valid in any case.
 1059:     $json =~ s/,\s*,/,/g;
 1060:     $json =~ s/\}\s*\{/\},\{/g;
 1061:     $json =~ s/\}\s*,\s*\]/\}\]/g;
 1062:     return $json;
 1063: }
 1064: 
 1065: # recursive part of json file gathering
 1066: sub prepareJsonData_rec {
 1067:     my ($path, $entries, $firstfile, $firstdir, $pathToSkip) = @_;
 1068:     my $json;
 1069:     my $skipThisFolder = $path =~ m/$pathToSkip\/$/?1:0;
 1070: 
 1071:     my @dirs;
 1072:     my @resources;
 1073:     my @ignored = qw(bak log meta save . ..);
 1074: 
 1075: # Phase 1: Gathering
 1076:     opendir(DIR,$path);
 1077:     my @files=sort {uc($a) cmp uc($b)} (readdir(DIR));
 1078:     foreach my $filename (@files) {
 1079:         next if ($filename eq '.DS_Store');
 1080: 
 1081:         # gather all resources
 1082:         if ($filename !~ /\./) {
 1083:             # its a folder
 1084:             push(@dirs, $filename);
 1085:         } else {
 1086:             # only push files we dont want to ignore
 1087:             next if ($skipThisFolder);
 1088: 
 1089:             $filename =~ /\.(\w+?)$/;
 1090:             unless (grep /$1/, @ignored) {
 1091:                 push(@resources, $filename);
 1092:             }
 1093:         }
 1094:     }
 1095:     closedir(DIR);
 1096:     # nothing to do here if both lists are empty
 1097:     return unless ( @dirs || @resources );
 1098:     
 1099: # Phase 2: Working
 1100:     $$firstfile = 1;
 1101: 
 1102:     foreach (@dirs) {
 1103:         $json .= '{"name":"'.$_.'",'.
 1104:                   '"path":"'.$path.$_.'",'.
 1105:                   '"title":"",'.
 1106:                   '"status":"",'.
 1107:                   '"cmtime":""},';
 1108:     }
 1109: 
 1110:     foreach (@resources) {
 1111:         last if ($$entries < 1);
 1112:         my $title = &getTitleString($path.$_);
 1113: 
 1114:         my $privpath = $path.$_;
 1115:         my $respath = $privpath;
 1116:         $respath =~ s/httpd\/html\/priv\//httpd\/html\/res\//;
 1117: 
 1118:         my $cmtime = (stat($privpath))[9];
 1119:         my $rmtime = (stat($respath))[9];
 1120: 
 1121:         unless ($$firstfile) { $json .= ','; } else { $$firstfile = 0; }
 1122: 
 1123:         my $status = 'unpublished';
 1124: 
 1125:         # if a resource is published, the published version (/html/res/filepath) gets its own modification time
 1126:         # this is newer or equal then the version in your authoring space (/html/priv/filepath)
 1127:         if ($rmtime >= $cmtime) {
 1128:             # obsolete
 1129:             if (&Apache::lonnet::metadata($respath, 'obsolete')) {
 1130:                 $status = 'obsolete';
 1131:             }else{
 1132:                 $status = 'published';
 1133:             }
 1134:         } else {
 1135:             $status = 'modified';
 1136:         }
 1137: 
 1138:         $json .= '{"name":"'.$_.'",'.
 1139:                   '"path":"'.$path.'",'.
 1140:                   '"title":"'.$title.'",'.
 1141:                   '"status":"'.$status.'",'.
 1142:                   '"cmtime":"'.&Apache::lonlocal::locallocaltime($cmtime).'"}';
 1143:         $$entries--;
 1144:     }
 1145: 
 1146:     foreach(@dirs) {
 1147:         next if ($$entries < 1);
 1148:         $json .= ',';
 1149:         $json .= &prepareJsonData_rec
 1150:                     ($path.$_.'/', $entries, $firstfile, $firstdir, $pathToSkip);
 1151:     }
 1152:     return $json;
 1153: }
 1154: 1;
 1155: __END__
 1156: 
 1157: 
 1158: =head1 NAME
 1159: 
 1160: Apache::lonpubdir - Authoring space directory lister
 1161: 
 1162: =head1 SYNOPSIS
 1163: 
 1164: Invoked (for various locations) by /etc/httpd/conf/srm.conf:
 1165: 
 1166:  <LocationMatch "^/+priv.*/$">
 1167:  PerlAccessHandler       Apache::loncacc
 1168:  SetHandler perl-script
 1169:  PerlHandler Apache::lonpubdir
 1170:  ErrorDocument     403 /adm/login
 1171:  ErrorDocument     404 /adm/notfound.html
 1172:  ErrorDocument     406 /adm/unauthorized.html
 1173:  ErrorDocument	  500 /adm/errorhandler
 1174:  </LocationMatch>
 1175: 
 1176:  <Location /adm/pubdir>
 1177:  PerlAccessHandler       Apache::lonacc
 1178:  SetHandler perl-script
 1179:  PerlHandler Apache::lonpubdir
 1180:  ErrorDocument     403 /adm/login
 1181:  ErrorDocument     404 /adm/notfound.html
 1182:  ErrorDocument     406 /adm/unauthorized.html
 1183:  ErrorDocument	  500 /adm/errorhandler
 1184:  </Location>
 1185: 
 1186: =head1 INTRODUCTION
 1187: 
 1188: This module publishes a directory of files.
 1189: 
 1190: This is part of the LearningOnline Network with CAPA project
 1191: described at http://www.lon-capa.org.
 1192: 
 1193: =head1 HANDLER SUBROUTINE
 1194: 
 1195: This routine is called by Apache and mod_perl.
 1196: 
 1197: =over 4
 1198: 
 1199: =item *
 1200: 
 1201: read in information
 1202: 
 1203: =item *
 1204: 
 1205: start page output
 1206: 
 1207: =item *
 1208: 
 1209: run through list of files and attempt to publish unhidden files
 1210: 
 1211: =back
 1212: 
 1213: =head1 SUBROUTINES:
 1214: 
 1215: =over
 1216: 
 1217: =item startpage($r, $uame, $udom, $thisdisfn)
 1218: 
 1219: Output the header of the page.  This includes:
 1220:  - The HTML header 
 1221:  - The H1/H3  stuff which includes the directory.
 1222:  
 1223:     startpage($r, $uame, $udom, $thisdisfn);
 1224:         $r     - The apache request object.
 1225:         $uname - User name.
 1226:         $udom  - Domain name the user is logged in under.
 1227:         $thisdisfn - Displayable version of the filename.
 1228: 
 1229: =item getTitleString($fullname)
 1230: 
 1231:     Get the title string or "[untitled]" if the file has no title metadata:
 1232:     Without the latter substitution, it's impossible to examine metadata for
 1233:     untitled resources.  Resources may be legitimately untitled, to prevent
 1234:     searches from locating them.
 1235:     
 1236:     $str = getTitleString($fullname);
 1237:         $fullname - Fully qualified filename to check.
 1238: 
 1239: =item putdirectory($r, $base, $here, $dirname, $modtime, $targetdir, $bombs,
 1240:                    $numdir)
 1241: 
 1242:     Put out a directory table row:
 1243:     
 1244:         $r        - Apache request object.
 1245:         $reqfile  - File in request.
 1246:         $here     - Where we are in directory tree.
 1247:         $dirname  - Name of directory special file.
 1248:         $modtime  - Encoded modification time.
 1249:         targetdir - Publication target directory.
 1250:         bombs     - Reference to hash of URLs with runtime error messages.
 1251:         numdir    - Reference to scalar used to track number of sub-directories
 1252:                     in directory (used in form name for each "actions" dropdown).
 1253: 
 1254: =back
 1255: 
 1256: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>