File:  [LON-CAPA] / loncom / publisher / lonpubdir.pm
Revision 1.174: download - view: text, annotated - select for diffs
Fri May 27 04:24:55 2022 UTC (2 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Use of a frameset for Authoring Space (from lonconstruct.pm) was eliminated
  in 2.11.0. As a result target="_parent" is no longer required in lonpubdir.pm

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

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