File:  [LON-CAPA] / loncom / publisher / lonpubdir.pm
Revision 1.168: download - view: text, annotated - select for diffs
Fri Jun 10 22:31:34 2016 UTC (7 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Display course's quota usage in file upload section in Course Editor
- Consistent conversion for kB -> MB
- div style for disk usage: inline in Authoring Space; block in portfolio.

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

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