File:  [LON-CAPA] / loncom / publisher / lonpubdir.pm
Revision 1.177: download - view: text, annotated - select for diffs
Sun Jun 11 19:46:01 2023 UTC (11 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- xhtml validation.

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

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