File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1093: download - view: text, annotated - select for diffs
Tue Aug 21 01:50:33 2012 UTC (11 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Checkboxes so user can choose what user information to include in user listings.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1093 2012/08/21 01:50:33 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: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: use Text::Aspell;
   74: 
   75: # ---------------------------------------------- Designs
   76: use vars qw(%defaultdesign);
   77: 
   78: my $readit;
   79: 
   80: 
   81: ##
   82: ## Global Variables
   83: ##
   84: 
   85: 
   86: # ----------------------------------------------- SSI with retries:
   87: #
   88: 
   89: =pod
   90: 
   91: =head1 Server Side include with retries:
   92: 
   93: =over 4
   94: 
   95: =item * &ssi_with_retries(resource,retries form)
   96: 
   97: Performs an ssi with some number of retries.  Retries continue either
   98: until the result is ok or until the retry count supplied by the
   99: caller is exhausted.  
  100: 
  101: Inputs:
  102: 
  103: =over 4
  104: 
  105: resource   - Identifies the resource to insert.
  106: 
  107: retries    - Count of the number of retries allowed.
  108: 
  109: form       - Hash that identifies the rendering options.
  110: 
  111: =back
  112: 
  113: Returns:
  114: 
  115: =over 4
  116: 
  117: content    - The content of the response.  If retries were exhausted this is empty.
  118: 
  119: response   - The response from the last attempt (which may or may not have been successful.
  120: 
  121: =back
  122: 
  123: =back
  124: 
  125: =cut
  126: 
  127: sub ssi_with_retries {
  128:     my ($resource, $retries, %form) = @_;
  129: 
  130: 
  131:     my $ok = 0;			# True if we got a good response.
  132:     my $content;
  133:     my $response;
  134: 
  135:     # Try to get the ssi done. within the retries count:
  136: 
  137:     do {
  138: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  139: 	$ok      = $response->is_success;
  140:         if (!$ok) {
  141:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  142:         }
  143: 	$retries--;
  144:     } while (!$ok && ($retries > 0));
  145: 
  146:     if (!$ok) {
  147: 	$content = '';		# On error return an empty content.
  148:     }
  149:     return ($content, $response);
  150: 
  151: }
  152: 
  153: 
  154: 
  155: # ----------------------------------------------- Filetypes/Languages/Copyright
  156: my %language;
  157: my %supported_language;
  158: my %supported_codes;
  159: my %latex_language;		# For choosing hyphenation in <transl..>
  160: my %latex_language_bykey;	# for choosing hyphenation from metadata
  161: my %cprtag;
  162: my %scprtag;
  163: my %fe; my %fd; my %fm;
  164: my %category_extensions;
  165: 
  166: # ---------------------------------------------- Thesaurus variables
  167: #
  168: # %Keywords:
  169: #      A hash used by &keyword to determine if a word is considered a keyword.
  170: # $thesaurus_db_file 
  171: #      Scalar containing the full path to the thesaurus database.
  172: 
  173: my %Keywords;
  174: my $thesaurus_db_file;
  175: 
  176: #
  177: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  178: # thesaurus.tab, and filecategories.tab.
  179: #
  180: BEGIN {
  181:     # Variable initialization
  182:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  183:     #
  184:     unless ($readit) {
  185: # ------------------------------------------------------------------- languages
  186:     {
  187:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  188:                                    '/language.tab';
  189:         if ( open(my $fh,"<$langtabfile") ) {
  190:             while (my $line = <$fh>) {
  191:                 next if ($line=~/^\#/);
  192:                 chomp($line);
  193:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  194:                 $language{$key}=$val.' - '.$enc;
  195:                 if ($sup) {
  196:                     $supported_language{$key}=$sup;
  197: 		    $supported_codes{$key}   = $code;
  198:                 }
  199: 		if ($latex) {
  200: 		    $latex_language_bykey{$key} = $latex;
  201: 		    $latex_language{$code} = $latex;
  202: 		}
  203:             }
  204:             close($fh);
  205:         }
  206:     }
  207: # ------------------------------------------------------------------ copyrights
  208:     {
  209:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  210:                                   '/copyright.tab';
  211:         if ( open (my $fh,"<$copyrightfile") ) {
  212:             while (my $line = <$fh>) {
  213:                 next if ($line=~/^\#/);
  214:                 chomp($line);
  215:                 my ($key,$val)=(split(/\s+/,$line,2));
  216:                 $cprtag{$key}=$val;
  217:             }
  218:             close($fh);
  219:         }
  220:     }
  221: # ----------------------------------------------------------- source copyrights
  222:     {
  223:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  224:                                   '/source_copyright.tab';
  225:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  226:             while (my $line = <$fh>) {
  227:                 next if ($line =~ /^\#/);
  228:                 chomp($line);
  229:                 my ($key,$val)=(split(/\s+/,$line,2));
  230:                 $scprtag{$key}=$val;
  231:             }
  232:             close($fh);
  233:         }
  234:     }
  235: 
  236: # -------------------------------------------------------------- default domain designs
  237:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  238:     my $designfile = $designdir.'/default.tab';
  239:     if ( open (my $fh,"<$designfile") ) {
  240:         while (my $line = <$fh>) {
  241:             next if ($line =~ /^\#/);
  242:             chomp($line);
  243:             my ($key,$val)=(split(/\=/,$line));
  244:             if ($val) { $defaultdesign{$key}=$val; }
  245:         }
  246:         close($fh);
  247:     }
  248: 
  249: # ------------------------------------------------------------- file categories
  250:     {
  251:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  252:                                   '/filecategories.tab';
  253:         if ( open (my $fh,"<$categoryfile") ) {
  254: 	    while (my $line = <$fh>) {
  255: 		next if ($line =~ /^\#/);
  256: 		chomp($line);
  257:                 my ($extension,$category)=(split(/\s+/,$line,2));
  258:                 push @{$category_extensions{lc($category)}},$extension;
  259:             }
  260:             close($fh);
  261:         }
  262: 
  263:     }
  264: # ------------------------------------------------------------------ file types
  265:     {
  266:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  267:                '/filetypes.tab';
  268:         if ( open (my $fh,"<$typesfile") ) {
  269:             while (my $line = <$fh>) {
  270: 		next if ($line =~ /^\#/);
  271: 		chomp($line);
  272:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  273:                 if ($descr ne '') {
  274:                     $fe{$ending}=lc($emb);
  275:                     $fd{$ending}=$descr;
  276:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  277:                 }
  278:             }
  279:             close($fh);
  280:         }
  281:     }
  282:     &Apache::lonnet::logthis(
  283:              "<span style='color:yellow;'>INFO: Read file types</span>");
  284:     $readit=1;
  285:     }  # end of unless($readit) 
  286:     
  287: }
  288: 
  289: ###############################################################
  290: ##           HTML and Javascript Helper Functions            ##
  291: ###############################################################
  292: 
  293: =pod 
  294: 
  295: =head1 HTML and Javascript Functions
  296: 
  297: =over 4
  298: 
  299: =item * &browser_and_searcher_javascript()
  300: 
  301: X<browsing, javascript>X<searching, javascript>Returns a string
  302: containing javascript with two functions, C<openbrowser> and
  303: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  304: tags.
  305: 
  306: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  307: 
  308: inputs: formname, elementname, only, omit
  309: 
  310: formname and elementname indicate the name of the html form and name of
  311: the element that the results of the browsing selection are to be placed in. 
  312: 
  313: Specifying 'only' will restrict the browser to displaying only files
  314: with the given extension.  Can be a comma separated list.
  315: 
  316: Specifying 'omit' will restrict the browser to NOT displaying files
  317: with the given extension.  Can be a comma separated list.
  318: 
  319: =item * &opensearcher(formname,elementname) [javascript]
  320: 
  321: Inputs: formname, elementname
  322: 
  323: formname and elementname specify the name of the html form and the name
  324: of the element the selection from the search results will be placed in.
  325: 
  326: =cut
  327: 
  328: sub browser_and_searcher_javascript {
  329:     my ($mode)=@_;
  330:     if (!defined($mode)) { $mode='edit'; }
  331:     my $resurl=&escape_single(&lastresurl());
  332:     return <<END;
  333: // <!-- BEGIN LON-CAPA Internal
  334:     var editbrowser = null;
  335:     function openbrowser(formname,elementname,only,omit,titleelement) {
  336:         var url = '$resurl/?';
  337:         if (editbrowser == null) {
  338:             url += 'launch=1&';
  339:         }
  340:         url += 'catalogmode=interactive&';
  341:         url += 'mode=$mode&';
  342:         url += 'inhibitmenu=yes&';
  343:         url += 'form=' + formname + '&';
  344:         if (only != null) {
  345:             url += 'only=' + only + '&';
  346:         } else {
  347:             url += 'only=&';
  348: 	}
  349:         if (omit != null) {
  350:             url += 'omit=' + omit + '&';
  351:         } else {
  352:             url += 'omit=&';
  353: 	}
  354:         if (titleelement != null) {
  355:             url += 'titleelement=' + titleelement + '&';
  356:         } else {
  357: 	    url += 'titleelement=&';
  358: 	}
  359:         url += 'element=' + elementname + '';
  360:         var title = 'Browser';
  361:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  362:         options += ',width=700,height=600';
  363:         editbrowser = open(url,title,options,'1');
  364:         editbrowser.focus();
  365:     }
  366:     var editsearcher;
  367:     function opensearcher(formname,elementname,titleelement) {
  368:         var url = '/adm/searchcat?';
  369:         if (editsearcher == null) {
  370:             url += 'launch=1&';
  371:         }
  372:         url += 'catalogmode=interactive&';
  373:         url += 'mode=$mode&';
  374:         url += 'form=' + formname + '&';
  375:         if (titleelement != null) {
  376:             url += 'titleelement=' + titleelement + '&';
  377:         } else {
  378: 	    url += 'titleelement=&';
  379: 	}
  380:         url += 'element=' + elementname + '';
  381:         var title = 'Search';
  382:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  383:         options += ',width=700,height=600';
  384:         editsearcher = open(url,title,options,'1');
  385:         editsearcher.focus();
  386:     }
  387: // END LON-CAPA Internal -->
  388: END
  389: }
  390: 
  391: sub lastresurl {
  392:     if ($env{'environment.lastresurl'}) {
  393: 	return $env{'environment.lastresurl'}
  394:     } else {
  395: 	return '/res';
  396:     }
  397: }
  398: 
  399: sub storeresurl {
  400:     my $resurl=&Apache::lonnet::clutter(shift);
  401:     unless ($resurl=~/^\/res/) { return 0; }
  402:     $resurl=~s/\/$//;
  403:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  404:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  405:     return 1;
  406: }
  407: 
  408: sub studentbrowser_javascript {
  409:    unless (
  410:             (($env{'request.course.id'}) && 
  411:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  412: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  413: 					  '/'.$env{'request.course.sec'})
  414: 	      ))
  415:          || ($env{'request.role'}=~/^(au|dc|su)/)
  416:           ) { return ''; }  
  417:    return (<<'ENDSTDBRW');
  418: <script type="text/javascript" language="Javascript">
  419: // <![CDATA[
  420:     var stdeditbrowser;
  421:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  422:         var url = '/adm/pickstudent?';
  423:         var filter;
  424: 	if (!ignorefilter) {
  425: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  426: 	}
  427:         if (filter != null) {
  428:            if (filter != '') {
  429:                url += 'filter='+filter+'&';
  430: 	   }
  431:         }
  432:         url += 'form=' + formname + '&unameelement='+uname+
  433:                                     '&udomelement='+udom+
  434:                                     '&clicker='+clicker;
  435: 	if (roleflag) { url+="&roles=1"; }
  436:         if (courseadvonly) { url+="&courseadvonly=1"; }
  437:         var title = 'Student_Browser';
  438:         var options = 'scrollbars=1,resizable=1,menubar=0';
  439:         options += ',width=700,height=600';
  440:         stdeditbrowser = open(url,title,options,'1');
  441:         stdeditbrowser.focus();
  442:     }
  443: // ]]>
  444: </script>
  445: ENDSTDBRW
  446: }
  447: 
  448: sub resourcebrowser_javascript {
  449:    unless ($env{'request.course.id'}) { return ''; }
  450:    return (<<'ENDRESBRW');
  451: <script type="text/javascript" language="Javascript">
  452: // <![CDATA[
  453:     var reseditbrowser;
  454:     function openresbrowser(formname,reslink) {
  455:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  456:         var title = 'Resource_Browser';
  457:         var options = 'scrollbars=1,resizable=1,menubar=0';
  458:         options += ',width=700,height=500';
  459:         reseditbrowser = open(url,title,options,'1');
  460:         reseditbrowser.focus();
  461:     }
  462: // ]]>
  463: </script>
  464: ENDRESBRW
  465: }
  466: 
  467: sub selectstudent_link {
  468:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  469:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  470:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  471:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  472:    if ($env{'request.course.id'}) {  
  473:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  474: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  475: 					'/'.$env{'request.course.sec'})) {
  476: 	   return '';
  477:        }
  478:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  479:        if ($courseadvonly)  {
  480:            $callargs .= ",'',1,1";
  481:        }
  482:        return '<span class="LC_nobreak">'.
  483:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  484:               &mt('Select User').'</a></span>';
  485:    }
  486:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  487:        $callargs .= ",'',1"; 
  488:        return '<span class="LC_nobreak">'.
  489:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  490:               &mt('Select User').'</a></span>';
  491:    }
  492:    return '';
  493: }
  494: 
  495: sub selectresource_link {
  496:    my ($form,$reslink,$arg)=@_;
  497:    
  498:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  499:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  500:    unless ($env{'request.course.id'}) { return $arg; }
  501:    return '<span class="LC_nobreak">'.
  502:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  503:               $arg.'</a></span>';
  504: }
  505: 
  506: 
  507: 
  508: sub authorbrowser_javascript {
  509:     return <<"ENDAUTHORBRW";
  510: <script type="text/javascript" language="JavaScript">
  511: // <![CDATA[
  512: var stdeditbrowser;
  513: 
  514: function openauthorbrowser(formname,udom) {
  515:     var url = '/adm/pickauthor?';
  516:     url += 'form='+formname+'&roledom='+udom;
  517:     var title = 'Author_Browser';
  518:     var options = 'scrollbars=1,resizable=1,menubar=0';
  519:     options += ',width=700,height=600';
  520:     stdeditbrowser = open(url,title,options,'1');
  521:     stdeditbrowser.focus();
  522: }
  523: 
  524: // ]]>
  525: </script>
  526: ENDAUTHORBRW
  527: }
  528: 
  529: sub coursebrowser_javascript {
  530:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  531:     my $wintitle = 'Course_Browser';
  532:     if ($crstype eq 'Community') {
  533:         $wintitle = 'Community_Browser';
  534:     }
  535:     my $id_functions = &javascript_index_functions();
  536:     my $output = '
  537: <script type="text/javascript" language="JavaScript">
  538: // <![CDATA[
  539:     var stdeditbrowser;'."\n";
  540: 
  541:     $output .= <<"ENDSTDBRW";
  542:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  543:         var url = '/adm/pickcourse?';
  544:         var formid = getFormIdByName(formname);
  545:         var domainfilter = getDomainFromSelectbox(formname,udom);
  546:         if (domainfilter != null) {
  547:            if (domainfilter != '') {
  548:                url += 'domainfilter='+domainfilter+'&';
  549: 	   }
  550:         }
  551:         url += 'form=' + formname + '&cnumelement='+uname+
  552: 	                            '&cdomelement='+udom+
  553:                                     '&cnameelement='+desc;
  554:         if (extra_element !=null && extra_element != '') {
  555:             if (formname == 'rolechoice' || formname == 'studentform') {
  556:                 url += '&roleelement='+extra_element;
  557:                 if (domainfilter == null || domainfilter == '') {
  558:                     url += '&domainfilter='+extra_element;
  559:                 }
  560:             }
  561:             else {
  562:                 if (formname == 'portform') {
  563:                     url += '&setroles='+extra_element;
  564:                 } else {
  565:                     if (formname == 'rules') {
  566:                         url += '&fixeddom='+extra_element; 
  567:                     }
  568:                 }
  569:             }     
  570:         }
  571:         if (type != null && type != '') {
  572:             url += '&type='+type;
  573:         }
  574:         if (type_elem != null && type_elem != '') {
  575:             url += '&typeelement='+type_elem;
  576:         }
  577:         if (formname == 'ccrs') {
  578:             var ownername = document.forms[formid].ccuname.value;
  579:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  580:             url += '&cloner='+ownername+':'+ownerdom;
  581:         }
  582:         if (multflag !=null && multflag != '') {
  583:             url += '&multiple='+multflag;
  584:         }
  585:         var title = '$wintitle';
  586:         var options = 'scrollbars=1,resizable=1,menubar=0';
  587:         options += ',width=700,height=600';
  588:         stdeditbrowser = open(url,title,options,'1');
  589:         stdeditbrowser.focus();
  590:     }
  591: $id_functions
  592: ENDSTDBRW
  593:     if (($sec_element ne '') || ($role_element ne '')) {
  594:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  595:     }
  596:     $output .= '
  597: // ]]>
  598: </script>';
  599:     return $output;
  600: }
  601: 
  602: sub javascript_index_functions {
  603:     return <<"ENDJS";
  604: 
  605: function getFormIdByName(formname) {
  606:     for (var i=0;i<document.forms.length;i++) {
  607:         if (document.forms[i].name == formname) {
  608:             return i;
  609:         }
  610:     }
  611:     return -1;
  612: }
  613: 
  614: function getIndexByName(formid,item) {
  615:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  616:         if (document.forms[formid].elements[i].name == item) {
  617:             return i;
  618:         }
  619:     }
  620:     return -1;
  621: }
  622: 
  623: function getDomainFromSelectbox(formname,udom) {
  624:     var userdom;
  625:     var formid = getFormIdByName(formname);
  626:     if (formid > -1) {
  627:         var domid = getIndexByName(formid,udom);
  628:         if (domid > -1) {
  629:             if (document.forms[formid].elements[domid].type == 'select-one') {
  630:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  631:             }
  632:             if (document.forms[formid].elements[domid].type == 'hidden') {
  633:                 userdom=document.forms[formid].elements[domid].value;
  634:             }
  635:         }
  636:     }
  637:     return userdom;
  638: }
  639: 
  640: ENDJS
  641: 
  642: }
  643: 
  644: sub javascript_array_indexof {
  645:     return <<ENDJS;
  646: <script type="text/javascript" language="JavaScript">
  647: // <![CDATA[
  648: 
  649: if (!Array.prototype.indexOf) {
  650:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  651:         "use strict";
  652:         if (this === void 0 || this === null) {
  653:             throw new TypeError();
  654:         }
  655:         var t = Object(this);
  656:         var len = t.length >>> 0;
  657:         if (len === 0) {
  658:             return -1;
  659:         }
  660:         var n = 0;
  661:         if (arguments.length > 0) {
  662:             n = Number(arguments[1]);
  663:             if (n !== n) { // shortcut for verifying if it is NaN
  664:                 n = 0;
  665:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  666:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  667:             }
  668:         }
  669:         if (n >= len) {
  670:             return -1;
  671:         }
  672:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  673:         for (; k < len; k++) {
  674:             if (k in t && t[k] === searchElement) {
  675:                 return k;
  676:             }
  677:         }
  678:         return -1;
  679:     }
  680: }
  681: 
  682: // ]]>
  683: </script>
  684: 
  685: ENDJS
  686: 
  687: }
  688: 
  689: sub userbrowser_javascript {
  690:     my $id_functions = &javascript_index_functions();
  691:     return <<"ENDUSERBRW";
  692: 
  693: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  694:     var url = '/adm/pickuser?';
  695:     var userdom = getDomainFromSelectbox(formname,udom);
  696:     if (userdom != null) {
  697:        if (userdom != '') {
  698:            url += 'srchdom='+userdom+'&';
  699:        }
  700:     }
  701:     url += 'form=' + formname + '&unameelement='+uname+
  702:                                 '&udomelement='+udom+
  703:                                 '&ulastelement='+ulast+
  704:                                 '&ufirstelement='+ufirst+
  705:                                 '&uemailelement='+uemail+
  706:                                 '&hideudomelement='+hideudom+
  707:                                 '&coursedom='+crsdom;
  708:     if ((caller != null) && (caller != undefined)) {
  709:         url += '&caller='+caller;
  710:     }
  711:     var title = 'User_Browser';
  712:     var options = 'scrollbars=1,resizable=1,menubar=0';
  713:     options += ',width=700,height=600';
  714:     var stdeditbrowser = open(url,title,options,'1');
  715:     stdeditbrowser.focus();
  716: }
  717: 
  718: function fix_domain (formname,udom,origdom,uname) {
  719:     var formid = getFormIdByName(formname);
  720:     if (formid > -1) {
  721:         var unameid = getIndexByName(formid,uname);
  722:         var domid = getIndexByName(formid,udom);
  723:         var hidedomid = getIndexByName(formid,origdom);
  724:         if (hidedomid > -1) {
  725:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  726:             var unameval = document.forms[formid].elements[unameid].value;
  727:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  728:                 if (domid > -1) {
  729:                     var slct = document.forms[formid].elements[domid];
  730:                     if (slct.type == 'select-one') {
  731:                         var i;
  732:                         for (i=0;i<slct.length;i++) {
  733:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  734:                         }
  735:                     }
  736:                     if (slct.type == 'hidden') {
  737:                         slct.value = fixeddom;
  738:                     }
  739:                 }
  740:             }
  741:         }
  742:     }
  743:     return;
  744: }
  745: 
  746: $id_functions
  747: ENDUSERBRW
  748: }
  749: 
  750: sub setsec_javascript {
  751:     my ($sec_element,$formname,$role_element) = @_;
  752:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  753:         $communityrolestr);
  754:     if ($role_element ne '') {
  755:         my @allroles = ('st','ta','ep','in','ad');
  756:         foreach my $crstype ('Course','Community') {
  757:             if ($crstype eq 'Community') {
  758:                 foreach my $role (@allroles) {
  759:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  760:                 }
  761:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  762:             } else {
  763:                 foreach my $role (@allroles) {
  764:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  765:                 }
  766:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  767:             }
  768:         }
  769:         $rolestr = '"'.join('","',@allroles).'"';
  770:         $courserolestr = '"'.join('","',@courserolenames).'"';
  771:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  772:     }
  773:     my $setsections = qq|
  774: function setSect(sectionlist) {
  775:     var sectionsArray = new Array();
  776:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  777:         sectionsArray = sectionlist.split(",");
  778:     }
  779:     var numSections = sectionsArray.length;
  780:     document.$formname.$sec_element.length = 0;
  781:     if (numSections == 0) {
  782:         document.$formname.$sec_element.multiple=false;
  783:         document.$formname.$sec_element.size=1;
  784:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  785:     } else {
  786:         if (numSections == 1) {
  787:             document.$formname.$sec_element.multiple=false;
  788:             document.$formname.$sec_element.size=1;
  789:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  790:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  791:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  792:         } else {
  793:             for (var i=0; i<numSections; i++) {
  794:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  795:             }
  796:             document.$formname.$sec_element.multiple=true
  797:             if (numSections < 3) {
  798:                 document.$formname.$sec_element.size=numSections;
  799:             } else {
  800:                 document.$formname.$sec_element.size=3;
  801:             }
  802:             document.$formname.$sec_element.options[0].selected = false
  803:         }
  804:     }
  805: }
  806: 
  807: function setRole(crstype) {
  808: |;
  809:     if ($role_element eq '') {
  810:         $setsections .= '    return;
  811: }
  812: ';
  813:     } else {
  814:         $setsections .= qq|
  815:     var elementLength = document.$formname.$role_element.length;
  816:     var allroles = Array($rolestr);
  817:     var courserolenames = Array($courserolestr);
  818:     var communityrolenames = Array($communityrolestr);
  819:     if (elementLength != undefined) {
  820:         if (document.$formname.$role_element.options[5].value == 'cc') {
  821:             if (crstype == 'Course') {
  822:                 return;
  823:             } else {
  824:                 allroles[5] = 'co';
  825:                 for (var i=0; i<6; i++) {
  826:                     document.$formname.$role_element.options[i].value = allroles[i];
  827:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  828:                 }
  829:             }
  830:         } else {
  831:             if (crstype == 'Community') {
  832:                 return;
  833:             } else {
  834:                 allroles[5] = 'cc';
  835:                 for (var i=0; i<6; i++) {
  836:                     document.$formname.$role_element.options[i].value = allroles[i];
  837:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  838:                 }
  839:             }
  840:         }
  841:     }
  842:     return;
  843: }
  844: |;
  845:     }
  846:     return $setsections;
  847: }
  848: 
  849: sub selectcourse_link {
  850:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  851:        $typeelement) = @_;
  852:    my $type = $selecttype;
  853:    my $linktext = &mt('Select Course');
  854:    if ($selecttype eq 'Community') {
  855:        $linktext = &mt('Select Community');
  856:    } elsif ($selecttype eq 'Course/Community') {
  857:        $linktext = &mt('Select Course/Community');
  858:        $type = '';
  859:    } elsif ($selecttype eq 'Select') {
  860:        $linktext = &mt('Select');
  861:        $type = '';
  862:    }
  863:    return '<span class="LC_nobreak">'
  864:          ."<a href='"
  865:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  866:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  867:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  868:          ."'>".$linktext.'</a>'
  869:          .'</span>';
  870: }
  871: 
  872: sub selectauthor_link {
  873:    my ($form,$udom)=@_;
  874:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  875:           &mt('Select Author').'</a>';
  876: }
  877: 
  878: sub selectuser_link {
  879:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  880:         $coursedom,$linktext,$caller) = @_;
  881:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  882:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  883:            ');">'.$linktext.'</a>';
  884: }
  885: 
  886: sub check_uncheck_jscript {
  887:     my $jscript = <<"ENDSCRT";
  888: function checkAll(field) {
  889:     if (field.length > 0) {
  890:         for (i = 0; i < field.length; i++) {
  891:             if (!field[i].disabled) { 
  892:                 field[i].checked = true;
  893:             }
  894:         }
  895:     } else {
  896:         if (!field.disabled) { 
  897:             field.checked = true;
  898:         }
  899:     }
  900: }
  901:  
  902: function uncheckAll(field) {
  903:     if (field.length > 0) {
  904:         for (i = 0; i < field.length; i++) {
  905:             field[i].checked = false ;
  906:         }
  907:     } else {
  908:         field.checked = false ;
  909:     }
  910: }
  911: ENDSCRT
  912:     return $jscript;
  913: }
  914: 
  915: sub select_timezone {
  916:    my ($name,$selected,$onchange,$includeempty)=@_;
  917:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  918:    if ($includeempty) {
  919:        $output .= '<option value=""';
  920:        if (($selected eq '') || ($selected eq 'local')) {
  921:            $output .= ' selected="selected" ';
  922:        }
  923:        $output .= '> </option>';
  924:    }
  925:    my @timezones = DateTime::TimeZone->all_names;
  926:    foreach my $tzone (@timezones) {
  927:        $output.= '<option value="'.$tzone.'"';
  928:        if ($tzone eq $selected) {
  929:            $output.=' selected="selected"';
  930:        }
  931:        $output.=">$tzone</option>\n";
  932:    }
  933:    $output.="</select>";
  934:    return $output;
  935: }
  936: 
  937: sub select_datelocale {
  938:     my ($name,$selected,$onchange,$includeempty)=@_;
  939:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  940:     if ($includeempty) {
  941:         $output .= '<option value=""';
  942:         if ($selected eq '') {
  943:             $output .= ' selected="selected" ';
  944:         }
  945:         $output .= '> </option>';
  946:     }
  947:     my (@possibles,%locale_names);
  948:     my @locales = DateTime::Locale::Catalog::Locales;
  949:     foreach my $locale (@locales) {
  950:         if (ref($locale) eq 'HASH') {
  951:             my $id = $locale->{'id'};
  952:             if ($id ne '') {
  953:                 my $en_terr = $locale->{'en_territory'};
  954:                 my $native_terr = $locale->{'native_territory'};
  955:                 my @languages = &Apache::lonlocal::preferred_languages();
  956:                 if (grep(/^en$/,@languages) || !@languages) {
  957:                     if ($en_terr ne '') {
  958:                         $locale_names{$id} = '('.$en_terr.')';
  959:                     } elsif ($native_terr ne '') {
  960:                         $locale_names{$id} = $native_terr;
  961:                     }
  962:                 } else {
  963:                     if ($native_terr ne '') {
  964:                         $locale_names{$id} = $native_terr.' ';
  965:                     } elsif ($en_terr ne '') {
  966:                         $locale_names{$id} = '('.$en_terr.')';
  967:                     }
  968:                 }
  969:                 push (@possibles,$id);
  970:             }
  971:         }
  972:     }
  973:     foreach my $item (sort(@possibles)) {
  974:         $output.= '<option value="'.$item.'"';
  975:         if ($item eq $selected) {
  976:             $output.=' selected="selected"';
  977:         }
  978:         $output.=">$item";
  979:         if ($locale_names{$item} ne '') {
  980:             $output.="  $locale_names{$item}</option>\n";
  981:         }
  982:         $output.="</option>\n";
  983:     }
  984:     $output.="</select>";
  985:     return $output;
  986: }
  987: 
  988: sub select_language {
  989:     my ($name,$selected,$includeempty) = @_;
  990:     my %langchoices;
  991:     if ($includeempty) {
  992:         %langchoices = ('' => 'No language preference');
  993:     }
  994:     foreach my $id (&languageids()) {
  995:         my $code = &supportedlanguagecode($id);
  996:         if ($code) {
  997:             $langchoices{$code} = &plainlanguagedescription($id);
  998:         }
  999:     }
 1000:     return &select_form($selected,$name,\%langchoices);
 1001: }
 1002: 
 1003: =pod
 1004: 
 1005: 
 1006: =item * &list_languages()
 1007: 
 1008: Returns an array reference that is suitable for use in language prompters.
 1009: Each array element is itself a two element array.  The first element
 1010: is the language code.  The second element a descsriptiuon of the 
 1011: language itself.  This is suitable for use in e.g.
 1012: &Apache::edit::select_arg (once dereferenced that is).
 1013: 
 1014: =cut 
 1015: 
 1016: sub list_languages {
 1017:     my @lang_choices;
 1018: 
 1019:     foreach my $id (&languageids()) {
 1020: 	my $code = &supportedlanguagecode($id);
 1021: 	if ($code) {
 1022: 	    my $selector    = $supported_codes{$id};
 1023: 	    my $description = &plainlanguagedescription($id);
 1024: 	    push (@lang_choices, [$selector, $description]);
 1025: 	}
 1026:     }
 1027:     return \@lang_choices;
 1028: }
 1029: 
 1030: =pod
 1031: 
 1032: =item * &linked_select_forms(...)
 1033: 
 1034: linked_select_forms returns a string containing a <script></script> block
 1035: and html for two <select> menus.  The select menus will be linked in that
 1036: changing the value of the first menu will result in new values being placed
 1037: in the second menu.  The values in the select menu will appear in alphabetical
 1038: order unless a defined order is provided.
 1039: 
 1040: linked_select_forms takes the following ordered inputs:
 1041: 
 1042: =over 4
 1043: 
 1044: =item * $formname, the name of the <form> tag
 1045: 
 1046: =item * $middletext, the text which appears between the <select> tags
 1047: 
 1048: =item * $firstdefault, the default value for the first menu
 1049: 
 1050: =item * $firstselectname, the name of the first <select> tag
 1051: 
 1052: =item * $secondselectname, the name of the second <select> tag
 1053: 
 1054: =item * $hashref, a reference to a hash containing the data for the menus.
 1055: 
 1056: =item * $menuorder, the order of values in the first menu
 1057: 
 1058: =back 
 1059: 
 1060: Below is an example of such a hash.  Only the 'text', 'default', and 
 1061: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1062: values for the first select menu.  The text that coincides with the 
 1063: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1064: and text for the second menu are given in the hash pointed to by 
 1065: $menu{$choice1}->{'select2'}.  
 1066: 
 1067:  my %menu = ( A1 => { text =>"Choice A1" ,
 1068:                        default => "B3",
 1069:                        select2 => { 
 1070:                            B1 => "Choice B1",
 1071:                            B2 => "Choice B2",
 1072:                            B3 => "Choice B3",
 1073:                            B4 => "Choice B4"
 1074:                            },
 1075:                        order => ['B4','B3','B1','B2'],
 1076:                    },
 1077:                A2 => { text =>"Choice A2" ,
 1078:                        default => "C2",
 1079:                        select2 => { 
 1080:                            C1 => "Choice C1",
 1081:                            C2 => "Choice C2",
 1082:                            C3 => "Choice C3"
 1083:                            },
 1084:                        order => ['C2','C1','C3'],
 1085:                    },
 1086:                A3 => { text =>"Choice A3" ,
 1087:                        default => "D6",
 1088:                        select2 => { 
 1089:                            D1 => "Choice D1",
 1090:                            D2 => "Choice D2",
 1091:                            D3 => "Choice D3",
 1092:                            D4 => "Choice D4",
 1093:                            D5 => "Choice D5",
 1094:                            D6 => "Choice D6",
 1095:                            D7 => "Choice D7"
 1096:                            },
 1097:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1098:                    }
 1099:                );
 1100: 
 1101: =cut
 1102: 
 1103: sub linked_select_forms {
 1104:     my ($formname,
 1105:         $middletext,
 1106:         $firstdefault,
 1107:         $firstselectname,
 1108:         $secondselectname, 
 1109:         $hashref,
 1110:         $menuorder,
 1111:         ) = @_;
 1112:     my $second = "document.$formname.$secondselectname";
 1113:     my $first = "document.$formname.$firstselectname";
 1114:     # output the javascript to do the changing
 1115:     my $result = '';
 1116:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1117:     $result.="// <![CDATA[\n";
 1118:     $result.="var select2data = new Object();\n";
 1119:     $" = '","';
 1120:     my $debug = '';
 1121:     foreach my $s1 (sort(keys(%$hashref))) {
 1122:         $result.="select2data.d_$s1 = new Object();\n";        
 1123:         $result.="select2data.d_$s1.def = new String('".
 1124:             $hashref->{$s1}->{'default'}."');\n";
 1125:         $result.="select2data.d_$s1.values = new Array(";
 1126:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1127:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1128:             @s2values = @{$hashref->{$s1}->{'order'}};
 1129:         }
 1130:         $result.="\"@s2values\");\n";
 1131:         $result.="select2data.d_$s1.texts = new Array(";        
 1132:         my @s2texts;
 1133:         foreach my $value (@s2values) {
 1134:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1135:         }
 1136:         $result.="\"@s2texts\");\n";
 1137:     }
 1138:     $"=' ';
 1139:     $result.= <<"END";
 1140: 
 1141: function select1_changed() {
 1142:     // Determine new choice
 1143:     var newvalue = "d_" + $first.value;
 1144:     // update select2
 1145:     var values     = select2data[newvalue].values;
 1146:     var texts      = select2data[newvalue].texts;
 1147:     var select2def = select2data[newvalue].def;
 1148:     var i;
 1149:     // out with the old
 1150:     for (i = 0; i < $second.options.length; i++) {
 1151:         $second.options[i] = null;
 1152:     }
 1153:     // in with the nuclear
 1154:     for (i=0;i<values.length; i++) {
 1155:         $second.options[i] = new Option(values[i]);
 1156:         $second.options[i].value = values[i];
 1157:         $second.options[i].text = texts[i];
 1158:         if (values[i] == select2def) {
 1159:             $second.options[i].selected = true;
 1160:         }
 1161:     }
 1162: }
 1163: // ]]>
 1164: </script>
 1165: END
 1166:     # output the initial values for the selection lists
 1167:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1168:     my @order = sort(keys(%{$hashref}));
 1169:     if (ref($menuorder) eq 'ARRAY') {
 1170:         @order = @{$menuorder};
 1171:     }
 1172:     foreach my $value (@order) {
 1173:         $result.="    <option value=\"$value\" ";
 1174:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1175:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1176:     }
 1177:     $result .= "</select>\n";
 1178:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1179:     $result .= $middletext;
 1180:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1181:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1182:     
 1183:     my @secondorder = sort(keys(%select2));
 1184:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1185:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1186:     }
 1187:     foreach my $value (@secondorder) {
 1188:         $result.="    <option value=\"$value\" ";        
 1189:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1190:         $result.=">".&mt($select2{$value})."</option>\n";
 1191:     }
 1192:     $result .= "</select>\n";
 1193:     #    return $debug;
 1194:     return $result;
 1195: }   #  end of sub linked_select_forms {
 1196: 
 1197: =pod
 1198: 
 1199: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1200: 
 1201: Returns a string corresponding to an HTML link to the given help
 1202: $topic, where $topic corresponds to the name of a .tex file in
 1203: /home/httpd/html/adm/help/tex, with underscores replaced by
 1204: spaces. 
 1205: 
 1206: $text will optionally be linked to the same topic, allowing you to
 1207: link text in addition to the graphic. If you do not want to link
 1208: text, but wish to specify one of the later parameters, pass an
 1209: empty string. 
 1210: 
 1211: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1212: the link will not open a new window. If false, the link will open
 1213: a new window using Javascript. (Default is false.) 
 1214: 
 1215: $width and $height are optional numerical parameters that will
 1216: override the width and height of the popped up window, which may
 1217: be useful for certain help topics with big pictures included.
 1218: 
 1219: $imgid is the id of the img tag used for the help icon. This may be
 1220: used in a javascript call to switch the image src.  See 
 1221: lonhtmlcommon::htmlareaselectactive() for an example.
 1222: 
 1223: =cut
 1224: 
 1225: sub help_open_topic {
 1226:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1227:     $text = "" if (not defined $text);
 1228:     $stayOnPage = 0 if (not defined $stayOnPage);
 1229:     $width = 500 if (not defined $width);
 1230:     $height = 400 if (not defined $height);
 1231:     my $filename = $topic;
 1232:     $filename =~ s/ /_/g;
 1233: 
 1234:     my $template = "";
 1235:     my $link;
 1236:     
 1237:     $topic=~s/\W/\_/g;
 1238: 
 1239:     if (!$stayOnPage) {
 1240: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1241:     } elsif ($stayOnPage eq 'popup') {
 1242:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1243:     } else {
 1244: 	$link = "/adm/help/${filename}.hlp";
 1245:     }
 1246: 
 1247:     # Add the text
 1248:     if ($text ne "") {	
 1249: 	$template.='<span class="LC_help_open_topic">'
 1250:                   .'<a target="_top" href="'.$link.'">'
 1251:                   .$text.'</a>';
 1252:     }
 1253: 
 1254:     # (Always) Add the graphic
 1255:     my $title = &mt('Online Help');
 1256:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1257:     if ($imgid ne '') {
 1258:         $imgid = ' id="'.$imgid.'"';
 1259:     }
 1260:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1261:               .'<img src="'.$helpicon.'" border="0"'
 1262:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1263:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1264:               .' /></a>';
 1265:     if ($text ne "") {	
 1266:         $template.='</span>';
 1267:     }
 1268:     return $template;
 1269: 
 1270: }
 1271: 
 1272: # This is a quicky function for Latex cheatsheet editing, since it 
 1273: # appears in at least four places
 1274: sub helpLatexCheatsheet {
 1275:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1276:     my $out;
 1277:     my $addOther = '';
 1278:     if ($topic) {
 1279: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1280:     }
 1281:     $out = '<span>' # Start cheatsheet
 1282: 	  .$addOther
 1283:           .'<span>'
 1284: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1285: 	  .'</span> <span>'
 1286: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1287: 	  .'</span>';
 1288:     unless ($not_author) {
 1289:         $out .= ' <span>'
 1290: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1291: 	       .'</span>';
 1292:     }
 1293:     $out .= '</span>'; # End cheatsheet
 1294:     return $out;
 1295: }
 1296: 
 1297: sub general_help {
 1298:     my $helptopic='Student_Intro';
 1299:     if ($env{'request.role'}=~/^(ca|au)/) {
 1300: 	$helptopic='Authoring_Intro';
 1301:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1302: 	$helptopic='Course_Coordination_Intro';
 1303:     } elsif ($env{'request.role'}=~/^dc/) {
 1304:         $helptopic='Domain_Coordination_Intro';
 1305:     }
 1306:     return $helptopic;
 1307: }
 1308: 
 1309: sub update_help_link {
 1310:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1311:     my $origurl = $ENV{'REQUEST_URI'};
 1312:     $origurl=~s|^/~|/priv/|;
 1313:     my $timestamp = time;
 1314:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1315:         $$datum = &escape($$datum);
 1316:     }
 1317: 
 1318:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
 1319:     my $output .= <<"ENDOUTPUT";
 1320: <script type="text/javascript">
 1321: // <![CDATA[
 1322: banner_link = '$banner_link';
 1323: // ]]>
 1324: </script>
 1325: ENDOUTPUT
 1326:     return $output;
 1327: }
 1328: 
 1329: # now just updates the help link and generates a blue icon
 1330: sub help_open_menu {
 1331:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1332: 	= @_;    
 1333:     $stayOnPage = 1;
 1334:     my $output;
 1335:     if ($component_help) {
 1336: 	if (!$text) {
 1337: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1338: 				       $width,$height);
 1339: 	} else {
 1340: 	    my $help_text;
 1341: 	    $help_text=&unescape($topic);
 1342: 	    $output='<table><tr><td>'.
 1343: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1344: 				 $width,$height).'</td></tr></table>';
 1345: 	}
 1346:     }
 1347:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1348:     return $output.$banner_link;
 1349: }
 1350: 
 1351: sub top_nav_help {
 1352:     my ($text) = @_;
 1353:     $text = &mt($text);
 1354:     my $stay_on_page = 1;
 1355: 
 1356:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1357: 	                     : "javascript:helpMenu('open')";
 1358:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1359: 
 1360:     my $title = &mt('Get help');
 1361: 
 1362:     return <<"END";
 1363: $banner_link
 1364:  <a href="$link" title="$title">$text</a>
 1365: END
 1366: }
 1367: 
 1368: sub help_menu_js {
 1369:     my ($text) = @_;
 1370:     my $stayOnPage = 1;
 1371:     my $width = 620;
 1372:     my $height = 600;
 1373:     my $helptopic=&general_help();
 1374:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1375:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1376:     my $start_page =
 1377:         &Apache::loncommon::start_page('Help Menu', undef,
 1378: 				       {'frameset'    => 1,
 1379: 					'js_ready'    => 1,
 1380: 					'add_entries' => {
 1381: 					    'border' => '0',
 1382: 					    'rows'   => "110,*",},});
 1383:     my $end_page =
 1384:         &Apache::loncommon::end_page({'frameset' => 1,
 1385: 				      'js_ready' => 1,});
 1386: 
 1387:     my $template .= <<"ENDTEMPLATE";
 1388: <script type="text/javascript">
 1389: // <![CDATA[
 1390: // <!-- BEGIN LON-CAPA Internal
 1391: var banner_link = '';
 1392: function helpMenu(target) {
 1393:     var caller = this;
 1394:     if (target == 'open') {
 1395:         var newWindow = null;
 1396:         try {
 1397:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1398:         }
 1399:         catch(error) {
 1400:             writeHelp(caller);
 1401:             return;
 1402:         }
 1403:         if (newWindow) {
 1404:             caller = newWindow;
 1405:         }
 1406:     }
 1407:     writeHelp(caller);
 1408:     return;
 1409: }
 1410: function writeHelp(caller) {
 1411:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
 1412:     caller.document.close()
 1413:     caller.focus()
 1414: }
 1415: // END LON-CAPA Internal -->
 1416: // ]]>
 1417: </script>
 1418: ENDTEMPLATE
 1419:     return $template;
 1420: }
 1421: 
 1422: sub help_open_bug {
 1423:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1424:     unless ($env{'user.adv'}) { return ''; }
 1425:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1426:     $text = "" if (not defined $text);
 1427: 	$stayOnPage=1;
 1428:     $width = 600 if (not defined $width);
 1429:     $height = 600 if (not defined $height);
 1430: 
 1431:     $topic=~s/\W+/\+/g;
 1432:     my $link='';
 1433:     my $template='';
 1434:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1435: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1436:     if (!$stayOnPage)
 1437:     {
 1438: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1439:     }
 1440:     else
 1441:     {
 1442: 	$link = $url;
 1443:     }
 1444:     # Add the text
 1445:     if ($text ne "")
 1446:     {
 1447: 	$template .= 
 1448:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1449:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1450:     }
 1451: 
 1452:     # Add the graphic
 1453:     my $title = &mt('Report a Bug');
 1454:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1455:     $template .= <<"ENDTEMPLATE";
 1456:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1457: ENDTEMPLATE
 1458:     if ($text ne '') { $template.='</td></tr></table>' };
 1459:     return $template;
 1460: 
 1461: }
 1462: 
 1463: sub help_open_faq {
 1464:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1465:     unless ($env{'user.adv'}) { return ''; }
 1466:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1467:     $text = "" if (not defined $text);
 1468: 	$stayOnPage=1;
 1469:     $width = 350 if (not defined $width);
 1470:     $height = 400 if (not defined $height);
 1471: 
 1472:     $topic=~s/\W+/\+/g;
 1473:     my $link='';
 1474:     my $template='';
 1475:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1476:     if (!$stayOnPage)
 1477:     {
 1478: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1479:     }
 1480:     else
 1481:     {
 1482: 	$link = $url;
 1483:     }
 1484: 
 1485:     # Add the text
 1486:     if ($text ne "")
 1487:     {
 1488: 	$template .= 
 1489:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1490:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1491:     }
 1492: 
 1493:     # Add the graphic
 1494:     my $title = &mt('View the FAQ');
 1495:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1496:     $template .= <<"ENDTEMPLATE";
 1497:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1498: ENDTEMPLATE
 1499:     if ($text ne '') { $template.='</td></tr></table>' };
 1500:     return $template;
 1501: 
 1502: }
 1503: 
 1504: ###############################################################
 1505: ###############################################################
 1506: 
 1507: =pod
 1508: 
 1509: =item * &change_content_javascript():
 1510: 
 1511: This and the next function allow you to create small sections of an
 1512: otherwise static HTML page that you can update on the fly with
 1513: Javascript, even in Netscape 4.
 1514: 
 1515: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1516: must be written to the HTML page once. It will prove the Javascript
 1517: function "change(name, content)". Calling the change function with the
 1518: name of the section 
 1519: you want to update, matching the name passed to C<changable_area>, and
 1520: the new content you want to put in there, will put the content into
 1521: that area.
 1522: 
 1523: B<Note>: Netscape 4 only reserves enough space for the changable area
 1524: to contain room for the original contents. You need to "make space"
 1525: for whatever changes you wish to make, and be B<sure> to check your
 1526: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1527: it's adequate for updating a one-line status display, but little more.
 1528: This script will set the space to 100% width, so you only need to
 1529: worry about height in Netscape 4.
 1530: 
 1531: Modern browsers are much less limiting, and if you can commit to the
 1532: user not using Netscape 4, this feature may be used freely with
 1533: pretty much any HTML.
 1534: 
 1535: =cut
 1536: 
 1537: sub change_content_javascript {
 1538:     # If we're on Netscape 4, we need to use Layer-based code
 1539:     if ($env{'browser.type'} eq 'netscape' &&
 1540: 	$env{'browser.version'} =~ /^4\./) {
 1541: 	return (<<NETSCAPE4);
 1542: 	function change(name, content) {
 1543: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1544: 	    doc.open();
 1545: 	    doc.write(content);
 1546: 	    doc.close();
 1547: 	}
 1548: NETSCAPE4
 1549:     } else {
 1550: 	# Otherwise, we need to use semi-standards-compliant code
 1551: 	# (technically, "innerHTML" isn't standard but the equivalent
 1552: 	# is really scary, and every useful browser supports it
 1553: 	return (<<DOMBASED);
 1554: 	function change(name, content) {
 1555: 	    element = document.getElementById(name);
 1556: 	    element.innerHTML = content;
 1557: 	}
 1558: DOMBASED
 1559:     }
 1560: }
 1561: 
 1562: =pod
 1563: 
 1564: =item * &changable_area($name,$origContent):
 1565: 
 1566: This provides a "changable area" that can be modified on the fly via
 1567: the Javascript code provided in C<change_content_javascript>. $name is
 1568: the name you will use to reference the area later; do not repeat the
 1569: same name on a given HTML page more then once. $origContent is what
 1570: the area will originally contain, which can be left blank.
 1571: 
 1572: =cut
 1573: 
 1574: sub changable_area {
 1575:     my ($name, $origContent) = @_;
 1576: 
 1577:     if ($env{'browser.type'} eq 'netscape' &&
 1578: 	$env{'browser.version'} =~ /^4\./) {
 1579: 	# If this is netscape 4, we need to use the Layer tag
 1580: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1581:     } else {
 1582: 	return "<span id='$name'>$origContent</span>";
 1583:     }
 1584: }
 1585: 
 1586: =pod
 1587: 
 1588: =item * &viewport_geometry_js 
 1589: 
 1590: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1591: 
 1592: =cut
 1593: 
 1594: 
 1595: sub viewport_geometry_js { 
 1596:     return <<"GEOMETRY";
 1597: var Geometry = {};
 1598: function init_geometry() {
 1599:     if (Geometry.init) { return };
 1600:     Geometry.init=1;
 1601:     if (window.innerHeight) {
 1602:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1603:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1604:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1605:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1606:     }
 1607:     else if (document.documentElement && document.documentElement.clientHeight) {
 1608:         Geometry.getViewportHeight =
 1609:             function() { return document.documentElement.clientHeight; };
 1610:         Geometry.getViewportWidth =
 1611:             function() { return document.documentElement.clientWidth; };
 1612: 
 1613:         Geometry.getHorizontalScroll =
 1614:             function() { return document.documentElement.scrollLeft; };
 1615:         Geometry.getVerticalScroll =
 1616:             function() { return document.documentElement.scrollTop; };
 1617:     }
 1618:     else if (document.body.clientHeight) {
 1619:         Geometry.getViewportHeight =
 1620:             function() { return document.body.clientHeight; };
 1621:         Geometry.getViewportWidth =
 1622:             function() { return document.body.clientWidth; };
 1623:         Geometry.getHorizontalScroll =
 1624:             function() { return document.body.scrollLeft; };
 1625:         Geometry.getVerticalScroll =
 1626:             function() { return document.body.scrollTop; };
 1627:     }
 1628: }
 1629: 
 1630: GEOMETRY
 1631: }
 1632: 
 1633: =pod
 1634: 
 1635: =item * &viewport_size_js()
 1636: 
 1637: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
 1638: 
 1639: =cut
 1640: 
 1641: sub viewport_size_js {
 1642:     my $geometry = &viewport_geometry_js();
 1643:     return <<"DIMS";
 1644: 
 1645: $geometry
 1646: 
 1647: function getViewportDims(width,height) {
 1648:     init_geometry();
 1649:     width.value = Geometry.getViewportWidth();
 1650:     height.value = Geometry.getViewportHeight();
 1651:     return;
 1652: }
 1653: 
 1654: DIMS
 1655: }
 1656: 
 1657: =pod
 1658: 
 1659: =item * &resize_textarea_js()
 1660: 
 1661: emits the needed javascript to resize a textarea to be as big as possible
 1662: 
 1663: creates a function resize_textrea that takes two IDs first should be
 1664: the id of the element to resize, second should be the id of a div that
 1665: surrounds everything that comes after the textarea, this routine needs
 1666: to be attached to the <body> for the onload and onresize events.
 1667: 
 1668: =back
 1669: 
 1670: =cut
 1671: 
 1672: sub resize_textarea_js {
 1673:     my $geometry = &viewport_geometry_js();
 1674:     return <<"RESIZE";
 1675:     <script type="text/javascript">
 1676: // <![CDATA[
 1677: $geometry
 1678: 
 1679: function getX(element) {
 1680:     var x = 0;
 1681:     while (element) {
 1682: 	x += element.offsetLeft;
 1683: 	element = element.offsetParent;
 1684:     }
 1685:     return x;
 1686: }
 1687: function getY(element) {
 1688:     var y = 0;
 1689:     while (element) {
 1690: 	y += element.offsetTop;
 1691: 	element = element.offsetParent;
 1692:     }
 1693:     return y;
 1694: }
 1695: 
 1696: 
 1697: function resize_textarea(textarea_id,bottom_id) {
 1698:     init_geometry();
 1699:     var textarea        = document.getElementById(textarea_id);
 1700:     //alert(textarea);
 1701: 
 1702:     var textarea_top    = getY(textarea);
 1703:     var textarea_height = textarea.offsetHeight;
 1704:     var bottom          = document.getElementById(bottom_id);
 1705:     var bottom_top      = getY(bottom);
 1706:     var bottom_height   = bottom.offsetHeight;
 1707:     var window_height   = Geometry.getViewportHeight();
 1708:     var fudge           = 23;
 1709:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1710:     if (new_height < 300) {
 1711: 	new_height = 300;
 1712:     }
 1713:     textarea.style.height=new_height+'px';
 1714: }
 1715: // ]]>
 1716: </script>
 1717: RESIZE
 1718: 
 1719: }
 1720: 
 1721: =pod
 1722: 
 1723: =head1 Excel and CSV file utility routines
 1724: 
 1725: =over 4
 1726: 
 1727: =cut
 1728: 
 1729: ###############################################################
 1730: ###############################################################
 1731: 
 1732: =pod
 1733: 
 1734: =item * &csv_translate($text) 
 1735: 
 1736: Translate $text to allow it to be output as a 'comma separated values' 
 1737: format.
 1738: 
 1739: =cut
 1740: 
 1741: ###############################################################
 1742: ###############################################################
 1743: sub csv_translate {
 1744:     my $text = shift;
 1745:     $text =~ s/\"/\"\"/g;
 1746:     $text =~ s/\n/ /g;
 1747:     return $text;
 1748: }
 1749: 
 1750: ###############################################################
 1751: ###############################################################
 1752: 
 1753: =pod
 1754: 
 1755: =item * &define_excel_formats()
 1756: 
 1757: Define some commonly used Excel cell formats.
 1758: 
 1759: Currently supported formats:
 1760: 
 1761: =over 4
 1762: 
 1763: =item header
 1764: 
 1765: =item bold
 1766: 
 1767: =item h1
 1768: 
 1769: =item h2
 1770: 
 1771: =item h3
 1772: 
 1773: =item h4
 1774: 
 1775: =item i
 1776: 
 1777: =item date
 1778: 
 1779: =back
 1780: 
 1781: Inputs: $workbook
 1782: 
 1783: Returns: $format, a hash reference.
 1784: 
 1785: 
 1786: =cut
 1787: 
 1788: ###############################################################
 1789: ###############################################################
 1790: sub define_excel_formats {
 1791:     my ($workbook) = @_;
 1792:     my $format;
 1793:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1794:                                                 bottom    => 1,
 1795:                                                 align     => 'center');
 1796:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1797:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1798:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1799:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1800:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1801:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1802:     $format->{'date'} = $workbook->add_format(num_format=>
 1803:                                             'mm/dd/yyyy hh:mm:ss');
 1804:     return $format;
 1805: }
 1806: 
 1807: ###############################################################
 1808: ###############################################################
 1809: 
 1810: =pod
 1811: 
 1812: =item * &create_workbook()
 1813: 
 1814: Create an Excel worksheet.  If it fails, output message on the
 1815: request object and return undefs.
 1816: 
 1817: Inputs: Apache request object
 1818: 
 1819: Returns (undef) on failure, 
 1820:     Excel worksheet object, scalar with filename, and formats 
 1821:     from &Apache::loncommon::define_excel_formats on success
 1822: 
 1823: =cut
 1824: 
 1825: ###############################################################
 1826: ###############################################################
 1827: sub create_workbook {
 1828:     my ($r) = @_;
 1829:         #
 1830:     # Create the excel spreadsheet
 1831:     my $filename = '/prtspool/'.
 1832:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1833:         time.'_'.rand(1000000000).'.xls';
 1834:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1835:     if (! defined($workbook)) {
 1836:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1837:         $r->print(
 1838:             '<p class="LC_error">'
 1839:            .&mt('Problems occurred in creating the new Excel file.')
 1840:            .' '.&mt('This error has been logged.')
 1841:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1842:            .'</p>'
 1843:         );
 1844:         return (undef);
 1845:     }
 1846:     #
 1847:     $workbook->set_tempdir(LONCAPA::tempdir());
 1848:     #
 1849:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1850:     return ($workbook,$filename,$format);
 1851: }
 1852: 
 1853: ###############################################################
 1854: ###############################################################
 1855: 
 1856: =pod
 1857: 
 1858: =item * &create_text_file()
 1859: 
 1860: Create a file to write to and eventually make available to the user.
 1861: If file creation fails, outputs an error message on the request object and 
 1862: return undefs.
 1863: 
 1864: Inputs: Apache request object, and file suffix
 1865: 
 1866: Returns (undef) on failure, 
 1867:     Filehandle and filename on success.
 1868: 
 1869: =cut
 1870: 
 1871: ###############################################################
 1872: ###############################################################
 1873: sub create_text_file {
 1874:     my ($r,$suffix) = @_;
 1875:     if (! defined($suffix)) { $suffix = 'txt'; };
 1876:     my $fh;
 1877:     my $filename = '/prtspool/'.
 1878:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1879:         time.'_'.rand(1000000000).'.'.$suffix;
 1880:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1881:     if (! defined($fh)) {
 1882:         $r->log_error("Couldn't open $filename for output $!");
 1883:         $r->print(
 1884:             '<p class="LC_error">'
 1885:            .&mt('Problems occurred in creating the output file.')
 1886:            .' '.&mt('This error has been logged.')
 1887:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1888:            .'</p>'
 1889:         );
 1890:     }
 1891:     return ($fh,$filename)
 1892: }
 1893: 
 1894: 
 1895: =pod 
 1896: 
 1897: =back
 1898: 
 1899: =cut
 1900: 
 1901: ###############################################################
 1902: ##        Home server <option> list generating code          ##
 1903: ###############################################################
 1904: 
 1905: # ------------------------------------------
 1906: 
 1907: sub domain_select {
 1908:     my ($name,$value,$multiple)=@_;
 1909:     my %domains=map { 
 1910: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1911:     } &Apache::lonnet::all_domains();
 1912:     if ($multiple) {
 1913: 	$domains{''}=&mt('Any domain');
 1914: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1915: 	return &multiple_select_form($name,$value,4,\%domains);
 1916:     } else {
 1917: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1918: 	return &select_form($name,$value,\%domains);
 1919:     }
 1920: }
 1921: 
 1922: #-------------------------------------------
 1923: 
 1924: =pod
 1925: 
 1926: =head1 Routines for form select boxes
 1927: 
 1928: =over 4
 1929: 
 1930: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1931: 
 1932: Returns a string containing a <select> element int multiple mode
 1933: 
 1934: 
 1935: Args:
 1936:   $name - name of the <select> element
 1937:   $value - scalar or array ref of values that should already be selected
 1938:   $size - number of rows long the select element is
 1939:   $hash - the elements should be 'option' => 'shown text'
 1940:           (shown text should already have been &mt())
 1941:   $order - (optional) array ref of the order to show the elements in
 1942: 
 1943: =cut
 1944: 
 1945: #-------------------------------------------
 1946: sub multiple_select_form {
 1947:     my ($name,$value,$size,$hash,$order)=@_;
 1948:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1949:     my $output='';
 1950:     if (! defined($size)) {
 1951:         $size = 4;
 1952:         if (scalar(keys(%$hash))<4) {
 1953:             $size = scalar(keys(%$hash));
 1954:         }
 1955:     }
 1956:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1957:     my @order;
 1958:     if (ref($order) eq 'ARRAY')  {
 1959:         @order = @{$order};
 1960:     } else {
 1961:         @order = sort(keys(%$hash));
 1962:     }
 1963:     if (exists($$hash{'select_form_order'})) {
 1964:         @order = @{$$hash{'select_form_order'}};
 1965:     }
 1966:         
 1967:     foreach my $key (@order) {
 1968:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1969:         $output.='selected="selected" ' if ($selected{$key});
 1970:         $output.='>'.$hash->{$key}."</option>\n";
 1971:     }
 1972:     $output.="</select>\n";
 1973:     return $output;
 1974: }
 1975: 
 1976: #-------------------------------------------
 1977: 
 1978: =pod
 1979: 
 1980: =item * &select_form($defdom,$name,$hashref,$onchange)
 1981: 
 1982: Returns a string containing a <select name='$name' size='1'> form to 
 1983: allow a user to select options from a ref to a hash containing:
 1984: option_name => displayed text. An optional $onchange can include
 1985: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1986: 
 1987: See lonrights.pm for an example invocation and use.
 1988: 
 1989: =cut
 1990: 
 1991: #-------------------------------------------
 1992: sub select_form {
 1993:     my ($def,$name,$hashref,$onchange) = @_;
 1994:     return unless (ref($hashref) eq 'HASH');
 1995:     if ($onchange) {
 1996:         $onchange = ' onchange="'.$onchange.'"';
 1997:     }
 1998:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1999:     my @keys;
 2000:     if (exists($hashref->{'select_form_order'})) {
 2001: 	@keys=@{$hashref->{'select_form_order'}};
 2002:     } else {
 2003: 	@keys=sort(keys(%{$hashref}));
 2004:     }
 2005:     foreach my $key (@keys) {
 2006:         $selectform.=
 2007: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2008:             ($key eq $def ? 'selected="selected" ' : '').
 2009:                 ">".$hashref->{$key}."</option>\n";
 2010:     }
 2011:     $selectform.="</select>";
 2012:     return $selectform;
 2013: }
 2014: 
 2015: # For display filters
 2016: 
 2017: sub display_filter {
 2018:     my ($context) = @_;
 2019:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2020:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2021:     my $phraseinput = 'hidden';
 2022:     my $includeinput = 'hidden';
 2023:     my ($checked,$includetypestext);
 2024:     if ($env{'form.displayfilter'} eq 'containing') {
 2025:         $phraseinput = 'text'; 
 2026:         if ($context eq 'parmslog') {
 2027:             $includeinput = 'checkbox';
 2028:             if ($env{'form.includetypes'}) {
 2029:                 $checked = ' checked="checked"';
 2030:             }
 2031:             $includetypestext = &mt('Include parameter types');
 2032:         }
 2033:     } else {
 2034:         $includetypestext = '&nbsp;';
 2035:     }
 2036:     my ($additional,$secondid,$thirdid);
 2037:     if ($context eq 'parmslog') {
 2038:         $additional = 
 2039:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2040:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2041:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2042:             '</label>';
 2043:         $secondid = 'includetypes';
 2044:         $thirdid = 'includetypestext';
 2045:     }
 2046:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2047:                                                     '$secondid','$thirdid')";
 2048:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2049: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2050: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2051: 	   '</label></span> <span class="LC_nobreak">'.
 2052:            &mt('Filter: [_1]',
 2053: 	   &select_form($env{'form.displayfilter'},
 2054: 			'displayfilter',
 2055: 			{'currentfolder' => 'Current folder/page',
 2056: 			 'containing' => 'Containing phrase',
 2057: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2058: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2059:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2060:                          '" />'.$additional;
 2061: }
 2062: 
 2063: sub display_filter_js {
 2064:     my $includetext = &mt('Include parameter types');
 2065:     return <<"ENDJS";
 2066:   
 2067: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2068:     var firstType = 'hidden';
 2069:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2070:         firstType = 'text';
 2071:     }
 2072:     firstObject = document.getElementById(firstid);
 2073:     if (typeof(firstObject) == 'object') {
 2074:         if (firstObject.type != firstType) {
 2075:             changeInputType(firstObject,firstType);
 2076:         }
 2077:     }
 2078:     if (context == 'parmslog') {
 2079:         var secondType = 'hidden';
 2080:         if (firstType == 'text') {
 2081:             secondType = 'checkbox';
 2082:         }
 2083:         secondObject = document.getElementById(secondid);  
 2084:         if (typeof(secondObject) == 'object') {
 2085:             if (secondObject.type != secondType) {
 2086:                 changeInputType(secondObject,secondType);
 2087:             }
 2088:         }
 2089:         var textItem = document.getElementById(thirdid);
 2090:         var currtext = textItem.innerHTML;
 2091:         var newtext;
 2092:         if (firstType == 'text') {
 2093:             newtext = '$includetext';
 2094:         } else {
 2095:             newtext = '&nbsp;';
 2096:         }
 2097:         if (currtext != newtext) {
 2098:             textItem.innerHTML = newtext;
 2099:         }
 2100:     }
 2101:     return;
 2102: }
 2103: 
 2104: function changeInputType(oldObject,newType) {
 2105:     var newObject = document.createElement('input');
 2106:     newObject.type = newType;
 2107:     if (oldObject.size) {
 2108:         newObject.size = oldObject.size;
 2109:     }
 2110:     if (oldObject.value) {
 2111:         newObject.value = oldObject.value;
 2112:     }
 2113:     if (oldObject.name) {
 2114:         newObject.name = oldObject.name;
 2115:     }
 2116:     if (oldObject.id) {
 2117:         newObject.id = oldObject.id;
 2118:     }
 2119:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2120:     return;
 2121: }
 2122: 
 2123: ENDJS
 2124: }
 2125: 
 2126: sub gradeleveldescription {
 2127:     my $gradelevel=shift;
 2128:     my %gradelevels=(0 => 'Not specified',
 2129: 		     1 => 'Grade 1',
 2130: 		     2 => 'Grade 2',
 2131: 		     3 => 'Grade 3',
 2132: 		     4 => 'Grade 4',
 2133: 		     5 => 'Grade 5',
 2134: 		     6 => 'Grade 6',
 2135: 		     7 => 'Grade 7',
 2136: 		     8 => 'Grade 8',
 2137: 		     9 => 'Grade 9',
 2138: 		     10 => 'Grade 10',
 2139: 		     11 => 'Grade 11',
 2140: 		     12 => 'Grade 12',
 2141: 		     13 => 'Grade 13',
 2142: 		     14 => '100 Level',
 2143: 		     15 => '200 Level',
 2144: 		     16 => '300 Level',
 2145: 		     17 => '400 Level',
 2146: 		     18 => 'Graduate Level');
 2147:     return &mt($gradelevels{$gradelevel});
 2148: }
 2149: 
 2150: sub select_level_form {
 2151:     my ($deflevel,$name)=@_;
 2152:     unless ($deflevel) { $deflevel=0; }
 2153:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2154:     for (my $i=0; $i<=18; $i++) {
 2155:         $selectform.="<option value=\"$i\" ".
 2156:             ($i==$deflevel ? 'selected="selected" ' : '').
 2157:                 ">".&gradeleveldescription($i)."</option>\n";
 2158:     }
 2159:     $selectform.="</select>";
 2160:     return $selectform;
 2161: }
 2162: 
 2163: #-------------------------------------------
 2164: 
 2165: =pod
 2166: 
 2167: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 2168: 
 2169: Returns a string containing a <select name='$name' size='1'> form to 
 2170: allow a user to select the domain to preform an operation in.  
 2171: See loncreateuser.pm for an example invocation and use.
 2172: 
 2173: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2174: selected");
 2175: 
 2176: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2177: 
 2178: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
 2179: 
 2180: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 2181: 
 2182: =cut
 2183: 
 2184: #-------------------------------------------
 2185: sub select_dom_form {
 2186:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 2187:     if ($onchange) {
 2188:         $onchange = ' onchange="'.$onchange.'"';
 2189:     }
 2190:     my @domains;
 2191:     if (ref($incdoms) eq 'ARRAY') {
 2192:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2193:     } else {
 2194:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2195:     }
 2196:     if ($includeempty) { @domains=('',@domains); }
 2197:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2198:     foreach my $dom (@domains) {
 2199:         $selectdomain.="<option value=\"$dom\" ".
 2200:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2201:         if ($showdomdesc) {
 2202:             if ($dom ne '') {
 2203:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2204:                 if ($domdesc ne '') {
 2205:                     $selectdomain .= ' ('.$domdesc.')';
 2206:                 }
 2207:             } 
 2208:         }
 2209:         $selectdomain .= "</option>\n";
 2210:     }
 2211:     $selectdomain.="</select>";
 2212:     return $selectdomain;
 2213: }
 2214: 
 2215: #-------------------------------------------
 2216: 
 2217: =pod
 2218: 
 2219: =item * &home_server_form_item($domain,$name,$defaultflag)
 2220: 
 2221: input: 4 arguments (two required, two optional) - 
 2222:     $domain - domain of new user
 2223:     $name - name of form element
 2224:     $default - Value of 'default' causes a default item to be first 
 2225:                             option, and selected by default. 
 2226:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2227:                             if 1 server found, or default, if 0 found.
 2228: output: returns 2 items: 
 2229: (a) form element which contains either:
 2230:    (i) <select name="$name">
 2231:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2232:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2233:        </select>
 2234:        form item if there are multiple library servers in $domain, or
 2235:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2236:        if there is only one library server in $domain.
 2237: 
 2238: (b) number of library servers found.
 2239: 
 2240: See loncreateuser.pm for example of use.
 2241: 
 2242: =cut
 2243: 
 2244: #-------------------------------------------
 2245: sub home_server_form_item {
 2246:     my ($domain,$name,$default,$hide) = @_;
 2247:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2248:     my $result;
 2249:     my $numlib = keys(%servers);
 2250:     if ($numlib > 1) {
 2251:         $result .= '<select name="'.$name.'" />'."\n";
 2252:         if ($default) {
 2253:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2254:                        '</option>'."\n";
 2255:         }
 2256:         foreach my $hostid (sort(keys(%servers))) {
 2257:             $result.= '<option value="'.$hostid.'">'.
 2258: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2259:         }
 2260:         $result .= '</select>'."\n";
 2261:     } elsif ($numlib == 1) {
 2262:         my $hostid;
 2263:         foreach my $item (keys(%servers)) {
 2264:             $hostid = $item;
 2265:         }
 2266:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2267:                    $hostid.'" />';
 2268:                    if (!$hide) {
 2269:                        $result .= $hostid.' '.$servers{$hostid};
 2270:                    }
 2271:                    $result .= "\n";
 2272:     } elsif ($default) {
 2273:         $result .= '<input type="hidden" name="'.$name.
 2274:                    '" value="default" />';
 2275:                    if (!$hide) {
 2276:                        $result .= &mt('default');
 2277:                    }
 2278:                    $result .= "\n";
 2279:     }
 2280:     return ($result,$numlib);
 2281: }
 2282: 
 2283: =pod
 2284: 
 2285: =back 
 2286: 
 2287: =cut
 2288: 
 2289: ###############################################################
 2290: ##                  Decoding User Agent                      ##
 2291: ###############################################################
 2292: 
 2293: =pod
 2294: 
 2295: =head1 Decoding the User Agent
 2296: 
 2297: =over 4
 2298: 
 2299: =item * &decode_user_agent()
 2300: 
 2301: Inputs: $r
 2302: 
 2303: Outputs:
 2304: 
 2305: =over 4
 2306: 
 2307: =item * $httpbrowser
 2308: 
 2309: =item * $clientbrowser
 2310: 
 2311: =item * $clientversion
 2312: 
 2313: =item * $clientmathml
 2314: 
 2315: =item * $clientunicode
 2316: 
 2317: =item * $clientos
 2318: 
 2319: =back
 2320: 
 2321: =back 
 2322: 
 2323: =cut
 2324: 
 2325: ###############################################################
 2326: ###############################################################
 2327: sub decode_user_agent {
 2328:     my ($r)=@_;
 2329:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2330:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2331:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2332:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2333:     my $clientbrowser='unknown';
 2334:     my $clientversion='0';
 2335:     my $clientmathml='';
 2336:     my $clientunicode='0';
 2337:     for (my $i=0;$i<=$#browsertype;$i++) {
 2338:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2339: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2340: 	    $clientbrowser=$bname;
 2341:             $httpbrowser=~/$vreg/i;
 2342: 	    $clientversion=$1;
 2343:             $clientmathml=($clientversion>=$minv);
 2344:             $clientunicode=($clientversion>=$univ);
 2345: 	}
 2346:     }
 2347:     my $clientos='unknown';
 2348:     if (($httpbrowser=~/linux/i) ||
 2349:         ($httpbrowser=~/unix/i) ||
 2350:         ($httpbrowser=~/ux/i) ||
 2351:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2352:     if (($httpbrowser=~/vax/i) ||
 2353:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2354:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2355:     if (($httpbrowser=~/mac/i) ||
 2356:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2357:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2358:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2359:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2360:             $clientunicode,$clientos,);
 2361: }
 2362: 
 2363: ###############################################################
 2364: ##    Authentication changing form generation subroutines    ##
 2365: ###############################################################
 2366: ##
 2367: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2368: ## hash, and have reasonable default values.
 2369: ##
 2370: ##    formname = the name given in the <form> tag.
 2371: #-------------------------------------------
 2372: 
 2373: =pod
 2374: 
 2375: =head1 Authentication Routines
 2376: 
 2377: =over 4
 2378: 
 2379: =item * &authform_xxxxxx()
 2380: 
 2381: The authform_xxxxxx subroutines provide javascript and html forms which 
 2382: handle some of the conveniences required for authentication forms.  
 2383: This is not an optimal method, but it works.  
 2384: 
 2385: =over 4
 2386: 
 2387: =item * authform_header
 2388: 
 2389: =item * authform_authorwarning
 2390: 
 2391: =item * authform_nochange
 2392: 
 2393: =item * authform_kerberos
 2394: 
 2395: =item * authform_internal
 2396: 
 2397: =item * authform_filesystem
 2398: 
 2399: =back
 2400: 
 2401: See loncreateuser.pm for invocation and use examples.
 2402: 
 2403: =cut
 2404: 
 2405: #-------------------------------------------
 2406: sub authform_header{  
 2407:     my %in = (
 2408:         formname => 'cu',
 2409:         kerb_def_dom => '',
 2410:         @_,
 2411:     );
 2412:     $in{'formname'} = 'document.' . $in{'formname'};
 2413:     my $result='';
 2414: 
 2415: #---------------------------------------------- Code for upper case translation
 2416:     my $Javascript_toUpperCase;
 2417:     unless ($in{kerb_def_dom}) {
 2418:         $Javascript_toUpperCase =<<"END";
 2419:         switch (choice) {
 2420:            case 'krb': currentform.elements[choicearg].value =
 2421:                currentform.elements[choicearg].value.toUpperCase();
 2422:                break;
 2423:            default:
 2424:         }
 2425: END
 2426:     } else {
 2427:         $Javascript_toUpperCase = "";
 2428:     }
 2429: 
 2430:     my $radioval = "'nochange'";
 2431:     if (defined($in{'curr_authtype'})) {
 2432:         if ($in{'curr_authtype'} ne '') {
 2433:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2434:         }
 2435:     }
 2436:     my $argfield = 'null';
 2437:     if (defined($in{'mode'})) {
 2438:         if ($in{'mode'} eq 'modifycourse')  {
 2439:             if (defined($in{'curr_autharg'})) {
 2440:                 if ($in{'curr_autharg'} ne '') {
 2441:                     $argfield = "'$in{'curr_autharg'}'";
 2442:                 }
 2443:             }
 2444:         }
 2445:     }
 2446: 
 2447:     $result.=<<"END";
 2448: var current = new Object();
 2449: current.radiovalue = $radioval;
 2450: current.argfield = $argfield;
 2451: 
 2452: function changed_radio(choice,currentform) {
 2453:     var choicearg = choice + 'arg';
 2454:     // If a radio button in changed, we need to change the argfield
 2455:     if (current.radiovalue != choice) {
 2456:         current.radiovalue = choice;
 2457:         if (current.argfield != null) {
 2458:             currentform.elements[current.argfield].value = '';
 2459:         }
 2460:         if (choice == 'nochange') {
 2461:             current.argfield = null;
 2462:         } else {
 2463:             current.argfield = choicearg;
 2464:             switch(choice) {
 2465:                 case 'krb': 
 2466:                     currentform.elements[current.argfield].value = 
 2467:                         "$in{'kerb_def_dom'}";
 2468:                 break;
 2469:               default:
 2470:                 break;
 2471:             }
 2472:         }
 2473:     }
 2474:     return;
 2475: }
 2476: 
 2477: function changed_text(choice,currentform) {
 2478:     var choicearg = choice + 'arg';
 2479:     if (currentform.elements[choicearg].value !='') {
 2480:         $Javascript_toUpperCase
 2481:         // clear old field
 2482:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2483:             currentform.elements[current.argfield].value = '';
 2484:         }
 2485:         current.argfield = choicearg;
 2486:     }
 2487:     set_auth_radio_buttons(choice,currentform);
 2488:     return;
 2489: }
 2490: 
 2491: function set_auth_radio_buttons(newvalue,currentform) {
 2492:     var numauthchoices = currentform.login.length;
 2493:     if (typeof numauthchoices  == "undefined") {
 2494:         return;
 2495:     } 
 2496:     var i=0;
 2497:     while (i < numauthchoices) {
 2498:         if (currentform.login[i].value == newvalue) { break; }
 2499:         i++;
 2500:     }
 2501:     if (i == numauthchoices) {
 2502:         return;
 2503:     }
 2504:     current.radiovalue = newvalue;
 2505:     currentform.login[i].checked = true;
 2506:     return;
 2507: }
 2508: END
 2509:     return $result;
 2510: }
 2511: 
 2512: sub authform_authorwarning{
 2513:     my $result='';
 2514:     $result='<i>'.
 2515:         &mt('As a general rule, only authors or co-authors should be '.
 2516:             'filesystem authenticated '.
 2517:             '(which allows access to the server filesystem).')."</i>\n";
 2518:     return $result;
 2519: }
 2520: 
 2521: sub authform_nochange{  
 2522:     my %in = (
 2523:               formname => 'document.cu',
 2524:               kerb_def_dom => 'MSU.EDU',
 2525:               @_,
 2526:           );
 2527:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2528:     my $result;
 2529:     if (keys(%can_assign) == 0) {
 2530:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2531:     } else {
 2532:         $result = '<label>'.&mt('[_1] Do not change login data',
 2533:                   '<input type="radio" name="login" value="nochange" '.
 2534:                   'checked="checked" onclick="'.
 2535:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2536: 	    '</label>';
 2537:     }
 2538:     return $result;
 2539: }
 2540: 
 2541: sub authform_kerberos {
 2542:     my %in = (
 2543:               formname => 'document.cu',
 2544:               kerb_def_dom => 'MSU.EDU',
 2545:               kerb_def_auth => 'krb4',
 2546:               @_,
 2547:               );
 2548:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2549:         $autharg,$jscall);
 2550:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2551:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2552:        $check5 = ' checked="checked"';
 2553:     } else {
 2554:        $check4 = ' checked="checked"';
 2555:     }
 2556:     $krbarg = $in{'kerb_def_dom'};
 2557:     if (defined($in{'curr_authtype'})) {
 2558:         if ($in{'curr_authtype'} eq 'krb') {
 2559:             $krbcheck = ' checked="checked"';
 2560:             if (defined($in{'mode'})) {
 2561:                 if ($in{'mode'} eq 'modifyuser') {
 2562:                     $krbcheck = '';
 2563:                 }
 2564:             }
 2565:             if (defined($in{'curr_kerb_ver'})) {
 2566:                 if ($in{'curr_krb_ver'} eq '5') {
 2567:                     $check5 = ' checked="checked"';
 2568:                     $check4 = '';
 2569:                 } else {
 2570:                     $check4 = ' checked="checked"';
 2571:                     $check5 = '';
 2572:                 }
 2573:             }
 2574:             if (defined($in{'curr_autharg'})) {
 2575:                 $krbarg = $in{'curr_autharg'};
 2576:             }
 2577:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2578:                 if (defined($in{'curr_autharg'})) {
 2579:                     $result = 
 2580:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2581:         $in{'curr_autharg'},$krbver);
 2582:                 } else {
 2583:                     $result =
 2584:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2585:                 }
 2586:                 return $result; 
 2587:             }
 2588:         }
 2589:     } else {
 2590:         if ($authnum == 1) {
 2591:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2592:         }
 2593:     }
 2594:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2595:         return;
 2596:     } elsif ($authtype eq '') {
 2597:         if (defined($in{'mode'})) {
 2598:             if ($in{'mode'} eq 'modifycourse') {
 2599:                 if ($authnum == 1) {
 2600:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2601:                 }
 2602:             }
 2603:         }
 2604:     }
 2605:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2606:     if ($authtype eq '') {
 2607:         $authtype = '<input type="radio" name="login" value="krb" '.
 2608:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2609:                     $krbcheck.' />';
 2610:     }
 2611:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2612:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2613:          $in{'curr_authtype'} eq 'krb5') ||
 2614:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2615:          $in{'curr_authtype'} eq 'krb4')) {
 2616:         $result .= &mt
 2617:         ('[_1] Kerberos authenticated with domain [_2] '.
 2618:          '[_3] Version 4 [_4] Version 5 [_5]',
 2619:          '<label>'.$authtype,
 2620:          '</label><input type="text" size="10" name="krbarg" '.
 2621:              'value="'.$krbarg.'" '.
 2622:              'onchange="'.$jscall.'" />',
 2623:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2624:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2625: 	 '</label>');
 2626:     } elsif ($can_assign{'krb4'}) {
 2627:         $result .= &mt
 2628:         ('[_1] Kerberos authenticated with domain [_2] '.
 2629:          '[_3] Version 4 [_4]',
 2630:          '<label>'.$authtype,
 2631:          '</label><input type="text" size="10" name="krbarg" '.
 2632:              'value="'.$krbarg.'" '.
 2633:              'onchange="'.$jscall.'" />',
 2634:          '<label><input type="hidden" name="krbver" value="4" />',
 2635:          '</label>');
 2636:     } elsif ($can_assign{'krb5'}) {
 2637:         $result .= &mt
 2638:         ('[_1] Kerberos authenticated with domain [_2] '.
 2639:          '[_3] Version 5 [_4]',
 2640:          '<label>'.$authtype,
 2641:          '</label><input type="text" size="10" name="krbarg" '.
 2642:              'value="'.$krbarg.'" '.
 2643:              'onchange="'.$jscall.'" />',
 2644:          '<label><input type="hidden" name="krbver" value="5" />',
 2645:          '</label>');
 2646:     }
 2647:     return $result;
 2648: }
 2649: 
 2650: sub authform_internal{  
 2651:     my %in = (
 2652:                 formname => 'document.cu',
 2653:                 kerb_def_dom => 'MSU.EDU',
 2654:                 @_,
 2655:                 );
 2656:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2657:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2658:     if (defined($in{'curr_authtype'})) {
 2659:         if ($in{'curr_authtype'} eq 'int') {
 2660:             if ($can_assign{'int'}) {
 2661:                 $intcheck = 'checked="checked" ';
 2662:                 if (defined($in{'mode'})) {
 2663:                     if ($in{'mode'} eq 'modifyuser') {
 2664:                         $intcheck = '';
 2665:                     }
 2666:                 }
 2667:                 if (defined($in{'curr_autharg'})) {
 2668:                     $intarg = $in{'curr_autharg'};
 2669:                 }
 2670:             } else {
 2671:                 $result = &mt('Currently internally authenticated.');
 2672:                 return $result;
 2673:             }
 2674:         }
 2675:     } else {
 2676:         if ($authnum == 1) {
 2677:             $authtype = '<input type="hidden" name="login" value="int" />';
 2678:         }
 2679:     }
 2680:     if (!$can_assign{'int'}) {
 2681:         return;
 2682:     } elsif ($authtype eq '') {
 2683:         if (defined($in{'mode'})) {
 2684:             if ($in{'mode'} eq 'modifycourse') {
 2685:                 if ($authnum == 1) {
 2686:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2687:                 }
 2688:             }
 2689:         }
 2690:     }
 2691:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2692:     if ($authtype eq '') {
 2693:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2694:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2695:     }
 2696:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2697:                $intarg.'" onchange="'.$jscall.'" />';
 2698:     $result = &mt
 2699:         ('[_1] Internally authenticated (with initial password [_2])',
 2700:          '<label>'.$authtype,'</label>'.$autharg);
 2701:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 2702:     return $result;
 2703: }
 2704: 
 2705: sub authform_local{  
 2706:     my %in = (
 2707:               formname => 'document.cu',
 2708:               kerb_def_dom => 'MSU.EDU',
 2709:               @_,
 2710:               );
 2711:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2712:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2713:     if (defined($in{'curr_authtype'})) {
 2714:         if ($in{'curr_authtype'} eq 'loc') {
 2715:             if ($can_assign{'loc'}) {
 2716:                 $loccheck = 'checked="checked" ';
 2717:                 if (defined($in{'mode'})) {
 2718:                     if ($in{'mode'} eq 'modifyuser') {
 2719:                         $loccheck = '';
 2720:                     }
 2721:                 }
 2722:                 if (defined($in{'curr_autharg'})) {
 2723:                     $locarg = $in{'curr_autharg'};
 2724:                 }
 2725:             } else {
 2726:                 $result = &mt('Currently using local (institutional) authentication.');
 2727:                 return $result;
 2728:             }
 2729:         }
 2730:     } else {
 2731:         if ($authnum == 1) {
 2732:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2733:         }
 2734:     }
 2735:     if (!$can_assign{'loc'}) {
 2736:         return;
 2737:     } elsif ($authtype eq '') {
 2738:         if (defined($in{'mode'})) {
 2739:             if ($in{'mode'} eq 'modifycourse') {
 2740:                 if ($authnum == 1) {
 2741:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2742:                 }
 2743:             }
 2744:         }
 2745:     }
 2746:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2747:     if ($authtype eq '') {
 2748:         $authtype = '<input type="radio" name="login" value="loc" '.
 2749:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2750:                     $jscall.'" />';
 2751:     }
 2752:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2753:                $locarg.'" onchange="'.$jscall.'" />';
 2754:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2755:                   '<label>'.$authtype,'</label>'.$autharg);
 2756:     return $result;
 2757: }
 2758: 
 2759: sub authform_filesystem{  
 2760:     my %in = (
 2761:               formname => 'document.cu',
 2762:               kerb_def_dom => 'MSU.EDU',
 2763:               @_,
 2764:               );
 2765:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2766:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2767:     if (defined($in{'curr_authtype'})) {
 2768:         if ($in{'curr_authtype'} eq 'fsys') {
 2769:             if ($can_assign{'fsys'}) {
 2770:                 $fsyscheck = 'checked="checked" ';
 2771:                 if (defined($in{'mode'})) {
 2772:                     if ($in{'mode'} eq 'modifyuser') {
 2773:                         $fsyscheck = '';
 2774:                     }
 2775:                 }
 2776:             } else {
 2777:                 $result = &mt('Currently Filesystem Authenticated.');
 2778:                 return $result;
 2779:             }           
 2780:         }
 2781:     } else {
 2782:         if ($authnum == 1) {
 2783:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2784:         }
 2785:     }
 2786:     if (!$can_assign{'fsys'}) {
 2787:         return;
 2788:     } elsif ($authtype eq '') {
 2789:         if (defined($in{'mode'})) {
 2790:             if ($in{'mode'} eq 'modifycourse') {
 2791:                 if ($authnum == 1) {
 2792:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2793:                 }
 2794:             }
 2795:         }
 2796:     }
 2797:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2798:     if ($authtype eq '') {
 2799:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2800:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2801:                     $jscall.'" />';
 2802:     }
 2803:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2804:                ' onchange="'.$jscall.'" />';
 2805:     $result = &mt
 2806:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2807:          '<label><input type="radio" name="login" value="fsys" '.
 2808:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2809:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2810:                   'onchange="'.$jscall.'" />');
 2811:     return $result;
 2812: }
 2813: 
 2814: sub get_assignable_auth {
 2815:     my ($dom) = @_;
 2816:     if ($dom eq '') {
 2817:         $dom = $env{'request.role.domain'};
 2818:     }
 2819:     my %can_assign = (
 2820:                           krb4 => 1,
 2821:                           krb5 => 1,
 2822:                           int  => 1,
 2823:                           loc  => 1,
 2824:                      );
 2825:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2826:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2827:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2828:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2829:             my $context;
 2830:             if ($env{'request.role'} =~ /^au/) {
 2831:                 $context = 'author';
 2832:             } elsif ($env{'request.role'} =~ /^dc/) {
 2833:                 $context = 'domain';
 2834:             } elsif ($env{'request.course.id'}) {
 2835:                 $context = 'course';
 2836:             }
 2837:             if ($context) {
 2838:                 if (ref($authhash->{$context}) eq 'HASH') {
 2839:                    %can_assign = %{$authhash->{$context}}; 
 2840:                 }
 2841:             }
 2842:         }
 2843:     }
 2844:     my $authnum = 0;
 2845:     foreach my $key (keys(%can_assign)) {
 2846:         if ($can_assign{$key}) {
 2847:             $authnum ++;
 2848:         }
 2849:     }
 2850:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2851:         $authnum --;
 2852:     }
 2853:     return ($authnum,%can_assign);
 2854: }
 2855: 
 2856: ###############################################################
 2857: ##    Get Kerberos Defaults for Domain                 ##
 2858: ###############################################################
 2859: ##
 2860: ## Returns default kerberos version and an associated argument
 2861: ## as listed in file domain.tab. If not listed, provides
 2862: ## appropriate default domain and kerberos version.
 2863: ##
 2864: #-------------------------------------------
 2865: 
 2866: =pod
 2867: 
 2868: =item * &get_kerberos_defaults()
 2869: 
 2870: get_kerberos_defaults($target_domain) returns the default kerberos
 2871: version and domain. If not found, it defaults to version 4 and the 
 2872: domain of the server.
 2873: 
 2874: =over 4
 2875: 
 2876: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2877: 
 2878: =back
 2879: 
 2880: =back
 2881: 
 2882: =cut
 2883: 
 2884: #-------------------------------------------
 2885: sub get_kerberos_defaults {
 2886:     my $domain=shift;
 2887:     my ($krbdef,$krbdefdom);
 2888:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2889:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2890:         $krbdef = $domdefaults{'auth_def'};
 2891:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2892:     } else {
 2893:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2894:         my $krbdefdom=$1;
 2895:         $krbdefdom=~tr/a-z/A-Z/;
 2896:         $krbdef = "krb4";
 2897:     }
 2898:     return ($krbdef,$krbdefdom);
 2899: }
 2900: 
 2901: 
 2902: ###############################################################
 2903: ##                Thesaurus Functions                        ##
 2904: ###############################################################
 2905: 
 2906: =pod
 2907: 
 2908: =head1 Thesaurus Functions
 2909: 
 2910: =over 4
 2911: 
 2912: =item * &initialize_keywords()
 2913: 
 2914: Initializes the package variable %Keywords if it is empty.  Uses the
 2915: package variable $thesaurus_db_file.
 2916: 
 2917: =cut
 2918: 
 2919: ###################################################
 2920: 
 2921: sub initialize_keywords {
 2922:     return 1 if (scalar keys(%Keywords));
 2923:     # If we are here, %Keywords is empty, so fill it up
 2924:     #   Make sure the file we need exists...
 2925:     if (! -e $thesaurus_db_file) {
 2926:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2927:                                  " failed because it does not exist");
 2928:         return 0;
 2929:     }
 2930:     #   Set up the hash as a database
 2931:     my %thesaurus_db;
 2932:     if (! tie(%thesaurus_db,'GDBM_File',
 2933:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2934:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2935:                                  $thesaurus_db_file);
 2936:         return 0;
 2937:     } 
 2938:     #  Get the average number of appearances of a word.
 2939:     my $avecount = $thesaurus_db{'average.count'};
 2940:     #  Put keywords (those that appear > average) into %Keywords
 2941:     while (my ($word,$data)=each (%thesaurus_db)) {
 2942:         my ($count,undef) = split /:/,$data;
 2943:         $Keywords{$word}++ if ($count > $avecount);
 2944:     }
 2945:     untie %thesaurus_db;
 2946:     # Remove special values from %Keywords.
 2947:     foreach my $value ('total.count','average.count') {
 2948:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2949:   }
 2950:     return 1;
 2951: }
 2952: 
 2953: ###################################################
 2954: 
 2955: =pod
 2956: 
 2957: =item * &keyword($word)
 2958: 
 2959: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2960: than the average number of times in the thesaurus database.  Calls 
 2961: &initialize_keywords
 2962: 
 2963: =cut
 2964: 
 2965: ###################################################
 2966: 
 2967: sub keyword {
 2968:     return if (!&initialize_keywords());
 2969:     my $word=lc(shift());
 2970:     $word=~s/\W//g;
 2971:     return exists($Keywords{$word});
 2972: }
 2973: 
 2974: ###############################################################
 2975: 
 2976: =pod 
 2977: 
 2978: =item * &get_related_words()
 2979: 
 2980: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2981: an array of words.  If the keyword is not in the thesaurus, an empty array
 2982: will be returned.  The order of the words returned is determined by the
 2983: database which holds them.
 2984: 
 2985: Uses global $thesaurus_db_file.
 2986: 
 2987: 
 2988: =cut
 2989: 
 2990: ###############################################################
 2991: sub get_related_words {
 2992:     my $keyword = shift;
 2993:     my %thesaurus_db;
 2994:     if (! -e $thesaurus_db_file) {
 2995:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2996:                                  "failed because the file does not exist");
 2997:         return ();
 2998:     }
 2999:     if (! tie(%thesaurus_db,'GDBM_File',
 3000:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3001:         return ();
 3002:     } 
 3003:     my @Words=();
 3004:     my $count=0;
 3005:     if (exists($thesaurus_db{$keyword})) {
 3006: 	# The first element is the number of times
 3007: 	# the word appears.  We do not need it now.
 3008: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3009: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3010: 	my $threshold=$mostfrequentcount/10;
 3011:         foreach my $possibleword (@RelatedWords) {
 3012:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3013:             if ($wordcount>$threshold) {
 3014: 		push(@Words,$word);
 3015:                 $count++;
 3016:                 if ($count>10) { last; }
 3017: 	    }
 3018:         }
 3019:     }
 3020:     untie %thesaurus_db;
 3021:     return @Words;
 3022: }
 3023: ###############################################################
 3024: #
 3025: #  Spell checking
 3026: #
 3027: 
 3028: =pod
 3029: 
 3030: =head1 Spell checking
 3031: 
 3032: =over 4
 3033: 
 3034: =item * &check_spelling($wordlist $language)
 3035: 
 3036: Takes a string containing words and feeds it to an external
 3037: spellcheck program via a pipeline. Returns a string containing
 3038: them mis-spelled words.
 3039: 
 3040: Parameters:
 3041: 
 3042: =over 4
 3043: 
 3044: =item - $wordlist
 3045: 
 3046: String that will be fed into the spellcheck program.
 3047: 
 3048: =item - $language
 3049: 
 3050: Language string that specifies the language for which the spell
 3051: check will be performed.
 3052: 
 3053: =back
 3054: 
 3055: =back
 3056: 
 3057: Note: This sub assumes that aspell is installed.
 3058: 
 3059: 
 3060: =cut
 3061: 
 3062: 
 3063: =pod
 3064: 
 3065: =back
 3066: 
 3067: =cut
 3068: 
 3069: sub check_spelling {
 3070:     my ($wordlist, $language) = @_;
 3071:     my @misspellings;
 3072:     
 3073:     # Generate the speller and set the langauge.
 3074:     # if explicitly selected:
 3075: 
 3076:     my $speller = Text::Aspell->new;
 3077:     if ($language) {
 3078: 	$speller->set_option('lang', $language);
 3079:     }
 3080: 
 3081:     # Turn the word list into an array of words by splittingon whitespace
 3082: 
 3083:     my @words = split(/\s+/, $wordlist);
 3084: 
 3085:     foreach my $word (@words) {
 3086: 	if(! $speller->check($word)) {
 3087: 	    push(@misspellings, $word);
 3088: 	}
 3089:     }
 3090:     return join(' ', @misspellings);
 3091:     
 3092: }
 3093: 
 3094: # -------------------------------------------------------------- Plaintext name
 3095: =pod
 3096: 
 3097: =head1 User Name Functions
 3098: 
 3099: =over 4
 3100: 
 3101: =item * &plainname($uname,$udom,$first)
 3102: 
 3103: Takes a users logon name and returns it as a string in
 3104: "first middle last generation" form 
 3105: if $first is set to 'lastname' then it returns it as
 3106: 'lastname generation, firstname middlename' if their is a lastname
 3107: 
 3108: =cut
 3109: 
 3110: 
 3111: ###############################################################
 3112: sub plainname {
 3113:     my ($uname,$udom,$first)=@_;
 3114:     return if (!defined($uname) || !defined($udom));
 3115:     my %names=&getnames($uname,$udom);
 3116:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3117: 					  $names{'middlename'},
 3118: 					  $names{'lastname'},
 3119: 					  $names{'generation'},$first);
 3120:     $name=~s/^\s+//;
 3121:     $name=~s/\s+$//;
 3122:     $name=~s/\s+/ /g;
 3123:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3124:     return $name;
 3125: }
 3126: 
 3127: # -------------------------------------------------------------------- Nickname
 3128: =pod
 3129: 
 3130: =item * &nickname($uname,$udom)
 3131: 
 3132: Gets a users name and returns it as a string as
 3133: 
 3134: "&quot;nickname&quot;"
 3135: 
 3136: if the user has a nickname or
 3137: 
 3138: "first middle last generation"
 3139: 
 3140: if the user does not
 3141: 
 3142: =cut
 3143: 
 3144: sub nickname {
 3145:     my ($uname,$udom)=@_;
 3146:     return if (!defined($uname) || !defined($udom));
 3147:     my %names=&getnames($uname,$udom);
 3148:     my $name=$names{'nickname'};
 3149:     if ($name) {
 3150:        $name='&quot;'.$name.'&quot;'; 
 3151:     } else {
 3152:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3153: 	     $names{'lastname'}.' '.$names{'generation'};
 3154:        $name=~s/\s+$//;
 3155:        $name=~s/\s+/ /g;
 3156:     }
 3157:     return $name;
 3158: }
 3159: 
 3160: sub getnames {
 3161:     my ($uname,$udom)=@_;
 3162:     return if (!defined($uname) || !defined($udom));
 3163:     if ($udom eq 'public' && $uname eq 'public') {
 3164: 	return ('lastname' => &mt('Public'));
 3165:     }
 3166:     my $id=$uname.':'.$udom;
 3167:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3168:     if ($cached) {
 3169: 	return %{$names};
 3170:     } else {
 3171: 	my %loadnames=&Apache::lonnet::get('environment',
 3172:                     ['firstname','middlename','lastname','generation','nickname'],
 3173: 					 $udom,$uname);
 3174: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3175: 	return %loadnames;
 3176:     }
 3177: }
 3178: 
 3179: # -------------------------------------------------------------------- getemails
 3180: 
 3181: =pod
 3182: 
 3183: =item * &getemails($uname,$udom)
 3184: 
 3185: Gets a user's email information and returns it as a hash with keys:
 3186: notification, critnotification, permanentemail
 3187: 
 3188: For notification and critnotification, values are comma-separated lists 
 3189: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3190:  
 3191: 
 3192: =cut
 3193: 
 3194: 
 3195: sub getemails {
 3196:     my ($uname,$udom)=@_;
 3197:     if ($udom eq 'public' && $uname eq 'public') {
 3198: 	return;
 3199:     }
 3200:     if (!$udom) { $udom=$env{'user.domain'}; }
 3201:     if (!$uname) { $uname=$env{'user.name'}; }
 3202:     my $id=$uname.':'.$udom;
 3203:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3204:     if ($cached) {
 3205: 	return %{$names};
 3206:     } else {
 3207: 	my %loadnames=&Apache::lonnet::get('environment',
 3208:                     			   ['notification','critnotification',
 3209: 					    'permanentemail'],
 3210: 					   $udom,$uname);
 3211: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3212: 	return %loadnames;
 3213:     }
 3214: }
 3215: 
 3216: sub flush_email_cache {
 3217:     my ($uname,$udom)=@_;
 3218:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3219:     if (!$uname) { $uname=$env{'user.name'};   }
 3220:     return if ($udom eq 'public' && $uname eq 'public');
 3221:     my $id=$uname.':'.$udom;
 3222:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3223: }
 3224: 
 3225: # -------------------------------------------------------------------- getlangs
 3226: 
 3227: =pod
 3228: 
 3229: =item * &getlangs($uname,$udom)
 3230: 
 3231: Gets a user's language preference and returns it as a hash with key:
 3232: language.
 3233: 
 3234: =cut
 3235: 
 3236: 
 3237: sub getlangs {
 3238:     my ($uname,$udom) = @_;
 3239:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3240:     if (!$uname) { $uname=$env{'user.name'};   }
 3241:     my $id=$uname.':'.$udom;
 3242:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3243:     if ($cached) {
 3244:         return %{$langs};
 3245:     } else {
 3246:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3247:                                            $udom,$uname);
 3248:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3249:         return %loadlangs;
 3250:     }
 3251: }
 3252: 
 3253: sub flush_langs_cache {
 3254:     my ($uname,$udom)=@_;
 3255:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3256:     if (!$uname) { $uname=$env{'user.name'};   }
 3257:     return if ($udom eq 'public' && $uname eq 'public');
 3258:     my $id=$uname.':'.$udom;
 3259:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3260: }
 3261: 
 3262: # ------------------------------------------------------------------ Screenname
 3263: 
 3264: =pod
 3265: 
 3266: =item * &screenname($uname,$udom)
 3267: 
 3268: Gets a users screenname and returns it as a string
 3269: 
 3270: =cut
 3271: 
 3272: sub screenname {
 3273:     my ($uname,$udom)=@_;
 3274:     if ($uname eq $env{'user.name'} &&
 3275: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3276:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3277:     return $names{'screenname'};
 3278: }
 3279: 
 3280: 
 3281: # ------------------------------------------------------------- Confirm Wrapper
 3282: =pod
 3283: 
 3284: =item confirmwrapper
 3285: 
 3286: Wrap messages about completion of operation in box
 3287: 
 3288: =cut
 3289: 
 3290: sub confirmwrapper {
 3291:     my ($message)=@_;
 3292:     if ($message) {
 3293:         return "\n".'<div class="LC_confirm_box">'."\n"
 3294:                .$message."\n"
 3295:                .'</div>'."\n";
 3296:     } else {
 3297:         return $message;
 3298:     }
 3299: }
 3300: 
 3301: # ------------------------------------------------------------- Message Wrapper
 3302: 
 3303: sub messagewrapper {
 3304:     my ($link,$username,$domain,$subject,$text)=@_;
 3305:     return 
 3306:         '<a href="/adm/email?compose=individual&amp;'.
 3307:         'recname='.$username.'&amp;recdom='.$domain.
 3308: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3309:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3310: }
 3311: 
 3312: # --------------------------------------------------------------- Notes Wrapper
 3313: 
 3314: sub noteswrapper {
 3315:     my ($link,$un,$do)=@_;
 3316:     return 
 3317: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3318: }
 3319: 
 3320: # ------------------------------------------------------------- Aboutme Wrapper
 3321: 
 3322: sub aboutmewrapper {
 3323:     my ($link,$username,$domain,$target,$class)=@_;
 3324:     if (!defined($username)  && !defined($domain)) {
 3325:         return;
 3326:     }
 3327:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 3328: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3329: }
 3330: 
 3331: # ------------------------------------------------------------ Syllabus Wrapper
 3332: 
 3333: sub syllabuswrapper {
 3334:     my ($linktext,$coursedir,$domain)=@_;
 3335:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3336: }
 3337: 
 3338: # -----------------------------------------------------------------------------
 3339: 
 3340: sub track_student_link {
 3341:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3342:     my $link ="/adm/trackstudent?";
 3343:     my $title = 'View recent activity';
 3344:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3345:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3346:         $link .= "selected_student=$sname:$sdom";
 3347:         $title .= ' of this student';
 3348:     } 
 3349:     if (defined($target) && $target !~ /^\s*$/) {
 3350:         $target = qq{target="$target"};
 3351:     } else {
 3352:         $target = '';
 3353:     }
 3354:     if ($start) { $link.='&amp;start='.$start; }
 3355:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3356:     $title = &mt($title);
 3357:     $linktext = &mt($linktext);
 3358:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3359: 	&help_open_topic('View_recent_activity');
 3360: }
 3361: 
 3362: sub slot_reservations_link {
 3363:     my ($linktext,$sname,$sdom,$target) = @_;
 3364:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3365:     my $title = 'View slot reservation history';
 3366:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3367:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3368:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3369:         $title .= ' of this student';
 3370:     }
 3371:     if (defined($target) && $target !~ /^\s*$/) {
 3372:         $target = qq{target="$target"};
 3373:     } else {
 3374:         $target = '';
 3375:     }
 3376:     $title = &mt($title);
 3377:     $linktext = &mt($linktext);
 3378:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3379: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3380: 
 3381: }
 3382: 
 3383: # ===================================================== Display a student photo
 3384: 
 3385: 
 3386: sub student_image_tag {
 3387:     my ($domain,$user)=@_;
 3388:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3389:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3390: 	return '<img src="'.$imgsrc.'" align="right" />';
 3391:     } else {
 3392: 	return '';
 3393:     }
 3394: }
 3395: 
 3396: =pod
 3397: 
 3398: =back
 3399: 
 3400: =head1 Access .tab File Data
 3401: 
 3402: =over 4
 3403: 
 3404: =item * &languageids() 
 3405: 
 3406: returns list of all language ids
 3407: 
 3408: =cut
 3409: 
 3410: sub languageids {
 3411:     return sort(keys(%language));
 3412: }
 3413: 
 3414: =pod
 3415: 
 3416: =item * &languagedescription() 
 3417: 
 3418: returns description of a specified language id
 3419: 
 3420: =cut
 3421: 
 3422: sub languagedescription {
 3423:     my $code=shift;
 3424:     return  ($supported_language{$code}?'* ':'').
 3425:             $language{$code}.
 3426: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3427: }
 3428: 
 3429: =pod
 3430: 
 3431: =item * &plainlanguagedescription
 3432: 
 3433: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3434: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3435: 
 3436: =cut
 3437: 
 3438: sub plainlanguagedescription {
 3439:     my $code=shift;
 3440:     return $language{$code};
 3441: }
 3442: 
 3443: =pod
 3444: 
 3445: =item * &supportedlanguagecode
 3446: 
 3447: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3448: code.
 3449: 
 3450: =cut
 3451: 
 3452: sub supportedlanguagecode {
 3453:     my $code=shift;
 3454:     return $supported_language{$code};
 3455: }
 3456: 
 3457: =pod
 3458: 
 3459: =item * &latexlanguage()
 3460: 
 3461: Given a language key code returns the correspondnig language to use
 3462: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3463: is no supported hyphenation for the language code.
 3464: 
 3465: =cut
 3466: 
 3467: sub latexlanguage {
 3468:     my $code = shift;
 3469:     return $latex_language{$code};
 3470: }
 3471: 
 3472: =pod
 3473: 
 3474: =item * &latexhyphenation()
 3475: 
 3476: Same as above but what's supplied is the language as it might be stored
 3477: in the metadata.
 3478: 
 3479: =cut
 3480: 
 3481: sub latexhyphenation {
 3482:     my $key = shift;
 3483:     return $latex_language_bykey{$key};
 3484: }
 3485: 
 3486: =pod
 3487: 
 3488: =item * &copyrightids() 
 3489: 
 3490: returns list of all copyrights
 3491: 
 3492: =cut
 3493: 
 3494: sub copyrightids {
 3495:     return sort(keys(%cprtag));
 3496: }
 3497: 
 3498: =pod
 3499: 
 3500: =item * &copyrightdescription() 
 3501: 
 3502: returns description of a specified copyright id
 3503: 
 3504: =cut
 3505: 
 3506: sub copyrightdescription {
 3507:     return &mt($cprtag{shift(@_)});
 3508: }
 3509: 
 3510: =pod
 3511: 
 3512: =item * &source_copyrightids() 
 3513: 
 3514: returns list of all source copyrights
 3515: 
 3516: =cut
 3517: 
 3518: sub source_copyrightids {
 3519:     return sort(keys(%scprtag));
 3520: }
 3521: 
 3522: =pod
 3523: 
 3524: =item * &source_copyrightdescription() 
 3525: 
 3526: returns description of a specified source copyright id
 3527: 
 3528: =cut
 3529: 
 3530: sub source_copyrightdescription {
 3531:     return &mt($scprtag{shift(@_)});
 3532: }
 3533: 
 3534: =pod
 3535: 
 3536: =item * &filecategories() 
 3537: 
 3538: returns list of all file categories
 3539: 
 3540: =cut
 3541: 
 3542: sub filecategories {
 3543:     return sort(keys(%category_extensions));
 3544: }
 3545: 
 3546: =pod
 3547: 
 3548: =item * &filecategorytypes() 
 3549: 
 3550: returns list of file types belonging to a given file
 3551: category
 3552: 
 3553: =cut
 3554: 
 3555: sub filecategorytypes {
 3556:     my ($cat) = @_;
 3557:     return @{$category_extensions{lc($cat)}};
 3558: }
 3559: 
 3560: =pod
 3561: 
 3562: =item * &fileembstyle() 
 3563: 
 3564: returns embedding style for a specified file type
 3565: 
 3566: =cut
 3567: 
 3568: sub fileembstyle {
 3569:     return $fe{lc(shift(@_))};
 3570: }
 3571: 
 3572: sub filemimetype {
 3573:     return $fm{lc(shift(@_))};
 3574: }
 3575: 
 3576: 
 3577: sub filecategoryselect {
 3578:     my ($name,$value)=@_;
 3579:     return &select_form($value,$name,
 3580:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3581: }
 3582: 
 3583: =pod
 3584: 
 3585: =item * &filedescription() 
 3586: 
 3587: returns description for a specified file type
 3588: 
 3589: =cut
 3590: 
 3591: sub filedescription {
 3592:     my $file_description = $fd{lc(shift())};
 3593:     $file_description =~ s:([\[\]]):~$1:g;
 3594:     return &mt($file_description);
 3595: }
 3596: 
 3597: =pod
 3598: 
 3599: =item * &filedescriptionex() 
 3600: 
 3601: returns description for a specified file type with
 3602: extra formatting
 3603: 
 3604: =cut
 3605: 
 3606: sub filedescriptionex {
 3607:     my $ex=shift;
 3608:     my $file_description = $fd{lc($ex)};
 3609:     $file_description =~ s:([\[\]]):~$1:g;
 3610:     return '.'.$ex.' '.&mt($file_description);
 3611: }
 3612: 
 3613: # End of .tab access
 3614: =pod
 3615: 
 3616: =back
 3617: 
 3618: =cut
 3619: 
 3620: # ------------------------------------------------------------------ File Types
 3621: sub fileextensions {
 3622:     return sort(keys(%fe));
 3623: }
 3624: 
 3625: # ----------------------------------------------------------- Display Languages
 3626: # returns a hash with all desired display languages
 3627: #
 3628: 
 3629: sub display_languages {
 3630:     my %languages=();
 3631:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3632: 	$languages{$lang}=1;
 3633:     }
 3634:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3635:     if ($env{'form.displaylanguage'}) {
 3636: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3637: 	    $languages{$lang}=1;
 3638:         }
 3639:     }
 3640:     return %languages;
 3641: }
 3642: 
 3643: sub languages {
 3644:     my ($possible_langs) = @_;
 3645:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3646:     if (!ref($possible_langs)) {
 3647: 	if( wantarray ) {
 3648: 	    return @preferred_langs;
 3649: 	} else {
 3650: 	    return $preferred_langs[0];
 3651: 	}
 3652:     }
 3653:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3654:     my @preferred_possibilities;
 3655:     foreach my $preferred_lang (@preferred_langs) {
 3656: 	if (exists($possibilities{$preferred_lang})) {
 3657: 	    push(@preferred_possibilities, $preferred_lang);
 3658: 	}
 3659:     }
 3660:     if( wantarray ) {
 3661: 	return @preferred_possibilities;
 3662:     }
 3663:     return $preferred_possibilities[0];
 3664: }
 3665: 
 3666: sub user_lang {
 3667:     my ($touname,$toudom,$fromcid) = @_;
 3668:     my @userlangs;
 3669:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3670:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3671:                     $env{'course.'.$fromcid.'.languages'}));
 3672:     } else {
 3673:         my %langhash = &getlangs($touname,$toudom);
 3674:         if ($langhash{'languages'} ne '') {
 3675:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3676:         } else {
 3677:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3678:             if ($domdefs{'lang_def'} ne '') {
 3679:                 @userlangs = ($domdefs{'lang_def'});
 3680:             }
 3681:         }
 3682:     }
 3683:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3684:     my $user_lh = Apache::localize->get_handle(@languages);
 3685:     return $user_lh;
 3686: }
 3687: 
 3688: 
 3689: ###############################################################
 3690: ##               Student Answer Attempts                     ##
 3691: ###############################################################
 3692: 
 3693: =pod
 3694: 
 3695: =head1 Alternate Problem Views
 3696: 
 3697: =over 4
 3698: 
 3699: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3700:     $getattempt, $regexp, $gradesub)
 3701: 
 3702: Return string with previous attempt on problem. Arguments:
 3703: 
 3704: =over 4
 3705: 
 3706: =item * $symb: Problem, including path
 3707: 
 3708: =item * $username: username of the desired student
 3709: 
 3710: =item * $domain: domain of the desired student
 3711: 
 3712: =item * $course: Course ID
 3713: 
 3714: =item * $getattempt: Leave blank for all attempts, otherwise put
 3715:     something
 3716: 
 3717: =item * $regexp: if string matches this regexp, the string will be
 3718:     sent to $gradesub
 3719: 
 3720: =item * $gradesub: routine that processes the string if it matches $regexp
 3721: 
 3722: =back
 3723: 
 3724: The output string is a table containing all desired attempts, if any.
 3725: 
 3726: =cut
 3727: 
 3728: sub get_previous_attempt {
 3729:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3730:   my $prevattempts='';
 3731:   no strict 'refs';
 3732:   if ($symb) {
 3733:     my (%returnhash)=
 3734:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3735:     if ($returnhash{'version'}) {
 3736:       my %lasthash=();
 3737:       my $version;
 3738:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3739:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3740: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3741:         }
 3742:       }
 3743:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3744:       $prevattempts.='<th>'.&mt('History').'</th>';
 3745:       my (%typeparts,%lasthidden);
 3746:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3747:       foreach my $key (sort(keys(%lasthash))) {
 3748: 	my ($ign,@parts) = split(/\./,$key);
 3749: 	if ($#parts > 0) {
 3750: 	  my $data=$parts[-1];
 3751:           next if ($data eq 'foilorder');
 3752: 	  pop(@parts);
 3753:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3754:           if ($data eq 'type') {
 3755:               unless ($showsurv) {
 3756:                   my $id = join(',',@parts);
 3757:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3758:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3759:                       $lasthidden{$ign.'.'.$id} = 1;
 3760:                   }
 3761:               }
 3762:           } 
 3763: 	} else {
 3764: 	  if ($#parts == 0) {
 3765: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3766: 	  } else {
 3767: 	    $prevattempts.='<th>'.$ign.'</th>';
 3768: 	  }
 3769: 	}
 3770:       }
 3771:       $prevattempts.=&end_data_table_header_row();
 3772:       if ($getattempt eq '') {
 3773: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3774:             my @hidden;
 3775:             if (%typeparts) {
 3776:                 foreach my $id (keys(%typeparts)) {
 3777:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3778:                         push(@hidden,$id);
 3779:                     }
 3780:                 }
 3781:             }
 3782:             $prevattempts.=&start_data_table_row().
 3783:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3784:             if (@hidden) {
 3785:                 foreach my $key (sort(keys(%lasthash))) {
 3786:                     next if ($key =~ /\.foilorder$/);
 3787:                     my $hide;
 3788:                     foreach my $id (@hidden) {
 3789:                         if ($key =~ /^\Q$id\E/) {
 3790:                             $hide = 1;
 3791:                             last;
 3792:                         }
 3793:                     }
 3794:                     if ($hide) {
 3795:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3796:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3797:                             my $value = &format_previous_attempt_value($key,
 3798:                                              $returnhash{$version.':'.$key});
 3799:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3800:                         } else {
 3801:                             $prevattempts.='<td>&nbsp;</td>';
 3802:                         }
 3803:                     } else {
 3804:                         if ($key =~ /\./) {
 3805:                             my $value = &format_previous_attempt_value($key,
 3806:                                               $returnhash{$version.':'.$key});
 3807:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3808:                         } else {
 3809:                             $prevattempts.='<td>&nbsp;</td>';
 3810:                         }
 3811:                     }
 3812:                 }
 3813:             } else {
 3814: 	        foreach my $key (sort(keys(%lasthash))) {
 3815:                     next if ($key =~ /\.foilorder$/);
 3816: 		    my $value = &format_previous_attempt_value($key,
 3817: 			            $returnhash{$version.':'.$key});
 3818: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3819: 	        }
 3820:             }
 3821: 	    $prevattempts.=&end_data_table_row();
 3822: 	 }
 3823:       }
 3824:       my @currhidden = keys(%lasthidden);
 3825:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3826:       foreach my $key (sort(keys(%lasthash))) {
 3827:           next if ($key =~ /\.foilorder$/);
 3828:           if (%typeparts) {
 3829:               my $hidden;
 3830:               foreach my $id (@currhidden) {
 3831:                   if ($key =~ /^\Q$id\E/) {
 3832:                       $hidden = 1;
 3833:                       last;
 3834:                   }
 3835:               }
 3836:               if ($hidden) {
 3837:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3838:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3839:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3840:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3841:                           $value = &$gradesub($value);
 3842:                       }
 3843:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3844:                   } else {
 3845:                       $prevattempts.='<td>&nbsp;</td>';
 3846:                   }
 3847:               } else {
 3848:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3849:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3850:                       $value = &$gradesub($value);
 3851:                   }
 3852:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3853:               }
 3854:           } else {
 3855: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3856: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3857:                   $value = &$gradesub($value);
 3858:               }
 3859: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3860:           }
 3861:       }
 3862:       $prevattempts.= &end_data_table_row().&end_data_table();
 3863:     } else {
 3864:       $prevattempts=
 3865: 	  &start_data_table().&start_data_table_row().
 3866: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3867: 	  &end_data_table_row().&end_data_table();
 3868:     }
 3869:   } else {
 3870:     $prevattempts=
 3871: 	  &start_data_table().&start_data_table_row().
 3872: 	  '<td>'.&mt('No data.').'</td>'.
 3873: 	  &end_data_table_row().&end_data_table();
 3874:   }
 3875: }
 3876: 
 3877: sub format_previous_attempt_value {
 3878:     my ($key,$value) = @_;
 3879:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3880: 	$value = &Apache::lonlocal::locallocaltime($value);
 3881:     } elsif (ref($value) eq 'ARRAY') {
 3882: 	$value = '('.join(', ', @{ $value }).')';
 3883:     } elsif ($key =~ /answerstring$/) {
 3884:         my %answers = &Apache::lonnet::str2hash($value);
 3885:         my @anskeys = sort(keys(%answers));
 3886:         if (@anskeys == 1) {
 3887:             my $answer = $answers{$anskeys[0]};
 3888:             if ($answer =~ m{\0}) {
 3889:                 $answer =~ s{\0}{,}g;
 3890:             }
 3891:             my $tag_internal_answer_name = 'INTERNAL';
 3892:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3893:                 $value = $answer; 
 3894:             } else {
 3895:                 $value = $anskeys[0].'='.$answer;
 3896:             }
 3897:         } else {
 3898:             foreach my $ans (@anskeys) {
 3899:                 my $answer = $answers{$ans};
 3900:                 if ($answer =~ m{\0}) {
 3901:                     $answer =~ s{\0}{,}g;
 3902:                 }
 3903:                 $value .=  $ans.'='.$answer.'<br />';;
 3904:             } 
 3905:         }
 3906:     } else {
 3907: 	$value = &unescape($value);
 3908:     }
 3909:     return $value;
 3910: }
 3911: 
 3912: 
 3913: sub relative_to_absolute {
 3914:     my ($url,$output)=@_;
 3915:     my $parser=HTML::TokeParser->new(\$output);
 3916:     my $token;
 3917:     my $thisdir=$url;
 3918:     my @rlinks=();
 3919:     while ($token=$parser->get_token) {
 3920: 	if ($token->[0] eq 'S') {
 3921: 	    if ($token->[1] eq 'a') {
 3922: 		if ($token->[2]->{'href'}) {
 3923: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3924: 		}
 3925: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3926: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3927: 	    } elsif ($token->[1] eq 'base') {
 3928: 		$thisdir=$token->[2]->{'href'};
 3929: 	    }
 3930: 	}
 3931:     }
 3932:     $thisdir=~s-/[^/]*$--;
 3933:     foreach my $link (@rlinks) {
 3934: 	unless (($link=~/^https?\:\/\//i) ||
 3935: 		($link=~/^\//) ||
 3936: 		($link=~/^javascript:/i) ||
 3937: 		($link=~/^mailto:/i) ||
 3938: 		($link=~/^\#/)) {
 3939: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3940: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3941: 	}
 3942:     }
 3943: # -------------------------------------------------- Deal with Applet codebases
 3944:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3945:     return $output;
 3946: }
 3947: 
 3948: =pod
 3949: 
 3950: =item * &get_student_view()
 3951: 
 3952: show a snapshot of what student was looking at
 3953: 
 3954: =cut
 3955: 
 3956: sub get_student_view {
 3957:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3958:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3959:   my (%form);
 3960:   my @elements=('symb','courseid','domain','username');
 3961:   foreach my $element (@elements) {
 3962:       $form{'grade_'.$element}=eval '$'.$element #'
 3963:   }
 3964:   if (defined($moreenv)) {
 3965:       %form=(%form,%{$moreenv});
 3966:   }
 3967:   if (defined($target)) { $form{'grade_target'} = $target; }
 3968:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3969:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3970:   $userview=~s/\<body[^\>]*\>//gi;
 3971:   $userview=~s/\<\/body\>//gi;
 3972:   $userview=~s/\<html\>//gi;
 3973:   $userview=~s/\<\/html\>//gi;
 3974:   $userview=~s/\<head\>//gi;
 3975:   $userview=~s/\<\/head\>//gi;
 3976:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3977:   $userview=&relative_to_absolute($feedurl,$userview);
 3978:   if (wantarray) {
 3979:      return ($userview,$response);
 3980:   } else {
 3981:      return $userview;
 3982:   }
 3983: }
 3984: 
 3985: sub get_student_view_with_retries {
 3986:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3987: 
 3988:     my $ok = 0;                 # True if we got a good response.
 3989:     my $content;
 3990:     my $response;
 3991: 
 3992:     # Try to get the student_view done. within the retries count:
 3993:     
 3994:     do {
 3995:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3996:          $ok      = $response->is_success;
 3997:          if (!$ok) {
 3998:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3999:          }
 4000:          $retries--;
 4001:     } while (!$ok && ($retries > 0));
 4002:     
 4003:     if (!$ok) {
 4004:        $content = '';          # On error return an empty content.
 4005:     }
 4006:     if (wantarray) {
 4007:        return ($content, $response);
 4008:     } else {
 4009:        return $content;
 4010:     }
 4011: }
 4012: 
 4013: =pod
 4014: 
 4015: =item * &get_student_answers() 
 4016: 
 4017: show a snapshot of how student was answering problem
 4018: 
 4019: =cut
 4020: 
 4021: sub get_student_answers {
 4022:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4023:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4024:   my (%moreenv);
 4025:   my @elements=('symb','courseid','domain','username');
 4026:   foreach my $element (@elements) {
 4027:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4028:   }
 4029:   $moreenv{'grade_target'}='answer';
 4030:   %moreenv=(%form,%moreenv);
 4031:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4032:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4033:   return $userview;
 4034: }
 4035: 
 4036: =pod
 4037: 
 4038: =item * &submlink()
 4039: 
 4040: Inputs: $text $uname $udom $symb $target
 4041: 
 4042: Returns: A link to grades.pm such as to see the SUBM view of a student
 4043: 
 4044: =cut
 4045: 
 4046: ###############################################
 4047: sub submlink {
 4048:     my ($text,$uname,$udom,$symb,$target)=@_;
 4049:     if (!($uname && $udom)) {
 4050: 	(my $cursymb, my $courseid,$udom,$uname)=
 4051: 	    &Apache::lonnet::whichuser($symb);
 4052: 	if (!$symb) { $symb=$cursymb; }
 4053:     }
 4054:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4055:     $symb=&escape($symb);
 4056:     if ($target) { $target=" target=\"$target\""; }
 4057:     return
 4058:         '<a href="/adm/grades?command=submission'.
 4059:         '&amp;symb='.$symb.
 4060:         '&amp;student='.$uname.
 4061:         '&amp;userdom='.$udom.'"'.
 4062:         $target.'>'.$text.'</a>';
 4063: }
 4064: ##############################################
 4065: 
 4066: =pod
 4067: 
 4068: =item * &pgrdlink()
 4069: 
 4070: Inputs: $text $uname $udom $symb $target
 4071: 
 4072: Returns: A link to grades.pm such as to see the PGRD view of a student
 4073: 
 4074: =cut
 4075: 
 4076: ###############################################
 4077: sub pgrdlink {
 4078:     my $link=&submlink(@_);
 4079:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4080:     return $link;
 4081: }
 4082: ##############################################
 4083: 
 4084: =pod
 4085: 
 4086: =item * &pprmlink()
 4087: 
 4088: Inputs: $text $uname $udom $symb $target
 4089: 
 4090: Returns: A link to parmset.pm such as to see the PPRM view of a
 4091: student and a specific resource
 4092: 
 4093: =cut
 4094: 
 4095: ###############################################
 4096: sub pprmlink {
 4097:     my ($text,$uname,$udom,$symb,$target)=@_;
 4098:     if (!($uname && $udom)) {
 4099: 	(my $cursymb, my $courseid,$udom,$uname)=
 4100: 	    &Apache::lonnet::whichuser($symb);
 4101: 	if (!$symb) { $symb=$cursymb; }
 4102:     }
 4103:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4104:     $symb=&escape($symb);
 4105:     if ($target) { $target="target=\"$target\""; }
 4106:     return '<a href="/adm/parmset?command=set&amp;'.
 4107: 	'symb='.$symb.'&amp;uname='.$uname.
 4108: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4109: }
 4110: ##############################################
 4111: 
 4112: =pod
 4113: 
 4114: =back
 4115: 
 4116: =cut
 4117: 
 4118: ###############################################
 4119: 
 4120: 
 4121: sub timehash {
 4122:     my ($thistime) = @_;
 4123:     my $timezone = &Apache::lonlocal::gettimezone();
 4124:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4125:                      ->set_time_zone($timezone);
 4126:     my $wday = $dt->day_of_week();
 4127:     if ($wday == 7) { $wday = 0; }
 4128:     return ( 'second' => $dt->second(),
 4129:              'minute' => $dt->minute(),
 4130:              'hour'   => $dt->hour(),
 4131:              'day'     => $dt->day_of_month(),
 4132:              'month'   => $dt->month(),
 4133:              'year'    => $dt->year(),
 4134:              'weekday' => $wday,
 4135:              'dayyear' => $dt->day_of_year(),
 4136:              'dlsav'   => $dt->is_dst() );
 4137: }
 4138: 
 4139: sub utc_string {
 4140:     my ($date)=@_;
 4141:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4142: }
 4143: 
 4144: sub maketime {
 4145:     my %th=@_;
 4146:     my ($epoch_time,$timezone,$dt);
 4147:     $timezone = &Apache::lonlocal::gettimezone();
 4148:     eval {
 4149:         $dt = DateTime->new( year   => $th{'year'},
 4150:                              month  => $th{'month'},
 4151:                              day    => $th{'day'},
 4152:                              hour   => $th{'hour'},
 4153:                              minute => $th{'minute'},
 4154:                              second => $th{'second'},
 4155:                              time_zone => $timezone,
 4156:                          );
 4157:     };
 4158:     if (!$@) {
 4159:         $epoch_time = $dt->epoch;
 4160:         if ($epoch_time) {
 4161:             return $epoch_time;
 4162:         }
 4163:     }
 4164:     return POSIX::mktime(
 4165:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4166:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4167: }
 4168: 
 4169: #########################################
 4170: 
 4171: sub findallcourses {
 4172:     my ($roles,$uname,$udom) = @_;
 4173:     my %roles;
 4174:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4175:     my %courses;
 4176:     my $now=time;
 4177:     if (!defined($uname)) {
 4178:         $uname = $env{'user.name'};
 4179:     }
 4180:     if (!defined($udom)) {
 4181:         $udom = $env{'user.domain'};
 4182:     }
 4183:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4184:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4185:         if (!%roles) {
 4186:             %roles = (
 4187:                        cc => 1,
 4188:                        co => 1,
 4189:                        in => 1,
 4190:                        ep => 1,
 4191:                        ta => 1,
 4192:                        cr => 1,
 4193:                        st => 1,
 4194:              );
 4195:         }
 4196:         foreach my $entry (keys(%roleshash)) {
 4197:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4198:             if ($trole =~ /^cr/) { 
 4199:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4200:             } else {
 4201:                 next if (!exists($roles{$trole}));
 4202:             }
 4203:             if ($tend) {
 4204:                 next if ($tend < $now);
 4205:             }
 4206:             if ($tstart) {
 4207:                 next if ($tstart > $now);
 4208:             }
 4209:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4210:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4211:             my $value = $trole.'/'.$cdom.'/';
 4212:             if ($secpart eq '') {
 4213:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4214:                 $sec = 'none';
 4215:                 $value .= $cnum.'/';
 4216:             } else {
 4217:                 $cnum = $cnumpart;
 4218:                 ($sec,$role) = split(/_/,$secpart);
 4219:                 $value .= $cnum.'/'.$sec;
 4220:             }
 4221:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4222:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4223:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4224:                 }
 4225:             } else {
 4226:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4227:             }
 4228:         }
 4229:     } else {
 4230:         foreach my $key (keys(%env)) {
 4231: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4232:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4233: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4234: 	        next if ($role eq 'ca' || $role eq 'aa');
 4235: 	        next if (%roles && !exists($roles{$role}));
 4236: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4237:                 my $active=1;
 4238:                 if ($starttime) {
 4239: 		    if ($now<$starttime) { $active=0; }
 4240:                 }
 4241:                 if ($endtime) {
 4242:                     if ($now>$endtime) { $active=0; }
 4243:                 }
 4244:                 if ($active) {
 4245:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4246:                     if ($sec eq '') {
 4247:                         $sec = 'none';
 4248:                     } else {
 4249:                         $value .= $sec;
 4250:                     }
 4251:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4252:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4253:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4254:                         }
 4255:                     } else {
 4256:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4257:                     }
 4258:                 }
 4259:             }
 4260:         }
 4261:     }
 4262:     return %courses;
 4263: }
 4264: 
 4265: ###############################################
 4266: 
 4267: sub blockcheck {
 4268:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4269: 
 4270:     if (!defined($udom)) {
 4271:         $udom = $env{'user.domain'};
 4272:     }
 4273:     if (!defined($uname)) {
 4274:         $uname = $env{'user.name'};
 4275:     }
 4276: 
 4277:     # If uname and udom are for a course, check for blocks in the course.
 4278: 
 4279:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4280:         my ($startblock,$endblock,$triggerblock) = 
 4281:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4282:         return ($startblock,$endblock,$triggerblock);
 4283:     }
 4284: 
 4285:     my $startblock = 0;
 4286:     my $endblock = 0;
 4287:     my $triggerblock = '';
 4288:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4289: 
 4290:     # If uname is for a user, and activity is course-specific, i.e.,
 4291:     # boards, chat or groups, check for blocking in current course only.
 4292: 
 4293:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4294:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4295:         foreach my $key (keys(%live_courses)) {
 4296:             if ($key ne $env{'request.course.id'}) {
 4297:                 delete($live_courses{$key});
 4298:             }
 4299:         }
 4300:     }
 4301: 
 4302:     my $otheruser = 0;
 4303:     my %own_courses;
 4304:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4305:         # Resource belongs to user other than current user.
 4306:         $otheruser = 1;
 4307:         # Gather courses for current user
 4308:         %own_courses = 
 4309:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4310:     }
 4311: 
 4312:     # Gather active course roles - course coordinator, instructor, 
 4313:     # exam proctor, ta, student, or custom role.
 4314: 
 4315:     foreach my $course (keys(%live_courses)) {
 4316:         my ($cdom,$cnum);
 4317:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4318:             $cdom = $env{'course.'.$course.'.domain'};
 4319:             $cnum = $env{'course.'.$course.'.num'};
 4320:         } else {
 4321:             ($cdom,$cnum) = split(/_/,$course); 
 4322:         }
 4323:         my $no_ownblock = 0;
 4324:         my $no_userblock = 0;
 4325:         if ($otheruser && $activity ne 'com') {
 4326:             # Check if current user has 'evb' priv for this
 4327:             if (defined($own_courses{$course})) {
 4328:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4329:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4330:                     if ($sec ne 'none') {
 4331:                         $checkrole .= '/'.$sec;
 4332:                     }
 4333:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4334:                         $no_ownblock = 1;
 4335:                         last;
 4336:                     }
 4337:                 }
 4338:             }
 4339:             # if they have 'evb' priv and are currently not playing student
 4340:             next if (($no_ownblock) &&
 4341:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4342:         }
 4343:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4344:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4345:             if ($sec ne 'none') {
 4346:                 $checkrole .= '/'.$sec;
 4347:             }
 4348:             if ($otheruser) {
 4349:                 # Resource belongs to user other than current user.
 4350:                 # Assemble privs for that user, and check for 'evb' priv.
 4351:                 my (%allroles,%userroles);
 4352:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4353:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4354:                         my ($trole,$tdom,$tnum,$tsec);
 4355:                         if ($entry =~ /^cr/) {
 4356:                             ($trole,$tdom,$tnum,$tsec) = 
 4357:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4358:                         } else {
 4359:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4360:                         }
 4361:                         my ($spec,$area,$trest);
 4362:                         $area = '/'.$tdom.'/'.$tnum;
 4363:                         $trest = $tnum;
 4364:                         if ($tsec ne '') {
 4365:                             $area .= '/'.$tsec;
 4366:                             $trest .= '/'.$tsec;
 4367:                         }
 4368:                         $spec = $trole.'.'.$area;
 4369:                         if ($trole =~ /^cr/) {
 4370:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4371:                                                               $tdom,$spec,$trest,$area);
 4372:                         } else {
 4373:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4374:                                                                 $tdom,$spec,$trest,$area);
 4375:                         }
 4376:                     }
 4377:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4378:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4379:                         if ($1) {
 4380:                             $no_userblock = 1;
 4381:                             last;
 4382:                         }
 4383:                     }
 4384:                 }
 4385:             } else {
 4386:                 # Resource belongs to current user
 4387:                 # Check for 'evb' priv via lonnet::allowed().
 4388:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4389:                     $no_ownblock = 1;
 4390:                     last;
 4391:                 }
 4392:             }
 4393:         }
 4394:         # if they have the evb priv and are currently not playing student
 4395:         next if (($no_ownblock) &&
 4396:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4397:         next if ($no_userblock);
 4398: 
 4399:         # Retrieve blocking times and identity of locker for course
 4400:         # of specified user, unless user has 'evb' privilege.
 4401:         
 4402:         my ($start,$end,$trigger) = 
 4403:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4404:         if (($start != 0) && 
 4405:             (($startblock == 0) || ($startblock > $start))) {
 4406:             $startblock = $start;
 4407:             if ($trigger ne '') {
 4408:                 $triggerblock = $trigger;
 4409:             }
 4410:         }
 4411:         if (($end != 0)  &&
 4412:             (($endblock == 0) || ($endblock < $end))) {
 4413:             $endblock = $end;
 4414:             if ($trigger ne '') {
 4415:                 $triggerblock = $trigger;
 4416:             }
 4417:         }
 4418:     }
 4419:     return ($startblock,$endblock,$triggerblock);
 4420: }
 4421: 
 4422: sub get_blocks {
 4423:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4424:     my $startblock = 0;
 4425:     my $endblock = 0;
 4426:     my $triggerblock = '';
 4427:     my $course = $cdom.'_'.$cnum;
 4428:     $setters->{$course} = {};
 4429:     $setters->{$course}{'staff'} = [];
 4430:     $setters->{$course}{'times'} = [];
 4431:     $setters->{$course}{'triggers'} = [];
 4432:     my (@blockers,%triggered);
 4433:     my $now = time;
 4434:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4435:     if ($activity eq 'docs') {
 4436:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4437:         foreach my $block (@blockers) {
 4438:             if ($block =~ /^firstaccess____(.+)$/) {
 4439:                 my $item = $1;
 4440:                 my $type = 'map';
 4441:                 my $timersymb = $item;
 4442:                 if ($item eq 'course') {
 4443:                     $type = 'course';
 4444:                 } elsif ($item =~ /___\d+___/) {
 4445:                     $type = 'resource';
 4446:                 } else {
 4447:                     $timersymb = &Apache::lonnet::symbread($item);
 4448:                 }
 4449:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4450:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4451:                 $triggered{$block} = {
 4452:                                        start => $start,
 4453:                                        end   => $end,
 4454:                                        type  => $type,
 4455:                                      };
 4456:             }
 4457:         }
 4458:     } else {
 4459:         foreach my $block (keys(%commblocks)) {
 4460:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4461:                 my ($start,$end) = ($1,$2);
 4462:                 if ($start <= time && $end >= time) {
 4463:                     if (ref($commblocks{$block}) eq 'HASH') {
 4464:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4465:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4466:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4467:                                     push(@blockers,$block);
 4468:                                 }
 4469:                             }
 4470:                         }
 4471:                     }
 4472:                 }
 4473:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4474:                 my $item = $1;
 4475:                 my $timersymb = $item; 
 4476:                 my $type = 'map';
 4477:                 if ($item eq 'course') {
 4478:                     $type = 'course';
 4479:                 } elsif ($item =~ /___\d+___/) {
 4480:                     $type = 'resource';
 4481:                 } else {
 4482:                     $timersymb = &Apache::lonnet::symbread($item);
 4483:                 }
 4484:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4485:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4486:                 if ($start && $end) {
 4487:                     if (($start <= time) && ($end >= time)) {
 4488:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4489:                             push(@blockers,$block);
 4490:                             $triggered{$block} = {
 4491:                                                    start => $start,
 4492:                                                    end   => $end,
 4493:                                                    type  => $type,
 4494:                                                  };
 4495:                         }
 4496:                     }
 4497:                 }
 4498:             }
 4499:         }
 4500:     }
 4501:     foreach my $blocker (@blockers) {
 4502:         my ($staff_name,$staff_dom,$title,$blocks) =
 4503:             &parse_block_record($commblocks{$blocker});
 4504:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4505:         my ($start,$end,$triggertype);
 4506:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4507:             ($start,$end) = ($1,$2);
 4508:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4509:             $start = $triggered{$blocker}{'start'};
 4510:             $end = $triggered{$blocker}{'end'};
 4511:             $triggertype = $triggered{$blocker}{'type'};
 4512:         }
 4513:         if ($start) {
 4514:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4515:             if ($triggertype) {
 4516:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4517:             } else {
 4518:                 push(@{$$setters{$course}{'triggers'}},0);
 4519:             }
 4520:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4521:                 $startblock = $start;
 4522:                 if ($triggertype) {
 4523:                     $triggerblock = $blocker;
 4524:                 }
 4525:             }
 4526:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4527:                $endblock = $end;
 4528:                if ($triggertype) {
 4529:                    $triggerblock = $blocker;
 4530:                }
 4531:             }
 4532:         }
 4533:     }
 4534:     return ($startblock,$endblock,$triggerblock);
 4535: }
 4536: 
 4537: sub parse_block_record {
 4538:     my ($record) = @_;
 4539:     my ($setuname,$setudom,$title,$blocks);
 4540:     if (ref($record) eq 'HASH') {
 4541:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4542:         $title = &unescape($record->{'event'});
 4543:         $blocks = $record->{'blocks'};
 4544:     } else {
 4545:         my @data = split(/:/,$record,3);
 4546:         if (scalar(@data) eq 2) {
 4547:             $title = $data[1];
 4548:             ($setuname,$setudom) = split(/@/,$data[0]);
 4549:         } else {
 4550:             ($setuname,$setudom,$title) = @data;
 4551:         }
 4552:         $blocks = { 'com' => 'on' };
 4553:     }
 4554:     return ($setuname,$setudom,$title,$blocks);
 4555: }
 4556: 
 4557: sub blocking_status {
 4558:     my ($activity,$uname,$udom,$url) = @_;
 4559:     my %setters;
 4560: 
 4561: # check for active blocking
 4562:     my ($startblock,$endblock,$triggerblock) = 
 4563:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4564:     my $blocked = 0;
 4565:     if ($startblock && $endblock) {
 4566:         $blocked = 1;
 4567:     }
 4568: 
 4569: # caller just wants to know whether a block is active
 4570:     if (!wantarray) { return $blocked; }
 4571: 
 4572: # build a link to a popup window containing the details
 4573:     my $querystring  = "?activity=$activity";
 4574: # $uname and $udom decide whose portfolio the user is trying to look at
 4575:     if ($activity eq 'port') {
 4576:         $querystring .= "&amp;udom=$udom"      if $udom;
 4577:         $querystring .= "&amp;uname=$uname"    if $uname;
 4578:     } elsif ($activity eq 'docs') {
 4579:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4580:     }
 4581: 
 4582:     my $output .= <<'END_MYBLOCK';
 4583: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4584:     var options = "width=" + w + ",height=" + h + ",";
 4585:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4586:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4587:     var newWin = window.open(url, wdwName, options);
 4588:     newWin.focus();
 4589: }
 4590: END_MYBLOCK
 4591: 
 4592:     $output = Apache::lonhtmlcommon::scripttag($output);
 4593:   
 4594:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4595:     my $text = &mt('Communication Blocked');
 4596:     if ($activity eq 'docs') {
 4597:         $text = &mt('Content Access Blocked');
 4598:     } elsif ($activity eq 'printout') {
 4599:         $text = &mt('Printing Blocked');
 4600:     }
 4601:     $output .= <<"END_BLOCK";
 4602: <div class='LC_comblock'>
 4603:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4604:   title='$text'>
 4605:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4606:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4607:   title='$text'>$text</a>
 4608: </div>
 4609: 
 4610: END_BLOCK
 4611: 
 4612:     return ($blocked, $output);
 4613: }
 4614: 
 4615: ###############################################
 4616: 
 4617: sub check_ip_acc {
 4618:     my ($acc)=@_;
 4619:     &Apache::lonxml::debug("acc is $acc");
 4620:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4621:         return 1;
 4622:     }
 4623:     my $allowed=0;
 4624:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4625: 
 4626:     my $name;
 4627:     foreach my $pattern (split(',',$acc)) {
 4628:         $pattern =~ s/^\s*//;
 4629:         $pattern =~ s/\s*$//;
 4630:         if ($pattern =~ /\*$/) {
 4631:             #35.8.*
 4632:             $pattern=~s/\*//;
 4633:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4634:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4635:             #35.8.3.[34-56]
 4636:             my $low=$2;
 4637:             my $high=$3;
 4638:             $pattern=$1;
 4639:             if ($ip =~ /^\Q$pattern\E/) {
 4640:                 my $last=(split(/\./,$ip))[3];
 4641:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4642:             }
 4643:         } elsif ($pattern =~ /^\*/) {
 4644:             #*.msu.edu
 4645:             $pattern=~s/\*//;
 4646:             if (!defined($name)) {
 4647:                 use Socket;
 4648:                 my $netaddr=inet_aton($ip);
 4649:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4650:             }
 4651:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4652:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4653:             #127.0.0.1
 4654:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4655:         } else {
 4656:             #some.name.com
 4657:             if (!defined($name)) {
 4658:                 use Socket;
 4659:                 my $netaddr=inet_aton($ip);
 4660:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4661:             }
 4662:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4663:         }
 4664:         if ($allowed) { last; }
 4665:     }
 4666:     return $allowed;
 4667: }
 4668: 
 4669: ###############################################
 4670: 
 4671: =pod
 4672: 
 4673: =head1 Domain Template Functions
 4674: 
 4675: =over 4
 4676: 
 4677: =item * &determinedomain()
 4678: 
 4679: Inputs: $domain (usually will be undef)
 4680: 
 4681: Returns: Determines which domain should be used for designs
 4682: 
 4683: =cut
 4684: 
 4685: ###############################################
 4686: sub determinedomain {
 4687:     my $domain=shift;
 4688:     if (! $domain) {
 4689:         # Determine domain if we have not been given one
 4690:         $domain = &Apache::lonnet::default_login_domain();
 4691:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4692:         if ($env{'request.role.domain'}) { 
 4693:             $domain=$env{'request.role.domain'}; 
 4694:         }
 4695:     }
 4696:     return $domain;
 4697: }
 4698: ###############################################
 4699: 
 4700: sub devalidate_domconfig_cache {
 4701:     my ($udom)=@_;
 4702:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4703: }
 4704: 
 4705: # ---------------------- Get domain configuration for a domain
 4706: sub get_domainconf {
 4707:     my ($udom) = @_;
 4708:     my $cachetime=1800;
 4709:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4710:     if (defined($cached)) { return %{$result}; }
 4711: 
 4712:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4713: 					     ['login','rolecolors','autoenroll'],$udom);
 4714:     my (%designhash,%legacy);
 4715:     if (keys(%domconfig) > 0) {
 4716:         if (ref($domconfig{'login'}) eq 'HASH') {
 4717:             if (keys(%{$domconfig{'login'}})) {
 4718:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4719:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4720:                         if ($key eq 'loginvia') {
 4721:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4722:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4723:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4724:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4725:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4726:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4727:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4728: 
 4729:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4730:                                             } else {
 4731:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4732:                                             }
 4733:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4734:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4735:                                             }
 4736:                                         }
 4737:                                     }
 4738:                                 }
 4739:                             }
 4740:                         } else {
 4741:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4742:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4743:                                     $domconfig{'login'}{$key}{$img};
 4744:                             }
 4745:                         }
 4746:                     } else {
 4747:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4748:                     }
 4749:                 }
 4750:             } else {
 4751:                 $legacy{'login'} = 1;
 4752:             }
 4753:         } else {
 4754:             $legacy{'login'} = 1;
 4755:         }
 4756:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4757:             if (keys(%{$domconfig{'rolecolors'}})) {
 4758:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4759:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4760:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4761:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4762:                         }
 4763:                     }
 4764:                 }
 4765:             } else {
 4766:                 $legacy{'rolecolors'} = 1;
 4767:             }
 4768:         } else {
 4769:             $legacy{'rolecolors'} = 1;
 4770:         }
 4771:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4772:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4773:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4774:             }
 4775:         }
 4776:         if (keys(%legacy) > 0) {
 4777:             my %legacyhash = &get_legacy_domconf($udom);
 4778:             foreach my $item (keys(%legacyhash)) {
 4779:                 if ($item =~ /^\Q$udom\E\.login/) {
 4780:                     if ($legacy{'login'}) { 
 4781:                         $designhash{$item} = $legacyhash{$item};
 4782:                     }
 4783:                 } else {
 4784:                     if ($legacy{'rolecolors'}) {
 4785:                         $designhash{$item} = $legacyhash{$item};
 4786:                     }
 4787:                 }
 4788:             }
 4789:         }
 4790:     } else {
 4791:         %designhash = &get_legacy_domconf($udom); 
 4792:     }
 4793:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4794: 				  $cachetime);
 4795:     return %designhash;
 4796: }
 4797: 
 4798: sub get_legacy_domconf {
 4799:     my ($udom) = @_;
 4800:     my %legacyhash;
 4801:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4802:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4803:     if (-e $designfile) {
 4804:         if ( open (my $fh,"<$designfile") ) {
 4805:             while (my $line = <$fh>) {
 4806:                 next if ($line =~ /^\#/);
 4807:                 chomp($line);
 4808:                 my ($key,$val)=(split(/\=/,$line));
 4809:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4810:             }
 4811:             close($fh);
 4812:         }
 4813:     }
 4814:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4815:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4816:     }
 4817:     return %legacyhash;
 4818: }
 4819: 
 4820: =pod
 4821: 
 4822: =item * &domainlogo()
 4823: 
 4824: Inputs: $domain (usually will be undef)
 4825: 
 4826: Returns: A link to a domain logo, if the domain logo exists.
 4827: If the domain logo does not exist, a description of the domain.
 4828: 
 4829: =cut
 4830: 
 4831: ###############################################
 4832: sub domainlogo {
 4833:     my $domain = &determinedomain(shift);
 4834:     my %designhash = &get_domainconf($domain);    
 4835:     # See if there is a logo
 4836:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4837:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4838:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4839: 	    if ($imgsrc =~ m{^/res/}) {
 4840: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4841: 		&Apache::lonnet::repcopy($local_name);
 4842: 	    }
 4843: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4844:         } 
 4845:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4846:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4847:         return &Apache::lonnet::domain($domain,'description');
 4848:     } else {
 4849:         return '';
 4850:     }
 4851: }
 4852: ##############################################
 4853: 
 4854: =pod
 4855: 
 4856: =item * &designparm()
 4857: 
 4858: Inputs: $which parameter; $domain (usually will be undef)
 4859: 
 4860: Returns: value of designparamter $which
 4861: 
 4862: =cut
 4863: 
 4864: 
 4865: ##############################################
 4866: sub designparm {
 4867:     my ($which,$domain)=@_;
 4868:     if (exists($env{'environment.color.'.$which})) {
 4869:         return $env{'environment.color.'.$which};
 4870:     }
 4871:     $domain=&determinedomain($domain);
 4872:     my %domdesign;
 4873:     unless ($domain eq 'public') {
 4874:         %domdesign = &get_domainconf($domain);
 4875:     }
 4876:     my $output;
 4877:     if ($domdesign{$domain.'.'.$which} ne '') {
 4878:         $output = $domdesign{$domain.'.'.$which};
 4879:     } else {
 4880:         $output = $defaultdesign{$which};
 4881:     }
 4882:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4883:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4884:         if ($output =~ m{^/(adm|res)/}) {
 4885:             if ($output =~ m{^/res/}) {
 4886:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4887:                 &Apache::lonnet::repcopy($local_name);
 4888:             }
 4889:             $output = &lonhttpdurl($output);
 4890:         }
 4891:     }
 4892:     return $output;
 4893: }
 4894: 
 4895: ##############################################
 4896: =pod
 4897: 
 4898: =item * &authorspace()
 4899: 
 4900: Inputs: $url (usually will be undef).
 4901: 
 4902: Returns: Path to Construction Space containing the resource or 
 4903:          directory being viewed (or for which action is being taken). 
 4904:          If $url is provided, and begins /priv/<domain>/<uname>
 4905:          the path will be that portion of the $context argument.
 4906:          Otherwise the path will be for the author space of the current
 4907:          user when the current role is author, or for that of the 
 4908:          co-author/assistant co-author space when the current role 
 4909:          is co-author or assistant co-author.
 4910: 
 4911: =cut
 4912: 
 4913: sub authorspace {
 4914:     my ($url) = @_;
 4915:     if ($url ne '') {
 4916:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4917:            return $1;
 4918:         }
 4919:     }
 4920:     my $caname = '';
 4921:     my $cadom = '';
 4922:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4923:         ($cadom,$caname) =
 4924:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4925:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4926:         $caname = $env{'user.name'};
 4927:         $cadom = $env{'user.domain'};
 4928:     }
 4929:     if (($caname ne '') && ($cadom ne '')) {
 4930:         return "/priv/$cadom/$caname/";
 4931:     }
 4932:     return;
 4933: }
 4934: 
 4935: ##############################################
 4936: =pod
 4937: 
 4938: =item * &head_subbox()
 4939: 
 4940: Inputs: $content (contains HTML code with page functions, etc.)
 4941: 
 4942: Returns: HTML div with $content
 4943:          To be included in page header
 4944: 
 4945: =cut
 4946: 
 4947: sub head_subbox {
 4948:     my ($content)=@_;
 4949:     my $output =
 4950:         '<div class="LC_head_subbox">'
 4951:        .$content
 4952:        .'</div>'
 4953: }
 4954: 
 4955: ##############################################
 4956: =pod
 4957: 
 4958: =item * &CSTR_pageheader()
 4959: 
 4960: Input: (optional) filename from which breadcrumb trail is built.
 4961:        In most cases no input as needed, as $env{'request.filename'}
 4962:        is appropriate for use in building the breadcrumb trail.
 4963: 
 4964: Returns: HTML div with CSTR path and recent box
 4965:          To be included on Construction Space pages
 4966: 
 4967: =cut
 4968: 
 4969: sub CSTR_pageheader {
 4970:     my ($trailfile) = @_;
 4971:     if ($trailfile eq '') {
 4972:         $trailfile = $env{'request.filename'};
 4973:     }
 4974: 
 4975: # this is for resources; directories have customtitle, and crumbs
 4976: # and select recent are created in lonpubdir.pm
 4977: 
 4978:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4979:     my ($udom,$uname,$thisdisfn)=
 4980:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
 4981:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4982:     $formaction =~ s{/+}{/}g;
 4983: 
 4984:     my $parentpath = '';
 4985:     my $lastitem = '';
 4986:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4987:         $parentpath = $1;
 4988:         $lastitem = $2;
 4989:     } else {
 4990:         $lastitem = $thisdisfn;
 4991:     }
 4992: 
 4993:     my $output =
 4994:          '<div>'
 4995:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4996:         .'<b>'.&mt('Construction Space:').'</b> '
 4997:         .'<form name="dirs" method="post" action="'.$formaction
 4998:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4999:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5000: 
 5001:     if ($lastitem) {
 5002:         $output .=
 5003:              '<span class="LC_filename">'
 5004:             .$lastitem
 5005:             .'</span>';
 5006:     }
 5007:     $output .=
 5008:          '<br />'
 5009:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5010:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5011:         .'</form>'
 5012:         .&Apache::lonmenu::constspaceform()
 5013:         .'</div>';
 5014: 
 5015:     return $output;
 5016: }
 5017: 
 5018: ###############################################
 5019: ###############################################
 5020: 
 5021: =pod
 5022: 
 5023: =back
 5024: 
 5025: =head1 HTML Helpers
 5026: 
 5027: =over 4
 5028: 
 5029: =item * &bodytag()
 5030: 
 5031: Returns a uniform header for LON-CAPA web pages.
 5032: 
 5033: Inputs: 
 5034: 
 5035: =over 4
 5036: 
 5037: =item * $title, A title to be displayed on the page.
 5038: 
 5039: =item * $function, the current role (can be undef).
 5040: 
 5041: =item * $addentries, extra parameters for the <body> tag.
 5042: 
 5043: =item * $bodyonly, if defined, only return the <body> tag.
 5044: 
 5045: =item * $domain, if defined, force a given domain.
 5046: 
 5047: =item * $forcereg, if page should register as content page (relevant for 
 5048:             text interface only)
 5049: 
 5050: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5051:                      navigational links
 5052: 
 5053: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5054: 
 5055: =item * $args, optional argument valid values are
 5056:             no_auto_mt_title -> prevents &mt()ing the title arg
 5057:             inherit_jsmath -> when creating popup window in a page,
 5058:                               should it have jsmath forced on by the
 5059:                               current page
 5060: 
 5061: =back
 5062: 
 5063: Returns: A uniform header for LON-CAPA web pages.  
 5064: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5065: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5066: other decorations will be returned.
 5067: 
 5068: =cut
 5069: 
 5070: sub bodytag {
 5071:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5072:         $no_nav_bar,$bgcolor,$args)=@_;
 5073: 
 5074:     my $public;
 5075:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5076:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5077:         $public = 1;
 5078:     }
 5079:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5080: 
 5081:     $function = &get_users_function() if (!$function);
 5082:     my $img =    &designparm($function.'.img',$domain);
 5083:     my $font =   &designparm($function.'.font',$domain);
 5084:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5085: 
 5086:     my %design = ( 'style'   => 'margin-top: 0',
 5087: 		   'bgcolor' => $pgbg,
 5088: 		   'text'    => $font,
 5089:                    'alink'   => &designparm($function.'.alink',$domain),
 5090: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5091: 		   'link'    => &designparm($function.'.link',$domain),);
 5092:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5093: 
 5094:  # role and realm
 5095:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 5096:     if ($role  eq 'ca') {
 5097:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5098:         $realm = &plainname($rname,$rdom);
 5099:     } 
 5100: # realm
 5101:     if ($env{'request.course.id'}) {
 5102:         if ($env{'request.role'} !~ /^cr/) {
 5103:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5104:         }
 5105:         if ($env{'request.course.sec'}) {
 5106:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5107:         }   
 5108: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5109:     } else {
 5110:         $role = &Apache::lonnet::plaintext($role);
 5111:     }
 5112: 
 5113:     if (!$realm) { $realm='&nbsp;'; }
 5114: 
 5115:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5116: 
 5117: # construct main body tag
 5118:     my $bodytag = "<body $extra_body_attr>".
 5119: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5120: 
 5121:     if ($bodyonly) {
 5122:         return $bodytag;
 5123:     } 
 5124: 
 5125:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5126:     if ($public) {
 5127: 	undef($role);
 5128:     } else {
 5129: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5130:                                 undef,'LC_menubuttons_link');
 5131:     }
 5132:     
 5133:     my $titleinfo = '<h1>'.$title.'</h1>';
 5134:     #
 5135:     # Extra info if you are the DC
 5136:     my $dc_info = '';
 5137:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5138:                         $env{'course.'.$env{'request.course.id'}.
 5139:                                  '.domain'}.'/'})) {
 5140:         my $cid = $env{'request.course.id'};
 5141:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5142:         $dc_info =~ s/\s+$//;
 5143:     }
 5144: 
 5145:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5146:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5147: 
 5148:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 5149:             return $bodytag; 
 5150:         } 
 5151: 
 5152:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5153: 
 5154:         #    if ($env{'request.state'} eq 'construct') {
 5155:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5156:         #    }
 5157: 
 5158: 
 5159: 
 5160:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5161:              if ($dc_info) {
 5162:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5163:              }
 5164:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 5165:                 <em>$realm</em> $dc_info</div>|;
 5166:             return $bodytag;
 5167:         }
 5168: 
 5169:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5170:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 5171:         }
 5172: 
 5173:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5174:             Apache::lonmenu::utilityfunctions(), 'start');
 5175: 
 5176:         $bodytag .= Apache::lonmenu::primary_menu();
 5177: 
 5178:         if ($dc_info) {
 5179:             $dc_info = &dc_courseid_toggle($dc_info);
 5180:         }
 5181:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5182: 
 5183:         #don't show menus for public users
 5184:         if (!$public){
 5185:             $bodytag .= Apache::lonmenu::secondary_menu();
 5186:             $bodytag .= Apache::lonmenu::serverform();
 5187:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5188:             if ($env{'request.state'} eq 'construct') {
 5189:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5190:                                 $args->{'bread_crumbs'});
 5191:             } elsif ($forcereg) { 
 5192:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
 5193:             }
 5194:         }else{
 5195:             # this is to seperate menu from content when there's no secondary
 5196:             # menu. Especially needed for public accessible ressources.
 5197:             $bodytag .= '<hr style="clear:both" />';
 5198:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5199:         }
 5200: 
 5201:         return $bodytag;
 5202: }
 5203: 
 5204: sub dc_courseid_toggle {
 5205:     my ($dc_info) = @_;
 5206:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5207:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5208:            &mt('(More ...)').'</a></span>'.
 5209:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5210: }
 5211: 
 5212: sub make_attr_string {
 5213:     my ($register,$attr_ref) = @_;
 5214: 
 5215:     if ($attr_ref && !ref($attr_ref)) {
 5216: 	die("addentries Must be a hash ref ".
 5217: 	    join(':',caller(1))." ".
 5218: 	    join(':',caller(0))." ");
 5219:     }
 5220: 
 5221:     if ($register) {
 5222: 	my ($on_load,$on_unload);
 5223: 	foreach my $key (keys(%{$attr_ref})) {
 5224: 	    if      (lc($key) eq 'onload') {
 5225: 		$on_load.=$attr_ref->{$key}.';';
 5226: 		delete($attr_ref->{$key});
 5227: 
 5228: 	    } elsif (lc($key) eq 'onunload') {
 5229: 		$on_unload.=$attr_ref->{$key}.';';
 5230: 		delete($attr_ref->{$key});
 5231: 	    }
 5232: 	}
 5233: 	$attr_ref->{'onload'}  = $on_load;
 5234: 	$attr_ref->{'onunload'}= $on_unload;
 5235:     }
 5236: 
 5237:     my $attr_string;
 5238:     foreach my $attr (keys(%$attr_ref)) {
 5239: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5240:     }
 5241:     return $attr_string;
 5242: }
 5243: 
 5244: 
 5245: ###############################################
 5246: ###############################################
 5247: 
 5248: =pod
 5249: 
 5250: =item * &endbodytag()
 5251: 
 5252: Returns a uniform footer for LON-CAPA web pages.
 5253: 
 5254: Inputs: 1 - optional reference to an args hash
 5255: If in the hash, key for noredirectlink has a value which evaluates to true,
 5256: a 'Continue' link is not displayed if the page contains an
 5257: internal redirect in the <head></head> section,
 5258: i.e., $env{'internal.head.redirect'} exists   
 5259: 
 5260: =cut
 5261: 
 5262: sub endbodytag {
 5263:     my ($args) = @_;
 5264:     my $endbodytag;
 5265:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5266:         $endbodytag='</body>';
 5267:     }
 5268:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5269:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5270:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5271: 	    $endbodytag=
 5272: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5273: 	        &mt('Continue').'</a>'.
 5274: 	        $endbodytag;
 5275:         }
 5276:     }
 5277:     return $endbodytag;
 5278: }
 5279: 
 5280: =pod
 5281: 
 5282: =item * &standard_css()
 5283: 
 5284: Returns a style sheet
 5285: 
 5286: Inputs: (all optional)
 5287:             domain         -> force to color decorate a page for a specific
 5288:                                domain
 5289:             function       -> force usage of a specific rolish color scheme
 5290:             bgcolor        -> override the default page bgcolor
 5291: 
 5292: =cut
 5293: 
 5294: sub standard_css {
 5295:     my ($function,$domain,$bgcolor) = @_;
 5296:     $function  = &get_users_function() if (!$function);
 5297:     my $img    = &designparm($function.'.img',   $domain);
 5298:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5299:     my $font   = &designparm($function.'.font',  $domain);
 5300:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5301: #second colour for later usage
 5302:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5303:     my $pgbg_or_bgcolor =
 5304: 	         $bgcolor ||
 5305: 	         &designparm($function.'.pgbg',  $domain);
 5306:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5307:     my $alink  = &designparm($function.'.alink', $domain);
 5308:     my $vlink  = &designparm($function.'.vlink', $domain);
 5309:     my $link   = &designparm($function.'.link',  $domain);
 5310: 
 5311:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5312:     my $mono                 = 'monospace';
 5313:     my $data_table_head      = $sidebg;
 5314:     my $data_table_light     = '#FAFAFA';
 5315:     my $data_table_dark      = '#E0E0E0';
 5316:     my $data_table_darker    = '#CCCCCC';
 5317:     my $data_table_highlight = '#FFFF00';
 5318:     my $mail_new             = '#FFBB77';
 5319:     my $mail_new_hover       = '#DD9955';
 5320:     my $mail_read            = '#BBBB77';
 5321:     my $mail_read_hover      = '#999944';
 5322:     my $mail_replied         = '#AAAA88';
 5323:     my $mail_replied_hover   = '#888855';
 5324:     my $mail_other           = '#99BBBB';
 5325:     my $mail_other_hover     = '#669999';
 5326:     my $table_header         = '#DDDDDD';
 5327:     my $feedback_link_bg     = '#BBBBBB';
 5328:     my $lg_border_color      = '#C8C8C8';
 5329:     my $button_hover         = '#BF2317';
 5330: 
 5331:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5332:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5333:                                              : '0 3px 0 4px';
 5334: 
 5335: 
 5336:     return <<END;
 5337: 
 5338: /* needed for iframe to allow 100% height in FF */
 5339: body, html { 
 5340:     margin: 0;
 5341:     padding: 0 0.5%;
 5342:     height: 99%; /* to avoid scrollbars */
 5343: }
 5344: 
 5345: body {
 5346:   font-family: $sans;
 5347:   line-height:130%;
 5348:   font-size:0.83em;
 5349:   color:$font;
 5350: }
 5351: 
 5352: a:focus,
 5353: a:focus img {
 5354:   color: red;
 5355: }
 5356: 
 5357: form, .inline {
 5358:   display: inline;
 5359: }
 5360: 
 5361: .LC_right {
 5362:   text-align:right;
 5363: }
 5364: 
 5365: .LC_middle {
 5366:   vertical-align:middle;
 5367: }
 5368: 
 5369: .LC_400Box {
 5370:   width:400px;
 5371: }
 5372: 
 5373: .LC_iframecontainer {
 5374:     width: 98%;
 5375:     margin: 0;
 5376:     position: fixed;
 5377:     top: 8.5em;
 5378:     bottom: 0;
 5379: }
 5380: 
 5381: .LC_iframecontainer iframe{
 5382:     border: none;
 5383:     width: 100%;
 5384:     height: 100%;
 5385: }
 5386: 
 5387: .LC_filename {
 5388:   font-family: $mono;
 5389:   white-space:pre;
 5390:   font-size: 120%;
 5391: }
 5392: 
 5393: .LC_fileicon {
 5394:   border: none;
 5395:   height: 1.3em;
 5396:   vertical-align: text-bottom;
 5397:   margin-right: 0.3em;
 5398:   text-decoration:none;
 5399: }
 5400: 
 5401: .LC_setting {
 5402:   text-decoration:underline;
 5403: }
 5404: 
 5405: .LC_error {
 5406:   color: red;
 5407:   font-size: larger;
 5408: }
 5409: 
 5410: .LC_warning,
 5411: .LC_diff_removed {
 5412:   color: red;
 5413: }
 5414: 
 5415: .LC_info,
 5416: .LC_success,
 5417: .LC_diff_added {
 5418:   color: green;
 5419: }
 5420: 
 5421: div.LC_confirm_box {
 5422:   background-color: #FAFAFA;
 5423:   border: 1px solid $lg_border_color;
 5424:   margin-right: 0;
 5425:   padding: 5px;
 5426: }
 5427: 
 5428: div.LC_confirm_box .LC_error img,
 5429: div.LC_confirm_box .LC_success img {
 5430:   vertical-align: middle;
 5431: }
 5432: 
 5433: .LC_icon {
 5434:   border: none;
 5435:   vertical-align: middle;
 5436: }
 5437: 
 5438: .LC_docs_spacer {
 5439:   width: 25px;
 5440:   height: 1px;
 5441:   border: none;
 5442: }
 5443: 
 5444: .LC_internal_info {
 5445:   color: #999999;
 5446: }
 5447: 
 5448: .LC_discussion {
 5449:   background: $data_table_dark;
 5450:   border: 1px solid black;
 5451:   margin: 2px;
 5452: }
 5453: 
 5454: .LC_disc_action_left {
 5455:   background: $sidebg;
 5456:   text-align: left;
 5457:   padding: 4px;
 5458:   margin: 2px;
 5459: }
 5460: 
 5461: .LC_disc_action_right {
 5462:   background: $sidebg;
 5463:   text-align: right;
 5464:   padding: 4px;
 5465:   margin: 2px;
 5466: }
 5467: 
 5468: .LC_disc_new_item {
 5469:   background: white;
 5470:   border: 2px solid red;
 5471:   margin: 4px;
 5472:   padding: 4px;
 5473: }
 5474: 
 5475: .LC_disc_old_item {
 5476:   background: white;
 5477:   margin: 4px;
 5478:   padding: 4px;
 5479: }
 5480: 
 5481: table.LC_pastsubmission {
 5482:   border: 1px solid black;
 5483:   margin: 2px;
 5484: }
 5485: 
 5486: table#LC_menubuttons {
 5487:   width: 100%;
 5488:   background: $pgbg;
 5489:   border: 2px;
 5490:   border-collapse: separate;
 5491:   padding: 0;
 5492: }
 5493: 
 5494: table#LC_title_bar a {
 5495:   color: $fontmenu;
 5496: }
 5497: 
 5498: table#LC_title_bar {
 5499:   clear: both;
 5500:   display: none;
 5501: }
 5502: 
 5503: table#LC_title_bar,
 5504: table.LC_breadcrumbs, /* obsolete? */
 5505: table#LC_title_bar.LC_with_remote {
 5506:   width: 100%;
 5507:   border-color: $pgbg;
 5508:   border-style: solid;
 5509:   border-width: $border;
 5510:   background: $pgbg;
 5511:   color: $fontmenu;
 5512:   border-collapse: collapse;
 5513:   padding: 0;
 5514:   margin: 0;
 5515: }
 5516: 
 5517: ul.LC_breadcrumb_tools_outerlist {
 5518:     margin: 0;
 5519:     padding: 0;
 5520:     position: relative;
 5521:     list-style: none;
 5522: }
 5523: ul.LC_breadcrumb_tools_outerlist li {
 5524:     display: inline;
 5525: }
 5526: 
 5527: .LC_breadcrumb_tools_navigation {
 5528:     padding: 0;
 5529:     margin: 0;
 5530:     float: left;
 5531: }
 5532: .LC_breadcrumb_tools_tools {
 5533:     padding: 0;
 5534:     margin: 0;
 5535:     float: right;
 5536: }
 5537: 
 5538: table#LC_title_bar td {
 5539:   background: $tabbg;
 5540: }
 5541: 
 5542: table#LC_menubuttons img {
 5543:   border: none;
 5544: }
 5545: 
 5546: .LC_breadcrumbs_component {
 5547:   float: right;
 5548:   margin: 0 1em;
 5549: }
 5550: .LC_breadcrumbs_component img {
 5551:   vertical-align: middle;
 5552: }
 5553: 
 5554: td.LC_table_cell_checkbox {
 5555:   text-align: center;
 5556: }
 5557: 
 5558: .LC_fontsize_small {
 5559:   font-size: 70%;
 5560: }
 5561: 
 5562: #LC_breadcrumbs {
 5563:   clear:both;
 5564:   background: $sidebg;
 5565:   border-bottom: 1px solid $lg_border_color;
 5566:   line-height: 2.5em;
 5567:   overflow: hidden;
 5568:   margin: 0;
 5569:   padding: 0;
 5570:   text-align: left;
 5571: }
 5572: 
 5573: .LC_head_subbox {
 5574:   clear:both;
 5575:   background: #F8F8F8; /* $sidebg; */
 5576:   border: 1px solid $sidebg;
 5577:   margin: 0 0 10px 0;      
 5578:   padding: 3px;
 5579:   text-align: left;
 5580: }
 5581: 
 5582: .LC_fontsize_medium {
 5583:   font-size: 85%;
 5584: }
 5585: 
 5586: .LC_fontsize_large {
 5587:   font-size: 120%;
 5588: }
 5589: 
 5590: .LC_menubuttons_inline_text {
 5591:   color: $font;
 5592:   font-size: 90%;
 5593:   padding-left:3px;
 5594: }
 5595: 
 5596: .LC_menubuttons_inline_text img{
 5597:   vertical-align: middle;
 5598: }
 5599: 
 5600: li.LC_menubuttons_inline_text img {
 5601:   cursor:pointer;
 5602:   text-decoration: none;
 5603: }
 5604: 
 5605: .LC_menubuttons_link {
 5606:   text-decoration: none;
 5607: }
 5608: 
 5609: .LC_menubuttons_category {
 5610:   color: $font;
 5611:   background: $pgbg;
 5612:   font-size: larger;
 5613:   font-weight: bold;
 5614: }
 5615: 
 5616: td.LC_menubuttons_text {
 5617:   color: $font;
 5618: }
 5619: 
 5620: .LC_current_location {
 5621:   background: $tabbg;
 5622: }
 5623: 
 5624: table.LC_data_table {
 5625:   border: 1px solid #000000;
 5626:   border-collapse: separate;
 5627:   border-spacing: 1px;
 5628:   background: $pgbg;
 5629: }
 5630: 
 5631: .LC_data_table_dense {
 5632:   font-size: small;
 5633: }
 5634: 
 5635: table.LC_nested_outer {
 5636:   border: 1px solid #000000;
 5637:   border-collapse: collapse;
 5638:   border-spacing: 0;
 5639:   width: 100%;
 5640: }
 5641: 
 5642: table.LC_innerpickbox,
 5643: table.LC_nested {
 5644:   border: none;
 5645:   border-collapse: collapse;
 5646:   border-spacing: 0;
 5647:   width: 100%;
 5648: }
 5649: 
 5650: table.LC_data_table tr th,
 5651: table.LC_calendar tr th,
 5652: table.LC_prior_tries tr th,
 5653: table.LC_innerpickbox tr th {
 5654:   font-weight: bold;
 5655:   background-color: $data_table_head;
 5656:   color:$fontmenu;
 5657:   font-size:90%;
 5658: }
 5659: 
 5660: table.LC_innerpickbox tr th,
 5661: table.LC_innerpickbox tr td {
 5662:   vertical-align: top;
 5663: }
 5664: 
 5665: table.LC_data_table tr.LC_info_row > td {
 5666:   background-color: #CCCCCC;
 5667:   font-weight: bold;
 5668:   text-align: left;
 5669: }
 5670: 
 5671: table.LC_data_table tr.LC_odd_row > td {
 5672:   background-color: $data_table_light;
 5673:   padding: 2px;
 5674:   vertical-align: top;
 5675: }
 5676: 
 5677: table.LC_pick_box tr > td.LC_odd_row {
 5678:   background-color: $data_table_light;
 5679:   vertical-align: top;
 5680: }
 5681: 
 5682: table.LC_data_table tr.LC_even_row > td {
 5683:   background-color: $data_table_dark;
 5684:   padding: 2px;
 5685:   vertical-align: top;
 5686: }
 5687: 
 5688: table.LC_pick_box tr > td.LC_even_row {
 5689:   background-color: $data_table_dark;
 5690:   vertical-align: top;
 5691: }
 5692: 
 5693: table.LC_data_table tr.LC_data_table_highlight td {
 5694:   background-color: $data_table_darker;
 5695: }
 5696: 
 5697: table.LC_data_table tr td.LC_leftcol_header {
 5698:   background-color: $data_table_head;
 5699:   font-weight: bold;
 5700: }
 5701: 
 5702: table.LC_data_table tr.LC_empty_row td,
 5703: table.LC_nested tr.LC_empty_row td {
 5704:   font-weight: bold;
 5705:   font-style: italic;
 5706:   text-align: center;
 5707:   padding: 8px;
 5708: }
 5709: 
 5710: table.LC_data_table tr.LC_empty_row td {
 5711:   background-color: $sidebg;
 5712: }
 5713: 
 5714: table.LC_nested tr.LC_empty_row td {
 5715:   background-color: #FFFFFF;
 5716: }
 5717: 
 5718: table.LC_caption {
 5719: }
 5720: 
 5721: table.LC_nested tr.LC_empty_row td {
 5722:   padding: 4ex
 5723: }
 5724: 
 5725: table.LC_nested_outer tr th {
 5726:   font-weight: bold;
 5727:   color:$fontmenu;
 5728:   background-color: $data_table_head;
 5729:   font-size: small;
 5730:   border-bottom: 1px solid #000000;
 5731: }
 5732: 
 5733: table.LC_nested_outer tr td.LC_subheader {
 5734:   background-color: $data_table_head;
 5735:   font-weight: bold;
 5736:   font-size: small;
 5737:   border-bottom: 1px solid #000000;
 5738:   text-align: right;
 5739: }
 5740: 
 5741: table.LC_nested tr.LC_info_row td {
 5742:   background-color: #CCCCCC;
 5743:   font-weight: bold;
 5744:   font-size: small;
 5745:   text-align: center;
 5746: }
 5747: 
 5748: table.LC_nested tr.LC_info_row td.LC_left_item,
 5749: table.LC_nested_outer tr th.LC_left_item {
 5750:   text-align: left;
 5751: }
 5752: 
 5753: table.LC_nested td {
 5754:   background-color: #FFFFFF;
 5755:   font-size: small;
 5756: }
 5757: 
 5758: table.LC_nested_outer tr th.LC_right_item,
 5759: table.LC_nested tr.LC_info_row td.LC_right_item,
 5760: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5761: table.LC_nested tr td.LC_right_item {
 5762:   text-align: right;
 5763: }
 5764: 
 5765: table.LC_nested tr.LC_odd_row td {
 5766:   background-color: #EEEEEE;
 5767: }
 5768: 
 5769: table.LC_createuser {
 5770: }
 5771: 
 5772: table.LC_createuser tr.LC_section_row td {
 5773:   font-size: small;
 5774: }
 5775: 
 5776: table.LC_createuser tr.LC_info_row td  {
 5777:   background-color: #CCCCCC;
 5778:   font-weight: bold;
 5779:   text-align: center;
 5780: }
 5781: 
 5782: table.LC_calendar {
 5783:   border: 1px solid #000000;
 5784:   border-collapse: collapse;
 5785:   width: 98%;
 5786: }
 5787: 
 5788: table.LC_calendar_pickdate {
 5789:   font-size: xx-small;
 5790: }
 5791: 
 5792: table.LC_calendar tr td {
 5793:   border: 1px solid #000000;
 5794:   vertical-align: top;
 5795:   width: 14%;
 5796: }
 5797: 
 5798: table.LC_calendar tr td.LC_calendar_day_empty {
 5799:   background-color: $data_table_dark;
 5800: }
 5801: 
 5802: table.LC_calendar tr td.LC_calendar_day_current {
 5803:   background-color: $data_table_highlight;
 5804: }
 5805: 
 5806: table.LC_data_table tr td.LC_mail_new {
 5807:   background-color: $mail_new;
 5808: }
 5809: 
 5810: table.LC_data_table tr.LC_mail_new:hover {
 5811:   background-color: $mail_new_hover;
 5812: }
 5813: 
 5814: table.LC_data_table tr td.LC_mail_read {
 5815:   background-color: $mail_read;
 5816: }
 5817: 
 5818: /*
 5819: table.LC_data_table tr.LC_mail_read:hover {
 5820:   background-color: $mail_read_hover;
 5821: }
 5822: */
 5823: 
 5824: table.LC_data_table tr td.LC_mail_replied {
 5825:   background-color: $mail_replied;
 5826: }
 5827: 
 5828: /*
 5829: table.LC_data_table tr.LC_mail_replied:hover {
 5830:   background-color: $mail_replied_hover;
 5831: }
 5832: */
 5833: 
 5834: table.LC_data_table tr td.LC_mail_other {
 5835:   background-color: $mail_other;
 5836: }
 5837: 
 5838: /*
 5839: table.LC_data_table tr.LC_mail_other:hover {
 5840:   background-color: $mail_other_hover;
 5841: }
 5842: */
 5843: 
 5844: table.LC_data_table tr > td.LC_browser_file,
 5845: table.LC_data_table tr > td.LC_browser_file_published {
 5846:   background: #AAEE77;
 5847: }
 5848: 
 5849: table.LC_data_table tr > td.LC_browser_file_locked,
 5850: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5851:   background: #FFAA99;
 5852: }
 5853: 
 5854: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5855:   background: #888888;
 5856: }
 5857: 
 5858: table.LC_data_table tr > td.LC_browser_file_modified,
 5859: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5860:   background: #F8F866;
 5861: }
 5862: 
 5863: table.LC_data_table tr.LC_browser_folder > td {
 5864:   background: #E0E8FF;
 5865: }
 5866: 
 5867: table.LC_data_table tr > td.LC_roles_is {
 5868:   /* background: #77FF77; */
 5869: }
 5870: 
 5871: table.LC_data_table tr > td.LC_roles_future {
 5872:   border-right: 8px solid #FFFF77;
 5873: }
 5874: 
 5875: table.LC_data_table tr > td.LC_roles_will {
 5876:   border-right: 8px solid #FFAA77;
 5877: }
 5878: 
 5879: table.LC_data_table tr > td.LC_roles_expired {
 5880:   border-right: 8px solid #FF7777;
 5881: }
 5882: 
 5883: table.LC_data_table tr > td.LC_roles_will_not {
 5884:   border-right: 8px solid #AAFF77;
 5885: }
 5886: 
 5887: table.LC_data_table tr > td.LC_roles_selected {
 5888:   border-right: 8px solid #11CC55;
 5889: }
 5890: 
 5891: span.LC_current_location {
 5892:   font-size:larger;
 5893:   background: $pgbg;
 5894: }
 5895: 
 5896: span.LC_current_nav_location {
 5897:   font-weight:bold;
 5898:   background: $sidebg;
 5899: }
 5900: 
 5901: span.LC_parm_menu_item {
 5902:   font-size: larger;
 5903: }
 5904: 
 5905: span.LC_parm_scope_all {
 5906:   color: red;
 5907: }
 5908: 
 5909: span.LC_parm_scope_folder {
 5910:   color: green;
 5911: }
 5912: 
 5913: span.LC_parm_scope_resource {
 5914:   color: orange;
 5915: }
 5916: 
 5917: span.LC_parm_part {
 5918:   color: blue;
 5919: }
 5920: 
 5921: span.LC_parm_folder,
 5922: span.LC_parm_symb {
 5923:   font-size: x-small;
 5924:   font-family: $mono;
 5925:   color: #AAAAAA;
 5926: }
 5927: 
 5928: ul.LC_parm_parmlist li {
 5929:   display: inline-block;
 5930:   padding: 0.3em 0.8em;
 5931:   vertical-align: top;
 5932:   width: 150px;
 5933:   border-top:1px solid $lg_border_color;
 5934: }
 5935: 
 5936: td.LC_parm_overview_level_menu,
 5937: td.LC_parm_overview_map_menu,
 5938: td.LC_parm_overview_parm_selectors,
 5939: td.LC_parm_overview_restrictions  {
 5940:   border: 1px solid black;
 5941:   border-collapse: collapse;
 5942: }
 5943: 
 5944: table.LC_parm_overview_restrictions td {
 5945:   border-width: 1px 4px 1px 4px;
 5946:   border-style: solid;
 5947:   border-color: $pgbg;
 5948:   text-align: center;
 5949: }
 5950: 
 5951: table.LC_parm_overview_restrictions th {
 5952:   background: $tabbg;
 5953:   border-width: 1px 4px 1px 4px;
 5954:   border-style: solid;
 5955:   border-color: $pgbg;
 5956: }
 5957: 
 5958: table#LC_helpmenu {
 5959:   border: none;
 5960:   height: 55px;
 5961:   border-spacing: 0;
 5962: }
 5963: 
 5964: table#LC_helpmenu fieldset legend {
 5965:   font-size: larger;
 5966: }
 5967: 
 5968: table#LC_helpmenu_links {
 5969:   width: 100%;
 5970:   border: 1px solid black;
 5971:   background: $pgbg;
 5972:   padding: 0;
 5973:   border-spacing: 1px;
 5974: }
 5975: 
 5976: table#LC_helpmenu_links tr td {
 5977:   padding: 1px;
 5978:   background: $tabbg;
 5979:   text-align: center;
 5980:   font-weight: bold;
 5981: }
 5982: 
 5983: table#LC_helpmenu_links a:link,
 5984: table#LC_helpmenu_links a:visited,
 5985: table#LC_helpmenu_links a:active {
 5986:   text-decoration: none;
 5987:   color: $font;
 5988: }
 5989: 
 5990: table#LC_helpmenu_links a:hover {
 5991:   text-decoration: underline;
 5992:   color: $vlink;
 5993: }
 5994: 
 5995: .LC_chrt_popup_exists {
 5996:   border: 1px solid #339933;
 5997:   margin: -1px;
 5998: }
 5999: 
 6000: .LC_chrt_popup_up {
 6001:   border: 1px solid yellow;
 6002:   margin: -1px;
 6003: }
 6004: 
 6005: .LC_chrt_popup {
 6006:   border: 1px solid #8888FF;
 6007:   background: #CCCCFF;
 6008: }
 6009: 
 6010: table.LC_pick_box {
 6011:   border-collapse: separate;
 6012:   background: white;
 6013:   border: 1px solid black;
 6014:   border-spacing: 1px;
 6015: }
 6016: 
 6017: table.LC_pick_box td.LC_pick_box_title {
 6018:   background: $sidebg;
 6019:   font-weight: bold;
 6020:   text-align: left;
 6021:   vertical-align: top;
 6022:   width: 184px;
 6023:   padding: 8px;
 6024: }
 6025: 
 6026: table.LC_pick_box td.LC_pick_box_value {
 6027:   text-align: left;
 6028:   padding: 8px;
 6029: }
 6030: 
 6031: table.LC_pick_box td.LC_pick_box_select {
 6032:   text-align: left;
 6033:   padding: 8px;
 6034: }
 6035: 
 6036: table.LC_pick_box td.LC_pick_box_separator {
 6037:   padding: 0;
 6038:   height: 1px;
 6039:   background: black;
 6040: }
 6041: 
 6042: table.LC_pick_box td.LC_pick_box_submit {
 6043:   text-align: right;
 6044: }
 6045: 
 6046: table.LC_pick_box td.LC_evenrow_value {
 6047:   text-align: left;
 6048:   padding: 8px;
 6049:   background-color: $data_table_light;
 6050: }
 6051: 
 6052: table.LC_pick_box td.LC_oddrow_value {
 6053:   text-align: left;
 6054:   padding: 8px;
 6055:   background-color: $data_table_light;
 6056: }
 6057: 
 6058: span.LC_helpform_receipt_cat {
 6059:   font-weight: bold;
 6060: }
 6061: 
 6062: table.LC_group_priv_box {
 6063:   background: white;
 6064:   border: 1px solid black;
 6065:   border-spacing: 1px;
 6066: }
 6067: 
 6068: table.LC_group_priv_box td.LC_pick_box_title {
 6069:   background: $tabbg;
 6070:   font-weight: bold;
 6071:   text-align: right;
 6072:   width: 184px;
 6073: }
 6074: 
 6075: table.LC_group_priv_box td.LC_groups_fixed {
 6076:   background: $data_table_light;
 6077:   text-align: center;
 6078: }
 6079: 
 6080: table.LC_group_priv_box td.LC_groups_optional {
 6081:   background: $data_table_dark;
 6082:   text-align: center;
 6083: }
 6084: 
 6085: table.LC_group_priv_box td.LC_groups_functionality {
 6086:   background: $data_table_darker;
 6087:   text-align: center;
 6088:   font-weight: bold;
 6089: }
 6090: 
 6091: table.LC_group_priv td {
 6092:   text-align: left;
 6093:   padding: 0;
 6094: }
 6095: 
 6096: .LC_navbuttons {
 6097:   margin: 2ex 0ex 2ex 0ex;
 6098: }
 6099: 
 6100: .LC_topic_bar {
 6101:   font-weight: bold;
 6102:   background: $tabbg;
 6103:   margin: 1em 0em 1em 2em;
 6104:   padding: 3px;
 6105:   font-size: 1.2em;
 6106: }
 6107: 
 6108: .LC_topic_bar span {
 6109:   left: 0.5em;
 6110:   position: absolute;
 6111:   vertical-align: middle;
 6112:   font-size: 1.2em;
 6113: }
 6114: 
 6115: table.LC_course_group_status {
 6116:   margin: 20px;
 6117: }
 6118: 
 6119: table.LC_status_selector td {
 6120:   vertical-align: top;
 6121:   text-align: center;
 6122:   padding: 4px;
 6123: }
 6124: 
 6125: div.LC_feedback_link {
 6126:   clear: both;
 6127:   background: $sidebg;
 6128:   width: 100%;
 6129:   padding-bottom: 10px;
 6130:   border: 1px $tabbg solid;
 6131:   height: 22px;
 6132:   line-height: 22px;
 6133:   padding-top: 5px;
 6134: }
 6135: 
 6136: div.LC_feedback_link img {
 6137:   height: 22px;
 6138:   vertical-align:middle;
 6139: }
 6140: 
 6141: div.LC_feedback_link a {
 6142:   text-decoration: none;
 6143: }
 6144: 
 6145: div.LC_comblock {
 6146:   display:inline;
 6147:   color:$font;
 6148:   font-size:90%;
 6149: }
 6150: 
 6151: div.LC_feedback_link div.LC_comblock {
 6152:   padding-left:5px;
 6153: }
 6154: 
 6155: div.LC_feedback_link div.LC_comblock a {
 6156:   color:$font;
 6157: }
 6158: 
 6159: span.LC_feedback_link {
 6160:   /* background: $feedback_link_bg; */
 6161:   font-size: larger;
 6162: }
 6163: 
 6164: span.LC_message_link {
 6165:   /* background: $feedback_link_bg; */
 6166:   font-size: larger;
 6167:   position: absolute;
 6168:   right: 1em;
 6169: }
 6170: 
 6171: table.LC_prior_tries {
 6172:   border: 1px solid #000000;
 6173:   border-collapse: separate;
 6174:   border-spacing: 1px;
 6175: }
 6176: 
 6177: table.LC_prior_tries td {
 6178:   padding: 2px;
 6179: }
 6180: 
 6181: .LC_answer_correct {
 6182:   background: lightgreen;
 6183:   color: darkgreen;
 6184:   padding: 6px;
 6185: }
 6186: 
 6187: .LC_answer_charged_try {
 6188:   background: #FFAAAA;
 6189:   color: darkred;
 6190:   padding: 6px;
 6191: }
 6192: 
 6193: .LC_answer_not_charged_try,
 6194: .LC_answer_no_grade,
 6195: .LC_answer_late {
 6196:   background: lightyellow;
 6197:   color: black;
 6198:   padding: 6px;
 6199: }
 6200: 
 6201: .LC_answer_previous {
 6202:   background: lightblue;
 6203:   color: darkblue;
 6204:   padding: 6px;
 6205: }
 6206: 
 6207: .LC_answer_no_message {
 6208:   background: #FFFFFF;
 6209:   color: black;
 6210:   padding: 6px;
 6211: }
 6212: 
 6213: .LC_answer_unknown {
 6214:   background: orange;
 6215:   color: black;
 6216:   padding: 6px;
 6217: }
 6218: 
 6219: span.LC_prior_numerical,
 6220: span.LC_prior_string,
 6221: span.LC_prior_custom,
 6222: span.LC_prior_reaction,
 6223: span.LC_prior_math {
 6224:   font-family: $mono;
 6225:   white-space: pre;
 6226: }
 6227: 
 6228: span.LC_prior_string {
 6229:   font-family: $mono;
 6230:   white-space: pre;
 6231: }
 6232: 
 6233: table.LC_prior_option {
 6234:   width: 100%;
 6235:   border-collapse: collapse;
 6236: }
 6237: 
 6238: table.LC_prior_rank,
 6239: table.LC_prior_match {
 6240:   border-collapse: collapse;
 6241: }
 6242: 
 6243: table.LC_prior_option tr td,
 6244: table.LC_prior_rank tr td,
 6245: table.LC_prior_match tr td {
 6246:   border: 1px solid #000000;
 6247: }
 6248: 
 6249: .LC_nobreak {
 6250:   white-space: nowrap;
 6251: }
 6252: 
 6253: span.LC_cusr_emph {
 6254:   font-style: italic;
 6255: }
 6256: 
 6257: span.LC_cusr_subheading {
 6258:   font-weight: normal;
 6259:   font-size: 85%;
 6260: }
 6261: 
 6262: div.LC_docs_entry_move {
 6263:   border: 1px solid #BBBBBB;
 6264:   background: #DDDDDD;
 6265:   width: 22px;
 6266:   padding: 1px;
 6267:   margin: 0;
 6268: }
 6269: 
 6270: table.LC_data_table tr > td.LC_docs_entry_commands,
 6271: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6272:   background: #DDDDDD;
 6273:   font-size: x-small;
 6274: }
 6275: 
 6276: .LC_docs_entry_parameter {
 6277:   white-space: nowrap;
 6278: }
 6279: 
 6280: .LC_docs_copy {
 6281:   color: #000099;
 6282: }
 6283: 
 6284: .LC_docs_cut {
 6285:   color: #550044;
 6286: }
 6287: 
 6288: .LC_docs_rename {
 6289:   color: #009900;
 6290: }
 6291: 
 6292: .LC_docs_remove {
 6293:   color: #990000;
 6294: }
 6295: 
 6296: .LC_docs_reinit_warn,
 6297: .LC_docs_ext_edit {
 6298:   font-size: x-small;
 6299: }
 6300: 
 6301: table.LC_docs_adddocs td,
 6302: table.LC_docs_adddocs th {
 6303:   border: 1px solid #BBBBBB;
 6304:   padding: 4px;
 6305:   background: #DDDDDD;
 6306: }
 6307: 
 6308: table.LC_sty_begin {
 6309:   background: #BBFFBB;
 6310: }
 6311: 
 6312: table.LC_sty_end {
 6313:   background: #FFBBBB;
 6314: }
 6315: 
 6316: table.LC_double_column {
 6317:   border-width: 0;
 6318:   border-collapse: collapse;
 6319:   width: 100%;
 6320:   padding: 2px;
 6321: }
 6322: 
 6323: table.LC_double_column tr td.LC_left_col {
 6324:   top: 2px;
 6325:   left: 2px;
 6326:   width: 47%;
 6327:   vertical-align: top;
 6328: }
 6329: 
 6330: table.LC_double_column tr td.LC_right_col {
 6331:   top: 2px;
 6332:   right: 2px;
 6333:   width: 47%;
 6334:   vertical-align: top;
 6335: }
 6336: 
 6337: div.LC_left_float {
 6338:   float: left;
 6339:   padding-right: 5%;
 6340:   padding-bottom: 4px;
 6341: }
 6342: 
 6343: div.LC_clear_float_header {
 6344:   padding-bottom: 2px;
 6345: }
 6346: 
 6347: div.LC_clear_float_footer {
 6348:   padding-top: 10px;
 6349:   clear: both;
 6350: }
 6351: 
 6352: div.LC_grade_show_user {
 6353: /*  border-left: 5px solid $sidebg; */
 6354:   border-top: 5px solid #000000;
 6355:   margin: 50px 0 0 0;
 6356:   padding: 15px 0 5px 10px;
 6357: }
 6358: 
 6359: div.LC_grade_show_user_odd_row {
 6360: /*  border-left: 5px solid #000000; */
 6361: }
 6362: 
 6363: div.LC_grade_show_user div.LC_Box {
 6364:   margin-right: 50px;
 6365: }
 6366: 
 6367: div.LC_grade_submissions,
 6368: div.LC_grade_message_center,
 6369: div.LC_grade_info_links {
 6370:   margin: 5px;
 6371:   width: 99%;
 6372:   background: #FFFFFF;
 6373: }
 6374: 
 6375: div.LC_grade_submissions_header,
 6376: div.LC_grade_message_center_header {
 6377:   font-weight: bold;
 6378:   font-size: large;
 6379: }
 6380: 
 6381: div.LC_grade_submissions_body,
 6382: div.LC_grade_message_center_body {
 6383:   border: 1px solid black;
 6384:   width: 99%;
 6385:   background: #FFFFFF;
 6386: }
 6387: 
 6388: table.LC_scantron_action {
 6389:   width: 100%;
 6390: }
 6391: 
 6392: table.LC_scantron_action tr th {
 6393:   font-weight:bold;
 6394:   font-style:normal;
 6395: }
 6396: 
 6397: .LC_edit_problem_header,
 6398: div.LC_edit_problem_footer {
 6399:   font-weight: normal;
 6400:   font-size:  medium;
 6401:   margin: 2px;
 6402:   background-color: $sidebg;
 6403: }
 6404: 
 6405: div.LC_edit_problem_header,
 6406: div.LC_edit_problem_header div,
 6407: div.LC_edit_problem_footer,
 6408: div.LC_edit_problem_footer div,
 6409: div.LC_edit_problem_editxml_header,
 6410: div.LC_edit_problem_editxml_header div {
 6411:   margin-top: 5px;
 6412: }
 6413: 
 6414: div.LC_edit_problem_header_title {
 6415:   font-weight: bold;
 6416:   font-size: larger;
 6417:   background: $tabbg;
 6418:   padding: 3px;
 6419:   margin: 0 0 5px 0;
 6420: }
 6421: 
 6422: table.LC_edit_problem_header_title {
 6423:   width: 100%;
 6424:   background: $tabbg;
 6425: }
 6426: 
 6427: div.LC_edit_problem_discards {
 6428:   float: left;
 6429:   padding-bottom: 5px;
 6430: }
 6431: 
 6432: div.LC_edit_problem_saves {
 6433:   float: right;
 6434:   padding-bottom: 5px;
 6435: }
 6436: 
 6437: img.stift {
 6438:   border-width: 0;
 6439:   vertical-align: middle;
 6440: }
 6441: 
 6442: table td.LC_mainmenu_col_fieldset {
 6443:   vertical-align: top;
 6444: }
 6445: 
 6446: div.LC_createcourse {
 6447:   margin: 10px 10px 10px 10px;
 6448: }
 6449: 
 6450: .LC_dccid {
 6451:   margin: 0.2em 0 0 0;
 6452:   padding: 0;
 6453:   font-size: 90%;
 6454:   display:none;
 6455: }
 6456: 
 6457: ol.LC_primary_menu a:hover,
 6458: ol#LC_MenuBreadcrumbs a:hover,
 6459: ol#LC_PathBreadcrumbs a:hover,
 6460: ul#LC_secondary_menu a:hover,
 6461: .LC_FormSectionClearButton input:hover
 6462: ul.LC_TabContent   li:hover a {
 6463:   color:$button_hover;
 6464:   text-decoration:none;
 6465: }
 6466: 
 6467: h1 {
 6468:   padding: 0;
 6469:   line-height:130%;
 6470: }
 6471: 
 6472: h2,
 6473: h3,
 6474: h4,
 6475: h5,
 6476: h6 {
 6477:   margin: 5px 0 5px 0;
 6478:   padding: 0;
 6479:   line-height:130%;
 6480: }
 6481: 
 6482: .LC_hcell {
 6483:   padding:3px 15px 3px 15px;
 6484:   margin: 0;
 6485:   background-color:$tabbg;
 6486:   color:$fontmenu;
 6487:   border-bottom:solid 1px $lg_border_color;
 6488: }
 6489: 
 6490: .LC_Box > .LC_hcell {
 6491:   margin: 0 -10px 10px -10px;
 6492: }
 6493: 
 6494: .LC_noBorder {
 6495:   border: 0;
 6496: }
 6497: 
 6498: .LC_FormSectionClearButton input {
 6499:   background-color:transparent;
 6500:   border: none;
 6501:   cursor:pointer;
 6502:   text-decoration:underline;
 6503: }
 6504: 
 6505: .LC_help_open_topic {
 6506:   color: #FFFFFF;
 6507:   background-color: #EEEEFF;
 6508:   margin: 1px;
 6509:   padding: 4px;
 6510:   border: 1px solid #000033;
 6511:   white-space: nowrap;
 6512:   /* vertical-align: middle; */
 6513: }
 6514: 
 6515: dl,
 6516: ul,
 6517: div,
 6518: fieldset {
 6519:   margin: 10px 10px 10px 0;
 6520:   /* overflow: hidden; */
 6521: }
 6522: 
 6523: fieldset > legend {
 6524:   font-weight: bold;
 6525:   padding: 0 5px 0 5px;
 6526: }
 6527: 
 6528: #LC_nav_bar {
 6529:   float: left;
 6530:   background-color: $pgbg_or_bgcolor;
 6531:   margin: 0 0 2px 0;
 6532: }
 6533: 
 6534: #LC_realm {
 6535:   margin: 0.2em 0 0 0;
 6536:   padding: 0;
 6537:   font-weight: bold;
 6538:   text-align: center;
 6539:   background-color: $pgbg_or_bgcolor;
 6540: }
 6541: 
 6542: #LC_nav_bar em {
 6543:   font-weight: bold;
 6544:   font-style: normal;
 6545: }
 6546: 
 6547: ol.LC_primary_menu {
 6548:   float: right;
 6549:   margin: 0;
 6550:   padding: 0;
 6551:   background-color: $pgbg_or_bgcolor;
 6552: }
 6553: 
 6554: ol#LC_PathBreadcrumbs {
 6555:   margin: 0;
 6556: }
 6557: 
 6558: ol.LC_primary_menu li {
 6559:   color: RGB(80, 80, 80);
 6560:   vertical-align: middle;
 6561:   text-align: left;
 6562:   list-style: none;
 6563:   float: left;
 6564: }
 6565: 
 6566: ol.LC_primary_menu li a {
 6567:   display: block;
 6568:   margin: 0;
 6569:   padding: 0 5px 0 10px;
 6570:   text-decoration: none;
 6571: }
 6572: 
 6573: ol.LC_primary_menu li ul {
 6574:   display: none;
 6575:   width: 10em;
 6576:   background-color: $data_table_light;
 6577: }
 6578: 
 6579: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6580:   display: block;
 6581:   position: absolute;
 6582:   margin: 0;
 6583:   padding: 0;
 6584:   z-index: 2;
 6585: }
 6586: 
 6587: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6588:   font-size: 90%;
 6589:   vertical-align: top;
 6590:   float: none;
 6591:   border-left: 1px solid black;
 6592:   border-right: 1px solid black;
 6593: }
 6594: 
 6595: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6596:   background-color:$data_table_light;
 6597: }
 6598: 
 6599: ol.LC_primary_menu li li a:hover {
 6600:    color:$button_hover;
 6601:    background-color:$data_table_dark;
 6602: }
 6603: 
 6604: ol.LC_primary_menu li img {
 6605:   vertical-align: bottom;
 6606:   height: 1.1em;
 6607:   margin: 0.2em 0 0 0;
 6608: }
 6609: 
 6610: ol.LC_primary_menu a {
 6611:   color: RGB(80, 80, 80);
 6612:   text-decoration: none;
 6613: }
 6614: 
 6615: ol.LC_primary_menu a.LC_new_message {
 6616:   font-weight:bold;
 6617:   color: darkred;
 6618: }
 6619: 
 6620: ol.LC_docs_parameters {
 6621:   margin-left: 0;
 6622:   padding: 0;
 6623:   list-style: none;
 6624: }
 6625: 
 6626: ol.LC_docs_parameters li {
 6627:   margin: 0;
 6628:   padding-right: 20px;
 6629:   display: inline;
 6630: }
 6631: 
 6632: ol.LC_docs_parameters li:before {
 6633:   content: "\\002022 \\0020";
 6634: }
 6635: 
 6636: li.LC_docs_parameters_title {
 6637:   font-weight: bold;
 6638: }
 6639: 
 6640: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6641:   content: "";
 6642: }
 6643: 
 6644: ul#LC_secondary_menu {
 6645:   clear: both;
 6646:   color: $fontmenu;
 6647:   background: $tabbg;
 6648:   list-style: none;
 6649:   padding: 0;
 6650:   margin: 0;
 6651:   width: 100%;
 6652:   text-align: left;
 6653: }
 6654: 
 6655: ul#LC_secondary_menu li {
 6656:   font-weight: bold;
 6657:   line-height: 1.8em;
 6658:   padding: 0 0.8em;
 6659:   border-right: 1px solid black;
 6660:   display: inline;
 6661:   vertical-align: middle;
 6662: }
 6663: 
 6664: ul.LC_TabContent {
 6665:   display:block;
 6666:   background: $sidebg;
 6667:   border-bottom: solid 1px $lg_border_color;
 6668:   list-style:none;
 6669:   margin: -1px -10px 0 -10px;
 6670:   padding: 0;
 6671: }
 6672: 
 6673: ul.LC_TabContent li,
 6674: ul.LC_TabContentBigger li {
 6675:   float:left;
 6676: }
 6677: 
 6678: ul#LC_secondary_menu li a {
 6679:   color: $fontmenu;
 6680:   text-decoration: none;
 6681: }
 6682: 
 6683: ul.LC_TabContent {
 6684:   min-height:20px;
 6685: }
 6686: 
 6687: ul.LC_TabContent li {
 6688:   vertical-align:middle;
 6689:   padding: 0 16px 0 10px;
 6690:   background-color:$tabbg;
 6691:   border-bottom:solid 1px $lg_border_color;
 6692:   border-left: solid 1px $font;
 6693: }
 6694: 
 6695: ul.LC_TabContent .right {
 6696:   float:right;
 6697: }
 6698: 
 6699: ul.LC_TabContent li a,
 6700: ul.LC_TabContent li {
 6701:   color:rgb(47,47,47);
 6702:   text-decoration:none;
 6703:   font-size:95%;
 6704:   font-weight:bold;
 6705:   min-height:20px;
 6706: }
 6707: 
 6708: ul.LC_TabContent li a:hover,
 6709: ul.LC_TabContent li a:focus {
 6710:   color: $button_hover;
 6711:   background:none;
 6712:   outline:none;
 6713: }
 6714: 
 6715: ul.LC_TabContent li:hover {
 6716:   color: $button_hover;
 6717:   cursor:pointer;
 6718: }
 6719: 
 6720: ul.LC_TabContent li.active {
 6721:   color: $font;
 6722:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6723:   border-bottom:solid 1px #FFFFFF;
 6724:   cursor: default;
 6725: }
 6726: 
 6727: ul.LC_TabContent li.active a {
 6728:   color:$font;
 6729:   background:#FFFFFF;
 6730:   outline: none;
 6731: }
 6732: 
 6733: ul.LC_TabContent li.goback {
 6734:   float: left;
 6735:   border-left: none;
 6736: }
 6737: 
 6738: #maincoursedoc {
 6739:   clear:both;
 6740: }
 6741: 
 6742: ul.LC_TabContentBigger {
 6743:   display:block;
 6744:   list-style:none;
 6745:   padding: 0;
 6746: }
 6747: 
 6748: ul.LC_TabContentBigger li {
 6749:   vertical-align:bottom;
 6750:   height: 30px;
 6751:   font-size:110%;
 6752:   font-weight:bold;
 6753:   color: #737373;
 6754: }
 6755: 
 6756: ul.LC_TabContentBigger li.active {
 6757:   position: relative;
 6758:   top: 1px;
 6759: }
 6760: 
 6761: ul.LC_TabContentBigger li a {
 6762:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6763:   height: 30px;
 6764:   line-height: 30px;
 6765:   text-align: center;
 6766:   display: block;
 6767:   text-decoration: none;
 6768:   outline: none;  
 6769: }
 6770: 
 6771: ul.LC_TabContentBigger li.active a {
 6772:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6773:   color:$font;
 6774: }
 6775: 
 6776: ul.LC_TabContentBigger li b {
 6777:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6778:   display: block;
 6779:   float: left;
 6780:   padding: 0 30px;
 6781:   border-bottom: 1px solid $lg_border_color;
 6782: }
 6783: 
 6784: ul.LC_TabContentBigger li:hover b {
 6785:   color:$button_hover;
 6786: }
 6787: 
 6788: ul.LC_TabContentBigger li.active b {
 6789:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6790:   color:$font;
 6791:   border: 0;
 6792: }
 6793: 
 6794: 
 6795: ul.LC_CourseBreadcrumbs {
 6796:   background: $sidebg;
 6797:   height: 2em;
 6798:   padding-left: 10px;
 6799:   margin: 0;
 6800:   list-style-position: inside;
 6801: }
 6802: 
 6803: ol#LC_MenuBreadcrumbs,
 6804: ol#LC_PathBreadcrumbs {
 6805:   padding-left: 10px;
 6806:   margin: 0;
 6807:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6808: }
 6809: 
 6810: ol#LC_MenuBreadcrumbs li,
 6811: ol#LC_PathBreadcrumbs li,
 6812: ul.LC_CourseBreadcrumbs li {
 6813:   display: inline;
 6814:   white-space: normal;  
 6815: }
 6816: 
 6817: ol#LC_MenuBreadcrumbs li a,
 6818: ul.LC_CourseBreadcrumbs li a {
 6819:   text-decoration: none;
 6820:   font-size:90%;
 6821: }
 6822: 
 6823: ol#LC_MenuBreadcrumbs h1 {
 6824:   display: inline;
 6825:   font-size: 90%;
 6826:   line-height: 2.5em;
 6827:   margin: 0;
 6828:   padding: 0;
 6829: }
 6830: 
 6831: ol#LC_PathBreadcrumbs li a {
 6832:   text-decoration:none;
 6833:   font-size:100%;
 6834:   font-weight:bold;
 6835: }
 6836: 
 6837: .LC_Box {
 6838:   border: solid 1px $lg_border_color;
 6839:   padding: 0 10px 10px 10px;
 6840: }
 6841: 
 6842: .LC_DocsBox {
 6843:   border: solid 1px $lg_border_color;
 6844:   padding: 0 0 10px 10px;
 6845: }
 6846: 
 6847: .LC_AboutMe_Image {
 6848:   float:left;
 6849:   margin-right:10px;
 6850: }
 6851: 
 6852: .LC_Clear_AboutMe_Image {
 6853:   clear:left;
 6854: }
 6855: 
 6856: dl.LC_ListStyleClean dt {
 6857:   padding-right: 5px;
 6858:   display: table-header-group;
 6859: }
 6860: 
 6861: dl.LC_ListStyleClean dd {
 6862:   display: table-row;
 6863: }
 6864: 
 6865: .LC_ListStyleClean,
 6866: .LC_ListStyleSimple,
 6867: .LC_ListStyleNormal,
 6868: .LC_ListStyleSpecial {
 6869:   /* display:block; */
 6870:   list-style-position: inside;
 6871:   list-style-type: none;
 6872:   overflow: hidden;
 6873:   padding: 0;
 6874: }
 6875: 
 6876: .LC_ListStyleSimple li,
 6877: .LC_ListStyleSimple dd,
 6878: .LC_ListStyleNormal li,
 6879: .LC_ListStyleNormal dd,
 6880: .LC_ListStyleSpecial li,
 6881: .LC_ListStyleSpecial dd {
 6882:   margin: 0;
 6883:   padding: 5px 5px 5px 10px;
 6884:   clear: both;
 6885: }
 6886: 
 6887: .LC_ListStyleClean li,
 6888: .LC_ListStyleClean dd {
 6889:   padding-top: 0;
 6890:   padding-bottom: 0;
 6891: }
 6892: 
 6893: .LC_ListStyleSimple dd,
 6894: .LC_ListStyleSimple li {
 6895:   border-bottom: solid 1px $lg_border_color;
 6896: }
 6897: 
 6898: .LC_ListStyleSpecial li,
 6899: .LC_ListStyleSpecial dd {
 6900:   list-style-type: none;
 6901:   background-color: RGB(220, 220, 220);
 6902:   margin-bottom: 4px;
 6903: }
 6904: 
 6905: table.LC_SimpleTable {
 6906:   margin:5px;
 6907:   border:solid 1px $lg_border_color;
 6908: }
 6909: 
 6910: table.LC_SimpleTable tr {
 6911:   padding: 0;
 6912:   border:solid 1px $lg_border_color;
 6913: }
 6914: 
 6915: table.LC_SimpleTable thead {
 6916:   background:rgb(220,220,220);
 6917: }
 6918: 
 6919: div.LC_columnSection {
 6920:   display: block;
 6921:   clear: both;
 6922:   overflow: hidden;
 6923:   margin: 0;
 6924: }
 6925: 
 6926: div.LC_columnSection>* {
 6927:   float: left;
 6928:   margin: 10px 20px 10px 0;
 6929:   overflow:hidden;
 6930: }
 6931: 
 6932: table em {
 6933:   font-weight: bold;
 6934:   font-style: normal;
 6935: }
 6936: 
 6937: table.LC_tableBrowseRes,
 6938: table.LC_tableOfContent {
 6939:   border:none;
 6940:   border-spacing: 1px;
 6941:   padding: 3px;
 6942:   background-color: #FFFFFF;
 6943:   font-size: 90%;
 6944: }
 6945: 
 6946: table.LC_tableOfContent {
 6947:   border-collapse: collapse;
 6948: }
 6949: 
 6950: table.LC_tableBrowseRes a,
 6951: table.LC_tableOfContent a {
 6952:   background-color: transparent;
 6953:   text-decoration: none;
 6954: }
 6955: 
 6956: table.LC_tableOfContent img {
 6957:   border: none;
 6958:   height: 1.3em;
 6959:   vertical-align: text-bottom;
 6960:   margin-right: 0.3em;
 6961: }
 6962: 
 6963: a#LC_content_toolbar_firsthomework {
 6964:   background-image:url(/res/adm/pages/open-first-problem.gif);
 6965: }
 6966: 
 6967: a#LC_content_toolbar_everything {
 6968:   background-image:url(/res/adm/pages/show-all.gif);
 6969: }
 6970: 
 6971: a#LC_content_toolbar_uncompleted {
 6972:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6973: }
 6974: 
 6975: #LC_content_toolbar_clearbubbles {
 6976:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6977: }
 6978: 
 6979: a#LC_content_toolbar_changefolder {
 6980:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6981: }
 6982: 
 6983: a#LC_content_toolbar_changefolder_toggled {
 6984:   background-image:url(/res/adm/pages/open-all-folders.gif);
 6985: }
 6986: 
 6987: a#LC_content_toolbar_edittoplevel {
 6988:   background-image:url(/res/adm/pages/edittoplevel.gif);
 6989: }
 6990: 
 6991: ul#LC_toolbar li a:hover {
 6992:   background-position: bottom center;
 6993: }
 6994: 
 6995: ul#LC_toolbar {
 6996:   padding: 0;
 6997:   margin: 2px;
 6998:   list-style:none;
 6999:   position:relative;
 7000:   background-color:white;
 7001:   overflow: auto;
 7002: }
 7003: 
 7004: ul#LC_toolbar li {
 7005:   border:1px solid white;
 7006:   padding: 0;
 7007:   margin: 0;
 7008:   float: left;
 7009:   display:inline;
 7010:   vertical-align:middle;
 7011:   white-space: nowrap;
 7012: }
 7013: 
 7014: 
 7015: a.LC_toolbarItem {
 7016:   display:block;
 7017:   padding: 0;
 7018:   margin: 0;
 7019:   height: 32px;
 7020:   width: 32px;
 7021:   color:white;
 7022:   border: none;
 7023:   background-repeat:no-repeat;
 7024:   background-color:transparent;
 7025: }
 7026: 
 7027: ul.LC_funclist {
 7028:     margin: 0;
 7029:     padding: 0.5em 1em 0.5em 0;
 7030: }
 7031: 
 7032: ul.LC_funclist > li:first-child {
 7033:     font-weight:bold; 
 7034:     margin-left:0.8em;
 7035: }
 7036: 
 7037: ul.LC_funclist + ul.LC_funclist {
 7038:     /* 
 7039:        left border as a seperator if we have more than
 7040:        one list 
 7041:     */
 7042:     border-left: 1px solid $sidebg;
 7043:     /* 
 7044:        this hides the left border behind the border of the 
 7045:        outer box if element is wrapped to the next 'line' 
 7046:     */
 7047:     margin-left: -1px;
 7048: }
 7049: 
 7050: ul.LC_funclist li {
 7051:   display: inline;
 7052:   white-space: nowrap;
 7053:   margin: 0 0 0 25px;
 7054:   line-height: 150%;
 7055: }
 7056: 
 7057: .LC_hidden {
 7058:   display: none;
 7059: }
 7060: 
 7061: .LCmodal-overlay {
 7062: 		position:fixed;
 7063: 		top:0;
 7064: 		right:0;
 7065: 		bottom:0;
 7066: 		left:0;
 7067: 		height:100%;
 7068: 		width:100%;
 7069: 		margin:0;
 7070: 		padding:0;
 7071: 		background:#999;
 7072: 		opacity:.75;
 7073: 		filter: alpha(opacity=75);
 7074: 		-moz-opacity: 0.75;
 7075: 		z-index:101;
 7076: }
 7077: 
 7078: * html .LCmodal-overlay {   
 7079: 		position: absolute;
 7080: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7081: }
 7082: 
 7083: .LCmodal-window {
 7084: 		position:fixed;
 7085: 		top:50%;
 7086: 		left:50%;
 7087: 		margin:0;
 7088: 		padding:0;
 7089: 		z-index:102;
 7090: 	}
 7091: 
 7092: * html .LCmodal-window {
 7093: 		position:absolute;
 7094: }
 7095: 
 7096: .LCclose-window {
 7097: 		position:absolute;
 7098: 		width:32px;
 7099: 		height:32px;
 7100: 		right:8px;
 7101: 		top:8px;
 7102: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7103: 		text-indent:-99999px;
 7104: 		overflow:hidden;
 7105: 		cursor:pointer;
 7106: }
 7107: 
 7108: END
 7109: }
 7110: 
 7111: =pod
 7112: 
 7113: =item * &headtag()
 7114: 
 7115: Returns a uniform footer for LON-CAPA web pages.
 7116: 
 7117: Inputs: $title - optional title for the head
 7118:         $head_extra - optional extra HTML to put inside the <head>
 7119:         $args - optional arguments
 7120:             force_register - if is true call registerurl so the remote is 
 7121:                              informed
 7122:             redirect       -> array ref of
 7123:                                    1- seconds before redirect occurs
 7124:                                    2- url to redirect to
 7125:                                    3- whether the side effect should occur
 7126:                            (side effect of setting 
 7127:                                $env{'internal.head.redirect'} to the url 
 7128:                                redirected too)
 7129:             domain         -> force to color decorate a page for a specific
 7130:                                domain
 7131:             function       -> force usage of a specific rolish color scheme
 7132:             bgcolor        -> override the default page bgcolor
 7133:             no_auto_mt_title
 7134:                            -> prevent &mt()ing the title arg
 7135: 
 7136: =cut
 7137: 
 7138: sub headtag {
 7139:     my ($title,$head_extra,$args) = @_;
 7140:     
 7141:     my $function = $args->{'function'} || &get_users_function();
 7142:     my $domain   = $args->{'domain'}   || &determinedomain();
 7143:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7144:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7145: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7146: 		   #time(),
 7147: 		   $env{'environment.color.timestamp'},
 7148: 		   $function,$domain,$bgcolor);
 7149: 
 7150:     $url = '/adm/css/'.&escape($url).'.css';
 7151: 
 7152:     my $result =
 7153: 	'<head>'.
 7154: 	&font_settings();
 7155: 
 7156:     my $inhibitprint = &print_suppression();
 7157: 
 7158:     if (!$args->{'frameset'}) {
 7159: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7160:     }
 7161:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 7162:         $result .= Apache::lonxml::display_title();
 7163:     }
 7164:     if (!$args->{'no_nav_bar'} 
 7165: 	&& !$args->{'only_body'}
 7166: 	&& !$args->{'frameset'}) {
 7167: 	$result .= &help_menu_js();
 7168:         $result.=&modal_window();
 7169:         $result.=&togglebox_script();
 7170:         $result.=&wishlist_window();
 7171:         $result.=&LCprogressbarUpdate_script();
 7172:     } else {
 7173:         if ($args->{'add_modal'}) {
 7174:            $result.=&modal_window();
 7175:         }
 7176:         if ($args->{'add_wishlist'}) {
 7177:            $result.=&wishlist_window();
 7178:         }
 7179:         if ($args->{'add_togglebox'}) {
 7180:            $result.=&togglebox_script();
 7181:         }
 7182:         if ($args->{'add_progressbar'}) {
 7183:            $result.=&LCprogressbarUpdate_script();
 7184:         }
 7185:     }
 7186:     if (ref($args->{'redirect'})) {
 7187: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7188: 	$url = &Apache::lonenc::check_encrypt($url);
 7189: 	if (!$inhibit_continue) {
 7190: 	    $env{'internal.head.redirect'} = $url;
 7191: 	}
 7192: 	$result.=<<ADDMETA
 7193: <meta http-equiv="pragma" content="no-cache" />
 7194: <meta http-equiv="Refresh" content="$time; url=$url" />
 7195: ADDMETA
 7196:     }
 7197:     if (!defined($title)) {
 7198: 	$title = 'The LearningOnline Network with CAPA';
 7199:     }
 7200:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7201:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7202: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 7203:         .$inhibitprint
 7204: 	.$head_extra;
 7205:     return $result.'</head>';
 7206: }
 7207: 
 7208: =pod
 7209: 
 7210: =item * &font_settings()
 7211: 
 7212: Returns neccessary <meta> to set the proper encoding
 7213: 
 7214: Inputs: none
 7215: 
 7216: =cut
 7217: 
 7218: sub font_settings {
 7219:     my $headerstring='';
 7220:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 7221: 	$headerstring.=
 7222: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 7223:     }
 7224:     return $headerstring;
 7225: }
 7226: 
 7227: =pod
 7228: 
 7229: =item * &print_suppression()
 7230: 
 7231: In course context returns css which causes the body to be blank when media="print",
 7232: if printout generation is unavailable for the current resource.
 7233: 
 7234: This could be because:
 7235: 
 7236: (a) printstartdate is in the future
 7237: 
 7238: (b) printenddate is in the past
 7239: 
 7240: (c) there is an active exam block with "printout"
 7241: functionality blocked
 7242: 
 7243: Users with pav, pfo or evb privileges are exempt.
 7244: 
 7245: Inputs: none
 7246: 
 7247: =cut
 7248: 
 7249: 
 7250: sub print_suppression {
 7251:     my $noprint;
 7252:     if ($env{'request.course.id'}) {
 7253:         my $scope = $env{'request.course.id'};
 7254:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7255:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7256:             return;
 7257:         }
 7258:         if ($env{'request.course.sec'} ne '') {
 7259:             $scope .= "/$env{'request.course.sec'}";
 7260:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7261:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7262:                 return;
 7263:             }
 7264:         }
 7265:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7266:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7267:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7268:         if ($blocked) {
 7269:             my $checkrole = "cm./$cdom/$cnum";
 7270:             if ($env{'request.course.sec'} ne '') {
 7271:                 $checkrole .= "/$env{'request.course.sec'}";
 7272:             }
 7273:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7274:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7275:                 $noprint = 1;
 7276:             }
 7277:         }
 7278:         unless ($noprint) {
 7279:             my $symb = &Apache::lonnet::symbread();
 7280:             if ($symb ne '') {
 7281:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7282:                 if (ref($navmap)) {
 7283:                     my $res = $navmap->getBySymb($symb);
 7284:                     if (ref($res)) {
 7285:                         if (!$res->resprintable()) {
 7286:                             $noprint = 1;
 7287:                         }
 7288:                     }
 7289:                 }
 7290:             }
 7291:         }
 7292:         if ($noprint) {
 7293:             return <<"ENDSTYLE";
 7294: <style type="text/css" media="print">
 7295:     body { display:none }
 7296: </style>
 7297: ENDSTYLE
 7298:         }
 7299:     }
 7300:     return;
 7301: }
 7302: 
 7303: =pod
 7304: 
 7305: =item * &xml_begin()
 7306: 
 7307: Returns the needed doctype and <html>
 7308: 
 7309: Inputs: none
 7310: 
 7311: =cut
 7312: 
 7313: sub xml_begin {
 7314:     my $output='';
 7315: 
 7316:     if ($env{'browser.mathml'}) {
 7317: 	$output='<?xml version="1.0"?>'
 7318:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7319: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7320:             
 7321: #	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
 7322: 	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
 7323:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7324: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7325:     } else {
 7326: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 7327:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 7328:     }
 7329:     return $output;
 7330: }
 7331: 
 7332: =pod
 7333: 
 7334: =item * &start_page()
 7335: 
 7336: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7337: 
 7338: Inputs:
 7339: 
 7340: =over 4
 7341: 
 7342: $title - optional title for the page
 7343: 
 7344: $head_extra - optional extra HTML to incude inside the <head>
 7345: 
 7346: $args - additional optional args supported are:
 7347: 
 7348: =over 8
 7349: 
 7350:              only_body      -> is true will set &bodytag() onlybodytag
 7351:                                     arg on
 7352:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7353:              add_entries    -> additional attributes to add to the  <body>
 7354:              domain         -> force to color decorate a page for a 
 7355:                                     specific domain
 7356:              function       -> force usage of a specific rolish color
 7357:                                     scheme
 7358:              redirect       -> see &headtag()
 7359:              bgcolor        -> override the default page bg color
 7360:              js_ready       -> return a string ready for being used in 
 7361:                                     a javascript writeln
 7362:              html_encode    -> return a string ready for being used in 
 7363:                                     a html attribute
 7364:              force_register -> if is true will turn on the &bodytag()
 7365:                                     $forcereg arg
 7366:              frameset       -> if true will start with a <frameset>
 7367:                                     rather than <body>
 7368:              skip_phases    -> hash ref of 
 7369:                                     head -> skip the <html><head> generation
 7370:                                     body -> skip all <body> generation
 7371:              no_auto_mt_title -> prevent &mt()ing the title arg
 7372:              inherit_jsmath -> when creating popup window in a page,
 7373:                                     should it have jsmath forced on by the
 7374:                                     current page
 7375:              bread_crumbs ->             Array containing breadcrumbs
 7376:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7377: 
 7378: =back
 7379: 
 7380: =back
 7381: 
 7382: =cut
 7383: 
 7384: sub start_page {
 7385:     my ($title,$head_extra,$args) = @_;
 7386:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7387: 
 7388:     $env{'internal.start_page'}++;
 7389:     my $result;
 7390: 
 7391:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7392:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 7393:     }
 7394:     
 7395:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7396: 	if ($args->{'frameset'}) {
 7397: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7398: 						$args->{'add_entries'});
 7399: 	    $result .= "\n<frameset $attr_string>\n";
 7400:         } else {
 7401:             $result .=
 7402:                 &bodytag($title, 
 7403:                          $args->{'function'},       $args->{'add_entries'},
 7404:                          $args->{'only_body'},      $args->{'domain'},
 7405:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7406:                          $args->{'bgcolor'},        $args);
 7407:         }
 7408:     }
 7409: 
 7410:     if ($args->{'js_ready'}) {
 7411: 		$result = &js_ready($result);
 7412:     }
 7413:     if ($args->{'html_encode'}) {
 7414: 		$result = &html_encode($result);
 7415:     }
 7416: 
 7417:     # Preparation for new and consistent functionlist at top of screen
 7418:     # if ($args->{'functionlist'}) {
 7419:     #            $result .= &build_functionlist();
 7420:     #}
 7421: 
 7422:     # Don't add anything more if only_body wanted or in const space
 7423:     return $result if    $args->{'only_body'} 
 7424:                       || $env{'request.state'} eq 'construct';
 7425: 
 7426:     #Breadcrumbs
 7427:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7428: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7429: 		#if any br links exists, add them to the breadcrumbs
 7430: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7431: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7432: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7433: 			}
 7434: 		}
 7435: 
 7436: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7437: 		if(exists($args->{'bread_crumbs_component'})){
 7438: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7439: 		}else{
 7440: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7441: 		}
 7442:     }
 7443:     return $result;
 7444: }
 7445: 
 7446: sub end_page {
 7447:     my ($args) = @_;
 7448:     $env{'internal.end_page'}++;
 7449:     my $result;
 7450:     if ($args->{'discussion'}) {
 7451: 	my ($target,$parser);
 7452: 	if (ref($args->{'discussion'})) {
 7453: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7454: 				$args->{'discussion'}{'parser'});
 7455: 	}
 7456: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7457:     }
 7458:     if ($args->{'frameset'}) {
 7459: 	$result .= '</frameset>';
 7460:     } else {
 7461: 	$result .= &endbodytag($args);
 7462:     }
 7463:     unless ($args->{'notbody'}) {
 7464:         $result .= "\n</html>";
 7465:     }
 7466: 
 7467:     if ($args->{'js_ready'}) {
 7468: 	$result = &js_ready($result);
 7469:     }
 7470: 
 7471:     if ($args->{'html_encode'}) {
 7472: 	$result = &html_encode($result);
 7473:     }
 7474: 
 7475:     return $result;
 7476: }
 7477: 
 7478: sub wishlist_window {
 7479:     return(<<'ENDWISHLIST');
 7480: <script type="text/javascript">
 7481: // <![CDATA[
 7482: // <!-- BEGIN LON-CAPA Internal
 7483: function set_wishlistlink(title, path) {
 7484:     if (!title) {
 7485:         title = document.title;
 7486:         title = title.replace(/^LON-CAPA /,'');
 7487:     }
 7488:     if (!path) {
 7489:         path = location.pathname;
 7490:     }
 7491:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7492:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7493: }
 7494: // END LON-CAPA Internal -->
 7495: // ]]>
 7496: </script>
 7497: ENDWISHLIST
 7498: }
 7499: 
 7500: sub modal_window {
 7501:     return(<<'ENDMODAL');
 7502: <script type="text/javascript">
 7503: // <![CDATA[
 7504: // <!-- BEGIN LON-CAPA Internal
 7505: var modalWindow = {
 7506: 	parent:"body",
 7507: 	windowId:null,
 7508: 	content:null,
 7509: 	width:null,
 7510: 	height:null,
 7511: 	close:function()
 7512: 	{
 7513: 	        $(".LCmodal-window").remove();
 7514: 	        $(".LCmodal-overlay").remove();
 7515: 	},
 7516: 	open:function()
 7517: 	{
 7518: 		var modal = "";
 7519: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7520: 		modal += "<div id=\"" + this.windowId + "\" class=\"LCmodal-window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";
 7521: 		modal += this.content;
 7522: 		modal += "</div>";	
 7523: 
 7524: 		$(this.parent).append(modal);
 7525: 
 7526: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7527: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7528: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7529: 	}
 7530: };
 7531: 	var openMyModal = function(source,width,height,scrolling)
 7532: 	{
 7533: 		modalWindow.windowId = "myModal";
 7534: 		modalWindow.width = width;
 7535: 		modalWindow.height = height;
 7536: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
 7537: 		modalWindow.open();
 7538: 	};	
 7539: // END LON-CAPA Internal -->
 7540: // ]]>
 7541: </script>
 7542: ENDMODAL
 7543: }
 7544: 
 7545: sub modal_link {
 7546:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
 7547:     unless ($width) { $width=480; }
 7548:     unless ($height) { $height=400; }
 7549:     unless ($scrolling) { $scrolling='yes'; }
 7550:     my $target_attr;
 7551:     if (defined($target)) {
 7552:         $target_attr = 'target="'.$target.'"';
 7553:     }
 7554:     return <<"ENDLINK";
 7555: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
 7556:            $linktext</a>
 7557: ENDLINK
 7558: }
 7559: 
 7560: sub modal_adhoc_script {
 7561:     my ($funcname,$width,$height,$content)=@_;
 7562:     return (<<ENDADHOC);
 7563: <script type="text/javascript">
 7564: // <![CDATA[
 7565:         var $funcname = function()
 7566:         {
 7567:                 modalWindow.windowId = "myModal";
 7568:                 modalWindow.width = $width;
 7569:                 modalWindow.height = $height;
 7570:                 modalWindow.content = '$content';
 7571:                 modalWindow.open();
 7572:         };  
 7573: // ]]>
 7574: </script>
 7575: ENDADHOC
 7576: }
 7577: 
 7578: sub modal_adhoc_inner {
 7579:     my ($funcname,$width,$height,$content)=@_;
 7580:     my $innerwidth=$width-20;
 7581:     $content=&js_ready(
 7582:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7583:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
 7584:                     $content.
 7585:                  &end_scrollbox().
 7586:                &end_page()
 7587:              );
 7588:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7589: }
 7590: 
 7591: sub modal_adhoc_window {
 7592:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7593:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7594:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7595: }
 7596: 
 7597: sub modal_adhoc_launch {
 7598:     my ($funcname,$width,$height,$content)=@_;
 7599:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7600: <script type="text/javascript">
 7601: // <![CDATA[
 7602: $funcname();
 7603: // ]]>
 7604: </script>
 7605: ENDLAUNCH
 7606: }
 7607: 
 7608: sub modal_adhoc_close {
 7609:     return (<<ENDCLOSE);
 7610: <script type="text/javascript">
 7611: // <![CDATA[
 7612: modalWindow.close();
 7613: // ]]>
 7614: </script>
 7615: ENDCLOSE
 7616: }
 7617: 
 7618: sub togglebox_script {
 7619:    return(<<ENDTOGGLE);
 7620: <script type="text/javascript"> 
 7621: // <![CDATA[
 7622: function LCtoggleDisplay(id,hidetext,showtext) {
 7623:    link = document.getElementById(id + "link").childNodes[0];
 7624:    with (document.getElementById(id).style) {
 7625:       if (display == "none" ) {
 7626:           display = "inline";
 7627:           link.nodeValue = hidetext;
 7628:         } else {
 7629:           display = "none";
 7630:           link.nodeValue = showtext;
 7631:        }
 7632:    }
 7633: }
 7634: // ]]>
 7635: </script>
 7636: ENDTOGGLE
 7637: }
 7638: 
 7639: sub start_togglebox {
 7640:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7641:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7642:     unless ($showtext) { $showtext=&mt('show'); }
 7643:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7644:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7645:     return &start_data_table().
 7646:            &start_data_table_header_row().
 7647:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7648:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7649:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7650:            &end_data_table_header_row().
 7651:            '<tr id="'.$id.'" style="display:none""><td>';
 7652: }
 7653: 
 7654: sub end_togglebox {
 7655:     return '</td></tr>'.&end_data_table();
 7656: }
 7657: 
 7658: sub LCprogressbar_script {
 7659:    my ($id)=@_;
 7660:    return(<<ENDPROGRESS);
 7661: <script type="text/javascript">
 7662: // <![CDATA[
 7663: \$('#progressbar$id').progressbar({
 7664:   value: 0,
 7665:   change: function(event, ui) {
 7666:     var newVal = \$(this).progressbar('option', 'value');
 7667:     \$('.pblabel', this).text(LCprogressTxt);
 7668:   }
 7669: });
 7670: // ]]>
 7671: </script>
 7672: ENDPROGRESS
 7673: }
 7674: 
 7675: sub LCprogressbarUpdate_script {
 7676:    return(<<ENDPROGRESSUPDATE);
 7677: <style type="text/css">
 7678: .ui-progressbar { position:relative; }
 7679: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7680: </style>
 7681: <script type="text/javascript">
 7682: // <![CDATA[
 7683: var LCprogressTxt='---';
 7684: 
 7685: function LCupdateProgress(percent,progresstext,id) {
 7686:    LCprogressTxt=progresstext;
 7687:    \$('#progressbar'+id).progressbar('value',percent);
 7688: }
 7689: // ]]>
 7690: </script>
 7691: ENDPROGRESSUPDATE
 7692: }
 7693: 
 7694: my $LClastpercent;
 7695: my $LCidcnt;
 7696: my $LCcurrentid;
 7697: 
 7698: sub LCprogressbar {
 7699:     my ($r)=(@_);
 7700:     $LClastpercent=0;
 7701:     $LCidcnt++;
 7702:     $LCcurrentid=$$.'_'.$LCidcnt;
 7703:     my $starting=&mt('Starting');
 7704:     my $content=(<<ENDPROGBAR);
 7705: <p>
 7706:   <div id="progressbar$LCcurrentid">
 7707:     <span class="pblabel">$starting</span>
 7708:   </div>
 7709: </p>
 7710: ENDPROGBAR
 7711:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7712: }
 7713: 
 7714: sub LCprogressbarUpdate {
 7715:     my ($r,$val,$text)=@_;
 7716:     unless ($val) { 
 7717:        if ($LClastpercent) {
 7718:            $val=$LClastpercent;
 7719:        } else {
 7720:            $val=0;
 7721:        }
 7722:     }
 7723:     if ($val<0) { $val=0; }
 7724:     if ($val>100) { $val=0; }
 7725:     $LClastpercent=$val;
 7726:     unless ($text) { $text=$val.'%'; }
 7727:     $text=&js_ready($text);
 7728:     &r_print($r,<<ENDUPDATE);
 7729: <script type="text/javascript">
 7730: // <![CDATA[
 7731: LCupdateProgress($val,'$text','$LCcurrentid');
 7732: // ]]>
 7733: </script>
 7734: ENDUPDATE
 7735: }
 7736: 
 7737: sub LCprogressbarClose {
 7738:     my ($r)=@_;
 7739:     $LClastpercent=0;
 7740:     &r_print($r,<<ENDCLOSE);
 7741: <script type="text/javascript">
 7742: // <![CDATA[
 7743: \$("#progressbar$LCcurrentid").hide('slow'); 
 7744: // ]]>
 7745: </script>
 7746: ENDCLOSE
 7747: }
 7748: 
 7749: sub r_print {
 7750:     my ($r,$to_print)=@_;
 7751:     if ($r) {
 7752:       $r->print($to_print);
 7753:       $r->rflush();
 7754:     } else {
 7755:       print($to_print);
 7756:     }
 7757: }
 7758: 
 7759: sub html_encode {
 7760:     my ($result) = @_;
 7761: 
 7762:     $result = &HTML::Entities::encode($result,'<>&"');
 7763:     
 7764:     return $result;
 7765: }
 7766: 
 7767: sub js_ready {
 7768:     my ($result) = @_;
 7769: 
 7770:     $result =~ s/[\n\r]/ /xmsg;
 7771:     $result =~ s/\\/\\\\/xmsg;
 7772:     $result =~ s/'/\\'/xmsg;
 7773:     $result =~ s{</}{<\\/}xmsg;
 7774:     
 7775:     return $result;
 7776: }
 7777: 
 7778: sub validate_page {
 7779:     if (  exists($env{'internal.start_page'})
 7780: 	  &&     $env{'internal.start_page'} > 1) {
 7781: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7782: 				 $env{'internal.start_page'}.' '.
 7783: 				 $ENV{'request.filename'});
 7784:     }
 7785:     if (  exists($env{'internal.end_page'})
 7786: 	  &&     $env{'internal.end_page'} > 1) {
 7787: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7788: 				 $env{'internal.end_page'}.' '.
 7789: 				 $env{'request.filename'});
 7790:     }
 7791:     if (     exists($env{'internal.start_page'})
 7792: 	&& ! exists($env{'internal.end_page'})) {
 7793: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7794: 				 $env{'request.filename'});
 7795:     }
 7796:     if (   ! exists($env{'internal.start_page'})
 7797: 	&&   exists($env{'internal.end_page'})) {
 7798: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7799: 				 $env{'request.filename'});
 7800:     }
 7801: }
 7802: 
 7803: 
 7804: sub start_scrollbox {
 7805:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
 7806:     unless ($outerwidth) { $outerwidth='520px'; }
 7807:     unless ($width) { $width='500px'; }
 7808:     unless ($height) { $height='200px'; }
 7809:     my ($table_id,$div_id,$tdcol);
 7810:     if ($id ne '') {
 7811:         $table_id = " id='table_$id'";
 7812:         $div_id = " id='div_$id'";
 7813:     }
 7814:     if ($bgcolor ne '') {
 7815:         $tdcol = "background-color: $bgcolor;";
 7816:     }
 7817:     return <<"END";
 7818: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol"><div style="overflow:auto; width:$width; height: $height;"$div_id>
 7819: END
 7820: }
 7821: 
 7822: sub end_scrollbox {
 7823:     return '</div></td></tr></table>';
 7824: }
 7825: 
 7826: sub simple_error_page {
 7827:     my ($r,$title,$msg) = @_;
 7828:     my $page =
 7829: 	&Apache::loncommon::start_page($title).
 7830: 	&mt($msg).
 7831: 	&Apache::loncommon::end_page();
 7832:     if (ref($r)) {
 7833: 	$r->print($page);
 7834: 	return;
 7835:     }
 7836:     return $page;
 7837: }
 7838: 
 7839: {
 7840:     my @row_count;
 7841: 
 7842:     sub start_data_table_count {
 7843:         unshift(@row_count, 0);
 7844:         return;
 7845:     }
 7846: 
 7847:     sub end_data_table_count {
 7848:         shift(@row_count);
 7849:         return;
 7850:     }
 7851: 
 7852:     sub start_data_table {
 7853: 	my ($add_class,$id) = @_;
 7854: 	my $css_class = (join(' ','LC_data_table',$add_class));
 7855:         my $table_id;
 7856:         if (defined($id)) {
 7857:             $table_id = ' id="'.$id.'"';
 7858:         }
 7859: 	&start_data_table_count();
 7860: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 7861:     }
 7862: 
 7863:     sub end_data_table {
 7864: 	&end_data_table_count();
 7865: 	return '</table>'."\n";;
 7866:     }
 7867: 
 7868:     sub start_data_table_row {
 7869: 	my ($add_class, $id) = @_;
 7870: 	$row_count[0]++;
 7871: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7872: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7873:         $id = (' id="'.$id.'"') unless ($id eq '');
 7874:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7875:     }
 7876:     
 7877:     sub continue_data_table_row {
 7878: 	my ($add_class, $id) = @_;
 7879: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7880: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7881:         $id = (' id="'.$id.'"') unless ($id eq '');
 7882:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7883:     }
 7884: 
 7885:     sub end_data_table_row {
 7886: 	return '</tr>'."\n";;
 7887:     }
 7888: 
 7889:     sub start_data_table_empty_row {
 7890: #	$row_count[0]++;
 7891: 	return  '<tr class="LC_empty_row" >'."\n";;
 7892:     }
 7893: 
 7894:     sub end_data_table_empty_row {
 7895: 	return '</tr>'."\n";;
 7896:     }
 7897: 
 7898:     sub start_data_table_header_row {
 7899: 	return  '<tr class="LC_header_row">'."\n";;
 7900:     }
 7901: 
 7902:     sub end_data_table_header_row {
 7903: 	return '</tr>'."\n";;
 7904:     }
 7905: 
 7906:     sub data_table_caption {
 7907:         my $caption = shift;
 7908:         return "<caption class=\"LC_caption\">$caption</caption>";
 7909:     }
 7910: }
 7911: 
 7912: =pod
 7913: 
 7914: =item * &inhibit_menu_check($arg)
 7915: 
 7916: Checks for a inhibitmenu state and generates output to preserve it
 7917: 
 7918: Inputs:         $arg - can be any of
 7919:                      - undef - in which case the return value is a string 
 7920:                                to add  into arguments list of a uri
 7921:                      - 'input' - in which case the return value is a HTML
 7922:                                  <form> <input> field of type hidden to
 7923:                                  preserve the value
 7924:                      - a url - in which case the return value is the url with
 7925:                                the neccesary cgi args added to preserve the
 7926:                                inhibitmenu state
 7927:                      - a ref to a url - no return value, but the string is
 7928:                                         updated to include the neccessary cgi
 7929:                                         args to preserve the inhibitmenu state
 7930: 
 7931: =cut
 7932: 
 7933: sub inhibit_menu_check {
 7934:     my ($arg) = @_;
 7935:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 7936:     if ($arg eq 'input') {
 7937: 	if ($env{'form.inhibitmenu'}) {
 7938: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 7939: 	} else {
 7940: 	    return
 7941: 	}
 7942:     }
 7943:     if ($env{'form.inhibitmenu'}) {
 7944: 	if (ref($arg)) {
 7945: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7946: 	} elsif ($arg eq '') {
 7947: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 7948: 	} else {
 7949: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7950: 	}
 7951:     }
 7952:     if (!ref($arg)) {
 7953: 	return $arg;
 7954:     }
 7955: }
 7956: 
 7957: ###############################################
 7958: 
 7959: =pod
 7960: 
 7961: =back
 7962: 
 7963: =head1 User Information Routines
 7964: 
 7965: =over 4
 7966: 
 7967: =item * &get_users_function()
 7968: 
 7969: Used by &bodytag to determine the current users primary role.
 7970: Returns either 'student','coordinator','admin', or 'author'.
 7971: 
 7972: =cut
 7973: 
 7974: ###############################################
 7975: sub get_users_function {
 7976:     my $function = 'norole';
 7977:     if ($env{'request.role'}=~/^(st)/) {
 7978:         $function='student';
 7979:     }
 7980:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 7981:         $function='coordinator';
 7982:     }
 7983:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 7984:         $function='admin';
 7985:     }
 7986:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 7987:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 7988:         $function='author';
 7989:     }
 7990:     return $function;
 7991: }
 7992: 
 7993: ###############################################
 7994: 
 7995: =pod
 7996: 
 7997: =item * &show_course()
 7998: 
 7999: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8000: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8001: 
 8002: Inputs:
 8003: None
 8004: 
 8005: Outputs:
 8006: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8007: 
 8008: =cut
 8009: 
 8010: ###############################################
 8011: sub show_course {
 8012:     my $course = !$env{'user.adv'};
 8013:     if (!$env{'user.adv'}) {
 8014:         foreach my $env (keys(%env)) {
 8015:             next if ($env !~ m/^user\.priv\./);
 8016:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8017:                 $course = 0;
 8018:                 last;
 8019:             }
 8020:         }
 8021:     }
 8022:     return $course;
 8023: }
 8024: 
 8025: ###############################################
 8026: 
 8027: =pod
 8028: 
 8029: =item * &check_user_status()
 8030: 
 8031: Determines current status of supplied role for a
 8032: specific user. Roles can be active, previous or future.
 8033: 
 8034: Inputs: 
 8035: user's domain, user's username, course's domain,
 8036: course's number, optional section ID.
 8037: 
 8038: Outputs:
 8039: role status: active, previous or future. 
 8040: 
 8041: =cut
 8042: 
 8043: sub check_user_status {
 8044:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8045:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8046:     my @uroles = keys %userinfo;
 8047:     my $srchstr;
 8048:     my $active_chk = 'none';
 8049:     my $now = time;
 8050:     if (@uroles > 0) {
 8051:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8052:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8053:         } else {
 8054:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8055:         }
 8056:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8057:             my $role_end = 0;
 8058:             my $role_start = 0;
 8059:             $active_chk = 'active';
 8060:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8061:                 $role_end = $1;
 8062:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8063:                     $role_start = $1;
 8064:                 }
 8065:             }
 8066:             if ($role_start > 0) {
 8067:                 if ($now < $role_start) {
 8068:                     $active_chk = 'future';
 8069:                 }
 8070:             }
 8071:             if ($role_end > 0) {
 8072:                 if ($now > $role_end) {
 8073:                     $active_chk = 'previous';
 8074:                 }
 8075:             }
 8076:         }
 8077:     }
 8078:     return $active_chk;
 8079: }
 8080: 
 8081: ###############################################
 8082: 
 8083: =pod
 8084: 
 8085: =item * &get_sections()
 8086: 
 8087: Determines all the sections for a course including
 8088: sections with students and sections containing other roles.
 8089: Incoming parameters: 
 8090: 
 8091: 1. domain
 8092: 2. course number 
 8093: 3. reference to array containing roles for which sections should 
 8094: be gathered (optional).
 8095: 4. reference to array containing status types for which sections 
 8096: should be gathered (optional).
 8097: 
 8098: If the third argument is undefined, sections are gathered for any role. 
 8099: If the fourth argument is undefined, sections are gathered for any status.
 8100: Permissible values are 'active' or 'future' or 'previous'.
 8101:  
 8102: Returns section hash (keys are section IDs, values are
 8103: number of users in each section), subject to the
 8104: optional roles filter, optional status filter 
 8105: 
 8106: =cut
 8107: 
 8108: ###############################################
 8109: sub get_sections {
 8110:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8111:     if (!defined($cdom) || !defined($cnum)) {
 8112:         my $cid =  $env{'request.course.id'};
 8113: 
 8114: 	return if (!defined($cid));
 8115: 
 8116:         $cdom = $env{'course.'.$cid.'.domain'};
 8117:         $cnum = $env{'course.'.$cid.'.num'};
 8118:     }
 8119: 
 8120:     my %sectioncount;
 8121:     my $now = time;
 8122: 
 8123:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 8124: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8125: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8126: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8127:         my $start_index = &Apache::loncoursedata::CL_START();
 8128:         my $end_index = &Apache::loncoursedata::CL_END();
 8129:         my $status;
 8130: 	while (my ($student,$data) = each(%$classlist)) {
 8131: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8132: 				                     $data->[$status_index],
 8133:                                                      $data->[$start_index],
 8134:                                                      $data->[$end_index]);
 8135:             if ($stu_status eq 'Active') {
 8136:                 $status = 'active';
 8137:             } elsif ($end < $now) {
 8138:                 $status = 'previous';
 8139:             } elsif ($start > $now) {
 8140:                 $status = 'future';
 8141:             } 
 8142: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8143:                 if ((!defined($possible_status)) || (($status ne '') && 
 8144:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8145: 		    $sectioncount{$section}++;
 8146:                 }
 8147: 	    }
 8148: 	}
 8149:     }
 8150:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8151:     foreach my $user (sort(keys(%courseroles))) {
 8152: 	if ($user !~ /^(\w{2})/) { next; }
 8153: 	my ($role) = ($user =~ /^(\w{2})/);
 8154: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8155: 	my ($section,$status);
 8156: 	if ($role eq 'cr' &&
 8157: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8158: 	    $section=$1;
 8159: 	}
 8160: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8161: 	if (!defined($section) || $section eq '-1') { next; }
 8162:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8163:         if ($end == -1 && $start == -1) {
 8164:             next; #deleted role
 8165:         }
 8166:         if (!defined($possible_status)) { 
 8167:             $sectioncount{$section}++;
 8168:         } else {
 8169:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8170:                 $status = 'active';
 8171:             } elsif ($end < $now) {
 8172:                 $status = 'future';
 8173:             } elsif ($start > $now) {
 8174:                 $status = 'previous';
 8175:             }
 8176:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8177:                 $sectioncount{$section}++;
 8178:             }
 8179:         }
 8180:     }
 8181:     return %sectioncount;
 8182: }
 8183: 
 8184: ###############################################
 8185: 
 8186: =pod
 8187: 
 8188: =item * &get_course_users()
 8189: 
 8190: Retrieves usernames:domains for users in the specified course
 8191: with specific role(s), and access status. 
 8192: 
 8193: Incoming parameters:
 8194: 1. course domain
 8195: 2. course number
 8196: 3. access status: users must have - either active, 
 8197: previous, future, or all.
 8198: 4. reference to array of permissible roles
 8199: 5. reference to array of section restrictions (optional)
 8200: 6. reference to results object (hash of hashes).
 8201: 7. reference to optional userdata hash
 8202: 8. reference to optional statushash
 8203: 9. flag if privileged users (except those set to unhide in
 8204:    course settings) should be excluded    
 8205: Keys of top level results hash are roles.
 8206: Keys of inner hashes are username:domain, with 
 8207: values set to access type.
 8208: Optional userdata hash returns an array with arguments in the 
 8209: same order as loncoursedata::get_classlist() for student data.
 8210: 
 8211: Optional statushash returns
 8212: 
 8213: Entries for end, start, section and status are blank because
 8214: of the possibility of multiple values for non-student roles.
 8215: 
 8216: =cut
 8217: 
 8218: ###############################################
 8219: 
 8220: sub get_course_users {
 8221:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8222:     my %idx = ();
 8223:     my %seclists;
 8224: 
 8225:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8226:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8227:     $idx{end} = &Apache::loncoursedata::CL_END();
 8228:     $idx{start} = &Apache::loncoursedata::CL_START();
 8229:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8230:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8231:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8232:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8233: 
 8234:     if (grep(/^st$/,@{$roles})) {
 8235:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8236:         my $now = time;
 8237:         foreach my $student (keys(%{$classlist})) {
 8238:             my $match = 0;
 8239:             my $secmatch = 0;
 8240:             my $section = $$classlist{$student}[$idx{section}];
 8241:             my $status = $$classlist{$student}[$idx{status}];
 8242:             if ($section eq '') {
 8243:                 $section = 'none';
 8244:             }
 8245:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8246:                 if (grep(/^all$/,@{$sections})) {
 8247:                     $secmatch = 1;
 8248:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8249:                     if (grep(/^none$/,@{$sections})) {
 8250:                         $secmatch = 1;
 8251:                     }
 8252:                 } else {  
 8253: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8254: 		        $secmatch = 1;
 8255:                     }
 8256: 		}
 8257:                 if (!$secmatch) {
 8258:                     next;
 8259:                 }
 8260:             }
 8261:             if (defined($$types{'active'})) {
 8262:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8263:                     push(@{$$users{st}{$student}},'active');
 8264:                     $match = 1;
 8265:                 }
 8266:             }
 8267:             if (defined($$types{'previous'})) {
 8268:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8269:                     push(@{$$users{st}{$student}},'previous');
 8270:                     $match = 1;
 8271:                 }
 8272:             }
 8273:             if (defined($$types{'future'})) {
 8274:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8275:                     push(@{$$users{st}{$student}},'future');
 8276:                     $match = 1;
 8277:                 }
 8278:             }
 8279:             if ($match) {
 8280:                 push(@{$seclists{$student}},$section);
 8281:                 if (ref($userdata) eq 'HASH') {
 8282:                     $$userdata{$student} = $$classlist{$student};
 8283:                 }
 8284:                 if (ref($statushash) eq 'HASH') {
 8285:                     $statushash->{$student}{'st'}{$section} = $status;
 8286:                 }
 8287:             }
 8288:         }
 8289:     }
 8290:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8291:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8292:         my $now = time;
 8293:         my %displaystatus = ( previous => 'Expired',
 8294:                               active   => 'Active',
 8295:                               future   => 'Future',
 8296:                             );
 8297:         my %nothide;
 8298:         if ($hidepriv) {
 8299:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8300:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8301:                 if ($user !~ /:/) {
 8302:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8303:                 } else {
 8304:                     $nothide{$user} = 1;
 8305:                 }
 8306:             }
 8307:         }
 8308:         foreach my $person (sort(keys(%coursepersonnel))) {
 8309:             my $match = 0;
 8310:             my $secmatch = 0;
 8311:             my $status;
 8312:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8313:             $user =~ s/:$//;
 8314:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8315:             if ($end == -1 || $start == -1) {
 8316:                 next;
 8317:             }
 8318:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8319:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8320:                 my ($uname,$udom) = split(/:/,$user);
 8321:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8322:                     if (grep(/^all$/,@{$sections})) {
 8323:                         $secmatch = 1;
 8324:                     } elsif ($usec eq '') {
 8325:                         if (grep(/^none$/,@{$sections})) {
 8326:                             $secmatch = 1;
 8327:                         }
 8328:                     } else {
 8329:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8330:                             $secmatch = 1;
 8331:                         }
 8332:                     }
 8333:                     if (!$secmatch) {
 8334:                         next;
 8335:                     }
 8336:                 }
 8337:                 if ($usec eq '') {
 8338:                     $usec = 'none';
 8339:                 }
 8340:                 if ($uname ne '' && $udom ne '') {
 8341:                     if ($hidepriv) {
 8342:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 8343:                             (!$nothide{$uname.':'.$udom})) {
 8344:                             next;
 8345:                         }
 8346:                     }
 8347:                     if ($end > 0 && $end < $now) {
 8348:                         $status = 'previous';
 8349:                     } elsif ($start > $now) {
 8350:                         $status = 'future';
 8351:                     } else {
 8352:                         $status = 'active';
 8353:                     }
 8354:                     foreach my $type (keys(%{$types})) { 
 8355:                         if ($status eq $type) {
 8356:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8357:                                 push(@{$$users{$role}{$user}},$type);
 8358:                             }
 8359:                             $match = 1;
 8360:                         }
 8361:                     }
 8362:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8363:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8364: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8365:                         }
 8366:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8367:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8368:                         }
 8369:                         if (ref($statushash) eq 'HASH') {
 8370:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8371:                         }
 8372:                     }
 8373:                 }
 8374:             }
 8375:         }
 8376:         if (grep(/^ow$/,@{$roles})) {
 8377:             if ((defined($cdom)) && (defined($cnum))) {
 8378:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8379:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8380:                     my $owner = $csettings{'internal.courseowner'};
 8381:                     next if ($owner eq '');
 8382:                     my ($ownername,$ownerdom);
 8383:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8384:                         $ownername = $1;
 8385:                         $ownerdom = $2;
 8386:                     } else {
 8387:                         $ownername = $owner;
 8388:                         $ownerdom = $cdom;
 8389:                         $owner = $ownername.':'.$ownerdom;
 8390:                     }
 8391:                     @{$$users{'ow'}{$owner}} = 'any';
 8392:                     if (defined($userdata) && 
 8393: 			!exists($$userdata{$owner})) {
 8394: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8395:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8396:                             push(@{$seclists{$owner}},'none');
 8397:                         }
 8398:                         if (ref($statushash) eq 'HASH') {
 8399:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8400:                         }
 8401: 		    }
 8402:                 }
 8403:             }
 8404:         }
 8405:         foreach my $user (keys(%seclists)) {
 8406:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8407:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8408:         }
 8409:     }
 8410:     return;
 8411: }
 8412: 
 8413: sub get_user_info {
 8414:     my ($udom,$uname,$idx,$userdata) = @_;
 8415:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8416: 	&plainname($uname,$udom,'lastname');
 8417:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8418:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8419:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8420:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8421:     return;
 8422: }
 8423: 
 8424: ###############################################
 8425: 
 8426: =pod
 8427: 
 8428: =item * &get_user_quota()
 8429: 
 8430: Retrieves quota assigned for storage of portfolio files for a user  
 8431: 
 8432: Incoming parameters:
 8433: 1. user's username
 8434: 2. user's domain
 8435: 
 8436: Returns:
 8437: 1. Disk quota (in Mb) assigned to student.
 8438: 2. (Optional) Type of setting: custom or default
 8439:    (individually assigned or default for user's 
 8440:    institutional status).
 8441: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8442:    or student - types as defined in localenroll::inst_usertypes 
 8443:    for user's domain, which determines default quota for user.
 8444: 4. (Optional) - Default quota which would apply to the user.
 8445: 
 8446: If a value has been stored in the user's environment, 
 8447: it will return that, otherwise it returns the maximal default
 8448: defined for the user's instituional status(es) in the domain.
 8449: 
 8450: =cut
 8451: 
 8452: ###############################################
 8453: 
 8454: 
 8455: sub get_user_quota {
 8456:     my ($uname,$udom) = @_;
 8457:     my ($quota,$quotatype,$settingstatus,$defquota);
 8458:     if (!defined($udom)) {
 8459:         $udom = $env{'user.domain'};
 8460:     }
 8461:     if (!defined($uname)) {
 8462:         $uname = $env{'user.name'};
 8463:     }
 8464:     if (($udom eq '' || $uname eq '') ||
 8465:         ($udom eq 'public') && ($uname eq 'public')) {
 8466:         $quota = 0;
 8467:         $quotatype = 'default';
 8468:         $defquota = 0; 
 8469:     } else {
 8470:         my $inststatus;
 8471:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8472:             $quota = $env{'environment.portfolioquota'};
 8473:             $inststatus = $env{'environment.inststatus'};
 8474:         } else {
 8475:             my %userenv = 
 8476:                 &Apache::lonnet::get('environment',['portfolioquota',
 8477:                                      'inststatus'],$udom,$uname);
 8478:             my ($tmp) = keys(%userenv);
 8479:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8480:                 $quota = $userenv{'portfolioquota'};
 8481:                 $inststatus = $userenv{'inststatus'};
 8482:             } else {
 8483:                 undef(%userenv);
 8484:             }
 8485:         }
 8486:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 8487:         if ($quota eq '') {
 8488:             $quota = $defquota;
 8489:             $quotatype = 'default';
 8490:         } else {
 8491:             $quotatype = 'custom';
 8492:         }
 8493:     }
 8494:     if (wantarray) {
 8495:         return ($quota,$quotatype,$settingstatus,$defquota);
 8496:     } else {
 8497:         return $quota;
 8498:     }
 8499: }
 8500: 
 8501: ###############################################
 8502: 
 8503: =pod
 8504: 
 8505: =item * &default_quota()
 8506: 
 8507: Retrieves default quota assigned for storage of user portfolio files,
 8508: given an (optional) user's institutional status.
 8509: 
 8510: Incoming parameters:
 8511: 1. domain
 8512: 2. (Optional) institutional status(es).  This is a : separated list of 
 8513:    status types (e.g., faculty, staff, student etc.)
 8514:    which apply to the user for whom the default is being retrieved.
 8515:    If the institutional status string in undefined, the domain
 8516:    default quota will be returned. 
 8517: 
 8518: Returns:
 8519: 1. Default disk quota (in Mb) for user portfolios in the domain.
 8520: 2. (Optional) institutional type which determined the value of the
 8521:    default quota.
 8522: 
 8523: If a value has been stored in the domain's configuration db,
 8524: it will return that, otherwise it returns 20 (for backwards 
 8525: compatibility with domains which have not set up a configuration
 8526: db file; the original statically defined portfolio quota was 20 Mb). 
 8527: 
 8528: If the user's status includes multiple types (e.g., staff and student),
 8529: the largest default quota which applies to the user determines the
 8530: default quota returned.
 8531: 
 8532: =back
 8533: 
 8534: =cut
 8535: 
 8536: ###############################################
 8537: 
 8538: 
 8539: sub default_quota {
 8540:     my ($udom,$inststatus) = @_;
 8541:     my ($defquota,$settingstatus);
 8542:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8543:                                             ['quotas'],$udom);
 8544:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8545:         if ($inststatus ne '') {
 8546:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8547:             foreach my $item (@statuses) {
 8548:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8549:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 8550:                         if ($defquota eq '') {
 8551:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8552:                             $settingstatus = $item;
 8553:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 8554:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8555:                             $settingstatus = $item;
 8556:                         }
 8557:                     }
 8558:                 } else {
 8559:                     if ($quotahash{'quotas'}{$item} ne '') {
 8560:                         if ($defquota eq '') {
 8561:                             $defquota = $quotahash{'quotas'}{$item};
 8562:                             $settingstatus = $item;
 8563:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8564:                             $defquota = $quotahash{'quotas'}{$item};
 8565:                             $settingstatus = $item;
 8566:                         }
 8567:                     }
 8568:                 }
 8569:             }
 8570:         }
 8571:         if ($defquota eq '') {
 8572:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8573:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 8574:             } else {
 8575:                 $defquota = $quotahash{'quotas'}{'default'};
 8576:             }
 8577:             $settingstatus = 'default';
 8578:         }
 8579:     } else {
 8580:         $settingstatus = 'default';
 8581:         $defquota = 20;
 8582:     }
 8583:     if (wantarray) {
 8584:         return ($defquota,$settingstatus);
 8585:     } else {
 8586:         return $defquota;
 8587:     }
 8588: }
 8589: 
 8590: sub get_secgrprole_info {
 8591:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8592:     my %sections_count = &get_sections($cdom,$cnum);
 8593:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8594:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8595:     my @groups = sort(keys(%curr_groups));
 8596:     my $allroles = [];
 8597:     my $rolehash;
 8598:     my $accesshash = {
 8599:                      active => 'Currently has access',
 8600:                      future => 'Will have future access',
 8601:                      previous => 'Previously had access',
 8602:                   };
 8603:     if ($needroles) {
 8604:         $rolehash = {'all' => 'all'};
 8605:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8606: 	if (&Apache::lonnet::error(%user_roles)) {
 8607: 	    undef(%user_roles);
 8608: 	}
 8609:         foreach my $item (keys(%user_roles)) {
 8610:             my ($role)=split(/\:/,$item,2);
 8611:             if ($role eq 'cr') { next; }
 8612:             if ($role =~ /^cr/) {
 8613:                 $$rolehash{$role} = (split('/',$role))[3];
 8614:             } else {
 8615:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 8616:             }
 8617:         }
 8618:         foreach my $key (sort(keys(%{$rolehash}))) {
 8619:             push(@{$allroles},$key);
 8620:         }
 8621:         push (@{$allroles},'st');
 8622:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 8623:     }
 8624:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 8625: }
 8626: 
 8627: sub user_picker {
 8628:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 8629:     my $currdom = $dom;
 8630:     my %curr_selected = (
 8631:                         srchin => 'dom',
 8632:                         srchby => 'lastname',
 8633:                       );
 8634:     my $srchterm;
 8635:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 8636:         if ($srch->{'srchby'} ne '') {
 8637:             $curr_selected{'srchby'} = $srch->{'srchby'};
 8638:         }
 8639:         if ($srch->{'srchin'} ne '') {
 8640:             $curr_selected{'srchin'} = $srch->{'srchin'};
 8641:         }
 8642:         if ($srch->{'srchtype'} ne '') {
 8643:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 8644:         }
 8645:         if ($srch->{'srchdomain'} ne '') {
 8646:             $currdom = $srch->{'srchdomain'};
 8647:         }
 8648:         $srchterm = $srch->{'srchterm'};
 8649:     }
 8650:     my %lt=&Apache::lonlocal::texthash(
 8651:                     'usr'       => 'Search criteria',
 8652:                     'doma'      => 'Domain/institution to search',
 8653:                     'uname'     => 'username',
 8654:                     'lastname'  => 'last name',
 8655:                     'lastfirst' => 'last name, first name',
 8656:                     'crs'       => 'in this course',
 8657:                     'dom'       => 'in selected LON-CAPA domain', 
 8658:                     'alc'       => 'all LON-CAPA',
 8659:                     'instd'     => 'in institutional directory for selected domain',
 8660:                     'exact'     => 'is',
 8661:                     'contains'  => 'contains',
 8662:                     'begins'    => 'begins with',
 8663:                     'youm'      => "You must include some text to search for.",
 8664:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 8665:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 8666:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 8667:                     'ymcd'      => "You must choose a domain when using a domain search.",
 8668:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 8669:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 8670:                      'thfo'     => "The following need to be corrected before the search can be run:",
 8671:                                        );
 8672:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 8673:     my $srchinsel = ' <select name="srchin">';
 8674: 
 8675:     my @srchins = ('crs','dom','alc','instd');
 8676: 
 8677:     foreach my $option (@srchins) {
 8678:         # FIXME 'alc' option unavailable until 
 8679:         #       loncreateuser::print_user_query_page()
 8680:         #       has been completed.
 8681:         next if ($option eq 'alc');
 8682:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 8683:         next if ($option eq 'crs' && !$env{'request.course.id'});
 8684:         if ($curr_selected{'srchin'} eq $option) {
 8685:             $srchinsel .= ' 
 8686:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8687:         } else {
 8688:             $srchinsel .= '
 8689:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8690:         }
 8691:     }
 8692:     $srchinsel .= "\n  </select>\n";
 8693: 
 8694:     my $srchbysel =  ' <select name="srchby">';
 8695:     foreach my $option ('lastname','lastfirst','uname') {
 8696:         if ($curr_selected{'srchby'} eq $option) {
 8697:             $srchbysel .= '
 8698:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8699:         } else {
 8700:             $srchbysel .= '
 8701:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8702:          }
 8703:     }
 8704:     $srchbysel .= "\n  </select>\n";
 8705: 
 8706:     my $srchtypesel = ' <select name="srchtype">';
 8707:     foreach my $option ('begins','contains','exact') {
 8708:         if ($curr_selected{'srchtype'} eq $option) {
 8709:             $srchtypesel .= '
 8710:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8711:         } else {
 8712:             $srchtypesel .= '
 8713:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8714:         }
 8715:     }
 8716:     $srchtypesel .= "\n  </select>\n";
 8717: 
 8718:     my ($newuserscript,$new_user_create);
 8719:     my $context_dom = $env{'request.role.domain'};
 8720:     if ($context eq 'requestcrs') {
 8721:         if ($env{'form.coursedom'} ne '') { 
 8722:             $context_dom = $env{'form.coursedom'};
 8723:         }
 8724:     }
 8725:     if ($forcenewuser) {
 8726:         if (ref($srch) eq 'HASH') {
 8727:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 8728:                 if ($cancreate) {
 8729:                     $new_user_create = '<p> <input type="submit" name="forcenew" value="'.&HTML::Entities::encode(&mt('Make new user "[_1]"',$srchterm),'<>&"').'" onclick="javascript:setSearch(\'1\','.$caller.');" /> </p>';
 8730:                 } else {
 8731:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 8732:                     my %usertypetext = (
 8733:                         official   => 'institutional',
 8734:                         unofficial => 'non-institutional',
 8735:                     );
 8736:                     $new_user_create = '<p class="LC_warning">'
 8737:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 8738:                                       .' '
 8739:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 8740:                                           ,'<a href="'.$helplink.'">','</a>')
 8741:                                       .'</p><br />';
 8742:                 }
 8743:             }
 8744:         }
 8745: 
 8746:         $newuserscript = <<"ENDSCRIPT";
 8747: 
 8748: function setSearch(createnew,callingForm) {
 8749:     if (createnew == 1) {
 8750:         for (var i=0; i<callingForm.srchby.length; i++) {
 8751:             if (callingForm.srchby.options[i].value == 'uname') {
 8752:                 callingForm.srchby.selectedIndex = i;
 8753:             }
 8754:         }
 8755:         for (var i=0; i<callingForm.srchin.length; i++) {
 8756:             if ( callingForm.srchin.options[i].value == 'dom') {
 8757: 		callingForm.srchin.selectedIndex = i;
 8758:             }
 8759:         }
 8760:         for (var i=0; i<callingForm.srchtype.length; i++) {
 8761:             if (callingForm.srchtype.options[i].value == 'exact') {
 8762:                 callingForm.srchtype.selectedIndex = i;
 8763:             }
 8764:         }
 8765:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 8766:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 8767:                 callingForm.srchdomain.selectedIndex = i;
 8768:             }
 8769:         }
 8770:     }
 8771: }
 8772: ENDSCRIPT
 8773: 
 8774:     }
 8775: 
 8776:     my $output = <<"END_BLOCK";
 8777: <script type="text/javascript">
 8778: // <![CDATA[
 8779: function validateEntry(callingForm) {
 8780: 
 8781:     var checkok = 1;
 8782:     var srchin;
 8783:     for (var i=0; i<callingForm.srchin.length; i++) {
 8784: 	if ( callingForm.srchin[i].checked ) {
 8785: 	    srchin = callingForm.srchin[i].value;
 8786: 	}
 8787:     }
 8788: 
 8789:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 8790:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 8791:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 8792:     var srchterm =  callingForm.srchterm.value;
 8793:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 8794:     var msg = "";
 8795: 
 8796:     if (srchterm == "") {
 8797:         checkok = 0;
 8798:         msg += "$lt{'youm'}\\n";
 8799:     }
 8800: 
 8801:     if (srchtype== 'begins') {
 8802:         if (srchterm.length < 2) {
 8803:             checkok = 0;
 8804:             msg += "$lt{'thte'}\\n";
 8805:         }
 8806:     }
 8807: 
 8808:     if (srchtype== 'contains') {
 8809:         if (srchterm.length < 3) {
 8810:             checkok = 0;
 8811:             msg += "$lt{'thet'}\\n";
 8812:         }
 8813:     }
 8814:     if (srchin == 'instd') {
 8815:         if (srchdomain == '') {
 8816:             checkok = 0;
 8817:             msg += "$lt{'yomc'}\\n";
 8818:         }
 8819:     }
 8820:     if (srchin == 'dom') {
 8821:         if (srchdomain == '') {
 8822:             checkok = 0;
 8823:             msg += "$lt{'ymcd'}\\n";
 8824:         }
 8825:     }
 8826:     if (srchby == 'lastfirst') {
 8827:         if (srchterm.indexOf(",") == -1) {
 8828:             checkok = 0;
 8829:             msg += "$lt{'whus'}\\n";
 8830:         }
 8831:         if (srchterm.indexOf(",") == srchterm.length -1) {
 8832:             checkok = 0;
 8833:             msg += "$lt{'whse'}\\n";
 8834:         }
 8835:     }
 8836:     if (checkok == 0) {
 8837:         alert("$lt{'thfo'}\\n"+msg);
 8838:         return;
 8839:     }
 8840:     if (checkok == 1) {
 8841:         callingForm.submit();
 8842:     }
 8843: }
 8844: 
 8845: $newuserscript
 8846: 
 8847: // ]]>
 8848: </script>
 8849: 
 8850: $new_user_create
 8851: 
 8852: END_BLOCK
 8853: 
 8854:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 8855:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 8856:                $domform.
 8857:                &Apache::lonhtmlcommon::row_closure().
 8858:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 8859:                $srchbysel.
 8860:                $srchtypesel. 
 8861:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 8862:                $srchinsel.
 8863:                &Apache::lonhtmlcommon::row_closure(1). 
 8864:                &Apache::lonhtmlcommon::end_pick_box().
 8865:                '<br />';
 8866:     return $output;
 8867: }
 8868: 
 8869: sub user_rule_check {
 8870:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 8871:     my $response;
 8872:     if (ref($usershash) eq 'HASH') {
 8873:         foreach my $user (keys(%{$usershash})) {
 8874:             my ($uname,$udom) = split(/:/,$user);
 8875:             next if ($udom eq '' || $uname eq '');
 8876:             my ($id,$newuser);
 8877:             if (ref($usershash->{$user}) eq 'HASH') {
 8878:                 $newuser = $usershash->{$user}->{'newuser'};
 8879:                 $id = $usershash->{$user}->{'id'};
 8880:             }
 8881:             my $inst_response;
 8882:             if (ref($checks) eq 'HASH') {
 8883:                 if (defined($checks->{'username'})) {
 8884:                     ($inst_response,%{$inst_results->{$user}}) = 
 8885:                         &Apache::lonnet::get_instuser($udom,$uname);
 8886:                 } elsif (defined($checks->{'id'})) {
 8887:                     ($inst_response,%{$inst_results->{$user}}) =
 8888:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 8889:                 }
 8890:             } else {
 8891:                 ($inst_response,%{$inst_results->{$user}}) =
 8892:                     &Apache::lonnet::get_instuser($udom,$uname);
 8893:                 return;
 8894:             }
 8895:             if (!$got_rules->{$udom}) {
 8896:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 8897:                                                   ['usercreation'],$udom);
 8898:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 8899:                     foreach my $item ('username','id') {
 8900:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 8901:                             $$curr_rules{$udom}{$item} = 
 8902:                                 $domconfig{'usercreation'}{$item.'_rule'};
 8903:                         }
 8904:                     }
 8905:                 }
 8906:                 $got_rules->{$udom} = 1;  
 8907:             }
 8908:             foreach my $item (keys(%{$checks})) {
 8909:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8910:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8911:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8912:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8913:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8914:                                 if ($rule_check{$rule}) {
 8915:                                     $$rulematch{$user}{$item} = $rule;
 8916:                                     if ($inst_response eq 'ok') {
 8917:                                         if (ref($inst_results) eq 'HASH') {
 8918:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 8919:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 8920:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 8921:                                                 }
 8922:                                             }
 8923:                                         }
 8924:                                     }
 8925:                                     last;
 8926:                                 }
 8927:                             }
 8928:                         }
 8929:                     }
 8930:                 }
 8931:             }
 8932:         }
 8933:     }
 8934:     return;
 8935: }
 8936: 
 8937: sub user_rule_formats {
 8938:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 8939:     my %text = ( 
 8940:                  'username' => 'Usernames',
 8941:                  'id'       => 'IDs',
 8942:                );
 8943:     my $output;
 8944:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 8945:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 8946:         if (@{$ruleorder} > 0) {
 8947:             $output = '<br />'.&mt("$text{$check} with the following format(s) may <span class=\"LC_cusr_emph\">only</span> be used for verified users at [_1]:",$domdesc).' <ul>';
 8948:             foreach my $rule (@{$ruleorder}) {
 8949:                 if (ref($curr_rules) eq 'ARRAY') {
 8950:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 8951:                         if (ref($rules->{$rule}) eq 'HASH') {
 8952:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 8953:                                         $rules->{$rule}{'desc'}.'</li>';
 8954:                         }
 8955:                     }
 8956:                 }
 8957:             }
 8958:             $output .= '</ul>';
 8959:         }
 8960:     }
 8961:     return $output;
 8962: }
 8963: 
 8964: sub instrule_disallow_msg {
 8965:     my ($checkitem,$domdesc,$count,$mode) = @_;
 8966:     my $response;
 8967:     my %text = (
 8968:                   item   => 'username',
 8969:                   items  => 'usernames',
 8970:                   match  => 'matches',
 8971:                   do     => 'does',
 8972:                   action => 'a username',
 8973:                   one    => 'one',
 8974:                );
 8975:     if ($count > 1) {
 8976:         $text{'item'} = 'usernames';
 8977:         $text{'match'} ='match';
 8978:         $text{'do'} = 'do';
 8979:         $text{'action'} = 'usernames',
 8980:         $text{'one'} = 'ones';
 8981:     }
 8982:     if ($checkitem eq 'id') {
 8983:         $text{'items'} = 'IDs';
 8984:         $text{'item'} = 'ID';
 8985:         $text{'action'} = 'an ID';
 8986:         if ($count > 1) {
 8987:             $text{'item'} = 'IDs';
 8988:             $text{'action'} = 'IDs';
 8989:         }
 8990:     }
 8991:     $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
 8992:     if ($mode eq 'upload') {
 8993:         if ($checkitem eq 'username') {
 8994:             $response .= &mt("You will need to modify your upload file so it will include $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 8995:         } elsif ($checkitem eq 'id') {
 8996:             $response .= &mt("Either upload a file which includes $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or when associating fields with data columns, omit an association for the Student/Employee ID field.");
 8997:         }
 8998:     } elsif ($mode eq 'selfcreate') {
 8999:         if ($checkitem eq 'id') {
 9000:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
 9001:         }
 9002:     } else {
 9003:         if ($checkitem eq 'username') {
 9004:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9005:         } elsif ($checkitem eq 'id') {
 9006:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
 9007:         }
 9008:     }
 9009:     return $response;
 9010: }
 9011: 
 9012: sub personal_data_fieldtitles {
 9013:     my %fieldtitles = &Apache::lonlocal::texthash (
 9014:                         id => 'Student/Employee ID',
 9015:                         permanentemail => 'E-mail address',
 9016:                         lastname => 'Last Name',
 9017:                         firstname => 'First Name',
 9018:                         middlename => 'Middle Name',
 9019:                         generation => 'Generation',
 9020:                         gen => 'Generation',
 9021:                         inststatus => 'Affiliation',
 9022:                    );
 9023:     return %fieldtitles;
 9024: }
 9025: 
 9026: sub sorted_inst_types {
 9027:     my ($dom) = @_;
 9028:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9029:     my $othertitle = &mt('All users');
 9030:     if ($env{'request.course.id'}) {
 9031:         $othertitle  = &mt('Any users');
 9032:     }
 9033:     my @types;
 9034:     if (ref($order) eq 'ARRAY') {
 9035:         @types = @{$order};
 9036:     }
 9037:     if (@types == 0) {
 9038:         if (ref($usertypes) eq 'HASH') {
 9039:             @types = sort(keys(%{$usertypes}));
 9040:         }
 9041:     }
 9042:     if (keys(%{$usertypes}) > 0) {
 9043:         $othertitle = &mt('Other users');
 9044:     }
 9045:     return ($othertitle,$usertypes,\@types);
 9046: }
 9047: 
 9048: sub get_institutional_codes {
 9049:     my ($settings,$allcourses,$LC_code) = @_;
 9050: # Get complete list of course sections to update
 9051:     my @currsections = ();
 9052:     my @currxlists = ();
 9053:     my $coursecode = $$settings{'internal.coursecode'};
 9054: 
 9055:     if ($$settings{'internal.sectionnums'} ne '') {
 9056:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9057:     }
 9058: 
 9059:     if ($$settings{'internal.crosslistings'} ne '') {
 9060:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9061:     }
 9062: 
 9063:     if (@currxlists > 0) {
 9064:         foreach (@currxlists) {
 9065:             if (m/^([^:]+):(\w*)$/) {
 9066:                 unless (grep/^$1$/,@{$allcourses}) {
 9067:                     push @{$allcourses},$1;
 9068:                     $$LC_code{$1} = $2;
 9069:                 }
 9070:             }
 9071:         }
 9072:     }
 9073:  
 9074:     if (@currsections > 0) {
 9075:         foreach (@currsections) {
 9076:             if (m/^(\w+):(\w*)$/) {
 9077:                 my $sec = $coursecode.$1;
 9078:                 my $lc_sec = $2;
 9079:                 unless (grep/^$sec$/,@{$allcourses}) {
 9080:                     push @{$allcourses},$sec;
 9081:                     $$LC_code{$sec} = $lc_sec;
 9082:                 }
 9083:             }
 9084:         }
 9085:     }
 9086:     return;
 9087: }
 9088: 
 9089: sub get_standard_codeitems {
 9090:     return ('Year','Semester','Department','Number','Section');
 9091: }
 9092: 
 9093: =pod
 9094: 
 9095: =head1 Slot Helpers
 9096: 
 9097: =over 4
 9098: 
 9099: =item * sorted_slots()
 9100: 
 9101: Sorts an array of slot names in order of an optional sort key,
 9102: default sort is by slot start time (earliest first). 
 9103: 
 9104: Inputs:
 9105: 
 9106: =over 4
 9107: 
 9108: slotsarr  - Reference to array of unsorted slot names.
 9109: 
 9110: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9111: 
 9112: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9113: 
 9114: =back
 9115: 
 9116: Returns:
 9117: 
 9118: =over 4
 9119: 
 9120: sorted   - An array of slot names sorted by a specified sort key 
 9121:            (default sort key is start time of the slot).
 9122: 
 9123: =back
 9124: 
 9125: =cut
 9126: 
 9127: 
 9128: sub sorted_slots {
 9129:     my ($slotsarr,$slots,$sortkey) = @_;
 9130:     if ($sortkey eq '') {
 9131:         $sortkey = 'starttime';
 9132:     }
 9133:     my @sorted;
 9134:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9135:         @sorted =
 9136:             sort {
 9137:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9138:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9139:                      }
 9140:                      if (ref($slots->{$a})) { return -1;}
 9141:                      if (ref($slots->{$b})) { return 1;}
 9142:                      return 0;
 9143:                  } @{$slotsarr};
 9144:     }
 9145:     return @sorted;
 9146: }
 9147: 
 9148: =pod
 9149: 
 9150: =item * get_future_slots()
 9151: 
 9152: Inputs:
 9153: 
 9154: =over 4
 9155: 
 9156: cnum - course number
 9157: 
 9158: cdom - course domain
 9159: 
 9160: now - current UNIX time
 9161: 
 9162: symb - optional symb
 9163: 
 9164: =back
 9165: 
 9166: Returns:
 9167: 
 9168: =over 4
 9169: 
 9170: sorted_reservable - ref to array of student_schedulable slots currently 
 9171:                     reservable, ordered by end date of reservation period.
 9172: 
 9173: reservable_now - ref to hash of student_schedulable slots currently
 9174:                  reservable.
 9175: 
 9176:     Keys in inner hash are:
 9177:     (a) symb: either blank or symb to which slot use is restricted.
 9178:     (b) endreserve: end date of reservation period. 
 9179: 
 9180: sorted_future - ref to array of student_schedulable slots reservable in
 9181:                 the future, ordered by start date of reservation period.
 9182: 
 9183: future_reservable - ref to hash of student_schedulable slots reservable
 9184:                     in the future.
 9185: 
 9186:     Keys in inner hash are:
 9187:     (a) symb: either blank or symb to which slot use is restricted.
 9188:     (b) startreserve:  start date of reservation period.
 9189: 
 9190: =back
 9191: 
 9192: =cut
 9193: 
 9194: sub get_future_slots {
 9195:     my ($cnum,$cdom,$now,$symb) = @_;
 9196:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9197:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9198:     foreach my $slot (keys(%slots)) {
 9199:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9200:         if ($symb) {
 9201:             next if (($slots{$slot}->{'symb'} ne '') && 
 9202:                      ($slots{$slot}->{'symb'} ne $symb));
 9203:         }
 9204:         if (($slots{$slot}->{'starttime'} > $now) &&
 9205:             ($slots{$slot}->{'endtime'} > $now)) {
 9206:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9207:                 my $userallowed = 0;
 9208:                 if ($slots{$slot}->{'allowedsections'}) {
 9209:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9210:                     if (!defined($env{'request.role.sec'})
 9211:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9212:                         $userallowed=1;
 9213:                     } else {
 9214:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9215:                             $userallowed=1;
 9216:                         }
 9217:                     }
 9218:                     unless ($userallowed) {
 9219:                         if (defined($env{'request.course.groups'})) {
 9220:                             my @groups = split(/:/,$env{'request.course.groups'});
 9221:                             foreach my $group (@groups) {
 9222:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9223:                                     $userallowed=1;
 9224:                                     last;
 9225:                                 }
 9226:                             }
 9227:                         }
 9228:                     }
 9229:                 }
 9230:                 if ($slots{$slot}->{'allowedusers'}) {
 9231:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9232:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9233:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9234:                         $userallowed = 1;
 9235:                     }
 9236:                 }
 9237:                 next unless($userallowed);
 9238:             }
 9239:             my $startreserve = $slots{$slot}->{'startreserve'};
 9240:             my $endreserve = $slots{$slot}->{'endreserve'};
 9241:             my $symb = $slots{$slot}->{'symb'};
 9242:             if (($startreserve < $now) &&
 9243:                 (!$endreserve || $endreserve > $now)) {
 9244:                 my $lastres = $endreserve;
 9245:                 if (!$lastres) {
 9246:                     $lastres = $slots{$slot}->{'starttime'};
 9247:                 }
 9248:                 $reservable_now{$slot} = {
 9249:                                            symb       => $symb,
 9250:                                            endreserve => $lastres
 9251:                                          };
 9252:             } elsif (($startreserve > $now) &&
 9253:                      (!$endreserve || $endreserve > $startreserve)) {
 9254:                 $future_reservable{$slot} = {
 9255:                                               symb         => $symb,
 9256:                                               startreserve => $startreserve
 9257:                                             };
 9258:             }
 9259:         }
 9260:     }
 9261:     my @unsorted_reservable = keys(%reservable_now);
 9262:     if (@unsorted_reservable > 0) {
 9263:         @sorted_reservable = 
 9264:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9265:     }
 9266:     my @unsorted_future = keys(%future_reservable);
 9267:     if (@unsorted_future > 0) {
 9268:         @sorted_future =
 9269:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9270:     }
 9271:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9272: }
 9273: 
 9274: =pod
 9275: 
 9276: =back
 9277: 
 9278: =head1 HTTP Helpers
 9279: 
 9280: =over 4
 9281: 
 9282: =item * &get_unprocessed_cgi($query,$possible_names)
 9283: 
 9284: Modify the %env hash to contain unprocessed CGI form parameters held in
 9285: $query.  The parameters listed in $possible_names (an array reference),
 9286: will be set in $env{'form.name'} if they do not already exist.
 9287: 
 9288: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9289: $possible_names is an ref to an array of form element names.  As an example:
 9290: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9291: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9292: 
 9293: =cut
 9294: 
 9295: sub get_unprocessed_cgi {
 9296:   my ($query,$possible_names)= @_;
 9297:   # $Apache::lonxml::debug=1;
 9298:   foreach my $pair (split(/&/,$query)) {
 9299:     my ($name, $value) = split(/=/,$pair);
 9300:     $name = &unescape($name);
 9301:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9302:       $value =~ tr/+/ /;
 9303:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9304:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9305:     }
 9306:   }
 9307: }
 9308: 
 9309: =pod
 9310: 
 9311: =item * &cacheheader() 
 9312: 
 9313: returns cache-controlling header code
 9314: 
 9315: =cut
 9316: 
 9317: sub cacheheader {
 9318:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9319:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9320:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9321:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9322:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9323:     return $output;
 9324: }
 9325: 
 9326: =pod
 9327: 
 9328: =item * &no_cache($r) 
 9329: 
 9330: specifies header code to not have cache
 9331: 
 9332: =cut
 9333: 
 9334: sub no_cache {
 9335:     my ($r) = @_;
 9336:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9337: 	$env{'request.method'} ne 'GET') { return ''; }
 9338:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9339:     $r->no_cache(1);
 9340:     $r->header_out("Expires" => $date);
 9341:     $r->header_out("Pragma" => "no-cache");
 9342: }
 9343: 
 9344: sub content_type {
 9345:     my ($r,$type,$charset) = @_;
 9346:     if ($r) {
 9347: 	#  Note that printout.pl calls this with undef for $r.
 9348: 	&no_cache($r);
 9349:     }
 9350:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9351:     unless ($charset) {
 9352: 	$charset=&Apache::lonlocal::current_encoding;
 9353:     }
 9354:     if ($charset) { $type.='; charset='.$charset; }
 9355:     if ($r) {
 9356: 	$r->content_type($type);
 9357:     } else {
 9358: 	print("Content-type: $type\n\n");
 9359:     }
 9360: }
 9361: 
 9362: =pod
 9363: 
 9364: =item * &add_to_env($name,$value) 
 9365: 
 9366: adds $name to the %env hash with value
 9367: $value, if $name already exists, the entry is converted to an array
 9368: reference and $value is added to the array.
 9369: 
 9370: =cut
 9371: 
 9372: sub add_to_env {
 9373:   my ($name,$value)=@_;
 9374:   if (defined($env{$name})) {
 9375:     if (ref($env{$name})) {
 9376:       #already have multiple values
 9377:       push(@{ $env{$name} },$value);
 9378:     } else {
 9379:       #first time seeing multiple values, convert hash entry to an arrayref
 9380:       my $first=$env{$name};
 9381:       undef($env{$name});
 9382:       push(@{ $env{$name} },$first,$value);
 9383:     }
 9384:   } else {
 9385:     $env{$name}=$value;
 9386:   }
 9387: }
 9388: 
 9389: =pod
 9390: 
 9391: =item * &get_env_multiple($name) 
 9392: 
 9393: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9394: values may be defined and end up as an array ref.
 9395: 
 9396: returns an array of values
 9397: 
 9398: =cut
 9399: 
 9400: sub get_env_multiple {
 9401:     my ($name) = @_;
 9402:     my @values;
 9403:     if (defined($env{$name})) {
 9404:         # exists is it an array
 9405:         if (ref($env{$name})) {
 9406:             @values=@{ $env{$name} };
 9407:         } else {
 9408:             $values[0]=$env{$name};
 9409:         }
 9410:     }
 9411:     return(@values);
 9412: }
 9413: 
 9414: sub ask_for_embedded_content {
 9415:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9416:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9417:         %currsubfile,%unused,$rem);
 9418:     my $counter = 0;
 9419:     my $numnew = 0;
 9420:     my $numremref = 0;
 9421:     my $numinvalid = 0;
 9422:     my $numpathchg = 0;
 9423:     my $numexisting = 0;
 9424:     my $numunused = 0;
 9425:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9426:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
 9427:     my $heading = &mt('Upload embedded files');
 9428:     my $buttontext = &mt('Upload');
 9429: 
 9430:     my $navmap;
 9431:     if ($env{'request.course.id'}) {
 9432:         $navmap = Apache::lonnavmaps::navmap->new();
 9433:     }
 9434:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9435:         my $current_path='/';
 9436:         if ($env{'form.currentpath'}) {
 9437:             $current_path = $env{'form.currentpath'};
 9438:         }
 9439:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9440:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9441:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 9442:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9443:         } else {
 9444:             $udom = $env{'user.domain'};
 9445:             $uname = $env{'user.name'};
 9446:             $url = '/userfiles/portfolio';
 9447:         }
 9448:         $toplevel = $url.'/';
 9449:         $url .= $current_path;
 9450:         $getpropath = 1;
 9451:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9452:              ($actionurl eq '/adm/imsimport')) { 
 9453:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9454:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9455:         $toplevel = $url;
 9456:         if ($rest ne '') {
 9457:             $url .= $rest;
 9458:         }
 9459:     } elsif ($actionurl eq '/adm/coursedocs') {
 9460:         if (ref($args) eq 'HASH') {
 9461:             $url = $args->{'docs_url'};
 9462:             $toplevel = $url;
 9463:             if ($args->{'context'} eq 'paste') {
 9464:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9465:                 ($path) = 
 9466:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9467:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9468:                 $fileloc =~ s{^/}{};
 9469:             }
 9470:         }
 9471:     } elsif ($actionurl eq '/adm/dependencies')  {
 9472:         if ($env{'request.course.id'} ne '') {
 9473:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9474:             $cnum =  $env{'course.'.$env{'request.course.id'}.'.num'};
 9475:             if (ref($args) eq 'HASH') {
 9476:                 $url = $args->{'docs_url'};
 9477:                 $title = $args->{'docs_title'};
 9478:                 $toplevel = "/$url";
 9479:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9480:                 ($path) =  
 9481:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9482:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9483:                 $fileloc =~ s{^/}{};
 9484:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9485:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9486:             }
 9487:         }
 9488:     }
 9489:     my $now = time();
 9490:     foreach my $embed_file (keys(%{$allfiles})) {
 9491:         my $absolutepath;
 9492:         if ($embed_file =~ m{^\w+://}) {
 9493:             $newfiles{$embed_file} = 1;
 9494:             $mapping{$embed_file} = $embed_file;
 9495:         } else {
 9496:             if ($embed_file =~ m{^/}) {
 9497:                 $absolutepath = $embed_file;
 9498:                 $embed_file =~ s{^(/+)}{};
 9499:             }
 9500:             if ($embed_file =~ m{/}) {
 9501:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 9502:                 $path = &check_for_traversal($path,$url,$toplevel);
 9503:                 my $item = $fname;
 9504:                 if ($path ne '') {
 9505:                     $item = $path.'/'.$fname;
 9506:                     $subdependencies{$path}{$fname} = 1;
 9507:                 } else {
 9508:                     $dependencies{$item} = 1;
 9509:                 }
 9510:                 if ($absolutepath) {
 9511:                     $mapping{$item} = $absolutepath;
 9512:                 } else {
 9513:                     $mapping{$item} = $embed_file;
 9514:                 }
 9515:             } else {
 9516:                 $dependencies{$embed_file} = 1;
 9517:                 if ($absolutepath) {
 9518:                     $mapping{$embed_file} = $absolutepath;
 9519:                 } else {
 9520:                     $mapping{$embed_file} = $embed_file;
 9521:                 }
 9522:             }
 9523:         }
 9524:     }
 9525:     my $dirptr = 16384;
 9526:     foreach my $path (keys(%subdependencies)) {
 9527:         $currsubfile{$path} = {};
 9528:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
 9529:             my ($sublistref,$listerror) =
 9530:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9531:             if (ref($sublistref) eq 'ARRAY') {
 9532:                 foreach my $line (@{$sublistref}) {
 9533:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9534:                     $currsubfile{$path}{$file_name} = 1;
 9535:                 }
 9536:             }
 9537:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9538:             if (opendir(my $dir,$url.'/'.$path)) {
 9539:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9540:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9541:             }
 9542:         } elsif (($actionurl eq '/adm/dependencies') ||
 9543:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9544:                   ($args->{'context'} eq 'paste'))) {
 9545:             if ($env{'request.course.id'} ne '') {
 9546:                 my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9547:                 if ($dir ne '') {
 9548:                     my ($sublistref,$listerror) =
 9549:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9550:                     if (ref($sublistref) eq 'ARRAY') {
 9551:                         foreach my $line (@{$sublistref}) {
 9552:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9553:                                 undef,$mtime)=split(/\&/,$line,12);
 9554:                             unless (($testdir&$dirptr) ||
 9555:                                     ($file_name =~ /^\.\.?$/)) {
 9556:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9557:                             }
 9558:                         }
 9559:                     }
 9560:                 }
 9561:             }
 9562:         }
 9563:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9564:             if (exists($currsubfile{$path}{$file})) {
 9565:                 my $item = $path.'/'.$file;
 9566:                 unless ($mapping{$item} eq $item) {
 9567:                     $pathchanges{$item} = 1;
 9568:                 }
 9569:                 $existing{$item} = 1;
 9570:                 $numexisting ++;
 9571:             } else {
 9572:                 $newfiles{$path.'/'.$file} = 1;
 9573:             }
 9574:         }
 9575:         if ($actionurl eq '/adm/dependencies') {
 9576:             foreach my $path (keys(%currsubfile)) {
 9577:                 if (ref($currsubfile{$path}) eq 'HASH') {
 9578:                     foreach my $file (keys(%{$currsubfile{$path}})) {
 9579:                          unless ($subdependencies{$path}{$file}) {
 9580:                              next if (($rem ne '') &&
 9581:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
 9582:                                        (ref($navmap) &&
 9583:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
 9584:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9585:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
 9586:                              $unused{$path.'/'.$file} = 1; 
 9587:                          }
 9588:                     }
 9589:                 }
 9590:             }
 9591:         }
 9592:     }
 9593:     my %currfile;
 9594:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9595:         my ($dirlistref,$listerror) =
 9596:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 9597:         if (ref($dirlistref) eq 'ARRAY') {
 9598:             foreach my $line (@{$dirlistref}) {
 9599:                 my ($file_name,$rest) = split(/\&/,$line,2);
 9600:                 $currfile{$file_name} = 1;
 9601:             }
 9602:         }
 9603:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9604:         if (opendir(my $dir,$url)) {
 9605:             my @dir_list = grep(!/^\./,readdir($dir));
 9606:             map {$currfile{$_} = 1;} @dir_list;
 9607:         }
 9608:     } elsif (($actionurl eq '/adm/dependencies') ||
 9609:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9610:               ($args->{'context'} eq 'paste'))) {
 9611:         if ($env{'request.course.id'} ne '') {
 9612:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9613:             if ($dir ne '') {
 9614:                 my ($dirlistref,$listerror) =
 9615:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
 9616:                 if (ref($dirlistref) eq 'ARRAY') {
 9617:                     foreach my $line (@{$dirlistref}) {
 9618:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
 9619:                             $size,undef,$mtime)=split(/\&/,$line,12);
 9620:                         unless (($testdir&$dirptr) ||
 9621:                                 ($file_name =~ /^\.\.?$/)) {
 9622:                             $currfile{$file_name} = [$size,$mtime];
 9623:                         }
 9624:                     }
 9625:                 }
 9626:             }
 9627:         }
 9628:     }
 9629:     foreach my $file (keys(%dependencies)) {
 9630:         if (exists($currfile{$file})) {
 9631:             unless ($mapping{$file} eq $file) {
 9632:                 $pathchanges{$file} = 1;
 9633:             }
 9634:             $existing{$file} = 1;
 9635:             $numexisting ++;
 9636:         } else {
 9637:             $newfiles{$file} = 1;
 9638:         }
 9639:     }
 9640:     foreach my $file (keys(%currfile)) {
 9641:         unless (($file eq $filename) ||
 9642:                 ($file eq $filename.'.bak') ||
 9643:                 ($dependencies{$file})) {
 9644:             if ($actionurl eq '/adm/dependencies') {
 9645:                 next if (($rem ne '') &&
 9646:                          (($env{"httpref.$rem".$file} ne '') ||
 9647:                           (ref($navmap) &&
 9648:                           (($navmap->getResourceByUrl($rem.$file) ne '') ||
 9649:                            (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9650:                             ($navmap->getResourceByUrl($rem.$1)))))));
 9651:             }
 9652:             $unused{$file} = 1;
 9653:         }
 9654:     }
 9655:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9656:         ($args->{'context'} eq 'paste')) {
 9657:         $counter = scalar(keys(%existing));
 9658:         $numpathchg = scalar(keys(%pathchanges));
 9659:         return ($output,$counter,$numpathchg,\%existing); 
 9660:     }
 9661:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 9662:         if ($actionurl eq '/adm/dependencies') {
 9663:             next if ($embed_file =~ m{^\w+://});
 9664:         }
 9665:         $upload_output .= &start_data_table_row().
 9666:                           '<td><img src="'.&icon($embed_file).'" />&nbsp;'.
 9667:                           '<span class="LC_filename">'.$embed_file.'</span>';
 9668:         unless ($mapping{$embed_file} eq $embed_file) {
 9669:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 9670:         }
 9671:         $upload_output .= '</td><td>';
 9672:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
 9673:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 9674:             $numremref++;
 9675:         } elsif ($args->{'error_on_invalid_names'}
 9676:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 9677:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 9678:             $numinvalid++;
 9679:         } else {
 9680:             $upload_output .= &embedded_file_element('upload_embedded',$counter,
 9681:                                                      $embed_file,\%mapping,
 9682:                                                      $allfiles,$codebase,'upload');
 9683:             $counter ++;
 9684:             $numnew ++;
 9685:         }
 9686:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 9687:     }
 9688:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 9689:         if ($actionurl eq '/adm/dependencies') {
 9690:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
 9691:             $modify_output .= &start_data_table_row().
 9692:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
 9693:                               '<img src="'.&icon($embed_file).'" border="0" />'.
 9694:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
 9695:                               '<td>'.$size.'</td>'.
 9696:                               '<td>'.$mtime.'</td>'.
 9697:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
 9698:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
 9699:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
 9700:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
 9701:                               &embedded_file_element('upload_embedded',$counter,
 9702:                                                      $embed_file,\%mapping,
 9703:                                                      $allfiles,$codebase,'modify').
 9704:                               '</div></td>'.
 9705:                               &end_data_table_row()."\n";
 9706:             $counter ++;
 9707:         } else {
 9708:             $upload_output .= &start_data_table_row().
 9709:                               '<td><span class="LC_filename">'.$embed_file.'</span></td>';
 9710:                               '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 9711:                               &Apache::loncommon::end_data_table_row()."\n";
 9712:         }
 9713:     }
 9714:     my $delidx = $counter;
 9715:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
 9716:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
 9717:         $delete_output .= &start_data_table_row().
 9718:                           '<td><img src="'.&icon($oldfile).'" />'.
 9719:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
 9720:                           '<td>'.$size.'</td>'.
 9721:                           '<td>'.$mtime.'</td>'.
 9722:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
 9723:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
 9724:                           &embedded_file_element('upload_embedded',$delidx,
 9725:                                                  $oldfile,\%mapping,$allfiles,
 9726:                                                  $codebase,'delete').'</td>'.
 9727:                           &end_data_table_row()."\n"; 
 9728:         $numunused ++;
 9729:         $delidx ++;
 9730:     }
 9731:     if ($upload_output) {
 9732:         $upload_output = &start_data_table().
 9733:                          $upload_output.
 9734:                          &end_data_table()."\n";
 9735:     }
 9736:     if ($modify_output) {
 9737:         $modify_output = &start_data_table().
 9738:                          &start_data_table_header_row().
 9739:                          '<th>'.&mt('File').'</th>'.
 9740:                          '<th>'.&mt('Size (KB)').'</th>'.
 9741:                          '<th>'.&mt('Modified').'</th>'.
 9742:                          '<th>'.&mt('Upload replacement?').'</th>'.
 9743:                          &end_data_table_header_row().
 9744:                          $modify_output.
 9745:                          &end_data_table()."\n";
 9746:     }
 9747:     if ($delete_output) {
 9748:         $delete_output = &start_data_table().
 9749:                          &start_data_table_header_row().
 9750:                          '<th>'.&mt('File').'</th>'.
 9751:                          '<th>'.&mt('Size (KB)').'</th>'.
 9752:                          '<th>'.&mt('Modified').'</th>'.
 9753:                          '<th>'.&mt('Delete?').'</th>'.
 9754:                          &end_data_table_header_row().
 9755:                          $delete_output.
 9756:                          &end_data_table()."\n";
 9757:     }
 9758:     my $applies = 0;
 9759:     if ($numremref) {
 9760:         $applies ++;
 9761:     }
 9762:     if ($numinvalid) {
 9763:         $applies ++;
 9764:     }
 9765:     if ($numexisting) {
 9766:         $applies ++;
 9767:     }
 9768:     if ($counter || $numunused) {
 9769:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 9770:                   ' method="post" enctype="multipart/form-data">'."\n".
 9771:                   $state.'<h3>'.$heading.'</h3>'; 
 9772:         if ($actionurl eq '/adm/dependencies') {
 9773:             if ($numnew) {
 9774:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
 9775:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
 9776:                            $upload_output.'<br />'."\n";
 9777:             }
 9778:             if ($numexisting) {
 9779:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
 9780:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
 9781:                            $modify_output.'<br />'."\n";
 9782:                            $buttontext = &mt('Save changes');
 9783:             }
 9784:             if ($numunused) {
 9785:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
 9786:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
 9787:                            $delete_output.'<br />'."\n";
 9788:                            $buttontext = &mt('Save changes');
 9789:             }
 9790:         } else {
 9791:             $output .= $upload_output.'<br />'."\n";
 9792:         }
 9793:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
 9794:                    $counter.'" />'."\n";
 9795:         if ($actionurl eq '/adm/dependencies') { 
 9796:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
 9797:                        $numnew.'" />'."\n";
 9798:         } elsif ($actionurl eq '') {
 9799:             $output .=  '<input type="hidden" name="phase" value="three" />';
 9800:         }
 9801:     } elsif ($applies) {
 9802:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 9803:         if ($applies > 1) {
 9804:             $output .=  
 9805:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 9806:             if ($numremref) {
 9807:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 9808:             }
 9809:             if ($numinvalid) {
 9810:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 9811:             }
 9812:             if ($numexisting) {
 9813:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 9814:             }
 9815:             $output .= '</ul><br />';
 9816:         } elsif ($numremref) {
 9817:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 9818:         } elsif ($numinvalid) {
 9819:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 9820:         } elsif ($numexisting) {
 9821:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 9822:         }
 9823:         $output .= $upload_output.'<br />';
 9824:     }
 9825:     my ($pathchange_output,$chgcount);
 9826:     $chgcount = $counter;
 9827:     if (keys(%pathchanges) > 0) {
 9828:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 9829:             if ($counter) {
 9830:                 $output .= &embedded_file_element('pathchange',$chgcount,
 9831:                                                   $embed_file,\%mapping,
 9832:                                                   $allfiles,$codebase,'change');
 9833:             } else {
 9834:                 $pathchange_output .= 
 9835:                     &start_data_table_row().
 9836:                     '<td><input type ="checkbox" name="namechange" value="'.
 9837:                     $chgcount.'" checked="checked" /></td>'.
 9838:                     '<td>'.$mapping{$embed_file}.'</td>'.
 9839:                     '<td>'.$embed_file.
 9840:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 9841:                                            \%mapping,$allfiles,$codebase,'change').
 9842:                     '</td>'.&end_data_table_row();
 9843:             }
 9844:             $numpathchg ++;
 9845:             $chgcount ++;
 9846:         }
 9847:     }
 9848:     if ($counter) {
 9849:         if ($numpathchg) {
 9850:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 9851:                        $numpathchg.'" />'."\n";
 9852:         }
 9853:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
 9854:             ($actionurl eq '/adm/imsimport')) {
 9855:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 9856:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 9857:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 9858:         } elsif ($actionurl eq '/adm/dependencies') {
 9859:             $output .= '<input type="hidden" name="action" value="process_changes" />';
 9860:         }
 9861:         $output .=  '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
 9862:     } elsif ($numpathchg) {
 9863:         my %pathchange = ();
 9864:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 9865:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9866:             $output .= '<p>'.&mt('or').'</p>'; 
 9867:         } 
 9868:     }
 9869:     return ($output,$counter,$numpathchg);
 9870: }
 9871: 
 9872: sub embedded_file_element {
 9873:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
 9874:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 9875:                    (ref($codebase) eq 'HASH'));
 9876:     my $output;
 9877:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
 9878:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 9879:     }
 9880:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 9881:                &escape($embed_file).'" />';
 9882:     unless (($context eq 'upload_embedded') && 
 9883:             ($mapping->{$embed_file} eq $embed_file)) {
 9884:         $output .='
 9885:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 9886:     }
 9887:     my $attrib;
 9888:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 9889:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 9890:     }
 9891:     $output .=
 9892:         "\n\t\t".
 9893:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 9894:         $attrib.'" />';
 9895:     if (exists($codebase->{$mapping->{$embed_file}})) {
 9896:         $output .=
 9897:             "\n\t\t".
 9898:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 9899:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 9900:     }
 9901:     return $output;
 9902: }
 9903: 
 9904: sub get_dependency_details {
 9905:     my ($currfile,$currsubfile,$embed_file) = @_;
 9906:     my ($size,$mtime,$showsize,$showmtime);
 9907:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
 9908:         if ($embed_file =~ m{/}) {
 9909:             my ($path,$fname) = split(/\//,$embed_file);
 9910:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
 9911:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
 9912:             }
 9913:         } else {
 9914:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
 9915:                 ($size,$mtime) = @{$currfile->{$embed_file}};
 9916:             }
 9917:         }
 9918:         $showsize = $size/1024.0;
 9919:         $showsize = sprintf("%.1f",$showsize);
 9920:         if ($mtime > 0) {
 9921:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
 9922:         }
 9923:     }
 9924:     return ($showsize,$showmtime);
 9925: }
 9926: 
 9927: sub ask_embedded_js {
 9928:     return <<"END";
 9929: <script type="text/javascript"">
 9930: // <![CDATA[
 9931: function toggleBrowse(counter) {
 9932:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
 9933:     var fileid = document.getElementById('embedded_item_'+counter);
 9934:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
 9935:     if (chkboxid.checked == true) {
 9936:         uploaddivid.style.display='block';
 9937:     } else {
 9938:         uploaddivid.style.display='none';
 9939:         fileid.value = '';
 9940:     }
 9941: }
 9942: // ]]>
 9943: </script>
 9944: 
 9945: END
 9946: }
 9947: 
 9948: sub upload_embedded {
 9949:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 9950:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
 9951:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
 9952:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 9953:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 9954:         my $orig_uploaded_filename =
 9955:             $env{'form.embedded_item_'.$i.'.filename'};
 9956:         foreach my $type ('orig','ref','attrib','codebase') {
 9957:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
 9958:                 $env{'form.embedded_'.$type.'_'.$i} =
 9959:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
 9960:             }
 9961:         }
 9962:         my ($path,$fname) =
 9963:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 9964:         # no path, whole string is fname
 9965:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 9966:         $fname = &Apache::lonnet::clean_filename($fname);
 9967:         # See if there is anything left
 9968:         next if ($fname eq '');
 9969: 
 9970:         # Check if file already exists as a file or directory.
 9971:         my ($state,$msg);
 9972:         if ($context eq 'portfolio') {
 9973:             my $port_path = $dirpath;
 9974:             if ($group ne '') {
 9975:                 $port_path = "groups/$group/$port_path";
 9976:             }
 9977:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
 9978:                                               $fname,$group,'embedded_item_'.$i,
 9979:                                               $dir_root,$port_path,$disk_quota,
 9980:                                               $current_disk_usage,$uname,$udom);
 9981:             if ($state eq 'will_exceed_quota'
 9982:                 || $state eq 'file_locked') {
 9983:                 $output .= $msg;
 9984:                 next;
 9985:             }
 9986:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 9987:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 9988:             if ($state eq 'exists') {
 9989:                 $output .= $msg;
 9990:                 next;
 9991:             }
 9992:         }
 9993:         # Check if extension is valid
 9994:         if (($fname =~ /\.(\w+)$/) &&
 9995:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 9996:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
 9997:             next;
 9998:         } elsif (($fname =~ /\.(\w+)$/) &&
 9999:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10000:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10001:             next;
10002:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10003:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10004:             next;
10005:         }
10006:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10007:         if ($context eq 'portfolio') {
10008:             my $result;
10009:             if ($state eq 'existingfile') {
10010:                 $result=
10011:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10012:                                                     $dirpath.$env{'form.currentpath'}.$path);
10013:             } else {
10014:                 $result=
10015:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10016:                                                     $dirpath.
10017:                                                     $env{'form.currentpath'}.$path);
10018:                 if ($result !~ m|^/uploaded/|) {
10019:                     $output .= '<span class="LC_error">'
10020:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10021:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10022:                                .'</span><br />';
10023:                     next;
10024:                 } else {
10025:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10026:                                $path.$fname.'</span>').'<br />';     
10027:                 }
10028:             }
10029:         } elsif ($context eq 'coursedoc') {
10030:             my $result =
10031:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
10032:                                                 $dirpath.'/'.$path);
10033:             if ($result !~ m|^/uploaded/|) {
10034:                 $output .= '<span class="LC_error">'
10035:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10036:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10037:                            .'</span><br />';
10038:                     next;
10039:             } else {
10040:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10041:                            $path.$fname.'</span>').'<br />';
10042:             }
10043:         } else {
10044: # Save the file
10045:             my $target = $env{'form.embedded_item_'.$i};
10046:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10047:             my $dest = $fullpath.$fname;
10048:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10049:             my @parts=split(/\//,"$dirpath/$path");
10050:             my $count;
10051:             my $filepath = $dir_root;
10052:             foreach my $subdir (@parts) {
10053:                 $filepath .= "/$subdir";
10054:                 if (!-e $filepath) {
10055:                     mkdir($filepath,0770);
10056:                 }
10057:             }
10058:             my $fh;
10059:             if (!open($fh,'>'.$dest)) {
10060:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10061:                 $output .= '<span class="LC_error">'.
10062:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10063:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10064:                            '</span><br />';
10065:             } else {
10066:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10067:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10068:                     $output .= '<span class="LC_error">'.
10069:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10070:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10071:                               '</span><br />';
10072:                 } else {
10073:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10074:                                $url.'</span>').'<br />';
10075:                     unless ($context eq 'testbank') {
10076:                         $footer .= &mt('View embedded file: [_1]',
10077:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10078:                     }
10079:                 }
10080:                 close($fh);
10081:             }
10082:         }
10083:         if ($env{'form.embedded_ref_'.$i}) {
10084:             $pathchange{$i} = 1;
10085:         }
10086:     }
10087:     if ($output) {
10088:         $output = '<p>'.$output.'</p>';
10089:     }
10090:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10091:     $returnflag = 'ok';
10092:     my $numpathchgs = scalar(keys(%pathchange));
10093:     if ($numpathchgs > 0) {
10094:         if ($context eq 'portfolio') {
10095:             $output .= '<p>'.&mt('or').'</p>';
10096:         } elsif ($context eq 'testbank') {
10097:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10098:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10099:             $returnflag = 'modify_orightml';
10100:         }
10101:     }
10102:     return ($output.$footer,$returnflag,$numpathchgs);
10103: }
10104: 
10105: sub modify_html_form {
10106:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10107:     my $end = 0;
10108:     my $modifyform;
10109:     if ($context eq 'upload_embedded') {
10110:         return unless (ref($pathchange) eq 'HASH');
10111:         if ($env{'form.number_embedded_items'}) {
10112:             $end += $env{'form.number_embedded_items'};
10113:         }
10114:         if ($env{'form.number_pathchange_items'}) {
10115:             $end += $env{'form.number_pathchange_items'};
10116:         }
10117:         if ($end) {
10118:             for (my $i=0; $i<$end; $i++) {
10119:                 if ($i < $env{'form.number_embedded_items'}) {
10120:                     next unless($pathchange->{$i});
10121:                 }
10122:                 $modifyform .=
10123:                     &start_data_table_row().
10124:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10125:                     'checked="checked" /></td>'.
10126:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10127:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10128:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10129:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10130:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10131:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10132:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10133:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10134:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10135:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10136:                     &end_data_table_row();
10137:             }
10138:         }
10139:     } else {
10140:         $modifyform = $pathchgtable;
10141:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10142:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10143:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10144:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10145:         }
10146:     }
10147:     if ($modifyform) {
10148:         if ($actionurl eq '/adm/dependencies') {
10149:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10150:         }
10151:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10152:                '<p>'.&mt('Changes need to be made to the reference(s) used for one or more of the dependencies, if your HTML file is to work correctly:').'<ol>'."\n".
10153:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10154:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10155:                '</ol></p>'."\n".'<p>'.
10156:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10157:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10158:                &start_data_table()."\n".
10159:                &start_data_table_header_row().
10160:                '<th>'.&mt('Change?').'</th>'.
10161:                '<th>'.&mt('Current reference').'</th>'.
10162:                '<th>'.&mt('Required reference').'</th>'.
10163:                &end_data_table_header_row()."\n".
10164:                $modifyform.
10165:                &end_data_table().'<br />'."\n".$hiddenstate.
10166:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10167:                '</form>'."\n";
10168:     }
10169:     return;
10170: }
10171: 
10172: sub modify_html_refs {
10173:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
10174:     my $container;
10175:     if ($context eq 'portfolio') {
10176:         $container = $env{'form.container'};
10177:     } elsif ($context eq 'coursedoc') {
10178:         $container = $env{'form.primaryurl'};
10179:     } elsif ($context eq 'manage_dependencies') {
10180:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10181:         $container = "/$container";
10182:     } else {
10183:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10184:     }
10185:     my (%allfiles,%codebase,$output,$content);
10186:     my @changes = &get_env_multiple('form.namechange');
10187:     unless (@changes > 0) {
10188:         if (wantarray) {
10189:             return ('',0,0); 
10190:         } else {
10191:             return;
10192:         }
10193:     }
10194:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10195:         ($context eq 'manage_dependencies')) {
10196:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10197:             if (wantarray) {
10198:                 return ('',0,0);
10199:             } else {
10200:                 return;
10201:             }
10202:         } 
10203:         $content = &Apache::lonnet::getfile($container);
10204:         if ($content eq '-1') {
10205:             if (wantarray) {
10206:                 return ('',0,0);
10207:             } else {
10208:                 return;
10209:             }
10210:         }
10211:     } else {
10212:         unless ($container =~ /^\Q$dir_root\E/) {
10213:             if (wantarray) {
10214:                 return ('',0,0);
10215:             } else {
10216:                 return;
10217:             }
10218:         } 
10219:         if (open(my $fh,"<$container")) {
10220:             $content = join('', <$fh>);
10221:             close($fh);
10222:         } else {
10223:             if (wantarray) {
10224:                 return ('',0,0);
10225:             } else {
10226:                 return;
10227:             }
10228:         }
10229:     }
10230:     my ($count,$codebasecount) = (0,0);
10231:     my $mm = new File::MMagic;
10232:     my $mime_type = $mm->checktype_contents($content);
10233:     if ($mime_type eq 'text/html') {
10234:         my $parse_result = 
10235:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10236:                                                     \%codebase,\$content);
10237:         if ($parse_result eq 'ok') {
10238:             foreach my $i (@changes) {
10239:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10240:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10241:                 if ($allfiles{$ref}) {
10242:                     my $newname =  $orig;
10243:                     my ($attrib_regexp,$codebase);
10244:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10245:                     if ($attrib_regexp =~ /:/) {
10246:                         $attrib_regexp =~ s/\:/|/g;
10247:                     }
10248:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10249:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10250:                         $count += $numchg;
10251:                     }
10252:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10253:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10254:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10255:                         $codebasecount ++;
10256:                     }
10257:                 }
10258:             }
10259:             if ($count || $codebasecount) {
10260:                 my $saveresult;
10261:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10262:                     ($context eq 'manage_dependencies')) {
10263:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10264:                     if ($url eq $container) {
10265:                         my ($fname) = ($container =~ m{/([^/]+)$});
10266:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10267:                                             $count,'<span class="LC_filename">'.
10268:                                             $fname.'</span>').'</p>';
10269:                     } else {
10270:                          $output = '<p class="LC_error">'.
10271:                                    &mt('Error: update failed for: [_1].',
10272:                                    '<span class="LC_filename">'.
10273:                                    $container.'</span>').'</p>';
10274:                     }
10275:                 } else {
10276:                     if (open(my $fh,">$container")) {
10277:                         print $fh $content;
10278:                         close($fh);
10279:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10280:                                   $count,'<span class="LC_filename">'.
10281:                                   $container.'</span>').'</p>';
10282:                     } else {
10283:                          $output = '<p class="LC_error">'.
10284:                                    &mt('Error: could not update [_1].',
10285:                                    '<span class="LC_filename">'.
10286:                                    $container.'</span>').'</p>';
10287:                     }
10288:                 }
10289:             }
10290:         } else {
10291:             &logthis('Failed to parse '.$container.
10292:                      ' to modify references: '.$parse_result);
10293:         }
10294:     }
10295:     if (wantarray) {
10296:         return ($output,$count,$codebasecount);
10297:     } else {
10298:         return $output;
10299:     }
10300: }
10301: 
10302: sub check_for_existing {
10303:     my ($path,$fname,$element) = @_;
10304:     my ($state,$msg);
10305:     if (-d $path.'/'.$fname) {
10306:         $state = 'exists';
10307:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10308:     } elsif (-e $path.'/'.$fname) {
10309:         $state = 'exists';
10310:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10311:     }
10312:     if ($state eq 'exists') {
10313:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10314:     }
10315:     return ($state,$msg);
10316: }
10317: 
10318: sub check_for_upload {
10319:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10320:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10321:     my $filesize = length($env{'form.'.$element});
10322:     if (!$filesize) {
10323:         my $msg = '<span class="LC_error">'.
10324:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10325:                       '<span class="LC_filename">'.$fname.'</span>',
10326:                       $filesize).'<br />'.
10327:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10328:                   '</span>';
10329:         return ('zero_bytes',$msg);
10330:     }
10331:     $filesize =  $filesize/1000; #express in k (1024?)
10332:     my $getpropath = 1;
10333:     my ($dirlistref,$listerror) =
10334:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10335:     my $found_file = 0;
10336:     my $locked_file = 0;
10337:     my @lockers;
10338:     my $navmap;
10339:     if ($env{'request.course.id'}) {
10340:         $navmap = Apache::lonnavmaps::navmap->new();
10341:     }
10342:     if (ref($dirlistref) eq 'ARRAY') {
10343:         foreach my $line (@{$dirlistref}) {
10344:             my ($file_name,$rest)=split(/\&/,$line,2);
10345:             if ($file_name eq $fname){
10346:                 $file_name = $path.$file_name;
10347:                 if ($group ne '') {
10348:                     $file_name = $group.$file_name;
10349:                 }
10350:                 $found_file = 1;
10351:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10352:                     foreach my $lock (@lockers) {
10353:                         if (ref($lock) eq 'ARRAY') {
10354:                             my ($symb,$crsid) = @{$lock};
10355:                             if ($crsid eq $env{'request.course.id'}) {
10356:                                 if (ref($navmap)) {
10357:                                     my $res = $navmap->getBySymb($symb);
10358:                                     foreach my $part (@{$res->parts()}) { 
10359:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10360:                                         unless (($slot_status == $res->RESERVED) ||
10361:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10362:                                             $locked_file = 1;
10363:                                         }
10364:                                     }
10365:                                 } else {
10366:                                     $locked_file = 1;
10367:                                 }
10368:                             } else {
10369:                                 $locked_file = 1;
10370:                             }
10371:                         }
10372:                    }
10373:                 } else {
10374:                     my @info = split(/\&/,$rest);
10375:                     my $currsize = $info[6]/1000;
10376:                     if ($currsize < $filesize) {
10377:                         my $extra = $filesize - $currsize;
10378:                         if (($current_disk_usage + $extra) > $disk_quota) {
10379:                             my $msg = '<span class="LC_error">'.
10380:                                       &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
10381:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10382:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10383:                                                    $disk_quota,$current_disk_usage);
10384:                             return ('will_exceed_quota',$msg);
10385:                         }
10386:                     }
10387:                 }
10388:             }
10389:         }
10390:     }
10391:     if (($current_disk_usage + $filesize) > $disk_quota){
10392:         my $msg = '<span class="LC_error">'.
10393:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10394:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10395:         return ('will_exceed_quota',$msg);
10396:     } elsif ($found_file) {
10397:         if ($locked_file) {
10398:             my $msg = '<span class="LC_error">';
10399:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
10400:             $msg .= '</span><br />';
10401:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10402:             return ('file_locked',$msg);
10403:         } else {
10404:             my $msg = '<span class="LC_error">';
10405:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10406:             $msg .= '</span>';
10407:             return ('existingfile',$msg);
10408:         }
10409:     }
10410: }
10411: 
10412: sub check_for_traversal {
10413:     my ($path,$url,$toplevel) = @_;
10414:     my @parts=split(/\//,$path);
10415:     my $cleanpath;
10416:     my $fullpath = $url;
10417:     for (my $i=0;$i<@parts;$i++) {
10418:         next if ($parts[$i] eq '.');
10419:         if ($parts[$i] eq '..') {
10420:             $fullpath =~ s{([^/]+/)$}{};
10421:         } else {
10422:             $fullpath .= $parts[$i].'/';
10423:         }
10424:     }
10425:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10426:         $cleanpath = $1;
10427:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10428:         my $curr_toprel = $1;
10429:         my @parts = split(/\//,$curr_toprel);
10430:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10431:         my @urlparts = split(/\//,$url_toprel);
10432:         my $doubledots;
10433:         my $startdiff = -1;
10434:         for (my $i=0; $i<@urlparts; $i++) {
10435:             if ($startdiff == -1) {
10436:                 unless ($urlparts[$i] eq $parts[$i]) {
10437:                     $startdiff = $i;
10438:                     $doubledots .= '../';
10439:                 }
10440:             } else {
10441:                 $doubledots .= '../';
10442:             }
10443:         }
10444:         if ($startdiff > -1) {
10445:             $cleanpath = $doubledots;
10446:             for (my $i=$startdiff; $i<@parts; $i++) {
10447:                 $cleanpath .= $parts[$i].'/';
10448:             }
10449:         }
10450:     }
10451:     $cleanpath =~ s{(/)$}{};
10452:     return $cleanpath;
10453: }
10454: 
10455: sub is_archive_file {
10456:     my ($mimetype) = @_;
10457:     if (($mimetype eq 'application/octet-stream') ||
10458:         ($mimetype eq 'application/x-stuffit') ||
10459:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10460:         return 1;
10461:     }
10462:     return;
10463: }
10464: 
10465: sub decompress_form {
10466:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10467:     my %lt = &Apache::lonlocal::texthash (
10468:         this => 'This file is an archive file.',
10469:         camt => 'This file is a Camtasia archive file.',
10470:         itsc => 'Its contents are as follows:',
10471:         youm => 'You may wish to extract its contents.',
10472:         extr => 'Extract contents',
10473:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10474:         proa => 'Process automatically?',
10475:         yes  => 'Yes',
10476:         no   => 'No',
10477:         fold => 'Title for folder containing movie',
10478:         movi => 'Title for page containing embedded movie', 
10479:     );
10480:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10481:     my ($is_camtasia,$topdir,%toplevel,@paths);
10482:     my $info = &list_archive_contents($fileloc,\@paths);
10483:     if (@paths) {
10484:         foreach my $path (@paths) {
10485:             $path =~ s{^/}{};
10486:             if ($path =~ m{^([^/]+)/$}) {
10487:                 $topdir = $1;
10488:             }
10489:             if ($path =~ m{^([^/]+)/}) {
10490:                 $toplevel{$1} = $path;
10491:             } else {
10492:                 $toplevel{$path} = $path;
10493:             }
10494:         }
10495:     }
10496:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10497:         my @camtasia = ("$topdir/","$topdir/index.html",
10498:                         "$topdir/media/",
10499:                         "$topdir/media/$topdir.mp4",
10500:                         "$topdir/media/FirstFrame.png",
10501:                         "$topdir/media/player.swf",
10502:                         "$topdir/media/swfobject.js",
10503:                         "$topdir/media/expressInstall.swf");
10504:         my @diffs = &compare_arrays(\@paths,\@camtasia);
10505:         if (@diffs == 0) {
10506:             $is_camtasia = 1;
10507:         }
10508:     }
10509:     my $output;
10510:     if ($is_camtasia) {
10511:         $output = <<"ENDCAM";
10512: <script type="text/javascript" language="Javascript">
10513: // <![CDATA[
10514: 
10515: function camtasiaToggle() {
10516:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
10517:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
10518:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
10519: 
10520:                 document.getElementById('camtasia_titles').style.display='block';
10521:             } else {
10522:                 document.getElementById('camtasia_titles').style.display='none';
10523:             }
10524:         }
10525:     }
10526:     return;
10527: }
10528: 
10529: // ]]>
10530: </script>
10531: <p>$lt{'camt'}</p>
10532: ENDCAM
10533:     } else {
10534:         $output = '<p>'.$lt{'this'};
10535:         if ($info eq '') {
10536:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
10537:         } else {
10538:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
10539:                        '<div><pre>'.$info.'</pre></div>';
10540:         }
10541:     }
10542:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
10543:     my $duplicates;
10544:     my $num = 0;
10545:     if (ref($dirlist) eq 'ARRAY') {
10546:         foreach my $item (@{$dirlist}) {
10547:             if (ref($item) eq 'ARRAY') {
10548:                 if (exists($toplevel{$item->[0]})) {
10549:                     $duplicates .= 
10550:                         &start_data_table_row().
10551:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
10552:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
10553:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
10554:                         'value="1" />'.&mt('Yes').'</label>'.
10555:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
10556:                         '<td>'.$item->[0].'</td>';
10557:                     if ($item->[2]) {
10558:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
10559:                     } else {
10560:                         $duplicates .= '<td>'.&mt('File').'</td>';
10561:                     }
10562:                     $duplicates .= '<td>'.$item->[3].'</td>'.
10563:                                    '<td>'.
10564:                                    &Apache::lonlocal::locallocaltime($item->[4]).
10565:                                    '</td>'.
10566:                                    &end_data_table_row();
10567:                     $num ++;
10568:                 }
10569:             }
10570:         }
10571:     }
10572:     my $itemcount;
10573:     if (@paths > 0) {
10574:         $itemcount = scalar(@paths);
10575:     } else {
10576:         $itemcount = 1;
10577:     }
10578:     if ($is_camtasia) {
10579:         $output .= $lt{'auto'}.'<br />'.
10580:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
10581:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
10582:                    $lt{'yes'}.'</label>&nbsp;<label>'.
10583:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
10584:                    $lt{'no'}.'</label></span><br />'.
10585:                    '<div id="camtasia_titles" style="display:block">'.
10586:                    &Apache::lonhtmlcommon::start_pick_box().
10587:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
10588:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
10589:                    &Apache::lonhtmlcommon::row_closure().
10590:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
10591:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
10592:                    &Apache::lonhtmlcommon::row_closure(1).
10593:                    &Apache::lonhtmlcommon::end_pick_box().
10594:                    '</div>';
10595:     }
10596:     $output .= 
10597:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
10598:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
10599:         "\n";
10600:     if ($duplicates ne '') {
10601:         $output .= '<p><span class="LC_warning">'.
10602:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
10603:                    &start_data_table().
10604:                    &start_data_table_header_row().
10605:                    '<th>'.&mt('Overwrite?').'</th>'.
10606:                    '<th>'.&mt('Name').'</th>'.
10607:                    '<th>'.&mt('Type').'</th>'.
10608:                    '<th>'.&mt('Size').'</th>'.
10609:                    '<th>'.&mt('Last modified').'</th>'.
10610:                    &end_data_table_header_row().
10611:                    $duplicates.
10612:                    &end_data_table().
10613:                    '</p>';
10614:     }
10615:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
10616:     if (ref($hiddenelements) eq 'HASH') {
10617:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
10618:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
10619:         }
10620:     }
10621:     $output .= <<"END";
10622: <br />
10623: <input type="submit" name="decompress" value="$lt{'extr'}" />
10624: </form>
10625: $noextract
10626: END
10627:     return $output;
10628: }
10629: 
10630: sub decompression_utility {
10631:     my ($program) = @_;
10632:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
10633:     my $location;
10634:     if (grep(/^\Q$program\E$/,@utilities)) { 
10635:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
10636:                          '/usr/sbin/') {
10637:             if (-x $dir.$program) {
10638:                 $location = $dir.$program;
10639:                 last;
10640:             }
10641:         }
10642:     }
10643:     return $location;
10644: }
10645: 
10646: sub list_archive_contents {
10647:     my ($file,$pathsref) = @_;
10648:     my (@cmd,$output);
10649:     my $needsregexp;
10650:     if ($file =~ /\.zip$/) {
10651:         @cmd = (&decompression_utility('unzip'),"-l");
10652:         $needsregexp = 1;
10653:     } elsif (($file =~ m/\.tar\.gz$/) ||
10654:              ($file =~ /\.tgz$/)) {
10655:         @cmd = (&decompression_utility('tar'),"-ztf");
10656:     } elsif ($file =~ /\.tar\.bz2$/) {
10657:         @cmd = (&decompression_utility('tar'),"-jtf");
10658:     } elsif ($file =~ m|\.tar$|) {
10659:         @cmd = (&decompression_utility('tar'),"-tf");
10660:     }
10661:     if (@cmd) {
10662:         undef($!);
10663:         undef($@);
10664:         if (open(my $fh,"-|", @cmd, $file)) {
10665:             while (my $line = <$fh>) {
10666:                 $output .= $line;
10667:                 chomp($line);
10668:                 my $item;
10669:                 if ($needsregexp) {
10670:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
10671:                 } else {
10672:                     $item = $line;
10673:                 }
10674:                 if ($item ne '') {
10675:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
10676:                         push(@{$pathsref},$item);
10677:                     } 
10678:                 }
10679:             }
10680:             close($fh);
10681:         }
10682:     }
10683:     return $output;
10684: }
10685: 
10686: sub decompress_uploaded_file {
10687:     my ($file,$dir) = @_;
10688:     &Apache::lonnet::appenv({'cgi.file' => $file});
10689:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
10690:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
10691:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
10692:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
10693:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
10694:     my $decompressed = $env{'cgi.decompressed'};
10695:     &Apache::lonnet::delenv('cgi.file');
10696:     &Apache::lonnet::delenv('cgi.dir');
10697:     &Apache::lonnet::delenv('cgi.decompressed');
10698:     return ($decompressed,$result);
10699: }
10700: 
10701: sub process_decompression {
10702:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
10703:     my ($dir,$error,$warning,$output);
10704:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
10705:         $error = &mt('File name not a supported archive file type.').
10706:                  '<br />'.&mt('File name should end with one of: [_1].',
10707:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
10708:     } else {
10709:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10710:         if ($docuhome eq 'no_host') {
10711:             $error = &mt('Could not determine home server for course.');
10712:         } else {
10713:             my @ids=&Apache::lonnet::current_machine_ids();
10714:             my $currdir = "$dir_root/$destination";
10715:             if (grep(/^\Q$docuhome\E$/,@ids)) {
10716:                 $dir = &LONCAPA::propath($docudom,$docuname).
10717:                        "$dir_root/$destination";
10718:             } else {
10719:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
10720:                        "$dir_root/$docudom/$docuname/$destination";
10721:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
10722:                     $error = &mt('Archive file not found.');
10723:                 }
10724:             }
10725:             my (@to_overwrite,@to_skip);
10726:             if ($env{'form.archive_overwrite_total'} > 0) {
10727:                 my $total = $env{'form.archive_overwrite_total'};
10728:                 for (my $i=0; $i<$total; $i++) {
10729:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
10730:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
10731:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
10732:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
10733:                     }
10734:                 }
10735:             }
10736:             my $numskip = scalar(@to_skip);
10737:             if (($numskip > 0) && 
10738:                 ($numskip == $env{'form.archive_itemcount'})) {
10739:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
10740:             } elsif ($dir eq '') {
10741:                 $error = &mt('Directory containing archive file unavailable.');
10742:             } elsif (!$error) {
10743:                 my ($decompressed,$display);
10744:                 if ($numskip > 0) {
10745:                     my $tempdir = time.'_'.$$.int(rand(10000));
10746:                     mkdir("$dir/$tempdir",0755);
10747:                     system("mv $dir/$file $dir/$tempdir/$file");
10748:                     ($decompressed,$display) = 
10749:                         &decompress_uploaded_file($file,"$dir/$tempdir");
10750:                     foreach my $item (@to_skip) {
10751:                         if (($item ne '') && ($item !~ /\.\./)) {
10752:                             if (-f "$dir/$tempdir/$item") { 
10753:                                 unlink("$dir/$tempdir/$item");
10754:                             } elsif (-d "$dir/$tempdir/$item") {
10755:                                 system("rm -rf $dir/$tempdir/$item");
10756:                             }
10757:                         }
10758:                     }
10759:                     system("mv $dir/$tempdir/* $dir");
10760:                     rmdir("$dir/$tempdir");   
10761:                 } else {
10762:                     ($decompressed,$display) = 
10763:                         &decompress_uploaded_file($file,$dir);
10764:                 }
10765:                 if ($decompressed eq 'ok') {
10766:                     $output = '<p class="LC_info">'.
10767:                               &mt('Files extracted successfully from archive.').
10768:                               '</p>'."\n";
10769:                     my ($warning,$result,@contents);
10770:                     my ($newdirlistref,$newlisterror) =
10771:                         &Apache::lonnet::dirlist($currdir,$docudom,
10772:                                                  $docuname,1);
10773:                     my (%is_dir,%changes,@newitems);
10774:                     my $dirptr = 16384;
10775:                     if (ref($newdirlistref) eq 'ARRAY') {
10776:                         foreach my $dir_line (@{$newdirlistref}) {
10777:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10778:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
10779:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
10780:                                 push(@newitems,$item);
10781:                                 if ($dirptr&$testdir) {
10782:                                     $is_dir{$item} = 1;
10783:                                 }
10784:                                 $changes{$item} = 1;
10785:                             }
10786:                         }
10787:                     }
10788:                     if (keys(%changes) > 0) {
10789:                         foreach my $item (sort(@newitems)) {
10790:                             if ($changes{$item}) {
10791:                                 push(@contents,$item);
10792:                             }
10793:                         }
10794:                     }
10795:                     if (@contents > 0) {
10796:                         my $wantform;
10797:                         unless ($env{'form.autoextract_camtasia'}) {
10798:                             $wantform = 1;
10799:                         }
10800:                         my (%children,%parent,%dirorder,%titles);
10801:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
10802:                                                                 $currdir,\%is_dir,
10803:                                                                 \%children,\%parent,
10804:                                                                 \@contents,\%dirorder,
10805:                                                                 \%titles,$wantform);
10806:                         if ($datatable ne '') {
10807:                             $output .= &archive_options_form('decompressed',$datatable,
10808:                                                              $count,$hiddenelem);
10809:                             my $startcount = 6;
10810:                             $output .= &archive_javascript($startcount,$count,
10811:                                                            \%titles,\%children);
10812:                         }
10813:                         if ($env{'form.autoextract_camtasia'}) {
10814:                             my %displayed;
10815:                             my $total = 1;
10816:                             $env{'form.archive_directory'} = [];
10817:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
10818:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
10819:                                 $path =~ s{/$}{};
10820:                                 my $item;
10821:                                 if ($path ne '') {
10822:                                     $item = "$path/$titles{$i}";
10823:                                 } else {
10824:                                     $item = $titles{$i};
10825:                                 }
10826:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
10827:                                 if ($item eq $contents[0]) {
10828:                                     push(@{$env{'form.archive_directory'}},$i);
10829:                                     $env{'form.archive_'.$i} = 'display';
10830:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
10831:                                     $displayed{'folder'} = $i;
10832:                                 } elsif ($item eq "$contents[0]/index.html") {
10833:                                     $env{'form.archive_'.$i} = 'display';
10834:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
10835:                                     $displayed{'web'} = $i;
10836:                                 } else {
10837:                                     if ($item eq "$contents[0]/media") {
10838:                                         push(@{$env{'form.archive_directory'}},$i);
10839:                                     }
10840:                                     $env{'form.archive_'.$i} = 'dependency';
10841:                                 }
10842:                                 $total ++;
10843:                             }
10844:                             for (my $i=1; $i<$total; $i++) {
10845:                                 next if ($i == $displayed{'web'});
10846:                                 next if ($i == $displayed{'folder'});
10847:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
10848:                             }
10849:                             $env{'form.phase'} = 'decompress_cleanup';
10850:                             $env{'form.archivedelete'} = 1;
10851:                             $env{'form.archive_count'} = $total-1;
10852:                             $output .=
10853:                                 &process_extracted_files('coursedocs',$docudom,
10854:                                                          $docuname,$destination,
10855:                                                          $dir_root,$hiddenelem);
10856:                         }
10857:                     } else {
10858:                         $warning = &mt('No new items extracted from archive file.');
10859:                     }
10860:                 } else {
10861:                     $output = $display;
10862:                     $error = &mt('An error occurred during extraction from the archive file.');
10863:                 }
10864:             }
10865:         }
10866:     }
10867:     if ($error) {
10868:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
10869:                    $error.'</p>'."\n";
10870:     }
10871:     if ($warning) {
10872:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
10873:     }
10874:     return $output;
10875: }
10876: 
10877: sub get_extracted {
10878:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
10879:         $titles,$wantform) = @_;
10880:     my $count = 0;
10881:     my $depth = 0;
10882:     my $datatable;
10883:     my @hierarchy;
10884:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
10885:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
10886:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
10887:     foreach my $item (@{$contents}) {
10888:         $count ++;
10889:         @{$dirorder->{$count}} = @hierarchy;
10890:         $titles->{$count} = $item;
10891:         &archive_hierarchy($depth,$count,$parent,$children);
10892:         if ($wantform) {
10893:             $datatable .= &archive_row($is_dir->{$item},$item,
10894:                                        $currdir,$depth,$count);
10895:         }
10896:         if ($is_dir->{$item}) {
10897:             $depth ++;
10898:             push(@hierarchy,$count);
10899:             $parent->{$depth} = $count;
10900:             $datatable .=
10901:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
10902:                                            \$depth,\$count,\@hierarchy,$dirorder,
10903:                                            $children,$parent,$titles,$wantform);
10904:             $depth --;
10905:             pop(@hierarchy);
10906:         }
10907:     }
10908:     return ($count,$datatable);
10909: }
10910: 
10911: sub recurse_extracted_archive {
10912:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
10913:         $children,$parent,$titles,$wantform) = @_;
10914:     my $result='';
10915:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
10916:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
10917:             (ref($dirorder) eq 'HASH')) {
10918:         return $result;
10919:     }
10920:     my $dirptr = 16384;
10921:     my ($newdirlistref,$newlisterror) =
10922:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
10923:     if (ref($newdirlistref) eq 'ARRAY') {
10924:         foreach my $dir_line (@{$newdirlistref}) {
10925:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10926:             unless ($item =~ /^\.+$/) {
10927:                 $$count ++;
10928:                 @{$dirorder->{$$count}} = @{$hierarchy};
10929:                 $titles->{$$count} = $item;
10930:                 &archive_hierarchy($$depth,$$count,$parent,$children);
10931: 
10932:                 my $is_dir;
10933:                 if ($dirptr&$testdir) {
10934:                     $is_dir = 1;
10935:                 }
10936:                 if ($wantform) {
10937:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
10938:                 }
10939:                 if ($is_dir) {
10940:                     $$depth ++;
10941:                     push(@{$hierarchy},$$count);
10942:                     $parent->{$$depth} = $$count;
10943:                     $result .=
10944:                         &recurse_extracted_archive("$currdir/$item",$docudom,
10945:                                                    $docuname,$depth,$count,
10946:                                                    $hierarchy,$dirorder,$children,
10947:                                                    $parent,$titles,$wantform);
10948:                     $$depth --;
10949:                     pop(@{$hierarchy});
10950:                 }
10951:             }
10952:         }
10953:     }
10954:     return $result;
10955: }
10956: 
10957: sub archive_hierarchy {
10958:     my ($depth,$count,$parent,$children) =@_;
10959:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
10960:         if (exists($parent->{$depth})) {
10961:              $children->{$parent->{$depth}} .= $count.':';
10962:         }
10963:     }
10964:     return;
10965: }
10966: 
10967: sub archive_row {
10968:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
10969:     my ($name) = ($item =~ m{([^/]+)$});
10970:     my %choices = &Apache::lonlocal::texthash (
10971:                                        'display'    => 'Add as file',
10972:                                        'dependency' => 'Include as dependency',
10973:                                        'discard'    => 'Discard',
10974:                                       );
10975:     if ($is_dir) {
10976:         $choices{'display'} = &mt('Add as folder'); 
10977:     }
10978:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
10979:     my $offset = 0;
10980:     foreach my $action ('display','dependency','discard') {
10981:         $offset ++;
10982:         if ($action ne 'display') {
10983:             $offset ++;
10984:         }  
10985:         $output .= '<td><span class="LC_nobreak">'.
10986:                    '<label><input type="radio" name="archive_'.$count.
10987:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
10988:         my $text = $choices{$action};
10989:         if ($is_dir) {
10990:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
10991:             if ($action eq 'display') {
10992:                 $text = &mt('Add as folder');
10993:             }
10994:         } else {
10995:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
10996: 
10997:         }
10998:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
10999:         if ($action eq 'dependency') {
11000:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11001:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11002:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11003:                        '<option value=""></option>'."\n".
11004:                        '</select>'."\n".
11005:                        '</div>';
11006:         } elsif ($action eq 'display') {
11007:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11008:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11009:                        '</div>';
11010:         }
11011:         $output .= '</td>';
11012:     }
11013:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11014:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11015:     for (my $i=0; $i<$depth; $i++) {
11016:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11017:     }
11018:     if ($is_dir) {
11019:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11020:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11021:     } else {
11022:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11023:     }
11024:     $output .= '&nbsp;'.$name.'</td>'."\n".
11025:                &end_data_table_row();
11026:     return $output;
11027: }
11028: 
11029: sub archive_options_form {
11030:     my ($form,$display,$count,$hiddenelem) = @_;
11031:     my %lt = &Apache::lonlocal::texthash(
11032:                perm => 'Permanently remove archive file?',
11033:                hows => 'How should each extracted item be incorporated in the course?',
11034:                cont => 'Content actions for all',
11035:                addf => 'Add as folder/file',
11036:                incd => 'Include as dependency for a displayed file',
11037:                disc => 'Discard',
11038:                no   => 'No',
11039:                yes  => 'Yes',
11040:                save => 'Save',
11041:     );
11042:     my $output = <<"END";
11043: <form name="$form" method="post" action="">
11044: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11045: <label>
11046:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11047: </label>
11048: &nbsp;
11049: <label>
11050:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11051: </span>
11052: </p>
11053: <input type="hidden" name="phase" value="decompress_cleanup" />
11054: <br />$lt{'hows'}
11055: <div class="LC_columnSection">
11056:   <fieldset>
11057:     <legend>$lt{'cont'}</legend>
11058:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11059:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11060:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11061:   </fieldset>
11062: </div>
11063: END
11064:     return $output.
11065:            &start_data_table()."\n".
11066:            $display."\n".
11067:            &end_data_table()."\n".
11068:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11069:            $hiddenelem.
11070:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11071:            '</form>';
11072: }
11073: 
11074: sub archive_javascript {
11075:     my ($startcount,$numitems,$titles,$children) = @_;
11076:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11077:     my $maintitle = $env{'form.comment'};
11078:     my $scripttag = <<START;
11079: <script type="text/javascript">
11080: // <![CDATA[
11081: 
11082: function checkAll(form,prefix) {
11083:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11084:     for (var i=0; i < form.elements.length; i++) {
11085:         var id = form.elements[i].id;
11086:         if ((id != '') && (id != undefined)) {
11087:             if (idstr.test(id)) {
11088:                 if (form.elements[i].type == 'radio') {
11089:                     form.elements[i].checked = true;
11090:                     var nostart = i-$startcount;
11091:                     var offset = nostart%7;
11092:                     var count = (nostart-offset)/7;    
11093:                     dependencyCheck(form,count,offset);
11094:                 }
11095:             }
11096:         }
11097:     }
11098: }
11099: 
11100: function propagateCheck(form,count) {
11101:     if (count > 0) {
11102:         var startelement = $startcount + ((count-1) * 7);
11103:         for (var j=1; j<6; j++) {
11104:             if ((j != 2) && (j != 4)) {
11105:                 var item = startelement + j; 
11106:                 if (form.elements[item].type == 'radio') {
11107:                     if (form.elements[item].checked) {
11108:                         containerCheck(form,count,j);
11109:                         break;
11110:                     }
11111:                 }
11112:             }
11113:         }
11114:     }
11115: }
11116: 
11117: numitems = $numitems
11118: var titles = new Array(numitems);
11119: var parents = new Array(numitems);
11120: for (var i=0; i<numitems; i++) {
11121:     parents[i] = new Array;
11122: }
11123: var maintitle = '$maintitle';
11124: 
11125: START
11126: 
11127:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11128:         my @contents = split(/:/,$children->{$container});
11129:         for (my $i=0; $i<@contents; $i ++) {
11130:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11131:         }
11132:     }
11133: 
11134:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11135:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11136:     }
11137: 
11138:     $scripttag .= <<END;
11139: 
11140: function containerCheck(form,count,offset) {
11141:     if (count > 0) {
11142:         dependencyCheck(form,count,offset);
11143:         var item = (offset+$startcount)+7*(count-1);
11144:         form.elements[item].checked = true;
11145:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11146:             if (parents[count].length > 0) {
11147:                 for (var j=0; j<parents[count].length; j++) {
11148:                     containerCheck(form,parents[count][j],offset);
11149:                 }
11150:             }
11151:         }
11152:     }
11153: }
11154: 
11155: function dependencyCheck(form,count,offset) {
11156:     if (count > 0) {
11157:         var chosen = (offset+$startcount)+7*(count-1);
11158:         var depitem = $startcount + ((count-1) * 7) + 4;
11159:         var currtype = form.elements[depitem].type;
11160:         if (form.elements[chosen].value == 'dependency') {
11161:             document.getElementById('arc_depon_'+count).style.display='block'; 
11162:             form.elements[depitem].options.length = 0;
11163:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11164:             for (var i=1; i<=numitems; i++) {
11165:                 if (i == count) {
11166:                     continue;
11167:                 }
11168:                 var startelement = $startcount + (i-1) * 7;
11169:                 for (var j=1; j<6; j++) {
11170:                     if ((j != 2) && (j!= 4)) {
11171:                         var item = startelement + j;
11172:                         if (form.elements[item].type == 'radio') {
11173:                             if (form.elements[item].checked) {
11174:                                 if (form.elements[item].value == 'display') {
11175:                                     var n = form.elements[depitem].options.length;
11176:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11177:                                 }
11178:                             }
11179:                         }
11180:                     }
11181:                 }
11182:             }
11183:         } else {
11184:             document.getElementById('arc_depon_'+count).style.display='none';
11185:             form.elements[depitem].options.length = 0;
11186:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11187:         }
11188:         titleCheck(form,count,offset);
11189:     }
11190: }
11191: 
11192: function propagateSelect(form,count,offset) {
11193:     if (count > 0) {
11194:         var item = (1+offset+$startcount)+7*(count-1);
11195:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11196:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11197:             if (parents[count].length > 0) {
11198:                 for (var j=0; j<parents[count].length; j++) {
11199:                     containerSelect(form,parents[count][j],offset,picked);
11200:                 }
11201:             }
11202:         }
11203:     }
11204: }
11205: 
11206: function containerSelect(form,count,offset,picked) {
11207:     if (count > 0) {
11208:         var item = (offset+$startcount)+7*(count-1);
11209:         if (form.elements[item].type == 'radio') {
11210:             if (form.elements[item].value == 'dependency') {
11211:                 if (form.elements[item+1].type == 'select-one') {
11212:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11213:                         if (form.elements[item+1].options[i].value == picked) {
11214:                             form.elements[item+1].selectedIndex = i;
11215:                             break;
11216:                         }
11217:                     }
11218:                 }
11219:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11220:                     if (parents[count].length > 0) {
11221:                         for (var j=0; j<parents[count].length; j++) {
11222:                             containerSelect(form,parents[count][j],offset,picked);
11223:                         }
11224:                     }
11225:                 }
11226:             }
11227:         }
11228:     }
11229: }
11230: 
11231: function titleCheck(form,count,offset) {
11232:     if (count > 0) {
11233:         var chosen = (offset+$startcount)+7*(count-1);
11234:         var depitem = $startcount + ((count-1) * 7) + 2;
11235:         var currtype = form.elements[depitem].type;
11236:         if (form.elements[chosen].value == 'display') {
11237:             document.getElementById('arc_title_'+count).style.display='block';
11238:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11239:                 document.getElementById('archive_title_'+count).value=maintitle;
11240:             }
11241:         } else {
11242:             document.getElementById('arc_title_'+count).style.display='none';
11243:             if (currtype == 'text') { 
11244:                 document.getElementById('archive_title_'+count).value='';
11245:             }
11246:         }
11247:     }
11248:     return;
11249: }
11250: 
11251: // ]]>
11252: </script>
11253: END
11254:     return $scripttag;
11255: }
11256: 
11257: sub process_extracted_files {
11258:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11259:     my $numitems = $env{'form.archive_count'};
11260:     return unless ($numitems);
11261:     my @ids=&Apache::lonnet::current_machine_ids();
11262:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11263:         %folders,%containers,%mapinner,%prompttofetch);
11264:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11265:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11266:         $prefix = &LONCAPA::propath($docudom,$docuname);
11267:         $pathtocheck = "$dir_root/$destination";
11268:         $dir = $dir_root;
11269:         $ishome = 1;
11270:     } else {
11271:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11272:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11273:         $dir = "$dir_root/$docudom/$docuname";    
11274:     }
11275:     my $currdir = "$dir_root/$destination";
11276:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11277:     if ($env{'form.folderpath'}) {
11278:         my @items = split('&',$env{'form.folderpath'});
11279:         $folders{'0'} = $items[-2];
11280:         $containers{'0'}='sequence';
11281:     } elsif ($env{'form.pagepath'}) {
11282:         my @items = split('&',$env{'form.pagepath'});
11283:         $folders{'0'} = $items[-2];
11284:         $containers{'0'}='page';
11285:     }
11286:     my @archdirs = &get_env_multiple('form.archive_directory');
11287:     if ($numitems) {
11288:         for (my $i=1; $i<=$numitems; $i++) {
11289:             my $path = $env{'form.archive_content_'.$i};
11290:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11291:                 my $item = $1;
11292:                 $toplevelitems{$item} = $i;
11293:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11294:                     $is_dir{$item} = 1;
11295:                 }
11296:             }
11297:         }
11298:     }
11299:     my ($output,%children,%parent,%titles,%dirorder,$result);
11300:     if (keys(%toplevelitems) > 0) {
11301:         my @contents = sort(keys(%toplevelitems));
11302:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11303:                                            \%parent,\@contents,\%dirorder,\%titles);
11304:     }
11305:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11306:     if ($numitems) {
11307:         for (my $i=1; $i<=$numitems; $i++) {
11308:             next if ($env{'form.archive_'.$i} eq 'dependency');
11309:             my $path = $env{'form.archive_content_'.$i};
11310:             if ($path =~ /^\Q$pathtocheck\E/) {
11311:                 if ($env{'form.archive_'.$i} eq 'discard') {
11312:                     if ($prefix ne '' && $path ne '') {
11313:                         if (-e $prefix.$path) {
11314:                             if ((@archdirs > 0) && 
11315:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11316:                                 $todeletedir{$prefix.$path} = 1;
11317:                             } else {
11318:                                 $todelete{$prefix.$path} = 1;
11319:                             }
11320:                         }
11321:                     }
11322:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11323:                     my ($docstitle,$title,$url,$outer);
11324:                     ($title) = ($path =~ m{/([^/]+)$});
11325:                     $docstitle = $env{'form.archive_title_'.$i};
11326:                     if ($docstitle eq '') {
11327:                         $docstitle = $title;
11328:                     }
11329:                     $outer = 0;
11330:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11331:                         if (@{$dirorder{$i}} > 0) {
11332:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11333:                                 if ($env{'form.archive_'.$item} eq 'display') {
11334:                                     $outer = $item;
11335:                                     last;
11336:                                 }
11337:                             }
11338:                         }
11339:                     }
11340:                     my ($errtext,$fatal) = 
11341:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11342:                                                '/'.$folders{$outer}.'.'.
11343:                                                $containers{$outer});
11344:                     next if ($fatal);
11345:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11346:                         if ($context eq 'coursedocs') {
11347:                             $mapinner{$i} = time;
11348:                             $folders{$i} = 'default_'.$mapinner{$i};
11349:                             $containers{$i} = 'sequence';
11350:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11351:                                       $folders{$i}.'.'.$containers{$i};
11352:                             my $newidx = &LONCAPA::map::getresidx();
11353:                             $LONCAPA::map::resources[$newidx]=
11354:                                 $docstitle.':'.$url.':false:normal:res';
11355:                             push(@LONCAPA::map::order,$newidx);
11356:                             my ($outtext,$errtext) =
11357:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11358:                                                         $docuname.'/'.$folders{$outer}.
11359:                                                         '.'.$containers{$outer},1,1);
11360:                             $newseqid{$i} = $newidx;
11361:                             unless ($errtext) {
11362:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11363:                             }
11364:                         }
11365:                     } else {
11366:                         if ($context eq 'coursedocs') {
11367:                             my $newidx=&LONCAPA::map::getresidx();
11368:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11369:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11370:                                       $title;
11371:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11372:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11373:                             }
11374:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11375:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11376:                             }
11377:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11378:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11379:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11380:                                 unless ($ishome) {
11381:                                     my $fetch = "$newdest{$i}/$title";
11382:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11383:                                     $prompttofetch{$fetch} = 1;
11384:                                 }
11385:                             }
11386:                             $LONCAPA::map::resources[$newidx]=
11387:                                 $docstitle.':'.$url.':false:normal:res';
11388:                             push(@LONCAPA::map::order, $newidx);
11389:                             my ($outtext,$errtext)=
11390:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11391:                                                         $docuname.'/'.$folders{$outer}.
11392:                                                         '.'.$containers{$outer},1,1);
11393:                             unless ($errtext) {
11394:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11395:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11396:                                 }
11397:                             }
11398:                         }
11399:                     }
11400:                 }
11401:             } else {
11402:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
11403:             }
11404:         }
11405:         for (my $i=1; $i<=$numitems; $i++) {
11406:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11407:             my $path = $env{'form.archive_content_'.$i};
11408:             if ($path =~ /^\Q$pathtocheck\E/) {
11409:                 my ($title) = ($path =~ m{/([^/]+)$});
11410:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11411:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11412:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11413:                         my ($itemidx,$fullpath,$relpath);
11414:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11415:                             my $container = $dirorder{$referrer{$i}}->[-1];
11416:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11417:                                 if ($dirorder{$i}->[$j] eq $container) {
11418:                                     $itemidx = $j;
11419:                                 }
11420:                             }
11421:                         }
11422:                         if ($itemidx eq '') {
11423:                             $itemidx =  0;
11424:                         } 
11425:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11426:                             if ($mapinner{$referrer{$i}}) {
11427:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11428:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11429:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11430:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11431:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11432:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11433:                                             if (!-e $fullpath) {
11434:                                                 mkdir($fullpath,0755);
11435:                                             }
11436:                                         }
11437:                                     } else {
11438:                                         last;
11439:                                     }
11440:                                 }
11441:                             }
11442:                         } elsif ($newdest{$referrer{$i}}) {
11443:                             $fullpath = $newdest{$referrer{$i}};
11444:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11445:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11446:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11447:                                     last;
11448:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11449:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11450:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11451:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11452:                                         if (!-e $fullpath) {
11453:                                             mkdir($fullpath,0755);
11454:                                         }
11455:                                     }
11456:                                 } else {
11457:                                     last;
11458:                                 }
11459:                             }
11460:                         }
11461:                         if ($fullpath ne '') {
11462:                             if (-e "$prefix$path") {
11463:                                 system("mv $prefix$path $fullpath/$title");
11464:                             }
11465:                             if (-e "$fullpath/$title") {
11466:                                 my $showpath;
11467:                                 if ($relpath ne '') {
11468:                                     $showpath = "$relpath/$title";
11469:                                 } else {
11470:                                     $showpath = "/$title";
11471:                                 } 
11472:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
11473:                             } 
11474:                             unless ($ishome) {
11475:                                 my $fetch = "$fullpath/$title";
11476:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
11477:                                 $prompttofetch{$fetch} = 1;
11478:                             }
11479:                         }
11480:                     }
11481:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
11482:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
11483:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
11484:                 }
11485:             } else {
11486:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
11487:             }
11488:         }
11489:         if (keys(%todelete)) {
11490:             foreach my $key (keys(%todelete)) {
11491:                 unlink($key);
11492:             }
11493:         }
11494:         if (keys(%todeletedir)) {
11495:             foreach my $key (keys(%todeletedir)) {
11496:                 rmdir($key);
11497:             }
11498:         }
11499:         foreach my $dir (sort(keys(%is_dir))) {
11500:             if (($pathtocheck ne '') && ($dir ne ''))  {
11501:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
11502:             }
11503:         }
11504:         if ($result ne '') {
11505:             $output .= '<ul>'."\n".
11506:                        $result."\n".
11507:                        '</ul>';
11508:         }
11509:         unless ($ishome) {
11510:             my $replicationfail;
11511:             foreach my $item (keys(%prompttofetch)) {
11512:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
11513:                 unless ($fetchresult eq 'ok') {
11514:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
11515:                 }
11516:             }
11517:             if ($replicationfail) {
11518:                 $output .= '<p class="LC_error">'.
11519:                            &mt('Course home server failed to retrieve:').'<ul>'.
11520:                            $replicationfail.
11521:                            '</ul></p>';
11522:             }
11523:         }
11524:     } else {
11525:         $warning = &mt('No items found in archive.');
11526:     }
11527:     if ($error) {
11528:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11529:                    $error.'</p>'."\n";
11530:     }
11531:     if ($warning) {
11532:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11533:     }
11534:     return $output;
11535: }
11536: 
11537: sub cleanup_empty_dirs {
11538:     my ($path) = @_;
11539:     if (($path ne '') && (-d $path)) {
11540:         if (opendir(my $dirh,$path)) {
11541:             my @dircontents = grep(!/^\./,readdir($dirh));
11542:             my $numitems = 0;
11543:             foreach my $item (@dircontents) {
11544:                 if (-d "$path/$item") {
11545:                     &recurse_dirs("$path/$item");
11546:                     if (-e "$path/$item") {
11547:                         $numitems ++;
11548:                     }
11549:                 } else {
11550:                     $numitems ++;
11551:                 }
11552:             }
11553:             if ($numitems == 0) {
11554:                 rmdir($path);
11555:             }
11556:             closedir($dirh);
11557:         }
11558:     }
11559:     return;
11560: }
11561: 
11562: =pod
11563: 
11564: =item &get_folder_hierarchy()
11565: 
11566: Provides hierarchy of names of folders/sub-folders containing the current
11567: item,
11568: 
11569: Inputs: 3
11570:      - $navmap - navmaps object
11571: 
11572:      - $map - url for map (either the trigger itself, or map containing
11573:                            the resource, which is the trigger).
11574: 
11575:      - $showitem - 1 => show title for map itself; 0 => do not show.
11576: 
11577: Outputs: 1 @pathitems - array of folder/subfolder names.
11578: 
11579: =cut
11580: 
11581: sub get_folder_hierarchy {
11582:     my ($navmap,$map,$showitem) = @_;
11583:     my @pathitems;
11584:     if (ref($navmap)) {
11585:         my $mapres = $navmap->getResourceByUrl($map);
11586:         if (ref($mapres)) {
11587:             my $pcslist = $mapres->map_hierarchy();
11588:             if ($pcslist ne '') {
11589:                 my @pcs = split(/,/,$pcslist);
11590:                 foreach my $pc (@pcs) {
11591:                     if ($pc == 1) {
11592:                         push(@pathitems,&mt('Main Course Documents'));
11593:                     } else {
11594:                         my $res = $navmap->getByMapPc($pc);
11595:                         if (ref($res)) {
11596:                             my $title = $res->compTitle();
11597:                             $title =~ s/\W+/_/g;
11598:                             if ($title ne '') {
11599:                                 push(@pathitems,$title);
11600:                             }
11601:                         }
11602:                     }
11603:                 }
11604:             }
11605:             if ($showitem) {
11606:                 if ($mapres->{ID} eq '0.0') {
11607:                     push(@pathitems,&mt('Main Course Documents'));
11608:                 } else {
11609:                     my $maptitle = $mapres->compTitle();
11610:                     $maptitle =~ s/\W+/_/g;
11611:                     if ($maptitle ne '') {
11612:                         push(@pathitems,$maptitle);
11613:                     }
11614:                 }
11615:             }
11616:         }
11617:     }
11618:     return @pathitems;
11619: }
11620: 
11621: =pod
11622: 
11623: =item * &get_turnedin_filepath()
11624: 
11625: Determines path in a user's portfolio file for storage of files uploaded
11626: to a specific essayresponse or dropbox item.
11627: 
11628: Inputs: 3 required + 1 optional.
11629: $symb is symb for resource, $uname and $udom are for current user (required).
11630: $caller is optional (can be "submission", if routine is called when storing
11631: an upoaded file when "Submit Answer" button was pressed).
11632: 
11633: Returns array containing $path and $multiresp. 
11634: $path is path in portfolio.  $multiresp is 1 if this resource contains more
11635: than one file upload item.  Callers of routine should append partid as a 
11636: subdirectory to $path in cases where $multiresp is 1.
11637: 
11638: Called by: homework/essayresponse.pm and homework/structuretags.pm
11639: 
11640: =cut
11641: 
11642: sub get_turnedin_filepath {
11643:     my ($symb,$uname,$udom,$caller) = @_;
11644:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
11645:     my $turnindir;
11646:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
11647:     $turnindir = $userhash{'turnindir'};
11648:     my ($path,$multiresp);
11649:     if ($turnindir eq '') {
11650:         if ($caller eq 'submission') {
11651:             $turnindir = &mt('turned in');
11652:             $turnindir =~ s/\W+/_/g;
11653:             my %newhash = (
11654:                             'turnindir' => $turnindir,
11655:                           );
11656:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
11657:         }
11658:     }
11659:     if ($turnindir ne '') {
11660:         $path = '/'.$turnindir.'/';
11661:         my ($multipart,$turnin,@pathitems);
11662:         my $navmap = Apache::lonnavmaps::navmap->new();
11663:         if (defined($navmap)) {
11664:             my $mapres = $navmap->getResourceByUrl($map);
11665:             if (ref($mapres)) {
11666:                 my $pcslist = $mapres->map_hierarchy();
11667:                 if ($pcslist ne '') {
11668:                     foreach my $pc (split(/,/,$pcslist)) {
11669:                         my $res = $navmap->getByMapPc($pc);
11670:                         if (ref($res)) {
11671:                             my $title = $res->compTitle();
11672:                             $title =~ s/\W+/_/g;
11673:                             if ($title ne '') {
11674:                                 push(@pathitems,$title);
11675:                             }
11676:                         }
11677:                     }
11678:                 }
11679:                 my $maptitle = $mapres->compTitle();
11680:                 $maptitle =~ s/\W+/_/g;
11681:                 if ($maptitle ne '') {
11682:                     push(@pathitems,$maptitle);
11683:                 }
11684:                 unless ($env{'request.state'} eq 'construct') {
11685:                     my $res = $navmap->getBySymb($symb);
11686:                     if (ref($res)) {
11687:                         my $partlist = $res->parts();
11688:                         my $totaluploads = 0;
11689:                         if (ref($partlist) eq 'ARRAY') {
11690:                             foreach my $part (@{$partlist}) {
11691:                                 my @types = $res->responseType($part);
11692:                                 my @ids = $res->responseIds($part);
11693:                                 for (my $i=0; $i < scalar(@ids); $i++) {
11694:                                     if ($types[$i] eq 'essay') {
11695:                                         my $partid = $part.'_'.$ids[$i];
11696:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
11697:                                             $totaluploads ++;
11698:                                         }
11699:                                     }
11700:                                 }
11701:                             }
11702:                             if ($totaluploads > 1) {
11703:                                 $multiresp = 1;
11704:                             }
11705:                         }
11706:                     }
11707:                 }
11708:             } else {
11709:                 return;
11710:             }
11711:         } else {
11712:             return;
11713:         }
11714:         my $restitle=&Apache::lonnet::gettitle($symb);
11715:         $restitle =~ s/\W+/_/g;
11716:         if ($restitle eq '') {
11717:             $restitle = ($resurl =~ m{/[^/]+$});
11718:             if ($restitle eq '') {
11719:                 $restitle = time;
11720:             }
11721:         }
11722:         push(@pathitems,$restitle);
11723:         $path .= join('/',@pathitems);
11724:     }
11725:     return ($path,$multiresp);
11726: }
11727: 
11728: =pod
11729: 
11730: =back
11731: 
11732: =head1 CSV Upload/Handling functions
11733: 
11734: =over 4
11735: 
11736: =item * &upfile_store($r)
11737: 
11738: Store uploaded file, $r should be the HTTP Request object,
11739: needs $env{'form.upfile'}
11740: returns $datatoken to be put into hidden field
11741: 
11742: =cut
11743: 
11744: sub upfile_store {
11745:     my $r=shift;
11746:     $env{'form.upfile'}=~s/\r/\n/gs;
11747:     $env{'form.upfile'}=~s/\f/\n/gs;
11748:     $env{'form.upfile'}=~s/\n+/\n/gs;
11749:     $env{'form.upfile'}=~s/\n+$//gs;
11750: 
11751:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
11752: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
11753:     {
11754:         my $datafile = $r->dir_config('lonDaemons').
11755:                            '/tmp/'.$datatoken.'.tmp';
11756:         if ( open(my $fh,">$datafile") ) {
11757:             print $fh $env{'form.upfile'};
11758:             close($fh);
11759:         }
11760:     }
11761:     return $datatoken;
11762: }
11763: 
11764: =pod
11765: 
11766: =item * &load_tmp_file($r)
11767: 
11768: Load uploaded file from tmp, $r should be the HTTP Request object,
11769: needs $env{'form.datatoken'},
11770: sets $env{'form.upfile'} to the contents of the file
11771: 
11772: =cut
11773: 
11774: sub load_tmp_file {
11775:     my $r=shift;
11776:     my @studentdata=();
11777:     {
11778:         my $studentfile = $r->dir_config('lonDaemons').
11779:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
11780:         if ( open(my $fh,"<$studentfile") ) {
11781:             @studentdata=<$fh>;
11782:             close($fh);
11783:         }
11784:     }
11785:     $env{'form.upfile'}=join('',@studentdata);
11786: }
11787: 
11788: =pod
11789: 
11790: =item * &upfile_record_sep()
11791: 
11792: Separate uploaded file into records
11793: returns array of records,
11794: needs $env{'form.upfile'} and $env{'form.upfiletype'}
11795: 
11796: =cut
11797: 
11798: sub upfile_record_sep {
11799:     if ($env{'form.upfiletype'} eq 'xml') {
11800:     } else {
11801: 	my @records;
11802: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
11803: 	    if ($line=~/^\s*$/) { next; }
11804: 	    push(@records,$line);
11805: 	}
11806: 	return @records;
11807:     }
11808: }
11809: 
11810: =pod
11811: 
11812: =item * &record_sep($record)
11813: 
11814: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
11815: 
11816: =cut
11817: 
11818: sub takeleft {
11819:     my $index=shift;
11820:     return substr('0000'.$index,-4,4);
11821: }
11822: 
11823: sub record_sep {
11824:     my $record=shift;
11825:     my %components=();
11826:     if ($env{'form.upfiletype'} eq 'xml') {
11827:     } elsif ($env{'form.upfiletype'} eq 'space') {
11828:         my $i=0;
11829:         foreach my $field (split(/\s+/,$record)) {
11830:             $field=~s/^(\"|\')//;
11831:             $field=~s/(\"|\')$//;
11832:             $components{&takeleft($i)}=$field;
11833:             $i++;
11834:         }
11835:     } elsif ($env{'form.upfiletype'} eq 'tab') {
11836:         my $i=0;
11837:         foreach my $field (split(/\t/,$record)) {
11838:             $field=~s/^(\"|\')//;
11839:             $field=~s/(\"|\')$//;
11840:             $components{&takeleft($i)}=$field;
11841:             $i++;
11842:         }
11843:     } else {
11844:         my $separator=',';
11845:         if ($env{'form.upfiletype'} eq 'semisv') {
11846:             $separator=';';
11847:         }
11848:         my $i=0;
11849: # the character we are looking for to indicate the end of a quote or a record 
11850:         my $looking_for=$separator;
11851: # do not add the characters to the fields
11852:         my $ignore=0;
11853: # we just encountered a separator (or the beginning of the record)
11854:         my $just_found_separator=1;
11855: # store the field we are working on here
11856:         my $field='';
11857: # work our way through all characters in record
11858:         foreach my $character ($record=~/(.)/g) {
11859:             if ($character eq $looking_for) {
11860:                if ($character ne $separator) {
11861: # Found the end of a quote, again looking for separator
11862:                   $looking_for=$separator;
11863:                   $ignore=1;
11864:                } else {
11865: # Found a separator, store away what we got
11866:                   $components{&takeleft($i)}=$field;
11867: 	          $i++;
11868:                   $just_found_separator=1;
11869:                   $ignore=0;
11870:                   $field='';
11871:                }
11872:                next;
11873:             }
11874: # single or double quotation marks after a separator indicate beginning of a quote
11875: # we are now looking for the end of the quote and need to ignore separators
11876:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
11877:                $looking_for=$character;
11878:                next;
11879:             }
11880: # ignore would be true after we reached the end of a quote
11881:             if ($ignore) { next; }
11882:             if (($just_found_separator) && ($character=~/\s/)) { next; }
11883:             $field.=$character;
11884:             $just_found_separator=0; 
11885:         }
11886: # catch the very last entry, since we never encountered the separator
11887:         $components{&takeleft($i)}=$field;
11888:     }
11889:     return %components;
11890: }
11891: 
11892: ######################################################
11893: ######################################################
11894: 
11895: =pod
11896: 
11897: =item * &upfile_select_html()
11898: 
11899: Return HTML code to select a file from the users machine and specify 
11900: the file type.
11901: 
11902: =cut
11903: 
11904: ######################################################
11905: ######################################################
11906: sub upfile_select_html {
11907:     my %Types = (
11908:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
11909:                  semisv => &mt('Semicolon separated values'),
11910:                  space => &mt('Space separated'),
11911:                  tab   => &mt('Tabulator separated'),
11912: #                 xml   => &mt('HTML/XML'),
11913:                  );
11914:     my $Str = '<input type="file" name="upfile" size="50" />'.
11915:         '<br />'.&mt('Type').': <select name="upfiletype">';
11916:     foreach my $type (sort(keys(%Types))) {
11917:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
11918:     }
11919:     $Str .= "</select>\n";
11920:     return $Str;
11921: }
11922: 
11923: sub get_samples {
11924:     my ($records,$toget) = @_;
11925:     my @samples=({});
11926:     my $got=0;
11927:     foreach my $rec (@$records) {
11928: 	my %temp = &record_sep($rec);
11929: 	if (! grep(/\S/, values(%temp))) { next; }
11930: 	if (%temp) {
11931: 	    $samples[$got]=\%temp;
11932: 	    $got++;
11933: 	    if ($got == $toget) { last; }
11934: 	}
11935:     }
11936:     return \@samples;
11937: }
11938: 
11939: ######################################################
11940: ######################################################
11941: 
11942: =pod
11943: 
11944: =item * &csv_print_samples($r,$records)
11945: 
11946: Prints a table of sample values from each column uploaded $r is an
11947: Apache Request ref, $records is an arrayref from
11948: &Apache::loncommon::upfile_record_sep
11949: 
11950: =cut
11951: 
11952: ######################################################
11953: ######################################################
11954: sub csv_print_samples {
11955:     my ($r,$records) = @_;
11956:     my $samples = &get_samples($records,5);
11957: 
11958:     $r->print(&mt('Samples').'<br />'.&start_data_table().
11959:               &start_data_table_header_row());
11960:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
11961:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
11962:     $r->print(&end_data_table_header_row());
11963:     foreach my $hash (@$samples) {
11964: 	$r->print(&start_data_table_row());
11965: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
11966: 	    $r->print('<td>');
11967: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
11968: 	    $r->print('</td>');
11969: 	}
11970: 	$r->print(&end_data_table_row());
11971:     }
11972:     $r->print(&end_data_table().'<br />'."\n");
11973: }
11974: 
11975: ######################################################
11976: ######################################################
11977: 
11978: =pod
11979: 
11980: =item * &csv_print_select_table($r,$records,$d)
11981: 
11982: Prints a table to create associations between values and table columns.
11983: 
11984: $r is an Apache Request ref,
11985: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
11986: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
11987: 
11988: =cut
11989: 
11990: ######################################################
11991: ######################################################
11992: sub csv_print_select_table {
11993:     my ($r,$records,$d) = @_;
11994:     my $i=0;
11995:     my $samples = &get_samples($records,1);
11996:     $r->print(&mt('Associate columns with student attributes.')."\n".
11997: 	      &start_data_table().&start_data_table_header_row().
11998:               '<th>'.&mt('Attribute').'</th>'.
11999:               '<th>'.&mt('Column').'</th>'.
12000:               &end_data_table_header_row()."\n");
12001:     foreach my $array_ref (@$d) {
12002: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12003: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12004: 
12005: 	$r->print('<td><select name="f'.$i.'"'.
12006: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12007: 	$r->print('<option value="none"></option>');
12008: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12009: 	    $r->print('<option value="'.$sample.'"'.
12010:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12011:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12012: 	}
12013: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12014: 	$i++;
12015:     }
12016:     $r->print(&end_data_table());
12017:     $i--;
12018:     return $i;
12019: }
12020: 
12021: ######################################################
12022: ######################################################
12023: 
12024: =pod
12025: 
12026: =item * &csv_samples_select_table($r,$records,$d)
12027: 
12028: Prints a table of sample values from the upload and can make associate samples to internal names.
12029: 
12030: $r is an Apache Request ref,
12031: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12032: $d is an array of 2 element arrays (internal name, displayed name)
12033: 
12034: =cut
12035: 
12036: ######################################################
12037: ######################################################
12038: sub csv_samples_select_table {
12039:     my ($r,$records,$d) = @_;
12040:     my $i=0;
12041:     #
12042:     my $max_samples = 5;
12043:     my $samples = &get_samples($records,$max_samples);
12044:     $r->print(&start_data_table().
12045:               &start_data_table_header_row().'<th>'.
12046:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12047:               &end_data_table_header_row());
12048: 
12049:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12050: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12051: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12052: 	foreach my $option (@$d) {
12053: 	    my ($value,$display,$defaultcol)=@{ $option };
12054: 	    $r->print('<option value="'.$value.'"'.
12055:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12056:                       $display.'</option>');
12057: 	}
12058: 	$r->print('</select></td><td>');
12059: 	foreach my $line (0..($max_samples-1)) {
12060: 	    if (defined($samples->[$line]{$key})) { 
12061: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12062: 	    }
12063: 	}
12064: 	$r->print('</td>'.&end_data_table_row());
12065: 	$i++;
12066:     }
12067:     $r->print(&end_data_table());
12068:     $i--;
12069:     return($i);
12070: }
12071: 
12072: ######################################################
12073: ######################################################
12074: 
12075: =pod
12076: 
12077: =item * &clean_excel_name($name)
12078: 
12079: Returns a replacement for $name which does not contain any illegal characters.
12080: 
12081: =cut
12082: 
12083: ######################################################
12084: ######################################################
12085: sub clean_excel_name {
12086:     my ($name) = @_;
12087:     $name =~ s/[:\*\?\/\\]//g;
12088:     if (length($name) > 31) {
12089:         $name = substr($name,0,31);
12090:     }
12091:     return $name;
12092: }
12093: 
12094: =pod
12095: 
12096: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12097: 
12098: Returns either 1 or undef
12099: 
12100: 1 if the part is to be hidden, undef if it is to be shown
12101: 
12102: Arguments are:
12103: 
12104: $id the id of the part to be checked
12105: $symb, optional the symb of the resource to check
12106: $udom, optional the domain of the user to check for
12107: $uname, optional the username of the user to check for
12108: 
12109: =cut
12110: 
12111: sub check_if_partid_hidden {
12112:     my ($id,$symb,$udom,$uname) = @_;
12113:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12114: 					 $symb,$udom,$uname);
12115:     my $truth=1;
12116:     #if the string starts with !, then the list is the list to show not hide
12117:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12118:     my @hiddenlist=split(/,/,$hiddenparts);
12119:     foreach my $checkid (@hiddenlist) {
12120: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12121:     }
12122:     return !$truth;
12123: }
12124: 
12125: 
12126: ############################################################
12127: ############################################################
12128: 
12129: =pod
12130: 
12131: =back 
12132: 
12133: =head1 cgi-bin script and graphing routines
12134: 
12135: =over 4
12136: 
12137: =item * &get_cgi_id()
12138: 
12139: Inputs: none
12140: 
12141: Returns an id which can be used to pass environment variables
12142: to various cgi-bin scripts.  These environment variables will
12143: be removed from the users environment after a given time by
12144: the routine &Apache::lonnet::transfer_profile_to_env.
12145: 
12146: =cut
12147: 
12148: ############################################################
12149: ############################################################
12150: my $uniq=0;
12151: sub get_cgi_id {
12152:     $uniq=($uniq+1)%100000;
12153:     return (time.'_'.$$.'_'.$uniq);
12154: }
12155: 
12156: ############################################################
12157: ############################################################
12158: 
12159: =pod
12160: 
12161: =item * &DrawBarGraph()
12162: 
12163: Facilitates the plotting of data in a (stacked) bar graph.
12164: Puts plot definition data into the users environment in order for 
12165: graph.png to plot it.  Returns an <img> tag for the plot.
12166: The bars on the plot are labeled '1','2',...,'n'.
12167: 
12168: Inputs:
12169: 
12170: =over 4
12171: 
12172: =item $Title: string, the title of the plot
12173: 
12174: =item $xlabel: string, text describing the X-axis of the plot
12175: 
12176: =item $ylabel: string, text describing the Y-axis of the plot
12177: 
12178: =item $Max: scalar, the maximum Y value to use in the plot
12179: If $Max is < any data point, the graph will not be rendered.
12180: 
12181: =item $colors: array ref holding the colors to be used for the data sets when
12182: they are plotted.  If undefined, default values will be used.
12183: 
12184: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12185: 
12186: =item @Values: An array of array references.  Each array reference holds data
12187: to be plotted in a stacked bar chart.
12188: 
12189: =item If the final element of @Values is a hash reference the key/value
12190: pairs will be added to the graph definition.
12191: 
12192: =back
12193: 
12194: Returns:
12195: 
12196: An <img> tag which references graph.png and the appropriate identifying
12197: information for the plot.
12198: 
12199: =cut
12200: 
12201: ############################################################
12202: ############################################################
12203: sub DrawBarGraph {
12204:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12205:     #
12206:     if (! defined($colors)) {
12207:         $colors = ['#33ff00', 
12208:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12209:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12210:                   ]; 
12211:     }
12212:     my $extra_settings = {};
12213:     if (ref($Values[-1]) eq 'HASH') {
12214:         $extra_settings = pop(@Values);
12215:     }
12216:     #
12217:     my $identifier = &get_cgi_id();
12218:     my $id = 'cgi.'.$identifier;        
12219:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12220:         return '';
12221:     }
12222:     #
12223:     my @Labels;
12224:     if (defined($labels)) {
12225:         @Labels = @$labels;
12226:     } else {
12227:         for (my $i=0;$i<@{$Values[0]};$i++) {
12228:             push (@Labels,$i+1);
12229:         }
12230:     }
12231:     #
12232:     my $NumBars = scalar(@{$Values[0]});
12233:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12234:     my %ValuesHash;
12235:     my $NumSets=1;
12236:     foreach my $array (@Values) {
12237:         next if (! ref($array));
12238:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12239:             join(',',@$array);
12240:     }
12241:     #
12242:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12243:     if ($NumBars < 3) {
12244:         $width = 120+$NumBars*32;
12245:         $xskip = 1;
12246:         $bar_width = 30;
12247:     } elsif ($NumBars < 5) {
12248:         $width = 120+$NumBars*20;
12249:         $xskip = 1;
12250:         $bar_width = 20;
12251:     } elsif ($NumBars < 10) {
12252:         $width = 120+$NumBars*15;
12253:         $xskip = 1;
12254:         $bar_width = 15;
12255:     } elsif ($NumBars <= 25) {
12256:         $width = 120+$NumBars*11;
12257:         $xskip = 5;
12258:         $bar_width = 8;
12259:     } elsif ($NumBars <= 50) {
12260:         $width = 120+$NumBars*8;
12261:         $xskip = 5;
12262:         $bar_width = 4;
12263:     } else {
12264:         $width = 120+$NumBars*8;
12265:         $xskip = 5;
12266:         $bar_width = 4;
12267:     }
12268:     #
12269:     $Max = 1 if ($Max < 1);
12270:     if ( int($Max) < $Max ) {
12271:         $Max++;
12272:         $Max = int($Max);
12273:     }
12274:     $Title  = '' if (! defined($Title));
12275:     $xlabel = '' if (! defined($xlabel));
12276:     $ylabel = '' if (! defined($ylabel));
12277:     $ValuesHash{$id.'.title'}    = &escape($Title);
12278:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12279:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12280:     $ValuesHash{$id.'.y_max_value'} = $Max;
12281:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12282:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12283:     $ValuesHash{$id.'.PlotType'} = 'bar';
12284:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12285:     $ValuesHash{$id.'.height'}   = $height;
12286:     $ValuesHash{$id.'.width'}    = $width;
12287:     $ValuesHash{$id.'.xskip'}    = $xskip;
12288:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12289:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12290:     #
12291:     # Deal with other parameters
12292:     while (my ($key,$value) = each(%$extra_settings)) {
12293:         $ValuesHash{$id.'.'.$key} = $value;
12294:     }
12295:     #
12296:     &Apache::lonnet::appenv(\%ValuesHash);
12297:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12298: }
12299: 
12300: ############################################################
12301: ############################################################
12302: 
12303: =pod
12304: 
12305: =item * &DrawXYGraph()
12306: 
12307: Facilitates the plotting of data in an XY graph.
12308: Puts plot definition data into the users environment in order for 
12309: graph.png to plot it.  Returns an <img> tag for the plot.
12310: 
12311: Inputs:
12312: 
12313: =over 4
12314: 
12315: =item $Title: string, the title of the plot
12316: 
12317: =item $xlabel: string, text describing the X-axis of the plot
12318: 
12319: =item $ylabel: string, text describing the Y-axis of the plot
12320: 
12321: =item $Max: scalar, the maximum Y value to use in the plot
12322: If $Max is < any data point, the graph will not be rendered.
12323: 
12324: =item $colors: Array ref containing the hex color codes for the data to be 
12325: plotted in.  If undefined, default values will be used.
12326: 
12327: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12328: 
12329: =item $Ydata: Array ref containing Array refs.  
12330: Each of the contained arrays will be plotted as a separate curve.
12331: 
12332: =item %Values: hash indicating or overriding any default values which are 
12333: passed to graph.png.  
12334: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12335: 
12336: =back
12337: 
12338: Returns:
12339: 
12340: An <img> tag which references graph.png and the appropriate identifying
12341: information for the plot.
12342: 
12343: =cut
12344: 
12345: ############################################################
12346: ############################################################
12347: sub DrawXYGraph {
12348:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12349:     #
12350:     # Create the identifier for the graph
12351:     my $identifier = &get_cgi_id();
12352:     my $id = 'cgi.'.$identifier;
12353:     #
12354:     $Title  = '' if (! defined($Title));
12355:     $xlabel = '' if (! defined($xlabel));
12356:     $ylabel = '' if (! defined($ylabel));
12357:     my %ValuesHash = 
12358:         (
12359:          $id.'.title'  => &escape($Title),
12360:          $id.'.xlabel' => &escape($xlabel),
12361:          $id.'.ylabel' => &escape($ylabel),
12362:          $id.'.y_max_value'=> $Max,
12363:          $id.'.labels'     => join(',',@$Xlabels),
12364:          $id.'.PlotType'   => 'XY',
12365:          );
12366:     #
12367:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12368:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12369:     }
12370:     #
12371:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12372:         return '';
12373:     }
12374:     my $NumSets=1;
12375:     foreach my $array (@{$Ydata}){
12376:         next if (! ref($array));
12377:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12378:     }
12379:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12380:     #
12381:     # Deal with other parameters
12382:     while (my ($key,$value) = each(%Values)) {
12383:         $ValuesHash{$id.'.'.$key} = $value;
12384:     }
12385:     #
12386:     &Apache::lonnet::appenv(\%ValuesHash);
12387:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12388: }
12389: 
12390: ############################################################
12391: ############################################################
12392: 
12393: =pod
12394: 
12395: =item * &DrawXYYGraph()
12396: 
12397: Facilitates the plotting of data in an XY graph with two Y axes.
12398: Puts plot definition data into the users environment in order for 
12399: graph.png to plot it.  Returns an <img> tag for the plot.
12400: 
12401: Inputs:
12402: 
12403: =over 4
12404: 
12405: =item $Title: string, the title of the plot
12406: 
12407: =item $xlabel: string, text describing the X-axis of the plot
12408: 
12409: =item $ylabel: string, text describing the Y-axis of the plot
12410: 
12411: =item $colors: Array ref containing the hex color codes for the data to be 
12412: plotted in.  If undefined, default values will be used.
12413: 
12414: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12415: 
12416: =item $Ydata1: The first data set
12417: 
12418: =item $Min1: The minimum value of the left Y-axis
12419: 
12420: =item $Max1: The maximum value of the left Y-axis
12421: 
12422: =item $Ydata2: The second data set
12423: 
12424: =item $Min2: The minimum value of the right Y-axis
12425: 
12426: =item $Max2: The maximum value of the left Y-axis
12427: 
12428: =item %Values: hash indicating or overriding any default values which are 
12429: passed to graph.png.  
12430: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12431: 
12432: =back
12433: 
12434: Returns:
12435: 
12436: An <img> tag which references graph.png and the appropriate identifying
12437: information for the plot.
12438: 
12439: =cut
12440: 
12441: ############################################################
12442: ############################################################
12443: sub DrawXYYGraph {
12444:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12445:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
12446:     #
12447:     # Create the identifier for the graph
12448:     my $identifier = &get_cgi_id();
12449:     my $id = 'cgi.'.$identifier;
12450:     #
12451:     $Title  = '' if (! defined($Title));
12452:     $xlabel = '' if (! defined($xlabel));
12453:     $ylabel = '' if (! defined($ylabel));
12454:     my %ValuesHash = 
12455:         (
12456:          $id.'.title'  => &escape($Title),
12457:          $id.'.xlabel' => &escape($xlabel),
12458:          $id.'.ylabel' => &escape($ylabel),
12459:          $id.'.labels' => join(',',@$Xlabels),
12460:          $id.'.PlotType' => 'XY',
12461:          $id.'.NumSets' => 2,
12462:          $id.'.two_axes' => 1,
12463:          $id.'.y1_max_value' => $Max1,
12464:          $id.'.y1_min_value' => $Min1,
12465:          $id.'.y2_max_value' => $Max2,
12466:          $id.'.y2_min_value' => $Min2,
12467:          );
12468:     #
12469:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12470:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12471:     }
12472:     #
12473:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
12474:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
12475:         return '';
12476:     }
12477:     my $NumSets=1;
12478:     foreach my $array ($Ydata1,$Ydata2){
12479:         next if (! ref($array));
12480:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12481:     }
12482:     #
12483:     # Deal with other parameters
12484:     while (my ($key,$value) = each(%Values)) {
12485:         $ValuesHash{$id.'.'.$key} = $value;
12486:     }
12487:     #
12488:     &Apache::lonnet::appenv(\%ValuesHash);
12489:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12490: }
12491: 
12492: ############################################################
12493: ############################################################
12494: 
12495: =pod
12496: 
12497: =back 
12498: 
12499: =head1 Statistics helper routines?  
12500: 
12501: Bad place for them but what the hell.
12502: 
12503: =over 4
12504: 
12505: =item * &chartlink()
12506: 
12507: Returns a link to the chart for a specific student.  
12508: 
12509: Inputs:
12510: 
12511: =over 4
12512: 
12513: =item $linktext: The text of the link
12514: 
12515: =item $sname: The students username
12516: 
12517: =item $sdomain: The students domain
12518: 
12519: =back
12520: 
12521: =back
12522: 
12523: =cut
12524: 
12525: ############################################################
12526: ############################################################
12527: sub chartlink {
12528:     my ($linktext, $sname, $sdomain) = @_;
12529:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
12530:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
12531:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
12532:        '">'.$linktext.'</a>';
12533: }
12534: 
12535: #######################################################
12536: #######################################################
12537: 
12538: =pod
12539: 
12540: =head1 Course Environment Routines
12541: 
12542: =over 4
12543: 
12544: =item * &restore_course_settings()
12545: 
12546: =item * &store_course_settings()
12547: 
12548: Restores/Store indicated form parameters from the course environment.
12549: Will not overwrite existing values of the form parameters.
12550: 
12551: Inputs: 
12552: a scalar describing the data (e.g. 'chart', 'problem_analysis')
12553: 
12554: a hash ref describing the data to be stored.  For example:
12555:    
12556: %Save_Parameters = ('Status' => 'scalar',
12557:     'chartoutputmode' => 'scalar',
12558:     'chartoutputdata' => 'scalar',
12559:     'Section' => 'array',
12560:     'Group' => 'array',
12561:     'StudentData' => 'array',
12562:     'Maps' => 'array');
12563: 
12564: Returns: both routines return nothing
12565: 
12566: =back
12567: 
12568: =cut
12569: 
12570: #######################################################
12571: #######################################################
12572: sub store_course_settings {
12573:     return &store_settings($env{'request.course.id'},@_);
12574: }
12575: 
12576: sub store_settings {
12577:     # save to the environment
12578:     # appenv the same items, just to be safe
12579:     my $udom  = $env{'user.domain'};
12580:     my $uname = $env{'user.name'};
12581:     my ($context,$prefix,$Settings) = @_;
12582:     my %SaveHash;
12583:     my %AppHash;
12584:     while (my ($setting,$type) = each(%$Settings)) {
12585:         my $basename = join('.','internal',$context,$prefix,$setting);
12586:         my $envname = 'environment.'.$basename;
12587:         if (exists($env{'form.'.$setting})) {
12588:             # Save this value away
12589:             if ($type eq 'scalar' &&
12590:                 (! exists($env{$envname}) || 
12591:                  $env{$envname} ne $env{'form.'.$setting})) {
12592:                 $SaveHash{$basename} = $env{'form.'.$setting};
12593:                 $AppHash{$envname}   = $env{'form.'.$setting};
12594:             } elsif ($type eq 'array') {
12595:                 my $stored_form;
12596:                 if (ref($env{'form.'.$setting})) {
12597:                     $stored_form = join(',',
12598:                                         map {
12599:                                             &escape($_);
12600:                                         } sort(@{$env{'form.'.$setting}}));
12601:                 } else {
12602:                     $stored_form = 
12603:                         &escape($env{'form.'.$setting});
12604:                 }
12605:                 # Determine if the array contents are the same.
12606:                 if ($stored_form ne $env{$envname}) {
12607:                     $SaveHash{$basename} = $stored_form;
12608:                     $AppHash{$envname}   = $stored_form;
12609:                 }
12610:             }
12611:         }
12612:     }
12613:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
12614:                                           $udom,$uname);
12615:     if ($put_result !~ /^(ok|delayed)/) {
12616:         &Apache::lonnet::logthis('unable to save form parameters, '.
12617:                                  'got error:'.$put_result);
12618:     }
12619:     # Make sure these settings stick around in this session, too
12620:     &Apache::lonnet::appenv(\%AppHash);
12621:     return;
12622: }
12623: 
12624: sub restore_course_settings {
12625:     return &restore_settings($env{'request.course.id'},@_);
12626: }
12627: 
12628: sub restore_settings {
12629:     my ($context,$prefix,$Settings) = @_;
12630:     while (my ($setting,$type) = each(%$Settings)) {
12631:         next if (exists($env{'form.'.$setting}));
12632:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
12633:             '.'.$setting;
12634:         if (exists($env{$envname})) {
12635:             if ($type eq 'scalar') {
12636:                 $env{'form.'.$setting} = $env{$envname};
12637:             } elsif ($type eq 'array') {
12638:                 $env{'form.'.$setting} = [ 
12639:                                            map { 
12640:                                                &unescape($_); 
12641:                                            } split(',',$env{$envname})
12642:                                            ];
12643:             }
12644:         }
12645:     }
12646: }
12647: 
12648: #######################################################
12649: #######################################################
12650: 
12651: =pod
12652: 
12653: =head1 Domain E-mail Routines  
12654: 
12655: =over 4
12656: 
12657: =item * &build_recipient_list()
12658: 
12659: Build recipient lists for five types of e-mail:
12660: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
12661: (d) Help requests, (e) Course requests needing approval,  generated by
12662: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
12663: loncoursequeueadmin.pm respectively.
12664: 
12665: Inputs:
12666: defmail (scalar - email address of default recipient), 
12667: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
12668: defdom (domain for which to retrieve configuration settings),
12669: origmail (scalar - email address of recipient from loncapa.conf, 
12670: i.e., predates configuration by DC via domainprefs.pm 
12671: 
12672: Returns: comma separated list of addresses to which to send e-mail.
12673: 
12674: =back
12675: 
12676: =cut
12677: 
12678: ############################################################
12679: ############################################################
12680: sub build_recipient_list {
12681:     my ($defmail,$mailing,$defdom,$origmail) = @_;
12682:     my @recipients;
12683:     my $otheremails;
12684:     my %domconfig =
12685:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
12686:     if (ref($domconfig{'contacts'}) eq 'HASH') {
12687:         if (exists($domconfig{'contacts'}{$mailing})) {
12688:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
12689:                 my @contacts = ('adminemail','supportemail');
12690:                 foreach my $item (@contacts) {
12691:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
12692:                         my $addr = $domconfig{'contacts'}{$item}; 
12693:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
12694:                             push(@recipients,$addr);
12695:                         }
12696:                     }
12697:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
12698:                 }
12699:             }
12700:         } elsif ($origmail ne '') {
12701:             push(@recipients,$origmail);
12702:         }
12703:     } elsif ($origmail ne '') {
12704:         push(@recipients,$origmail);
12705:     }
12706:     if (defined($defmail)) {
12707:         if ($defmail ne '') {
12708:             push(@recipients,$defmail);
12709:         }
12710:     }
12711:     if ($otheremails) {
12712:         my @others;
12713:         if ($otheremails =~ /,/) {
12714:             @others = split(/,/,$otheremails);
12715:         } else {
12716:             push(@others,$otheremails);
12717:         }
12718:         foreach my $addr (@others) {
12719:             if (!grep(/^\Q$addr\E$/,@recipients)) {
12720:                 push(@recipients,$addr);
12721:             }
12722:         }
12723:     }
12724:     my $recipientlist = join(',',@recipients); 
12725:     return $recipientlist;
12726: }
12727: 
12728: ############################################################
12729: ############################################################
12730: 
12731: =pod
12732: 
12733: =head1 Course Catalog Routines
12734: 
12735: =over 4
12736: 
12737: =item * &gather_categories()
12738: 
12739: Converts category definitions - keys of categories hash stored in  
12740: coursecategories in configuration.db on the primary library server in a 
12741: domain - to an array.  Also generates javascript and idx hash used to 
12742: generate Domain Coordinator interface for editing Course Categories.
12743: 
12744: Inputs:
12745: 
12746: categories (reference to hash of category definitions).
12747: 
12748: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12749:       categories and subcategories).
12750: 
12751: idx (reference to hash of counters used in Domain Coordinator interface for 
12752:       editing Course Categories).
12753: 
12754: jsarray (reference to array of categories used to create Javascript arrays for
12755:          Domain Coordinator interface for editing Course Categories).
12756: 
12757: Returns: nothing
12758: 
12759: Side effects: populates cats, idx and jsarray. 
12760: 
12761: =cut
12762: 
12763: sub gather_categories {
12764:     my ($categories,$cats,$idx,$jsarray) = @_;
12765:     my %counters;
12766:     my $num = 0;
12767:     foreach my $item (keys(%{$categories})) {
12768:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
12769:         if ($container eq '' && $depth == 0) {
12770:             $cats->[$depth][$categories->{$item}] = $cat;
12771:         } else {
12772:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
12773:         }
12774:         my ($escitem,$tail) = split(/:/,$item,2);
12775:         if ($counters{$tail} eq '') {
12776:             $counters{$tail} = $num;
12777:             $num ++;
12778:         }
12779:         if (ref($idx) eq 'HASH') {
12780:             $idx->{$item} = $counters{$tail};
12781:         }
12782:         if (ref($jsarray) eq 'ARRAY') {
12783:             push(@{$jsarray->[$counters{$tail}]},$item);
12784:         }
12785:     }
12786:     return;
12787: }
12788: 
12789: =pod
12790: 
12791: =item * &extract_categories()
12792: 
12793: Used to generate breadcrumb trails for course categories.
12794: 
12795: Inputs:
12796: 
12797: categories (reference to hash of category definitions).
12798: 
12799: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12800:       categories and subcategories).
12801: 
12802: trails (reference to array of breacrumb trails for each category).
12803: 
12804: allitems (reference to hash - key is category key 
12805:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12806: 
12807: idx (reference to hash of counters used in Domain Coordinator interface for
12808:       editing Course Categories).
12809: 
12810: jsarray (reference to array of categories used to create Javascript arrays for
12811:          Domain Coordinator interface for editing Course Categories).
12812: 
12813: subcats (reference to hash of arrays containing all subcategories within each 
12814:          category, -recursive)
12815: 
12816: Returns: nothing
12817: 
12818: Side effects: populates trails and allitems hash references.
12819: 
12820: =cut
12821: 
12822: sub extract_categories {
12823:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
12824:     if (ref($categories) eq 'HASH') {
12825:         &gather_categories($categories,$cats,$idx,$jsarray);
12826:         if (ref($cats->[0]) eq 'ARRAY') {
12827:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
12828:                 my $name = $cats->[0][$i];
12829:                 my $item = &escape($name).'::0';
12830:                 my $trailstr;
12831:                 if ($name eq 'instcode') {
12832:                     $trailstr = &mt('Official courses (with institutional codes)');
12833:                 } elsif ($name eq 'communities') {
12834:                     $trailstr = &mt('Communities');
12835:                 } else {
12836:                     $trailstr = $name;
12837:                 }
12838:                 if ($allitems->{$item} eq '') {
12839:                     push(@{$trails},$trailstr);
12840:                     $allitems->{$item} = scalar(@{$trails})-1;
12841:                 }
12842:                 my @parents = ($name);
12843:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
12844:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
12845:                         my $category = $cats->[1]{$name}[$j];
12846:                         if (ref($subcats) eq 'HASH') {
12847:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
12848:                         }
12849:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
12850:                     }
12851:                 } else {
12852:                     if (ref($subcats) eq 'HASH') {
12853:                         $subcats->{$item} = [];
12854:                     }
12855:                 }
12856:             }
12857:         }
12858:     }
12859:     return;
12860: }
12861: 
12862: =pod
12863: 
12864: =item *&recurse_categories()
12865: 
12866: Recursively used to generate breadcrumb trails for course categories.
12867: 
12868: Inputs:
12869: 
12870: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12871:       categories and subcategories).
12872: 
12873: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
12874: 
12875: category (current course category, for which breadcrumb trail is being generated).
12876: 
12877: trails (reference to array of breadcrumb trails for each category).
12878: 
12879: allitems (reference to hash - key is category key
12880:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12881: 
12882: parents (array containing containers directories for current category, 
12883:          back to top level). 
12884: 
12885: Returns: nothing
12886: 
12887: Side effects: populates trails and allitems hash references
12888: 
12889: =cut
12890: 
12891: sub recurse_categories {
12892:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
12893:     my $shallower = $depth - 1;
12894:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
12895:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
12896:             my $name = $cats->[$depth]{$category}[$k];
12897:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12898:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
12899:             if ($allitems->{$item} eq '') {
12900:                 push(@{$trails},$trailstr);
12901:                 $allitems->{$item} = scalar(@{$trails})-1;
12902:             }
12903:             my $deeper = $depth+1;
12904:             push(@{$parents},$category);
12905:             if (ref($subcats) eq 'HASH') {
12906:                 my $subcat = &escape($name).':'.$category.':'.$depth;
12907:                 for (my $j=@{$parents}; $j>=0; $j--) {
12908:                     my $higher;
12909:                     if ($j > 0) {
12910:                         $higher = &escape($parents->[$j]).':'.
12911:                                   &escape($parents->[$j-1]).':'.$j;
12912:                     } else {
12913:                         $higher = &escape($parents->[$j]).'::'.$j;
12914:                     }
12915:                     push(@{$subcats->{$higher}},$subcat);
12916:                 }
12917:             }
12918:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
12919:                                 $subcats);
12920:             pop(@{$parents});
12921:         }
12922:     } else {
12923:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12924:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
12925:         if ($allitems->{$item} eq '') {
12926:             push(@{$trails},$trailstr);
12927:             $allitems->{$item} = scalar(@{$trails})-1;
12928:         }
12929:     }
12930:     return;
12931: }
12932: 
12933: =pod
12934: 
12935: =item *&assign_categories_table()
12936: 
12937: Create a datatable for display of hierarchical categories in a domain,
12938: with checkboxes to allow a course to be categorized. 
12939: 
12940: Inputs:
12941: 
12942: cathash - reference to hash of categories defined for the domain (from
12943:           configuration.db)
12944: 
12945: currcat - scalar with an & separated list of categories assigned to a course. 
12946: 
12947: type    - scalar contains course type (Course or Community).
12948: 
12949: Returns: $output (markup to be displayed) 
12950: 
12951: =cut
12952: 
12953: sub assign_categories_table {
12954:     my ($cathash,$currcat,$type) = @_;
12955:     my $output;
12956:     if (ref($cathash) eq 'HASH') {
12957:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
12958:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
12959:         $maxdepth = scalar(@cats);
12960:         if (@cats > 0) {
12961:             my $itemcount = 0;
12962:             if (ref($cats[0]) eq 'ARRAY') {
12963:                 my @currcategories;
12964:                 if ($currcat ne '') {
12965:                     @currcategories = split('&',$currcat);
12966:                 }
12967:                 my $table;
12968:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
12969:                     my $parent = $cats[0][$i];
12970:                     next if ($parent eq 'instcode');
12971:                     if ($type eq 'Community') {
12972:                         next unless ($parent eq 'communities');
12973:                     } else {
12974:                         next if ($parent eq 'communities');
12975:                     }
12976:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
12977:                     my $item = &escape($parent).'::0';
12978:                     my $checked = '';
12979:                     if (@currcategories > 0) {
12980:                         if (grep(/^\Q$item\E$/,@currcategories)) {
12981:                             $checked = ' checked="checked"';
12982:                         }
12983:                     }
12984:                     my $parent_title = $parent;
12985:                     if ($parent eq 'communities') {
12986:                         $parent_title = &mt('Communities');
12987:                     }
12988:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
12989:                               '<input type="checkbox" name="usecategory" value="'.
12990:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
12991:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
12992:                     my $depth = 1;
12993:                     push(@path,$parent);
12994:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
12995:                     pop(@path);
12996:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
12997:                     $itemcount ++;
12998:                 }
12999:                 if ($itemcount) {
13000:                     $output = &Apache::loncommon::start_data_table().
13001:                               $table.
13002:                               &Apache::loncommon::end_data_table();
13003:                 }
13004:             }
13005:         }
13006:     }
13007:     return $output;
13008: }
13009: 
13010: =pod
13011: 
13012: =item *&assign_category_rows()
13013: 
13014: Create a datatable row for display of nested categories in a domain,
13015: with checkboxes to allow a course to be categorized,called recursively.
13016: 
13017: Inputs:
13018: 
13019: itemcount - track row number for alternating colors
13020: 
13021: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13022:       categories and subcategories.
13023: 
13024: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13025: 
13026: parent - parent of current category item
13027: 
13028: path - Array containing all categories back up through the hierarchy from the
13029:        current category to the top level.
13030: 
13031: currcategories - reference to array of current categories assigned to the course
13032: 
13033: Returns: $output (markup to be displayed).
13034: 
13035: =cut
13036: 
13037: sub assign_category_rows {
13038:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13039:     my ($text,$name,$item,$chgstr);
13040:     if (ref($cats) eq 'ARRAY') {
13041:         my $maxdepth = scalar(@{$cats});
13042:         if (ref($cats->[$depth]) eq 'HASH') {
13043:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13044:                 my $numchildren = @{$cats->[$depth]{$parent}};
13045:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13046:                 $text .= '<td><table class="LC_datatable">';
13047:                 for (my $j=0; $j<$numchildren; $j++) {
13048:                     $name = $cats->[$depth]{$parent}[$j];
13049:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13050:                     my $deeper = $depth+1;
13051:                     my $checked = '';
13052:                     if (ref($currcategories) eq 'ARRAY') {
13053:                         if (@{$currcategories} > 0) {
13054:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13055:                                 $checked = ' checked="checked"';
13056:                             }
13057:                         }
13058:                     }
13059:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13060:                              '<input type="checkbox" name="usecategory" value="'.
13061:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13062:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13063:                              '</td><td>';
13064:                     if (ref($path) eq 'ARRAY') {
13065:                         push(@{$path},$name);
13066:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13067:                         pop(@{$path});
13068:                     }
13069:                     $text .= '</td></tr>';
13070:                 }
13071:                 $text .= '</table></td>';
13072:             }
13073:         }
13074:     }
13075:     return $text;
13076: }
13077: 
13078: ############################################################
13079: ############################################################
13080: 
13081: 
13082: sub commit_customrole {
13083:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13084:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13085:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13086:                          ($end?', ending '.localtime($end):'').': <b>'.
13087:               &Apache::lonnet::assigncustomrole(
13088:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13089:                  '</b><br />';
13090:     return $output;
13091: }
13092: 
13093: sub commit_standardrole {
13094:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
13095:     my ($output,$logmsg,$linefeed);
13096:     if ($context eq 'auto') {
13097:         $linefeed = "\n";
13098:     } else {
13099:         $linefeed = "<br />\n";
13100:     }  
13101:     if ($three eq 'st') {
13102:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13103:                                          $one,$two,$sec,$context);
13104:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13105:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13106:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13107:         } else {
13108:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13109:                ($start?', '.&mt('starting').' '.localtime($start):'').
13110:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13111:             if ($context eq 'auto') {
13112:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13113:             } else {
13114:                $output .= '<b>'.$result.'</b>'.$linefeed.
13115:                &mt('Add to classlist').': <b>ok</b>';
13116:             }
13117:             $output .= $linefeed;
13118:         }
13119:     } else {
13120:         $output = &mt('Assigning').' '.$three.' in '.$url.
13121:                ($start?', '.&mt('starting').' '.localtime($start):'').
13122:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13123:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13124:         if ($context eq 'auto') {
13125:             $output .= $result.$linefeed;
13126:         } else {
13127:             $output .= '<b>'.$result.'</b>'.$linefeed;
13128:         }
13129:     }
13130:     return $output;
13131: }
13132: 
13133: sub commit_studentrole {
13134:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
13135:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13136:     if ($context eq 'auto') {
13137:         $linefeed = "\n";
13138:     } else {
13139:         $linefeed = '<br />'."\n";
13140:     }
13141:     if (defined($one) && defined($two)) {
13142:         my $cid=$one.'_'.$two;
13143:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13144:         my $secchange = 0;
13145:         my $expire_role_result;
13146:         my $modify_section_result;
13147:         if ($oldsec ne '-1') { 
13148:             if ($oldsec ne $sec) {
13149:                 $secchange = 1;
13150:                 my $now = time;
13151:                 my $uurl='/'.$cid;
13152:                 $uurl=~s/\_/\//g;
13153:                 if ($oldsec) {
13154:                     $uurl.='/'.$oldsec;
13155:                 }
13156:                 $oldsecurl = $uurl;
13157:                 $expire_role_result = 
13158:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13159:                 if ($env{'request.course.sec'} ne '') { 
13160:                     if ($expire_role_result eq 'refused') {
13161:                         my @roles = ('st');
13162:                         my @statuses = ('previous');
13163:                         my @roledoms = ($one);
13164:                         my $withsec = 1;
13165:                         my %roleshash = 
13166:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13167:                                               \@statuses,\@roles,\@roledoms,$withsec);
13168:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13169:                             my ($oldstart,$oldend) = 
13170:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13171:                             if ($oldend > 0 && $oldend <= $now) {
13172:                                 $expire_role_result = 'ok';
13173:                             }
13174:                         }
13175:                     }
13176:                 }
13177:                 $result = $expire_role_result;
13178:             }
13179:         }
13180:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13181:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
13182:             if ($modify_section_result =~ /^ok/) {
13183:                 if ($secchange == 1) {
13184:                     if ($sec eq '') {
13185:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13186:                     } else {
13187:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13188:                     }
13189:                 } elsif ($oldsec eq '-1') {
13190:                     if ($sec eq '') {
13191:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13192:                     } else {
13193:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13194:                     }
13195:                 } else {
13196:                     if ($sec eq '') {
13197:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13198:                     } else {
13199:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13200:                     }
13201:                 }
13202:             } else {
13203:                 if ($secchange) {       
13204:                     $$logmsg .= &mt('Error when attempting section change for [_1] from old section "[_2]" to new section: "[_3]" in course [_4] -error:',$uname,$oldsec,$sec,$cid).' '.$modify_section_result.$linefeed;
13205:                 } else {
13206:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13207:                 }
13208:             }
13209:             $result = $modify_section_result;
13210:         } elsif ($secchange == 1) {
13211:             if ($oldsec eq '') {
13212:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13213:             } else {
13214:                 $$logmsg .= &mt('Error when attempting to expire existing role for [_1] in section [_2] in course [_3] -error: ',$uname,$oldsec,$cid).' '.$expire_role_result.$linefeed;
13215:             }
13216:             if ($expire_role_result eq 'refused') {
13217:                 my $newsecurl = '/'.$cid;
13218:                 $newsecurl =~ s/\_/\//g;
13219:                 if ($sec ne '') {
13220:                     $newsecurl.='/'.$sec;
13221:                 }
13222:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13223:                     if ($sec eq '') {
13224:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments unaffiliated with any section.',$sec).$linefeed;
13225:                     } else {
13226:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',$sec).$linefeed;
13227:                     }
13228:                 }
13229:             }
13230:         }
13231:     } else {
13232:         $$logmsg .= &mt('Incomplete course id defined.').$linefeed.&mt('Addition of user [_1] from domain [_2] to course [_3], section [_4] not completed.',$uname,$udom,$one.'_'.$two,$sec).$linefeed;
13233:         $result = "error: incomplete course id\n";
13234:     }
13235:     return $result;
13236: }
13237: 
13238: ############################################################
13239: ############################################################
13240: 
13241: sub check_clone {
13242:     my ($args,$linefeed) = @_;
13243:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13244:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13245:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13246:     my $clonemsg;
13247:     my $can_clone = 0;
13248:     my $lctype = lc($args->{'crstype'});
13249:     if ($lctype ne 'community') {
13250:         $lctype = 'course';
13251:     }
13252:     if ($clonehome eq 'no_host') {
13253:         if ($args->{'crstype'} eq 'Community') {
13254:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
13255:         } else {
13256:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
13257:         }     
13258:     } else {
13259: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13260:         if ($args->{'crstype'} eq 'Community') {
13261:             if ($clonedesc{'type'} ne 'Community') {
13262:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
13263:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13264:             }
13265:         }
13266: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13267:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13268: 	    $can_clone = 1;
13269: 	} else {
13270: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13271: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13272: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13273:             if (grep(/^\*$/,@cloners)) {
13274:                 $can_clone = 1;
13275:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13276:                 $can_clone = 1;
13277:             } else {
13278:                 my $ccrole = 'cc';
13279:                 if ($args->{'crstype'} eq 'Community') {
13280:                     $ccrole = 'co';
13281:                 }
13282: 	        my %roleshash =
13283: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13284: 					 $args->{'ccdomain'},
13285:                                          'userroles',['active'],[$ccrole],
13286: 					 [$args->{'clonedomain'}]);
13287: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13288:                     $can_clone = 1;
13289:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13290:                     $can_clone = 1;
13291:                 } else {
13292:                     if ($args->{'crstype'} eq 'Community') {
13293:                         $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
13294:                     } else {
13295:                         $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
13296:                     }
13297: 	        }
13298: 	    }
13299:         }
13300:     }
13301:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13302: }
13303: 
13304: sub construct_course {
13305:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13306:     my $outcome;
13307:     my $linefeed =  '<br />'."\n";
13308:     if ($context eq 'auto') {
13309:         $linefeed = "\n";
13310:     }
13311: 
13312: #
13313: # Are we cloning?
13314: #
13315:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13316:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13317: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13318: 	if ($context ne 'auto') {
13319:             if ($clonemsg ne '') {
13320: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13321:             }
13322: 	}
13323: 	$outcome .= $clonemsg.$linefeed;
13324: 
13325:         if (!$can_clone) {
13326: 	    return (0,$outcome);
13327: 	}
13328:     }
13329: 
13330: #
13331: # Open course
13332: #
13333:     my $crstype = lc($args->{'crstype'});
13334:     my %cenv=();
13335:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13336:                                              $args->{'cdescr'},
13337:                                              $args->{'curl'},
13338:                                              $args->{'course_home'},
13339:                                              $args->{'nonstandard'},
13340:                                              $args->{'crscode'},
13341:                                              $args->{'ccuname'}.':'.
13342:                                              $args->{'ccdomain'},
13343:                                              $args->{'crstype'},
13344:                                              $cnum,$context,$category);
13345: 
13346:     # Note: The testing routines depend on this being output; see 
13347:     # Utils::Course. This needs to at least be output as a comment
13348:     # if anyone ever decides to not show this, and Utils::Course::new
13349:     # will need to be suitably modified.
13350:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13351:     if ($$courseid =~ /^error:/) {
13352:         return (0,$outcome);
13353:     }
13354: 
13355: #
13356: # Check if created correctly
13357: #
13358:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13359:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13360:     if ($crsuhome eq 'no_host') {
13361:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13362:         return (0,$outcome);
13363:     }
13364:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13365: 
13366: #
13367: # Do the cloning
13368: #   
13369:     if ($can_clone && $cloneid) {
13370: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13371: 	if ($context ne 'auto') {
13372: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13373: 	}
13374: 	$outcome .= $clonemsg.$linefeed;
13375: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13376: # Copy all files
13377: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13378: # Restore URL
13379: 	$cenv{'url'}=$oldcenv{'url'};
13380: # Restore title
13381: 	$cenv{'description'}=$oldcenv{'description'};
13382: # Restore creation date, creator and creation context.
13383:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13384:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13385:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13386: # Mark as cloned
13387: 	$cenv{'clonedfrom'}=$cloneid;
13388: # Need to clone grading mode
13389:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13390:         $cenv{'grading'}=$newenv{'grading'};
13391: # Do not clone these environment entries
13392:         &Apache::lonnet::del('environment',
13393:                   ['default_enrollment_start_date',
13394:                    'default_enrollment_end_date',
13395:                    'question.email',
13396:                    'policy.email',
13397:                    'comment.email',
13398:                    'pch.users.denied',
13399:                    'plc.users.denied',
13400:                    'hidefromcat',
13401:                    'categories'],
13402:                    $$crsudom,$$crsunum);
13403:     }
13404: 
13405: #
13406: # Set environment (will override cloned, if existing)
13407: #
13408:     my @sections = ();
13409:     my @xlists = ();
13410:     if ($args->{'crstype'}) {
13411:         $cenv{'type'}=$args->{'crstype'};
13412:     }
13413:     if ($args->{'crsid'}) {
13414:         $cenv{'courseid'}=$args->{'crsid'};
13415:     }
13416:     if ($args->{'crscode'}) {
13417:         $cenv{'internal.coursecode'}=$args->{'crscode'};
13418:     }
13419:     if ($args->{'crsquota'} ne '') {
13420:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
13421:     } else {
13422:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
13423:     }
13424:     if ($args->{'ccuname'}) {
13425:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
13426:                                         ':'.$args->{'ccdomain'};
13427:     } else {
13428:         $cenv{'internal.courseowner'} = $args->{'curruser'};
13429:     }
13430:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
13431:     if ($args->{'crssections'}) {
13432:         $cenv{'internal.sectionnums'} = '';
13433:         if ($args->{'crssections'} =~ m/,/) {
13434:             @sections = split/,/,$args->{'crssections'};
13435:         } else {
13436:             $sections[0] = $args->{'crssections'};
13437:         }
13438:         if (@sections > 0) {
13439:             foreach my $item (@sections) {
13440:                 my ($sec,$gp) = split/:/,$item;
13441:                 my $class = $args->{'crscode'}.$sec;
13442:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
13443:                 $cenv{'internal.sectionnums'} .= $item.',';
13444:                 unless ($addcheck eq 'ok') {
13445:                     push @badclasses, $class;
13446:                 }
13447:             }
13448:             $cenv{'internal.sectionnums'} =~ s/,$//;
13449:         }
13450:     }
13451: # do not hide course coordinator from staff listing, 
13452: # even if privileged
13453:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13454: # add crosslistings
13455:     if ($args->{'crsxlist'}) {
13456:         $cenv{'internal.crosslistings'}='';
13457:         if ($args->{'crsxlist'} =~ m/,/) {
13458:             @xlists = split/,/,$args->{'crsxlist'};
13459:         } else {
13460:             $xlists[0] = $args->{'crsxlist'};
13461:         }
13462:         if (@xlists > 0) {
13463:             foreach my $item (@xlists) {
13464:                 my ($xl,$gp) = split/:/,$item;
13465:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
13466:                 $cenv{'internal.crosslistings'} .= $item.',';
13467:                 unless ($addcheck eq 'ok') {
13468:                     push @badclasses, $xl;
13469:                 }
13470:             }
13471:             $cenv{'internal.crosslistings'} =~ s/,$//;
13472:         }
13473:     }
13474:     if ($args->{'autoadds'}) {
13475:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
13476:     }
13477:     if ($args->{'autodrops'}) {
13478:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
13479:     }
13480: # check for notification of enrollment changes
13481:     my @notified = ();
13482:     if ($args->{'notify_owner'}) {
13483:         if ($args->{'ccuname'} ne '') {
13484:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
13485:         }
13486:     }
13487:     if ($args->{'notify_dc'}) {
13488:         if ($uname ne '') { 
13489:             push(@notified,$uname.':'.$udom);
13490:         }
13491:     }
13492:     if (@notified > 0) {
13493:         my $notifylist;
13494:         if (@notified > 1) {
13495:             $notifylist = join(',',@notified);
13496:         } else {
13497:             $notifylist = $notified[0];
13498:         }
13499:         $cenv{'internal.notifylist'} = $notifylist;
13500:     }
13501:     if (@badclasses > 0) {
13502:         my %lt=&Apache::lonlocal::texthash(
13503:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
13504:                 'dnhr' => 'does not have rights to access enrollment in these classes',
13505:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
13506:         );
13507:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
13508:                            ' ('.$lt{'adby'}.')';
13509:         if ($context eq 'auto') {
13510:             $outcome .= $badclass_msg.$linefeed;
13511:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
13512:             foreach my $item (@badclasses) {
13513:                 if ($context eq 'auto') {
13514:                     $outcome .= " - $item\n";
13515:                 } else {
13516:                     $outcome .= "<li>$item</li>\n";
13517:                 }
13518:             }
13519:             if ($context eq 'auto') {
13520:                 $outcome .= $linefeed;
13521:             } else {
13522:                 $outcome .= "</ul><br /><br /></div>\n";
13523:             }
13524:         } 
13525:     }
13526:     if ($args->{'no_end_date'}) {
13527:         $args->{'endaccess'} = 0;
13528:     }
13529:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
13530:     $cenv{'internal.autoend'}=$args->{'enrollend'};
13531:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
13532:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
13533:     if ($args->{'showphotos'}) {
13534:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
13535:     }
13536:     $cenv{'internal.authtype'} = $args->{'authtype'};
13537:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
13538:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
13539:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
13540:             my $krb_msg = &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student'); 
13541:             if ($context eq 'auto') {
13542:                 $outcome .= $krb_msg;
13543:             } else {
13544:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
13545:             }
13546:             $outcome .= $linefeed;
13547:         }
13548:     }
13549:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
13550:        if ($args->{'setpolicy'}) {
13551:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13552:        }
13553:        if ($args->{'setcontent'}) {
13554:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13555:        }
13556:     }
13557:     if ($args->{'reshome'}) {
13558: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
13559: 	$cenv{'reshome'}=~s/\/+$/\//;
13560:     }
13561: #
13562: # course has keyed access
13563: #
13564:     if ($args->{'setkeys'}) {
13565:        $cenv{'keyaccess'}='yes';
13566:     }
13567: # if specified, key authority is not course, but user
13568: # only active if keyaccess is yes
13569:     if ($args->{'keyauth'}) {
13570: 	my ($user,$domain) = split(':',$args->{'keyauth'});
13571: 	$user = &LONCAPA::clean_username($user);
13572: 	$domain = &LONCAPA::clean_username($domain);
13573: 	if ($user ne '' && $domain ne '') {
13574: 	    $cenv{'keyauth'}=$user.':'.$domain;
13575: 	}
13576:     }
13577: 
13578:     if ($args->{'disresdis'}) {
13579:         $cenv{'pch.roles.denied'}='st';
13580:     }
13581:     if ($args->{'disablechat'}) {
13582:         $cenv{'plc.roles.denied'}='st';
13583:     }
13584: 
13585:     # Record we've not yet viewed the Course Initialization Helper for this 
13586:     # course
13587:     $cenv{'course.helper.not.run'} = 1;
13588:     #
13589:     # Use new Randomseed
13590:     #
13591:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
13592:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
13593:     #
13594:     # The encryption code and receipt prefix for this course
13595:     #
13596:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
13597:     $cenv{'internal.encpref'}=100+int(9*rand(99));
13598:     #
13599:     # By default, use standard grading
13600:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
13601: 
13602:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
13603:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
13604: #
13605: # Open all assignments
13606: #
13607:     if ($args->{'openall'}) {
13608:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
13609:        my %storecontent = ($storeunder         => time,
13610:                            $storeunder.'.type' => 'date_start');
13611:        
13612:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
13613:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
13614:    }
13615: #
13616: # Set first page
13617: #
13618:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
13619: 	    || ($cloneid)) {
13620: 	use LONCAPA::map;
13621: 	$outcome .= &mt('Setting first resource').': ';
13622: 
13623: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
13624:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
13625: 
13626:         $outcome .= ($fatal?$errtext:'read ok').' - ';
13627:         my $title; my $url;
13628:         if ($args->{'firstres'} eq 'syl') {
13629: 	    $title=&mt('Syllabus');
13630:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
13631:         } else {
13632:             $title=&mt('Table of Contents');
13633:             $url='/adm/navmaps';
13634:         }
13635: 
13636:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
13637: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
13638: 
13639: 	if ($errtext) { $fatal=2; }
13640:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
13641:     }
13642: 
13643:     return (1,$outcome);
13644: }
13645: 
13646: ############################################################
13647: ############################################################
13648: 
13649: #SD
13650: # only Community and Course, or anything else?
13651: sub course_type {
13652:     my ($cid) = @_;
13653:     if (!defined($cid)) {
13654:         $cid = $env{'request.course.id'};
13655:     }
13656:     if (defined($env{'course.'.$cid.'.type'})) {
13657:         return $env{'course.'.$cid.'.type'};
13658:     } else {
13659:         return 'Course';
13660:     }
13661: }
13662: 
13663: sub group_term {
13664:     my $crstype = &course_type();
13665:     my %names = (
13666:                   'Course' => 'group',
13667:                   'Community' => 'group',
13668:                 );
13669:     return $names{$crstype};
13670: }
13671: 
13672: sub course_types {
13673:     my @types = ('official','unofficial','community');
13674:     my %typename = (
13675:                          official   => 'Official course',
13676:                          unofficial => 'Unofficial course',
13677:                          community  => 'Community',
13678:                    );
13679:     return (\@types,\%typename);
13680: }
13681: 
13682: sub icon {
13683:     my ($file)=@_;
13684:     my $curfext = lc((split(/\./,$file))[-1]);
13685:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
13686:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
13687:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
13688: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
13689: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13690: 	            $curfext.".gif") {
13691: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13692: 		$curfext.".gif";
13693: 	}
13694:     }
13695:     return &lonhttpdurl($iconname);
13696: } 
13697: 
13698: sub lonhttpdurl {
13699: #
13700: # Had been used for "small fry" static images on separate port 8080.
13701: # Modify here if lightweight http functionality desired again.
13702: # Currently eliminated due to increasing firewall issues.
13703: #
13704:     my ($url)=@_;
13705:     return $url;
13706: }
13707: 
13708: sub connection_aborted {
13709:     my ($r)=@_;
13710:     $r->print(" ");$r->rflush();
13711:     my $c = $r->connection;
13712:     return $c->aborted();
13713: }
13714: 
13715: #    Escapes strings that may have embedded 's that will be put into
13716: #    strings as 'strings'.
13717: sub escape_single {
13718:     my ($input) = @_;
13719:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
13720:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
13721:     return $input;
13722: }
13723: 
13724: #  Same as escape_single, but escape's "'s  This 
13725: #  can be used for  "strings"
13726: sub escape_double {
13727:     my ($input) = @_;
13728:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
13729:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
13730:     return $input;
13731: }
13732:  
13733: #   Escapes the last element of a full URL.
13734: sub escape_url {
13735:     my ($url)   = @_;
13736:     my @urlslices = split(/\//, $url,-1);
13737:     my $lastitem = &escape(pop(@urlslices));
13738:     return join('/',@urlslices).'/'.$lastitem;
13739: }
13740: 
13741: sub compare_arrays {
13742:     my ($arrayref1,$arrayref2) = @_;
13743:     my (@difference,%count);
13744:     @difference = ();
13745:     %count = ();
13746:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
13747:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
13748:         foreach my $element (keys(%count)) {
13749:             if ($count{$element} == 1) {
13750:                 push(@difference,$element);
13751:             }
13752:         }
13753:     }
13754:     return @difference;
13755: }
13756: 
13757: # -------------------------------------------------------- Initialize user login
13758: sub init_user_environment {
13759:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
13760:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
13761: 
13762:     my $public=($username eq 'public' && $domain eq 'public');
13763: 
13764: # See if old ID present, if so, remove
13765: 
13766:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
13767:     my $now=time;
13768: 
13769:     if ($public) {
13770: 	my $max_public=100;
13771: 	my $oldest;
13772: 	my $oldest_time=0;
13773: 	for(my $next=1;$next<=$max_public;$next++) {
13774: 	    if (-e $lonids."/publicuser_$next.id") {
13775: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
13776: 		if ($mtime<$oldest_time || !$oldest_time) {
13777: 		    $oldest_time=$mtime;
13778: 		    $oldest=$next;
13779: 		}
13780: 	    } else {
13781: 		$cookie="publicuser_$next";
13782: 		last;
13783: 	    }
13784: 	}
13785: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
13786:     } else {
13787: 	# if this isn't a robot, kill any existing non-robot sessions
13788: 	if (!$args->{'robot'}) {
13789: 	    opendir(DIR,$lonids);
13790: 	    while ($filename=readdir(DIR)) {
13791: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
13792: 		    unlink($lonids.'/'.$filename);
13793: 		}
13794: 	    }
13795: 	    closedir(DIR);
13796: 	}
13797: # Give them a new cookie
13798: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
13799: 		                   : $now.$$.int(rand(10000)));
13800: 	$cookie="$username\_$id\_$domain\_$authhost";
13801:     
13802: # Initialize roles
13803: 
13804: 	($userroles,$firstaccenv,$timerintenv) = 
13805:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
13806:     }
13807: # ------------------------------------ Check browser type and MathML capability
13808: 
13809:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
13810:         $clientunicode,$clientos) = &decode_user_agent($r);
13811: 
13812: # ------------------------------------------------------------- Get environment
13813: 
13814:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
13815:     my ($tmp) = keys(%userenv);
13816:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13817:     } else {
13818: 	undef(%userenv);
13819:     }
13820:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
13821: 	$form->{'interface'}=$userenv{'interface'};
13822:     }
13823:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
13824: 
13825: # --------------- Do not trust query string to be put directly into environment
13826:     foreach my $option ('interface','localpath','localres') {
13827:         $form->{$option}=~s/[\n\r\=]//gs;
13828:     }
13829: # --------------------------------------------------------- Write first profile
13830: 
13831:     {
13832: 	my %initial_env = 
13833: 	    ("user.name"          => $username,
13834: 	     "user.domain"        => $domain,
13835: 	     "user.home"          => $authhost,
13836: 	     "browser.type"       => $clientbrowser,
13837: 	     "browser.version"    => $clientversion,
13838: 	     "browser.mathml"     => $clientmathml,
13839: 	     "browser.unicode"    => $clientunicode,
13840: 	     "browser.os"         => $clientos,
13841: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
13842: 	     "request.course.fn"  => '',
13843: 	     "request.course.uri" => '',
13844: 	     "request.course.sec" => '',
13845: 	     "request.role"       => 'cm',
13846: 	     "request.role.adv"   => $env{'user.adv'},
13847: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
13848: 
13849:         if ($form->{'localpath'}) {
13850: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
13851: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
13852:         }
13853: 	
13854: 	if ($form->{'interface'}) {
13855: 	    $form->{'interface'}=~s/\W//gs;
13856: 	    $initial_env{"browser.interface"} = $form->{'interface'};
13857: 	    $env{'browser.interface'}=$form->{'interface'};
13858: 	}
13859: 
13860:         my %is_adv = ( is_adv => $env{'user.adv'} );
13861:         my %domdef;
13862:         unless ($domain eq 'public') {
13863:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
13864:         }
13865: 
13866:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
13867:             $userenv{'availabletools.'.$tool} = 
13868:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
13869:                                                   undef,\%userenv,\%domdef,\%is_adv);
13870:         }
13871: 
13872:         foreach my $crstype ('official','unofficial','community') {
13873:             $userenv{'canrequest.'.$crstype} =
13874:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
13875:                                                   'reload','requestcourses',
13876:                                                   \%userenv,\%domdef,\%is_adv);
13877:         }
13878: 
13879:         $userenv{'canrequest.author'} =
13880:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
13881:                                         'reload','requestauthor',
13882:                                         \%userenv,\%domdef,\%is_adv);
13883:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
13884:                                              $domain,$username);
13885:         my $reqstatus = $reqauthor{'author_status'};
13886:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
13887:             if (ref($reqauthor{'author'}) eq 'HASH') {
13888:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
13889:                                                   $reqauthor{'author'}{'timestamp'};
13890:             }
13891:         }
13892: 
13893: 	$env{'user.environment'} = "$lonids/$cookie.id";
13894: 
13895: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
13896: 		 &GDBM_WRCREAT(),0640)) {
13897: 	    &_add_to_env(\%disk_env,\%initial_env);
13898: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
13899: 	    &_add_to_env(\%disk_env,$userroles);
13900:             if (ref($firstaccenv) eq 'HASH') {
13901:                 &_add_to_env(\%disk_env,$firstaccenv);
13902:             }
13903:             if (ref($timerintenv) eq 'HASH') {
13904:                 &_add_to_env(\%disk_env,$timerintenv);
13905:             }
13906: 	    if (ref($args->{'extra_env'})) {
13907: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
13908: 	    }
13909: 	    untie(%disk_env);
13910: 	} else {
13911: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
13912: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
13913: 	    return 'error: '.$!;
13914: 	}
13915:     }
13916:     $env{'request.role'}='cm';
13917:     $env{'request.role.adv'}=$env{'user.adv'};
13918:     $env{'browser.type'}=$clientbrowser;
13919: 
13920:     return $cookie;
13921: 
13922: }
13923: 
13924: sub _add_to_env {
13925:     my ($idf,$env_data,$prefix) = @_;
13926:     if (ref($env_data) eq 'HASH') {
13927:         while (my ($key,$value) = each(%$env_data)) {
13928: 	    $idf->{$prefix.$key} = $value;
13929: 	    $env{$prefix.$key}   = $value;
13930:         }
13931:     }
13932: }
13933: 
13934: # --- Get the symbolic name of a problem and the url
13935: sub get_symb {
13936:     my ($request,$silent) = @_;
13937:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
13938:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
13939:     if ($symb eq '') {
13940:         if (!$silent) {
13941:             if (ref($request)) { 
13942:                 $request->print("Unable to handle ambiguous references:$url:.");
13943:             }
13944:             return ();
13945:         }
13946:     }
13947:     &Apache::lonenc::check_decrypt(\$symb);
13948:     return ($symb);
13949: }
13950: 
13951: # --------------------------------------------------------------Get annotation
13952: 
13953: sub get_annotation {
13954:     my ($symb,$enc) = @_;
13955: 
13956:     my $key = $symb;
13957:     if (!$enc) {
13958:         $key =
13959:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
13960:     }
13961:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
13962:     return $annotation{$key};
13963: }
13964: 
13965: sub clean_symb {
13966:     my ($symb,$delete_enc) = @_;
13967: 
13968:     &Apache::lonenc::check_decrypt(\$symb);
13969:     my $enc = $env{'request.enc'};
13970:     if ($delete_enc) {
13971:         delete($env{'request.enc'});
13972:     }
13973: 
13974:     return ($symb,$enc);
13975: }
13976: 
13977: sub build_release_hashes {
13978:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
13979:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
13980:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
13981:                   (ref($randomizetry) eq 'HASH'));
13982:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
13983:         my ($item,$name,$value) = split(/:/,$key);
13984:         if ($item eq 'parameter') {
13985:             if (ref($checkparms->{$name}) eq 'ARRAY') {
13986:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
13987:                     push(@{$checkparms->{$name}},$value);
13988:                 }
13989:             } else {
13990:                 push(@{$checkparms->{$name}},$value);
13991:             }
13992:         } elsif ($item eq 'resourcetag') {
13993:             if ($name eq 'responsetype') {
13994:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
13995:             }
13996:         } elsif ($item eq 'course') {
13997:             if ($name eq 'crstype') {
13998:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
13999:             }
14000:         }
14001:     }
14002:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14003:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14004:     return;
14005: }
14006: 
14007: sub update_content_constraints {
14008:     my ($cdom,$cnum,$chome,$cid) = @_;
14009:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14010:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14011:     my %checkresponsetypes;
14012:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14013:         my ($item,$name,$value) = split(/:/,$key);
14014:         if ($item eq 'resourcetag') {
14015:             if ($name eq 'responsetype') {
14016:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14017:             }
14018:         }
14019:     }
14020:     my $navmap = Apache::lonnavmaps::navmap->new();
14021:     if (defined($navmap)) {
14022:         my %allresponses;
14023:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14024:             my %responses = $res->responseTypes();
14025:             foreach my $key (keys(%responses)) {
14026:                 next unless(exists($checkresponsetypes{$key}));
14027:                 $allresponses{$key} += $responses{$key};
14028:             }
14029:         }
14030:         foreach my $key (keys(%allresponses)) {
14031:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14032:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14033:                 ($reqdmajor,$reqdminor) = ($major,$minor);
14034:             }
14035:         }
14036:         undef($navmap);
14037:     }
14038:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14039:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14040:     }
14041:     return;
14042: }
14043: 
14044: sub parse_supplemental_title {
14045:     my ($title) = @_;
14046: 
14047:     my ($foldertitle,$renametitle);
14048:     if ($title =~ /&amp;&amp;&amp;/) {
14049:         $title = &HTML::Entites::decode($title);
14050:     }
14051:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14052:         $renametitle=$4;
14053:         my ($time,$uname,$udom) = ($1,$2,$3);
14054:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14055:         my $name =  &plainname($uname,$udom);
14056:         $name = &HTML::Entities::encode($name,'"<>&\'');
14057:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14058:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14059:             $name.': <br />'.$foldertitle;
14060:     }
14061:     if (wantarray) {
14062:         return ($title,$foldertitle,$renametitle);
14063:     }
14064:     return $title;
14065: }
14066: 
14067: =pod
14068: 
14069: =back
14070: 
14071: =cut
14072: 
14073: 1;
14074: __END__;
14075: 

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