File:  [LON-CAPA] / loncom / publisher / lonpubdir.pm
Revision 1.178: download - view: text, annotated - select for diffs
Sun Jun 11 20:45:40 2023 UTC (11 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Remove "Actions for current directory" drop-down list from box created by
  &CSTR_pageheader() when listing contents of a directory in Authoring Space
  and replace with icons/links in Functions menu below standard inline menus.
- Reverse part of changes in lonpubdir.pm 1.176 and loncommon.pm 1.1406

    1: # The LearningOnline Network with CAPA
    2: # Authoring Space Directory Lister
    3: #
    4: # $Id: lonpubdir.pm,v 1.178 2023/06/11 20:45:40 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:     # Put out the start of page.
  108:     
  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('','',&mt('Directory'))));
  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 checkUpload(theform) {
  414:         if (theform.file == '') {
  415:             alert("Please use 'Browse..' to choose a file first, before uploading")
  416:             return 
  417:         }
  418:         theform.submit()  
  419:     }
  420: 
  421:     function SetPubDir(theform,printForm) {
  422:         if (theform.diraction.options[theform.diraction.selectedIndex].value == "open") {
  423:             top.location = theform.openname.value
  424:             return
  425:         }
  426:         if (theform.diraction.options[theform.diraction.selectedIndex].value == "publish") {
  427:             theform.submit();
  428:         }
  429:         if (theform.diraction.options[theform.diraction.selectedIndex].value == "editmeta") {
  430:             top.location=theform.filename.value+'default.meta'
  431:         }
  432:         if (theform.diraction.options[theform.diraction.selectedIndex].value == "printdir") {
  433:             theform.action = '/adm/printout'
  434:             theform.postdata.value = theform.filename.value
  435:             theform.submit()
  436:         }
  437:         if (theform.diraction.options[theform.diraction.selectedIndex].value == "delete") {
  438:               var delform = document.delresource
  439:               delform.filename.value = theform.filename.value
  440:               delform.submit()
  441:         }
  442:         return
  443:     }
  444:     function SetResChoice(theform) {
  445:       var activity = theform.reschoice.options[theform.reschoice.selectedIndex].value
  446:       if ((activity == 'rename') || (activity == 'copy') || (activity == 'move')) {
  447:           changename(theform,activity)
  448:       }
  449:       if (activity == 'publish') {
  450:           var pubform = document.pubresource
  451:           pubform.filename.value = theform.filename.value
  452:           pubform.submit()
  453:       }
  454:       if (activity == 'delete') {
  455:           var delform = document.delresource
  456:           delform.filename.value = theform.filename.value
  457:           delform.submit()
  458:       }
  459:       if (activity == 'obsolete') {
  460:           var pubform = document.pubresource
  461:           pubform.filename.value = theform.filename.value
  462:           pubform.makeobsolete.value=1;
  463:           pubform.submit()
  464:       }
  465:       if (activity == 'print') {
  466:           document.printresource.postdata.value = theform.filename.value
  467:           document.printresource.submit()
  468:       }
  469:       if (activity == 'retrieve') {
  470:           document.retrieveres.filename.value = theform.filename.value
  471:           document.retrieveres.submit()
  472:       }
  473:       if (activity == 'cleanup') {
  474:           document.cleanup.filename.value = theform.filename.value
  475:           document.cleanup.submit()
  476:       }
  477:       return
  478:     }
  479:     function changename(theform,activity) {
  480:         var oldname=theform.dispfilename.value;
  481:         var newname=prompt('$newname',oldname);
  482:         if (newname == "" || !newname || newname == oldname)  {
  483:             return
  484:         }
  485:         document.moveresource.newfilename.value = newname
  486:         document.moveresource.filename.value = theform.filename.value
  487:         document.moveresource.action.value = activity
  488:         document.moveresource.submit();
  489:     }
  490: </script>
  491: ENDPUBDIRSCRIPT
  492:     $r->print($pubdirscript);
  493: }
  494: 
  495: sub dircontrols {
  496:     my ($r,$uname,$udom,$thisdisfn, $current_disk_usage, $disk_quota) = @_;
  497:     my %lt=&Apache::lonlocal::texthash(
  498:                                        cnpd => 'Cannot publish directory',
  499:                                        cnrd => 'Cannot retrieve directory',
  500:                                        mcdi => 'Must create new subdirectory inside a directory',
  501:                                        pubr => 'Publish this Resource',
  502:                                        rtrv => 'Retrieve Old Version',
  503:                                        list => 'List Directory',
  504:                                        uplo => 'Upload file',  
  505:                                        dele => 'Delete',
  506:                                        sela => 'Select Action',
  507:                                        nfil => 'New file',
  508:                                        nhtm => 'New HTML file',
  509:                                        nprb => 'New problem',
  510:                                        npag => 'New assembled page',
  511:                                        nseq => 'New assembled sequence',
  512:                                        ncrf => 'New custom rights file',
  513:                                        nsty => 'New style file',
  514:                                        nlib => 'New library file',
  515:                                        nbt  => 'New bridgetask file',
  516:                                        nsub => 'New subdirectory',
  517:                                        renm => 'Rename current file to',
  518:                                        move => 'Move current file to',
  519:                                        copy => 'Copy current file to',
  520:                                        type => 'Type Name Here',
  521:                                        go   => 'Go',
  522:                                        crea => 'Create a new subdirectory or document',
  523:                                        qs   => 'Quick name search',
  524:                                        cs   => 'Case Sensitive',
  525:                                        re   => 'Regular Expression',
  526: 				       updc => 'Upload a new document',
  527: 				       pick => 'Please select an action to perform using the new filename',
  528:                                        shcu => 'Shortcuts',
  529:                                       );
  530:     my %js_lt = &Apache::lonlocal::texthash(
  531:                                        nanf => 'Name of New File',
  532:                                        nans => 'Name of New Subdirectory',
  533:                                        psfn => 'Please specify file name',
  534:     ); 
  535:     &js_escape(\%js_lt);
  536:     my $mytype = $lt{'type'}; # avoid conflict with " and ' in javascript
  537:     # Calculate free space in bytes.
  538:     # $disk_quota is in MB and $current_disk_usage is in kB
  539:     my $free_space = 1024 * ((1024 * $disk_quota) - $current_disk_usage);
  540:     $r->printf(<<END,&Apache::loncommon::help_open_topic('Quicksearch'));
  541: <div class="LC_columnSection">
  542:     <div>
  543:       <fieldset style="display:inline">
  544:             <legend>$lt{'qs'}</legend>
  545:                 <script type="text/javascript" src="/adm/quicksearch/quicksearch.js"></script>
  546:                 <input type="text" id="quickfilter" placeholder="Enter search term" onkeyup="applyFilter()"/>
  547:                 <input type="button" value="Clear" onclick="document.getElementById(\'quickfilter\').value=\'\'; applyFilter()" />
  548:                 %s
  549:                 <br />
  550:                 <label><input type="checkbox" id="casesens" onchange="applyFilter()"/>$lt{'cs'}&nbsp;&nbsp;</label>
  551:                 <label><input type="checkbox" id="regex" onchange="applyFilter()"/>$lt{'re'}&nbsp;&nbsp;</label>
  552:         </fieldset>
  553:   </div>
  554: END
  555:     $r->print(<<END);
  556:   <div style="padding-bottom: 2px">
  557:     <form name="upublisher" enctype="multipart/form-data" method="post" action="/adm/upload">
  558:       <fieldset>
  559:         <legend>$lt{'updc'}</legend>
  560:         <input type="hidden" name="filename" value="/priv$thisdisfn/" />
  561:         <input type="file" name="upfile" class="LC_flUpload" />
  562:         <input type="hidden" id="LC_free_space" value="$free_space" />
  563:         <input type="button" value="$lt{'uplo'}"  onclick="checkUpload(this.form)" />
  564:       </fieldset>
  565:     </form>
  566:   </div>
  567: 
  568:   <div>
  569:     <form name="fileaction" method="post" action="/adm/cfile">
  570:       <fieldset>
  571:               <legend>$lt{'crea'}</legend>
  572: 	      <span class="LC_nobreak">
  573: 		<input type="hidden" name="filename" value="/priv$thisdisfn/" />
  574:                   <script type="text/javascript">
  575:                     function validate_go() {
  576:                         var selected = document.fileaction.action.selectedIndex;
  577:                         if (selected == 0) {
  578:                             alert('$lt{'pick'}');
  579:                         } else {
  580:                             document.fileaction.submit();
  581:                         }
  582:                     }
  583:                   </script>
  584: 		  <select name="action">
  585: 		    <option value="none">$lt{'sela'}</option>
  586: 		    <option value="newfile">$lt{'nfil'}:</option>
  587: 		    <option value="newhtmlfile">$lt{'nhtm'}:</option>
  588: 		    <option value="newproblemfile">$lt{'nprb'}:</option>
  589:                     <option value="newpagefile">$lt{'npag'}:</option>
  590:                     <option value="newsequencefile">$lt{'nseq'}:</option>
  591:                     <option value="newrightsfile">$lt{'ncrf'}:</option>
  592:                     <option value="newstyfile">$lt{'nsty'}:</option>
  593:                     <option value="newtaskfile">$lt{'nbt'}:</option>
  594:                     <option value="newlibraryfile">$lt{'nlib'}:</option>
  595: 	            <option value="newdir">$lt{'nsub'}:</option>
  596: 		  </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();" />
  597: 		<br />
  598:                 <span>$lt{'shcu'}:
  599:                  <input type="hidden" name="mode"/>
  600:                  <a href="javascript:void(0)" onclick="javascript:validate_action('blank')">
  601: 		    <img src="/adm/lonIcons/unknown.gif" title="Create blank problem file" alt="file icon" /></a>
  602:                  <a href="javascript:void(0)" onclick="javascript:validate_action('problemtempl')"> 
  603:                     <img src="/adm/lonIcons/problem.gif" title="Create new problem from template" alt="problem icon" /></a>
  604:                  <a href="javascript:void(0)" onclick="javascript:validate_action('blankhtml')"> 
  605:                     <img src="/adm/lonIcons/html.gif" title="Create new blank HTML file" alt="web page icon" /></a>
  606:                  <a href="javascript:void(0)" onclick="javascript:validate_action('folder')"> 
  607: 		    <img src="/adm/lonIcons/navmap.folder.closed.gif" title="Create new subdirectory" alt="folder icon" /></a>
  608:                 </span>
  609:                  <script type="text/javascript">
  610:                      function validate_action(action){
  611:                          if (document.getElementById('newnameid')) {
  612:                              if (document.getElementById('newnameid').value == '') {
  613:                                  var newname;
  614:                                  var prompttext = "$js_lt{'nanf'}";
  615:                                  if (action == 'folder') {
  616:                                      prompttext = "$js_lt{'nans'}";
  617:                                  }
  618:                                  newname=prompt(prompttext);
  619:                                  if (newname != '') {
  620:                                      document.getElementById('newnameid').value = newname;
  621:                                  }
  622:                              }
  623:                              if (document.getElementById('newnameid').value != '') {
  624:                                  if (action == 'blank') {
  625: 				     document.fileaction.action.value='newproblemfile';
  626: 				     document.fileaction.mode.value='blank';
  627: 			         } else if (action == 'problemtempl') {
  628: 				     document.fileaction.action.value='newproblemfile';
  629:                                      validate_go();
  630:                                  } else if (action == 'blankhtml') {
  631:                                      document.fileaction.action.value='newhtmlfile';
  632:                                      validate_go();
  633:                                  } else if (action == 'folder') {
  634:                                      document.fileaction.action.value='newdir';
  635:                                      document.fileaction.mode.value='folder';
  636:                                  }
  637:                                  fileaction.submit();
  638:                              } else {
  639:                                  alert("$js_lt{'psfn'}");
  640:                              }
  641:                          }
  642:                      }
  643:                  </script>
  644: 		 </span>
  645:       </fieldset>
  646:     </form>
  647:     </div>
  648: </div>
  649: END
  650: }
  651: 
  652: sub resourceactions {
  653:     my ($r,$uname,$udom,$thisdisfn) = @_;
  654:     $r->print(<<END);
  655:        <form name="moveresource" action="/adm/cfile" method="post">
  656:          <input type="hidden" name="filename" value="" />
  657:          <input type="hidden" name="newfilename" value="" />
  658:          <input type="hidden" name="action" value="" />
  659:        </form>
  660:        <form name="delresource" action="/adm/cfile" method="post">
  661:          <input type="hidden" name="filename" value="" />
  662:          <input type="hidden" name="action" value="delete" />
  663:        </form>
  664:        <form name="pubresource" action="/adm/publish" method="post">
  665:          <input type="hidden" name="filename" value="" />
  666:          <input type="hidden" name="makeobsolete" value="0" />
  667:        </form>
  668:        <form name="printresource" action="/adm/printout" method="post">
  669:            <input type="hidden" name="postdata" value="" />
  670:        </form>
  671:        <form name="retrieveres" action="/adm/retrieve" method="post">
  672:            <input type="hidden" name="filename" value="" />
  673:        </form>
  674:        <form name="cleanup" action="/adm/cleanup" method="post">
  675:            <input type="hidden" name="filename" value="" />
  676:        </form>
  677: END
  678: }
  679: 
  680: #
  681: #   Get the title string or "[untitled]" if the file has no title metadata:
  682: #   Without the latter substitution, it's impossible to examine metadata for
  683: #   untitled resources.  Resources may be legitimately untitled, to prevent
  684: #   searches from locating them.
  685: #
  686: #   $str = getTitleString($fullname);
  687: #       $fullname - Fully qualified filename to check.
  688: #
  689: sub getTitleString {
  690:     my $fullname = shift;
  691:     my $title    = &Apache::lonnet::metadata($fullname, 'title');
  692: 
  693:     unless ($title) {
  694: 	$title = "[".&mt('untitled')."]";
  695:     }
  696:     return $title;
  697: }
  698: 
  699: sub getCopyRightString {
  700:     my $fullname = shift;
  701:     return &Apache::lonnet::metadata($fullname, 'copyright');
  702: }
  703: 
  704: sub getSourceRightString {
  705:     my $fullname = shift;
  706:     return &Apache::lonnet::metadata($fullname, 'sourceavail');
  707: }
  708: #
  709: #  Put out a directory table row:
  710: #    putdirectory(r, base, here, dirname, modtime, targetdir, bombs, numdir)
  711: #      r         - Apache request object.
  712: #      reqfile   - File in request.
  713: #      here      - Where we are in directory tree.
  714: #      dirname   - Name of directory special file.
  715: #      modtime   - Encoded modification time.
  716: #      targetdir - Publication target directory.
  717: #      bombs     - Reference to hash of URLs with runtime error messages.
  718: #      numdir    - Reference to scalar used to track number of sub-directories
  719: #                  in directory (used in form name for each "actions" dropdown).
  720: #
  721: sub putdirectory {
  722:     my ($r, $reqfile, $here, $dirname, $modtime, $targetdir, $bombs, $numdir) = @_;
  723: 
  724: # construct the display filename: the directory name unless ..:
  725:    
  726:     my $actionitem;
  727:  
  728:     my $disfilename = $dirname;
  729: # Don't display directory itself, and there is no way up from root directory
  730:     unless ((($dirname eq '..') && ($reqfile=~/^\/[^\/]+\/[^\/]+$/)) || ($dirname eq '.')) {
  731:         my $kaputt=0;
  732:         if (ref($bombs) eq 'HASH') {
  733:             foreach my $key (keys(%{$bombs})) {
  734:                 my $currentdir = &Apache::lonnet::declutter("$targetdir/$disfilename");
  735:                 if (($key) =~ m{^\Q$currentdir\E/}) { $kaputt=1; last; }
  736:             }
  737:         }
  738: #
  739: # Get the metadata from that directory's default.meta to display titles
  740: #
  741: 	%Apache::lonpublisher::metadatafields=();
  742: 	%Apache::lonpublisher::metadatakeys=();
  743: 	&Apache::lonpublisher::metaeval(
  744:                  &Apache::lonnet::getfile($r->dir_config('lonDocRoot').$here.'/'.$dirname.'/default.meta')
  745:                                        );
  746:         if ($dirname eq '..') {
  747:             $actionitem = &mt('Go to ...');
  748:             $disfilename = '<i>'.&mt('Parent Directory').'</i>';
  749:         } else {
  750:             $actionitem = 
  751:                     '<form name="dirselect_'.$$numdir.
  752:                     '" action="/adm/publish">'.
  753:                     '<select name="diraction" onchange="SetPubDir(this.form,document)">'.
  754:                       '<option selected="selected">'.&mt('Select action').'</option>'.
  755:                       '<option value="open">'.&mt('Open').'</option>'.
  756:                       '<option value="publish">'.&mt('Publish').'</option>'.
  757:                       '<option value="editmeta">'.&mt('Edit Metadata').'</option>'.
  758:                       '<option value="printdir">'.&mt('Print directory').'</option>'.
  759:                       '<option value="delete">'.&mt('Delete directory').'</option>'.
  760:                     '</select>'.
  761:                      '<input type="hidden" name="filename" value="'.&HTML::Entities::encode($here.'/'.$dirname,'<>&"').'/" />'.
  762:                      '<input type="hidden" name="openname" value="'.$here.'/'.$dirname.'/" />'.
  763:                      '<input type="hidden" name="postdata" value="" />'.
  764:                    '</form>';
  765:             $$numdir ++;
  766:         }
  767: 	$r->print('<tr class="LC_browser_folder">'.
  768: 		  '<td><img src="'.
  769: 		  $Apache::lonnet::perlvar{'lonIconsURL'}.'/navmap.folder.closed.gif" alt="folder" /></td>'.
  770: 		  '<td>'.$actionitem.'</td>'.
  771: 		  '<td><span class="LC_filename"><a href="'.&HTML::Entities::encode($here.'/'.$dirname,'<>&"').'/">'.
  772: 		  $disfilename.'</a></span></td>'.
  773: 		        '<td colspan="3">'.($kaputt?&Apache::lonhtmlcommon::authorbombs($targetdir.'/'.$disfilename.'/'):'').$Apache::lonpublisher::metadatafields{'title'});
  774: 	if ($Apache::lonpublisher::metadatafields{'subject'} ne '') {
  775: 	    $r->print(' <i>'.
  776: 		      $Apache::lonpublisher::metadatafields{'subject'}.
  777: 		      '</i> ');
  778: 	}
  779: 	$r->print($Apache::lonpublisher::metadatafields{'keywords'}.'</td>'.
  780: 		  '<td>'.&Apache::lonlocal::locallocaltime($modtime).'</td>'.
  781: 	          '<td></td>'.
  782: 		  "</tr>\n");
  783:     }
  784:     return;
  785: }
  786: 
  787: sub getTitle {
  788:     my ($resdir, $targetdir, $filename, $linkfilename, $meta_same, $bombs) = @_;
  789:     my $title='';
  790:     my $titleString = &getTitleString($targetdir.'/'.$filename);
  791:     if (-e $resdir.'/'.$filename) {
  792: 	$title = '<a href="'.$targetdir.'/'.$filename.
  793: 	    '.meta" target="cat">'.$titleString.'</a>';
  794:         if (!$meta_same) {
  795: 	    $title = &mt('Metadata Modified').'<br />'.$title.
  796: 		'<br />'.
  797:                 &Apache::loncommon::modal_link(
  798:                     '/adm/diff?filename='.$linkfilename.'.meta'.'&amp;versiontwo=priv',
  799:                     &mt('Metadata Diffs'),600,500);
  800: 	    $title.="\n".'<br />'.
  801:                 &Apache::loncommon::modal_link(
  802:                     '/adm/retrieve?filename='.$linkfilename.'.meta&amp;inhibitmenu=yes&amp;add_modal=yes',
  803:                     &mt('Retrieve Metadata'),600,500);
  804:         } 
  805:     }
  806:     # Allow editing metadata of published and unpublished resources
  807:     $title .= "\n".'<br />' if ($title);
  808:     $title .= '<a href="'.$linkfilename.'.meta">'.
  809:               ($$bombs{&Apache::lonnet::declutter($targetdir.'/'.$filename)}?
  810:                   '<img src="/adm/lonMisc/bomb.gif" border="0" alt="'.&mt('bomb').'" />':
  811:                   &mt('Edit Metadata')).
  812:               '</a>';
  813: 
  814:     return ($title, $titleString);
  815: }
  816: 
  817: 
  818: sub isMetaSame {
  819:     my ($cstr_dir, $resdir, $filename) = @_;
  820:     my $meta_cmtime = (stat($cstr_dir.'/'.$filename.'.meta'))[9];
  821:     my $meta_rmtime = (stat($resdir.'/'.$filename.'.meta'))[9];
  822:     return (&Apache::londiff::are_different_files($resdir.'/'.$filename.'.meta',
  823:             $cstr_dir.'/'.$filename.'.meta') && $meta_rmtime < $meta_cmtime) 
  824:         ? 0 : 1;
  825: }
  826:     
  827: 
  828: sub getStatus {    
  829:     my ($resdir, $targetdir, $cstr_dir, $filename,  
  830:             $linkfilename, $cmtime, $meta_same) = @_;
  831:     my $pubstatus = 'unpublished';
  832:     my $status = &mt('Unpublished');
  833: 
  834:     if (-e $resdir.'/'.$filename) {
  835:         my $same = 0;
  836:         if ((stat($resdir.'/'.$filename))[9] >= $cmtime) {
  837:             $same = 1;
  838:         } else {
  839:            if (&Apache::londiff::are_different_files($resdir.'/'.$filename,
  840: 						     $cstr_dir.'/'.$filename)) {
  841:               $same = 0;
  842:            } else {
  843:               $same = 1;
  844:            }
  845:         }
  846: 
  847:         my $rights_status =
  848:             &mt(&getCopyRightString($targetdir.'/'.$filename)).', ';
  849: 
  850:         my %lt_SourceRight = &Apache::lonlocal::texthash(
  851:                'open'   => 'Source: open',
  852:                'closed' => 'Source: closed',
  853:         );
  854:         $rights_status .=
  855:             $lt_SourceRight{&getSourceRightString($targetdir.'/'.$filename)};
  856: 
  857: 	if ($same) {
  858: 	    if (&Apache::lonnet::metadata($targetdir.'/'.$filename,'obsolete')) {
  859:                 $pubstatus = 'obsolete';
  860: 		$status=&mt('Obsolete');
  861:             } else {
  862: 		if (!$meta_same) {
  863: 		    $pubstatus = 'metamodified';
  864: 		} else {
  865: 		    $pubstatus = 'published';
  866: 		}
  867: 		$status=&mt('Published').
  868: 		    '<br />'. $rights_status;
  869: 	    }
  870: 	} else {
  871:             $pubstatus = 'modified';
  872: 	    $status=&mt('Modified').
  873: 		'<br />'. $rights_status;
  874: 	    if (&Apache::loncommon::fileembstyle(($filename=~/\.(\w+)$/)) eq 'ssi') {
  875: 		$status.='<br />'.
  876:                          &Apache::loncommon::modal_link(
  877:                              '/adm/diff?filename='.$linkfilename.'&amp;versiontwo=priv',
  878:                              &mt('Diffs'),600,500);
  879: 	    }
  880: 	} 
  881: 
  882: 	$status.="\n".'<br />'.
  883:              &Apache::loncommon::modal_link(
  884:                  '/adm/retrieve?filename='.$linkfilename.'&amp;inhibitmenu=yes&amp;add_modal=yes',&mt('Retrieve'),600,500);
  885:     }
  886: 
  887:     return ($status, $pubstatus);
  888: }
  889: 
  890: 
  891: #
  892: #   Put a table row for a file resource.
  893: #
  894: sub putresource {
  895:     my ($r, $udom, $uname, $filename, $thisdisfn, $resdir, $targetdir, 
  896:             $linkdir, $cmtime, $size, $numres, $linkfilename, $title, 
  897:             $status, $pubstatus) = @_;
  898:     &Apache::lonnet::devalidate_cache_new('meta',$targetdir.'/'.$filename);
  899: 
  900:     my $editlink='';
  901:     my $editlink2='';
  902:     if ($filename=~/\.(xml|html|htm|xhtml|xhtm|sty)$/) {
  903: 	$editlink=' <br />(<a href="'.$linkdir.'/'.$filename.'?editmode=Edit&amp;problemmode=edit">'.&mt('Edit').'</a>)';
  904:     }
  905:     if ($filename=~/$LONCAPA::assess_re/) {
  906: 	$editlink=' (<a href="'.$linkdir.'/'.$filename.'?editmode=Edit&amp;problemmode=editxml">'.&mt('EditXML').'</a>)';
  907: 	$editlink2=' <br />(<a href="'.$linkdir.'/'.$filename.'?editmode=Edit&amp;problemmode=edit">'.&mt('Edit').'</a>)';
  908:     }
  909:     if ($filename=~/\.(xml|html|htm|xhtml|xhtm)$/ || $filename=~/$LONCAPA::assess_re/) {
  910:         if ($env{'browser.type'} ne 'explorer' || $env{'browser.version'} > 9) {
  911:             my $daxeurl = '/daxepage'.$linkdir.'/'.$filename;
  912:             $editlink .= ' (<a href="'.$daxeurl.'" target="_blank">Daxe</a>)';
  913:         }
  914:     }
  915:     if ($filename=~/\.(problem|exam|quiz|assess|survey|form|library|xml|html|htm|xhtml|xhtm|sty)$/) {
  916: 	$editlink.=' (<a href="/adm/cleanup?filename='.$linkfilename.'">'.&mt('Clean Up').')</a>';
  917:     }
  918:     if ($filename=~/\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
  919: 	$editlink=' (<a href="/adm/cfile?decompress='.$linkfilename.'">'.&mt('Decompress').'</a>)';
  920:     }
  921:     my $publish_button = (-e $resdir.'/'.$filename) ? &mt('Re-publish') : &mt('Publish');
  922:     my $pub_select = '';
  923:     &create_pubselect($r,\$pub_select,$udom,$uname,$thisdisfn,$filename,$resdir,$pubstatus,$publish_button,$numres);
  924:     $r->print(&Apache::loncommon::start_data_table_row().
  925: 	      '<td>'.($filename=~/[\#\~]$/?'&nbsp;':
  926: 		      '<img src="'.&Apache::loncommon::icon($filename).'" alt="" />').'</td>'.
  927:               '<td>'.$pub_select.'</td>'.
  928: 	      '<td><span class="LC_filename">'.
  929: 	      '<a href="'.$linkdir.'/'.$filename.'">'.
  930:                $filename.'</a></span>'.$editlink2.$editlink.
  931: 	      '</td>'.
  932: 	      '<td>'.$title.'</td>'.
  933:               '<td class="LC_browser_file_'.$pubstatus.'">&nbsp;&nbsp;</td>'. # Display publication status
  934:               '<td>'.$status.'</td>'.
  935: 	      '<td>'.&Apache::lonlocal::locallocaltime($cmtime).'</td>'.
  936: 	      '<td>'.sprintf("%.1f",$size).'</td>'.
  937: 	      &Apache::loncommon::end_data_table_row()
  938:     );
  939:     return;
  940: }
  941: 
  942: sub create_pubselect {
  943:     my ($r,$pub_select,$udom,$uname,$thisdisfn,$filename,$resdir,$pubstatus,$publish_button,$numres) = @_;
  944:     $$pub_select = '
  945: <form name="resselect_'.$$numres.'" action="">
  946: <select name="reschoice"  onchange="SetResChoice(this.form)">
  947: <option>'.&mt('Select action').'</option>'.
  948: '<option value="copy">'.&mt('Copy').'</option>';
  949:     if ($pubstatus eq 'obsolete' || $pubstatus eq 'unpublished') {
  950:         $$pub_select .= 
  951: '<option value="rename">'.&mt('Rename').'</option>'.
  952: '<option value="move">'.&mt('Move').'</option>'.
  953: '<option value="delete">'.&mt('Delete').'</option>';
  954:     } else {
  955:         $$pub_select .= '
  956: <option value="obsolete">'.&mt('Mark obsolete').'</option>';
  957:     }
  958: # check for versions
  959:     my $versions = &check_for_versions($r,'/'.$filename,$udom,$uname);
  960:     if ($versions > 0) {
  961:         $$pub_select .='
  962: <option value="retrieve">'.&mt('Retrieve old version').'</option>';
  963:     }
  964:     $$pub_select .= '
  965: <option value="publish">'.$publish_button.'</option>'.
  966: '<option value="cleanup">'.&mt('Clean up').'</option>'.
  967: '<option value="print">'.&mt('Print').'</option>'.
  968: '</select>
  969: <input type="hidden" name="filename" value="/priv'.
  970:  &HTML::Entities::encode($thisdisfn.'/'.$filename,'<>&"').'" />
  971:  <input type="hidden" name="dispfilename" value="'.
  972:  &HTML::Entities::encode($filename).'" /></form>';
  973:     $$numres ++;
  974: }
  975: 
  976: sub check_for_versions {
  977:     my ($r,$fn,$udom,$uname) = @_;
  978:     my $versions = 0;
  979:     my $docroot=$r->dir_config('lonDocRoot');
  980:     my $resfn=$docroot.'/res/'.$udom.'/'.$uname.$fn;
  981:     my $resdir=$resfn;
  982:     $resdir=~s/\/[^\/]+$/\//;
  983:     $fn=~/\/([^\/]+)\.(\w+)$/;
  984:     my $main=$1;
  985:     my $suffix=$2;
  986:     opendir(DIR,$resdir);
  987:     while (my $filename=readdir(DIR)) {
  988:         if ($filename=~/^\Q$main\E\.(\d+)\.\Q$suffix\E$/) {
  989:             $versions ++;        
  990:         }
  991:     }
  992:     closedir(DIR);
  993:     return $versions;
  994: }
  995: 
  996: sub prepareJsonTranslations {
  997:     my $json = 
  998:         '{"translations":{'.
  999:             '"edit":"'.&mt('Edit').'",'.
 1000:             '"editxml":"'.&mt('EditXML').'",'.
 1001:             '"editmeta":"'.&mt('Edit Metadata').'",'.
 1002:             '"obsolete":"'.&mt('Obsolete').'",'.
 1003:             '"modified":"'.&mt('Modified').'",'.
 1004:             '"published":"'.&mt('Published').'",'.
 1005:             '"unpublished":"'.&mt('Unpublished').'",'.
 1006:             '"diff":"'.&mt('Diff').'",'.
 1007:             '"retrieve":"'.&mt('Retrieve').'",'.
 1008:             '"directory":"'.&mt('Directory').'",'.
 1009:             '"results":"'.&mt('Show results for keyword:').'"'.
 1010:         '}}';
 1011: }
 1012: 
 1013: # gathers all files in the working directory except the ones that are already on screen
 1014: sub prepareJsonData {
 1015:     my ($uname, $udom, $pathToSkip) = @_;
 1016:     my $path = "/home/httpd/html/priv/$udom/$uname/";
 1017: 
 1018:     # maximum number of entries, to limit workload and required storage space
 1019:     my $entries = 100;
 1020:     my $firstfile = 1;
 1021:     my $firstdir = 1;
 1022: 
 1023:     my $json = '{"resources":[';
 1024:     $json .= &prepareJsonData_rec($path, \$entries, \$firstfile, \$firstdir, $pathToSkip);
 1025:     $json .= ']}';
 1026: 
 1027:     # if the json string is invalid the whole search breaks.
 1028:     # so we want to make sure that the string is valid in any case.
 1029:     $json =~ s/,\s*,/,/g;
 1030:     $json =~ s/\}\s*\{/\},\{/g;
 1031:     $json =~ s/\}\s*,\s*\]/\}\]/g;
 1032:     return $json;
 1033: }
 1034: 
 1035: # recursive part of json file gathering
 1036: sub prepareJsonData_rec {
 1037:     my ($path, $entries, $firstfile, $firstdir, $pathToSkip) = @_;
 1038:     my $json;
 1039:     my $skipThisFolder = $path =~ m/$pathToSkip\/$/?1:0;
 1040: 
 1041:     my @dirs;
 1042:     my @resources;
 1043:     my @ignored = qw(bak log meta save . ..);
 1044: 
 1045: # Phase 1: Gathering
 1046:     opendir(DIR,$path);
 1047:     my @files=sort {uc($a) cmp uc($b)} (readdir(DIR));
 1048:     foreach my $filename (@files) {
 1049:         next if ($filename eq '.DS_Store');
 1050: 
 1051:         # gather all resources
 1052:         if ($filename !~ /\./) {
 1053:             # its a folder
 1054:             push(@dirs, $filename);
 1055:         } else {
 1056:             # only push files we dont want to ignore
 1057:             next if ($skipThisFolder);
 1058: 
 1059:             $filename =~ /\.(\w+?)$/;
 1060:             unless (grep /$1/, @ignored) {
 1061:                 push(@resources, $filename);
 1062:             }
 1063:         }
 1064:     }
 1065:     closedir(DIR);
 1066:     # nothing to do here if both lists are empty
 1067:     return unless ( @dirs || @resources );
 1068:     
 1069: # Phase 2: Working
 1070:     $$firstfile = 1;
 1071: 
 1072:     foreach (@dirs) {
 1073:         $json .= '{"name":"'.$_.'",'.
 1074:                   '"path":"'.$path.$_.'",'.
 1075:                   '"title":"",'.
 1076:                   '"status":"",'.
 1077:                   '"cmtime":""},';
 1078:     }
 1079: 
 1080:     foreach (@resources) {
 1081:         last if ($$entries < 1);
 1082:         my $title = &getTitleString($path.$_);
 1083: 
 1084:         my $privpath = $path.$_;
 1085:         my $respath = $privpath;
 1086:         $respath =~ s/httpd\/html\/priv\//httpd\/html\/res\//;
 1087: 
 1088:         my $cmtime = (stat($privpath))[9];
 1089:         my $rmtime = (stat($respath))[9];
 1090: 
 1091:         unless ($$firstfile) { $json .= ','; } else { $$firstfile = 0; }
 1092: 
 1093:         my $status = 'unpublished';
 1094: 
 1095:         # if a resource is published, the published version (/html/res/filepath) gets its own modification time
 1096:         # this is newer or equal then the version in your authoring space (/html/priv/filepath)
 1097:         if ($rmtime >= $cmtime) {
 1098:             # obsolete
 1099:             if (&Apache::lonnet::metadata($respath, 'obsolete')) {
 1100:                 $status = 'obsolete';
 1101:             }else{
 1102:                 $status = 'published';
 1103:             }
 1104:         } else {
 1105:             $status = 'modified';
 1106:         }
 1107: 
 1108:         $json .= '{"name":"'.$_.'",'.
 1109:                   '"path":"'.$path.'",'.
 1110:                   '"title":"'.$title.'",'.
 1111:                   '"status":"'.$status.'",'.
 1112:                   '"cmtime":"'.&Apache::lonlocal::locallocaltime($cmtime).'"}';
 1113:         $$entries--;
 1114:     }
 1115: 
 1116:     foreach(@dirs) {
 1117:         next if ($$entries < 1);
 1118:         $json .= ',';
 1119:         $json .= &prepareJsonData_rec
 1120:                     ($path.$_.'/', $entries, $firstfile, $firstdir, $pathToSkip);
 1121:     }
 1122:     return $json;
 1123: }
 1124: 1;
 1125: __END__
 1126: 
 1127: 
 1128: =head1 NAME
 1129: 
 1130: Apache::lonpubdir - Authoring space directory lister
 1131: 
 1132: =head1 SYNOPSIS
 1133: 
 1134: Invoked (for various locations) by /etc/httpd/conf/srm.conf:
 1135: 
 1136:  <LocationMatch "^/+priv.*/$">
 1137:  PerlAccessHandler       Apache::loncacc
 1138:  SetHandler perl-script
 1139:  PerlHandler Apache::lonpubdir
 1140:  ErrorDocument     403 /adm/login
 1141:  ErrorDocument     404 /adm/notfound.html
 1142:  ErrorDocument     406 /adm/unauthorized.html
 1143:  ErrorDocument	  500 /adm/errorhandler
 1144:  </LocationMatch>
 1145: 
 1146:  <Location /adm/pubdir>
 1147:  PerlAccessHandler       Apache::lonacc
 1148:  SetHandler perl-script
 1149:  PerlHandler Apache::lonpubdir
 1150:  ErrorDocument     403 /adm/login
 1151:  ErrorDocument     404 /adm/notfound.html
 1152:  ErrorDocument     406 /adm/unauthorized.html
 1153:  ErrorDocument	  500 /adm/errorhandler
 1154:  </Location>
 1155: 
 1156: =head1 INTRODUCTION
 1157: 
 1158: This module publishes a directory of files.
 1159: 
 1160: This is part of the LearningOnline Network with CAPA project
 1161: described at http://www.lon-capa.org.
 1162: 
 1163: =head1 HANDLER SUBROUTINE
 1164: 
 1165: This routine is called by Apache and mod_perl.
 1166: 
 1167: =over 4
 1168: 
 1169: =item *
 1170: 
 1171: read in information
 1172: 
 1173: =item *
 1174: 
 1175: start page output
 1176: 
 1177: =item *
 1178: 
 1179: run through list of files and attempt to publish unhidden files
 1180: 
 1181: =back
 1182: 
 1183: =head1 SUBROUTINES:
 1184: 
 1185: =over
 1186: 
 1187: =item startpage($r, $uame, $udom, $thisdisfn)
 1188: 
 1189: Output the header of the page.  This includes:
 1190:  - The HTML header 
 1191:  - The H1/H3  stuff which includes the directory.
 1192:  
 1193:     startpage($r, $uame, $udom, $thisdisfn);
 1194:         $r     - The apache request object.
 1195:         $uname - User name.
 1196:         $udom  - Domain name the user is logged in under.
 1197:         $thisdisfn - Displayable version of the filename.
 1198: 
 1199: =item getTitleString($fullname)
 1200: 
 1201:     Get the title string or "[untitled]" if the file has no title metadata:
 1202:     Without the latter substitution, it's impossible to examine metadata for
 1203:     untitled resources.  Resources may be legitimately untitled, to prevent
 1204:     searches from locating them.
 1205:     
 1206:     $str = getTitleString($fullname);
 1207:         $fullname - Fully qualified filename to check.
 1208: 
 1209: =item putdirectory($r, $base, $here, $dirname, $modtime, $targetdir, $bombs,
 1210:                    $numdir)
 1211: 
 1212:     Put out a directory table row:
 1213:     
 1214:         $r        - Apache request object.
 1215:         $reqfile  - File in request.
 1216:         $here     - Where we are in directory tree.
 1217:         $dirname  - Name of directory special file.
 1218:         $modtime  - Encoded modification time.
 1219:         targetdir - Publication target directory.
 1220:         bombs     - Reference to hash of URLs with runtime error messages.
 1221:         numdir    - Reference to scalar used to track number of sub-directories
 1222:                     in directory (used in form name for each "actions" dropdown).
 1223: 
 1224: =back
 1225: 
 1226: =cut

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