File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.158: download - view: text, annotated - select for diffs
Mon Dec 13 19:55:44 2021 UTC (2 years, 5 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  Backport 1.1281, 1.1310 (part) 1.1323, 1.1345, 1.1346 (part), 1.1351, 1.1355,
           1.1356, 1.1357, 1.1358, 1.1366, 1.1367, 1.1369, 1.1372 (part)

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.158 2021/12/13 19:55:44 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 Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use HTTP::Request;
   75: use DateTime::TimeZone;
   76: use DateTime::Locale;
   77: use Encode();
   78: use Authen::Captcha;
   79: use Captcha::reCAPTCHA;
   80: use JSON::DWIW;
   81: use LWP::UserAgent;
   82: use Crypt::DES;
   83: use DynaLoader; # for Crypt::DES version
   84: use File::Copy();
   85: use File::Path();
   86: 
   87: # ---------------------------------------------- Designs
   88: use vars qw(%defaultdesign);
   89: 
   90: my $readit;
   91: 
   92: 
   93: ##
   94: ## Global Variables
   95: ##
   96: 
   97: 
   98: # ----------------------------------------------- SSI with retries:
   99: #
  100: 
  101: =pod
  102: 
  103: =head1 Server Side include with retries:
  104: 
  105: =over 4
  106: 
  107: =item * &ssi_with_retries(resource,retries form)
  108: 
  109: Performs an ssi with some number of retries.  Retries continue either
  110: until the result is ok or until the retry count supplied by the
  111: caller is exhausted.  
  112: 
  113: Inputs:
  114: 
  115: =over 4
  116: 
  117: resource   - Identifies the resource to insert.
  118: 
  119: retries    - Count of the number of retries allowed.
  120: 
  121: form       - Hash that identifies the rendering options.
  122: 
  123: =back
  124: 
  125: Returns:
  126: 
  127: =over 4
  128: 
  129: content    - The content of the response.  If retries were exhausted this is empty.
  130: 
  131: response   - The response from the last attempt (which may or may not have been successful.
  132: 
  133: =back
  134: 
  135: =back
  136: 
  137: =cut
  138: 
  139: sub ssi_with_retries {
  140:     my ($resource, $retries, %form) = @_;
  141: 
  142: 
  143:     my $ok = 0;			# True if we got a good response.
  144:     my $content;
  145:     my $response;
  146: 
  147:     # Try to get the ssi done. within the retries count:
  148: 
  149:     do {
  150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  151: 	$ok      = $response->is_success;
  152:         if (!$ok) {
  153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  154:         }
  155: 	$retries--;
  156:     } while (!$ok && ($retries > 0));
  157: 
  158:     if (!$ok) {
  159: 	$content = '';		# On error return an empty content.
  160:     }
  161:     return ($content, $response);
  162: 
  163: }
  164: 
  165: 
  166: 
  167: # ----------------------------------------------- Filetypes/Languages/Copyright
  168: my %language;
  169: my %supported_language;
  170: my %latex_language;		# For choosing hyphenation in <transl..>
  171: my %latex_language_bykey;	# for choosing hyphenation from metadata
  172: my %cprtag;
  173: my %scprtag;
  174: my %fe; my %fd; my %fm;
  175: my %category_extensions;
  176: 
  177: # ---------------------------------------------- Thesaurus variables
  178: #
  179: # %Keywords:
  180: #      A hash used by &keyword to determine if a word is considered a keyword.
  181: # $thesaurus_db_file 
  182: #      Scalar containing the full path to the thesaurus database.
  183: 
  184: my %Keywords;
  185: my $thesaurus_db_file;
  186: 
  187: #
  188: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  189: # thesaurus.tab, and filecategories.tab.
  190: #
  191: BEGIN {
  192:     # Variable initialization
  193:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  194:     #
  195:     unless ($readit) {
  196: # ------------------------------------------------------------------- languages
  197:     {
  198:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  199:                                    '/language.tab';
  200:         if ( open(my $fh,'<',$langtabfile) ) {
  201:             while (my $line = <$fh>) {
  202:                 next if ($line=~/^\#/);
  203:                 chomp($line);
  204:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  205:                 $language{$key}=$val.' - '.$enc;
  206:                 if ($sup) {
  207:                     $supported_language{$key}=$sup;
  208:                 }
  209: 		if ($latex) {
  210: 		    $latex_language_bykey{$key} = $latex;
  211: 		    $latex_language{$two} = $latex;
  212: 		}
  213:             }
  214:             close($fh);
  215:         }
  216:     }
  217: # ------------------------------------------------------------------ copyrights
  218:     {
  219:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  220:                                   '/copyright.tab';
  221:         if ( open (my $fh,'<',$copyrightfile) ) {
  222:             while (my $line = <$fh>) {
  223:                 next if ($line=~/^\#/);
  224:                 chomp($line);
  225:                 my ($key,$val)=(split(/\s+/,$line,2));
  226:                 $cprtag{$key}=$val;
  227:             }
  228:             close($fh);
  229:         }
  230:     }
  231: # ----------------------------------------------------------- source copyrights
  232:     {
  233:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  234:                                   '/source_copyright.tab';
  235:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  236:             while (my $line = <$fh>) {
  237:                 next if ($line =~ /^\#/);
  238:                 chomp($line);
  239:                 my ($key,$val)=(split(/\s+/,$line,2));
  240:                 $scprtag{$key}=$val;
  241:             }
  242:             close($fh);
  243:         }
  244:     }
  245: 
  246: # -------------------------------------------------------------- default domain designs
  247:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  248:     my $designfile = $designdir.'/default.tab';
  249:     if ( open (my $fh,'<',$designfile) ) {
  250:         while (my $line = <$fh>) {
  251:             next if ($line =~ /^\#/);
  252:             chomp($line);
  253:             my ($key,$val)=(split(/\=/,$line));
  254:             if ($val) { $defaultdesign{$key}=$val; }
  255:         }
  256:         close($fh);
  257:     }
  258: 
  259: # ------------------------------------------------------------- file categories
  260:     {
  261:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  262:                                   '/filecategories.tab';
  263:         if ( open (my $fh,'<',$categoryfile) ) {
  264: 	    while (my $line = <$fh>) {
  265: 		next if ($line =~ /^\#/);
  266: 		chomp($line);
  267:                 my ($extension,$category)=(split(/\s+/,$line,2));
  268:                 push(@{$category_extensions{lc($category)}},$extension);
  269:             }
  270:             close($fh);
  271:         }
  272: 
  273:     }
  274: # ------------------------------------------------------------------ file types
  275:     {
  276:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  277:                '/filetypes.tab';
  278:         if ( open (my $fh,'<',$typesfile) ) {
  279:             while (my $line = <$fh>) {
  280: 		next if ($line =~ /^\#/);
  281: 		chomp($line);
  282:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  283:                 if ($descr ne '') {
  284:                     $fe{$ending}=lc($emb);
  285:                     $fd{$ending}=$descr;
  286:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  287:                 }
  288:             }
  289:             close($fh);
  290:         }
  291:     }
  292:     &Apache::lonnet::logthis(
  293:              "<span style='color:yellow;'>INFO: Read file types</span>");
  294:     $readit=1;
  295:     }  # end of unless($readit) 
  296:     
  297: }
  298: 
  299: ###############################################################
  300: ##           HTML and Javascript Helper Functions            ##
  301: ###############################################################
  302: 
  303: =pod 
  304: 
  305: =head1 HTML and Javascript Functions
  306: 
  307: =over 4
  308: 
  309: =item * &browser_and_searcher_javascript()
  310: 
  311: X<browsing, javascript>X<searching, javascript>Returns a string
  312: containing javascript with two functions, C<openbrowser> and
  313: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  314: tags.
  315: 
  316: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  317: 
  318: inputs: formname, elementname, only, omit
  319: 
  320: formname and elementname indicate the name of the html form and name of
  321: the element that the results of the browsing selection are to be placed in. 
  322: 
  323: Specifying 'only' will restrict the browser to displaying only files
  324: with the given extension.  Can be a comma separated list.
  325: 
  326: Specifying 'omit' will restrict the browser to NOT displaying files
  327: with the given extension.  Can be a comma separated list.
  328: 
  329: =item * &opensearcher(formname,elementname) [javascript]
  330: 
  331: Inputs: formname, elementname
  332: 
  333: formname and elementname specify the name of the html form and the name
  334: of the element the selection from the search results will be placed in.
  335: 
  336: =cut
  337: 
  338: sub browser_and_searcher_javascript {
  339:     my ($mode)=@_;
  340:     if (!defined($mode)) { $mode='edit'; }
  341:     my $resurl=&escape_single(&lastresurl());
  342:     return <<END;
  343: // <!-- BEGIN LON-CAPA Internal
  344:     var editbrowser = null;
  345:     function openbrowser(formname,elementname,only,omit,titleelement) {
  346:         var url = '$resurl/?';
  347:         if (editbrowser == null) {
  348:             url += 'launch=1&';
  349:         }
  350:         url += 'catalogmode=interactive&';
  351:         url += 'mode=$mode&';
  352:         url += 'inhibitmenu=yes&';
  353:         url += 'form=' + formname + '&';
  354:         if (only != null) {
  355:             url += 'only=' + only + '&';
  356:         } else {
  357:             url += 'only=&';
  358: 	}
  359:         if (omit != null) {
  360:             url += 'omit=' + omit + '&';
  361:         } else {
  362:             url += 'omit=&';
  363: 	}
  364:         if (titleelement != null) {
  365:             url += 'titleelement=' + titleelement + '&';
  366:         } else {
  367: 	    url += 'titleelement=&';
  368: 	}
  369:         url += 'element=' + elementname + '';
  370:         var title = 'Browser';
  371:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  372:         options += ',width=700,height=600';
  373:         editbrowser = open(url,title,options,'1');
  374:         editbrowser.focus();
  375:     }
  376:     var editsearcher;
  377:     function opensearcher(formname,elementname,titleelement) {
  378:         var url = '/adm/searchcat?';
  379:         if (editsearcher == null) {
  380:             url += 'launch=1&';
  381:         }
  382:         url += 'catalogmode=interactive&';
  383:         url += 'mode=$mode&';
  384:         url += 'form=' + formname + '&';
  385:         if (titleelement != null) {
  386:             url += 'titleelement=' + titleelement + '&';
  387:         } else {
  388: 	    url += 'titleelement=&';
  389: 	}
  390:         url += 'element=' + elementname + '';
  391:         var title = 'Search';
  392:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  393:         options += ',width=700,height=600';
  394:         editsearcher = open(url,title,options,'1');
  395:         editsearcher.focus();
  396:     }
  397: // END LON-CAPA Internal -->
  398: END
  399: }
  400: 
  401: sub lastresurl {
  402:     if ($env{'environment.lastresurl'}) {
  403: 	return $env{'environment.lastresurl'}
  404:     } else {
  405: 	return '/res';
  406:     }
  407: }
  408: 
  409: sub storeresurl {
  410:     my $resurl=&Apache::lonnet::clutter(shift);
  411:     unless ($resurl=~/^\/res/) { return 0; }
  412:     $resurl=~s/\/$//;
  413:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  414:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  415:     return 1;
  416: }
  417: 
  418: sub studentbrowser_javascript {
  419:    unless (
  420:             (($env{'request.course.id'}) && 
  421:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  422: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  423: 					  '/'.$env{'request.course.sec'})
  424: 	      ))
  425:          || ($env{'request.role'}=~/^(au|dc|su)/)
  426:           ) { return ''; }  
  427:    return (<<'ENDSTDBRW');
  428: <script type="text/javascript" language="Javascript">
  429: // <![CDATA[
  430:     var stdeditbrowser;
  431:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  432:         var url = '/adm/pickstudent?';
  433:         var filter;
  434: 	if (!ignorefilter) {
  435: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  436: 	}
  437:         if (filter != null) {
  438:            if (filter != '') {
  439:                url += 'filter='+filter+'&';
  440: 	   }
  441:         }
  442:         url += 'form=' + formname + '&unameelement='+uname+
  443:                                     '&udomelement='+udom+
  444:                                     '&clicker='+clicker;
  445: 	if (roleflag) { url+="&roles=1"; }
  446:         if (courseadv == 'condition') {
  447:             if (document.getElementById('courseadv')) {
  448:                 courseadv = document.getElementById('courseadv').value;
  449:             }
  450:         }
  451:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  452:         var title = 'Student_Browser';
  453:         var options = 'scrollbars=1,resizable=1,menubar=0';
  454:         options += ',width=700,height=600';
  455:         stdeditbrowser = open(url,title,options,'1');
  456:         stdeditbrowser.focus();
  457:     }
  458: // ]]>
  459: </script>
  460: ENDSTDBRW
  461: }
  462: 
  463: sub resourcebrowser_javascript {
  464:    unless ($env{'request.course.id'}) { return ''; }
  465:    return (<<'ENDRESBRW');
  466: <script type="text/javascript" language="Javascript">
  467: // <![CDATA[
  468:     var reseditbrowser;
  469:     function openresbrowser(formname,reslink) {
  470:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  471:         var title = 'Resource_Browser';
  472:         var options = 'scrollbars=1,resizable=1,menubar=0';
  473:         options += ',width=700,height=500';
  474:         reseditbrowser = open(url,title,options,'1');
  475:         reseditbrowser.focus();
  476:     }
  477: // ]]>
  478: </script>
  479: ENDRESBRW
  480: }
  481: 
  482: sub selectstudent_link {
  483:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  484:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  485:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  486:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  487:    if ($env{'request.course.id'}) {  
  488:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  489: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  490: 					'/'.$env{'request.course.sec'})) {
  491: 	   return '';
  492:        }
  493:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  494:        if ($courseadv eq 'only') {
  495:            $callargs .= ",'',1,'$courseadv'";
  496:        } elsif ($courseadv eq 'none') {
  497:            $callargs .= ",'','','$courseadv'";
  498:        } elsif ($courseadv eq 'condition') {
  499:            $callargs .= ",'','','$courseadv'";
  500:        }
  501:        return '<span class="LC_nobreak">'.
  502:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  503:               &mt('Select User').'</a></span>';
  504:    }
  505:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  506:        $callargs .= ",'',1"; 
  507:        return '<span class="LC_nobreak">'.
  508:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  509:               &mt('Select User').'</a></span>';
  510:    }
  511:    return '';
  512: }
  513: 
  514: sub selectresource_link {
  515:    my ($form,$reslink,$arg)=@_;
  516:    
  517:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  518:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  519:    unless ($env{'request.course.id'}) { return $arg; }
  520:    return '<span class="LC_nobreak">'.
  521:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  522:               $arg.'</a></span>';
  523: }
  524: 
  525: 
  526: 
  527: sub authorbrowser_javascript {
  528:     return <<"ENDAUTHORBRW";
  529: <script type="text/javascript" language="JavaScript">
  530: // <![CDATA[
  531: var stdeditbrowser;
  532: 
  533: function openauthorbrowser(formname,udom) {
  534:     var url = '/adm/pickauthor?';
  535:     url += 'form='+formname+'&roledom='+udom;
  536:     var title = 'Author_Browser';
  537:     var options = 'scrollbars=1,resizable=1,menubar=0';
  538:     options += ',width=700,height=600';
  539:     stdeditbrowser = open(url,title,options,'1');
  540:     stdeditbrowser.focus();
  541: }
  542: 
  543: // ]]>
  544: </script>
  545: ENDAUTHORBRW
  546: }
  547: 
  548: sub coursebrowser_javascript {
  549:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  550:         $credits_element,$instcode) = @_;
  551:     my $wintitle = 'Course_Browser';
  552:     if ($crstype eq 'Community') {
  553:         $wintitle = 'Community_Browser';
  554:     }
  555:     my $id_functions = &javascript_index_functions();
  556:     my $output = '
  557: <script type="text/javascript" language="JavaScript">
  558: // <![CDATA[
  559:     var stdeditbrowser;'."\n";
  560: 
  561:     $output .= <<"ENDSTDBRW";
  562:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  563:         var url = '/adm/pickcourse?';
  564:         var formid = getFormIdByName(formname);
  565:         var domainfilter = getDomainFromSelectbox(formname,udom);
  566:         if (domainfilter != null) {
  567:            if (domainfilter != '') {
  568:                url += 'domainfilter='+domainfilter+'&';
  569: 	   }
  570:         }
  571:         url += 'form=' + formname + '&cnumelement='+uname+
  572: 	                            '&cdomelement='+udom+
  573:                                     '&cnameelement='+desc;
  574:         if (extra_element !=null && extra_element != '') {
  575:             if (formname == 'rolechoice' || formname == 'studentform') {
  576:                 url += '&roleelement='+extra_element;
  577:                 if (domainfilter == null || domainfilter == '') {
  578:                     url += '&domainfilter='+extra_element;
  579:                 }
  580:             }
  581:             else {
  582:                 if (formname == 'portform') {
  583:                     url += '&setroles='+extra_element;
  584:                 } else {
  585:                     if (formname == 'rules') {
  586:                         url += '&fixeddom='+extra_element; 
  587:                     }
  588:                 }
  589:             }     
  590:         }
  591:         if (type != null && type != '') {
  592:             url += '&type='+type;
  593:         }
  594:         if (type_elem != null && type_elem != '') {
  595:             url += '&typeelement='+type_elem;
  596:         }
  597:         if (formname == 'ccrs') {
  598:             var ownername = document.forms[formid].ccuname.value;
  599:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  600:             url += '&cloner='+ownername+':'+ownerdom;
  601:             if (type == 'Course') {
  602:                 url += '&crscode='+document.forms[formid].crscode.value;
  603:             }
  604:         }
  605:         if (formname == 'requestcrs') {
  606:             url += '&crsdom=$domainfilter&crscode=$instcode';
  607:         }
  608:         if (multflag !=null && multflag != '') {
  609:             url += '&multiple='+multflag;
  610:         }
  611:         var title = '$wintitle';
  612:         var options = 'scrollbars=1,resizable=1,menubar=0';
  613:         options += ',width=700,height=600';
  614:         stdeditbrowser = open(url,title,options,'1');
  615:         stdeditbrowser.focus();
  616:     }
  617: $id_functions
  618: ENDSTDBRW
  619:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  620:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  621:                                       $credits_element);
  622:     }
  623:     $output .= '
  624: // ]]>
  625: </script>';
  626:     return $output;
  627: }
  628: 
  629: sub javascript_index_functions {
  630:     return <<"ENDJS";
  631: 
  632: function getFormIdByName(formname) {
  633:     for (var i=0;i<document.forms.length;i++) {
  634:         if (document.forms[i].name == formname) {
  635:             return i;
  636:         }
  637:     }
  638:     return -1;
  639: }
  640: 
  641: function getIndexByName(formid,item) {
  642:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  643:         if (document.forms[formid].elements[i].name == item) {
  644:             return i;
  645:         }
  646:     }
  647:     return -1;
  648: }
  649: 
  650: function getDomainFromSelectbox(formname,udom) {
  651:     var userdom;
  652:     var formid = getFormIdByName(formname);
  653:     if (formid > -1) {
  654:         var domid = getIndexByName(formid,udom);
  655:         if (domid > -1) {
  656:             if (document.forms[formid].elements[domid].type == 'select-one') {
  657:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  658:             }
  659:             if (document.forms[formid].elements[domid].type == 'hidden') {
  660:                 userdom=document.forms[formid].elements[domid].value;
  661:             }
  662:         }
  663:     }
  664:     return userdom;
  665: }
  666: 
  667: ENDJS
  668: 
  669: }
  670: 
  671: sub javascript_array_indexof {
  672:     return <<ENDJS;
  673: <script type="text/javascript" language="JavaScript">
  674: // <![CDATA[
  675: 
  676: if (!Array.prototype.indexOf) {
  677:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  678:         "use strict";
  679:         if (this === void 0 || this === null) {
  680:             throw new TypeError();
  681:         }
  682:         var t = Object(this);
  683:         var len = t.length >>> 0;
  684:         if (len === 0) {
  685:             return -1;
  686:         }
  687:         var n = 0;
  688:         if (arguments.length > 0) {
  689:             n = Number(arguments[1]);
  690:             if (n !== n) { // shortcut for verifying if it's NaN
  691:                 n = 0;
  692:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  693:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  694:             }
  695:         }
  696:         if (n >= len) {
  697:             return -1;
  698:         }
  699:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  700:         for (; k < len; k++) {
  701:             if (k in t && t[k] === searchElement) {
  702:                 return k;
  703:             }
  704:         }
  705:         return -1;
  706:     }
  707: }
  708: 
  709: // ]]>
  710: </script>
  711: 
  712: ENDJS
  713: 
  714: }
  715: 
  716: sub userbrowser_javascript {
  717:     my $id_functions = &javascript_index_functions();
  718:     return <<"ENDUSERBRW";
  719: 
  720: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  721:     var url = '/adm/pickuser?';
  722:     var userdom = getDomainFromSelectbox(formname,udom);
  723:     if (userdom != null) {
  724:        if (userdom != '') {
  725:            url += 'srchdom='+userdom+'&';
  726:        }
  727:     }
  728:     url += 'form=' + formname + '&unameelement='+uname+
  729:                                 '&udomelement='+udom+
  730:                                 '&ulastelement='+ulast+
  731:                                 '&ufirstelement='+ufirst+
  732:                                 '&uemailelement='+uemail+
  733:                                 '&hideudomelement='+hideudom+
  734:                                 '&coursedom='+crsdom;
  735:     if ((caller != null) && (caller != undefined)) {
  736:         url += '&caller='+caller;
  737:     }
  738:     var title = 'User_Browser';
  739:     var options = 'scrollbars=1,resizable=1,menubar=0';
  740:     options += ',width=700,height=600';
  741:     var stdeditbrowser = open(url,title,options,'1');
  742:     stdeditbrowser.focus();
  743: }
  744: 
  745: function fix_domain (formname,udom,origdom,uname) {
  746:     var formid = getFormIdByName(formname);
  747:     if (formid > -1) {
  748:         var unameid = getIndexByName(formid,uname);
  749:         var domid = getIndexByName(formid,udom);
  750:         var hidedomid = getIndexByName(formid,origdom);
  751:         if (hidedomid > -1) {
  752:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  753:             var unameval = document.forms[formid].elements[unameid].value;
  754:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  755:                 if (domid > -1) {
  756:                     var slct = document.forms[formid].elements[domid];
  757:                     if (slct.type == 'select-one') {
  758:                         var i;
  759:                         for (i=0;i<slct.length;i++) {
  760:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  761:                         }
  762:                     }
  763:                     if (slct.type == 'hidden') {
  764:                         slct.value = fixeddom;
  765:                     }
  766:                 }
  767:             }
  768:         }
  769:     }
  770:     return;
  771: }
  772: 
  773: $id_functions
  774: ENDUSERBRW
  775: }
  776: 
  777: sub setsec_javascript {
  778:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  779:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  780:         $communityrolestr);
  781:     if ($role_element ne '') {
  782:         my @allroles = ('st','ta','ep','in','ad');
  783:         foreach my $crstype ('Course','Community') {
  784:             if ($crstype eq 'Community') {
  785:                 foreach my $role (@allroles) {
  786:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  787:                 }
  788:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  789:             } else {
  790:                 foreach my $role (@allroles) {
  791:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  792:                 }
  793:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  794:             }
  795:         }
  796:         $rolestr = '"'.join('","',@allroles).'"';
  797:         $courserolestr = '"'.join('","',@courserolenames).'"';
  798:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  799:     }
  800:     my $setsections = qq|
  801: function setSect(sectionlist) {
  802:     var sectionsArray = new Array();
  803:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  804:         sectionsArray = sectionlist.split(",");
  805:     }
  806:     var numSections = sectionsArray.length;
  807:     document.$formname.$sec_element.length = 0;
  808:     if (numSections == 0) {
  809:         document.$formname.$sec_element.multiple=false;
  810:         document.$formname.$sec_element.size=1;
  811:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  812:     } else {
  813:         if (numSections == 1) {
  814:             document.$formname.$sec_element.multiple=false;
  815:             document.$formname.$sec_element.size=1;
  816:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  817:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  818:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  819:         } else {
  820:             for (var i=0; i<numSections; i++) {
  821:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  822:             }
  823:             document.$formname.$sec_element.multiple=true
  824:             if (numSections < 3) {
  825:                 document.$formname.$sec_element.size=numSections;
  826:             } else {
  827:                 document.$formname.$sec_element.size=3;
  828:             }
  829:             document.$formname.$sec_element.options[0].selected = false
  830:         }
  831:     }
  832: }
  833: 
  834: function setRole(crstype) {
  835: |;
  836:     if ($role_element eq '') {
  837:         $setsections .= '    return;
  838: }
  839: ';
  840:     } else {
  841:         $setsections .= qq|
  842:     var elementLength = document.$formname.$role_element.length;
  843:     var allroles = Array($rolestr);
  844:     var courserolenames = Array($courserolestr);
  845:     var communityrolenames = Array($communityrolestr);
  846:     if (elementLength != undefined) {
  847:         if (document.$formname.$role_element.options[5].value == 'cc') {
  848:             if (crstype == 'Course') {
  849:                 return;
  850:             } else {
  851:                 allroles[5] = 'co';
  852:                 for (var i=0; i<6; i++) {
  853:                     document.$formname.$role_element.options[i].value = allroles[i];
  854:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  855:                 }
  856:             }
  857:         } else {
  858:             if (crstype == 'Community') {
  859:                 return;
  860:             } else {
  861:                 allroles[5] = 'cc';
  862:                 for (var i=0; i<6; i++) {
  863:                     document.$formname.$role_element.options[i].value = allroles[i];
  864:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  865:                 }
  866:             }
  867:         }
  868:     }
  869:     return;
  870: }
  871: |;
  872:     }
  873:     if ($credits_element) {
  874:         $setsections .= qq|
  875: function setCredits(defaultcredits) {
  876:     document.$formname.$credits_element.value = defaultcredits;
  877:     return;
  878: }
  879: |;
  880:     }
  881:     return $setsections;
  882: }
  883: 
  884: sub selectcourse_link {
  885:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  886:        $typeelement) = @_;
  887:    my $type = $selecttype;
  888:    my $linktext = &mt('Select Course');
  889:    if ($selecttype eq 'Community') {
  890:        $linktext = &mt('Select Community');
  891:    } elsif ($selecttype eq 'Course/Community') {
  892:        $linktext = &mt('Select Course/Community');
  893:        $type = '';
  894:    } elsif ($selecttype eq 'Select') {
  895:        $linktext = &mt('Select');
  896:        $type = '';
  897:    }
  898:    return '<span class="LC_nobreak">'
  899:          ."<a href='"
  900:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  901:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  902:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  903:          ."'>".$linktext.'</a>'
  904:          .'</span>';
  905: }
  906: 
  907: sub selectauthor_link {
  908:    my ($form,$udom)=@_;
  909:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  910:           &mt('Select Author').'</a>';
  911: }
  912: 
  913: sub selectuser_link {
  914:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  915:         $coursedom,$linktext,$caller) = @_;
  916:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  917:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  918:            ');">'.$linktext.'</a>';
  919: }
  920: 
  921: sub check_uncheck_jscript {
  922:     my $jscript = <<"ENDSCRT";
  923: function checkAll(field) {
  924:     if (field.length > 0) {
  925:         for (i = 0; i < field.length; i++) {
  926:             if (!field[i].disabled) {
  927:                 field[i].checked = true;
  928:             }
  929:         }
  930:     } else {
  931:         if (!field.disabled) {
  932:             field.checked = true;
  933:         }
  934:     }
  935: }
  936:  
  937: function uncheckAll(field) {
  938:     if (field.length > 0) {
  939:         for (i = 0; i < field.length; i++) {
  940:             field[i].checked = false ;
  941:         }
  942:     } else {
  943:         field.checked = false ;
  944:     }
  945: }
  946: ENDSCRT
  947:     return $jscript;
  948: }
  949: 
  950: sub select_timezone {
  951:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  952:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  953:    if ($includeempty) {
  954:        $output .= '<option value=""';
  955:        if (($selected eq '') || ($selected eq 'local')) {
  956:            $output .= ' selected="selected" ';
  957:        }
  958:        $output .= '> </option>';
  959:    }
  960:    my @timezones = DateTime::TimeZone->all_names;
  961:    foreach my $tzone (@timezones) {
  962:        $output.= '<option value="'.$tzone.'"';
  963:        if ($tzone eq $selected) {
  964:            $output.=' selected="selected"';
  965:        }
  966:        $output.=">$tzone</option>\n";
  967:    }
  968:    $output.="</select>";
  969:    return $output;
  970: }
  971: 
  972: sub select_datelocale {
  973:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  974:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  975:     if ($includeempty) {
  976:         $output .= '<option value=""';
  977:         if ($selected eq '') {
  978:             $output .= ' selected="selected" ';
  979:         }
  980:         $output .= '> </option>';
  981:     }
  982:     my @languages = &Apache::lonlocal::preferred_languages();
  983:     my (@possibles,%locale_names);
  984:     my @locales = DateTime::Locale->ids();
  985:     foreach my $id (@locales) {
  986:         if ($id ne '') {
  987:             my ($en_terr,$native_terr);
  988:             my $loc = DateTime::Locale->load($id);
  989:             if (ref($loc)) {
  990:                 $en_terr = $loc->name();
  991:                 $native_terr = $loc->native_name();
  992:                 if (grep(/^en$/,@languages) || !@languages) {
  993:                     if ($en_terr ne '') {
  994:                         $locale_names{$id} = '('.$en_terr.')';
  995:                     } elsif ($native_terr ne '') {
  996:                         $locale_names{$id} = $native_terr;
  997:                     }
  998:                 } else {
  999:                     if ($native_terr ne '') {
 1000:                         $locale_names{$id} = $native_terr.' ';
 1001:                     } elsif ($en_terr ne '') {
 1002:                         $locale_names{$id} = '('.$en_terr.')';
 1003:                     }
 1004:                 }
 1005:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1006:                 push(@possibles,$id);
 1007:             }
 1008:         }
 1009:     }
 1010:     foreach my $item (sort(@possibles)) {
 1011:         $output.= '<option value="'.$item.'"';
 1012:         if ($item eq $selected) {
 1013:             $output.=' selected="selected"';
 1014:         }
 1015:         $output.=">$item";
 1016:         if ($locale_names{$item} ne '') {
 1017:             $output.='  '.$locale_names{$item};
 1018:         }
 1019:         $output.="</option>\n";
 1020:     }
 1021:     $output.="</select>";
 1022:     return $output;
 1023: }
 1024: 
 1025: sub select_language {
 1026:     my ($name,$selected,$includeempty,$noedit) = @_;
 1027:     my %langchoices;
 1028:     if ($includeempty) {
 1029:         %langchoices = ('' => 'No language preference');
 1030:     }
 1031:     foreach my $id (&languageids()) {
 1032:         my $code = &supportedlanguagecode($id);
 1033:         if ($code) {
 1034:             $langchoices{$code} = &plainlanguagedescription($id);
 1035:         }
 1036:     }
 1037:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1038:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1039: }
 1040: 
 1041: =pod
 1042: 
 1043: =item * &linked_select_forms(...)
 1044: 
 1045: linked_select_forms returns a string containing a <script></script> block
 1046: and html for two <select> menus.  The select menus will be linked in that
 1047: changing the value of the first menu will result in new values being placed
 1048: in the second menu.  The values in the select menu will appear in alphabetical
 1049: order unless a defined order is provided.
 1050: 
 1051: linked_select_forms takes the following ordered inputs:
 1052: 
 1053: =over 4
 1054: 
 1055: =item * $formname, the name of the <form> tag
 1056: 
 1057: =item * $middletext, the text which appears between the <select> tags
 1058: 
 1059: =item * $firstdefault, the default value for the first menu
 1060: 
 1061: =item * $firstselectname, the name of the first <select> tag
 1062: 
 1063: =item * $secondselectname, the name of the second <select> tag
 1064: 
 1065: =item * $hashref, a reference to a hash containing the data for the menus.
 1066: 
 1067: =item * $menuorder, the order of values in the first menu
 1068: 
 1069: =item * $onchangefirst, additional javascript call to execute for an onchange
 1070:         event for the first <select> tag
 1071: 
 1072: =item * $onchangesecond, additional javascript call to execute for an onchange
 1073:         event for the second <select> tag
 1074: 
 1075: =back 
 1076: 
 1077: Below is an example of such a hash.  Only the 'text', 'default', and 
 1078: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1079: values for the first select menu.  The text that coincides with the 
 1080: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1081: and text for the second menu are given in the hash pointed to by 
 1082: $menu{$choice1}->{'select2'}.  
 1083: 
 1084:  my %menu = ( A1 => { text =>"Choice A1" ,
 1085:                        default => "B3",
 1086:                        select2 => { 
 1087:                            B1 => "Choice B1",
 1088:                            B2 => "Choice B2",
 1089:                            B3 => "Choice B3",
 1090:                            B4 => "Choice B4"
 1091:                            },
 1092:                        order => ['B4','B3','B1','B2'],
 1093:                    },
 1094:                A2 => { text =>"Choice A2" ,
 1095:                        default => "C2",
 1096:                        select2 => { 
 1097:                            C1 => "Choice C1",
 1098:                            C2 => "Choice C2",
 1099:                            C3 => "Choice C3"
 1100:                            },
 1101:                        order => ['C2','C1','C3'],
 1102:                    },
 1103:                A3 => { text =>"Choice A3" ,
 1104:                        default => "D6",
 1105:                        select2 => { 
 1106:                            D1 => "Choice D1",
 1107:                            D2 => "Choice D2",
 1108:                            D3 => "Choice D3",
 1109:                            D4 => "Choice D4",
 1110:                            D5 => "Choice D5",
 1111:                            D6 => "Choice D6",
 1112:                            D7 => "Choice D7"
 1113:                            },
 1114:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1115:                    }
 1116:                );
 1117: 
 1118: =cut
 1119: 
 1120: sub linked_select_forms {
 1121:     my ($formname,
 1122:         $middletext,
 1123:         $firstdefault,
 1124:         $firstselectname,
 1125:         $secondselectname, 
 1126:         $hashref,
 1127:         $menuorder,
 1128:         $onchangefirst,
 1129:         $onchangesecond
 1130:         ) = @_;
 1131:     my $second = "document.$formname.$secondselectname";
 1132:     my $first = "document.$formname.$firstselectname";
 1133:     # output the javascript to do the changing
 1134:     my $result = '';
 1135:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1136:     $result.="// <![CDATA[\n";
 1137:     $result.="var select2data = new Object();\n";
 1138:     $" = '","';
 1139:     my $debug = '';
 1140:     foreach my $s1 (sort(keys(%$hashref))) {
 1141:         $result.="select2data.d_$s1 = new Object();\n";        
 1142:         $result.="select2data.d_$s1.def = new String('".
 1143:             $hashref->{$s1}->{'default'}."');\n";
 1144:         $result.="select2data.d_$s1.values = new Array(";
 1145:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1146:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1147:             @s2values = @{$hashref->{$s1}->{'order'}};
 1148:         }
 1149:         $result.="\"@s2values\");\n";
 1150:         $result.="select2data.d_$s1.texts = new Array(";        
 1151:         my @s2texts;
 1152:         foreach my $value (@s2values) {
 1153:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1154:         }
 1155:         $result.="\"@s2texts\");\n";
 1156:     }
 1157:     $"=' ';
 1158:     $result.= <<"END";
 1159: 
 1160: function select1_changed() {
 1161:     // Determine new choice
 1162:     var newvalue = "d_" + $first.value;
 1163:     // update select2
 1164:     var values     = select2data[newvalue].values;
 1165:     var texts      = select2data[newvalue].texts;
 1166:     var select2def = select2data[newvalue].def;
 1167:     var i;
 1168:     // out with the old
 1169:     for (i = 0; i < $second.options.length; i++) {
 1170:         $second.options[i] = null;
 1171:     }
 1172:     // in with the nuclear
 1173:     for (i=0;i<values.length; i++) {
 1174:         $second.options[i] = new Option(values[i]);
 1175:         $second.options[i].value = values[i];
 1176:         $second.options[i].text = texts[i];
 1177:         if (values[i] == select2def) {
 1178:             $second.options[i].selected = true;
 1179:         }
 1180:     }
 1181: }
 1182: // ]]>
 1183: </script>
 1184: END
 1185:     # output the initial values for the selection lists
 1186:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1187:     my @order = sort(keys(%{$hashref}));
 1188:     if (ref($menuorder) eq 'ARRAY') {
 1189:         @order = @{$menuorder};
 1190:     }
 1191:     foreach my $value (@order) {
 1192:         $result.="    <option value=\"$value\" ";
 1193:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1194:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1195:     }
 1196:     $result .= "</select>\n";
 1197:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1198:     $result .= $middletext;
 1199:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1200:     if ($onchangesecond) {
 1201:         $result .= ' onchange="'.$onchangesecond.'"';
 1202:     }
 1203:     $result .= ">\n";
 1204:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1205:     
 1206:     my @secondorder = sort(keys(%select2));
 1207:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1208:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1209:     }
 1210:     foreach my $value (@secondorder) {
 1211:         $result.="    <option value=\"$value\" ";        
 1212:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1213:         $result.=">".&mt($select2{$value})."</option>\n";
 1214:     }
 1215:     $result .= "</select>\n";
 1216:     #    return $debug;
 1217:     return $result;
 1218: }   #  end of sub linked_select_forms {
 1219: 
 1220: =pod
 1221: 
 1222: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1223: 
 1224: Returns a string corresponding to an HTML link to the given help
 1225: $topic, where $topic corresponds to the name of a .tex file in
 1226: /home/httpd/html/adm/help/tex, with underscores replaced by
 1227: spaces. 
 1228: 
 1229: $text will optionally be linked to the same topic, allowing you to
 1230: link text in addition to the graphic. If you do not want to link
 1231: text, but wish to specify one of the later parameters, pass an
 1232: empty string. 
 1233: 
 1234: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1235: the link will not open a new window. If false, the link will open
 1236: a new window using Javascript. (Default is false.) 
 1237: 
 1238: $width and $height are optional numerical parameters that will
 1239: override the width and height of the popped up window, which may
 1240: be useful for certain help topics with big pictures included.
 1241: 
 1242: $imgid is the id of the img tag used for the help icon. This may be
 1243: used in a javascript call to switch the image src.  See 
 1244: lonhtmlcommon::htmlareaselectactive() for an example.
 1245: 
 1246: =cut
 1247: 
 1248: sub help_open_topic {
 1249:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1250:     $text = "" if (not defined $text);
 1251:     $stayOnPage = 0 if (not defined $stayOnPage);
 1252:     $width = 500 if (not defined $width);
 1253:     $height = 400 if (not defined $height);
 1254:     my $filename = $topic;
 1255:     $filename =~ s/ /_/g;
 1256: 
 1257:     my $template = "";
 1258:     my $link;
 1259:     
 1260:     $topic=~s/\W/\_/g;
 1261: 
 1262:     if (!$stayOnPage) {
 1263:         if ($env{'browser.mobile'}) {
 1264: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1265:         } else {
 1266:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1267:         }
 1268:     } elsif ($stayOnPage eq 'popup') {
 1269:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1270:     } else {
 1271: 	$link = "/adm/help/${filename}.hlp";
 1272:     }
 1273: 
 1274:     # Add the text
 1275:     if ($text ne "") {	
 1276: 	$template.='<span class="LC_help_open_topic">'
 1277:                   .'<a target="_top" href="'.$link.'">'
 1278:                   .$text.'</a>';
 1279:     }
 1280: 
 1281:     # (Always) Add the graphic
 1282:     my $title = &mt('Online Help');
 1283:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1284:     if ($imgid ne '') {
 1285:         $imgid = ' id="'.$imgid.'"';
 1286:     }
 1287:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1288:               .'<img src="'.$helpicon.'" border="0"'
 1289:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1290:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1291:               .' /></a>';
 1292:     if ($text ne "") {	
 1293:         $template.='</span>';
 1294:     }
 1295:     return $template;
 1296: 
 1297: }
 1298: 
 1299: # This is a quicky function for Latex cheatsheet editing, since it 
 1300: # appears in at least four places
 1301: sub helpLatexCheatsheet {
 1302:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1303:     my $out;
 1304:     my $addOther = '';
 1305:     if ($topic) {
 1306: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1307:     }
 1308:     $out = '<span>' # Start cheatsheet
 1309: 	  .$addOther
 1310:           .'<span>'
 1311: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1312: 	  .'</span> <span>'
 1313: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1314: 	  .'</span>';
 1315:     unless ($not_author) {
 1316:         $out .= ' <span>'
 1317: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1318: 	       .'</span> <span>'
 1319:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1320:                .'</span>';
 1321:     }
 1322:     $out .= '</span>'; # End cheatsheet
 1323:     return $out;
 1324: }
 1325: 
 1326: sub general_help {
 1327:     my $helptopic='Student_Intro';
 1328:     if ($env{'request.role'}=~/^(ca|au)/) {
 1329: 	$helptopic='Authoring_Intro';
 1330:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1331: 	$helptopic='Course_Coordination_Intro';
 1332:     } elsif ($env{'request.role'}=~/^dc/) {
 1333:         $helptopic='Domain_Coordination_Intro';
 1334:     }
 1335:     return $helptopic;
 1336: }
 1337: 
 1338: sub update_help_link {
 1339:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1340:     my $origurl = $ENV{'REQUEST_URI'};
 1341:     $origurl=~s|^/~|/priv/|;
 1342:     my $timestamp = time;
 1343:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1344:         $$datum = &escape($$datum);
 1345:     }
 1346: 
 1347:     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";
 1348:     my $output .= <<"ENDOUTPUT";
 1349: <script type="text/javascript">
 1350: // <![CDATA[
 1351: banner_link = '$banner_link';
 1352: // ]]>
 1353: </script>
 1354: ENDOUTPUT
 1355:     return $output;
 1356: }
 1357: 
 1358: # now just updates the help link and generates a blue icon
 1359: sub help_open_menu {
 1360:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1361: 	= @_;    
 1362:     $stayOnPage = 1;
 1363:     my $output;
 1364:     if ($component_help) {
 1365: 	if (!$text) {
 1366: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1367: 				       $width,$height);
 1368: 	} else {
 1369: 	    my $help_text;
 1370: 	    $help_text=&unescape($topic);
 1371: 	    $output='<table><tr><td>'.
 1372: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1373: 				 $width,$height).'</td></tr></table>';
 1374: 	}
 1375:     }
 1376:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1377:     return $output.$banner_link;
 1378: }
 1379: 
 1380: sub top_nav_help {
 1381:     my ($text,$linkattr) = @_;
 1382:     $text = &mt($text);
 1383:     my $stay_on_page;
 1384:     unless ($env{'environment.remote'} eq 'on') {
 1385:         $stay_on_page = 1;
 1386:     }
 1387:     my ($link,$banner_link);
 1388:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1389:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1390: 	                         : "javascript:helpMenu('open')";
 1391:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1392:     }
 1393:     my $title = &mt('Get help');
 1394:     if ($link) {
 1395:         return <<"END";
 1396: $banner_link
 1397: <a href="$link" title="$title" $linkattr>$text</a>
 1398: END
 1399:     } else {
 1400:         return '&nbsp;'.$text.'&nbsp;';
 1401:     }
 1402: }
 1403: 
 1404: sub help_menu_js {
 1405:     my ($httphost) = @_;
 1406:     my $stayOnPage = 1;
 1407:     my $width = 620;
 1408:     my $height = 600;
 1409:     my $helptopic=&general_help();
 1410:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1411:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1412:     my $start_page =
 1413:         &Apache::loncommon::start_page('Help Menu', undef,
 1414: 				       {'frameset'    => 1,
 1415: 					'js_ready'    => 1,
 1416:                                         'use_absolute' => $httphost,
 1417: 					'add_entries' => {
 1418: 					    'border' => '0',
 1419: 					    'rows'   => "110,*",},});
 1420:     my $end_page =
 1421:         &Apache::loncommon::end_page({'frameset' => 1,
 1422: 				      'js_ready' => 1,});
 1423: 
 1424:     my $template .= <<"ENDTEMPLATE";
 1425: <script type="text/javascript">
 1426: // <![CDATA[
 1427: // <!-- BEGIN LON-CAPA Internal
 1428: var banner_link = '';
 1429: function helpMenu(target) {
 1430:     var caller = this;
 1431:     if (target == 'open') {
 1432:         var newWindow = null;
 1433:         try {
 1434:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1435:         }
 1436:         catch(error) {
 1437:             writeHelp(caller);
 1438:             return;
 1439:         }
 1440:         if (newWindow) {
 1441:             caller = newWindow;
 1442:         }
 1443:     }
 1444:     writeHelp(caller);
 1445:     return;
 1446: }
 1447: function writeHelp(caller) {
 1448:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1449:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1450:     caller.document.close();
 1451:     caller.focus();
 1452: }
 1453: // END LON-CAPA Internal -->
 1454: // ]]>
 1455: </script>
 1456: ENDTEMPLATE
 1457:     return $template;
 1458: }
 1459: 
 1460: sub help_open_bug {
 1461:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1462:     unless ($env{'user.adv'}) { return ''; }
 1463:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1464:     $text = "" if (not defined $text);
 1465: 	$stayOnPage=1;
 1466:     $width = 600 if (not defined $width);
 1467:     $height = 600 if (not defined $height);
 1468: 
 1469:     $topic=~s/\W+/\+/g;
 1470:     my $link='';
 1471:     my $template='';
 1472:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1473: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1474:     if (!$stayOnPage)
 1475:     {
 1476: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1477:     }
 1478:     else
 1479:     {
 1480: 	$link = $url;
 1481:     }
 1482:     # Add the text
 1483:     if ($text ne "")
 1484:     {
 1485: 	$template .= 
 1486:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1487:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1488:     }
 1489: 
 1490:     # Add the graphic
 1491:     my $title = &mt('Report a Bug');
 1492:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1493:     $template .= <<"ENDTEMPLATE";
 1494:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1495: ENDTEMPLATE
 1496:     if ($text ne '') { $template.='</td></tr></table>' };
 1497:     return $template;
 1498: 
 1499: }
 1500: 
 1501: sub help_open_faq {
 1502:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1503:     unless ($env{'user.adv'}) { return ''; }
 1504:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1505:     $text = "" if (not defined $text);
 1506: 	$stayOnPage=1;
 1507:     $width = 350 if (not defined $width);
 1508:     $height = 400 if (not defined $height);
 1509: 
 1510:     $topic=~s/\W+/\+/g;
 1511:     my $link='';
 1512:     my $template='';
 1513:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1514:     if (!$stayOnPage)
 1515:     {
 1516: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1517:     }
 1518:     else
 1519:     {
 1520: 	$link = $url;
 1521:     }
 1522: 
 1523:     # Add the text
 1524:     if ($text ne "")
 1525:     {
 1526: 	$template .= 
 1527:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1528:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1529:     }
 1530: 
 1531:     # Add the graphic
 1532:     my $title = &mt('View the FAQ');
 1533:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1534:     $template .= <<"ENDTEMPLATE";
 1535:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1536: ENDTEMPLATE
 1537:     if ($text ne '') { $template.='</td></tr></table>' };
 1538:     return $template;
 1539: 
 1540: }
 1541: 
 1542: ###############################################################
 1543: ###############################################################
 1544: 
 1545: =pod
 1546: 
 1547: =item * &change_content_javascript():
 1548: 
 1549: This and the next function allow you to create small sections of an
 1550: otherwise static HTML page that you can update on the fly with
 1551: Javascript, even in Netscape 4.
 1552: 
 1553: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1554: must be written to the HTML page once. It will prove the Javascript
 1555: function "change(name, content)". Calling the change function with the
 1556: name of the section 
 1557: you want to update, matching the name passed to C<changable_area>, and
 1558: the new content you want to put in there, will put the content into
 1559: that area.
 1560: 
 1561: B<Note>: Netscape 4 only reserves enough space for the changable area
 1562: to contain room for the original contents. You need to "make space"
 1563: for whatever changes you wish to make, and be B<sure> to check your
 1564: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1565: it's adequate for updating a one-line status display, but little more.
 1566: This script will set the space to 100% width, so you only need to
 1567: worry about height in Netscape 4.
 1568: 
 1569: Modern browsers are much less limiting, and if you can commit to the
 1570: user not using Netscape 4, this feature may be used freely with
 1571: pretty much any HTML.
 1572: 
 1573: =cut
 1574: 
 1575: sub change_content_javascript {
 1576:     # If we're on Netscape 4, we need to use Layer-based code
 1577:     if ($env{'browser.type'} eq 'netscape' &&
 1578: 	$env{'browser.version'} =~ /^4\./) {
 1579: 	return (<<NETSCAPE4);
 1580: 	function change(name, content) {
 1581: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1582: 	    doc.open();
 1583: 	    doc.write(content);
 1584: 	    doc.close();
 1585: 	}
 1586: NETSCAPE4
 1587:     } else {
 1588: 	# Otherwise, we need to use semi-standards-compliant code
 1589: 	# (technically, "innerHTML" isn't standard but the equivalent
 1590: 	# is really scary, and every useful browser supports it
 1591: 	return (<<DOMBASED);
 1592: 	function change(name, content) {
 1593: 	    element = document.getElementById(name);
 1594: 	    element.innerHTML = content;
 1595: 	}
 1596: DOMBASED
 1597:     }
 1598: }
 1599: 
 1600: =pod
 1601: 
 1602: =item * &changable_area($name,$origContent):
 1603: 
 1604: This provides a "changable area" that can be modified on the fly via
 1605: the Javascript code provided in C<change_content_javascript>. $name is
 1606: the name you will use to reference the area later; do not repeat the
 1607: same name on a given HTML page more then once. $origContent is what
 1608: the area will originally contain, which can be left blank.
 1609: 
 1610: =cut
 1611: 
 1612: sub changable_area {
 1613:     my ($name, $origContent) = @_;
 1614: 
 1615:     if ($env{'browser.type'} eq 'netscape' &&
 1616: 	$env{'browser.version'} =~ /^4\./) {
 1617: 	# If this is netscape 4, we need to use the Layer tag
 1618: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1619:     } else {
 1620: 	return "<span id='$name'>$origContent</span>";
 1621:     }
 1622: }
 1623: 
 1624: =pod
 1625: 
 1626: =item * &viewport_geometry_js 
 1627: 
 1628: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1629: 
 1630: =cut
 1631: 
 1632: 
 1633: sub viewport_geometry_js { 
 1634:     return <<"GEOMETRY";
 1635: var Geometry = {};
 1636: function init_geometry() {
 1637:     if (Geometry.init) { return };
 1638:     Geometry.init=1;
 1639:     if (window.innerHeight) {
 1640:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1641:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1642:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1643:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1644:     }
 1645:     else if (document.documentElement && document.documentElement.clientHeight) {
 1646:         Geometry.getViewportHeight =
 1647:             function() { return document.documentElement.clientHeight; };
 1648:         Geometry.getViewportWidth =
 1649:             function() { return document.documentElement.clientWidth; };
 1650: 
 1651:         Geometry.getHorizontalScroll =
 1652:             function() { return document.documentElement.scrollLeft; };
 1653:         Geometry.getVerticalScroll =
 1654:             function() { return document.documentElement.scrollTop; };
 1655:     }
 1656:     else if (document.body.clientHeight) {
 1657:         Geometry.getViewportHeight =
 1658:             function() { return document.body.clientHeight; };
 1659:         Geometry.getViewportWidth =
 1660:             function() { return document.body.clientWidth; };
 1661:         Geometry.getHorizontalScroll =
 1662:             function() { return document.body.scrollLeft; };
 1663:         Geometry.getVerticalScroll =
 1664:             function() { return document.body.scrollTop; };
 1665:     }
 1666: }
 1667: 
 1668: GEOMETRY
 1669: }
 1670: 
 1671: =pod
 1672: 
 1673: =item * &viewport_size_js()
 1674: 
 1675: 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. 
 1676: 
 1677: =cut
 1678: 
 1679: sub viewport_size_js {
 1680:     my $geometry = &viewport_geometry_js();
 1681:     return <<"DIMS";
 1682: 
 1683: $geometry
 1684: 
 1685: function getViewportDims(width,height) {
 1686:     init_geometry();
 1687:     width.value = Geometry.getViewportWidth();
 1688:     height.value = Geometry.getViewportHeight();
 1689:     return;
 1690: }
 1691: 
 1692: DIMS
 1693: }
 1694: 
 1695: =pod
 1696: 
 1697: =item * &resize_textarea_js()
 1698: 
 1699: emits the needed javascript to resize a textarea to be as big as possible
 1700: 
 1701: creates a function resize_textrea that takes two IDs first should be
 1702: the id of the element to resize, second should be the id of a div that
 1703: surrounds everything that comes after the textarea, this routine needs
 1704: to be attached to the <body> for the onload and onresize events.
 1705: 
 1706: =back
 1707: 
 1708: =cut
 1709: 
 1710: sub resize_textarea_js {
 1711:     my $geometry = &viewport_geometry_js();
 1712:     return <<"RESIZE";
 1713:     <script type="text/javascript">
 1714: // <![CDATA[
 1715: $geometry
 1716: 
 1717: function getX(element) {
 1718:     var x = 0;
 1719:     while (element) {
 1720: 	x += element.offsetLeft;
 1721: 	element = element.offsetParent;
 1722:     }
 1723:     return x;
 1724: }
 1725: function getY(element) {
 1726:     var y = 0;
 1727:     while (element) {
 1728: 	y += element.offsetTop;
 1729: 	element = element.offsetParent;
 1730:     }
 1731:     return y;
 1732: }
 1733: 
 1734: 
 1735: function resize_textarea(textarea_id,bottom_id) {
 1736:     init_geometry();
 1737:     var textarea        = document.getElementById(textarea_id);
 1738:     //alert(textarea);
 1739: 
 1740:     var textarea_top    = getY(textarea);
 1741:     var textarea_height = textarea.offsetHeight;
 1742:     var bottom          = document.getElementById(bottom_id);
 1743:     var bottom_top      = getY(bottom);
 1744:     var bottom_height   = bottom.offsetHeight;
 1745:     var window_height   = Geometry.getViewportHeight();
 1746:     var fudge           = 23;
 1747:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1748:     if (new_height < 300) {
 1749: 	new_height = 300;
 1750:     }
 1751:     textarea.style.height=new_height+'px';
 1752: }
 1753: // ]]>
 1754: </script>
 1755: RESIZE
 1756: 
 1757: }
 1758: 
 1759: sub colorfuleditor_js {
 1760:     return <<"COLORFULEDIT"
 1761: <script type="text/javascript">
 1762: // <![CDATA[>
 1763:     function fold_box(curDepth, lastresource){
 1764: 
 1765:     // we need a list because there can be several blocks you need to fold in one tag
 1766:         var block = document.getElementsByName('foldblock_'+curDepth);
 1767:     // but there is only one folding button per tag
 1768:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1769: 
 1770:         if(block.item(0).style.display == 'none'){
 1771: 
 1772:             foldbutton.value = '@{[&mt("Hide")]}';
 1773:             for (i = 0; i < block.length; i++){
 1774:                 block.item(i).style.display = '';
 1775:             }
 1776:         }else{
 1777: 
 1778:             foldbutton.value = '@{[&mt("Show")]}';
 1779:             for (i = 0; i < block.length; i++){
 1780:                 // block.item(i).style.visibility = 'collapse';
 1781:                 block.item(i).style.display = 'none';
 1782:             }
 1783:         };
 1784:         saveState(lastresource);
 1785:     }
 1786: 
 1787:     function saveState (lastresource) {
 1788: 
 1789:         var tag_list = getTagList();
 1790:         if(tag_list != null){
 1791:             var timestamp = new Date().getTime();
 1792:             var key = lastresource;
 1793: 
 1794:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1795:             // starting with timestamp
 1796:             var value = timestamp+';';
 1797: 
 1798:             // building the list of key-value pairs
 1799:             for(var i = 0; i < tag_list.length; i++){
 1800:                 value += tag_list[i]+',';
 1801:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1802:             }
 1803: 
 1804:             // only iterate whole storage if nothing to override
 1805:             if(localStorage.getItem(key) == null){
 1806: 
 1807:                 // prevent storage from growing large
 1808:                 if(localStorage.length > 50){
 1809:                     var regex_getTimestamp = /^(?:\d)+;/;
 1810:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1811:                     var oldest_key;
 1812: 
 1813:                     for(var i = 1; i < localStorage.length; i++){
 1814:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1815:                             oldest_key = localStorage.key(i);
 1816:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1817:                         }
 1818:                     }
 1819:                     localStorage.removeItem(oldest_key);
 1820:                 }
 1821:             }
 1822:             localStorage.setItem(key,value);
 1823:         }
 1824:     }
 1825: 
 1826:     // restore folding status of blocks (on page load)
 1827:     function restoreState (lastresource) {
 1828:         if(localStorage.getItem(lastresource) != null){
 1829:             var key = lastresource;
 1830:             var value = localStorage.getItem(key);
 1831:             var regex_delTimestamp = /^\d+;/;
 1832: 
 1833:             value.replace(regex_delTimestamp, '');
 1834: 
 1835:             var valueArr = value.split(';');
 1836:             var pairs;
 1837:             var elements;
 1838:             for (var i = 0; i < valueArr.length; i++){
 1839:                 pairs = valueArr[i].split(',');
 1840:                 elements = document.getElementsByName(pairs[0]);
 1841: 
 1842:                 for (var j = 0; j < elements.length; j++){
 1843:                     elements[j].style.display = pairs[1];
 1844:                     if (pairs[1] == "none"){
 1845:                         var regex_id = /([_\\d]+)\$/;
 1846:                         regex_id.exec(pairs[0]);
 1847:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1848:                     }
 1849:                 }
 1850:             }
 1851:         }
 1852:     }
 1853: 
 1854:     function getTagList () {
 1855: 
 1856:         var stringToSearch = document.lonhomework.innerHTML;
 1857: 
 1858:         var ret = new Array();
 1859:         var regex_findBlock = /(foldblock_.*?)"/g;
 1860:         var tag_list = stringToSearch.match(regex_findBlock);
 1861: 
 1862:         if(tag_list != null){
 1863:             for(var i = 0; i < tag_list.length; i++){
 1864:                 ret.push(tag_list[i].replace(/"/, ''));
 1865:             }
 1866:         }
 1867:         return ret;
 1868:     }
 1869: 
 1870:     function saveScrollPosition (resource) {
 1871:         var tag_list = getTagList();
 1872: 
 1873:         // we dont always want to jump to the first block
 1874:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1875:         if(\$(window).scrollTop() > 170){
 1876:             if(tag_list != null){
 1877:                 var result;
 1878:                 for(var i = 0; i < tag_list.length; i++){
 1879:                     if(isElementInViewport(tag_list[i])){
 1880:                         result += tag_list[i]+';';
 1881:                     }
 1882:                 }
 1883:                 sessionStorage.setItem('anchor_'+resource, result);
 1884:             }
 1885:         } else {
 1886:             // we dont need to save zero, just delete the item to leave everything tidy
 1887:             sessionStorage.removeItem('anchor_'+resource);
 1888:         }
 1889:     }
 1890: 
 1891:     function restoreScrollPosition(resource){
 1892: 
 1893:         var elem = sessionStorage.getItem('anchor_'+resource);
 1894:         if(elem != null){
 1895:             var tag_list = elem.split(';');
 1896:             var elem_list;
 1897: 
 1898:             for(var i = 0; i < tag_list.length; i++){
 1899:                 elem_list = document.getElementsByName(tag_list[i]);
 1900: 
 1901:                 if(elem_list.length > 0){
 1902:                     elem = elem_list[0];
 1903:                     break;
 1904:                 }
 1905:             }
 1906:             elem.scrollIntoView();
 1907:         }
 1908:     }
 1909: 
 1910:     function isElementInViewport(el) {
 1911: 
 1912:         // change to last element instead of first
 1913:         var elem = document.getElementsByName(el);
 1914:         var rect = elem[0].getBoundingClientRect();
 1915: 
 1916:         return (
 1917:             rect.top >= 0 &&
 1918:             rect.left >= 0 &&
 1919:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1920:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1921:         );
 1922:     }
 1923: 
 1924:     function autosize(depth){
 1925:         var cmInst = window['cm'+depth];
 1926:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1927: 
 1928:         // is fixed size, switching to dynamic
 1929:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1930:             cmInst.setSize("","auto");
 1931:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1932:             sessionStorage.setItem("autosized_"+depth, "yes");
 1933: 
 1934:         // is dynamic size, switching to fixed
 1935:         } else {
 1936:             cmInst.setSize("","300px");
 1937:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1938:             sessionStorage.removeItem("autosized_"+depth);
 1939:         }
 1940:     }
 1941: 
 1942: 
 1943: 
 1944: // ]]>
 1945: </script>
 1946: COLORFULEDIT
 1947: }
 1948: 
 1949: sub xmleditor_js {
 1950:     return <<XMLEDIT
 1951: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1952: <script type="text/javascript">
 1953: // <![CDATA[>
 1954: 
 1955:     function saveScrollPosition (resource) {
 1956: 
 1957:         var scrollPos = \$(window).scrollTop();
 1958:         sessionStorage.setItem(resource,scrollPos);
 1959:     }
 1960: 
 1961:     function restoreScrollPosition(resource){
 1962: 
 1963:         var scrollPos = sessionStorage.getItem(resource);
 1964:         \$(window).scrollTop(scrollPos);
 1965:     }
 1966: 
 1967:     // unless internet explorer
 1968:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1969: 
 1970:         \$(document).ready(function() {
 1971:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1972:         });
 1973:     }
 1974: 
 1975:     // inserts text at cursor position into codemirror (xml editor only)
 1976:     function insertText(text){
 1977:         cm.focus();
 1978:         var curPos = cm.getCursor();
 1979:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1980:     }
 1981: // ]]>
 1982: </script>
 1983: XMLEDIT
 1984: }
 1985: 
 1986: sub insert_folding_button {
 1987:     my $curDepth = $Apache::lonxml::curdepth;
 1988:     my $lastresource = $env{'request.ambiguous'};
 1989: 
 1990:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 1991:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 1992: }
 1993: 
 1994: 
 1995: =pod
 1996: 
 1997: =head1 Excel and CSV file utility routines
 1998: 
 1999: =cut
 2000: 
 2001: ###############################################################
 2002: ###############################################################
 2003: 
 2004: =pod
 2005: 
 2006: =over 4
 2007: 
 2008: =item * &csv_translate($text) 
 2009: 
 2010: Translate $text to allow it to be output as a 'comma separated values' 
 2011: format.
 2012: 
 2013: =cut
 2014: 
 2015: ###############################################################
 2016: ###############################################################
 2017: sub csv_translate {
 2018:     my $text = shift;
 2019:     $text =~ s/\"/\"\"/g;
 2020:     $text =~ s/\n/ /g;
 2021:     return $text;
 2022: }
 2023: 
 2024: ###############################################################
 2025: ###############################################################
 2026: 
 2027: =pod
 2028: 
 2029: =item * &define_excel_formats()
 2030: 
 2031: Define some commonly used Excel cell formats.
 2032: 
 2033: Currently supported formats:
 2034: 
 2035: =over 4
 2036: 
 2037: =item header
 2038: 
 2039: =item bold
 2040: 
 2041: =item h1
 2042: 
 2043: =item h2
 2044: 
 2045: =item h3
 2046: 
 2047: =item h4
 2048: 
 2049: =item i
 2050: 
 2051: =item date
 2052: 
 2053: =back
 2054: 
 2055: Inputs: $workbook
 2056: 
 2057: Returns: $format, a hash reference.
 2058: 
 2059: 
 2060: =cut
 2061: 
 2062: ###############################################################
 2063: ###############################################################
 2064: sub define_excel_formats {
 2065:     my ($workbook) = @_;
 2066:     my $format;
 2067:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2068:                                                 bottom    => 1,
 2069:                                                 align     => 'center');
 2070:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2071:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2072:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2073:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2074:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2075:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2076:     $format->{'date'} = $workbook->add_format(num_format=>
 2077:                                             'mm/dd/yyyy hh:mm:ss');
 2078:     return $format;
 2079: }
 2080: 
 2081: ###############################################################
 2082: ###############################################################
 2083: 
 2084: =pod
 2085: 
 2086: =item * &create_workbook()
 2087: 
 2088: Create an Excel worksheet.  If it fails, output message on the
 2089: request object and return undefs.
 2090: 
 2091: Inputs: Apache request object
 2092: 
 2093: Returns (undef) on failure, 
 2094:     Excel worksheet object, scalar with filename, and formats 
 2095:     from &Apache::loncommon::define_excel_formats on success
 2096: 
 2097: =cut
 2098: 
 2099: ###############################################################
 2100: ###############################################################
 2101: sub create_workbook {
 2102:     my ($r) = @_;
 2103:         #
 2104:     # Create the excel spreadsheet
 2105:     my $filename = '/prtspool/'.
 2106:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2107:         time.'_'.rand(1000000000).'.xls';
 2108:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2109:     if (! defined($workbook)) {
 2110:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2111:         $r->print(
 2112:             '<p class="LC_error">'
 2113:            .&mt('Problems occurred in creating the new Excel file.')
 2114:            .' '.&mt('This error has been logged.')
 2115:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2116:            .'</p>'
 2117:         );
 2118:         return (undef);
 2119:     }
 2120:     #
 2121:     $workbook->set_tempdir(LONCAPA::tempdir());
 2122:     #
 2123:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2124:     return ($workbook,$filename,$format);
 2125: }
 2126: 
 2127: ###############################################################
 2128: ###############################################################
 2129: 
 2130: =pod
 2131: 
 2132: =item * &create_text_file()
 2133: 
 2134: Create a file to write to and eventually make available to the user.
 2135: If file creation fails, outputs an error message on the request object and 
 2136: return undefs.
 2137: 
 2138: Inputs: Apache request object, and file suffix
 2139: 
 2140: Returns (undef) on failure, 
 2141:     Filehandle and filename on success.
 2142: 
 2143: =cut
 2144: 
 2145: ###############################################################
 2146: ###############################################################
 2147: sub create_text_file {
 2148:     my ($r,$suffix) = @_;
 2149:     if (! defined($suffix)) { $suffix = 'txt'; };
 2150:     my $fh;
 2151:     my $filename = '/prtspool/'.
 2152:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2153:         time.'_'.rand(1000000000).'.'.$suffix;
 2154:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2155:     if (! defined($fh)) {
 2156:         $r->log_error("Couldn't open $filename for output $!");
 2157:         $r->print(
 2158:             '<p class="LC_error">'
 2159:            .&mt('Problems occurred in creating the output file.')
 2160:            .' '.&mt('This error has been logged.')
 2161:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2162:            .'</p>'
 2163:         );
 2164:     }
 2165:     return ($fh,$filename)
 2166: }
 2167: 
 2168: 
 2169: =pod 
 2170: 
 2171: =back
 2172: 
 2173: =cut
 2174: 
 2175: ###############################################################
 2176: ##        Home server <option> list generating code          ##
 2177: ###############################################################
 2178: 
 2179: # ------------------------------------------
 2180: 
 2181: sub domain_select {
 2182:     my ($name,$value,$multiple)=@_;
 2183:     my %domains=map { 
 2184: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2185:     } &Apache::lonnet::all_domains();
 2186:     if ($multiple) {
 2187: 	$domains{''}=&mt('Any domain');
 2188: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2189: 	return &multiple_select_form($name,$value,4,\%domains);
 2190:     } else {
 2191: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2192: 	return &select_form($name,$value,\%domains);
 2193:     }
 2194: }
 2195: 
 2196: #-------------------------------------------
 2197: 
 2198: =pod
 2199: 
 2200: =head1 Routines for form select boxes
 2201: 
 2202: =over 4
 2203: 
 2204: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2205: 
 2206: Returns a string containing a <select> element int multiple mode
 2207: 
 2208: 
 2209: Args:
 2210:   $name - name of the <select> element
 2211:   $value - scalar or array ref of values that should already be selected
 2212:   $size - number of rows long the select element is
 2213:   $hash - the elements should be 'option' => 'shown text'
 2214:           (shown text should already have been &mt())
 2215:   $order - (optional) array ref of the order to show the elements in
 2216: 
 2217: =cut
 2218: 
 2219: #-------------------------------------------
 2220: sub multiple_select_form {
 2221:     my ($name,$value,$size,$hash,$order)=@_;
 2222:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2223:     my $output='';
 2224:     if (! defined($size)) {
 2225:         $size = 4;
 2226:         if (scalar(keys(%$hash))<4) {
 2227:             $size = scalar(keys(%$hash));
 2228:         }
 2229:     }
 2230:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2231:     my @order;
 2232:     if (ref($order) eq 'ARRAY')  {
 2233:         @order = @{$order};
 2234:     } else {
 2235:         @order = sort(keys(%$hash));
 2236:     }
 2237:     if (exists($$hash{'select_form_order'})) {
 2238:         @order = @{$$hash{'select_form_order'}};
 2239:     }
 2240:         
 2241:     foreach my $key (@order) {
 2242:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2243:         $output.='selected="selected" ' if ($selected{$key});
 2244:         $output.='>'.$hash->{$key}."</option>\n";
 2245:     }
 2246:     $output.="</select>\n";
 2247:     return $output;
 2248: }
 2249: 
 2250: #-------------------------------------------
 2251: 
 2252: =pod
 2253: 
 2254: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2255: 
 2256: Returns a string containing a <select name='$name' size='1'> form to 
 2257: allow a user to select options from a ref to a hash containing:
 2258: option_name => displayed text. An optional $onchange can include
 2259: a javascript onchange item, e.g., onchange="this.form.submit();".
 2260: An optional arg -- $readonly -- if true will cause the select form
 2261: to be disabled, e.g., for the case where an instructor has a section-
 2262: specific role, and is viewing/modifying parameters.  
 2263: 
 2264: See lonrights.pm for an example invocation and use.
 2265: 
 2266: =cut
 2267: 
 2268: #-------------------------------------------
 2269: sub select_form {
 2270:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2271:     return unless (ref($hashref) eq 'HASH');
 2272:     if ($onchange) {
 2273:         $onchange = ' onchange="'.$onchange.'"';
 2274:     }
 2275:     my $disabled;
 2276:     if ($readonly) {
 2277:         $disabled = ' disabled="disabled"';
 2278:     }
 2279:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2280:     my @keys;
 2281:     if (exists($hashref->{'select_form_order'})) {
 2282: 	@keys=@{$hashref->{'select_form_order'}};
 2283:     } else {
 2284: 	@keys=sort(keys(%{$hashref}));
 2285:     }
 2286:     foreach my $key (@keys) {
 2287:         $selectform.=
 2288: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2289:             ($key eq $def ? 'selected="selected" ' : '').
 2290:                 ">".$hashref->{$key}."</option>\n";
 2291:     }
 2292:     $selectform.="</select>";
 2293:     return $selectform;
 2294: }
 2295: 
 2296: # For display filters
 2297: 
 2298: sub display_filter {
 2299:     my ($context) = @_;
 2300:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2301:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2302:     my $phraseinput = 'hidden';
 2303:     my $includeinput = 'hidden';
 2304:     my ($checked,$includetypestext);
 2305:     if ($env{'form.displayfilter'} eq 'containing') {
 2306:         $phraseinput = 'text'; 
 2307:         if ($context eq 'parmslog') {
 2308:             $includeinput = 'checkbox';
 2309:             if ($env{'form.includetypes'}) {
 2310:                 $checked = ' checked="checked"';
 2311:             }
 2312:             $includetypestext = &mt('Include parameter types');
 2313:         }
 2314:     } else {
 2315:         $includetypestext = '&nbsp;';
 2316:     }
 2317:     my ($additional,$secondid,$thirdid);
 2318:     if ($context eq 'parmslog') {
 2319:         $additional = 
 2320:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2321:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2322:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2323:             '</label>';
 2324:         $secondid = 'includetypes';
 2325:         $thirdid = 'includetypestext';
 2326:     }
 2327:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2328:                                                     '$secondid','$thirdid')";
 2329:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2330: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2331: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2332: 	   '</label></span> <span class="LC_nobreak">'.
 2333:            &mt('Filter: [_1]',
 2334: 	   &select_form($env{'form.displayfilter'},
 2335: 			'displayfilter',
 2336: 			{'currentfolder' => 'Current folder/page',
 2337: 			 'containing' => 'Containing phrase',
 2338: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2339: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2340:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2341:                          '" />'.$additional;
 2342: }
 2343: 
 2344: sub display_filter_js {
 2345:     my $includetext = &mt('Include parameter types');
 2346:     return <<"ENDJS";
 2347:   
 2348: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2349:     var firstType = 'hidden';
 2350:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2351:         firstType = 'text';
 2352:     }
 2353:     firstObject = document.getElementById(firstid);
 2354:     if (typeof(firstObject) == 'object') {
 2355:         if (firstObject.type != firstType) {
 2356:             changeInputType(firstObject,firstType);
 2357:         }
 2358:     }
 2359:     if (context == 'parmslog') {
 2360:         var secondType = 'hidden';
 2361:         if (firstType == 'text') {
 2362:             secondType = 'checkbox';
 2363:         }
 2364:         secondObject = document.getElementById(secondid);  
 2365:         if (typeof(secondObject) == 'object') {
 2366:             if (secondObject.type != secondType) {
 2367:                 changeInputType(secondObject,secondType);
 2368:             }
 2369:         }
 2370:         var textItem = document.getElementById(thirdid);
 2371:         var currtext = textItem.innerHTML;
 2372:         var newtext;
 2373:         if (firstType == 'text') {
 2374:             newtext = '$includetext';
 2375:         } else {
 2376:             newtext = '&nbsp;';
 2377:         }
 2378:         if (currtext != newtext) {
 2379:             textItem.innerHTML = newtext;
 2380:         }
 2381:     }
 2382:     return;
 2383: }
 2384: 
 2385: function changeInputType(oldObject,newType) {
 2386:     var newObject = document.createElement('input');
 2387:     newObject.type = newType;
 2388:     if (oldObject.size) {
 2389:         newObject.size = oldObject.size;
 2390:     }
 2391:     if (oldObject.value) {
 2392:         newObject.value = oldObject.value;
 2393:     }
 2394:     if (oldObject.name) {
 2395:         newObject.name = oldObject.name;
 2396:     }
 2397:     if (oldObject.id) {
 2398:         newObject.id = oldObject.id;
 2399:     }
 2400:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2401:     return;
 2402: }
 2403: 
 2404: ENDJS
 2405: }
 2406: 
 2407: sub gradeleveldescription {
 2408:     my $gradelevel=shift;
 2409:     my %gradelevels=(0 => 'Not specified',
 2410: 		     1 => 'Grade 1',
 2411: 		     2 => 'Grade 2',
 2412: 		     3 => 'Grade 3',
 2413: 		     4 => 'Grade 4',
 2414: 		     5 => 'Grade 5',
 2415: 		     6 => 'Grade 6',
 2416: 		     7 => 'Grade 7',
 2417: 		     8 => 'Grade 8',
 2418: 		     9 => 'Grade 9',
 2419: 		     10 => 'Grade 10',
 2420: 		     11 => 'Grade 11',
 2421: 		     12 => 'Grade 12',
 2422: 		     13 => 'Grade 13',
 2423: 		     14 => '100 Level',
 2424: 		     15 => '200 Level',
 2425: 		     16 => '300 Level',
 2426: 		     17 => '400 Level',
 2427: 		     18 => 'Graduate Level');
 2428:     return &mt($gradelevels{$gradelevel});
 2429: }
 2430: 
 2431: sub select_level_form {
 2432:     my ($deflevel,$name)=@_;
 2433:     unless ($deflevel) { $deflevel=0; }
 2434:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2435:     for (my $i=0; $i<=18; $i++) {
 2436:         $selectform.="<option value=\"$i\" ".
 2437:             ($i==$deflevel ? 'selected="selected" ' : '').
 2438:                 ">".&gradeleveldescription($i)."</option>\n";
 2439:     }
 2440:     $selectform.="</select>";
 2441:     return $selectform;
 2442: }
 2443: 
 2444: #-------------------------------------------
 2445: 
 2446: =pod
 2447: 
 2448: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2449: 
 2450: Returns a string containing a <select name='$name' size='1'> form to 
 2451: allow a user to select the domain to preform an operation in.  
 2452: See loncreateuser.pm for an example invocation and use.
 2453: 
 2454: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2455: selected");
 2456: 
 2457: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2458: 
 2459: 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.
 2460: 
 2461: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2462: 
 2463: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2464: 
 2465: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
 2466: 
 2467: =cut
 2468: 
 2469: #-------------------------------------------
 2470: sub select_dom_form {
 2471:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2472:     if ($onchange) {
 2473:         $onchange = ' onchange="'.$onchange.'"';
 2474:     }
 2475:     if ($disabled) {
 2476:         $disabled = ' disabled="disabled"';
 2477:     }
 2478:     my (@domains,%exclude);
 2479:     if (ref($incdoms) eq 'ARRAY') {
 2480:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2481:     } else {
 2482:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2483:     }
 2484:     if ($includeempty) { @domains=('',@domains); }
 2485:     if (ref($excdoms) eq 'ARRAY') {
 2486:         map { $exclude{$_} = 1; } @{$excdoms};
 2487:     }
 2488:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2489:     foreach my $dom (@domains) {
 2490:         next if ($exclude{$dom});
 2491:         $selectdomain.="<option value=\"$dom\" ".
 2492:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2493:         if ($showdomdesc) {
 2494:             if ($dom ne '') {
 2495:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2496:                 if ($domdesc ne '') {
 2497:                     $selectdomain .= ' ('.$domdesc.')';
 2498:                 }
 2499:             } 
 2500:         }
 2501:         $selectdomain .= "</option>\n";
 2502:     }
 2503:     $selectdomain.="</select>";
 2504:     return $selectdomain;
 2505: }
 2506: 
 2507: #-------------------------------------------
 2508: 
 2509: =pod
 2510: 
 2511: =item * &home_server_form_item($domain,$name,$defaultflag)
 2512: 
 2513: input: 4 arguments (two required, two optional) - 
 2514:     $domain - domain of new user
 2515:     $name - name of form element
 2516:     $default - Value of 'default' causes a default item to be first 
 2517:                             option, and selected by default. 
 2518:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2519:                             if 1 server found, or default, if 0 found.
 2520: output: returns 2 items: 
 2521: (a) form element which contains either:
 2522:    (i) <select name="$name">
 2523:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2524:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2525:        </select>
 2526:        form item if there are multiple library servers in $domain, or
 2527:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2528:        if there is only one library server in $domain.
 2529: 
 2530: (b) number of library servers found.
 2531: 
 2532: See loncreateuser.pm for example of use.
 2533: 
 2534: =cut
 2535: 
 2536: #-------------------------------------------
 2537: sub home_server_form_item {
 2538:     my ($domain,$name,$default,$hide) = @_;
 2539:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2540:     my $result;
 2541:     my $numlib = keys(%servers);
 2542:     if ($numlib > 1) {
 2543:         $result .= '<select name="'.$name.'" />'."\n";
 2544:         if ($default) {
 2545:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2546:                        '</option>'."\n";
 2547:         }
 2548:         foreach my $hostid (sort(keys(%servers))) {
 2549:             $result.= '<option value="'.$hostid.'">'.
 2550: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2551:         }
 2552:         $result .= '</select>'."\n";
 2553:     } elsif ($numlib == 1) {
 2554:         my $hostid;
 2555:         foreach my $item (keys(%servers)) {
 2556:             $hostid = $item;
 2557:         }
 2558:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2559:                    $hostid.'" />';
 2560:                    if (!$hide) {
 2561:                        $result .= $hostid.' '.$servers{$hostid};
 2562:                    }
 2563:                    $result .= "\n";
 2564:     } elsif ($default) {
 2565:         $result .= '<input type="hidden" name="'.$name.
 2566:                    '" value="default" />';
 2567:                    if (!$hide) {
 2568:                        $result .= &mt('default');
 2569:                    }
 2570:                    $result .= "\n";
 2571:     }
 2572:     return ($result,$numlib);
 2573: }
 2574: 
 2575: =pod
 2576: 
 2577: =back 
 2578: 
 2579: =cut
 2580: 
 2581: ###############################################################
 2582: ##                  Decoding User Agent                      ##
 2583: ###############################################################
 2584: 
 2585: =pod
 2586: 
 2587: =head1 Decoding the User Agent
 2588: 
 2589: =over 4
 2590: 
 2591: =item * &decode_user_agent()
 2592: 
 2593: Inputs: $r
 2594: 
 2595: Outputs:
 2596: 
 2597: =over 4
 2598: 
 2599: =item * $httpbrowser
 2600: 
 2601: =item * $clientbrowser
 2602: 
 2603: =item * $clientversion
 2604: 
 2605: =item * $clientmathml
 2606: 
 2607: =item * $clientunicode
 2608: 
 2609: =item * $clientos
 2610: 
 2611: =item * $clientmobile
 2612: 
 2613: =item * $clientinfo
 2614: 
 2615: =item * $clientosversion
 2616: 
 2617: =back
 2618: 
 2619: =back 
 2620: 
 2621: =cut
 2622: 
 2623: ###############################################################
 2624: ###############################################################
 2625: sub decode_user_agent {
 2626:     my ($r)=@_;
 2627:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2628:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2629:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2630:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2631:     my $clientbrowser='unknown';
 2632:     my $clientversion='0';
 2633:     my $clientmathml='';
 2634:     my $clientunicode='0';
 2635:     my $clientmobile=0;
 2636:     my $clientosversion='';
 2637:     for (my $i=0;$i<=$#browsertype;$i++) {
 2638:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2639: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2640: 	    $clientbrowser=$bname;
 2641:             $httpbrowser=~/$vreg/i;
 2642: 	    $clientversion=$1;
 2643:             $clientmathml=($clientversion>=$minv);
 2644:             $clientunicode=($clientversion>=$univ);
 2645: 	}
 2646:     }
 2647:     my $clientos='unknown';
 2648:     my $clientinfo;
 2649:     if (($httpbrowser=~/linux/i) ||
 2650:         ($httpbrowser=~/unix/i) ||
 2651:         ($httpbrowser=~/ux/i) ||
 2652:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2653:     if (($httpbrowser=~/vax/i) ||
 2654:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2655:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2656:     if (($httpbrowser=~/mac/i) ||
 2657:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2658:     if ($httpbrowser=~/win/i) {
 2659:         $clientos='win';
 2660:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2661:             $clientosversion = $1;
 2662:         }
 2663:     }
 2664:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2665:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2666:         $clientmobile=lc($1);
 2667:     }
 2668:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2669:         $clientinfo = 'firefox-'.$1;
 2670:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2671:         $clientinfo = 'chromeframe-'.$1;
 2672:     }
 2673:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2674:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2675:             $clientosversion);
 2676: }
 2677: 
 2678: ###############################################################
 2679: ##    Authentication changing form generation subroutines    ##
 2680: ###############################################################
 2681: ##
 2682: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2683: ## hash, and have reasonable default values.
 2684: ##
 2685: ##    formname = the name given in the <form> tag.
 2686: #-------------------------------------------
 2687: 
 2688: =pod
 2689: 
 2690: =head1 Authentication Routines
 2691: 
 2692: =over 4
 2693: 
 2694: =item * &authform_xxxxxx()
 2695: 
 2696: The authform_xxxxxx subroutines provide javascript and html forms which 
 2697: handle some of the conveniences required for authentication forms.  
 2698: This is not an optimal method, but it works.  
 2699: 
 2700: =over 4
 2701: 
 2702: =item * authform_header
 2703: 
 2704: =item * authform_authorwarning
 2705: 
 2706: =item * authform_nochange
 2707: 
 2708: =item * authform_kerberos
 2709: 
 2710: =item * authform_internal
 2711: 
 2712: =item * authform_filesystem
 2713: 
 2714: =back
 2715: 
 2716: See loncreateuser.pm for invocation and use examples.
 2717: 
 2718: =cut
 2719: 
 2720: #-------------------------------------------
 2721: sub authform_header{  
 2722:     my %in = (
 2723:         formname => 'cu',
 2724:         kerb_def_dom => '',
 2725:         @_,
 2726:     );
 2727:     $in{'formname'} = 'document.' . $in{'formname'};
 2728:     my $result='';
 2729: 
 2730: #---------------------------------------------- Code for upper case translation
 2731:     my $Javascript_toUpperCase;
 2732:     unless ($in{kerb_def_dom}) {
 2733:         $Javascript_toUpperCase =<<"END";
 2734:         switch (choice) {
 2735:            case 'krb': currentform.elements[choicearg].value =
 2736:                currentform.elements[choicearg].value.toUpperCase();
 2737:                break;
 2738:            default:
 2739:         }
 2740: END
 2741:     } else {
 2742:         $Javascript_toUpperCase = "";
 2743:     }
 2744: 
 2745:     my $radioval = "'nochange'";
 2746:     if (defined($in{'curr_authtype'})) {
 2747:         if ($in{'curr_authtype'} ne '') {
 2748:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2749:         }
 2750:     }
 2751:     my $argfield = 'null';
 2752:     if (defined($in{'mode'})) {
 2753:         if ($in{'mode'} eq 'modifycourse')  {
 2754:             if (defined($in{'curr_autharg'})) {
 2755:                 if ($in{'curr_autharg'} ne '') {
 2756:                     $argfield = "'$in{'curr_autharg'}'";
 2757:                 }
 2758:             }
 2759:         }
 2760:     }
 2761: 
 2762:     $result.=<<"END";
 2763: var current = new Object();
 2764: current.radiovalue = $radioval;
 2765: current.argfield = $argfield;
 2766: 
 2767: function changed_radio(choice,currentform) {
 2768:     var choicearg = choice + 'arg';
 2769:     // If a radio button in changed, we need to change the argfield
 2770:     if (current.radiovalue != choice) {
 2771:         current.radiovalue = choice;
 2772:         if (current.argfield != null) {
 2773:             currentform.elements[current.argfield].value = '';
 2774:         }
 2775:         if (choice == 'nochange') {
 2776:             current.argfield = null;
 2777:         } else {
 2778:             current.argfield = choicearg;
 2779:             switch(choice) {
 2780:                 case 'krb': 
 2781:                     currentform.elements[current.argfield].value = 
 2782:                         "$in{'kerb_def_dom'}";
 2783:                 break;
 2784:               default:
 2785:                 break;
 2786:             }
 2787:         }
 2788:     }
 2789:     return;
 2790: }
 2791: 
 2792: function changed_text(choice,currentform) {
 2793:     var choicearg = choice + 'arg';
 2794:     if (currentform.elements[choicearg].value !='') {
 2795:         $Javascript_toUpperCase
 2796:         // clear old field
 2797:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2798:             currentform.elements[current.argfield].value = '';
 2799:         }
 2800:         current.argfield = choicearg;
 2801:     }
 2802:     set_auth_radio_buttons(choice,currentform);
 2803:     return;
 2804: }
 2805: 
 2806: function set_auth_radio_buttons(newvalue,currentform) {
 2807:     var numauthchoices = currentform.login.length;
 2808:     if (typeof numauthchoices  == "undefined") {
 2809:         return;
 2810:     } 
 2811:     var i=0;
 2812:     while (i < numauthchoices) {
 2813:         if (currentform.login[i].value == newvalue) { break; }
 2814:         i++;
 2815:     }
 2816:     if (i == numauthchoices) {
 2817:         return;
 2818:     }
 2819:     current.radiovalue = newvalue;
 2820:     currentform.login[i].checked = true;
 2821:     return;
 2822: }
 2823: END
 2824:     return $result;
 2825: }
 2826: 
 2827: sub authform_authorwarning {
 2828:     my $result='';
 2829:     $result='<i>'.
 2830:         &mt('As a general rule, only authors or co-authors should be '.
 2831:             'filesystem authenticated '.
 2832:             '(which allows access to the server filesystem).')."</i>\n";
 2833:     return $result;
 2834: }
 2835: 
 2836: sub authform_nochange {
 2837:     my %in = (
 2838:               formname => 'document.cu',
 2839:               kerb_def_dom => 'MSU.EDU',
 2840:               @_,
 2841:           );
 2842:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2843:     my $result;
 2844:     if (!$authnum) {
 2845:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2846:     } else {
 2847:         $result = '<label>'.&mt('[_1] Do not change login data',
 2848:                   '<input type="radio" name="login" value="nochange" '.
 2849:                   'checked="checked" onclick="'.
 2850:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2851: 	    '</label>';
 2852:     }
 2853:     return $result;
 2854: }
 2855: 
 2856: sub authform_kerberos {
 2857:     my %in = (
 2858:               formname => 'document.cu',
 2859:               kerb_def_dom => 'MSU.EDU',
 2860:               kerb_def_auth => 'krb4',
 2861:               @_,
 2862:               );
 2863:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2864:         $autharg,$jscall,$disabled);
 2865:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2866:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2867:        $check5 = ' checked="checked"';
 2868:     } else {
 2869:        $check4 = ' checked="checked"';
 2870:     }
 2871:     if ($in{'readonly'}) {
 2872:         $disabled = ' disabled="disabled"';
 2873:     }
 2874:     $krbarg = $in{'kerb_def_dom'};
 2875:     if (defined($in{'curr_authtype'})) {
 2876:         if ($in{'curr_authtype'} eq 'krb') {
 2877:             $krbcheck = ' checked="checked"';
 2878:             if (defined($in{'mode'})) {
 2879:                 if ($in{'mode'} eq 'modifyuser') {
 2880:                     $krbcheck = '';
 2881:                 }
 2882:             }
 2883:             if (defined($in{'curr_kerb_ver'})) {
 2884:                 if ($in{'curr_krb_ver'} eq '5') {
 2885:                     $check5 = ' checked="checked"';
 2886:                     $check4 = '';
 2887:                 } else {
 2888:                     $check4 = ' checked="checked"';
 2889:                     $check5 = '';
 2890:                 }
 2891:             }
 2892:             if (defined($in{'curr_autharg'})) {
 2893:                 $krbarg = $in{'curr_autharg'};
 2894:             }
 2895:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2896:                 if (defined($in{'curr_autharg'})) {
 2897:                     $result = 
 2898:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2899:         $in{'curr_autharg'},$krbver);
 2900:                 } else {
 2901:                     $result =
 2902:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2903:                 }
 2904:                 return $result; 
 2905:             }
 2906:         }
 2907:     } else {
 2908:         if ($authnum == 1) {
 2909:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2910:         }
 2911:     }
 2912:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2913:         return;
 2914:     } elsif ($authtype eq '') {
 2915:         if (defined($in{'mode'})) {
 2916:             if ($in{'mode'} eq 'modifycourse') {
 2917:                 if ($authnum == 1) {
 2918:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 2919:                 }
 2920:             }
 2921:         }
 2922:     }
 2923:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2924:     if ($authtype eq '') {
 2925:         $authtype = '<input type="radio" name="login" value="krb" '.
 2926:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2927:                     $krbcheck.$disabled.' />';
 2928:     }
 2929:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2930:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2931:          $in{'curr_authtype'} eq 'krb5') ||
 2932:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2933:          $in{'curr_authtype'} eq 'krb4')) {
 2934:         $result .= &mt
 2935:         ('[_1] Kerberos authenticated with domain [_2] '.
 2936:          '[_3] Version 4 [_4] Version 5 [_5]',
 2937:          '<label>'.$authtype,
 2938:          '</label><input type="text" size="10" name="krbarg" '.
 2939:              'value="'.$krbarg.'" '.
 2940:              'onchange="'.$jscall.'"'.$disabled.' />',
 2941:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 2942:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 2943: 	 '</label>');
 2944:     } elsif ($can_assign{'krb4'}) {
 2945:         $result .= &mt
 2946:         ('[_1] Kerberos authenticated with domain [_2] '.
 2947:          '[_3] Version 4 [_4]',
 2948:          '<label>'.$authtype,
 2949:          '</label><input type="text" size="10" name="krbarg" '.
 2950:              'value="'.$krbarg.'" '.
 2951:              'onchange="'.$jscall.'"'.$disabled.' />',
 2952:          '<label><input type="hidden" name="krbver" value="4" />',
 2953:          '</label>');
 2954:     } elsif ($can_assign{'krb5'}) {
 2955:         $result .= &mt
 2956:         ('[_1] Kerberos authenticated with domain [_2] '.
 2957:          '[_3] Version 5 [_4]',
 2958:          '<label>'.$authtype,
 2959:          '</label><input type="text" size="10" name="krbarg" '.
 2960:              'value="'.$krbarg.'" '.
 2961:              'onchange="'.$jscall.'"'.$disabled.' />',
 2962:          '<label><input type="hidden" name="krbver" value="5" />',
 2963:          '</label>');
 2964:     }
 2965:     return $result;
 2966: }
 2967: 
 2968: sub authform_internal {
 2969:     my %in = (
 2970:                 formname => 'document.cu',
 2971:                 kerb_def_dom => 'MSU.EDU',
 2972:                 @_,
 2973:                 );
 2974:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 2975:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2976:     if ($in{'readonly'}) {
 2977:         $disabled = ' disabled="disabled"';
 2978:     }
 2979:     if (defined($in{'curr_authtype'})) {
 2980:         if ($in{'curr_authtype'} eq 'int') {
 2981:             if ($can_assign{'int'}) {
 2982:                 $intcheck = 'checked="checked" ';
 2983:                 if (defined($in{'mode'})) {
 2984:                     if ($in{'mode'} eq 'modifyuser') {
 2985:                         $intcheck = '';
 2986:                     }
 2987:                 }
 2988:                 if (defined($in{'curr_autharg'})) {
 2989:                     $intarg = $in{'curr_autharg'};
 2990:                 }
 2991:             } else {
 2992:                 $result = &mt('Currently internally authenticated.');
 2993:                 return $result;
 2994:             }
 2995:         }
 2996:     } else {
 2997:         if ($authnum == 1) {
 2998:             $authtype = '<input type="hidden" name="login" value="int" />';
 2999:         }
 3000:     }
 3001:     if (!$can_assign{'int'}) {
 3002:         return;
 3003:     } elsif ($authtype eq '') {
 3004:         if (defined($in{'mode'})) {
 3005:             if ($in{'mode'} eq 'modifycourse') {
 3006:                 if ($authnum == 1) {
 3007:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3008:                 }
 3009:             }
 3010:         }
 3011:     }
 3012:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3013:     if ($authtype eq '') {
 3014:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3015:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3016:     }
 3017:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3018:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3019:     $result = &mt
 3020:         ('[_1] Internally authenticated (with initial password [_2])',
 3021:          '<label>'.$authtype,'</label>'.$autharg);
 3022:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
 3023:     return $result;
 3024: }
 3025: 
 3026: sub authform_local {
 3027:     my %in = (
 3028:               formname => 'document.cu',
 3029:               kerb_def_dom => 'MSU.EDU',
 3030:               @_,
 3031:               );
 3032:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3033:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3034:     if ($in{'readonly'}) {
 3035:         $disabled = ' disabled="disabled"';
 3036:     }
 3037:     if (defined($in{'curr_authtype'})) {
 3038:         if ($in{'curr_authtype'} eq 'loc') {
 3039:             if ($can_assign{'loc'}) {
 3040:                 $loccheck = 'checked="checked" ';
 3041:                 if (defined($in{'mode'})) {
 3042:                     if ($in{'mode'} eq 'modifyuser') {
 3043:                         $loccheck = '';
 3044:                     }
 3045:                 }
 3046:                 if (defined($in{'curr_autharg'})) {
 3047:                     $locarg = $in{'curr_autharg'};
 3048:                 }
 3049:             } else {
 3050:                 $result = &mt('Currently using local (institutional) authentication.');
 3051:                 return $result;
 3052:             }
 3053:         }
 3054:     } else {
 3055:         if ($authnum == 1) {
 3056:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3057:         }
 3058:     }
 3059:     if (!$can_assign{'loc'}) {
 3060:         return;
 3061:     } elsif ($authtype eq '') {
 3062:         if (defined($in{'mode'})) {
 3063:             if ($in{'mode'} eq 'modifycourse') {
 3064:                 if ($authnum == 1) {
 3065:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3066:                 }
 3067:             }
 3068:         }
 3069:     }
 3070:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3071:     if ($authtype eq '') {
 3072:         $authtype = '<input type="radio" name="login" value="loc" '.
 3073:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3074:                     $jscall.'"'.$disabled.' />';
 3075:     }
 3076:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3077:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3078:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3079:                   '<label>'.$authtype,'</label>'.$autharg);
 3080:     return $result;
 3081: }
 3082: 
 3083: sub authform_filesystem {
 3084:     my %in = (
 3085:               formname => 'document.cu',
 3086:               kerb_def_dom => 'MSU.EDU',
 3087:               @_,
 3088:               );
 3089:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3090:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3091:     if ($in{'readonly'}) {
 3092:         $disabled = ' disabled="disabled"';
 3093:     }
 3094:     if (defined($in{'curr_authtype'})) {
 3095:         if ($in{'curr_authtype'} eq 'fsys') {
 3096:             if ($can_assign{'fsys'}) {
 3097:                 $fsyscheck = 'checked="checked" ';
 3098:                 if (defined($in{'mode'})) {
 3099:                     if ($in{'mode'} eq 'modifyuser') {
 3100:                         $fsyscheck = '';
 3101:                     }
 3102:                 }
 3103:             } else {
 3104:                 $result = &mt('Currently Filesystem Authenticated.');
 3105:                 return $result;
 3106:             }           
 3107:         }
 3108:     } else {
 3109:         if ($authnum == 1) {
 3110:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3111:         }
 3112:     }
 3113:     if (!$can_assign{'fsys'}) {
 3114:         return;
 3115:     } elsif ($authtype eq '') {
 3116:         if (defined($in{'mode'})) {
 3117:             if ($in{'mode'} eq 'modifycourse') {
 3118:                 if ($authnum == 1) {
 3119:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3120:                 }
 3121:             }
 3122:         }
 3123:     }
 3124:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3125:     if ($authtype eq '') {
 3126:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3127:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3128:                     $jscall.'"'.$disabled.' />';
 3129:     }
 3130:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3131:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3132:     $result = &mt
 3133:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3134:          '<label>'.$authtype,'</label>'.$autharg);
 3135:     return $result;
 3136: }
 3137: 
 3138: sub get_assignable_auth {
 3139:     my ($dom) = @_;
 3140:     if ($dom eq '') {
 3141:         $dom = $env{'request.role.domain'};
 3142:     }
 3143:     my %can_assign = (
 3144:                           krb4 => 1,
 3145:                           krb5 => 1,
 3146:                           int  => 1,
 3147:                           loc  => 1,
 3148:                      );
 3149:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3150:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3151:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3152:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3153:             my $context;
 3154:             if ($env{'request.role'} =~ /^au/) {
 3155:                 $context = 'author';
 3156:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3157:                 $context = 'domain';
 3158:             } elsif ($env{'request.course.id'}) {
 3159:                 $context = 'course';
 3160:             }
 3161:             if ($context) {
 3162:                 if (ref($authhash->{$context}) eq 'HASH') {
 3163:                    %can_assign = %{$authhash->{$context}}; 
 3164:                 }
 3165:             }
 3166:         }
 3167:     }
 3168:     my $authnum = 0;
 3169:     foreach my $key (keys(%can_assign)) {
 3170:         if ($can_assign{$key}) {
 3171:             $authnum ++;
 3172:         }
 3173:     }
 3174:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3175:         $authnum --;
 3176:     }
 3177:     return ($authnum,%can_assign);
 3178: }
 3179: 
 3180: sub check_passwd_rules {
 3181:     my ($domain,$plainpass) = @_;
 3182:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3183:     my ($min,$max,@chars,@brokerule,$warning);
 3184:     $min = $Apache::lonnet::passwdmin;
 3185:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3186:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3187:             if ($passwdconf{'min'} > $min) {
 3188:                 $min = $passwdconf{'min'};
 3189:             }
 3190:         }
 3191:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3192:             $max = $passwdconf{'max'};
 3193:         }
 3194:         @chars = @{$passwdconf{'chars'}};
 3195:     }
 3196:     if (($min) && (length($plainpass) < $min)) {
 3197:         push(@brokerule,'min');
 3198:     }
 3199:     if (($max) && (length($plainpass) > $max)) {
 3200:         push(@brokerule,'max');
 3201:     }
 3202:     if (@chars) {
 3203:         my %rules;
 3204:         map { $rules{$_} = 1; } @chars;
 3205:         if ($rules{'uc'}) {
 3206:             unless ($plainpass =~ /[A-Z]/) {
 3207:                 push(@brokerule,'uc');
 3208:             }
 3209:         }
 3210:         if ($rules{'lc'}) {
 3211:             unless ($plainpass =~ /[a-z]/) {
 3212:                 push(@brokerule,'lc');
 3213:             }
 3214:         }
 3215:         if ($rules{'num'}) {
 3216:             unless ($plainpass =~ /\d/) {
 3217:                 push(@brokerule,'num');
 3218:             }
 3219:         }
 3220:         if ($rules{'spec'}) {
 3221:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3222:                 push(@brokerule,'spec');
 3223:             }
 3224:         }
 3225:     }
 3226:     if (@brokerule) {
 3227:         my %rulenames = &Apache::lonlocal::texthash(
 3228:             uc   => 'At least one upper case letter',
 3229:             lc   => 'At least one lower case letter',
 3230:             num  => 'At least one number',
 3231:             spec => 'At least one non-alphanumeric',
 3232:         );
 3233:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3234:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3235:         $rulenames{'num'} .= ': 0123456789';
 3236:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3237:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3238:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3239:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3240:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3241:             if (grep(/^$rule$/,@brokerule)) {
 3242:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3243:             }
 3244:         }
 3245:         $warning .= '</ul>';
 3246:     }
 3247:     if (wantarray) {
 3248:         return @brokerule;
 3249:     }
 3250:     return $warning;
 3251: }
 3252: 
 3253: ###############################################################
 3254: ##    Get Kerberos Defaults for Domain                 ##
 3255: ###############################################################
 3256: ##
 3257: ## Returns default kerberos version and an associated argument
 3258: ## as listed in file domain.tab. If not listed, provides
 3259: ## appropriate default domain and kerberos version.
 3260: ##
 3261: #-------------------------------------------
 3262: 
 3263: =pod
 3264: 
 3265: =item * &get_kerberos_defaults()
 3266: 
 3267: get_kerberos_defaults($target_domain) returns the default kerberos
 3268: version and domain. If not found, it defaults to version 4 and the 
 3269: domain of the server.
 3270: 
 3271: =over 4
 3272: 
 3273: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3274: 
 3275: =back
 3276: 
 3277: =back
 3278: 
 3279: =cut
 3280: 
 3281: #-------------------------------------------
 3282: sub get_kerberos_defaults {
 3283:     my $domain=shift;
 3284:     my ($krbdef,$krbdefdom);
 3285:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3286:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3287:         $krbdef = $domdefaults{'auth_def'};
 3288:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3289:     } else {
 3290:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3291:         my $krbdefdom=$1;
 3292:         $krbdefdom=~tr/a-z/A-Z/;
 3293:         $krbdef = "krb4";
 3294:     }
 3295:     return ($krbdef,$krbdefdom);
 3296: }
 3297: 
 3298: 
 3299: ###############################################################
 3300: ##                Thesaurus Functions                        ##
 3301: ###############################################################
 3302: 
 3303: =pod
 3304: 
 3305: =head1 Thesaurus Functions
 3306: 
 3307: =over 4
 3308: 
 3309: =item * &initialize_keywords()
 3310: 
 3311: Initializes the package variable %Keywords if it is empty.  Uses the
 3312: package variable $thesaurus_db_file.
 3313: 
 3314: =cut
 3315: 
 3316: ###################################################
 3317: 
 3318: sub initialize_keywords {
 3319:     return 1 if (scalar keys(%Keywords));
 3320:     # If we are here, %Keywords is empty, so fill it up
 3321:     #   Make sure the file we need exists...
 3322:     if (! -e $thesaurus_db_file) {
 3323:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3324:                                  " failed because it does not exist");
 3325:         return 0;
 3326:     }
 3327:     #   Set up the hash as a database
 3328:     my %thesaurus_db;
 3329:     if (! tie(%thesaurus_db,'GDBM_File',
 3330:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3331:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3332:                                  $thesaurus_db_file);
 3333:         return 0;
 3334:     } 
 3335:     #  Get the average number of appearances of a word.
 3336:     my $avecount = $thesaurus_db{'average.count'};
 3337:     #  Put keywords (those that appear > average) into %Keywords
 3338:     while (my ($word,$data)=each (%thesaurus_db)) {
 3339:         my ($count,undef) = split /:/,$data;
 3340:         $Keywords{$word}++ if ($count > $avecount);
 3341:     }
 3342:     untie %thesaurus_db;
 3343:     # Remove special values from %Keywords.
 3344:     foreach my $value ('total.count','average.count') {
 3345:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3346:   }
 3347:     return 1;
 3348: }
 3349: 
 3350: ###################################################
 3351: 
 3352: =pod
 3353: 
 3354: =item * &keyword($word)
 3355: 
 3356: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3357: than the average number of times in the thesaurus database.  Calls 
 3358: &initialize_keywords
 3359: 
 3360: =cut
 3361: 
 3362: ###################################################
 3363: 
 3364: sub keyword {
 3365:     return if (!&initialize_keywords());
 3366:     my $word=lc(shift());
 3367:     $word=~s/\W//g;
 3368:     return exists($Keywords{$word});
 3369: }
 3370: 
 3371: ###############################################################
 3372: 
 3373: =pod 
 3374: 
 3375: =item * &get_related_words()
 3376: 
 3377: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3378: an array of words.  If the keyword is not in the thesaurus, an empty array
 3379: will be returned.  The order of the words returned is determined by the
 3380: database which holds them.
 3381: 
 3382: Uses global $thesaurus_db_file.
 3383: 
 3384: 
 3385: =cut
 3386: 
 3387: ###############################################################
 3388: sub get_related_words {
 3389:     my $keyword = shift;
 3390:     my %thesaurus_db;
 3391:     if (! -e $thesaurus_db_file) {
 3392:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3393:                                  "failed because the file does not exist");
 3394:         return ();
 3395:     }
 3396:     if (! tie(%thesaurus_db,'GDBM_File',
 3397:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3398:         return ();
 3399:     } 
 3400:     my @Words=();
 3401:     my $count=0;
 3402:     if (exists($thesaurus_db{$keyword})) {
 3403: 	# The first element is the number of times
 3404: 	# the word appears.  We do not need it now.
 3405: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3406: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3407: 	my $threshold=$mostfrequentcount/10;
 3408:         foreach my $possibleword (@RelatedWords) {
 3409:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3410:             if ($wordcount>$threshold) {
 3411: 		push(@Words,$word);
 3412:                 $count++;
 3413:                 if ($count>10) { last; }
 3414: 	    }
 3415:         }
 3416:     }
 3417:     untie %thesaurus_db;
 3418:     return @Words;
 3419: }
 3420: 
 3421: =pod
 3422: 
 3423: =back
 3424: 
 3425: =cut
 3426: 
 3427: # -------------------------------------------------------------- Plaintext name
 3428: =pod
 3429: 
 3430: =head1 User Name Functions
 3431: 
 3432: =over 4
 3433: 
 3434: =item * &plainname($uname,$udom,$first)
 3435: 
 3436: Takes a users logon name and returns it as a string in
 3437: "first middle last generation" form 
 3438: if $first is set to 'lastname' then it returns it as
 3439: 'lastname generation, firstname middlename' if their is a lastname
 3440: 
 3441: =cut
 3442: 
 3443: 
 3444: ###############################################################
 3445: sub plainname {
 3446:     my ($uname,$udom,$first)=@_;
 3447:     return if (!defined($uname) || !defined($udom));
 3448:     my %names=&getnames($uname,$udom);
 3449:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3450: 					  $names{'middlename'},
 3451: 					  $names{'lastname'},
 3452: 					  $names{'generation'},$first);
 3453:     $name=~s/^\s+//;
 3454:     $name=~s/\s+$//;
 3455:     $name=~s/\s+/ /g;
 3456:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3457:     return $name;
 3458: }
 3459: 
 3460: # -------------------------------------------------------------------- Nickname
 3461: =pod
 3462: 
 3463: =item * &nickname($uname,$udom)
 3464: 
 3465: Gets a users name and returns it as a string as
 3466: 
 3467: "&quot;nickname&quot;"
 3468: 
 3469: if the user has a nickname or
 3470: 
 3471: "first middle last generation"
 3472: 
 3473: if the user does not
 3474: 
 3475: =cut
 3476: 
 3477: sub nickname {
 3478:     my ($uname,$udom)=@_;
 3479:     return if (!defined($uname) || !defined($udom));
 3480:     my %names=&getnames($uname,$udom);
 3481:     my $name=$names{'nickname'};
 3482:     if ($name) {
 3483:        $name='&quot;'.$name.'&quot;'; 
 3484:     } else {
 3485:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3486: 	     $names{'lastname'}.' '.$names{'generation'};
 3487:        $name=~s/\s+$//;
 3488:        $name=~s/\s+/ /g;
 3489:     }
 3490:     return $name;
 3491: }
 3492: 
 3493: sub getnames {
 3494:     my ($uname,$udom)=@_;
 3495:     return if (!defined($uname) || !defined($udom));
 3496:     if ($udom eq 'public' && $uname eq 'public') {
 3497: 	return ('lastname' => &mt('Public'));
 3498:     }
 3499:     my $id=$uname.':'.$udom;
 3500:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3501:     if ($cached) {
 3502: 	return %{$names};
 3503:     } else {
 3504: 	my %loadnames=&Apache::lonnet::get('environment',
 3505:                     ['firstname','middlename','lastname','generation','nickname'],
 3506: 					 $udom,$uname);
 3507: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3508: 	return %loadnames;
 3509:     }
 3510: }
 3511: 
 3512: # -------------------------------------------------------------------- getemails
 3513: 
 3514: =pod
 3515: 
 3516: =item * &getemails($uname,$udom)
 3517: 
 3518: Gets a user's email information and returns it as a hash with keys:
 3519: notification, critnotification, permanentemail
 3520: 
 3521: For notification and critnotification, values are comma-separated lists 
 3522: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3523:  
 3524: 
 3525: =cut
 3526: 
 3527: 
 3528: sub getemails {
 3529:     my ($uname,$udom)=@_;
 3530:     if ($udom eq 'public' && $uname eq 'public') {
 3531: 	return;
 3532:     }
 3533:     if (!$udom) { $udom=$env{'user.domain'}; }
 3534:     if (!$uname) { $uname=$env{'user.name'}; }
 3535:     my $id=$uname.':'.$udom;
 3536:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3537:     if ($cached) {
 3538: 	return %{$names};
 3539:     } else {
 3540: 	my %loadnames=&Apache::lonnet::get('environment',
 3541:                     			   ['notification','critnotification',
 3542: 					    'permanentemail'],
 3543: 					   $udom,$uname);
 3544: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3545: 	return %loadnames;
 3546:     }
 3547: }
 3548: 
 3549: sub flush_email_cache {
 3550:     my ($uname,$udom)=@_;
 3551:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3552:     if (!$uname) { $uname=$env{'user.name'};   }
 3553:     return if ($udom eq 'public' && $uname eq 'public');
 3554:     my $id=$uname.':'.$udom;
 3555:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3556: }
 3557: 
 3558: # -------------------------------------------------------------------- getlangs
 3559: 
 3560: =pod
 3561: 
 3562: =item * &getlangs($uname,$udom)
 3563: 
 3564: Gets a user's language preference and returns it as a hash with key:
 3565: language.
 3566: 
 3567: =cut
 3568: 
 3569: 
 3570: sub getlangs {
 3571:     my ($uname,$udom) = @_;
 3572:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3573:     if (!$uname) { $uname=$env{'user.name'};   }
 3574:     my $id=$uname.':'.$udom;
 3575:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3576:     if ($cached) {
 3577:         return %{$langs};
 3578:     } else {
 3579:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3580:                                            $udom,$uname);
 3581:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3582:         return %loadlangs;
 3583:     }
 3584: }
 3585: 
 3586: sub flush_langs_cache {
 3587:     my ($uname,$udom)=@_;
 3588:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3589:     if (!$uname) { $uname=$env{'user.name'};   }
 3590:     return if ($udom eq 'public' && $uname eq 'public');
 3591:     my $id=$uname.':'.$udom;
 3592:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3593: }
 3594: 
 3595: # ------------------------------------------------------------------ Screenname
 3596: 
 3597: =pod
 3598: 
 3599: =item * &screenname($uname,$udom)
 3600: 
 3601: Gets a users screenname and returns it as a string
 3602: 
 3603: =cut
 3604: 
 3605: sub screenname {
 3606:     my ($uname,$udom)=@_;
 3607:     if ($uname eq $env{'user.name'} &&
 3608: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3609:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3610:     return $names{'screenname'};
 3611: }
 3612: 
 3613: 
 3614: # ------------------------------------------------------------- Confirm Wrapper
 3615: =pod
 3616: 
 3617: =item * &confirmwrapper($message)
 3618: 
 3619: Wrap messages about completion of operation in box
 3620: 
 3621: =cut
 3622: 
 3623: sub confirmwrapper {
 3624:     my ($message)=@_;
 3625:     if ($message) {
 3626:         return "\n".'<div class="LC_confirm_box">'."\n"
 3627:                .$message."\n"
 3628:                .'</div>'."\n";
 3629:     } else {
 3630:         return $message;
 3631:     }
 3632: }
 3633: 
 3634: # ------------------------------------------------------------- Message Wrapper
 3635: 
 3636: sub messagewrapper {
 3637:     my ($link,$username,$domain,$subject,$text)=@_;
 3638:     return 
 3639:         '<a href="/adm/email?compose=individual&amp;'.
 3640:         'recname='.$username.'&amp;recdom='.$domain.
 3641: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3642:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3643: }
 3644: 
 3645: # --------------------------------------------------------------- Notes Wrapper
 3646: 
 3647: sub noteswrapper {
 3648:     my ($link,$un,$do)=@_;
 3649:     return 
 3650: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3651: }
 3652: 
 3653: # ------------------------------------------------------------- Aboutme Wrapper
 3654: 
 3655: sub aboutmewrapper {
 3656:     my ($link,$username,$domain,$target,$class)=@_;
 3657:     if (!defined($username)  && !defined($domain)) {
 3658:         return;
 3659:     }
 3660:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3661: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3662: }
 3663: 
 3664: # ------------------------------------------------------------ Syllabus Wrapper
 3665: 
 3666: sub syllabuswrapper {
 3667:     my ($linktext,$coursedir,$domain)=@_;
 3668:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3669: }
 3670: 
 3671: # -----------------------------------------------------------------------------
 3672: 
 3673: sub track_student_link {
 3674:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3675:     my $link ="/adm/trackstudent?";
 3676:     my $title = 'View recent activity';
 3677:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3678:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3679:         $link .= "selected_student=$sname:$sdom";
 3680:         $title .= ' of this student';
 3681:     } 
 3682:     if (defined($target) && $target !~ /^\s*$/) {
 3683:         $target = qq{target="$target"};
 3684:     } else {
 3685:         $target = '';
 3686:     }
 3687:     if ($start) { $link.='&amp;start='.$start; }
 3688:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3689:     $title = &mt($title);
 3690:     $linktext = &mt($linktext);
 3691:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3692: 	&help_open_topic('View_recent_activity');
 3693: }
 3694: 
 3695: sub slot_reservations_link {
 3696:     my ($linktext,$sname,$sdom,$target) = @_;
 3697:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3698:     my $title = 'View slot reservation history';
 3699:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3700:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3701:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3702:         $title .= ' of this student';
 3703:     }
 3704:     if (defined($target) && $target !~ /^\s*$/) {
 3705:         $target = qq{target="$target"};
 3706:     } else {
 3707:         $target = '';
 3708:     }
 3709:     $title = &mt($title);
 3710:     $linktext = &mt($linktext);
 3711:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3712: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3713: 
 3714: }
 3715: 
 3716: # ===================================================== Display a student photo
 3717: 
 3718: 
 3719: sub student_image_tag {
 3720:     my ($domain,$user)=@_;
 3721:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3722:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3723: 	return '<img src="'.$imgsrc.'" align="right" />';
 3724:     } else {
 3725: 	return '';
 3726:     }
 3727: }
 3728: 
 3729: =pod
 3730: 
 3731: =back
 3732: 
 3733: =head1 Access .tab File Data
 3734: 
 3735: =over 4
 3736: 
 3737: =item * &languageids() 
 3738: 
 3739: returns list of all language ids
 3740: 
 3741: =cut
 3742: 
 3743: sub languageids {
 3744:     return sort(keys(%language));
 3745: }
 3746: 
 3747: =pod
 3748: 
 3749: =item * &languagedescription() 
 3750: 
 3751: returns description of a specified language id
 3752: 
 3753: =cut
 3754: 
 3755: sub languagedescription {
 3756:     my $code=shift;
 3757:     return  ($supported_language{$code}?'* ':'').
 3758:             $language{$code}.
 3759: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3760: }
 3761: 
 3762: =pod
 3763: 
 3764: =item * &plainlanguagedescription
 3765: 
 3766: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3767: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3768: 
 3769: =cut
 3770: 
 3771: sub plainlanguagedescription {
 3772:     my $code=shift;
 3773:     return $language{$code};
 3774: }
 3775: 
 3776: =pod
 3777: 
 3778: =item * &supportedlanguagecode
 3779: 
 3780: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3781: code.
 3782: 
 3783: =cut
 3784: 
 3785: sub supportedlanguagecode {
 3786:     my $code=shift;
 3787:     return $supported_language{$code};
 3788: }
 3789: 
 3790: =pod
 3791: 
 3792: =item * &latexlanguage()
 3793: 
 3794: Given a language key code returns the correspondnig language to use
 3795: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3796: is no supported hyphenation for the language code.
 3797: 
 3798: =cut
 3799: 
 3800: sub latexlanguage {
 3801:     my $code = shift;
 3802:     return $latex_language{$code};
 3803: }
 3804: 
 3805: =pod
 3806: 
 3807: =item * &latexhyphenation()
 3808: 
 3809: Same as above but what's supplied is the language as it might be stored
 3810: in the metadata.
 3811: 
 3812: =cut
 3813: 
 3814: sub latexhyphenation {
 3815:     my $key = shift;
 3816:     return $latex_language_bykey{$key};
 3817: }
 3818: 
 3819: =pod
 3820: 
 3821: =item * &copyrightids() 
 3822: 
 3823: returns list of all copyrights
 3824: 
 3825: =cut
 3826: 
 3827: sub copyrightids {
 3828:     return sort(keys(%cprtag));
 3829: }
 3830: 
 3831: =pod
 3832: 
 3833: =item * &copyrightdescription() 
 3834: 
 3835: returns description of a specified copyright id
 3836: 
 3837: =cut
 3838: 
 3839: sub copyrightdescription {
 3840:     return &mt($cprtag{shift(@_)});
 3841: }
 3842: 
 3843: =pod
 3844: 
 3845: =item * &source_copyrightids() 
 3846: 
 3847: returns list of all source copyrights
 3848: 
 3849: =cut
 3850: 
 3851: sub source_copyrightids {
 3852:     return sort(keys(%scprtag));
 3853: }
 3854: 
 3855: =pod
 3856: 
 3857: =item * &source_copyrightdescription() 
 3858: 
 3859: returns description of a specified source copyright id
 3860: 
 3861: =cut
 3862: 
 3863: sub source_copyrightdescription {
 3864:     return &mt($scprtag{shift(@_)});
 3865: }
 3866: 
 3867: =pod
 3868: 
 3869: =item * &filecategories() 
 3870: 
 3871: returns list of all file categories
 3872: 
 3873: =cut
 3874: 
 3875: sub filecategories {
 3876:     return sort(keys(%category_extensions));
 3877: }
 3878: 
 3879: =pod
 3880: 
 3881: =item * &filecategorytypes() 
 3882: 
 3883: returns list of file types belonging to a given file
 3884: category
 3885: 
 3886: =cut
 3887: 
 3888: sub filecategorytypes {
 3889:     my ($cat) = @_;
 3890:     return @{$category_extensions{lc($cat)}};
 3891: }
 3892: 
 3893: =pod
 3894: 
 3895: =item * &fileembstyle() 
 3896: 
 3897: returns embedding style for a specified file type
 3898: 
 3899: =cut
 3900: 
 3901: sub fileembstyle {
 3902:     return $fe{lc(shift(@_))};
 3903: }
 3904: 
 3905: sub filemimetype {
 3906:     return $fm{lc(shift(@_))};
 3907: }
 3908: 
 3909: 
 3910: sub filecategoryselect {
 3911:     my ($name,$value)=@_;
 3912:     return &select_form($value,$name,
 3913:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3914: }
 3915: 
 3916: =pod
 3917: 
 3918: =item * &filedescription() 
 3919: 
 3920: returns description for a specified file type
 3921: 
 3922: =cut
 3923: 
 3924: sub filedescription {
 3925:     my $file_description = $fd{lc(shift())};
 3926:     $file_description =~ s:([\[\]]):~$1:g;
 3927:     return &mt($file_description);
 3928: }
 3929: 
 3930: =pod
 3931: 
 3932: =item * &filedescriptionex() 
 3933: 
 3934: returns description for a specified file type with
 3935: extra formatting
 3936: 
 3937: =cut
 3938: 
 3939: sub filedescriptionex {
 3940:     my $ex=shift;
 3941:     my $file_description = $fd{lc($ex)};
 3942:     $file_description =~ s:([\[\]]):~$1:g;
 3943:     return '.'.$ex.' '.&mt($file_description);
 3944: }
 3945: 
 3946: # End of .tab access
 3947: =pod
 3948: 
 3949: =back
 3950: 
 3951: =cut
 3952: 
 3953: # ------------------------------------------------------------------ File Types
 3954: sub fileextensions {
 3955:     return sort(keys(%fe));
 3956: }
 3957: 
 3958: # ----------------------------------------------------------- Display Languages
 3959: # returns a hash with all desired display languages
 3960: #
 3961: 
 3962: sub display_languages {
 3963:     my %languages=();
 3964:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3965: 	$languages{$lang}=1;
 3966:     }
 3967:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3968:     if ($env{'form.displaylanguage'}) {
 3969: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3970: 	    $languages{$lang}=1;
 3971:         }
 3972:     }
 3973:     return %languages;
 3974: }
 3975: 
 3976: sub languages {
 3977:     my ($possible_langs) = @_;
 3978:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3979:     if (!ref($possible_langs)) {
 3980: 	if( wantarray ) {
 3981: 	    return @preferred_langs;
 3982: 	} else {
 3983: 	    return $preferred_langs[0];
 3984: 	}
 3985:     }
 3986:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3987:     my @preferred_possibilities;
 3988:     foreach my $preferred_lang (@preferred_langs) {
 3989: 	if (exists($possibilities{$preferred_lang})) {
 3990: 	    push(@preferred_possibilities, $preferred_lang);
 3991: 	}
 3992:     }
 3993:     if( wantarray ) {
 3994: 	return @preferred_possibilities;
 3995:     }
 3996:     return $preferred_possibilities[0];
 3997: }
 3998: 
 3999: sub user_lang {
 4000:     my ($touname,$toudom,$fromcid) = @_;
 4001:     my @userlangs;
 4002:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4003:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4004:                     $env{'course.'.$fromcid.'.languages'}));
 4005:     } else {
 4006:         my %langhash = &getlangs($touname,$toudom);
 4007:         if ($langhash{'languages'} ne '') {
 4008:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4009:         } else {
 4010:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4011:             if ($domdefs{'lang_def'} ne '') {
 4012:                 @userlangs = ($domdefs{'lang_def'});
 4013:             }
 4014:         }
 4015:     }
 4016:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4017:     my $user_lh = Apache::localize->get_handle(@languages);
 4018:     return $user_lh;
 4019: }
 4020: 
 4021: 
 4022: ###############################################################
 4023: ##               Student Answer Attempts                     ##
 4024: ###############################################################
 4025: 
 4026: =pod
 4027: 
 4028: =head1 Alternate Problem Views
 4029: 
 4030: =over 4
 4031: 
 4032: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4033:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4034: 
 4035: Return string with previous attempt on problem. Arguments:
 4036: 
 4037: =over 4
 4038: 
 4039: =item * $symb: Problem, including path
 4040: 
 4041: =item * $username: username of the desired student
 4042: 
 4043: =item * $domain: domain of the desired student
 4044: 
 4045: =item * $course: Course ID
 4046: 
 4047: =item * $getattempt: Leave blank for all attempts, otherwise put
 4048:     something
 4049: 
 4050: =item * $regexp: if string matches this regexp, the string will be
 4051:     sent to $gradesub
 4052: 
 4053: =item * $gradesub: routine that processes the string if it matches $regexp
 4054: 
 4055: =item * $usec: section of the desired student
 4056: 
 4057: =item * $identifier: counter for student (multiple students one problem) or
 4058:     problem (one student; whole sequence).
 4059: 
 4060: =back
 4061: 
 4062: The output string is a table containing all desired attempts, if any.
 4063: 
 4064: =cut
 4065: 
 4066: sub get_previous_attempt {
 4067:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4068:   my $prevattempts='';
 4069:   no strict 'refs';
 4070:   if ($symb) {
 4071:     my (%returnhash)=
 4072:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4073:     if ($returnhash{'version'}) {
 4074:       my %lasthash=();
 4075:       my $version;
 4076:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4077:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4078:             if ($key =~ /\.rawrndseed$/) {
 4079:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4080:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4081:             } else {
 4082:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4083:             }
 4084:         }
 4085:       }
 4086:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4087:       $prevattempts.='<th>'.&mt('History').'</th>';
 4088:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4089:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4090:       foreach my $key (sort(keys(%lasthash))) {
 4091: 	my ($ign,@parts) = split(/\./,$key);
 4092: 	if ($#parts > 0) {
 4093: 	  my $data=$parts[-1];
 4094:           next if ($data eq 'foilorder');
 4095: 	  pop(@parts);
 4096:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4097:           if ($data eq 'type') {
 4098:               unless ($showsurv) {
 4099:                   my $id = join(',',@parts);
 4100:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4101:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4102:                       $lasthidden{$ign.'.'.$id} = 1;
 4103:                   }
 4104:               }
 4105:               if ($identifier ne '') {
 4106:                   my $id = join(',',@parts);
 4107:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4108:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4109:                       $hidestatus{$ign.'.'.$id} = 1;
 4110:                   }
 4111:               }
 4112:           } elsif ($data eq 'regrader') {
 4113:               if (($identifier ne '') && (@parts)) {
 4114:                   my $id = join(',',@parts);
 4115:                   $regraded{$ign.'.'.$id} = 1;
 4116:               }
 4117:           } 
 4118: 	} else {
 4119: 	  if ($#parts == 0) {
 4120: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4121: 	  } else {
 4122: 	    $prevattempts.='<th>'.$ign.'</th>';
 4123: 	  }
 4124: 	}
 4125:       }
 4126:       $prevattempts.=&end_data_table_header_row();
 4127:       if ($getattempt eq '') {
 4128:         my (%solved,%resets,%probstatus);
 4129:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4130:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4131:                 foreach my $id (keys(%regraded)) {
 4132:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4133:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4134:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4135:                         push(@{$resets{$id}},$version);
 4136:                     }
 4137:                 }
 4138:             }
 4139:         }
 4140: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4141:             my (@hidden,@unsolved);
 4142:             if (%typeparts) {
 4143:                 foreach my $id (keys(%typeparts)) {
 4144:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4145:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4146:                         push(@hidden,$id);
 4147:                     } elsif ($identifier ne '') {
 4148:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4149:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4150:                                 ($hidestatus{$id})) {
 4151:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4152:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4153:                                 push(@{$solved{$id}},$version);
 4154:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4155:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4156:                                 my $skip;
 4157:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4158:                                     foreach my $reset (@{$resets{$id}}) {
 4159:                                         if ($reset > $solved{$id}[-1]) {
 4160:                                             $skip=1;
 4161:                                             last;
 4162:                                         }
 4163:                                     }
 4164:                                 }
 4165:                                 unless ($skip) {
 4166:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4167:                                     push(@unsolved,$partslist);
 4168:                                 }
 4169:                             }
 4170:                         }
 4171:                     }
 4172:                 }
 4173:             }
 4174:             $prevattempts.=&start_data_table_row().
 4175:                            '<td>'.&mt('Transaction [_1]',$version);
 4176:             if (@unsolved) {
 4177:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4178:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4179:                                  &mt('Hide').'</label></span>';
 4180:             }
 4181:             $prevattempts .= '</td>';
 4182:             if (@hidden) {
 4183:                 foreach my $key (sort(keys(%lasthash))) {
 4184:                     next if ($key =~ /\.foilorder$/);
 4185:                     my $hide;
 4186:                     foreach my $id (@hidden) {
 4187:                         if ($key =~ /^\Q$id\E/) {
 4188:                             $hide = 1;
 4189:                             last;
 4190:                         }
 4191:                     }
 4192:                     if ($hide) {
 4193:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4194:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4195:                             my $value = &format_previous_attempt_value($key,
 4196:                                              $returnhash{$version.':'.$key});
 4197:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4198:                         } else {
 4199:                             $prevattempts.='<td>&nbsp;</td>';
 4200:                         }
 4201:                     } else {
 4202:                         if ($key =~ /\./) {
 4203:                             my $value = $returnhash{$version.':'.$key};
 4204:                             if ($key =~ /\.rndseed$/) {
 4205:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4206:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4207:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4208:                                 }
 4209:                             }
 4210:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4211:                                            '&nbsp;</td>';
 4212:                         } else {
 4213:                             $prevattempts.='<td>&nbsp;</td>';
 4214:                         }
 4215:                     }
 4216:                 }
 4217:             } else {
 4218: 	        foreach my $key (sort(keys(%lasthash))) {
 4219:                     next if ($key =~ /\.foilorder$/);
 4220:                     my $value = $returnhash{$version.':'.$key};
 4221:                     if ($key =~ /\.rndseed$/) {
 4222:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4223:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4224:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4225:                         }
 4226:                     }
 4227:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4228:                                    '&nbsp;</td>';
 4229: 	        }
 4230:             }
 4231: 	    $prevattempts.=&end_data_table_row();
 4232: 	 }
 4233:       }
 4234:       my @currhidden = keys(%lasthidden);
 4235:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4236:       foreach my $key (sort(keys(%lasthash))) {
 4237:           next if ($key =~ /\.foilorder$/);
 4238:           if (%typeparts) {
 4239:               my $hidden;
 4240:               foreach my $id (@currhidden) {
 4241:                   if ($key =~ /^\Q$id\E/) {
 4242:                       $hidden = 1;
 4243:                       last;
 4244:                   }
 4245:               }
 4246:               if ($hidden) {
 4247:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4248:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4249:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4250:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4251:                           $value = &$gradesub($value);
 4252:                       }
 4253:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4254:                   } else {
 4255:                       $prevattempts.='<td>&nbsp;</td>';
 4256:                   }
 4257:               } else {
 4258:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4259:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4260:                       $value = &$gradesub($value);
 4261:                   }
 4262:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4263:               }
 4264:           } else {
 4265: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4266: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4267:                   $value = &$gradesub($value);
 4268:               }
 4269: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4270:           }
 4271:       }
 4272:       $prevattempts.= &end_data_table_row().&end_data_table();
 4273:     } else {
 4274:       $prevattempts=
 4275: 	  &start_data_table().&start_data_table_row().
 4276: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4277: 	  &end_data_table_row().&end_data_table();
 4278:     }
 4279:   } else {
 4280:     $prevattempts=
 4281: 	  &start_data_table().&start_data_table_row().
 4282: 	  '<td>'.&mt('No data.').'</td>'.
 4283: 	  &end_data_table_row().&end_data_table();
 4284:   }
 4285: }
 4286: 
 4287: sub format_previous_attempt_value {
 4288:     my ($key,$value) = @_;
 4289:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4290: 	$value = &Apache::lonlocal::locallocaltime($value);
 4291:     } elsif (ref($value) eq 'ARRAY') {
 4292: 	$value = '('.join(', ', @{ $value }).')';
 4293:     } elsif ($key =~ /answerstring$/) {
 4294:         my %answers = &Apache::lonnet::str2hash($value);
 4295:         my @anskeys = sort(keys(%answers));
 4296:         if (@anskeys == 1) {
 4297:             my $answer = $answers{$anskeys[0]};
 4298:             if ($answer =~ m{\0}) {
 4299:                 $answer =~ s{\0}{,}g;
 4300:             }
 4301:             my $tag_internal_answer_name = 'INTERNAL';
 4302:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4303:                 $value = $answer; 
 4304:             } else {
 4305:                 $value = $anskeys[0].'='.$answer;
 4306:             }
 4307:         } else {
 4308:             foreach my $ans (@anskeys) {
 4309:                 my $answer = $answers{$ans};
 4310:                 if ($answer =~ m{\0}) {
 4311:                     $answer =~ s{\0}{,}g;
 4312:                 }
 4313:                 $value .=  $ans.'='.$answer.'<br />';;
 4314:             } 
 4315:         }
 4316:     } else {
 4317: 	$value = &unescape($value);
 4318:     }
 4319:     return $value;
 4320: }
 4321: 
 4322: 
 4323: sub relative_to_absolute {
 4324:     my ($url,$output)=@_;
 4325:     my $parser=HTML::TokeParser->new(\$output);
 4326:     my $token;
 4327:     my $thisdir=$url;
 4328:     my @rlinks=();
 4329:     while ($token=$parser->get_token) {
 4330: 	if ($token->[0] eq 'S') {
 4331: 	    if ($token->[1] eq 'a') {
 4332: 		if ($token->[2]->{'href'}) {
 4333: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4334: 		}
 4335: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4336: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4337: 	    } elsif ($token->[1] eq 'base') {
 4338: 		$thisdir=$token->[2]->{'href'};
 4339: 	    }
 4340: 	}
 4341:     }
 4342:     $thisdir=~s-/[^/]*$--;
 4343:     foreach my $link (@rlinks) {
 4344: 	unless (($link=~/^https?\:\/\//i) ||
 4345: 		($link=~/^\//) ||
 4346: 		($link=~/^javascript:/i) ||
 4347: 		($link=~/^mailto:/i) ||
 4348: 		($link=~/^\#/)) {
 4349: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4350: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4351: 	}
 4352:     }
 4353: # -------------------------------------------------- Deal with Applet codebases
 4354:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4355:     return $output;
 4356: }
 4357: 
 4358: =pod
 4359: 
 4360: =item * &get_student_view()
 4361: 
 4362: show a snapshot of what student was looking at
 4363: 
 4364: =cut
 4365: 
 4366: sub get_student_view {
 4367:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4368:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4369:   my (%form);
 4370:   my @elements=('symb','courseid','domain','username');
 4371:   foreach my $element (@elements) {
 4372:       $form{'grade_'.$element}=eval '$'.$element #'
 4373:   }
 4374:   if (defined($moreenv)) {
 4375:       %form=(%form,%{$moreenv});
 4376:   }
 4377:   if (defined($target)) { $form{'grade_target'} = $target; }
 4378:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4379:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4380:   $userview=~s/\<body[^\>]*\>//gi;
 4381:   $userview=~s/\<\/body\>//gi;
 4382:   $userview=~s/\<html\>//gi;
 4383:   $userview=~s/\<\/html\>//gi;
 4384:   $userview=~s/\<head\>//gi;
 4385:   $userview=~s/\<\/head\>//gi;
 4386:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4387:   $userview=&relative_to_absolute($feedurl,$userview);
 4388:   if (wantarray) {
 4389:      return ($userview,$response);
 4390:   } else {
 4391:      return $userview;
 4392:   }
 4393: }
 4394: 
 4395: sub get_student_view_with_retries {
 4396:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4397: 
 4398:     my $ok = 0;                 # True if we got a good response.
 4399:     my $content;
 4400:     my $response;
 4401: 
 4402:     # Try to get the student_view done. within the retries count:
 4403:     
 4404:     do {
 4405:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4406:          $ok      = $response->is_success;
 4407:          if (!$ok) {
 4408:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4409:          }
 4410:          $retries--;
 4411:     } while (!$ok && ($retries > 0));
 4412:     
 4413:     if (!$ok) {
 4414:        $content = '';          # On error return an empty content.
 4415:     }
 4416:     if (wantarray) {
 4417:        return ($content, $response);
 4418:     } else {
 4419:        return $content;
 4420:     }
 4421: }
 4422: 
 4423: sub css_links {
 4424:     my ($currsymb,$level) = @_;
 4425:     my ($links,@symbs,%cssrefs,%httpref);
 4426:     if ($level eq 'map') {
 4427:         my $navmap = Apache::lonnavmaps::navmap->new();
 4428:         if (ref($navmap)) {
 4429:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 4430:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 4431:             foreach my $res (@resources) {
 4432:                 if (ref($res) && $res->symb()) {
 4433:                     push(@symbs,$res->symb());
 4434:                 }
 4435:             }
 4436:         }
 4437:     } else {
 4438:         @symbs = ($currsymb);
 4439:     }
 4440:     foreach my $symb (@symbs) {
 4441:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 4442:         if ($css_href =~ /\S/) {
 4443:             unless ($css_href =~ m{https?://}) {
 4444:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 4445:                 my $proburl =  &Apache::lonnet::clutter($url);
 4446:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 4447:                 unless ($css_href =~ m{^/}) {
 4448:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 4449:                 }
 4450:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 4451:                     unless (($httpref{'httpref.'.$css_href}) ||
 4452:                             (&Apache::lonnet::is_on_map($css_href))) {
 4453:                         my $thisurl = $proburl;
 4454:                         if ($env{'httpref.'.$proburl}) {
 4455:                             $thisurl = $env{'httpref.'.$proburl};
 4456:                         }
 4457:                         $httpref{'httpref.'.$css_href} = $thisurl;
 4458:                     }
 4459:                 }
 4460:             }
 4461:             $cssrefs{$css_href} = 1;
 4462:         }
 4463:     }
 4464:     if (keys(%httpref)) {
 4465:         &Apache::lonnet::appenv(\%httpref);
 4466:     }
 4467:     if (keys(%cssrefs)) {
 4468:         foreach my $css_href (keys(%cssrefs)) {
 4469:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 4470:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 4471:         }
 4472:     }
 4473:     return $links;
 4474: }
 4475: 
 4476: =pod
 4477: 
 4478: =item * &get_student_answers() 
 4479: 
 4480: show a snapshot of how student was answering problem
 4481: 
 4482: =cut
 4483: 
 4484: sub get_student_answers {
 4485:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4486:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4487:   my (%moreenv);
 4488:   my @elements=('symb','courseid','domain','username');
 4489:   foreach my $element (@elements) {
 4490:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4491:   }
 4492:   $moreenv{'grade_target'}='answer';
 4493:   %moreenv=(%form,%moreenv);
 4494:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4495:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4496:   return $userview;
 4497: }
 4498: 
 4499: =pod
 4500: 
 4501: =item * &submlink()
 4502: 
 4503: Inputs: $text $uname $udom $symb $target
 4504: 
 4505: Returns: A link to grades.pm such as to see the SUBM view of a student
 4506: 
 4507: =cut
 4508: 
 4509: ###############################################
 4510: sub submlink {
 4511:     my ($text,$uname,$udom,$symb,$target)=@_;
 4512:     if (!($uname && $udom)) {
 4513: 	(my $cursymb, my $courseid,$udom,$uname)=
 4514: 	    &Apache::lonnet::whichuser($symb);
 4515: 	if (!$symb) { $symb=$cursymb; }
 4516:     }
 4517:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4518:     $symb=&escape($symb);
 4519:     if ($target) { $target=" target=\"$target\""; }
 4520:     return
 4521:         '<a href="/adm/grades?command=submission'.
 4522:         '&amp;symb='.$symb.
 4523:         '&amp;student='.$uname.
 4524:         '&amp;userdom='.$udom.'"'.
 4525:         $target.'>'.$text.'</a>';
 4526: }
 4527: ##############################################
 4528: 
 4529: =pod
 4530: 
 4531: =item * &pgrdlink()
 4532: 
 4533: Inputs: $text $uname $udom $symb $target
 4534: 
 4535: Returns: A link to grades.pm such as to see the PGRD view of a student
 4536: 
 4537: =cut
 4538: 
 4539: ###############################################
 4540: sub pgrdlink {
 4541:     my $link=&submlink(@_);
 4542:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4543:     return $link;
 4544: }
 4545: ##############################################
 4546: 
 4547: =pod
 4548: 
 4549: =item * &pprmlink()
 4550: 
 4551: Inputs: $text $uname $udom $symb $target
 4552: 
 4553: Returns: A link to parmset.pm such as to see the PPRM view of a
 4554: student and a specific resource
 4555: 
 4556: =cut
 4557: 
 4558: ###############################################
 4559: sub pprmlink {
 4560:     my ($text,$uname,$udom,$symb,$target)=@_;
 4561:     if (!($uname && $udom)) {
 4562: 	(my $cursymb, my $courseid,$udom,$uname)=
 4563: 	    &Apache::lonnet::whichuser($symb);
 4564: 	if (!$symb) { $symb=$cursymb; }
 4565:     }
 4566:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4567:     $symb=&escape($symb);
 4568:     if ($target) { $target="target=\"$target\""; }
 4569:     return '<a href="/adm/parmset?command=set&amp;'.
 4570: 	'symb='.$symb.'&amp;uname='.$uname.
 4571: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4572: }
 4573: ##############################################
 4574: 
 4575: =pod
 4576: 
 4577: =back
 4578: 
 4579: =cut
 4580: 
 4581: ###############################################
 4582: 
 4583: 
 4584: sub timehash {
 4585:     my ($thistime) = @_;
 4586:     my $timezone = &Apache::lonlocal::gettimezone();
 4587:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4588:                      ->set_time_zone($timezone);
 4589:     my $wday = $dt->day_of_week();
 4590:     if ($wday == 7) { $wday = 0; }
 4591:     return ( 'second' => $dt->second(),
 4592:              'minute' => $dt->minute(),
 4593:              'hour'   => $dt->hour(),
 4594:              'day'     => $dt->day_of_month(),
 4595:              'month'   => $dt->month(),
 4596:              'year'    => $dt->year(),
 4597:              'weekday' => $wday,
 4598:              'dayyear' => $dt->day_of_year(),
 4599:              'dlsav'   => $dt->is_dst() );
 4600: }
 4601: 
 4602: sub utc_string {
 4603:     my ($date)=@_;
 4604:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4605: }
 4606: 
 4607: sub maketime {
 4608:     my %th=@_;
 4609:     my ($epoch_time,$timezone,$dt);
 4610:     $timezone = &Apache::lonlocal::gettimezone();
 4611:     eval {
 4612:         $dt = DateTime->new( year   => $th{'year'},
 4613:                              month  => $th{'month'},
 4614:                              day    => $th{'day'},
 4615:                              hour   => $th{'hour'},
 4616:                              minute => $th{'minute'},
 4617:                              second => $th{'second'},
 4618:                              time_zone => $timezone,
 4619:                          );
 4620:     };
 4621:     if (!$@) {
 4622:         $epoch_time = $dt->epoch;
 4623:         if ($epoch_time) {
 4624:             return $epoch_time;
 4625:         }
 4626:     }
 4627:     return POSIX::mktime(
 4628:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4629:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4630: }
 4631: 
 4632: #########################################
 4633: 
 4634: sub findallcourses {
 4635:     my ($roles,$uname,$udom) = @_;
 4636:     my %roles;
 4637:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4638:     my %courses;
 4639:     my $now=time;
 4640:     if (!defined($uname)) {
 4641:         $uname = $env{'user.name'};
 4642:     }
 4643:     if (!defined($udom)) {
 4644:         $udom = $env{'user.domain'};
 4645:     }
 4646:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4647:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4648:         if (!%roles) {
 4649:             %roles = (
 4650:                        cc => 1,
 4651:                        co => 1,
 4652:                        in => 1,
 4653:                        ep => 1,
 4654:                        ta => 1,
 4655:                        cr => 1,
 4656:                        st => 1,
 4657:              );
 4658:         }
 4659:         foreach my $entry (keys(%roleshash)) {
 4660:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4661:             if ($trole =~ /^cr/) { 
 4662:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4663:             } else {
 4664:                 next if (!exists($roles{$trole}));
 4665:             }
 4666:             if ($tend) {
 4667:                 next if ($tend < $now);
 4668:             }
 4669:             if ($tstart) {
 4670:                 next if ($tstart > $now);
 4671:             }
 4672:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4673:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4674:             my $value = $trole.'/'.$cdom.'/';
 4675:             if ($secpart eq '') {
 4676:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4677:                 $sec = 'none';
 4678:                 $value .= $cnum.'/';
 4679:             } else {
 4680:                 $cnum = $cnumpart;
 4681:                 ($sec,$role) = split(/_/,$secpart);
 4682:                 $value .= $cnum.'/'.$sec;
 4683:             }
 4684:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4685:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4686:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4687:                 }
 4688:             } else {
 4689:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4690:             }
 4691:         }
 4692:     } else {
 4693:         foreach my $key (keys(%env)) {
 4694: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4695:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4696: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4697: 	        next if ($role eq 'ca' || $role eq 'aa');
 4698: 	        next if (%roles && !exists($roles{$role}));
 4699: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4700:                 my $active=1;
 4701:                 if ($starttime) {
 4702: 		    if ($now<$starttime) { $active=0; }
 4703:                 }
 4704:                 if ($endtime) {
 4705:                     if ($now>$endtime) { $active=0; }
 4706:                 }
 4707:                 if ($active) {
 4708:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4709:                     if ($sec eq '') {
 4710:                         $sec = 'none';
 4711:                     } else {
 4712:                         $value .= $sec;
 4713:                     }
 4714:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4715:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4716:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4717:                         }
 4718:                     } else {
 4719:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4720:                     }
 4721:                 }
 4722:             }
 4723:         }
 4724:     }
 4725:     return %courses;
 4726: }
 4727: 
 4728: ###############################################
 4729: 
 4730: sub blockcheck {
 4731:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 4732: 
 4733:     unless ($activity eq 'docs') {
 4734:         my ($has_evb,$check_ipaccess);
 4735:         my $dom = $env{'user.domain'};
 4736:         if ($env{'request.course.id'}) {
 4737:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4738:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4739:             my $checkrole = "cm./$cdom/$cnum";
 4740:             my $sec = $env{'request.course.sec'};
 4741:             if ($sec ne '') {
 4742:                 $checkrole .= "/$sec";
 4743:             }
 4744:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 4745:                 ($env{'request.role'} !~ /^st/)) {
 4746:                 $has_evb = 1;
 4747:             }
 4748:             unless ($has_evb) {
 4749:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 4750:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 4751:                     if ($udom eq $cdom) {
 4752:                         $check_ipaccess = 1;
 4753:                     }
 4754:                 }
 4755:             }
 4756:         }
 4757:         unless ($has_evb || $check_ipaccess) {
 4758:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 4759:             if (($dom eq 'public') && ($activity eq 'port')) {
 4760:                 $dom = $udom;
 4761:             }
 4762:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 4763:                 $check_ipaccess = 1;
 4764:             } else {
 4765:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 4766:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 4767:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 4768:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 4769:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 4770:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 4771:                         $check_ipaccess = 1;
 4772:                     }
 4773:                 }
 4774:             }
 4775:         }
 4776:         if ($check_ipaccess) {
 4777:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 4778:             unless (defined($cached)) {
 4779:                 my %domconfig =
 4780:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 4781:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 4782:             }
 4783:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 4784:                 foreach my $id (keys(%{$ipaccessref})) {
 4785:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 4786:                         my $range = $ipaccessref->{$id}->{'ip'};
 4787:                         if ($range) {
 4788:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 4789:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 4790:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 4791:                                         return ('','','',$id,$dom);
 4792:                                         last;
 4793:                                     }
 4794:                                 }
 4795:                             }
 4796:                         }
 4797:                     }
 4798:                 }
 4799:             }
 4800:         }
 4801:     }
 4802:     if (defined($udom) && defined($uname)) {
 4803:         # If uname and udom are for a course, check for blocks in the course.
 4804:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4805:             my ($startblock,$endblock,$triggerblock) =
 4806:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 4807:             return ($startblock,$endblock,$triggerblock);
 4808:         }
 4809:     } else {
 4810:         $udom = $env{'user.domain'};
 4811:         $uname = $env{'user.name'};
 4812:     }
 4813: 
 4814:     my $startblock = 0;
 4815:     my $endblock = 0;
 4816:     my $triggerblock = '';
 4817:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4818: 
 4819:     # If uname is for a user, and activity is course-specific, i.e.,
 4820:     # boards, chat or groups, check for blocking in current course only.
 4821: 
 4822:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4823:          $activity eq 'groups' || $activity eq 'printout') &&
 4824:         ($env{'request.course.id'})) {
 4825:         foreach my $key (keys(%live_courses)) {
 4826:             if ($key ne $env{'request.course.id'}) {
 4827:                 delete($live_courses{$key});
 4828:             }
 4829:         }
 4830:     }
 4831: 
 4832:     my $otheruser = 0;
 4833:     my %own_courses;
 4834:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4835:         # Resource belongs to user other than current user.
 4836:         $otheruser = 1;
 4837:         # Gather courses for current user
 4838:         %own_courses = 
 4839:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4840:     }
 4841: 
 4842:     # Gather active course roles - course coordinator, instructor, 
 4843:     # exam proctor, ta, student, or custom role.
 4844: 
 4845:     foreach my $course (keys(%live_courses)) {
 4846:         my ($cdom,$cnum);
 4847:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4848:             $cdom = $env{'course.'.$course.'.domain'};
 4849:             $cnum = $env{'course.'.$course.'.num'};
 4850:         } else {
 4851:             ($cdom,$cnum) = split(/_/,$course); 
 4852:         }
 4853:         my $no_ownblock = 0;
 4854:         my $no_userblock = 0;
 4855:         if ($otheruser && $activity ne 'com') {
 4856:             # Check if current user has 'evb' priv for this
 4857:             if (defined($own_courses{$course})) {
 4858:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4859:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4860:                     if ($sec ne 'none') {
 4861:                         $checkrole .= '/'.$sec;
 4862:                     }
 4863:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4864:                         $no_ownblock = 1;
 4865:                         last;
 4866:                     }
 4867:                 }
 4868:             }
 4869:             # if they have 'evb' priv and are currently not playing student
 4870:             next if (($no_ownblock) &&
 4871:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4872:         }
 4873:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4874:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4875:             if ($sec ne 'none') {
 4876:                 $checkrole .= '/'.$sec;
 4877:             }
 4878:             if ($otheruser) {
 4879:                 # Resource belongs to user other than current user.
 4880:                 # Assemble privs for that user, and check for 'evb' priv.
 4881:                 my (%allroles,%userroles);
 4882:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4883:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4884:                         my ($trole,$tdom,$tnum,$tsec);
 4885:                         if ($entry =~ /^cr/) {
 4886:                             ($trole,$tdom,$tnum,$tsec) = 
 4887:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4888:                         } else {
 4889:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4890:                         }
 4891:                         my ($spec,$area,$trest);
 4892:                         $area = '/'.$tdom.'/'.$tnum;
 4893:                         $trest = $tnum;
 4894:                         if ($tsec ne '') {
 4895:                             $area .= '/'.$tsec;
 4896:                             $trest .= '/'.$tsec;
 4897:                         }
 4898:                         $spec = $trole.'.'.$area;
 4899:                         if ($trole =~ /^cr/) {
 4900:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4901:                                                               $tdom,$spec,$trest,$area);
 4902:                         } else {
 4903:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4904:                                                                 $tdom,$spec,$trest,$area);
 4905:                         }
 4906:                     }
 4907:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4908:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4909:                         if ($1) {
 4910:                             $no_userblock = 1;
 4911:                             last;
 4912:                         }
 4913:                     }
 4914:                 }
 4915:             } else {
 4916:                 # Resource belongs to current user
 4917:                 # Check for 'evb' priv via lonnet::allowed().
 4918:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4919:                     $no_ownblock = 1;
 4920:                     last;
 4921:                 }
 4922:             }
 4923:         }
 4924:         # if they have the evb priv and are currently not playing student
 4925:         next if (($no_ownblock) &&
 4926:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4927:         next if ($no_userblock);
 4928: 
 4929:         # Retrieve blocking times and identity of blocker for course
 4930:         # of specified user, unless user has 'evb' privilege.
 4931:         
 4932:         my ($start,$end,$trigger) = 
 4933:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 4934:         if (($start != 0) && 
 4935:             (($startblock == 0) || ($startblock > $start))) {
 4936:             $startblock = $start;
 4937:             if ($trigger ne '') {
 4938:                 $triggerblock = $trigger;
 4939:             }
 4940:         }
 4941:         if (($end != 0)  &&
 4942:             (($endblock == 0) || ($endblock < $end))) {
 4943:             $endblock = $end;
 4944:             if ($trigger ne '') {
 4945:                 $triggerblock = $trigger;
 4946:             }
 4947:         }
 4948:     }
 4949:     return ($startblock,$endblock,$triggerblock);
 4950: }
 4951: 
 4952: sub get_blocks {
 4953:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 4954:     my $startblock = 0;
 4955:     my $endblock = 0;
 4956:     my $triggerblock = '';
 4957:     my $course = $cdom.'_'.$cnum;
 4958:     $setters->{$course} = {};
 4959:     $setters->{$course}{'staff'} = [];
 4960:     $setters->{$course}{'times'} = [];
 4961:     $setters->{$course}{'triggers'} = [];
 4962:     my (@blockers,%triggered);
 4963:     my $now = time;
 4964:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4965:     if ($activity eq 'docs') {
 4966:         my ($blocked,$nosymbcache,$noenccheck);
 4967:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 4968:             $blocked = 1;
 4969:             $nosymbcache = 1;
 4970:             $noenccheck = 1;
 4971:         }
 4972:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 4973:         foreach my $block (@blockers) {
 4974:             if ($block =~ /^firstaccess____(.+)$/) {
 4975:                 my $item = $1;
 4976:                 my $type = 'map';
 4977:                 my $timersymb = $item;
 4978:                 if ($item eq 'course') {
 4979:                     $type = 'course';
 4980:                 } elsif ($item =~ /___\d+___/) {
 4981:                     $type = 'resource';
 4982:                 } else {
 4983:                     $timersymb = &Apache::lonnet::symbread($item);
 4984:                 }
 4985:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4986:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4987:                 $triggered{$block} = {
 4988:                                        start => $start,
 4989:                                        end   => $end,
 4990:                                        type  => $type,
 4991:                                      };
 4992:             }
 4993:         }
 4994:     } else {
 4995:         foreach my $block (keys(%commblocks)) {
 4996:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4997:                 my ($start,$end) = ($1,$2);
 4998:                 if ($start <= time && $end >= time) {
 4999:                     if (ref($commblocks{$block}) eq 'HASH') {
 5000:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5001:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5002:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5003:                                     push(@blockers,$block);
 5004:                                 }
 5005:                             }
 5006:                         }
 5007:                     }
 5008:                 }
 5009:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5010:                 my $item = $1;
 5011:                 my $timersymb = $item; 
 5012:                 my $type = 'map';
 5013:                 if ($item eq 'course') {
 5014:                     $type = 'course';
 5015:                 } elsif ($item =~ /___\d+___/) {
 5016:                     $type = 'resource';
 5017:                 } else {
 5018:                     $timersymb = &Apache::lonnet::symbread($item);
 5019:                 }
 5020:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5021:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5022:                 if ($start && $end) {
 5023:                     if (($start <= time) && ($end >= time)) {
 5024:                         if (ref($commblocks{$block}) eq 'HASH') {
 5025:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5026:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5027:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5028:                                         push(@blockers,$block);
 5029:                                         $triggered{$block} = {
 5030:                                                                start => $start,
 5031:                                                                end   => $end,
 5032:                                                                type  => $type,
 5033:                                                              };
 5034:                                     }
 5035:                                 }
 5036:                             }
 5037:                         }
 5038:                     }
 5039:                 }
 5040:             }
 5041:         }
 5042:     }
 5043:     foreach my $blocker (@blockers) {
 5044:         my ($staff_name,$staff_dom,$title,$blocks) =
 5045:             &parse_block_record($commblocks{$blocker});
 5046:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5047:         my ($start,$end,$triggertype);
 5048:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5049:             ($start,$end) = ($1,$2);
 5050:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5051:             $start = $triggered{$blocker}{'start'};
 5052:             $end = $triggered{$blocker}{'end'};
 5053:             $triggertype = $triggered{$blocker}{'type'};
 5054:         }
 5055:         if ($start) {
 5056:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5057:             if ($triggertype) {
 5058:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5059:             } else {
 5060:                 push(@{$$setters{$course}{'triggers'}},0);
 5061:             }
 5062:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5063:                 $startblock = $start;
 5064:                 if ($triggertype) {
 5065:                     $triggerblock = $blocker;
 5066:                 }
 5067:             }
 5068:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5069:                $endblock = $end;
 5070:                if ($triggertype) {
 5071:                    $triggerblock = $blocker;
 5072:                }
 5073:             }
 5074:         }
 5075:     }
 5076:     return ($startblock,$endblock,$triggerblock);
 5077: }
 5078: 
 5079: sub parse_block_record {
 5080:     my ($record) = @_;
 5081:     my ($setuname,$setudom,$title,$blocks);
 5082:     if (ref($record) eq 'HASH') {
 5083:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5084:         $title = &unescape($record->{'event'});
 5085:         $blocks = $record->{'blocks'};
 5086:     } else {
 5087:         my @data = split(/:/,$record,3);
 5088:         if (scalar(@data) eq 2) {
 5089:             $title = $data[1];
 5090:             ($setuname,$setudom) = split(/@/,$data[0]);
 5091:         } else {
 5092:             ($setuname,$setudom,$title) = @data;
 5093:         }
 5094:         $blocks = { 'com' => 'on' };
 5095:     }
 5096:     return ($setuname,$setudom,$title,$blocks);
 5097: }
 5098: 
 5099: sub blocking_status {
 5100:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5101:     my %setters;
 5102: 
 5103: # check for active blocking
 5104:     if ($clientip eq '') {
 5105:         $clientip = &Apache::lonnet::get_requestor_ip();
 5106:     }
 5107:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5108:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5109:     my $blocked = 0;
 5110:     if (($startblock && $endblock) || ($by_ip)) {
 5111:         $blocked = 1;
 5112:     }
 5113: 
 5114: # caller just wants to know whether a block is active
 5115:     if (!wantarray) { return $blocked; }
 5116: 
 5117: # build a link to a popup window containing the details
 5118:     my $querystring  = "?activity=$activity";
 5119: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5120:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5121:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 5122:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5123:     } elsif ($activity eq 'docs') {
 5124:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5125:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5126:         if ($symb) {
 5127:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5128:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5129:         }
 5130:     }
 5131: 
 5132:     my $output .= <<'END_MYBLOCK';
 5133: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5134:     var options = "width=" + w + ",height=" + h + ",";
 5135:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5136:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5137:     var newWin = window.open(url, wdwName, options);
 5138:     newWin.focus();
 5139: }
 5140: END_MYBLOCK
 5141: 
 5142:     $output = Apache::lonhtmlcommon::scripttag($output);
 5143:   
 5144:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5145:     my $text = &mt('Communication Blocked');
 5146:     my $class = 'LC_comblock';
 5147:     if ($activity eq 'docs') {
 5148:         $text = &mt('Content Access Blocked');
 5149:         $class = '';
 5150:     } elsif ($activity eq 'printout') {
 5151:         $text = &mt('Printing Blocked');
 5152:     } elsif ($activity eq 'passwd') {
 5153:         $text = &mt('Password Changing Blocked');
 5154:     } elsif ($activity eq 'grades') {
 5155:         $text = &mt('Gradebook Blocked');
 5156:     } elsif ($activity eq 'search') {
 5157:         $text = &mt('Search Blocked');
 5158:     } elsif ($activity eq 'about') {
 5159:         $text = &mt('Access to User Information Pages Blocked');
 5160:     }
 5161:     $output .= <<"END_BLOCK";
 5162: <div class='$class'>
 5163:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5164:   title='$text'>
 5165:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5166:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5167:   title='$text'>$text</a>
 5168: </div>
 5169: 
 5170: END_BLOCK
 5171: 
 5172:     return ($blocked, $output);
 5173: }
 5174: 
 5175: ###############################################
 5176: 
 5177: sub check_ip_acc {
 5178:     my ($acc,$clientip)=@_;
 5179:     &Apache::lonxml::debug("acc is $acc");
 5180:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5181:         return 1;
 5182:     }
 5183:     my $allowed=0;
 5184:     my $ip;
 5185:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5186:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5187:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5188:     } else {
 5189:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5190:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5191:     }
 5192: 
 5193:     my $name;
 5194:     foreach my $pattern (split(',',$acc)) {
 5195:         $pattern =~ s/^\s*//;
 5196:         $pattern =~ s/\s*$//;
 5197:         if ($pattern =~ /\*$/) {
 5198:             #35.8.*
 5199:             $pattern=~s/\*//;
 5200:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 5201:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5202:             #35.8.3.[34-56]
 5203:             my $low=$2;
 5204:             my $high=$3;
 5205:             $pattern=$1;
 5206:             if ($ip =~ /^\Q$pattern\E/) {
 5207:                 my $last=(split(/\./,$ip))[3];
 5208:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 5209:             }
 5210:         } elsif ($pattern =~ /^\*/) {
 5211:             #*.msu.edu
 5212:             $pattern=~s/\*//;
 5213:             if (!defined($name)) {
 5214:                 use Socket;
 5215:                 my $netaddr=inet_aton($ip);
 5216:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5217:             }
 5218:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 5219:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5220:             #127.0.0.1
 5221:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 5222:         } else {
 5223:             #some.name.com
 5224:             if (!defined($name)) {
 5225:                 use Socket;
 5226:                 my $netaddr=inet_aton($ip);
 5227:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5228:             }
 5229:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 5230:         }
 5231:         if ($allowed) { last; }
 5232:     }
 5233:     return $allowed;
 5234: }
 5235: 
 5236: ###############################################
 5237: 
 5238: =pod
 5239: 
 5240: =head1 Domain Template Functions
 5241: 
 5242: =over 4
 5243: 
 5244: =item * &determinedomain()
 5245: 
 5246: Inputs: $domain (usually will be undef)
 5247: 
 5248: Returns: Determines which domain should be used for designs
 5249: 
 5250: =cut
 5251: 
 5252: ###############################################
 5253: sub determinedomain {
 5254:     my $domain=shift;
 5255:     if (! $domain) {
 5256:         # Determine domain if we have not been given one
 5257:         $domain = &Apache::lonnet::default_login_domain();
 5258:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5259:         if ($env{'request.role.domain'}) { 
 5260:             $domain=$env{'request.role.domain'}; 
 5261:         }
 5262:     }
 5263:     return $domain;
 5264: }
 5265: ###############################################
 5266: 
 5267: sub devalidate_domconfig_cache {
 5268:     my ($udom)=@_;
 5269:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5270: }
 5271: 
 5272: # ---------------------- Get domain configuration for a domain
 5273: sub get_domainconf {
 5274:     my ($udom) = @_;
 5275:     my $cachetime=1800;
 5276:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5277:     if (defined($cached)) { return %{$result}; }
 5278: 
 5279:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5280: 					     ['login','rolecolors','autoenroll'],$udom);
 5281:     my (%designhash,%legacy);
 5282:     if (keys(%domconfig) > 0) {
 5283:         if (ref($domconfig{'login'}) eq 'HASH') {
 5284:             if (keys(%{$domconfig{'login'}})) {
 5285:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5286:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5287:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5288:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5289:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5290:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5291:                                         if ($key eq 'loginvia') {
 5292:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5293:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5294:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5295:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5296:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5297:                                                 } else {
 5298:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5299:                                                 }
 5300:                                             }
 5301:                                         } elsif ($key eq 'headtag') {
 5302:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5303:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5304:                                             }
 5305:                                         }
 5306:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5307:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5308:                                         }
 5309:                                     }
 5310:                                 }
 5311:                             }
 5312:                         } elsif ($key eq 'saml') {
 5313:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5314:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 5315:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 5316:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 5317:                                         foreach my $item ('text','img','alt','url','title','notsso') {
 5318:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 5319:                                         }
 5320:                                     }
 5321:                                 }
 5322:                             }
 5323:                         } else {
 5324:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5325:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5326:                                     $domconfig{'login'}{$key}{$img};
 5327:                             }
 5328:                         }
 5329:                     } else {
 5330:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5331:                     }
 5332:                 }
 5333:             } else {
 5334:                 $legacy{'login'} = 1;
 5335:             }
 5336:         } else {
 5337:             $legacy{'login'} = 1;
 5338:         }
 5339:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5340:             if (keys(%{$domconfig{'rolecolors'}})) {
 5341:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5342:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5343:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5344:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5345:                         }
 5346:                     }
 5347:                 }
 5348:             } else {
 5349:                 $legacy{'rolecolors'} = 1;
 5350:             }
 5351:         } else {
 5352:             $legacy{'rolecolors'} = 1;
 5353:         }
 5354:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5355:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5356:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5357:             }
 5358:         }
 5359:         if (keys(%legacy) > 0) {
 5360:             my %legacyhash = &get_legacy_domconf($udom);
 5361:             foreach my $item (keys(%legacyhash)) {
 5362:                 if ($item =~ /^\Q$udom\E\.login/) {
 5363:                     if ($legacy{'login'}) { 
 5364:                         $designhash{$item} = $legacyhash{$item};
 5365:                     }
 5366:                 } else {
 5367:                     if ($legacy{'rolecolors'}) {
 5368:                         $designhash{$item} = $legacyhash{$item};
 5369:                     }
 5370:                 }
 5371:             }
 5372:         }
 5373:     } else {
 5374:         %designhash = &get_legacy_domconf($udom); 
 5375:     }
 5376:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5377: 				  $cachetime);
 5378:     return %designhash;
 5379: }
 5380: 
 5381: sub get_legacy_domconf {
 5382:     my ($udom) = @_;
 5383:     my %legacyhash;
 5384:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5385:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5386:     if (-e $designfile) {
 5387:         if ( open (my $fh,'<',$designfile) ) {
 5388:             while (my $line = <$fh>) {
 5389:                 next if ($line =~ /^\#/);
 5390:                 chomp($line);
 5391:                 my ($key,$val)=(split(/\=/,$line));
 5392:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5393:             }
 5394:             close($fh);
 5395:         }
 5396:     }
 5397:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5398:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5399:     }
 5400:     return %legacyhash;
 5401: }
 5402: 
 5403: =pod
 5404: 
 5405: =item * &domainlogo()
 5406: 
 5407: Inputs: $domain (usually will be undef)
 5408: 
 5409: Returns: A link to a domain logo, if the domain logo exists.
 5410: If the domain logo does not exist, a description of the domain.
 5411: 
 5412: =cut
 5413: 
 5414: ###############################################
 5415: sub domainlogo {
 5416:     my $domain = &determinedomain(shift);
 5417:     my %designhash = &get_domainconf($domain);    
 5418:     # See if there is a logo
 5419:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5420:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5421:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5422: 	    if ($imgsrc =~ m{^/res/}) {
 5423: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5424: 		&Apache::lonnet::repcopy($local_name);
 5425: 	    }
 5426: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5427:         } 
 5428:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5429:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5430:         return &Apache::lonnet::domain($domain,'description');
 5431:     } else {
 5432:         return '';
 5433:     }
 5434: }
 5435: ##############################################
 5436: 
 5437: =pod
 5438: 
 5439: =item * &designparm()
 5440: 
 5441: Inputs: $which parameter; $domain (usually will be undef)
 5442: 
 5443: Returns: value of designparamter $which
 5444: 
 5445: =cut
 5446: 
 5447: 
 5448: ##############################################
 5449: sub designparm {
 5450:     my ($which,$domain)=@_;
 5451:     if (exists($env{'environment.color.'.$which})) {
 5452:         return $env{'environment.color.'.$which};
 5453:     }
 5454:     $domain=&determinedomain($domain);
 5455:     my %domdesign;
 5456:     unless ($domain eq 'public') {
 5457:         %domdesign = &get_domainconf($domain);
 5458:     }
 5459:     my $output;
 5460:     if ($domdesign{$domain.'.'.$which} ne '') {
 5461:         $output = $domdesign{$domain.'.'.$which};
 5462:     } else {
 5463:         $output = $defaultdesign{$which};
 5464:     }
 5465:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5466:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5467:         if ($output =~ m{^/(adm|res)/}) {
 5468:             if ($output =~ m{^/res/}) {
 5469:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5470:                 &Apache::lonnet::repcopy($local_name);
 5471:             }
 5472:             $output = &lonhttpdurl($output);
 5473:         }
 5474:     }
 5475:     return $output;
 5476: }
 5477: 
 5478: ##############################################
 5479: =pod
 5480: 
 5481: =item * &authorspace()
 5482: 
 5483: Inputs: $url (usually will be undef).
 5484: 
 5485: Returns: Path to Authoring Space containing the resource or 
 5486:          directory being viewed (or for which action is being taken). 
 5487:          If $url is provided, and begins /priv/<domain>/<uname>
 5488:          the path will be that portion of the $context argument.
 5489:          Otherwise the path will be for the author space of the current
 5490:          user when the current role is author, or for that of the 
 5491:          co-author/assistant co-author space when the current role 
 5492:          is co-author or assistant co-author.
 5493: 
 5494: =cut
 5495: 
 5496: sub authorspace {
 5497:     my ($url) = @_;
 5498:     if ($url ne '') {
 5499:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5500:            return $1;
 5501:         }
 5502:     }
 5503:     my $caname = '';
 5504:     my $cadom = '';
 5505:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5506:         ($cadom,$caname) =
 5507:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5508:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5509:         $caname = $env{'user.name'};
 5510:         $cadom = $env{'user.domain'};
 5511:     }
 5512:     if (($caname ne '') && ($cadom ne '')) {
 5513:         return "/priv/$cadom/$caname/";
 5514:     }
 5515:     return;
 5516: }
 5517: 
 5518: ##############################################
 5519: =pod
 5520: 
 5521: =item * &head_subbox()
 5522: 
 5523: Inputs: $content (contains HTML code with page functions, etc.)
 5524: 
 5525: Returns: HTML div with $content
 5526:          To be included in page header
 5527: 
 5528: =cut
 5529: 
 5530: sub head_subbox {
 5531:     my ($content)=@_;
 5532:     my $output =
 5533:         '<div class="LC_head_subbox">'
 5534:        .$content
 5535:        .'</div>'
 5536: }
 5537: 
 5538: ##############################################
 5539: =pod
 5540: 
 5541: =item * &CSTR_pageheader()
 5542: 
 5543: Input: (optional) filename from which breadcrumb trail is built.
 5544:        In most cases no input as needed, as $env{'request.filename'}
 5545:        is appropriate for use in building the breadcrumb trail.
 5546: 
 5547: Returns: HTML div with CSTR path and recent box
 5548:          To be included on Authoring Space pages
 5549: 
 5550: =cut
 5551: 
 5552: sub CSTR_pageheader {
 5553:     my ($trailfile) = @_;
 5554:     if ($trailfile eq '') {
 5555:         $trailfile = $env{'request.filename'};
 5556:     }
 5557: 
 5558: # this is for resources; directories have customtitle, and crumbs
 5559: # and select recent are created in lonpubdir.pm
 5560: 
 5561:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5562:     my ($udom,$uname,$thisdisfn)=
 5563:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5564:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5565:     $formaction =~ s{/+}{/}g;
 5566: 
 5567:     my $parentpath = '';
 5568:     my $lastitem = '';
 5569:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5570:         $parentpath = $1;
 5571:         $lastitem = $2;
 5572:     } else {
 5573:         $lastitem = $thisdisfn;
 5574:     }
 5575: 
 5576:     my $output =
 5577:          '<div>'
 5578:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5579:         .'<b>'.&mt('Authoring Space:').'</b> '
 5580:         .'<form name="dirs" method="post" action="'.$formaction
 5581:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5582:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5583: 
 5584:     if ($lastitem) {
 5585:         $output .=
 5586:              '<span class="LC_filename">'
 5587:             .$lastitem
 5588:             .'</span>';
 5589:     }
 5590:     $output .=
 5591:          '<br />'
 5592:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5593:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5594:         .'</form>'
 5595:         .&Apache::lonmenu::constspaceform()
 5596:         .'</div>';
 5597: 
 5598:     return $output;
 5599: }
 5600: 
 5601: ###############################################
 5602: ###############################################
 5603: 
 5604: =pod
 5605: 
 5606: =back
 5607: 
 5608: =head1 HTML Helpers
 5609: 
 5610: =over 4
 5611: 
 5612: =item * &bodytag()
 5613: 
 5614: Returns a uniform header for LON-CAPA web pages.
 5615: 
 5616: Inputs: 
 5617: 
 5618: =over 4
 5619: 
 5620: =item * $title, A title to be displayed on the page.
 5621: 
 5622: =item * $function, the current role (can be undef).
 5623: 
 5624: =item * $addentries, extra parameters for the <body> tag.
 5625: 
 5626: =item * $bodyonly, if defined, only return the <body> tag.
 5627: 
 5628: =item * $domain, if defined, force a given domain.
 5629: 
 5630: =item * $forcereg, if page should register as content page (relevant for 
 5631:             text interface only)
 5632: 
 5633: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5634:                      navigational links
 5635: 
 5636: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5637: 
 5638: =item * $no_inline_link, if true and in remote mode, don't show the
 5639:          'Switch To Inline Menu' link
 5640: 
 5641: =item * $args, optional argument valid values are
 5642:             no_auto_mt_title -> prevents &mt()ing the title arg
 5643:             use_absolute     -> for external resource or syllabus, this will
 5644:                                 contain https://<hostname> if server uses
 5645:                                 https (as per hosts.tab), but request is for http
 5646:             hostname         -> hostname, from $r->hostname().
 5647: 
 5648: =item * $advtoolsref, optional argument, ref to an array containing
 5649:             inlineremote items to be added in "Functions" menu below
 5650:             breadcrumbs.
 5651: 
 5652: =back
 5653: 
 5654: Returns: A uniform header for LON-CAPA web pages.  
 5655: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5656: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5657: other decorations will be returned.
 5658: 
 5659: =cut
 5660: 
 5661: sub bodytag {
 5662:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5663:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5664: 
 5665:     my $public;
 5666:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5667:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5668:         $public = 1;
 5669:     }
 5670:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5671:     my $httphost = $args->{'use_absolute'};
 5672:     my $hostname = $args->{'hostname'};
 5673: 
 5674:     $function = &get_users_function() if (!$function);
 5675:     my $img =    &designparm($function.'.img',$domain);
 5676:     my $font =   &designparm($function.'.font',$domain);
 5677:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5678: 
 5679:     my %design = ( 'style'   => 'margin-top: 0',
 5680: 		   'bgcolor' => $pgbg,
 5681: 		   'text'    => $font,
 5682:                    'alink'   => &designparm($function.'.alink',$domain),
 5683: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5684: 		   'link'    => &designparm($function.'.link',$domain),);
 5685:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5686: 
 5687:  # role and realm
 5688:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5689:     if ($realm) {
 5690:         $realm = '/'.$realm;
 5691:     }
 5692:     if ($rol  eq 'ca') {
 5693:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5694:         $realm = &plainname($rname,$rdom);
 5695:     } 
 5696: # realm
 5697:     my ($cid,$sec);
 5698:     if ($env{'request.course.id'}) {
 5699:         $cid = $env{'request.course.id'};
 5700:         if ($env{'request.course.sec'}) {
 5701:             $sec = $env{'request.course.sec'};
 5702:         }
 5703:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 5704:         if (&Apache::lonnet::is_course($1,$2)) {
 5705:             $cid = $1.'_'.$2;
 5706:             $sec = $3;
 5707:         }
 5708:     }
 5709:     if ($cid) {
 5710:         if ($env{'request.role'} !~ /^cr/) {
 5711:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5712:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5713:             if ($env{'request.role.desc'}) {
 5714:                 $role = $env{'request.role.desc'};
 5715:             } else {
 5716:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5717:             }
 5718:         } else {
 5719:             $role = (split(/\//,$role,4))[-1];
 5720:         }
 5721:         if ($sec) {
 5722:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 5723:         }   
 5724: 	$realm = $env{'course.'.$cid.'.description'};
 5725:     } else {
 5726:         $role = &Apache::lonnet::plaintext($role);
 5727:     }
 5728: 
 5729:     if (!$realm) { $realm='&nbsp;'; }
 5730: 
 5731:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5732: 
 5733: # construct main body tag
 5734:     my $bodytag = "<body $extra_body_attr>".
 5735: 	&Apache::lontexconvert::init_math_support();
 5736: 
 5737:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5738: 
 5739:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5740:         return $bodytag;
 5741:     }
 5742: 
 5743:     if ($public) {
 5744: 	undef($role);
 5745:     }
 5746: 
 5747:     my $titleinfo = '<h1>'.$title.'</h1>';
 5748:     #
 5749:     # Extra info if you are the DC
 5750:     my $dc_info = '';
 5751:     if (($env{'user.adv'} && ($env{'request.course.id'}) &&
 5752:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 5753:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5754:         $dc_info =~ s/\s+$//;
 5755:     }
 5756: 
 5757:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5758: 
 5759:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5760: 
 5761: 
 5762: 
 5763:     my $funclist;
 5764:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5765:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5766:                     Apache::lonmenu::serverform();
 5767:         my $forbodytag;
 5768:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5769:                                             $forcereg,$args->{'group'},
 5770:                                             $args->{'bread_crumbs'},
 5771:                                             $advtoolsref,'','',\$forbodytag);
 5772:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5773:             $funclist = $forbodytag;
 5774:         }
 5775:     } else {
 5776: 
 5777:         #    if ($env{'request.state'} eq 'construct') {
 5778:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5779:         #    }
 5780: 
 5781:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5782:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5783: 
 5784:         my ($left,$right) = Apache::lonmenu::primary_menu($args->{'links_disabled'});
 5785: 
 5786:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5787:             if ($dc_info) {
 5788:                 $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5789:             }
 5790:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5791:                            <em>$realm</em> $dc_info</div>|;
 5792:             return $bodytag;
 5793:         }
 5794: 
 5795:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5796:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5797:         }
 5798: 
 5799:         $bodytag .= $right;
 5800: 
 5801:         if ($dc_info) {
 5802:             $dc_info = &dc_courseid_toggle($dc_info);
 5803:         }
 5804:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5805: 
 5806:         #if directed to not display the secondary menu, don't.
 5807:         if ($args->{'no_secondary_menu'}) {
 5808:             return $bodytag;
 5809:         }
 5810:         #don't show menus for public users
 5811:         if (!$public){
 5812:             $bodytag .= Apache::lonmenu::secondary_menu($httphost,$args->{'links_disabled'});
 5813:             $bodytag .= Apache::lonmenu::serverform();
 5814:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5815:             if ($env{'request.state'} eq 'construct') {
 5816:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5817:                                 $args->{'bread_crumbs'},'','',$hostname);
 5818:             } elsif ($forcereg) {
 5819:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5820:                                                             $args->{'group'},
 5821:                                                             $args->{'hide_buttons',
 5822:                                                             $hostname});
 5823:             } else {
 5824:                 my $forbodytag;
 5825:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5826:                                                     $forcereg,$args->{'group'},
 5827:                                                     $args->{'bread_crumbs'},
 5828:                                                     $advtoolsref,'',$hostname,
 5829:                                                     \$forbodytag);
 5830:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5831:                     $bodytag .= $forbodytag;
 5832:                 }
 5833:             }
 5834:         }else{
 5835:             # this is to seperate menu from content when there's no secondary
 5836:             # menu. Especially needed for public accessible ressources.
 5837:             $bodytag .= '<hr style="clear:both" />';
 5838:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5839:         }
 5840: 
 5841:         return $bodytag;
 5842:     }
 5843: 
 5844: #
 5845: # Top frame rendering, Remote is up
 5846: #
 5847: 
 5848:     my $imgsrc = $img;
 5849:     if ($img =~ /^\/adm/) {
 5850:         $imgsrc = &lonhttpdurl($img);
 5851:     }
 5852:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5853: 
 5854:     my $help=($no_inline_link?''
 5855:               :&Apache::loncommon::top_nav_help('Help'));
 5856: 
 5857:     # Explicit link to get inline menu
 5858:     my $menu= ($no_inline_link?''
 5859:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5860: 
 5861:     if ($dc_info) {
 5862:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5863:     }
 5864: 
 5865:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5866:     unless ($public) {
 5867:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5868:                                 undef,'LC_menubuttons_link');
 5869:     }
 5870: 
 5871:     unless ($env{'form.inhibitmenu'}) {
 5872:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5873:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5874:                        <li>$help</li>
 5875:                        <li>$menu</li>
 5876:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5877:     }
 5878:     if ($env{'request.state'} eq 'construct') {
 5879:         if (!$public){
 5880:             if ($env{'request.state'} eq 'construct') {
 5881:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5882:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5883:                             &Apache::lonhtmlcommon::scripttag('','end').
 5884:                             &Apache::lonmenu::innerregister($forcereg,
 5885:                                                             $args->{'bread_crumbs'});
 5886:             }
 5887:         }
 5888:     }
 5889:     return $bodytag."\n".$funclist;
 5890: }
 5891: 
 5892: sub dc_courseid_toggle {
 5893:     my ($dc_info) = @_;
 5894:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5895:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5896:            &mt('(More ...)').'</a></span>'.
 5897:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5898: }
 5899: 
 5900: sub make_attr_string {
 5901:     my ($register,$attr_ref) = @_;
 5902: 
 5903:     if ($attr_ref && !ref($attr_ref)) {
 5904: 	die("addentries Must be a hash ref ".
 5905: 	    join(':',caller(1))." ".
 5906: 	    join(':',caller(0))." ");
 5907:     }
 5908: 
 5909:     if ($register) {
 5910: 	my ($on_load,$on_unload);
 5911: 	foreach my $key (keys(%{$attr_ref})) {
 5912: 	    if      (lc($key) eq 'onload') {
 5913: 		$on_load.=$attr_ref->{$key}.';';
 5914: 		delete($attr_ref->{$key});
 5915: 
 5916: 	    } elsif (lc($key) eq 'onunload') {
 5917: 		$on_unload.=$attr_ref->{$key}.';';
 5918: 		delete($attr_ref->{$key});
 5919: 	    }
 5920: 	}
 5921:         if ($env{'environment.remote'} eq 'on') {
 5922:             $attr_ref->{'onload'}  =
 5923:                 &Apache::lonmenu::loadevents().  $on_load;
 5924:             $attr_ref->{'onunload'}=
 5925:                 &Apache::lonmenu::unloadevents().$on_unload;
 5926:         } else {  
 5927: 	    $attr_ref->{'onload'}  = $on_load;
 5928: 	    $attr_ref->{'onunload'}= $on_unload;
 5929:         }
 5930:     }
 5931: 
 5932:     my $attr_string;
 5933:     foreach my $attr (sort(keys(%$attr_ref))) {
 5934: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5935:     }
 5936:     return $attr_string;
 5937: }
 5938: 
 5939: 
 5940: ###############################################
 5941: ###############################################
 5942: 
 5943: =pod
 5944: 
 5945: =item * &endbodytag()
 5946: 
 5947: Returns a uniform footer for LON-CAPA web pages.
 5948: 
 5949: Inputs: 1 - optional reference to an args hash
 5950: If in the hash, key for noredirectlink has a value which evaluates to true,
 5951: a 'Continue' link is not displayed if the page contains an
 5952: internal redirect in the <head></head> section,
 5953: i.e., $env{'internal.head.redirect'} exists   
 5954: 
 5955: =cut
 5956: 
 5957: sub endbodytag {
 5958:     my ($args) = @_;
 5959:     my $endbodytag;
 5960:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5961:         $endbodytag='</body>';
 5962:     }
 5963:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5964:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5965: 	    $endbodytag=
 5966: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5967: 	        &mt('Continue').'</a>'.
 5968: 	        $endbodytag;
 5969:         }
 5970:     }
 5971:     return $endbodytag;
 5972: }
 5973: 
 5974: =pod
 5975: 
 5976: =item * &standard_css()
 5977: 
 5978: Returns a style sheet
 5979: 
 5980: Inputs: (all optional)
 5981:             domain         -> force to color decorate a page for a specific
 5982:                                domain
 5983:             function       -> force usage of a specific rolish color scheme
 5984:             bgcolor        -> override the default page bgcolor
 5985: 
 5986: =cut
 5987: 
 5988: sub standard_css {
 5989:     my ($function,$domain,$bgcolor) = @_;
 5990:     $function  = &get_users_function() if (!$function);
 5991:     my $img    = &designparm($function.'.img',   $domain);
 5992:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5993:     my $font   = &designparm($function.'.font',  $domain);
 5994:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5995: #second colour for later usage
 5996:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5997:     my $pgbg_or_bgcolor =
 5998: 	         $bgcolor ||
 5999: 	         &designparm($function.'.pgbg',  $domain);
 6000:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6001:     my $alink  = &designparm($function.'.alink', $domain);
 6002:     my $vlink  = &designparm($function.'.vlink', $domain);
 6003:     my $link   = &designparm($function.'.link',  $domain);
 6004: 
 6005:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6006:     my $mono                 = 'monospace';
 6007:     my $data_table_head      = $sidebg;
 6008:     my $data_table_light     = '#FAFAFA';
 6009:     my $data_table_dark      = '#E0E0E0';
 6010:     my $data_table_darker    = '#CCCCCC';
 6011:     my $data_table_highlight = '#FFFF00';
 6012:     my $mail_new             = '#FFBB77';
 6013:     my $mail_new_hover       = '#DD9955';
 6014:     my $mail_read            = '#BBBB77';
 6015:     my $mail_read_hover      = '#999944';
 6016:     my $mail_replied         = '#AAAA88';
 6017:     my $mail_replied_hover   = '#888855';
 6018:     my $mail_other           = '#99BBBB';
 6019:     my $mail_other_hover     = '#669999';
 6020:     my $table_header         = '#DDDDDD';
 6021:     my $feedback_link_bg     = '#BBBBBB';
 6022:     my $lg_border_color      = '#C8C8C8';
 6023:     my $button_hover         = '#BF2317';
 6024: 
 6025:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6026:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6027:                                              : '0 3px 0 4px';
 6028: 
 6029: 
 6030:     return <<END;
 6031: 
 6032: /* needed for iframe to allow 100% height in FF */
 6033: body, html { 
 6034:     margin: 0;
 6035:     padding: 0 0.5%;
 6036:     height: 99%; /* to avoid scrollbars */
 6037: }
 6038: 
 6039: body {
 6040:   font-family: $sans;
 6041:   line-height:130%;
 6042:   font-size:0.83em;
 6043:   color:$font;
 6044: }
 6045: 
 6046: a:focus,
 6047: a:focus img {
 6048:   color: red;
 6049: }
 6050: 
 6051: form, .inline {
 6052:   display: inline;
 6053: }
 6054: 
 6055: .LC_right {
 6056:   text-align:right;
 6057: }
 6058: 
 6059: .LC_middle {
 6060:   vertical-align:middle;
 6061: }
 6062: 
 6063: .LC_floatleft {
 6064:   float: left;
 6065: }
 6066: 
 6067: .LC_floatright {
 6068:   float: right;
 6069: }
 6070: 
 6071: .LC_400Box {
 6072:   width:400px;
 6073: }
 6074: 
 6075: .LC_iframecontainer {
 6076:     width: 98%;
 6077:     margin: 0;
 6078:     position: fixed;
 6079:     top: 8.5em;
 6080:     bottom: 0;
 6081: }
 6082: 
 6083: .LC_iframecontainer iframe{
 6084:     border: none;
 6085:     width: 100%;
 6086:     height: 100%;
 6087: }
 6088: 
 6089: .LC_filename {
 6090:   font-family: $mono;
 6091:   white-space:pre;
 6092:   font-size: 120%;
 6093: }
 6094: 
 6095: .LC_fileicon {
 6096:   border: none;
 6097:   height: 1.3em;
 6098:   vertical-align: text-bottom;
 6099:   margin-right: 0.3em;
 6100:   text-decoration:none;
 6101: }
 6102: 
 6103: .LC_setting {
 6104:   text-decoration:underline;
 6105: }
 6106: 
 6107: .LC_error {
 6108:   color: red;
 6109: }
 6110: 
 6111: .LC_warning {
 6112:   color: darkorange;
 6113: }
 6114: 
 6115: .LC_diff_removed {
 6116:   color: red;
 6117: }
 6118: 
 6119: .LC_info,
 6120: .LC_success,
 6121: .LC_diff_added {
 6122:   color: green;
 6123: }
 6124: 
 6125: div.LC_confirm_box {
 6126:   background-color: #FAFAFA;
 6127:   border: 1px solid $lg_border_color;
 6128:   margin-right: 0;
 6129:   padding: 5px;
 6130: }
 6131: 
 6132: div.LC_confirm_box .LC_error img,
 6133: div.LC_confirm_box .LC_success img {
 6134:   vertical-align: middle;
 6135: }
 6136: 
 6137: .LC_maxwidth {
 6138:   max-width: 100%;
 6139:   height: auto;
 6140: }
 6141: 
 6142: .LC_textsize_mobile {
 6143:   \@media only screen and (max-device-width: 480px) {
 6144:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6145:   }
 6146: }
 6147: 
 6148: .LC_icon {
 6149:   border: none;
 6150:   vertical-align: middle;
 6151: }
 6152: 
 6153: .LC_docs_spacer {
 6154:   width: 25px;
 6155:   height: 1px;
 6156:   border: none;
 6157: }
 6158: 
 6159: .LC_internal_info {
 6160:   color: #999999;
 6161: }
 6162: 
 6163: .LC_discussion {
 6164:   background: $data_table_dark;
 6165:   border: 1px solid black;
 6166:   margin: 2px;
 6167: }
 6168: 
 6169: .LC_disc_action_left {
 6170:   background: $sidebg;
 6171:   text-align: left;
 6172:   padding: 4px;
 6173:   margin: 2px;
 6174: }
 6175: 
 6176: .LC_disc_action_right {
 6177:   background: $sidebg;
 6178:   text-align: right;
 6179:   padding: 4px;
 6180:   margin: 2px;
 6181: }
 6182: 
 6183: .LC_disc_new_item {
 6184:   background: white;
 6185:   border: 2px solid red;
 6186:   margin: 4px;
 6187:   padding: 4px;
 6188: }
 6189: 
 6190: .LC_disc_old_item {
 6191:   background: white;
 6192:   margin: 4px;
 6193:   padding: 4px;
 6194: }
 6195: 
 6196: table.LC_pastsubmission {
 6197:   border: 1px solid black;
 6198:   margin: 2px;
 6199: }
 6200: 
 6201: table#LC_menubuttons {
 6202:   width: 100%;
 6203:   background: $pgbg;
 6204:   border: 2px;
 6205:   border-collapse: separate;
 6206:   padding: 0;
 6207: }
 6208: 
 6209: table#LC_title_bar a {
 6210:   color: $fontmenu;
 6211: }
 6212: 
 6213: table#LC_title_bar {
 6214:   clear: both;
 6215:   display: none;
 6216: }
 6217: 
 6218: table#LC_title_bar,
 6219: table.LC_breadcrumbs, /* obsolete? */
 6220: table#LC_title_bar.LC_with_remote {
 6221:   width: 100%;
 6222:   border-color: $pgbg;
 6223:   border-style: solid;
 6224:   border-width: $border;
 6225:   background: $pgbg;
 6226:   color: $fontmenu;
 6227:   border-collapse: collapse;
 6228:   padding: 0;
 6229:   margin: 0;
 6230: }
 6231: 
 6232: ul.LC_breadcrumb_tools_outerlist {
 6233:     margin: 0;
 6234:     padding: 0;
 6235:     position: relative;
 6236:     list-style: none;
 6237: }
 6238: ul.LC_breadcrumb_tools_outerlist li {
 6239:     display: inline;
 6240: }
 6241: 
 6242: .LC_breadcrumb_tools_navigation {
 6243:     padding: 0;
 6244:     margin: 0;
 6245:     float: left;
 6246: }
 6247: .LC_breadcrumb_tools_tools {
 6248:     padding: 0;
 6249:     margin: 0;
 6250:     float: right;
 6251: }
 6252: 
 6253: table#LC_title_bar td {
 6254:   background: $tabbg;
 6255: }
 6256: 
 6257: table#LC_menubuttons img {
 6258:   border: none;
 6259: }
 6260: 
 6261: .LC_breadcrumbs_component {
 6262:   float: right;
 6263:   margin: 0 1em;
 6264: }
 6265: .LC_breadcrumbs_component img {
 6266:   vertical-align: middle;
 6267: }
 6268: 
 6269: .LC_breadcrumbs_hoverable {
 6270:   background: $sidebg;
 6271: }
 6272: 
 6273: td.LC_table_cell_checkbox {
 6274:   text-align: center;
 6275: }
 6276: 
 6277: .LC_fontsize_small {
 6278:   font-size: 70%;
 6279: }
 6280: 
 6281: #LC_breadcrumbs {
 6282:   clear:both;
 6283:   background: $sidebg;
 6284:   border-bottom: 1px solid $lg_border_color;
 6285:   line-height: 2.5em;
 6286:   overflow: hidden;
 6287:   margin: 0;
 6288:   padding: 0;
 6289:   text-align: left;
 6290: }
 6291: 
 6292: .LC_head_subbox, .LC_actionbox {
 6293:   clear:both;
 6294:   background: #F8F8F8; /* $sidebg; */
 6295:   border: 1px solid $sidebg;
 6296:   margin: 0 0 10px 0;
 6297:   padding: 3px;
 6298:   text-align: left;
 6299: }
 6300: 
 6301: .LC_fontsize_medium {
 6302:   font-size: 85%;
 6303: }
 6304: 
 6305: .LC_fontsize_large {
 6306:   font-size: 120%;
 6307: }
 6308: 
 6309: .LC_menubuttons_inline_text {
 6310:   color: $font;
 6311:   font-size: 90%;
 6312:   padding-left:3px;
 6313: }
 6314: 
 6315: .LC_menubuttons_inline_text img{
 6316:   vertical-align: middle;
 6317: }
 6318: 
 6319: li.LC_menubuttons_inline_text img {
 6320:   cursor:pointer;
 6321:   text-decoration: none;
 6322: }
 6323: 
 6324: .LC_menubuttons_link {
 6325:   text-decoration: none;
 6326: }
 6327: 
 6328: .LC_menubuttons_category {
 6329:   color: $font;
 6330:   background: $pgbg;
 6331:   font-size: larger;
 6332:   font-weight: bold;
 6333: }
 6334: 
 6335: td.LC_menubuttons_text {
 6336:   color: $font;
 6337: }
 6338: 
 6339: .LC_current_location {
 6340:   background: $tabbg;
 6341: }
 6342: 
 6343: td.LC_zero_height {
 6344:   line-height: 0;
 6345:   cellpadding: 0;
 6346: }
 6347: 
 6348: table.LC_data_table {
 6349:   border: 1px solid #000000;
 6350:   border-collapse: separate;
 6351:   border-spacing: 1px;
 6352:   background: $pgbg;
 6353: }
 6354: 
 6355: .LC_data_table_dense {
 6356:   font-size: small;
 6357: }
 6358: 
 6359: table.LC_nested_outer {
 6360:   border: 1px solid #000000;
 6361:   border-collapse: collapse;
 6362:   border-spacing: 0;
 6363:   width: 100%;
 6364: }
 6365: 
 6366: table.LC_innerpickbox,
 6367: table.LC_nested {
 6368:   border: none;
 6369:   border-collapse: collapse;
 6370:   border-spacing: 0;
 6371:   width: 100%;
 6372: }
 6373: 
 6374: table.LC_data_table tr th,
 6375: table.LC_calendar tr th,
 6376: table.LC_prior_tries tr th,
 6377: table.LC_innerpickbox tr th {
 6378:   font-weight: bold;
 6379:   background-color: $data_table_head;
 6380:   color:$fontmenu;
 6381:   font-size:90%;
 6382: }
 6383: 
 6384: table.LC_innerpickbox tr th,
 6385: table.LC_innerpickbox tr td {
 6386:   vertical-align: top;
 6387: }
 6388: 
 6389: table.LC_data_table tr.LC_info_row > td {
 6390:   background-color: #CCCCCC;
 6391:   font-weight: bold;
 6392:   text-align: left;
 6393: }
 6394: 
 6395: table.LC_data_table tr.LC_odd_row > td {
 6396:   background-color: $data_table_light;
 6397:   padding: 2px;
 6398:   vertical-align: top;
 6399: }
 6400: 
 6401: table.LC_pick_box tr > td.LC_odd_row {
 6402:   background-color: $data_table_light;
 6403:   vertical-align: top;
 6404: }
 6405: 
 6406: table.LC_data_table tr.LC_even_row > td {
 6407:   background-color: $data_table_dark;
 6408:   padding: 2px;
 6409:   vertical-align: top;
 6410: }
 6411: 
 6412: table.LC_pick_box tr > td.LC_even_row {
 6413:   background-color: $data_table_dark;
 6414:   vertical-align: top;
 6415: }
 6416: 
 6417: table.LC_data_table tr.LC_data_table_highlight td {
 6418:   background-color: $data_table_darker;
 6419: }
 6420: 
 6421: table.LC_data_table tr td.LC_leftcol_header {
 6422:   background-color: $data_table_head;
 6423:   font-weight: bold;
 6424: }
 6425: 
 6426: table.LC_data_table tr.LC_empty_row td,
 6427: table.LC_nested tr.LC_empty_row td {
 6428:   font-weight: bold;
 6429:   font-style: italic;
 6430:   text-align: center;
 6431:   padding: 8px;
 6432: }
 6433: 
 6434: table.LC_data_table tr.LC_empty_row td,
 6435: table.LC_data_table tr.LC_footer_row td {
 6436:   background-color: $sidebg;
 6437: }
 6438: 
 6439: table.LC_nested tr.LC_empty_row td {
 6440:   background-color: #FFFFFF;
 6441: }
 6442: 
 6443: table.LC_caption {
 6444: }
 6445: 
 6446: table.LC_nested tr.LC_empty_row td {
 6447:   padding: 4ex
 6448: }
 6449: 
 6450: table.LC_nested_outer tr th {
 6451:   font-weight: bold;
 6452:   color:$fontmenu;
 6453:   background-color: $data_table_head;
 6454:   font-size: small;
 6455:   border-bottom: 1px solid #000000;
 6456: }
 6457: 
 6458: table.LC_nested_outer tr td.LC_subheader {
 6459:   background-color: $data_table_head;
 6460:   font-weight: bold;
 6461:   font-size: small;
 6462:   border-bottom: 1px solid #000000;
 6463:   text-align: right;
 6464: }
 6465: 
 6466: table.LC_nested tr.LC_info_row td {
 6467:   background-color: #CCCCCC;
 6468:   font-weight: bold;
 6469:   font-size: small;
 6470:   text-align: center;
 6471: }
 6472: 
 6473: table.LC_nested tr.LC_info_row td.LC_left_item,
 6474: table.LC_nested_outer tr th.LC_left_item {
 6475:   text-align: left;
 6476: }
 6477: 
 6478: table.LC_nested td {
 6479:   background-color: #FFFFFF;
 6480:   font-size: small;
 6481: }
 6482: 
 6483: table.LC_nested_outer tr th.LC_right_item,
 6484: table.LC_nested tr.LC_info_row td.LC_right_item,
 6485: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6486: table.LC_nested tr td.LC_right_item {
 6487:   text-align: right;
 6488: }
 6489: 
 6490: table.LC_nested tr.LC_odd_row td {
 6491:   background-color: #EEEEEE;
 6492: }
 6493: 
 6494: table.LC_createuser {
 6495: }
 6496: 
 6497: table.LC_createuser tr.LC_section_row td {
 6498:   font-size: small;
 6499: }
 6500: 
 6501: table.LC_createuser tr.LC_info_row td  {
 6502:   background-color: #CCCCCC;
 6503:   font-weight: bold;
 6504:   text-align: center;
 6505: }
 6506: 
 6507: table.LC_calendar {
 6508:   border: 1px solid #000000;
 6509:   border-collapse: collapse;
 6510:   width: 98%;
 6511: }
 6512: 
 6513: table.LC_calendar_pickdate {
 6514:   font-size: xx-small;
 6515: }
 6516: 
 6517: table.LC_calendar tr td {
 6518:   border: 1px solid #000000;
 6519:   vertical-align: top;
 6520:   width: 14%;
 6521: }
 6522: 
 6523: table.LC_calendar tr td.LC_calendar_day_empty {
 6524:   background-color: $data_table_dark;
 6525: }
 6526: 
 6527: table.LC_calendar tr td.LC_calendar_day_current {
 6528:   background-color: $data_table_highlight;
 6529: }
 6530: 
 6531: table.LC_data_table tr td.LC_mail_new {
 6532:   background-color: $mail_new;
 6533: }
 6534: 
 6535: table.LC_data_table tr.LC_mail_new:hover {
 6536:   background-color: $mail_new_hover;
 6537: }
 6538: 
 6539: table.LC_data_table tr td.LC_mail_read {
 6540:   background-color: $mail_read;
 6541: }
 6542: 
 6543: /*
 6544: table.LC_data_table tr.LC_mail_read:hover {
 6545:   background-color: $mail_read_hover;
 6546: }
 6547: */
 6548: 
 6549: table.LC_data_table tr td.LC_mail_replied {
 6550:   background-color: $mail_replied;
 6551: }
 6552: 
 6553: /*
 6554: table.LC_data_table tr.LC_mail_replied:hover {
 6555:   background-color: $mail_replied_hover;
 6556: }
 6557: */
 6558: 
 6559: table.LC_data_table tr td.LC_mail_other {
 6560:   background-color: $mail_other;
 6561: }
 6562: 
 6563: /*
 6564: table.LC_data_table tr.LC_mail_other:hover {
 6565:   background-color: $mail_other_hover;
 6566: }
 6567: */
 6568: 
 6569: table.LC_data_table tr > td.LC_browser_file,
 6570: table.LC_data_table tr > td.LC_browser_file_published {
 6571:   background: #AAEE77;
 6572: }
 6573: 
 6574: table.LC_data_table tr > td.LC_browser_file_locked,
 6575: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6576:   background: #FFAA99;
 6577: }
 6578: 
 6579: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6580:   background: #888888;
 6581: }
 6582: 
 6583: table.LC_data_table tr > td.LC_browser_file_modified,
 6584: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6585:   background: #F8F866;
 6586: }
 6587: 
 6588: table.LC_data_table tr.LC_browser_folder > td {
 6589:   background: #E0E8FF;
 6590: }
 6591: 
 6592: table.LC_data_table tr > td.LC_roles_is {
 6593:   /* background: #77FF77; */
 6594: }
 6595: 
 6596: table.LC_data_table tr > td.LC_roles_future {
 6597:   border-right: 8px solid #FFFF77;
 6598: }
 6599: 
 6600: table.LC_data_table tr > td.LC_roles_will {
 6601:   border-right: 8px solid #FFAA77;
 6602: }
 6603: 
 6604: table.LC_data_table tr > td.LC_roles_expired {
 6605:   border-right: 8px solid #FF7777;
 6606: }
 6607: 
 6608: table.LC_data_table tr > td.LC_roles_will_not {
 6609:   border-right: 8px solid #AAFF77;
 6610: }
 6611: 
 6612: table.LC_data_table tr > td.LC_roles_selected {
 6613:   border-right: 8px solid #11CC55;
 6614: }
 6615: 
 6616: span.LC_current_location {
 6617:   font-size:larger;
 6618:   background: $pgbg;
 6619: }
 6620: 
 6621: span.LC_current_nav_location {
 6622:   font-weight:bold;
 6623:   background: $sidebg;
 6624: }
 6625: 
 6626: span.LC_parm_menu_item {
 6627:   font-size: larger;
 6628: }
 6629: 
 6630: span.LC_parm_scope_all {
 6631:   color: red;
 6632: }
 6633: 
 6634: span.LC_parm_scope_folder {
 6635:   color: green;
 6636: }
 6637: 
 6638: span.LC_parm_scope_resource {
 6639:   color: orange;
 6640: }
 6641: 
 6642: span.LC_parm_part {
 6643:   color: blue;
 6644: }
 6645: 
 6646: span.LC_parm_folder,
 6647: span.LC_parm_symb {
 6648:   font-size: x-small;
 6649:   font-family: $mono;
 6650:   color: #AAAAAA;
 6651: }
 6652: 
 6653: ul.LC_parm_parmlist li {
 6654:   display: inline-block;
 6655:   padding: 0.3em 0.8em;
 6656:   vertical-align: top;
 6657:   width: 150px;
 6658:   border-top:1px solid $lg_border_color;
 6659: }
 6660: 
 6661: td.LC_parm_overview_level_menu,
 6662: td.LC_parm_overview_map_menu,
 6663: td.LC_parm_overview_parm_selectors,
 6664: td.LC_parm_overview_restrictions  {
 6665:   border: 1px solid black;
 6666:   border-collapse: collapse;
 6667: }
 6668: 
 6669: table.LC_parm_overview_restrictions td {
 6670:   border-width: 1px 4px 1px 4px;
 6671:   border-style: solid;
 6672:   border-color: $pgbg;
 6673:   text-align: center;
 6674: }
 6675: 
 6676: table.LC_parm_overview_restrictions th {
 6677:   background: $tabbg;
 6678:   border-width: 1px 4px 1px 4px;
 6679:   border-style: solid;
 6680:   border-color: $pgbg;
 6681: }
 6682: 
 6683: table#LC_helpmenu {
 6684:   border: none;
 6685:   height: 55px;
 6686:   border-spacing: 0;
 6687: }
 6688: 
 6689: table#LC_helpmenu fieldset legend {
 6690:   font-size: larger;
 6691: }
 6692: 
 6693: table#LC_helpmenu_links {
 6694:   width: 100%;
 6695:   border: 1px solid black;
 6696:   background: $pgbg;
 6697:   padding: 0;
 6698:   border-spacing: 1px;
 6699: }
 6700: 
 6701: table#LC_helpmenu_links tr td {
 6702:   padding: 1px;
 6703:   background: $tabbg;
 6704:   text-align: center;
 6705:   font-weight: bold;
 6706: }
 6707: 
 6708: table#LC_helpmenu_links a:link,
 6709: table#LC_helpmenu_links a:visited,
 6710: table#LC_helpmenu_links a:active {
 6711:   text-decoration: none;
 6712:   color: $font;
 6713: }
 6714: 
 6715: table#LC_helpmenu_links a:hover {
 6716:   text-decoration: underline;
 6717:   color: $vlink;
 6718: }
 6719: 
 6720: .LC_chrt_popup_exists {
 6721:   border: 1px solid #339933;
 6722:   margin: -1px;
 6723: }
 6724: 
 6725: .LC_chrt_popup_up {
 6726:   border: 1px solid yellow;
 6727:   margin: -1px;
 6728: }
 6729: 
 6730: .LC_chrt_popup {
 6731:   border: 1px solid #8888FF;
 6732:   background: #CCCCFF;
 6733: }
 6734: 
 6735: table.LC_pick_box {
 6736:   border-collapse: separate;
 6737:   background: white;
 6738:   border: 1px solid black;
 6739:   border-spacing: 1px;
 6740: }
 6741: 
 6742: table.LC_pick_box td.LC_pick_box_title {
 6743:   background: $sidebg;
 6744:   font-weight: bold;
 6745:   text-align: left;
 6746:   vertical-align: top;
 6747:   width: 184px;
 6748:   padding: 8px;
 6749: }
 6750: 
 6751: table.LC_pick_box td.LC_pick_box_value {
 6752:   text-align: left;
 6753:   padding: 8px;
 6754: }
 6755: 
 6756: table.LC_pick_box td.LC_pick_box_select {
 6757:   text-align: left;
 6758:   padding: 8px;
 6759: }
 6760: 
 6761: table.LC_pick_box td.LC_pick_box_separator {
 6762:   padding: 0;
 6763:   height: 1px;
 6764:   background: black;
 6765: }
 6766: 
 6767: table.LC_pick_box td.LC_pick_box_submit {
 6768:   text-align: right;
 6769: }
 6770: 
 6771: table.LC_pick_box td.LC_evenrow_value {
 6772:   text-align: left;
 6773:   padding: 8px;
 6774:   background-color: $data_table_light;
 6775: }
 6776: 
 6777: table.LC_pick_box td.LC_oddrow_value {
 6778:   text-align: left;
 6779:   padding: 8px;
 6780:   background-color: $data_table_light;
 6781: }
 6782: 
 6783: span.LC_helpform_receipt_cat {
 6784:   font-weight: bold;
 6785: }
 6786: 
 6787: table.LC_group_priv_box {
 6788:   background: white;
 6789:   border: 1px solid black;
 6790:   border-spacing: 1px;
 6791: }
 6792: 
 6793: table.LC_group_priv_box td.LC_pick_box_title {
 6794:   background: $tabbg;
 6795:   font-weight: bold;
 6796:   text-align: right;
 6797:   width: 184px;
 6798: }
 6799: 
 6800: table.LC_group_priv_box td.LC_groups_fixed {
 6801:   background: $data_table_light;
 6802:   text-align: center;
 6803: }
 6804: 
 6805: table.LC_group_priv_box td.LC_groups_optional {
 6806:   background: $data_table_dark;
 6807:   text-align: center;
 6808: }
 6809: 
 6810: table.LC_group_priv_box td.LC_groups_functionality {
 6811:   background: $data_table_darker;
 6812:   text-align: center;
 6813:   font-weight: bold;
 6814: }
 6815: 
 6816: table.LC_group_priv td {
 6817:   text-align: left;
 6818:   padding: 0;
 6819: }
 6820: 
 6821: .LC_navbuttons {
 6822:   margin: 2ex 0ex 2ex 0ex;
 6823: }
 6824: 
 6825: .LC_topic_bar {
 6826:   font-weight: bold;
 6827:   background: $tabbg;
 6828:   margin: 1em 0em 1em 2em;
 6829:   padding: 3px;
 6830:   font-size: 1.2em;
 6831: }
 6832: 
 6833: .LC_topic_bar span {
 6834:   left: 0.5em;
 6835:   position: absolute;
 6836:   vertical-align: middle;
 6837:   font-size: 1.2em;
 6838: }
 6839: 
 6840: table.LC_course_group_status {
 6841:   margin: 20px;
 6842: }
 6843: 
 6844: table.LC_status_selector td {
 6845:   vertical-align: top;
 6846:   text-align: center;
 6847:   padding: 4px;
 6848: }
 6849: 
 6850: div.LC_feedback_link {
 6851:   clear: both;
 6852:   background: $sidebg;
 6853:   width: 100%;
 6854:   padding-bottom: 10px;
 6855:   border: 1px $tabbg solid;
 6856:   height: 22px;
 6857:   line-height: 22px;
 6858:   padding-top: 5px;
 6859: }
 6860: 
 6861: div.LC_feedback_link img {
 6862:   height: 22px;
 6863:   vertical-align:middle;
 6864: }
 6865: 
 6866: div.LC_feedback_link a {
 6867:   text-decoration: none;
 6868: }
 6869: 
 6870: div.LC_comblock {
 6871:   display:inline;
 6872:   color:$font;
 6873:   font-size:90%;
 6874: }
 6875: 
 6876: div.LC_feedback_link div.LC_comblock {
 6877:   padding-left:5px;
 6878: }
 6879: 
 6880: div.LC_feedback_link div.LC_comblock a {
 6881:   color:$font;
 6882: }
 6883: 
 6884: span.LC_feedback_link {
 6885:   /* background: $feedback_link_bg; */
 6886:   font-size: larger;
 6887: }
 6888: 
 6889: span.LC_message_link {
 6890:   /* background: $feedback_link_bg; */
 6891:   font-size: larger;
 6892:   position: absolute;
 6893:   right: 1em;
 6894: }
 6895: 
 6896: table.LC_prior_tries {
 6897:   border: 1px solid #000000;
 6898:   border-collapse: separate;
 6899:   border-spacing: 1px;
 6900: }
 6901: 
 6902: table.LC_prior_tries td {
 6903:   padding: 2px;
 6904: }
 6905: 
 6906: .LC_answer_correct {
 6907:   background: lightgreen;
 6908:   color: darkgreen;
 6909:   padding: 6px;
 6910: }
 6911: 
 6912: .LC_answer_charged_try {
 6913:   background: #FFAAAA;
 6914:   color: darkred;
 6915:   padding: 6px;
 6916: }
 6917: 
 6918: .LC_answer_not_charged_try,
 6919: .LC_answer_no_grade,
 6920: .LC_answer_late {
 6921:   background: lightyellow;
 6922:   color: black;
 6923:   padding: 6px;
 6924: }
 6925: 
 6926: .LC_answer_previous {
 6927:   background: lightblue;
 6928:   color: darkblue;
 6929:   padding: 6px;
 6930: }
 6931: 
 6932: .LC_answer_no_message {
 6933:   background: #FFFFFF;
 6934:   color: black;
 6935:   padding: 6px;
 6936: }
 6937: 
 6938: .LC_answer_unknown,
 6939: .LC_answer_warning {
 6940:   background: orange;
 6941:   color: black;
 6942:   padding: 6px;
 6943: }
 6944: 
 6945: span.LC_prior_numerical,
 6946: span.LC_prior_string,
 6947: span.LC_prior_custom,
 6948: span.LC_prior_reaction,
 6949: span.LC_prior_math {
 6950:   font-family: $mono;
 6951:   white-space: pre;
 6952: }
 6953: 
 6954: span.LC_prior_string {
 6955:   font-family: $mono;
 6956:   white-space: pre;
 6957: }
 6958: 
 6959: table.LC_prior_option {
 6960:   width: 100%;
 6961:   border-collapse: collapse;
 6962: }
 6963: 
 6964: table.LC_prior_rank,
 6965: table.LC_prior_match {
 6966:   border-collapse: collapse;
 6967: }
 6968: 
 6969: table.LC_prior_option tr td,
 6970: table.LC_prior_rank tr td,
 6971: table.LC_prior_match tr td {
 6972:   border: 1px solid #000000;
 6973: }
 6974: 
 6975: .LC_nobreak {
 6976:   white-space: nowrap;
 6977: }
 6978: 
 6979: span.LC_cusr_emph {
 6980:   font-style: italic;
 6981: }
 6982: 
 6983: span.LC_cusr_subheading {
 6984:   font-weight: normal;
 6985:   font-size: 85%;
 6986: }
 6987: 
 6988: div.LC_docs_entry_move {
 6989:   border: 1px solid #BBBBBB;
 6990:   background: #DDDDDD;
 6991:   width: 22px;
 6992:   padding: 1px;
 6993:   margin: 0;
 6994: }
 6995: 
 6996: table.LC_data_table tr > td.LC_docs_entry_commands,
 6997: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6998:   font-size: x-small;
 6999: }
 7000: 
 7001: .LC_docs_entry_parameter {
 7002:   white-space: nowrap;
 7003: }
 7004: 
 7005: .LC_docs_copy {
 7006:   color: #000099;
 7007: }
 7008: 
 7009: .LC_docs_cut {
 7010:   color: #550044;
 7011: }
 7012: 
 7013: .LC_docs_rename {
 7014:   color: #009900;
 7015: }
 7016: 
 7017: .LC_docs_remove {
 7018:   color: #990000;
 7019: }
 7020: 
 7021: .LC_domprefs_email,
 7022: .LC_docs_reinit_warn,
 7023: .LC_docs_ext_edit {
 7024:   font-size: x-small;
 7025: }
 7026: 
 7027: table.LC_docs_adddocs td,
 7028: table.LC_docs_adddocs th {
 7029:   border: 1px solid #BBBBBB;
 7030:   padding: 4px;
 7031:   background: #DDDDDD;
 7032: }
 7033: 
 7034: table.LC_sty_begin {
 7035:   background: #BBFFBB;
 7036: }
 7037: 
 7038: table.LC_sty_end {
 7039:   background: #FFBBBB;
 7040: }
 7041: 
 7042: table.LC_double_column {
 7043:   border-width: 0;
 7044:   border-collapse: collapse;
 7045:   width: 100%;
 7046:   padding: 2px;
 7047: }
 7048: 
 7049: table.LC_double_column tr td.LC_left_col {
 7050:   top: 2px;
 7051:   left: 2px;
 7052:   width: 47%;
 7053:   vertical-align: top;
 7054: }
 7055: 
 7056: table.LC_double_column tr td.LC_right_col {
 7057:   top: 2px;
 7058:   right: 2px;
 7059:   width: 47%;
 7060:   vertical-align: top;
 7061: }
 7062: 
 7063: div.LC_left_float {
 7064:   float: left;
 7065:   padding-right: 5%;
 7066:   padding-bottom: 4px;
 7067: }
 7068: 
 7069: div.LC_clear_float_header {
 7070:   padding-bottom: 2px;
 7071: }
 7072: 
 7073: div.LC_clear_float_footer {
 7074:   padding-top: 10px;
 7075:   clear: both;
 7076: }
 7077: 
 7078: div.LC_grade_show_user {
 7079: /*  border-left: 5px solid $sidebg; */
 7080:   border-top: 5px solid #000000;
 7081:   margin: 50px 0 0 0;
 7082:   padding: 15px 0 5px 10px;
 7083: }
 7084: 
 7085: div.LC_grade_show_user_odd_row {
 7086: /*  border-left: 5px solid #000000; */
 7087: }
 7088: 
 7089: div.LC_grade_show_user div.LC_Box {
 7090:   margin-right: 50px;
 7091: }
 7092: 
 7093: div.LC_grade_submissions,
 7094: div.LC_grade_message_center,
 7095: div.LC_grade_info_links {
 7096:   margin: 5px;
 7097:   width: 99%;
 7098:   background: #FFFFFF;
 7099: }
 7100: 
 7101: div.LC_grade_submissions_header,
 7102: div.LC_grade_message_center_header {
 7103:   font-weight: bold;
 7104:   font-size: large;
 7105: }
 7106: 
 7107: div.LC_grade_submissions_body,
 7108: div.LC_grade_message_center_body {
 7109:   border: 1px solid black;
 7110:   width: 99%;
 7111:   background: #FFFFFF;
 7112: }
 7113: 
 7114: table.LC_scantron_action {
 7115:   width: 100%;
 7116: }
 7117: 
 7118: table.LC_scantron_action tr th {
 7119:   font-weight:bold;
 7120:   font-style:normal;
 7121: }
 7122: 
 7123: .LC_edit_problem_header,
 7124: div.LC_edit_problem_footer {
 7125:   font-weight: normal;
 7126:   font-size:  medium;
 7127:   margin: 2px;
 7128:   background-color: $sidebg;
 7129: }
 7130: 
 7131: div.LC_edit_problem_header,
 7132: div.LC_edit_problem_header div,
 7133: div.LC_edit_problem_footer,
 7134: div.LC_edit_problem_footer div,
 7135: div.LC_edit_problem_editxml_header,
 7136: div.LC_edit_problem_editxml_header div {
 7137:   z-index: 100;
 7138: }
 7139: 
 7140: div.LC_edit_problem_header_title {
 7141:   font-weight: bold;
 7142:   font-size: larger;
 7143:   background: $tabbg;
 7144:   padding: 3px;
 7145:   margin: 0 0 5px 0;
 7146: }
 7147: 
 7148: table.LC_edit_problem_header_title {
 7149:   width: 100%;
 7150:   background: $tabbg;
 7151: }
 7152: 
 7153: div.LC_edit_actionbar {
 7154:     background-color: $sidebg;
 7155:     margin: 0;
 7156:     padding: 0;
 7157:     line-height: 200%;
 7158: }
 7159: 
 7160: div.LC_edit_actionbar div{
 7161:     padding: 0;
 7162:     margin: 0;
 7163:     display: inline-block;
 7164: }
 7165: 
 7166: .LC_edit_opt {
 7167:   padding-left: 1em;
 7168:   white-space: nowrap;
 7169: }
 7170: 
 7171: .LC_edit_problem_latexhelper{
 7172:     text-align: right;
 7173: }
 7174: 
 7175: #LC_edit_problem_colorful div{
 7176:     margin-left: 40px;
 7177: }
 7178: 
 7179: #LC_edit_problem_codemirror div{
 7180:     margin-left: 0px;
 7181: }
 7182: 
 7183: img.stift {
 7184:   border-width: 0;
 7185:   vertical-align: middle;
 7186: }
 7187: 
 7188: table td.LC_mainmenu_col_fieldset {
 7189:   vertical-align: top;
 7190: }
 7191: 
 7192: div.LC_createcourse {
 7193:   margin: 10px 10px 10px 10px;
 7194: }
 7195: 
 7196: .LC_dccid {
 7197:   float: right;
 7198:   margin: 0.2em 0 0 0;
 7199:   padding: 0;
 7200:   font-size: 90%;
 7201:   display:none;
 7202: }
 7203: 
 7204: ol.LC_primary_menu a:hover,
 7205: ol#LC_MenuBreadcrumbs a:hover,
 7206: ol#LC_PathBreadcrumbs a:hover,
 7207: ul#LC_secondary_menu a:hover,
 7208: .LC_FormSectionClearButton input:hover
 7209: ul.LC_TabContent   li:hover a {
 7210:   color:$button_hover;
 7211:   text-decoration:none;
 7212: }
 7213: 
 7214: h1 {
 7215:   padding: 0;
 7216:   line-height:130%;
 7217: }
 7218: 
 7219: h2,
 7220: h3,
 7221: h4,
 7222: h5,
 7223: h6 {
 7224:   margin: 5px 0 5px 0;
 7225:   padding: 0;
 7226:   line-height:130%;
 7227: }
 7228: 
 7229: .LC_hcell {
 7230:   padding:3px 15px 3px 15px;
 7231:   margin: 0;
 7232:   background-color:$tabbg;
 7233:   color:$fontmenu;
 7234:   border-bottom:solid 1px $lg_border_color;
 7235: }
 7236: 
 7237: .LC_Box > .LC_hcell {
 7238:   margin: 0 -10px 10px -10px;
 7239: }
 7240: 
 7241: .LC_noBorder {
 7242:   border: 0;
 7243: }
 7244: 
 7245: .LC_FormSectionClearButton input {
 7246:   background-color:transparent;
 7247:   border: none;
 7248:   cursor:pointer;
 7249:   text-decoration:underline;
 7250: }
 7251: 
 7252: .LC_help_open_topic {
 7253:   color: #FFFFFF;
 7254:   background-color: #EEEEFF;
 7255:   margin: 1px;
 7256:   padding: 4px;
 7257:   border: 1px solid #000033;
 7258:   white-space: nowrap;
 7259:   /* vertical-align: middle; */
 7260: }
 7261: 
 7262: dl,
 7263: ul,
 7264: div,
 7265: fieldset {
 7266:   margin: 10px 10px 10px 0;
 7267:   /* overflow: hidden; */
 7268: }
 7269: 
 7270: article.geogebraweb div {
 7271:     margin: 0;
 7272: }
 7273: 
 7274: fieldset > legend {
 7275:   font-weight: bold;
 7276:   padding: 0 5px 0 5px;
 7277: }
 7278: 
 7279: #LC_nav_bar {
 7280:   float: left;
 7281:   background-color: $pgbg_or_bgcolor;
 7282:   margin: 0 0 2px 0;
 7283: }
 7284: 
 7285: #LC_realm {
 7286:   margin: 0.2em 0 0 0;
 7287:   padding: 0;
 7288:   font-weight: bold;
 7289:   text-align: center;
 7290:   background-color: $pgbg_or_bgcolor;
 7291: }
 7292: 
 7293: #LC_nav_bar em {
 7294:   font-weight: bold;
 7295:   font-style: normal;
 7296: }
 7297: 
 7298: ol.LC_primary_menu {
 7299:   margin: 0;
 7300:   padding: 0;
 7301: }
 7302: 
 7303: ol#LC_PathBreadcrumbs {
 7304:   margin: 0;
 7305: }
 7306: 
 7307: ol.LC_primary_menu li {
 7308:   color: RGB(80, 80, 80);
 7309:   vertical-align: middle;
 7310:   text-align: left;
 7311:   list-style: none;
 7312:   position: relative;
 7313:   float: left;
 7314:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7315:   line-height: 1.5em;
 7316: }
 7317: 
 7318: ol.LC_primary_menu li a, 
 7319: ol.LC_primary_menu li p {
 7320:   display: block;
 7321:   margin: 0;
 7322:   padding: 0 5px 0 10px;
 7323:   text-decoration: none;
 7324: }
 7325: 
 7326: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7327:   display: inline-block;
 7328:   width: 95%;
 7329:   text-align: left;
 7330: }
 7331: 
 7332: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7333:   display: inline-block;
 7334:   width: 5%;
 7335:   float: right;
 7336:   text-align: right;
 7337:   font-size: 70%;
 7338: }
 7339: 
 7340: ol.LC_primary_menu ul {
 7341:   display: none;
 7342:   width: 15em;
 7343:   background-color: $data_table_light;
 7344:   position: absolute;
 7345:   top: 100%;
 7346: }
 7347: 
 7348: ol.LC_primary_menu ul ul {
 7349:   left: 100%;
 7350:   top: 0;
 7351: }
 7352: 
 7353: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7354:   display: block;
 7355:   position: absolute;
 7356:   margin: 0;
 7357:   padding: 0;
 7358:   z-index: 2;
 7359: }
 7360: 
 7361: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7362: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7363:   font-size: 90%;
 7364:   vertical-align: top;
 7365:   float: none;
 7366:   border-left: 1px solid black;
 7367:   border-right: 1px solid black;
 7368: /* A dark bottom border to visualize different menu options;
 7369: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7370:   border-bottom: 1px solid $data_table_dark;
 7371: }
 7372: 
 7373: ol.LC_primary_menu li li p:hover {
 7374:   color:$button_hover;
 7375:   text-decoration:none;
 7376:   background-color:$data_table_dark;
 7377: }
 7378: 
 7379: ol.LC_primary_menu li li a:hover {
 7380:    color:$button_hover;
 7381:    background-color:$data_table_dark;
 7382: }
 7383: 
 7384: /* Font-size equal to the size of the predecessors*/
 7385: ol.LC_primary_menu li:hover li li {
 7386:   font-size: 100%;
 7387: }
 7388: 
 7389: ol.LC_primary_menu li img {
 7390:   vertical-align: bottom;
 7391:   height: 1.1em;
 7392:   margin: 0.2em 0 0 0;
 7393: }
 7394: 
 7395: ol.LC_primary_menu a {
 7396:   color: RGB(80, 80, 80);
 7397:   text-decoration: none;
 7398: }
 7399: 
 7400: ol.LC_primary_menu a.LC_new_message {
 7401:   font-weight:bold;
 7402:   color: darkred;
 7403: }
 7404: 
 7405: ol.LC_docs_parameters {
 7406:   margin-left: 0;
 7407:   padding: 0;
 7408:   list-style: none;
 7409: }
 7410: 
 7411: ol.LC_docs_parameters li {
 7412:   margin: 0;
 7413:   padding-right: 20px;
 7414:   display: inline;
 7415: }
 7416: 
 7417: ol.LC_docs_parameters li:before {
 7418:   content: "\\002022 \\0020";
 7419: }
 7420: 
 7421: li.LC_docs_parameters_title {
 7422:   font-weight: bold;
 7423: }
 7424: 
 7425: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7426:   content: "";
 7427: }
 7428: 
 7429: ul#LC_secondary_menu {
 7430:   clear: right;
 7431:   color: $fontmenu;
 7432:   background: $tabbg;
 7433:   list-style: none;
 7434:   padding: 0;
 7435:   margin: 0;
 7436:   width: 100%;
 7437:   text-align: left;
 7438:   float: left;
 7439: }
 7440: 
 7441: ul#LC_secondary_menu li {
 7442:   font-weight: bold;
 7443:   line-height: 1.8em;
 7444:   border-right: 1px solid black;
 7445:   float: left;
 7446: }
 7447: 
 7448: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7449:   background-color: $data_table_light;
 7450: }
 7451: 
 7452: ul#LC_secondary_menu li a {
 7453:   padding: 0 0.8em;
 7454: }
 7455: 
 7456: ul#LC_secondary_menu li ul {
 7457:   display: none;
 7458: }
 7459: 
 7460: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7461:   display: block;
 7462:   position: absolute;
 7463:   margin: 0;
 7464:   padding: 0;
 7465:   list-style:none;
 7466:   float: none;
 7467:   background-color: $data_table_light;
 7468:   z-index: 2;
 7469:   margin-left: -1px;
 7470: }
 7471: 
 7472: ul#LC_secondary_menu li ul li {
 7473:   font-size: 90%;
 7474:   vertical-align: top;
 7475:   border-left: 1px solid black;
 7476:   border-right: 1px solid black;
 7477:   background-color: $data_table_light;
 7478:   list-style:none;
 7479:   float: none;
 7480: }
 7481: 
 7482: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7483:   background-color: $data_table_dark;
 7484: }
 7485: 
 7486: ul.LC_TabContent {
 7487:   display:block;
 7488:   background: $sidebg;
 7489:   border-bottom: solid 1px $lg_border_color;
 7490:   list-style:none;
 7491:   margin: -1px -10px 0 -10px;
 7492:   padding: 0;
 7493: }
 7494: 
 7495: ul.LC_TabContent li,
 7496: ul.LC_TabContentBigger li {
 7497:   float:left;
 7498: }
 7499: 
 7500: ul#LC_secondary_menu li a {
 7501:   color: $fontmenu;
 7502:   text-decoration: none;
 7503: }
 7504: 
 7505: ul.LC_TabContent {
 7506:   min-height:20px;
 7507: }
 7508: 
 7509: ul.LC_TabContent li {
 7510:   vertical-align:middle;
 7511:   padding: 0 16px 0 10px;
 7512:   background-color:$tabbg;
 7513:   border-bottom:solid 1px $lg_border_color;
 7514:   border-left: solid 1px $font;
 7515: }
 7516: 
 7517: ul.LC_TabContent .right {
 7518:   float:right;
 7519: }
 7520: 
 7521: ul.LC_TabContent li a,
 7522: ul.LC_TabContent li {
 7523:   color:rgb(47,47,47);
 7524:   text-decoration:none;
 7525:   font-size:95%;
 7526:   font-weight:bold;
 7527:   min-height:20px;
 7528: }
 7529: 
 7530: ul.LC_TabContent li a:hover,
 7531: ul.LC_TabContent li a:focus {
 7532:   color: $button_hover;
 7533:   background:none;
 7534:   outline:none;
 7535: }
 7536: 
 7537: ul.LC_TabContent li:hover {
 7538:   color: $button_hover;
 7539:   cursor:pointer;
 7540: }
 7541: 
 7542: ul.LC_TabContent li.active {
 7543:   color: $font;
 7544:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7545:   border-bottom:solid 1px #FFFFFF;
 7546:   cursor: default;
 7547: }
 7548: 
 7549: ul.LC_TabContent li.active a {
 7550:   color:$font;
 7551:   background:#FFFFFF;
 7552:   outline: none;
 7553: }
 7554: 
 7555: ul.LC_TabContent li.goback {
 7556:   float: left;
 7557:   border-left: none;
 7558: }
 7559: 
 7560: #maincoursedoc {
 7561:   clear:both;
 7562: }
 7563: 
 7564: ul.LC_TabContentBigger {
 7565:   display:block;
 7566:   list-style:none;
 7567:   padding: 0;
 7568: }
 7569: 
 7570: ul.LC_TabContentBigger li {
 7571:   vertical-align:bottom;
 7572:   height: 30px;
 7573:   font-size:110%;
 7574:   font-weight:bold;
 7575:   color: #737373;
 7576: }
 7577: 
 7578: ul.LC_TabContentBigger li.active {
 7579:   position: relative;
 7580:   top: 1px;
 7581: }
 7582: 
 7583: ul.LC_TabContentBigger li a {
 7584:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7585:   height: 30px;
 7586:   line-height: 30px;
 7587:   text-align: center;
 7588:   display: block;
 7589:   text-decoration: none;
 7590:   outline: none;  
 7591: }
 7592: 
 7593: ul.LC_TabContentBigger li.active a {
 7594:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7595:   color:$font;
 7596: }
 7597: 
 7598: ul.LC_TabContentBigger li b {
 7599:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7600:   display: block;
 7601:   float: left;
 7602:   padding: 0 30px;
 7603:   border-bottom: 1px solid $lg_border_color;
 7604: }
 7605: 
 7606: ul.LC_TabContentBigger li:hover b {
 7607:   color:$button_hover;
 7608: }
 7609: 
 7610: ul.LC_TabContentBigger li.active b {
 7611:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7612:   color:$font;
 7613:   border: 0;
 7614: }
 7615: 
 7616: 
 7617: ul.LC_CourseBreadcrumbs {
 7618:   background: $sidebg;
 7619:   height: 2em;
 7620:   padding-left: 10px;
 7621:   margin: 0;
 7622:   list-style-position: inside;
 7623: }
 7624: 
 7625: ol#LC_MenuBreadcrumbs,
 7626: ol#LC_PathBreadcrumbs {
 7627:   padding-left: 10px;
 7628:   margin: 0;
 7629:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7630: }
 7631: 
 7632: ol#LC_MenuBreadcrumbs li,
 7633: ol#LC_PathBreadcrumbs li,
 7634: ul.LC_CourseBreadcrumbs li {
 7635:   display: inline;
 7636:   white-space: normal;  
 7637: }
 7638: 
 7639: ol#LC_MenuBreadcrumbs li a,
 7640: ul.LC_CourseBreadcrumbs li a {
 7641:   text-decoration: none;
 7642:   font-size:90%;
 7643: }
 7644: 
 7645: ol#LC_MenuBreadcrumbs h1 {
 7646:   display: inline;
 7647:   font-size: 90%;
 7648:   line-height: 2.5em;
 7649:   margin: 0;
 7650:   padding: 0;
 7651: }
 7652: 
 7653: ol#LC_PathBreadcrumbs li a {
 7654:   text-decoration:none;
 7655:   font-size:100%;
 7656:   font-weight:bold;
 7657: }
 7658: 
 7659: .LC_Box {
 7660:   border: solid 1px $lg_border_color;
 7661:   padding: 0 10px 10px 10px;
 7662: }
 7663: 
 7664: .LC_DocsBox {
 7665:   border: solid 1px $lg_border_color;
 7666:   padding: 0 0 10px 10px;
 7667: }
 7668: 
 7669: .LC_AboutMe_Image {
 7670:   float:left;
 7671:   margin-right:10px;
 7672: }
 7673: 
 7674: .LC_Clear_AboutMe_Image {
 7675:   clear:left;
 7676: }
 7677: 
 7678: dl.LC_ListStyleClean dt {
 7679:   padding-right: 5px;
 7680:   display: table-header-group;
 7681: }
 7682: 
 7683: dl.LC_ListStyleClean dd {
 7684:   display: table-row;
 7685: }
 7686: 
 7687: .LC_ListStyleClean,
 7688: .LC_ListStyleSimple,
 7689: .LC_ListStyleNormal,
 7690: .LC_ListStyleSpecial {
 7691:   /* display:block; */
 7692:   list-style-position: inside;
 7693:   list-style-type: none;
 7694:   overflow: hidden;
 7695:   padding: 0;
 7696: }
 7697: 
 7698: .LC_ListStyleSimple li,
 7699: .LC_ListStyleSimple dd,
 7700: .LC_ListStyleNormal li,
 7701: .LC_ListStyleNormal dd,
 7702: .LC_ListStyleSpecial li,
 7703: .LC_ListStyleSpecial dd {
 7704:   margin: 0;
 7705:   padding: 5px 5px 5px 10px;
 7706:   clear: both;
 7707: }
 7708: 
 7709: .LC_ListStyleClean li,
 7710: .LC_ListStyleClean dd {
 7711:   padding-top: 0;
 7712:   padding-bottom: 0;
 7713: }
 7714: 
 7715: .LC_ListStyleSimple dd,
 7716: .LC_ListStyleSimple li {
 7717:   border-bottom: solid 1px $lg_border_color;
 7718: }
 7719: 
 7720: .LC_ListStyleSpecial li,
 7721: .LC_ListStyleSpecial dd {
 7722:   list-style-type: none;
 7723:   background-color: RGB(220, 220, 220);
 7724:   margin-bottom: 4px;
 7725: }
 7726: 
 7727: table.LC_SimpleTable {
 7728:   margin:5px;
 7729:   border:solid 1px $lg_border_color;
 7730: }
 7731: 
 7732: table.LC_SimpleTable tr {
 7733:   padding: 0;
 7734:   border:solid 1px $lg_border_color;
 7735: }
 7736: 
 7737: table.LC_SimpleTable thead {
 7738:   background:rgb(220,220,220);
 7739: }
 7740: 
 7741: div.LC_columnSection {
 7742:   display: block;
 7743:   clear: both;
 7744:   overflow: hidden;
 7745:   margin: 0;
 7746: }
 7747: 
 7748: div.LC_columnSection>* {
 7749:   float: left;
 7750:   margin: 10px 20px 10px 0;
 7751:   overflow:hidden;
 7752: }
 7753: 
 7754: table em {
 7755:   font-weight: bold;
 7756:   font-style: normal;
 7757: }
 7758: 
 7759: table.LC_tableBrowseRes,
 7760: table.LC_tableOfContent {
 7761:   border:none;
 7762:   border-spacing: 1px;
 7763:   padding: 3px;
 7764:   background-color: #FFFFFF;
 7765:   font-size: 90%;
 7766: }
 7767: 
 7768: table.LC_tableOfContent {
 7769:   border-collapse: collapse;
 7770: }
 7771: 
 7772: table.LC_tableBrowseRes a,
 7773: table.LC_tableOfContent a {
 7774:   background-color: transparent;
 7775:   text-decoration: none;
 7776: }
 7777: 
 7778: table.LC_tableOfContent img {
 7779:   border: none;
 7780:   height: 1.3em;
 7781:   vertical-align: text-bottom;
 7782:   margin-right: 0.3em;
 7783: }
 7784: 
 7785: a#LC_content_toolbar_firsthomework {
 7786:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7787: }
 7788: 
 7789: a#LC_content_toolbar_everything {
 7790:   background-image:url(/res/adm/pages/show-all.gif);
 7791: }
 7792: 
 7793: a#LC_content_toolbar_uncompleted {
 7794:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7795: }
 7796: 
 7797: #LC_content_toolbar_clearbubbles {
 7798:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7799: }
 7800: 
 7801: a#LC_content_toolbar_changefolder {
 7802:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7803: }
 7804: 
 7805: a#LC_content_toolbar_changefolder_toggled {
 7806:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7807: }
 7808: 
 7809: a#LC_content_toolbar_edittoplevel {
 7810:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7811: }
 7812: 
 7813: ul#LC_toolbar li a:hover {
 7814:   background-position: bottom center;
 7815: }
 7816: 
 7817: ul#LC_toolbar {
 7818:   padding: 0;
 7819:   margin: 2px;
 7820:   list-style:none;
 7821:   position:relative;
 7822:   background-color:white;
 7823:   overflow: auto;
 7824: }
 7825: 
 7826: ul#LC_toolbar li {
 7827:   border:1px solid white;
 7828:   padding: 0;
 7829:   margin: 0;
 7830:   float: left;
 7831:   display:inline;
 7832:   vertical-align:middle;
 7833:   white-space: nowrap;
 7834: }
 7835: 
 7836: 
 7837: a.LC_toolbarItem {
 7838:   display:block;
 7839:   padding: 0;
 7840:   margin: 0;
 7841:   height: 32px;
 7842:   width: 32px;
 7843:   color:white;
 7844:   border: none;
 7845:   background-repeat:no-repeat;
 7846:   background-color:transparent;
 7847: }
 7848: 
 7849: ul.LC_funclist {
 7850:     margin: 0;
 7851:     padding: 0.5em 1em 0.5em 0;
 7852: }
 7853: 
 7854: ul.LC_funclist > li:first-child {
 7855:     font-weight:bold; 
 7856:     margin-left:0.8em;
 7857: }
 7858: 
 7859: ul.LC_funclist + ul.LC_funclist {
 7860:     /* 
 7861:        left border as a seperator if we have more than
 7862:        one list 
 7863:     */
 7864:     border-left: 1px solid $sidebg;
 7865:     /* 
 7866:        this hides the left border behind the border of the 
 7867:        outer box if element is wrapped to the next 'line' 
 7868:     */
 7869:     margin-left: -1px;
 7870: }
 7871: 
 7872: ul.LC_funclist li {
 7873:   display: inline;
 7874:   white-space: nowrap;
 7875:   margin: 0 0 0 25px;
 7876:   line-height: 150%;
 7877: }
 7878: 
 7879: .LC_hidden {
 7880:   display: none;
 7881: }
 7882: 
 7883: .LCmodal-overlay {
 7884: 		position:fixed;
 7885: 		top:0;
 7886: 		right:0;
 7887: 		bottom:0;
 7888: 		left:0;
 7889: 		height:100%;
 7890: 		width:100%;
 7891: 		margin:0;
 7892: 		padding:0;
 7893: 		background:#999;
 7894: 		opacity:.75;
 7895: 		filter: alpha(opacity=75);
 7896: 		-moz-opacity: 0.75;
 7897: 		z-index:101;
 7898: }
 7899: 
 7900: * html .LCmodal-overlay {   
 7901: 		position: absolute;
 7902: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7903: }
 7904: 
 7905: .LCmodal-window {
 7906: 		position:fixed;
 7907: 		top:50%;
 7908: 		left:50%;
 7909: 		margin:0;
 7910: 		padding:0;
 7911: 		z-index:102;
 7912: 	}
 7913: 
 7914: * html .LCmodal-window {
 7915: 		position:absolute;
 7916: }
 7917: 
 7918: .LCclose-window {
 7919: 		position:absolute;
 7920: 		width:32px;
 7921: 		height:32px;
 7922: 		right:8px;
 7923: 		top:8px;
 7924: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7925: 		text-indent:-99999px;
 7926: 		overflow:hidden;
 7927: 		cursor:pointer;
 7928: }
 7929: 
 7930: .LCisDisabled {
 7931:   cursor: not-allowed;
 7932:   opacity: 0.5;
 7933: }
 7934: 
 7935: a[aria-disabled="true"] {
 7936:   color: currentColor;
 7937:   display: inline-block;  /* For IE11/ MS Edge bug */
 7938:   pointer-events: none;
 7939:   text-decoration: none;
 7940: }
 7941: 
 7942: pre.LC_wordwrap {
 7943:   white-space: pre-wrap;
 7944:   white-space: -moz-pre-wrap;
 7945:   white-space: -pre-wrap;
 7946:   white-space: -o-pre-wrap;
 7947:   word-wrap: break-word;
 7948: }
 7949: 
 7950: /*
 7951:   styles used by TTH when "Default set of options to pass to tth/m
 7952:   when converting TeX" in course settings has been set
 7953: 
 7954:   option passed: -t
 7955: 
 7956: */
 7957: 
 7958: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7959: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7960: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7961: td div.norm {line-height:normal;}
 7962: 
 7963: /*
 7964:   option passed -y3
 7965: */
 7966: 
 7967: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7968: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7969: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7970: 
 7971: #LC_minitab_header {
 7972:   float:left;
 7973:   width:100%;
 7974:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 7975:   font-size:93%;
 7976:   line-height:normal;
 7977:   margin: 0.5em 0 0.5em 0;
 7978: }
 7979: #LC_minitab_header ul {
 7980:   margin:0;
 7981:   padding:10px 10px 0;
 7982:   list-style:none;
 7983: }
 7984: #LC_minitab_header li {
 7985:   float:left;
 7986:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 7987:   margin:0;
 7988:   padding:0 0 0 9px;
 7989: }
 7990: #LC_minitab_header a {
 7991:   display:block;
 7992:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 7993:   padding:5px 15px 4px 6px;
 7994: }
 7995: #LC_minitab_header #LC_current_minitab {
 7996:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 7997: }
 7998: #LC_minitab_header #LC_current_minitab a {
 7999:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8000:   padding-bottom:5px;
 8001: }
 8002: 
 8003: 
 8004: END
 8005: }
 8006: 
 8007: =pod
 8008: 
 8009: =item * &headtag()
 8010: 
 8011: Returns a uniform footer for LON-CAPA web pages.
 8012: 
 8013: Inputs: $title - optional title for the head
 8014:         $head_extra - optional extra HTML to put inside the <head>
 8015:         $args - optional arguments
 8016:             force_register - if is true call registerurl so the remote is 
 8017:                              informed
 8018:             redirect       -> array ref of
 8019:                                    1- seconds before redirect occurs
 8020:                                    2- url to redirect to
 8021:                                    3- whether the side effect should occur
 8022:                            (side effect of setting 
 8023:                                $env{'internal.head.redirect'} to the url 
 8024:                                redirected too)
 8025:             domain         -> force to color decorate a page for a specific
 8026:                                domain
 8027:             function       -> force usage of a specific rolish color scheme
 8028:             bgcolor        -> override the default page bgcolor
 8029:             no_auto_mt_title
 8030:                            -> prevent &mt()ing the title arg
 8031: 
 8032: =cut
 8033: 
 8034: sub headtag {
 8035:     my ($title,$head_extra,$args) = @_;
 8036:     
 8037:     my $function = $args->{'function'} || &get_users_function();
 8038:     my $domain   = $args->{'domain'}   || &determinedomain();
 8039:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8040:     my $httphost = $args->{'use_absolute'};
 8041:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8042: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8043: 		   #time(),
 8044: 		   $env{'environment.color.timestamp'},
 8045: 		   $function,$domain,$bgcolor);
 8046: 
 8047:     $url = '/adm/css/'.&escape($url).'.css';
 8048: 
 8049:     my $result =
 8050: 	'<head>'.
 8051: 	&font_settings($args);
 8052: 
 8053:     my $inhibitprint;
 8054:     if ($args->{'print_suppress'}) {
 8055:         $inhibitprint = &print_suppression();
 8056:     }
 8057: 
 8058:     if (!$args->{'frameset'}) {
 8059: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8060:     }
 8061:     if ($args->{'force_register'}) {
 8062:         $result .= &Apache::lonmenu::registerurl(1);
 8063:     }
 8064:     if (!$args->{'no_nav_bar'} 
 8065: 	&& !$args->{'only_body'}
 8066: 	&& !$args->{'frameset'}) {
 8067: 	$result .= &help_menu_js($httphost);
 8068:         $result.=&modal_window();
 8069:         $result.=&togglebox_script();
 8070:         $result.=&wishlist_window();
 8071:         $result.=&LCprogressbarUpdate_script();
 8072:     } else {
 8073:         if ($args->{'add_modal'}) {
 8074:            $result.=&modal_window();
 8075:         }
 8076:         if ($args->{'add_wishlist'}) {
 8077:            $result.=&wishlist_window();
 8078:         }
 8079:         if ($args->{'add_togglebox'}) {
 8080:            $result.=&togglebox_script();
 8081:         }
 8082:         if ($args->{'add_progressbar'}) {
 8083:            $result.=&LCprogressbarUpdate_script();
 8084:         }
 8085:     }
 8086:     if (ref($args->{'redirect'})) {
 8087: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8088: 	$url = &Apache::lonenc::check_encrypt($url);
 8089: 	if (!$inhibit_continue) {
 8090: 	    $env{'internal.head.redirect'} = $url;
 8091: 	}
 8092: 	$result.=<<ADDMETA
 8093: <meta http-equiv="pragma" content="no-cache" />
 8094: <meta http-equiv="Refresh" content="$time; url=$url" />
 8095: ADDMETA
 8096:     } else {
 8097:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8098:             my $requrl = $env{'request.uri'};
 8099:             if ($requrl eq '') {
 8100:                 $requrl = $ENV{'REQUEST_URI'};
 8101:                 $requrl =~ s/\?.+$//;
 8102:             }
 8103:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8104:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8105:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8106:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8107:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8108:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8109:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8110:                     my ($offload,$offloadoth);
 8111:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8112:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8113:                             $offload = 1;
 8114:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8115:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8116:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8117:                                     $offloadoth = 1;
 8118:                                     $dom_in_use = $env{'user.domain'};
 8119:                                 }
 8120:                             }
 8121:                         }
 8122:                     }
 8123:                     unless ($offload) {
 8124:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 8125:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 8126:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8127:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8128:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8129:                                         $offload = 1;
 8130:                                         $offloadoth = 1;
 8131:                                         $dom_in_use = $env{'user.domain'};
 8132:                                     }
 8133:                                 }
 8134:                             }
 8135:                         }
 8136:                     }
 8137:                     if ($offload) {
 8138:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 8139:                         if (($newserver eq '') && ($offloadoth)) {
 8140:                             my @domains = &Apache::lonnet::current_machine_domains();
 8141:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 8142:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 8143:                             }
 8144:                         }
 8145:                         if (($newserver) && ($newserver ne $lonhost)) {
 8146:                             my $numsec = 5;
 8147:                             my $timeout = $numsec * 1000;
 8148:                             my ($newurl,$locknum,%locks,$msg);
 8149:                             if ($env{'request.role.adv'}) {
 8150:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 8151:                             }
 8152:                             my $disable_submit = 0;
 8153:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 8154:                                 $disable_submit = 1;
 8155:                             }
 8156:                             if ($locknum) {
 8157:                                 my @lockinfo = sort(values(%locks));
 8158:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 8159:                                        join(", ",sort(values(%locks)))."\n";
 8160:                                 if (&show_course()) {
 8161:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 8162:                                 } else {
 8163:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 8164:                                 }
 8165:                             } else {
 8166:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8167:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 8168:                                 }
 8169:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8170:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 8171:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8172:                                     $newurl .= '&role='.$env{'request.role'};
 8173:                                 }
 8174:                                 if ($env{'request.symb'}) {
 8175:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 8176:                                     if ($shownsymb =~ m{^/enc/}) {
 8177:                                         my $reqdmajor = 2;
 8178:                                         my $reqdminor = 11;
 8179:                                         my $reqdsubminor = 3;
 8180:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 8181:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 8182:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 8183:                                         if (($major eq '' && $minor eq '') ||
 8184:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 8185:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 8186:                                              ($reqdsubminor > $subminor))))) {
 8187:                                             undef($shownsymb);
 8188:                                         }
 8189:                                     }
 8190:                                     if ($shownsymb) {
 8191:                                         &js_escape(\$shownsymb);
 8192:                                         $newurl .= '&symb='.$shownsymb;
 8193:                                     }
 8194:                                 } else {
 8195:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 8196:                                     &js_escape(\$shownurl);
 8197:                                     $newurl .= '&origurl='.$shownurl;
 8198:                                 }
 8199:                             }
 8200:                             &js_escape(\$msg);
 8201:                             $result.=<<OFFLOAD
 8202: <meta http-equiv="pragma" content="no-cache" />
 8203: <script type="text/javascript">
 8204: // <![CDATA[
 8205: function LC_Offload_Now() {
 8206:     var dest = "$newurl";
 8207:     if (dest != '') {
 8208:         window.location.href="$newurl";
 8209:     }
 8210: }
 8211: \$(document).ready(function () {
 8212:     window.alert('$msg');
 8213:     if ($disable_submit) {
 8214:         \$(".LC_hwk_submit").prop("disabled", true);
 8215:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8216:     }
 8217:     setTimeout('LC_Offload_Now()', $timeout);
 8218: });
 8219: // ]]>
 8220: </script>
 8221: OFFLOAD
 8222:                         }
 8223:                     }
 8224:                 }
 8225:             }
 8226:         }
 8227:     }
 8228:     if (!defined($title)) {
 8229: 	$title = 'The LearningOnline Network with CAPA';
 8230:     }
 8231:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8232:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8233: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8234:     if (!$args->{'frameset'}) {
 8235:         $result .= ' /';
 8236:     }
 8237:     $result .= '>'
 8238:         .$inhibitprint
 8239: 	.$head_extra;
 8240:     my $clientmobile;
 8241:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8242:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8243:     } else {
 8244:         $clientmobile = $env{'browser.mobile'};
 8245:     }
 8246:     if ($clientmobile) {
 8247:         $result .= '
 8248: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8249: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8250:     }
 8251:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8252:     return $result.'</head>';
 8253: }
 8254: 
 8255: =pod
 8256: 
 8257: =item * &font_settings()
 8258: 
 8259: Returns neccessary <meta> to set the proper encoding
 8260: 
 8261: Inputs: optional reference to HASH -- $args passed to &headtag()
 8262: 
 8263: =cut
 8264: 
 8265: sub font_settings {
 8266:     my ($args) = @_;
 8267:     my $headerstring='';
 8268:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8269:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8270: 	$headerstring.=
 8271: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8272:         if (!$args->{'frameset'}) {
 8273:             $headerstring.= ' /';
 8274:         }
 8275:         $headerstring .= '>'."\n";
 8276:     }
 8277:     return $headerstring;
 8278: }
 8279: 
 8280: =pod
 8281: 
 8282: =item * &print_suppression()
 8283: 
 8284: In course context returns css which causes the body to be blank when media="print",
 8285: if printout generation is unavailable for the current resource.
 8286: 
 8287: This could be because:
 8288: 
 8289: (a) printstartdate is in the future
 8290: 
 8291: (b) printenddate is in the past
 8292: 
 8293: (c) there is an active exam block with "printout"
 8294: functionality blocked
 8295: 
 8296: Users with pav, pfo or evb privileges are exempt.
 8297: 
 8298: Inputs: none
 8299: 
 8300: =cut
 8301: 
 8302: 
 8303: sub print_suppression {
 8304:     my $noprint;
 8305:     if ($env{'request.course.id'}) {
 8306:         my $scope = $env{'request.course.id'};
 8307:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8308:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8309:             return;
 8310:         }
 8311:         if ($env{'request.course.sec'} ne '') {
 8312:             $scope .= "/$env{'request.course.sec'}";
 8313:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8314:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8315:                 return;
 8316:             }
 8317:         }
 8318:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8319:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8320:         my $clientip = &Apache::lonnet::get_requestor_ip();
 8321:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 8322:         if ($blocked) {
 8323:             my $checkrole = "cm./$cdom/$cnum";
 8324:             if ($env{'request.course.sec'} ne '') {
 8325:                 $checkrole .= "/$env{'request.course.sec'}";
 8326:             }
 8327:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8328:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8329:                 $noprint = 1;
 8330:             }
 8331:         }
 8332:         unless ($noprint) {
 8333:             my $symb = &Apache::lonnet::symbread();
 8334:             if ($symb ne '') {
 8335:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8336:                 if (ref($navmap)) {
 8337:                     my $res = $navmap->getBySymb($symb);
 8338:                     if (ref($res)) {
 8339:                         if (!$res->resprintable()) {
 8340:                             $noprint = 1;
 8341:                         }
 8342:                     }
 8343:                 }
 8344:             }
 8345:         }
 8346:         if ($noprint) {
 8347:             return <<"ENDSTYLE";
 8348: <style type="text/css" media="print">
 8349:     body { display:none }
 8350: </style>
 8351: ENDSTYLE
 8352:         }
 8353:     }
 8354:     return;
 8355: }
 8356: 
 8357: =pod
 8358: 
 8359: =item * &xml_begin()
 8360: 
 8361: Returns the needed doctype and <html>
 8362: 
 8363: Inputs: none
 8364: 
 8365: =cut
 8366: 
 8367: sub xml_begin {
 8368:     my ($is_frameset) = @_;
 8369:     my $output='';
 8370: 
 8371:     if ($env{'browser.mathml'}) {
 8372: 	$output='<?xml version="1.0"?>'
 8373:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8374: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8375:             
 8376: #	    .'<!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">] >'
 8377: 	    .'<!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">'
 8378:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8379: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8380:     } elsif ($is_frameset) {
 8381:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8382:                 '<html>'."\n";
 8383:     } else {
 8384: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8385:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8386:     }
 8387:     return $output;
 8388: }
 8389: 
 8390: =pod
 8391: 
 8392: =item * &start_page()
 8393: 
 8394: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8395: 
 8396: Inputs:
 8397: 
 8398: =over 4
 8399: 
 8400: $title - optional title for the page
 8401: 
 8402: $head_extra - optional extra HTML to incude inside the <head>
 8403: 
 8404: $args - additional optional args supported are:
 8405: 
 8406: =over 8
 8407: 
 8408:              only_body      -> is true will set &bodytag() onlybodytag
 8409:                                     arg on
 8410:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8411:              add_entries    -> additional attributes to add to the  <body>
 8412:              domain         -> force to color decorate a page for a 
 8413:                                     specific domain
 8414:              function       -> force usage of a specific rolish color
 8415:                                     scheme
 8416:              redirect       -> see &headtag()
 8417:              bgcolor        -> override the default page bg color
 8418:              js_ready       -> return a string ready for being used in 
 8419:                                     a javascript writeln
 8420:              html_encode    -> return a string ready for being used in 
 8421:                                     a html attribute
 8422:              force_register -> if is true will turn on the &bodytag()
 8423:                                     $forcereg arg
 8424:              frameset       -> if true will start with a <frameset>
 8425:                                     rather than <body>
 8426:              skip_phases    -> hash ref of 
 8427:                                     head -> skip the <html><head> generation
 8428:                                     body -> skip all <body> generation
 8429:              no_inline_link -> if true and in remote mode, don't show the
 8430:                                     'Switch To Inline Menu' link
 8431:              no_auto_mt_title -> prevent &mt()ing the title arg
 8432:              bread_crumbs ->             Array containing breadcrumbs
 8433:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8434:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8435:                                     to lonhtmlcommon::breadcrumbs
 8436:              group          -> includes the current group, if page is for a
 8437:                                specific group
 8438:              use_absolute   -> for request for external resource or syllabus, this
 8439:                                will contain https://<hostname> if server uses
 8440:                                https (as per hosts.tab), but request is for http
 8441:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8442:              links_disabled -> Links in primary and secondary menus are disabled
 8443:                                (Can enable them once page has loaded - see lonroles.pm
 8444:                                for an example).
 8445: 
 8446: =back
 8447: 
 8448: =back
 8449: 
 8450: =cut
 8451: 
 8452: sub start_page {
 8453:     my ($title,$head_extra,$args) = @_;
 8454:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8455: 
 8456:     $env{'internal.start_page'}++;
 8457:     my ($result,@advtools);
 8458: 
 8459:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8460:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8461:     }
 8462:     
 8463:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8464: 	if ($args->{'frameset'}) {
 8465: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8466: 						$args->{'add_entries'});
 8467: 	    $result .= "\n<frameset $attr_string>\n";
 8468:         } else {
 8469:             $result .=
 8470:                 &bodytag($title, 
 8471:                          $args->{'function'},       $args->{'add_entries'},
 8472:                          $args->{'only_body'},      $args->{'domain'},
 8473:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8474:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8475:                          $args,                     \@advtools);
 8476:         }
 8477:     }
 8478: 
 8479:     if ($args->{'js_ready'}) {
 8480: 		$result = &js_ready($result);
 8481:     }
 8482:     if ($args->{'html_encode'}) {
 8483: 		$result = &html_encode($result);
 8484:     }
 8485: 
 8486:     # Preparation for new and consistent functionlist at top of screen
 8487:     # if ($args->{'functionlist'}) {
 8488:     #            $result .= &build_functionlist();
 8489:     #}
 8490: 
 8491:     # Don't add anything more if only_body wanted or in const space
 8492:     return $result if    $args->{'only_body'} 
 8493:                       || $env{'request.state'} eq 'construct';
 8494: 
 8495:     #Breadcrumbs
 8496:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8497: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8498: 		#if any br links exists, add them to the breadcrumbs
 8499: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8500: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8501: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8502: 			}
 8503: 		}
 8504:                 # if @advtools array contains items add then to the breadcrumbs
 8505:                 if (@advtools > 0) {
 8506:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8507:                 }
 8508:                 my $menulink;
 8509:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8510:                 if (exists($args->{'bread_crumbs_nomenu'})) {
 8511:                     $menulink = 0;
 8512:                 } else {
 8513:                     undef($menulink);
 8514:                 }
 8515: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8516: 		if(exists($args->{'bread_crumbs_component'})){
 8517: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8518: 		}else{
 8519: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8520: 		}
 8521:     } elsif (($env{'environment.remote'} eq 'on') &&
 8522:              ($env{'form.inhibitmenu'} ne 'yes') &&
 8523:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 8524:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 8525:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 8526:     }
 8527:     return $result;
 8528: }
 8529: 
 8530: sub end_page {
 8531:     my ($args) = @_;
 8532:     $env{'internal.end_page'}++;
 8533:     my $result;
 8534:     if ($args->{'discussion'}) {
 8535: 	my ($target,$parser);
 8536: 	if (ref($args->{'discussion'})) {
 8537: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8538: 				$args->{'discussion'}{'parser'});
 8539: 	}
 8540: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8541:     }
 8542:     if ($args->{'frameset'}) {
 8543: 	$result .= '</frameset>';
 8544:     } else {
 8545: 	$result .= &endbodytag($args);
 8546:     }
 8547:     unless ($args->{'notbody'}) {
 8548:         $result .= "\n</html>";
 8549:     }
 8550: 
 8551:     if ($args->{'js_ready'}) {
 8552: 	$result = &js_ready($result);
 8553:     }
 8554: 
 8555:     if ($args->{'html_encode'}) {
 8556: 	$result = &html_encode($result);
 8557:     }
 8558: 
 8559:     return $result;
 8560: }
 8561: 
 8562: sub wishlist_window {
 8563:     return(<<'ENDWISHLIST');
 8564: <script type="text/javascript">
 8565: // <![CDATA[
 8566: // <!-- BEGIN LON-CAPA Internal
 8567: function set_wishlistlink(title, path) {
 8568:     if (!title) {
 8569:         title = document.title;
 8570:         title = title.replace(/^LON-CAPA /,'');
 8571:     }
 8572:     title = encodeURIComponent(title);
 8573:     title = title.replace("'","\\\'");
 8574:     if (!path) {
 8575:         path = location.pathname;
 8576:     }
 8577:     path = encodeURIComponent(path);
 8578:     path = path.replace("'","\\\'");
 8579:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8580:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8581: }
 8582: // END LON-CAPA Internal -->
 8583: // ]]>
 8584: </script>
 8585: ENDWISHLIST
 8586: }
 8587: 
 8588: sub modal_window {
 8589:     return(<<'ENDMODAL');
 8590: <script type="text/javascript">
 8591: // <![CDATA[
 8592: // <!-- BEGIN LON-CAPA Internal
 8593: var modalWindow = {
 8594: 	parent:"body",
 8595: 	windowId:null,
 8596: 	content:null,
 8597: 	width:null,
 8598: 	height:null,
 8599: 	close:function()
 8600: 	{
 8601: 	        $(".LCmodal-window").remove();
 8602: 	        $(".LCmodal-overlay").remove();
 8603: 	},
 8604: 	open:function()
 8605: 	{
 8606: 		var modal = "";
 8607: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8608: 		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;\">";
 8609: 		modal += this.content;
 8610: 		modal += "</div>";	
 8611: 
 8612: 		$(this.parent).append(modal);
 8613: 
 8614: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8615: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8616: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8617: 	}
 8618: };
 8619: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8620: 	{
 8621:                 source = source.replace(/'/g,"&#39;");
 8622: 		modalWindow.windowId = "myModal";
 8623: 		modalWindow.width = width;
 8624: 		modalWindow.height = height;
 8625: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8626: 		modalWindow.open();
 8627: 	};
 8628: // END LON-CAPA Internal -->
 8629: // ]]>
 8630: </script>
 8631: ENDMODAL
 8632: }
 8633: 
 8634: sub modal_link {
 8635:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8636:     unless ($width) { $width=480; }
 8637:     unless ($height) { $height=400; }
 8638:     unless ($scrolling) { $scrolling='yes'; }
 8639:     unless ($transparency) { $transparency='true'; }
 8640: 
 8641:     my $target_attr;
 8642:     if (defined($target)) {
 8643:         $target_attr = 'target="'.$target.'"';
 8644:     }
 8645:     return <<"ENDLINK";
 8646: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 8647: ENDLINK
 8648: }
 8649: 
 8650: sub modal_adhoc_script {
 8651:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 8652:     my $mathjax;
 8653:     if ($possmathjax) {
 8654:         $mathjax = <<'ENDJAX';
 8655:                if (typeof MathJax == 'object') {
 8656:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 8657:                }
 8658: ENDJAX
 8659:     }
 8660:     return (<<ENDADHOC);
 8661: <script type="text/javascript">
 8662: // <![CDATA[
 8663:         var $funcname = function()
 8664:         {
 8665:                 modalWindow.windowId = "myModal";
 8666:                 modalWindow.width = $width;
 8667:                 modalWindow.height = $height;
 8668:                 modalWindow.content = '$content';
 8669:                 modalWindow.open();
 8670:                 $mathjax
 8671:         };  
 8672: // ]]>
 8673: </script>
 8674: ENDADHOC
 8675: }
 8676: 
 8677: sub modal_adhoc_inner {
 8678:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 8679:     my $innerwidth=$width-20;
 8680:     $content=&js_ready(
 8681:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8682:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8683:                  $content.
 8684:                  &end_scrollbox().
 8685:                  &end_page()
 8686:              );
 8687:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 8688: }
 8689: 
 8690: sub modal_adhoc_window {
 8691:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 8692:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 8693:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8694: }
 8695: 
 8696: sub modal_adhoc_launch {
 8697:     my ($funcname,$width,$height,$content)=@_;
 8698:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8699: <script type="text/javascript">
 8700: // <![CDATA[
 8701: $funcname();
 8702: // ]]>
 8703: </script>
 8704: ENDLAUNCH
 8705: }
 8706: 
 8707: sub modal_adhoc_close {
 8708:     return (<<ENDCLOSE);
 8709: <script type="text/javascript">
 8710: // <![CDATA[
 8711: modalWindow.close();
 8712: // ]]>
 8713: </script>
 8714: ENDCLOSE
 8715: }
 8716: 
 8717: sub togglebox_script {
 8718:    return(<<ENDTOGGLE);
 8719: <script type="text/javascript"> 
 8720: // <![CDATA[
 8721: function LCtoggleDisplay(id,hidetext,showtext) {
 8722:    link = document.getElementById(id + "link").childNodes[0];
 8723:    with (document.getElementById(id).style) {
 8724:       if (display == "none" ) {
 8725:           display = "inline";
 8726:           link.nodeValue = hidetext;
 8727:         } else {
 8728:           display = "none";
 8729:           link.nodeValue = showtext;
 8730:        }
 8731:    }
 8732: }
 8733: // ]]>
 8734: </script>
 8735: ENDTOGGLE
 8736: }
 8737: 
 8738: sub start_togglebox {
 8739:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8740:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8741:     unless ($showtext) { $showtext=&mt('show'); }
 8742:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8743:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8744:     return &start_data_table().
 8745:            &start_data_table_header_row().
 8746:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8747:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8748:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8749:            &end_data_table_header_row().
 8750:            '<tr id="'.$id.'" style="display:none""><td>';
 8751: }
 8752: 
 8753: sub end_togglebox {
 8754:     return '</td></tr>'.&end_data_table();
 8755: }
 8756: 
 8757: sub LCprogressbar_script {
 8758:    my ($id,$number_to_do)=@_;
 8759:    if ($number_to_do) {
 8760:        return(<<ENDPROGRESS);
 8761: <script type="text/javascript">
 8762: // <![CDATA[
 8763: \$('#progressbar$id').progressbar({
 8764:   value: 0,
 8765:   change: function(event, ui) {
 8766:     var newVal = \$(this).progressbar('option', 'value');
 8767:     \$('.pblabel', this).text(LCprogressTxt);
 8768:   }
 8769: });
 8770: // ]]>
 8771: </script>
 8772: ENDPROGRESS
 8773:    } else {
 8774:        return(<<ENDPROGRESS);
 8775: <script type="text/javascript">
 8776: // <![CDATA[
 8777: \$('#progressbar$id').progressbar({
 8778:   value: false,
 8779:   create: function(event, ui) {
 8780:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 8781:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 8782:   }
 8783: });
 8784: // ]]>
 8785: </script>
 8786: ENDPROGRESS
 8787:    }
 8788: }
 8789: 
 8790: sub LCprogressbarUpdate_script {
 8791:    return(<<ENDPROGRESSUPDATE);
 8792: <style type="text/css">
 8793: .ui-progressbar { position:relative; }
 8794: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
 8795: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8796: </style>
 8797: <script type="text/javascript">
 8798: // <![CDATA[
 8799: var LCprogressTxt='---';
 8800: 
 8801: function LCupdateProgress(percent,progresstext,id,maxnum) {
 8802:    LCprogressTxt=progresstext;
 8803:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 8804:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 8805:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 8806:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 8807:    } else {
 8808:        \$('#progressbar'+id).progressbar('value',percent);
 8809:    }
 8810: }
 8811: // ]]>
 8812: </script>
 8813: ENDPROGRESSUPDATE
 8814: }
 8815: 
 8816: my $LClastpercent;
 8817: my $LCidcnt;
 8818: my $LCcurrentid;
 8819: 
 8820: sub LCprogressbar {
 8821:     my ($r,$number_to_do,$preamble)=@_;
 8822:     $LClastpercent=0;
 8823:     $LCidcnt++;
 8824:     $LCcurrentid=$$.'_'.$LCidcnt;
 8825:     my ($starting,$content);
 8826:     if ($number_to_do) {
 8827:         $starting=&mt('Starting');
 8828:         $content=(<<ENDPROGBAR);
 8829: $preamble
 8830:   <div id="progressbar$LCcurrentid">
 8831:     <span class="pblabel">$starting</span>
 8832:   </div>
 8833: ENDPROGBAR
 8834:     } else {
 8835:         $starting=&mt('Loading...');
 8836:         $LClastpercent='false';
 8837:         $content=(<<ENDPROGBAR);
 8838: $preamble
 8839:   <div id="progressbar$LCcurrentid">
 8840:       <div class="progress-label">$starting</div>
 8841:   </div>
 8842: ENDPROGBAR
 8843:     }
 8844:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 8845: }
 8846: 
 8847: sub LCprogressbarUpdate {
 8848:     my ($r,$val,$text,$number_to_do)=@_;
 8849:     if ($number_to_do) {
 8850:         unless ($val) { 
 8851:             if ($LClastpercent) {
 8852:                 $val=$LClastpercent;
 8853:             } else {
 8854:                 $val=0;
 8855:             }
 8856:         }
 8857:         if ($val<0) { $val=0; }
 8858:         if ($val>100) { $val=0; }
 8859:         $LClastpercent=$val;
 8860:         unless ($text) { $text=$val.'%'; }
 8861:     } else {
 8862:         $val = 'false';
 8863:     }
 8864:     $text=&js_ready($text);
 8865:     &r_print($r,<<ENDUPDATE);
 8866: <script type="text/javascript">
 8867: // <![CDATA[
 8868: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 8869: // ]]>
 8870: </script>
 8871: ENDUPDATE
 8872: }
 8873: 
 8874: sub LCprogressbarClose {
 8875:     my ($r)=@_;
 8876:     $LClastpercent=0;
 8877:     &r_print($r,<<ENDCLOSE);
 8878: <script type="text/javascript">
 8879: // <![CDATA[
 8880: \$("#progressbar$LCcurrentid").hide('slow'); 
 8881: // ]]>
 8882: </script>
 8883: ENDCLOSE
 8884: }
 8885: 
 8886: sub r_print {
 8887:     my ($r,$to_print)=@_;
 8888:     if ($r) {
 8889:       $r->print($to_print);
 8890:       $r->rflush();
 8891:     } else {
 8892:       print($to_print);
 8893:     }
 8894: }
 8895: 
 8896: sub html_encode {
 8897:     my ($result) = @_;
 8898: 
 8899:     $result = &HTML::Entities::encode($result,'<>&"');
 8900:     
 8901:     return $result;
 8902: }
 8903: 
 8904: sub js_ready {
 8905:     my ($result) = @_;
 8906: 
 8907:     $result =~ s/[\n\r]/ /xmsg;
 8908:     $result =~ s/\\/\\\\/xmsg;
 8909:     $result =~ s/'/\\'/xmsg;
 8910:     $result =~ s{</}{<\\/}xmsg;
 8911:     
 8912:     return $result;
 8913: }
 8914: 
 8915: sub validate_page {
 8916:     if (  exists($env{'internal.start_page'})
 8917: 	  &&     $env{'internal.start_page'} > 1) {
 8918: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8919: 				 $env{'internal.start_page'}.' '.
 8920: 				 $ENV{'request.filename'});
 8921:     }
 8922:     if (  exists($env{'internal.end_page'})
 8923: 	  &&     $env{'internal.end_page'} > 1) {
 8924: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8925: 				 $env{'internal.end_page'}.' '.
 8926: 				 $env{'request.filename'});
 8927:     }
 8928:     if (     exists($env{'internal.start_page'})
 8929: 	&& ! exists($env{'internal.end_page'})) {
 8930: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8931: 				 $env{'request.filename'});
 8932:     }
 8933:     if (   ! exists($env{'internal.start_page'})
 8934: 	&&   exists($env{'internal.end_page'})) {
 8935: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8936: 				 $env{'request.filename'});
 8937:     }
 8938: }
 8939: 
 8940: 
 8941: sub start_scrollbox {
 8942:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8943:     unless ($outerwidth) { $outerwidth='520px'; }
 8944:     unless ($width) { $width='500px'; }
 8945:     unless ($height) { $height='200px'; }
 8946:     my ($table_id,$div_id,$tdcol);
 8947:     if ($id ne '') {
 8948:         $table_id = ' id="table_'.$id.'"';
 8949:         $div_id = ' id="div_'.$id.'"';
 8950:     }
 8951:     if ($bgcolor ne '') {
 8952:         $tdcol = "background-color: $bgcolor;";
 8953:     }
 8954:     my $nicescroll_js;
 8955:     if ($env{'browser.mobile'}) {
 8956:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8957:     }
 8958:     return <<"END";
 8959: $nicescroll_js
 8960: 
 8961: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8962: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8963: END
 8964: }
 8965: 
 8966: sub end_scrollbox {
 8967:     return '</div></td></tr></table>';
 8968: }
 8969: 
 8970: sub nicescroll_javascript {
 8971:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8972:     my %options;
 8973:     if (ref($cursor) eq 'HASH') {
 8974:         %options = %{$cursor};
 8975:     }
 8976:     unless ($options{'railalign'} =~ /^left|right$/) {
 8977:         $options{'railalign'} = 'left';
 8978:     }
 8979:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8980:         my $function  = &get_users_function();
 8981:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8982:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8983:             $options{'cursorcolor'} = '#00F';
 8984:         }
 8985:     }
 8986:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8987:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8988:             $options{'cursoropacity'}='1.0';
 8989:         }
 8990:     } else {
 8991:         $options{'cursoropacity'}='1.0';
 8992:     }
 8993:     if ($options{'cursorfixedheight'} eq 'none') {
 8994:         delete($options{'cursorfixedheight'});
 8995:     } else {
 8996:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8997:     }
 8998:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8999:         delete($options{'railoffset'});
 9000:     }
 9001:     my @niceoptions;
 9002:     while (my($key,$value) = each(%options)) {
 9003:         if ($value =~ /^\{.+\}$/) {
 9004:             push(@niceoptions,$key.':'.$value);
 9005:         } else {
 9006:             push(@niceoptions,$key.':"'.$value.'"');
 9007:         }
 9008:     }
 9009:     my $nicescroll_js = '
 9010: $(document).ready(
 9011:       function() {
 9012:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9013:       }
 9014: );
 9015: ';
 9016:     if ($framecheck) {
 9017:         $nicescroll_js .= '
 9018: function expand_div(caller) {
 9019:     if (top === self) {
 9020:         document.getElementById("'.$id.'").style.width = "auto";
 9021:         document.getElementById("'.$id.'").style.height = "auto";
 9022:     } else {
 9023:         try {
 9024:             if (parent.frames) {
 9025:                 if (parent.frames.length > 1) {
 9026:                     var framesrc = parent.frames[1].location.href;
 9027:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9028:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9029:                         document.getElementById("'.$id.'").style.width = "auto";
 9030:                         document.getElementById("'.$id.'").style.height = "auto";
 9031:                     }
 9032:                 }
 9033:             }
 9034:         } catch (e) {
 9035:             return;
 9036:         }
 9037:     }
 9038:     return;
 9039: }
 9040: ';
 9041:     }
 9042:     if ($needjsready) {
 9043:         $nicescroll_js = '
 9044: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9045:     } else {
 9046:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9047:     }
 9048:     return $nicescroll_js;
 9049: }
 9050: 
 9051: sub simple_error_page {
 9052:     my ($r,$title,$msg,$args) = @_;
 9053:     if (ref($args) eq 'HASH') {
 9054:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9055:     } else {
 9056:         $msg = &mt($msg);
 9057:     }
 9058: 
 9059:     my $page =
 9060: 	&Apache::loncommon::start_page($title).
 9061: 	'<p class="LC_error">'.$msg.'</p>'.
 9062: 	&Apache::loncommon::end_page();
 9063:     if (ref($r)) {
 9064: 	$r->print($page);
 9065: 	return;
 9066:     }
 9067:     return $page;
 9068: }
 9069: 
 9070: {
 9071:     my @row_count;
 9072: 
 9073:     sub start_data_table_count {
 9074:         unshift(@row_count, 0);
 9075:         return;
 9076:     }
 9077: 
 9078:     sub end_data_table_count {
 9079:         shift(@row_count);
 9080:         return;
 9081:     }
 9082: 
 9083:     sub start_data_table {
 9084: 	my ($add_class,$id) = @_;
 9085: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9086:         my $table_id;
 9087:         if (defined($id)) {
 9088:             $table_id = ' id="'.$id.'"';
 9089:         }
 9090: 	&start_data_table_count();
 9091: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9092:     }
 9093: 
 9094:     sub end_data_table {
 9095: 	&end_data_table_count();
 9096: 	return '</table>'."\n";;
 9097:     }
 9098: 
 9099:     sub start_data_table_row {
 9100: 	my ($add_class, $id) = @_;
 9101: 	$row_count[0]++;
 9102: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9103: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9104:         $id = (' id="'.$id.'"') unless ($id eq '');
 9105:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9106:     }
 9107:     
 9108:     sub continue_data_table_row {
 9109: 	my ($add_class, $id) = @_;
 9110: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9111: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9112:         $id = (' id="'.$id.'"') unless ($id eq '');
 9113:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9114:     }
 9115: 
 9116:     sub end_data_table_row {
 9117: 	return '</tr>'."\n";;
 9118:     }
 9119: 
 9120:     sub start_data_table_empty_row {
 9121: #	$row_count[0]++;
 9122: 	return  '<tr class="LC_empty_row" >'."\n";;
 9123:     }
 9124: 
 9125:     sub end_data_table_empty_row {
 9126: 	return '</tr>'."\n";;
 9127:     }
 9128: 
 9129:     sub start_data_table_header_row {
 9130: 	return  '<tr class="LC_header_row">'."\n";;
 9131:     }
 9132: 
 9133:     sub end_data_table_header_row {
 9134: 	return '</tr>'."\n";;
 9135:     }
 9136: 
 9137:     sub data_table_caption {
 9138:         my $caption = shift;
 9139:         return "<caption class=\"LC_caption\">$caption</caption>";
 9140:     }
 9141: }
 9142: 
 9143: =pod
 9144: 
 9145: =item * &inhibit_menu_check($arg)
 9146: 
 9147: Checks for a inhibitmenu state and generates output to preserve it
 9148: 
 9149: Inputs:         $arg - can be any of
 9150:                      - undef - in which case the return value is a string 
 9151:                                to add  into arguments list of a uri
 9152:                      - 'input' - in which case the return value is a HTML
 9153:                                  <form> <input> field of type hidden to
 9154:                                  preserve the value
 9155:                      - a url - in which case the return value is the url with
 9156:                                the neccesary cgi args added to preserve the
 9157:                                inhibitmenu state
 9158:                      - a ref to a url - no return value, but the string is
 9159:                                         updated to include the neccessary cgi
 9160:                                         args to preserve the inhibitmenu state
 9161: 
 9162: =cut
 9163: 
 9164: sub inhibit_menu_check {
 9165:     my ($arg) = @_;
 9166:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9167:     if ($arg eq 'input') {
 9168: 	if ($env{'form.inhibitmenu'}) {
 9169: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9170: 	} else {
 9171: 	    return
 9172: 	}
 9173:     }
 9174:     if ($env{'form.inhibitmenu'}) {
 9175: 	if (ref($arg)) {
 9176: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9177: 	} elsif ($arg eq '') {
 9178: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9179: 	} else {
 9180: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9181: 	}
 9182:     }
 9183:     if (!ref($arg)) {
 9184: 	return $arg;
 9185:     }
 9186: }
 9187: 
 9188: ###############################################
 9189: 
 9190: =pod
 9191: 
 9192: =back
 9193: 
 9194: =head1 User Information Routines
 9195: 
 9196: =over 4
 9197: 
 9198: =item * &get_users_function()
 9199: 
 9200: Used by &bodytag to determine the current users primary role.
 9201: Returns either 'student','coordinator','admin', or 'author'.
 9202: 
 9203: =cut
 9204: 
 9205: ###############################################
 9206: sub get_users_function {
 9207:     my $function = 'norole';
 9208:     if ($env{'request.role'}=~/^(st)/) {
 9209:         $function='student';
 9210:     }
 9211:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9212:         $function='coordinator';
 9213:     }
 9214:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9215:         $function='admin';
 9216:     }
 9217:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9218:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9219:         $function='author';
 9220:     }
 9221:     return $function;
 9222: }
 9223: 
 9224: ###############################################
 9225: 
 9226: =pod
 9227: 
 9228: =item * &show_course()
 9229: 
 9230: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9231: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9232: 
 9233: Inputs:
 9234: None
 9235: 
 9236: Outputs:
 9237: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9238: 
 9239: =cut
 9240: 
 9241: ###############################################
 9242: sub show_course {
 9243:     my $course = !$env{'user.adv'};
 9244:     if (!$env{'user.adv'}) {
 9245:         foreach my $env (keys(%env)) {
 9246:             next if ($env !~ m/^user\.priv\./);
 9247:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9248:                 $course = 0;
 9249:                 last;
 9250:             }
 9251:         }
 9252:     }
 9253:     return $course;
 9254: }
 9255: 
 9256: ###############################################
 9257: 
 9258: =pod
 9259: 
 9260: =item * &check_user_status()
 9261: 
 9262: Determines current status of supplied role for a
 9263: specific user. Roles can be active, previous or future.
 9264: 
 9265: Inputs: 
 9266: user's domain, user's username, course's domain,
 9267: course's number, optional section ID.
 9268: 
 9269: Outputs:
 9270: role status: active, previous or future. 
 9271: 
 9272: =cut
 9273: 
 9274: sub check_user_status {
 9275:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9276:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9277:     my @uroles = keys(%userinfo);
 9278:     my $srchstr;
 9279:     my $active_chk = 'none';
 9280:     my $now = time;
 9281:     if (@uroles > 0) {
 9282:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9283:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9284:         } else {
 9285:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9286:         }
 9287:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9288:             my $role_end = 0;
 9289:             my $role_start = 0;
 9290:             $active_chk = 'active';
 9291:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9292:                 $role_end = $1;
 9293:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9294:                     $role_start = $1;
 9295:                 }
 9296:             }
 9297:             if ($role_start > 0) {
 9298:                 if ($now < $role_start) {
 9299:                     $active_chk = 'future';
 9300:                 }
 9301:             }
 9302:             if ($role_end > 0) {
 9303:                 if ($now > $role_end) {
 9304:                     $active_chk = 'previous';
 9305:                 }
 9306:             }
 9307:         }
 9308:     }
 9309:     return $active_chk;
 9310: }
 9311: 
 9312: ###############################################
 9313: 
 9314: =pod
 9315: 
 9316: =item * &get_sections()
 9317: 
 9318: Determines all the sections for a course including
 9319: sections with students and sections containing other roles.
 9320: Incoming parameters: 
 9321: 
 9322: 1. domain
 9323: 2. course number 
 9324: 3. reference to array containing roles for which sections should 
 9325: be gathered (optional).
 9326: 4. reference to array containing status types for which sections 
 9327: should be gathered (optional).
 9328: 
 9329: If the third argument is undefined, sections are gathered for any role. 
 9330: If the fourth argument is undefined, sections are gathered for any status.
 9331: Permissible values are 'active' or 'future' or 'previous'.
 9332:  
 9333: Returns section hash (keys are section IDs, values are
 9334: number of users in each section), subject to the
 9335: optional roles filter, optional status filter 
 9336: 
 9337: =cut
 9338: 
 9339: ###############################################
 9340: sub get_sections {
 9341:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9342:     if (!defined($cdom) || !defined($cnum)) {
 9343:         my $cid =  $env{'request.course.id'};
 9344: 
 9345: 	return if (!defined($cid));
 9346: 
 9347:         $cdom = $env{'course.'.$cid.'.domain'};
 9348:         $cnum = $env{'course.'.$cid.'.num'};
 9349:     }
 9350: 
 9351:     my %sectioncount;
 9352:     my $now = time;
 9353: 
 9354:     my $check_students = 1;
 9355:     my $only_students = 0;
 9356:     if (ref($possible_roles) eq 'ARRAY') {
 9357:         if (grep(/^st$/,@{$possible_roles})) {
 9358:             if (@{$possible_roles} == 1) {
 9359:                 $only_students = 1;
 9360:             }
 9361:         } else {
 9362:             $check_students = 0;
 9363:         }
 9364:     }
 9365: 
 9366:     if ($check_students) {
 9367: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9368: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9369: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9370:         my $start_index = &Apache::loncoursedata::CL_START();
 9371:         my $end_index = &Apache::loncoursedata::CL_END();
 9372:         my $status;
 9373: 	while (my ($student,$data) = each(%$classlist)) {
 9374: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9375: 				                     $data->[$status_index],
 9376:                                                      $data->[$start_index],
 9377:                                                      $data->[$end_index]);
 9378:             if ($stu_status eq 'Active') {
 9379:                 $status = 'active';
 9380:             } elsif ($end < $now) {
 9381:                 $status = 'previous';
 9382:             } elsif ($start > $now) {
 9383:                 $status = 'future';
 9384:             } 
 9385: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9386:                 if ((!defined($possible_status)) || (($status ne '') && 
 9387:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9388: 		    $sectioncount{$section}++;
 9389:                 }
 9390: 	    }
 9391: 	}
 9392:     }
 9393:     if ($only_students) {
 9394:         return %sectioncount;
 9395:     }
 9396:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9397:     foreach my $user (sort(keys(%courseroles))) {
 9398: 	if ($user !~ /^(\w{2})/) { next; }
 9399: 	my ($role) = ($user =~ /^(\w{2})/);
 9400: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9401: 	my ($section,$status);
 9402: 	if ($role eq 'cr' &&
 9403: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9404: 	    $section=$1;
 9405: 	}
 9406: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9407: 	if (!defined($section) || $section eq '-1') { next; }
 9408:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9409:         if ($end == -1 && $start == -1) {
 9410:             next; #deleted role
 9411:         }
 9412:         if (!defined($possible_status)) { 
 9413:             $sectioncount{$section}++;
 9414:         } else {
 9415:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9416:                 $status = 'active';
 9417:             } elsif ($end < $now) {
 9418:                 $status = 'future';
 9419:             } elsif ($start > $now) {
 9420:                 $status = 'previous';
 9421:             }
 9422:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9423:                 $sectioncount{$section}++;
 9424:             }
 9425:         }
 9426:     }
 9427:     return %sectioncount;
 9428: }
 9429: 
 9430: ###############################################
 9431: 
 9432: =pod
 9433: 
 9434: =item * &get_course_users()
 9435: 
 9436: Retrieves usernames:domains for users in the specified course
 9437: with specific role(s), and access status. 
 9438: 
 9439: Incoming parameters:
 9440: 1. course domain
 9441: 2. course number
 9442: 3. access status: users must have - either active, 
 9443: previous, future, or all.
 9444: 4. reference to array of permissible roles
 9445: 5. reference to array of section restrictions (optional)
 9446: 6. reference to results object (hash of hashes).
 9447: 7. reference to optional userdata hash
 9448: 8. reference to optional statushash
 9449: 9. flag if privileged users (except those set to unhide in
 9450:    course settings) should be excluded    
 9451: Keys of top level results hash are roles.
 9452: Keys of inner hashes are username:domain, with 
 9453: values set to access type.
 9454: Optional userdata hash returns an array with arguments in the 
 9455: same order as loncoursedata::get_classlist() for student data.
 9456: 
 9457: Optional statushash returns
 9458: 
 9459: Entries for end, start, section and status are blank because
 9460: of the possibility of multiple values for non-student roles.
 9461: 
 9462: =cut
 9463: 
 9464: ###############################################
 9465: 
 9466: sub get_course_users {
 9467:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9468:     my %idx = ();
 9469:     my %seclists;
 9470: 
 9471:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9472:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9473:     $idx{end} = &Apache::loncoursedata::CL_END();
 9474:     $idx{start} = &Apache::loncoursedata::CL_START();
 9475:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9476:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9477:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9478:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9479: 
 9480:     if (grep(/^st$/,@{$roles})) {
 9481:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9482:         my $now = time;
 9483:         foreach my $student (keys(%{$classlist})) {
 9484:             my $match = 0;
 9485:             my $secmatch = 0;
 9486:             my $section = $$classlist{$student}[$idx{section}];
 9487:             my $status = $$classlist{$student}[$idx{status}];
 9488:             if ($section eq '') {
 9489:                 $section = 'none';
 9490:             }
 9491:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9492:                 if (grep(/^all$/,@{$sections})) {
 9493:                     $secmatch = 1;
 9494:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9495:                     if (grep(/^none$/,@{$sections})) {
 9496:                         $secmatch = 1;
 9497:                     }
 9498:                 } else {  
 9499: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9500: 		        $secmatch = 1;
 9501:                     }
 9502: 		}
 9503:                 if (!$secmatch) {
 9504:                     next;
 9505:                 }
 9506:             }
 9507:             if (defined($$types{'active'})) {
 9508:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9509:                     push(@{$$users{st}{$student}},'active');
 9510:                     $match = 1;
 9511:                 }
 9512:             }
 9513:             if (defined($$types{'previous'})) {
 9514:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9515:                     push(@{$$users{st}{$student}},'previous');
 9516:                     $match = 1;
 9517:                 }
 9518:             }
 9519:             if (defined($$types{'future'})) {
 9520:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9521:                     push(@{$$users{st}{$student}},'future');
 9522:                     $match = 1;
 9523:                 }
 9524:             }
 9525:             if ($match) {
 9526:                 push(@{$seclists{$student}},$section);
 9527:                 if (ref($userdata) eq 'HASH') {
 9528:                     $$userdata{$student} = $$classlist{$student};
 9529:                 }
 9530:                 if (ref($statushash) eq 'HASH') {
 9531:                     $statushash->{$student}{'st'}{$section} = $status;
 9532:                 }
 9533:             }
 9534:         }
 9535:     }
 9536:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9537:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9538:         my $now = time;
 9539:         my %displaystatus = ( previous => 'Expired',
 9540:                               active   => 'Active',
 9541:                               future   => 'Future',
 9542:                             );
 9543:         my (%nothide,@possdoms);
 9544:         if ($hidepriv) {
 9545:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9546:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9547:                 if ($user !~ /:/) {
 9548:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9549:                 } else {
 9550:                     $nothide{$user} = 1;
 9551:                 }
 9552:             }
 9553:             my @possdoms = ($cdom);
 9554:             if ($coursehash{'checkforpriv'}) {
 9555:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9556:             }
 9557:         }
 9558:         foreach my $person (sort(keys(%coursepersonnel))) {
 9559:             my $match = 0;
 9560:             my $secmatch = 0;
 9561:             my $status;
 9562:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9563:             $user =~ s/:$//;
 9564:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9565:             if ($end == -1 || $start == -1) {
 9566:                 next;
 9567:             }
 9568:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9569:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9570:                 my ($uname,$udom) = split(/:/,$user);
 9571:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9572:                     if (grep(/^all$/,@{$sections})) {
 9573:                         $secmatch = 1;
 9574:                     } elsif ($usec eq '') {
 9575:                         if (grep(/^none$/,@{$sections})) {
 9576:                             $secmatch = 1;
 9577:                         }
 9578:                     } else {
 9579:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9580:                             $secmatch = 1;
 9581:                         }
 9582:                     }
 9583:                     if (!$secmatch) {
 9584:                         next;
 9585:                     }
 9586:                 }
 9587:                 if ($usec eq '') {
 9588:                     $usec = 'none';
 9589:                 }
 9590:                 if ($uname ne '' && $udom ne '') {
 9591:                     if ($hidepriv) {
 9592:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9593:                             (!$nothide{$uname.':'.$udom})) {
 9594:                             next;
 9595:                         }
 9596:                     }
 9597:                     if ($end > 0 && $end < $now) {
 9598:                         $status = 'previous';
 9599:                     } elsif ($start > $now) {
 9600:                         $status = 'future';
 9601:                     } else {
 9602:                         $status = 'active';
 9603:                     }
 9604:                     foreach my $type (keys(%{$types})) { 
 9605:                         if ($status eq $type) {
 9606:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9607:                                 push(@{$$users{$role}{$user}},$type);
 9608:                             }
 9609:                             $match = 1;
 9610:                         }
 9611:                     }
 9612:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9613:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9614: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9615:                         }
 9616:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9617:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9618:                         }
 9619:                         if (ref($statushash) eq 'HASH') {
 9620:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9621:                         }
 9622:                     }
 9623:                 }
 9624:             }
 9625:         }
 9626:         if (grep(/^ow$/,@{$roles})) {
 9627:             if ((defined($cdom)) && (defined($cnum))) {
 9628:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9629:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9630:                     my $owner = $csettings{'internal.courseowner'};
 9631:                     next if ($owner eq '');
 9632:                     my ($ownername,$ownerdom);
 9633:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9634:                         $ownername = $1;
 9635:                         $ownerdom = $2;
 9636:                     } else {
 9637:                         $ownername = $owner;
 9638:                         $ownerdom = $cdom;
 9639:                         $owner = $ownername.':'.$ownerdom;
 9640:                     }
 9641:                     @{$$users{'ow'}{$owner}} = 'any';
 9642:                     if (defined($userdata) && 
 9643: 			!exists($$userdata{$owner})) {
 9644: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9645:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9646:                             push(@{$seclists{$owner}},'none');
 9647:                         }
 9648:                         if (ref($statushash) eq 'HASH') {
 9649:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9650:                         }
 9651: 		    }
 9652:                 }
 9653:             }
 9654:         }
 9655:         foreach my $user (keys(%seclists)) {
 9656:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9657:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9658:         }
 9659:     }
 9660:     return;
 9661: }
 9662: 
 9663: sub get_user_info {
 9664:     my ($udom,$uname,$idx,$userdata) = @_;
 9665:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9666: 	&plainname($uname,$udom,'lastname');
 9667:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9668:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9669:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9670:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9671:     return;
 9672: }
 9673: 
 9674: ###############################################
 9675: 
 9676: =pod
 9677: 
 9678: =item * &get_user_quota()
 9679: 
 9680: Retrieves quota assigned for storage of user files.
 9681: Default is to report quota for portfolio files.
 9682: 
 9683: Incoming parameters:
 9684: 1. user's username
 9685: 2. user's domain
 9686: 3. quota name - portfolio, author, or course
 9687:    (if no quota name provided, defaults to portfolio).
 9688: 4. crstype - official, unofficial, textbook or community, if quota name is
 9689:    course
 9690: 
 9691: Returns:
 9692: 1. Disk quota (in MB) assigned to student.
 9693: 2. (Optional) Type of setting: custom or default
 9694:    (individually assigned or default for user's 
 9695:    institutional status).
 9696: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9697:    or student - types as defined in localenroll::inst_usertypes 
 9698:    for user's domain, which determines default quota for user.
 9699: 4. (Optional) - Default quota which would apply to the user.
 9700: 
 9701: If a value has been stored in the user's environment, 
 9702: it will return that, otherwise it returns the maximal default
 9703: defined for the user's institutional status(es) in the domain.
 9704: 
 9705: =cut
 9706: 
 9707: ###############################################
 9708: 
 9709: 
 9710: sub get_user_quota {
 9711:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9712:     my ($quota,$quotatype,$settingstatus,$defquota);
 9713:     if (!defined($udom)) {
 9714:         $udom = $env{'user.domain'};
 9715:     }
 9716:     if (!defined($uname)) {
 9717:         $uname = $env{'user.name'};
 9718:     }
 9719:     if (($udom eq '' || $uname eq '') ||
 9720:         ($udom eq 'public') && ($uname eq 'public')) {
 9721:         $quota = 0;
 9722:         $quotatype = 'default';
 9723:         $defquota = 0; 
 9724:     } else {
 9725:         my $inststatus;
 9726:         if ($quotaname eq 'course') {
 9727:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9728:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9729:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9730:             } else {
 9731:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9732:                 $quota = $cenv{'internal.uploadquota'};
 9733:             }
 9734:         } else {
 9735:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9736:                 if ($quotaname eq 'author') {
 9737:                     $quota = $env{'environment.authorquota'};
 9738:                 } else {
 9739:                     $quota = $env{'environment.portfolioquota'};
 9740:                 }
 9741:                 $inststatus = $env{'environment.inststatus'};
 9742:             } else {
 9743:                 my %userenv = 
 9744:                     &Apache::lonnet::get('environment',['portfolioquota',
 9745:                                          'authorquota','inststatus'],$udom,$uname);
 9746:                 my ($tmp) = keys(%userenv);
 9747:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9748:                     if ($quotaname eq 'author') {
 9749:                         $quota = $userenv{'authorquota'};
 9750:                     } else {
 9751:                         $quota = $userenv{'portfolioquota'};
 9752:                     }
 9753:                     $inststatus = $userenv{'inststatus'};
 9754:                 } else {
 9755:                     undef(%userenv);
 9756:                 }
 9757:             }
 9758:         }
 9759:         if ($quota eq '' || wantarray) {
 9760:             if ($quotaname eq 'course') {
 9761:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9762:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 9763:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 9764:                     $defquota = $domdefs{$crstype.'quota'};
 9765:                 }
 9766:                 if ($defquota eq '') {
 9767:                     $defquota = 500;
 9768:                 }
 9769:             } else {
 9770:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9771:             }
 9772:             if ($quota eq '') {
 9773:                 $quota = $defquota;
 9774:                 $quotatype = 'default';
 9775:             } else {
 9776:                 $quotatype = 'custom';
 9777:             }
 9778:         }
 9779:     }
 9780:     if (wantarray) {
 9781:         return ($quota,$quotatype,$settingstatus,$defquota);
 9782:     } else {
 9783:         return $quota;
 9784:     }
 9785: }
 9786: 
 9787: ###############################################
 9788: 
 9789: =pod
 9790: 
 9791: =item * &default_quota()
 9792: 
 9793: Retrieves default quota assigned for storage of user portfolio files,
 9794: given an (optional) user's institutional status.
 9795: 
 9796: Incoming parameters:
 9797: 
 9798: 1. domain
 9799: 2. (Optional) institutional status(es).  This is a : separated list of 
 9800:    status types (e.g., faculty, staff, student etc.)
 9801:    which apply to the user for whom the default is being retrieved.
 9802:    If the institutional status string in undefined, the domain
 9803:    default quota will be returned.
 9804: 3.  quota name - portfolio, author, or course
 9805:    (if no quota name provided, defaults to portfolio).
 9806: 
 9807: Returns:
 9808: 
 9809: 1. Default disk quota (in MB) for user portfolios in the domain.
 9810: 2. (Optional) institutional type which determined the value of the
 9811:    default quota.
 9812: 
 9813: If a value has been stored in the domain's configuration db,
 9814: it will return that, otherwise it returns 20 (for backwards 
 9815: compatibility with domains which have not set up a configuration
 9816: db file; the original statically defined portfolio quota was 20 MB). 
 9817: 
 9818: If the user's status includes multiple types (e.g., staff and student),
 9819: the largest default quota which applies to the user determines the
 9820: default quota returned.
 9821: 
 9822: =cut
 9823: 
 9824: ###############################################
 9825: 
 9826: 
 9827: sub default_quota {
 9828:     my ($udom,$inststatus,$quotaname) = @_;
 9829:     my ($defquota,$settingstatus);
 9830:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9831:                                             ['quotas'],$udom);
 9832:     my $key = 'defaultquota';
 9833:     if ($quotaname eq 'author') {
 9834:         $key = 'authorquota';
 9835:     }
 9836:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9837:         if ($inststatus ne '') {
 9838:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9839:             foreach my $item (@statuses) {
 9840:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9841:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9842:                         if ($defquota eq '') {
 9843:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9844:                             $settingstatus = $item;
 9845:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9846:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9847:                             $settingstatus = $item;
 9848:                         }
 9849:                     }
 9850:                 } elsif ($key eq 'defaultquota') {
 9851:                     if ($quotahash{'quotas'}{$item} ne '') {
 9852:                         if ($defquota eq '') {
 9853:                             $defquota = $quotahash{'quotas'}{$item};
 9854:                             $settingstatus = $item;
 9855:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9856:                             $defquota = $quotahash{'quotas'}{$item};
 9857:                             $settingstatus = $item;
 9858:                         }
 9859:                     }
 9860:                 }
 9861:             }
 9862:         }
 9863:         if ($defquota eq '') {
 9864:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9865:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9866:             } elsif ($key eq 'defaultquota') {
 9867:                 $defquota = $quotahash{'quotas'}{'default'};
 9868:             }
 9869:             $settingstatus = 'default';
 9870:             if ($defquota eq '') {
 9871:                 if ($quotaname eq 'author') {
 9872:                     $defquota = 500;
 9873:                 }
 9874:             }
 9875:         }
 9876:     } else {
 9877:         $settingstatus = 'default';
 9878:         if ($quotaname eq 'author') {
 9879:             $defquota = 500;
 9880:         } else {
 9881:             $defquota = 20;
 9882:         }
 9883:     }
 9884:     if (wantarray) {
 9885:         return ($defquota,$settingstatus);
 9886:     } else {
 9887:         return $defquota;
 9888:     }
 9889: }
 9890: 
 9891: ###############################################
 9892: 
 9893: =pod
 9894: 
 9895: =item * &excess_filesize_warning()
 9896: 
 9897: Returns warning message if upload of file to authoring space, or copying
 9898: of existing file within authoring space will cause quota for the authoring
 9899: space to be exceeded.
 9900: 
 9901: Same, if upload of a file directly to a course/community via Course Editor
 9902: will cause quota for uploaded content for the course to be exceeded.
 9903: 
 9904: Inputs: 7 
 9905: 1. username or coursenum
 9906: 2. domain
 9907: 3. context ('author' or 'course')
 9908: 4. filename of file for which action is being requested
 9909: 5. filesize (kB) of file
 9910: 6. action being taken: copy or upload.
 9911: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9912: 
 9913: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9914:          otherwise return null.
 9915: 
 9916: =back
 9917: 
 9918: =cut
 9919: 
 9920: sub excess_filesize_warning {
 9921:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9922:     my $current_disk_usage = 0;
 9923:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9924:     if ($context eq 'author') {
 9925:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9926:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9927:     } else {
 9928:         foreach my $subdir ('docs','supplemental') {
 9929:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9930:         }
 9931:     }
 9932:     $disk_quota = int($disk_quota * 1000);
 9933:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9934:         return '<p class="LC_warning">'.
 9935:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9936:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9937:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9938:                             $disk_quota,$current_disk_usage).
 9939:                '</p>';
 9940:     }
 9941:     return;
 9942: }
 9943: 
 9944: ###############################################
 9945: 
 9946: 
 9947: sub get_secgrprole_info {
 9948:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9949:     my %sections_count = &get_sections($cdom,$cnum);
 9950:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9951:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9952:     my @groups = sort(keys(%curr_groups));
 9953:     my $allroles = [];
 9954:     my $rolehash;
 9955:     my $accesshash = {
 9956:                      active => 'Currently has access',
 9957:                      future => 'Will have future access',
 9958:                      previous => 'Previously had access',
 9959:                   };
 9960:     if ($needroles) {
 9961:         $rolehash = {'all' => 'all'};
 9962:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9963: 	if (&Apache::lonnet::error(%user_roles)) {
 9964: 	    undef(%user_roles);
 9965: 	}
 9966:         foreach my $item (keys(%user_roles)) {
 9967:             my ($role)=split(/\:/,$item,2);
 9968:             if ($role eq 'cr') { next; }
 9969:             if ($role =~ /^cr/) {
 9970:                 $$rolehash{$role} = (split('/',$role))[3];
 9971:             } else {
 9972:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9973:             }
 9974:         }
 9975:         foreach my $key (sort(keys(%{$rolehash}))) {
 9976:             push(@{$allroles},$key);
 9977:         }
 9978:         push (@{$allroles},'st');
 9979:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9980:     }
 9981:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9982: }
 9983: 
 9984: sub user_picker {
 9985:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
 9986:     my $currdom = $dom;
 9987:     my @alldoms = &Apache::lonnet::all_domains();
 9988:     if (@alldoms == 1) {
 9989:         my %domsrch = &Apache::lonnet::get_dom('configuration',
 9990:                                                ['directorysrch'],$alldoms[0]);
 9991:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
 9992:         my $showdom = $domdesc;
 9993:         if ($showdom eq '') {
 9994:             $showdom = $dom;
 9995:         }
 9996:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
 9997:             if ((!$domsrch{'directorysrch'}{'available'}) &&
 9998:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
 9999:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10000:             }
10001:         }
10002:     }
10003:     my %curr_selected = (
10004:                         srchin => 'dom',
10005:                         srchby => 'lastname',
10006:                       );
10007:     my $srchterm;
10008:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10009:         if ($srch->{'srchby'} ne '') {
10010:             $curr_selected{'srchby'} = $srch->{'srchby'};
10011:         }
10012:         if ($srch->{'srchin'} ne '') {
10013:             $curr_selected{'srchin'} = $srch->{'srchin'};
10014:         }
10015:         if ($srch->{'srchtype'} ne '') {
10016:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10017:         }
10018:         if ($srch->{'srchdomain'} ne '') {
10019:             $currdom = $srch->{'srchdomain'};
10020:         }
10021:         $srchterm = $srch->{'srchterm'};
10022:     }
10023:     my %html_lt=&Apache::lonlocal::texthash(
10024:                     'usr'       => 'Search criteria',
10025:                     'doma'      => 'Domain/institution to search',
10026:                     'uname'     => 'username',
10027:                     'lastname'  => 'last name',
10028:                     'lastfirst' => 'last name, first name',
10029:                     'crs'       => 'in this course',
10030:                     'dom'       => 'in selected LON-CAPA domain', 
10031:                     'alc'       => 'all LON-CAPA',
10032:                     'instd'     => 'in institutional directory for selected domain',
10033:                     'exact'     => 'is',
10034:                     'contains'  => 'contains',
10035:                     'begins'    => 'begins with',
10036:                                        );
10037:     my %js_lt=&Apache::lonlocal::texthash(
10038:                     'youm'      => "You must include some text to search for.",
10039:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10040:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10041:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10042:                     'ymcd'      => "You must choose a domain when using a domain search.",
10043:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10044:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10045:                      'thfo'     => "The following need to be corrected before the search can be run:",
10046:                                        );
10047:     &html_escape(\%html_lt);
10048:     &js_escape(\%js_lt);
10049:     my $domform;
10050:     my $allow_blank = 1;
10051:     if ($fixeddom) {
10052:         $allow_blank = 0;
10053:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10054:     } else {
10055:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
10056:     }
10057:     my $srchinsel = ' <select name="srchin">';
10058: 
10059:     my @srchins = ('crs','dom','alc','instd');
10060: 
10061:     foreach my $option (@srchins) {
10062:         # FIXME 'alc' option unavailable until 
10063:         #       loncreateuser::print_user_query_page()
10064:         #       has been completed.
10065:         next if ($option eq 'alc');
10066:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10067:         next if ($option eq 'crs' && !$env{'request.course.id'});
10068:         next if (($option eq 'instd') && ($noinstd));
10069:         if ($curr_selected{'srchin'} eq $option) {
10070:             $srchinsel .= ' 
10071:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10072:         } else {
10073:             $srchinsel .= '
10074:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10075:         }
10076:     }
10077:     $srchinsel .= "\n  </select>\n";
10078: 
10079:     my $srchbysel =  ' <select name="srchby">';
10080:     foreach my $option ('lastname','lastfirst','uname') {
10081:         if ($curr_selected{'srchby'} eq $option) {
10082:             $srchbysel .= '
10083:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10084:         } else {
10085:             $srchbysel .= '
10086:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10087:          }
10088:     }
10089:     $srchbysel .= "\n  </select>\n";
10090: 
10091:     my $srchtypesel = ' <select name="srchtype">';
10092:     foreach my $option ('begins','contains','exact') {
10093:         if ($curr_selected{'srchtype'} eq $option) {
10094:             $srchtypesel .= '
10095:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10096:         } else {
10097:             $srchtypesel .= '
10098:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10099:         }
10100:     }
10101:     $srchtypesel .= "\n  </select>\n";
10102: 
10103:     my ($newuserscript,$new_user_create);
10104:     my $context_dom = $env{'request.role.domain'};
10105:     if ($context eq 'requestcrs') {
10106:         if ($env{'form.coursedom'} ne '') { 
10107:             $context_dom = $env{'form.coursedom'};
10108:         }
10109:     }
10110:     if ($forcenewuser) {
10111:         if (ref($srch) eq 'HASH') {
10112:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10113:                 if ($cancreate) {
10114:                     $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>';
10115:                 } else {
10116:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10117:                     my %usertypetext = (
10118:                         official   => 'institutional',
10119:                         unofficial => 'non-institutional',
10120:                     );
10121:                     $new_user_create = '<p class="LC_warning">'
10122:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10123:                                       .' '
10124:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10125:                                           ,'<a href="'.$helplink.'">','</a>')
10126:                                       .'</p><br />';
10127:                 }
10128:             }
10129:         }
10130: 
10131:         $newuserscript = <<"ENDSCRIPT";
10132: 
10133: function setSearch(createnew,callingForm) {
10134:     if (createnew == 1) {
10135:         for (var i=0; i<callingForm.srchby.length; i++) {
10136:             if (callingForm.srchby.options[i].value == 'uname') {
10137:                 callingForm.srchby.selectedIndex = i;
10138:             }
10139:         }
10140:         for (var i=0; i<callingForm.srchin.length; i++) {
10141:             if ( callingForm.srchin.options[i].value == 'dom') {
10142: 		callingForm.srchin.selectedIndex = i;
10143:             }
10144:         }
10145:         for (var i=0; i<callingForm.srchtype.length; i++) {
10146:             if (callingForm.srchtype.options[i].value == 'exact') {
10147:                 callingForm.srchtype.selectedIndex = i;
10148:             }
10149:         }
10150:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10151:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10152:                 callingForm.srchdomain.selectedIndex = i;
10153:             }
10154:         }
10155:     }
10156: }
10157: ENDSCRIPT
10158: 
10159:     }
10160: 
10161:     my $output = <<"END_BLOCK";
10162: <script type="text/javascript">
10163: // <![CDATA[
10164: function validateEntry(callingForm) {
10165: 
10166:     var checkok = 1;
10167:     var srchin;
10168:     for (var i=0; i<callingForm.srchin.length; i++) {
10169: 	if ( callingForm.srchin[i].checked ) {
10170: 	    srchin = callingForm.srchin[i].value;
10171: 	}
10172:     }
10173: 
10174:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10175:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10176:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10177:     var srchterm =  callingForm.srchterm.value;
10178:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10179:     var msg = "";
10180: 
10181:     if (srchterm == "") {
10182:         checkok = 0;
10183:         msg += "$js_lt{'youm'}\\n";
10184:     }
10185: 
10186:     if (srchtype== 'begins') {
10187:         if (srchterm.length < 2) {
10188:             checkok = 0;
10189:             msg += "$js_lt{'thte'}\\n";
10190:         }
10191:     }
10192: 
10193:     if (srchtype== 'contains') {
10194:         if (srchterm.length < 3) {
10195:             checkok = 0;
10196:             msg += "$js_lt{'thet'}\\n";
10197:         }
10198:     }
10199:     if (srchin == 'instd') {
10200:         if (srchdomain == '') {
10201:             checkok = 0;
10202:             msg += "$js_lt{'yomc'}\\n";
10203:         }
10204:     }
10205:     if (srchin == 'dom') {
10206:         if (srchdomain == '') {
10207:             checkok = 0;
10208:             msg += "$js_lt{'ymcd'}\\n";
10209:         }
10210:     }
10211:     if (srchby == 'lastfirst') {
10212:         if (srchterm.indexOf(",") == -1) {
10213:             checkok = 0;
10214:             msg += "$js_lt{'whus'}\\n";
10215:         }
10216:         if (srchterm.indexOf(",") == srchterm.length -1) {
10217:             checkok = 0;
10218:             msg += "$js_lt{'whse'}\\n";
10219:         }
10220:     }
10221:     if (checkok == 0) {
10222:         alert("$js_lt{'thfo'}\\n"+msg);
10223:         return;
10224:     }
10225:     if (checkok == 1) {
10226:         callingForm.submit();
10227:     }
10228: }
10229: 
10230: $newuserscript
10231: 
10232: // ]]>
10233: </script>
10234: 
10235: $new_user_create
10236: 
10237: END_BLOCK
10238: 
10239:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10240:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10241:                $domform.
10242:                &Apache::lonhtmlcommon::row_closure().
10243:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10244:                $srchbysel.
10245:                $srchtypesel. 
10246:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10247:                $srchinsel.
10248:                &Apache::lonhtmlcommon::row_closure(1). 
10249:                &Apache::lonhtmlcommon::end_pick_box().
10250:                '<br />';
10251:     return ($output,1);
10252: }
10253: 
10254: sub user_rule_check {
10255:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10256:     my ($response,%inst_response);
10257:     if (ref($usershash) eq 'HASH') {
10258:         if (keys(%{$usershash}) > 1) {
10259:             my (%by_username,%by_id,%userdoms);
10260:             my $checkid;
10261:             if (ref($checks) eq 'HASH') {
10262:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10263:                     $checkid = 1;
10264:                 }
10265:             }
10266:             foreach my $user (keys(%{$usershash})) {
10267:                 my ($uname,$udom) = split(/:/,$user);
10268:                 if ($checkid) {
10269:                     if (ref($usershash->{$user}) eq 'HASH') {
10270:                         if ($usershash->{$user}->{'id'} ne '') {
10271:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10272:                             $userdoms{$udom} = 1;
10273:                             if (ref($inst_results) eq 'HASH') {
10274:                                 $inst_results->{$uname.':'.$udom} = {};
10275:                             }
10276:                         }
10277:                     }
10278:                 } else {
10279:                     $by_username{$udom}{$uname} = 1;
10280:                     $userdoms{$udom} = 1;
10281:                     if (ref($inst_results) eq 'HASH') {
10282:                         $inst_results->{$uname.':'.$udom} = {};
10283:                     }
10284:                 }
10285:             }
10286:             foreach my $udom (keys(%userdoms)) {
10287:                 if (!$got_rules->{$udom}) {
10288:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10289:                                                              ['usercreation'],$udom);
10290:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10291:                         foreach my $item ('username','id') {
10292:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10293:                                 $$curr_rules{$udom}{$item} =
10294:                                     $domconfig{'usercreation'}{$item.'_rule'};
10295:                             }
10296:                         }
10297:                     }
10298:                     $got_rules->{$udom} = 1;
10299:                 }
10300:             }
10301:             if ($checkid) {
10302:                 foreach my $udom (keys(%by_id)) {
10303:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10304:                     if ($outcome eq 'ok') {
10305:                         foreach my $id (keys(%{$by_id{$udom}})) {
10306:                             my $uname = $by_id{$udom}{$id};
10307:                             $inst_response{$uname.':'.$udom} = $outcome;
10308:                         }
10309:                         if (ref($results) eq 'HASH') {
10310:                             foreach my $uname (keys(%{$results})) {
10311:                                 if (exists($inst_response{$uname.':'.$udom})) {
10312:                                     $inst_response{$uname.':'.$udom} = $outcome;
10313:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10314:                                 }
10315:                             }
10316:                         }
10317:                     }
10318:                 }
10319:             } else {
10320:                 foreach my $udom (keys(%by_username)) {
10321:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10322:                     if ($outcome eq 'ok') {
10323:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10324:                             $inst_response{$uname.':'.$udom} = $outcome;
10325:                         }
10326:                         if (ref($results) eq 'HASH') {
10327:                             foreach my $uname (keys(%{$results})) {
10328:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10329:                             }
10330:                         }
10331:                     }
10332:                 }
10333:             }
10334:         } elsif (keys(%{$usershash}) == 1) {
10335:             my $user = (keys(%{$usershash}))[0];
10336:             my ($uname,$udom) = split(/:/,$user);
10337:             if (($udom ne '') && ($uname ne '')) {
10338:                 if (ref($usershash->{$user}) eq 'HASH') {
10339:                     if (ref($checks) eq 'HASH') {
10340:                         if (defined($checks->{'username'})) {
10341:                             ($inst_response{$user},%{$inst_results->{$user}}) =
10342:                                 &Apache::lonnet::get_instuser($udom,$uname);
10343:                         } elsif (defined($checks->{'id'})) {
10344:                             if ($usershash->{$user}->{'id'} ne '') {
10345:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10346:                                     &Apache::lonnet::get_instuser($udom,undef,
10347:                                                                   $usershash->{$user}->{'id'});
10348:                             } else {
10349:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10350:                                     &Apache::lonnet::get_instuser($udom,$uname);
10351:                             }
10352:                         }
10353:                     } else {
10354:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10355:                             &Apache::lonnet::get_instuser($udom,$uname);
10356:                        return;
10357:                     }
10358:                     if (!$got_rules->{$udom}) {
10359:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10360:                                                                  ['usercreation'],$udom);
10361:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10362:                             foreach my $item ('username','id') {
10363:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10364:                                    $$curr_rules{$udom}{$item} =
10365:                                        $domconfig{'usercreation'}{$item.'_rule'};
10366:                                 }
10367:                             }
10368:                         }
10369:                         $got_rules->{$udom} = 1;
10370:                     }
10371:                 }
10372:             } else {
10373:                 return;
10374:             }
10375:         } else {
10376:             return;
10377:         }
10378:         foreach my $user (keys(%{$usershash})) {
10379:             my ($uname,$udom) = split(/:/,$user);
10380:             next if (($udom eq '') || ($uname eq ''));
10381:             my $id;
10382:             if (ref($inst_results) eq 'HASH') {
10383:                 if (ref($inst_results->{$user}) eq 'HASH') {
10384:                     $id = $inst_results->{$user}->{'id'};
10385:                 }
10386:             }
10387:             if ($id eq '') {
10388:                 if (ref($usershash->{$user})) {
10389:                     $id = $usershash->{$user}->{'id'};
10390:                 }
10391:             }
10392:             foreach my $item (keys(%{$checks})) {
10393:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10394:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10395:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10396:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10397:                                                                              $$curr_rules{$udom}{$item});
10398:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10399:                                 if ($rule_check{$rule}) {
10400:                                     $$rulematch{$user}{$item} = $rule;
10401:                                     if ($inst_response{$user} eq 'ok') {
10402:                                         if (ref($inst_results) eq 'HASH') {
10403:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10404:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10405:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10406:                                                 } elsif ($item eq 'id') {
10407:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10408:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10409:                                                     }
10410:                                                 }
10411:                                             }
10412:                                         }
10413:                                     }
10414:                                     last;
10415:                                 }
10416:                             }
10417:                         }
10418:                     }
10419:                 }
10420:             }
10421:         }
10422:     }
10423:     return;
10424: }
10425: 
10426: sub user_rule_formats {
10427:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10428:     my %text = ( 
10429:                  'username' => 'Usernames',
10430:                  'id'       => 'IDs',
10431:                );
10432:     my $output;
10433:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10434:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10435:         if (@{$ruleorder} > 0) {
10436:             $output = '<br />'.
10437:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10438:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10439:                       ' <ul>';
10440:             foreach my $rule (@{$ruleorder}) {
10441:                 if (ref($curr_rules) eq 'ARRAY') {
10442:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10443:                         if (ref($rules->{$rule}) eq 'HASH') {
10444:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10445:                                         $rules->{$rule}{'desc'}.'</li>';
10446:                         }
10447:                     }
10448:                 }
10449:             }
10450:             $output .= '</ul>';
10451:         }
10452:     }
10453:     return $output;
10454: }
10455: 
10456: sub instrule_disallow_msg {
10457:     my ($checkitem,$domdesc,$count,$mode) = @_;
10458:     my $response;
10459:     my %text = (
10460:                   item   => 'username',
10461:                   items  => 'usernames',
10462:                   match  => 'matches',
10463:                   do     => 'does',
10464:                   action => 'a username',
10465:                   one    => 'one',
10466:                );
10467:     if ($count > 1) {
10468:         $text{'item'} = 'usernames';
10469:         $text{'match'} ='match';
10470:         $text{'do'} = 'do';
10471:         $text{'action'} = 'usernames',
10472:         $text{'one'} = 'ones';
10473:     }
10474:     if ($checkitem eq 'id') {
10475:         $text{'items'} = 'IDs';
10476:         $text{'item'} = 'ID';
10477:         $text{'action'} = 'an ID';
10478:         if ($count > 1) {
10479:             $text{'item'} = 'IDs';
10480:             $text{'action'} = 'IDs';
10481:         }
10482:     }
10483:     $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 />';
10484:     if ($mode eq 'upload') {
10485:         if ($checkitem eq 'username') {
10486:             $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'}.");
10487:         } elsif ($checkitem eq 'id') {
10488:             $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.");
10489:         }
10490:     } elsif ($mode eq 'selfcreate') {
10491:         if ($checkitem eq 'id') {
10492:             $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.");
10493:         }
10494:     } else {
10495:         if ($checkitem eq 'username') {
10496:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10497:         } elsif ($checkitem eq 'id') {
10498:             $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.");
10499:         }
10500:     }
10501:     return $response;
10502: }
10503: 
10504: sub personal_data_fieldtitles {
10505:     my %fieldtitles = &Apache::lonlocal::texthash (
10506:                         id => 'Student/Employee ID',
10507:                         permanentemail => 'E-mail address',
10508:                         lastname => 'Last Name',
10509:                         firstname => 'First Name',
10510:                         middlename => 'Middle Name',
10511:                         generation => 'Generation',
10512:                         gen => 'Generation',
10513:                         inststatus => 'Affiliation',
10514:                    );
10515:     return %fieldtitles;
10516: }
10517: 
10518: sub sorted_inst_types {
10519:     my ($dom) = @_;
10520:     my ($usertypes,$order);
10521:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10522:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10523:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10524:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10525:     } else {
10526:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10527:     }
10528:     my $othertitle = &mt('All users');
10529:     if ($env{'request.course.id'}) {
10530:         $othertitle  = &mt('Any users');
10531:     }
10532:     my @types;
10533:     if (ref($order) eq 'ARRAY') {
10534:         @types = @{$order};
10535:     }
10536:     if (@types == 0) {
10537:         if (ref($usertypes) eq 'HASH') {
10538:             @types = sort(keys(%{$usertypes}));
10539:         }
10540:     }
10541:     if (keys(%{$usertypes}) > 0) {
10542:         $othertitle = &mt('Other users');
10543:     }
10544:     return ($othertitle,$usertypes,\@types);
10545: }
10546: 
10547: sub get_institutional_codes {
10548:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
10549: # Get complete list of course sections to update
10550:     my @currsections = ();
10551:     my @currxlists = ();
10552:     my (%unclutteredsec,%unclutteredlcsec);
10553:     my $coursecode = $$settings{'internal.coursecode'};
10554:     my $crskey = $crs.':'.$coursecode;
10555:     @{$unclutteredsec{$crskey}} = ();
10556:     @{$unclutteredlcsec{$crskey}} = ();
10557: 
10558:     if ($$settings{'internal.sectionnums'} ne '') {
10559:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10560:     }
10561: 
10562:     if ($$settings{'internal.crosslistings'} ne '') {
10563:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10564:     }
10565: 
10566:     if (@currxlists > 0) {
10567:         foreach my $xl (@currxlists) {
10568:             if ($xl =~ /^([^:]+):(\w*)$/) {
10569:                 unless (grep/^$1$/,@{$allcourses}) {
10570:                     push(@{$allcourses},$1);
10571:                     $$LC_code{$1} = $2;
10572:                 }
10573:             }
10574:         }
10575:     }
10576: 
10577:     if (@currsections > 0) {
10578:         foreach my $sec (@currsections) {
10579:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
10580:                 my $instsec = $1;
10581:                 my $lc_sec = $2;
10582:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
10583:                     push(@{$unclutteredsec{$crskey}},$instsec);
10584:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
10585:                 }
10586:             }
10587:         }
10588:     }
10589: 
10590:     if (@{$unclutteredsec{$crskey}} > 0) {
10591:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
10592:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
10593:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
10594:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
10595:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
10596:                     push(@{$allcourses},$sec);
10597:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
10598:                 }
10599:             }
10600:         }
10601:     }
10602:     return;
10603: }
10604: 
10605: sub get_standard_codeitems {
10606:     return ('Year','Semester','Department','Number','Section');
10607: }
10608: 
10609: =pod
10610: 
10611: =head1 Slot Helpers
10612: 
10613: =over 4
10614: 
10615: =item * sorted_slots()
10616: 
10617: Sorts an array of slot names in order of an optional sort key,
10618: default sort is by slot start time (earliest first). 
10619: 
10620: Inputs:
10621: 
10622: =over 4
10623: 
10624: slotsarr  - Reference to array of unsorted slot names.
10625: 
10626: slots     - Reference to hash of hash, where outer hash keys are slot names.
10627: 
10628: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10629: 
10630: =back
10631: 
10632: Returns:
10633: 
10634: =over 4
10635: 
10636: sorted   - An array of slot names sorted by a specified sort key 
10637:            (default sort key is start time of the slot).
10638: 
10639: =back
10640: 
10641: =cut
10642: 
10643: 
10644: sub sorted_slots {
10645:     my ($slotsarr,$slots,$sortkey) = @_;
10646:     if ($sortkey eq '') {
10647:         $sortkey = 'starttime';
10648:     }
10649:     my @sorted;
10650:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10651:         @sorted =
10652:             sort {
10653:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10654:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10655:                      }
10656:                      if (ref($slots->{$a})) { return -1;}
10657:                      if (ref($slots->{$b})) { return 1;}
10658:                      return 0;
10659:                  } @{$slotsarr};
10660:     }
10661:     return @sorted;
10662: }
10663: 
10664: =pod
10665: 
10666: =item * get_future_slots()
10667: 
10668: Inputs:
10669: 
10670: =over 4
10671: 
10672: cnum - course number
10673: 
10674: cdom - course domain
10675: 
10676: now - current UNIX time
10677: 
10678: symb - optional symb
10679: 
10680: =back
10681: 
10682: Returns:
10683: 
10684: =over 4
10685: 
10686: sorted_reservable - ref to array of student_schedulable slots currently 
10687:                     reservable, ordered by end date of reservation period.
10688: 
10689: reservable_now - ref to hash of student_schedulable slots currently
10690:                  reservable.
10691: 
10692:     Keys in inner hash are:
10693:     (a) symb: either blank or symb to which slot use is restricted.
10694:     (b) endreserve: end date of reservation period.
10695:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10696:         selected.
10697: 
10698: sorted_future - ref to array of student_schedulable slots reservable in
10699:                 the future, ordered by start date of reservation period.
10700: 
10701: future_reservable - ref to hash of student_schedulable slots reservable
10702:                     in the future.
10703: 
10704:     Keys in inner hash are:
10705:     (a) symb: either blank or symb to which slot use is restricted.
10706:     (b) startreserve:  start date of reservation period.
10707:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10708:         selected.
10709: 
10710: =back
10711: 
10712: =cut
10713: 
10714: sub get_future_slots {
10715:     my ($cnum,$cdom,$now,$symb) = @_;
10716:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10717:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10718:     foreach my $slot (keys(%slots)) {
10719:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10720:         if ($symb) {
10721:             next if (($slots{$slot}->{'symb'} ne '') && 
10722:                      ($slots{$slot}->{'symb'} ne $symb));
10723:         }
10724:         if (($slots{$slot}->{'starttime'} > $now) &&
10725:             ($slots{$slot}->{'endtime'} > $now)) {
10726:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10727:                 my $userallowed = 0;
10728:                 if ($slots{$slot}->{'allowedsections'}) {
10729:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10730:                     if (!defined($env{'request.role.sec'})
10731:                         && grep(/^No section assigned$/,@allowed_sec)) {
10732:                         $userallowed=1;
10733:                     } else {
10734:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10735:                             $userallowed=1;
10736:                         }
10737:                     }
10738:                     unless ($userallowed) {
10739:                         if (defined($env{'request.course.groups'})) {
10740:                             my @groups = split(/:/,$env{'request.course.groups'});
10741:                             foreach my $group (@groups) {
10742:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10743:                                     $userallowed=1;
10744:                                     last;
10745:                                 }
10746:                             }
10747:                         }
10748:                     }
10749:                 }
10750:                 if ($slots{$slot}->{'allowedusers'}) {
10751:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10752:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10753:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10754:                         $userallowed = 1;
10755:                     }
10756:                 }
10757:                 next unless($userallowed);
10758:             }
10759:             my $startreserve = $slots{$slot}->{'startreserve'};
10760:             my $endreserve = $slots{$slot}->{'endreserve'};
10761:             my $symb = $slots{$slot}->{'symb'};
10762:             my $uniqueperiod;
10763:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10764:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10765:             }
10766:             if (($startreserve < $now) &&
10767:                 (!$endreserve || $endreserve > $now)) {
10768:                 my $lastres = $endreserve;
10769:                 if (!$lastres) {
10770:                     $lastres = $slots{$slot}->{'starttime'};
10771:                 }
10772:                 $reservable_now{$slot} = {
10773:                                            symb       => $symb,
10774:                                            endreserve => $lastres,
10775:                                            uniqueperiod => $uniqueperiod,   
10776:                                          };
10777:             } elsif (($startreserve > $now) &&
10778:                      (!$endreserve || $endreserve > $startreserve)) {
10779:                 $future_reservable{$slot} = {
10780:                                               symb         => $symb,
10781:                                               startreserve => $startreserve,
10782:                                               uniqueperiod => $uniqueperiod,
10783:                                             };
10784:             }
10785:         }
10786:     }
10787:     my @unsorted_reservable = keys(%reservable_now);
10788:     if (@unsorted_reservable > 0) {
10789:         @sorted_reservable = 
10790:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10791:     }
10792:     my @unsorted_future = keys(%future_reservable);
10793:     if (@unsorted_future > 0) {
10794:         @sorted_future =
10795:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10796:     }
10797:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10798: }
10799: 
10800: =pod
10801: 
10802: =back
10803: 
10804: =head1 HTTP Helpers
10805: 
10806: =over 4
10807: 
10808: =item * &get_unprocessed_cgi($query,$possible_names)
10809: 
10810: Modify the %env hash to contain unprocessed CGI form parameters held in
10811: $query.  The parameters listed in $possible_names (an array reference),
10812: will be set in $env{'form.name'} if they do not already exist.
10813: 
10814: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10815: $possible_names is an ref to an array of form element names.  As an example:
10816: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10817: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10818: 
10819: =cut
10820: 
10821: sub get_unprocessed_cgi {
10822:   my ($query,$possible_names)= @_;
10823:   # $Apache::lonxml::debug=1;
10824:   foreach my $pair (split(/&/,$query)) {
10825:     my ($name, $value) = split(/=/,$pair);
10826:     $name = &unescape($name);
10827:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10828:       $value =~ tr/+/ /;
10829:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10830:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10831:     }
10832:   }
10833: }
10834: 
10835: =pod
10836: 
10837: =item * &cacheheader() 
10838: 
10839: returns cache-controlling header code
10840: 
10841: =cut
10842: 
10843: sub cacheheader {
10844:     unless ($env{'request.method'} eq 'GET') { return ''; }
10845:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10846:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10847:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10848:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10849:     return $output;
10850: }
10851: 
10852: =pod
10853: 
10854: =item * &no_cache($r) 
10855: 
10856: specifies header code to not have cache
10857: 
10858: =cut
10859: 
10860: sub no_cache {
10861:     my ($r) = @_;
10862:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10863: 	$env{'request.method'} ne 'GET') { return ''; }
10864:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10865:     $r->no_cache(1);
10866:     $r->header_out("Expires" => $date);
10867:     $r->header_out("Pragma" => "no-cache");
10868: }
10869: 
10870: sub content_type {
10871:     my ($r,$type,$charset) = @_;
10872:     if ($r) {
10873: 	#  Note that printout.pl calls this with undef for $r.
10874: 	&no_cache($r);
10875:     }
10876:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10877:     unless ($charset) {
10878: 	$charset=&Apache::lonlocal::current_encoding;
10879:     }
10880:     if ($charset) { $type.='; charset='.$charset; }
10881:     if ($r) {
10882: 	$r->content_type($type);
10883:     } else {
10884: 	print("Content-type: $type\n\n");
10885:     }
10886: }
10887: 
10888: =pod
10889: 
10890: =item * &add_to_env($name,$value) 
10891: 
10892: adds $name to the %env hash with value
10893: $value, if $name already exists, the entry is converted to an array
10894: reference and $value is added to the array.
10895: 
10896: =cut
10897: 
10898: sub add_to_env {
10899:   my ($name,$value)=@_;
10900:   if (defined($env{$name})) {
10901:     if (ref($env{$name})) {
10902:       #already have multiple values
10903:       push(@{ $env{$name} },$value);
10904:     } else {
10905:       #first time seeing multiple values, convert hash entry to an arrayref
10906:       my $first=$env{$name};
10907:       undef($env{$name});
10908:       push(@{ $env{$name} },$first,$value);
10909:     }
10910:   } else {
10911:     $env{$name}=$value;
10912:   }
10913: }
10914: 
10915: =pod
10916: 
10917: =item * &get_env_multiple($name) 
10918: 
10919: gets $name from the %env hash, it seemlessly handles the cases where multiple
10920: values may be defined and end up as an array ref.
10921: 
10922: returns an array of values
10923: 
10924: =cut
10925: 
10926: sub get_env_multiple {
10927:     my ($name) = @_;
10928:     my @values;
10929:     if (defined($env{$name})) {
10930:         # exists is it an array
10931:         if (ref($env{$name})) {
10932:             @values=@{ $env{$name} };
10933:         } else {
10934:             $values[0]=$env{$name};
10935:         }
10936:     }
10937:     return(@values);
10938: }
10939: 
10940: sub ask_for_embedded_content {
10941:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10942:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10943:         %currsubfile,%unused,$rem);
10944:     my $counter = 0;
10945:     my $numnew = 0;
10946:     my $numremref = 0;
10947:     my $numinvalid = 0;
10948:     my $numpathchg = 0;
10949:     my $numexisting = 0;
10950:     my $numunused = 0;
10951:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10952:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10953:     my $heading = &mt('Upload embedded files');
10954:     my $buttontext = &mt('Upload');
10955: 
10956:     if ($env{'request.course.id'}) {
10957:         if ($actionurl eq '/adm/dependencies') {
10958:             $navmap = Apache::lonnavmaps::navmap->new();
10959:         }
10960:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10961:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10962:     }
10963:     if (($actionurl eq '/adm/portfolio') ||
10964:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10965:         my $current_path='/';
10966:         if ($env{'form.currentpath'}) {
10967:             $current_path = $env{'form.currentpath'};
10968:         }
10969:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10970:             $udom = $cdom;
10971:             $uname = $cnum;
10972:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10973:         } else {
10974:             $udom = $env{'user.domain'};
10975:             $uname = $env{'user.name'};
10976:             $url = '/userfiles/portfolio';
10977:         }
10978:         $toplevel = $url.'/';
10979:         $url .= $current_path;
10980:         $getpropath = 1;
10981:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10982:              ($actionurl eq '/adm/imsimport')) { 
10983:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10984:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10985:         $toplevel = $url;
10986:         if ($rest ne '') {
10987:             $url .= $rest;
10988:         }
10989:     } elsif ($actionurl eq '/adm/coursedocs') {
10990:         if (ref($args) eq 'HASH') {
10991:             $url = $args->{'docs_url'};
10992:             $toplevel = $url;
10993:             if ($args->{'context'} eq 'paste') {
10994:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10995:                 ($path) =
10996:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10997:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10998:                 $fileloc =~ s{^/}{};
10999:             }
11000:         }
11001:     } elsif ($actionurl eq '/adm/dependencies') {
11002:         if ($env{'request.course.id'} ne '') {
11003:             if (ref($args) eq 'HASH') {
11004:                 $url = $args->{'docs_url'};
11005:                 $title = $args->{'docs_title'};
11006:                 $toplevel = $url;
11007:                 unless ($toplevel =~ m{^/}) {
11008:                     $toplevel = "/$url";
11009:                 }
11010:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11011:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11012:                     $path = $1;
11013:                 } else {
11014:                     ($path) =
11015:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11016:                 }
11017:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11018:                     $fileloc = $toplevel;
11019:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11020:                     my ($udom,$uname,$fname) =
11021:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11022:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11023:                 } else {
11024:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11025:                 }
11026:                 $fileloc =~ s{^/}{};
11027:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11028:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11029:             }
11030:         }
11031:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11032:         $udom = $cdom;
11033:         $uname = $cnum;
11034:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11035:         $toplevel = $url;
11036:         $path = $url;
11037:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11038:         $fileloc =~ s{^/}{};
11039:     }
11040:     foreach my $file (keys(%{$allfiles})) {
11041:         my $embed_file;
11042:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11043:             $embed_file = $1;
11044:         } else {
11045:             $embed_file = $file;
11046:         }
11047:         my ($absolutepath,$cleaned_file);
11048:         if ($embed_file =~ m{^\w+://}) {
11049:             $cleaned_file = $embed_file;
11050:             $newfiles{$cleaned_file} = 1;
11051:             $mapping{$cleaned_file} = $embed_file;
11052:         } else {
11053:             $cleaned_file = &clean_path($embed_file);
11054:             if ($embed_file =~ m{^/}) {
11055:                 $absolutepath = $embed_file;
11056:             }
11057:             if ($cleaned_file =~ m{/}) {
11058:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11059:                 $path = &check_for_traversal($path,$url,$toplevel);
11060:                 my $item = $fname;
11061:                 if ($path ne '') {
11062:                     $item = $path.'/'.$fname;
11063:                     $subdependencies{$path}{$fname} = 1;
11064:                 } else {
11065:                     $dependencies{$item} = 1;
11066:                 }
11067:                 if ($absolutepath) {
11068:                     $mapping{$item} = $absolutepath;
11069:                 } else {
11070:                     $mapping{$item} = $embed_file;
11071:                 }
11072:             } else {
11073:                 $dependencies{$embed_file} = 1;
11074:                 if ($absolutepath) {
11075:                     $mapping{$cleaned_file} = $absolutepath;
11076:                 } else {
11077:                     $mapping{$cleaned_file} = $embed_file;
11078:                 }
11079:             }
11080:         }
11081:     }
11082:     my $dirptr = 16384;
11083:     foreach my $path (keys(%subdependencies)) {
11084:         $currsubfile{$path} = {};
11085:         if (($actionurl eq '/adm/portfolio') ||
11086:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
11087:             my ($sublistref,$listerror) =
11088:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11089:             if (ref($sublistref) eq 'ARRAY') {
11090:                 foreach my $line (@{$sublistref}) {
11091:                     my ($file_name,$rest) = split(/\&/,$line,2);
11092:                     $currsubfile{$path}{$file_name} = 1;
11093:                 }
11094:             }
11095:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11096:             if (opendir(my $dir,$url.'/'.$path)) {
11097:                 my @subdir_list = grep(!/^\./,readdir($dir));
11098:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11099:             }
11100:         } elsif (($actionurl eq '/adm/dependencies') ||
11101:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11102:                   ($args->{'context'} eq 'paste')) ||
11103:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11104:             if ($env{'request.course.id'} ne '') {
11105:                 my $dir;
11106:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11107:                     $dir = $fileloc;
11108:                 } else {
11109:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11110:                 }
11111:                 if ($dir ne '') {
11112:                     my ($sublistref,$listerror) =
11113:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11114:                     if (ref($sublistref) eq 'ARRAY') {
11115:                         foreach my $line (@{$sublistref}) {
11116:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11117:                                 undef,$mtime)=split(/\&/,$line,12);
11118:                             unless (($testdir&$dirptr) ||
11119:                                     ($file_name =~ /^\.\.?$/)) {
11120:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11121:                             }
11122:                         }
11123:                     }
11124:                 }
11125:             }
11126:         }
11127:         foreach my $file (keys(%{$subdependencies{$path}})) {
11128:             if (exists($currsubfile{$path}{$file})) {
11129:                 my $item = $path.'/'.$file;
11130:                 unless ($mapping{$item} eq $item) {
11131:                     $pathchanges{$item} = 1;
11132:                 }
11133:                 $existing{$item} = 1;
11134:                 $numexisting ++;
11135:             } else {
11136:                 $newfiles{$path.'/'.$file} = 1;
11137:             }
11138:         }
11139:         if ($actionurl eq '/adm/dependencies') {
11140:             foreach my $path (keys(%currsubfile)) {
11141:                 if (ref($currsubfile{$path}) eq 'HASH') {
11142:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11143:                          unless ($subdependencies{$path}{$file}) {
11144:                              next if (($rem ne '') &&
11145:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11146:                                        (ref($navmap) &&
11147:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11148:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11149:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11150:                              $unused{$path.'/'.$file} = 1; 
11151:                          }
11152:                     }
11153:                 }
11154:             }
11155:         }
11156:     }
11157:     my %currfile;
11158:     if (($actionurl eq '/adm/portfolio') ||
11159:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11160:         my ($dirlistref,$listerror) =
11161:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11162:         if (ref($dirlistref) eq 'ARRAY') {
11163:             foreach my $line (@{$dirlistref}) {
11164:                 my ($file_name,$rest) = split(/\&/,$line,2);
11165:                 $currfile{$file_name} = 1;
11166:             }
11167:         }
11168:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11169:         if (opendir(my $dir,$url)) {
11170:             my @dir_list = grep(!/^\./,readdir($dir));
11171:             map {$currfile{$_} = 1;} @dir_list;
11172:         }
11173:     } elsif (($actionurl eq '/adm/dependencies') ||
11174:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11175:               ($args->{'context'} eq 'paste')) ||
11176:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11177:         if ($env{'request.course.id'} ne '') {
11178:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11179:             if ($dir ne '') {
11180:                 my ($dirlistref,$listerror) =
11181:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11182:                 if (ref($dirlistref) eq 'ARRAY') {
11183:                     foreach my $line (@{$dirlistref}) {
11184:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11185:                             $size,undef,$mtime)=split(/\&/,$line,12);
11186:                         unless (($testdir&$dirptr) ||
11187:                                 ($file_name =~ /^\.\.?$/)) {
11188:                             $currfile{$file_name} = [$size,$mtime];
11189:                         }
11190:                     }
11191:                 }
11192:             }
11193:         }
11194:     }
11195:     foreach my $file (keys(%dependencies)) {
11196:         if (exists($currfile{$file})) {
11197:             unless ($mapping{$file} eq $file) {
11198:                 $pathchanges{$file} = 1;
11199:             }
11200:             $existing{$file} = 1;
11201:             $numexisting ++;
11202:         } else {
11203:             $newfiles{$file} = 1;
11204:         }
11205:     }
11206:     foreach my $file (keys(%currfile)) {
11207:         unless (($file eq $filename) ||
11208:                 ($file eq $filename.'.bak') ||
11209:                 ($dependencies{$file})) {
11210:             if ($actionurl eq '/adm/dependencies') {
11211:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11212:                     next if (($rem ne '') &&
11213:                              (($env{"httpref.$rem".$file} ne '') ||
11214:                               (ref($navmap) &&
11215:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11216:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11217:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11218:                 }
11219:             }
11220:             $unused{$file} = 1;
11221:         }
11222:     }
11223:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11224:         ($args->{'context'} eq 'paste')) {
11225:         $counter = scalar(keys(%existing));
11226:         $numpathchg = scalar(keys(%pathchanges));
11227:         return ($output,$counter,$numpathchg,\%existing);
11228:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
11229:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11230:         $counter = scalar(keys(%existing));
11231:         $numpathchg = scalar(keys(%pathchanges));
11232:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11233:     }
11234:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11235:         if ($actionurl eq '/adm/dependencies') {
11236:             next if ($embed_file =~ m{^\w+://});
11237:         }
11238:         $upload_output .= &start_data_table_row().
11239:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11240:                           '<span class="LC_filename">'.$embed_file.'</span>';
11241:         unless ($mapping{$embed_file} eq $embed_file) {
11242:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11243:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11244:         }
11245:         $upload_output .= '</td>';
11246:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11247:             $upload_output.='<td align="right">'.
11248:                             '<span class="LC_info LC_fontsize_medium">'.
11249:                             &mt("URL points to web address").'</span>';
11250:             $numremref++;
11251:         } elsif ($args->{'error_on_invalid_names'}
11252:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11253:             $upload_output.='<td align="right"><span class="LC_warning">'.
11254:                             &mt('Invalid characters').'</span>';
11255:             $numinvalid++;
11256:         } else {
11257:             $upload_output .= '<td>'.
11258:                               &embedded_file_element('upload_embedded',$counter,
11259:                                                      $embed_file,\%mapping,
11260:                                                      $allfiles,$codebase,'upload');
11261:             $counter ++;
11262:             $numnew ++;
11263:         }
11264:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11265:     }
11266:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11267:         if ($actionurl eq '/adm/dependencies') {
11268:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11269:             $modify_output .= &start_data_table_row().
11270:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11271:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11272:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11273:                               '<td>'.$size.'</td>'.
11274:                               '<td>'.$mtime.'</td>'.
11275:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11276:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11277:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11278:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11279:                               &embedded_file_element('upload_embedded',$counter,
11280:                                                      $embed_file,\%mapping,
11281:                                                      $allfiles,$codebase,'modify').
11282:                               '</div></td>'.
11283:                               &end_data_table_row()."\n";
11284:             $counter ++;
11285:         } else {
11286:             $upload_output .= &start_data_table_row().
11287:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11288:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11289:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11290:                               &Apache::loncommon::end_data_table_row()."\n";
11291:         }
11292:     }
11293:     my $delidx = $counter;
11294:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11295:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11296:         $delete_output .= &start_data_table_row().
11297:                           '<td><img src="'.&icon($oldfile).'" />'.
11298:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11299:                           '<td>'.$size.'</td>'.
11300:                           '<td>'.$mtime.'</td>'.
11301:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11302:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11303:                           &embedded_file_element('upload_embedded',$delidx,
11304:                                                  $oldfile,\%mapping,$allfiles,
11305:                                                  $codebase,'delete').'</td>'.
11306:                           &end_data_table_row()."\n"; 
11307:         $numunused ++;
11308:         $delidx ++;
11309:     }
11310:     if ($upload_output) {
11311:         $upload_output = &start_data_table().
11312:                          $upload_output.
11313:                          &end_data_table()."\n";
11314:     }
11315:     if ($modify_output) {
11316:         $modify_output = &start_data_table().
11317:                          &start_data_table_header_row().
11318:                          '<th>'.&mt('File').'</th>'.
11319:                          '<th>'.&mt('Size (KB)').'</th>'.
11320:                          '<th>'.&mt('Modified').'</th>'.
11321:                          '<th>'.&mt('Upload replacement?').'</th>'.
11322:                          &end_data_table_header_row().
11323:                          $modify_output.
11324:                          &end_data_table()."\n";
11325:     }
11326:     if ($delete_output) {
11327:         $delete_output = &start_data_table().
11328:                          &start_data_table_header_row().
11329:                          '<th>'.&mt('File').'</th>'.
11330:                          '<th>'.&mt('Size (KB)').'</th>'.
11331:                          '<th>'.&mt('Modified').'</th>'.
11332:                          '<th>'.&mt('Delete?').'</th>'.
11333:                          &end_data_table_header_row().
11334:                          $delete_output.
11335:                          &end_data_table()."\n";
11336:     }
11337:     my $applies = 0;
11338:     if ($numremref) {
11339:         $applies ++;
11340:     }
11341:     if ($numinvalid) {
11342:         $applies ++;
11343:     }
11344:     if ($numexisting) {
11345:         $applies ++;
11346:     }
11347:     if ($counter || $numunused) {
11348:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11349:                   ' method="post" enctype="multipart/form-data">'."\n".
11350:                   $state.'<h3>'.$heading.'</h3>'; 
11351:         if ($actionurl eq '/adm/dependencies') {
11352:             if ($numnew) {
11353:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11354:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11355:                            $upload_output.'<br />'."\n";
11356:             }
11357:             if ($numexisting) {
11358:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11359:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11360:                            $modify_output.'<br />'."\n";
11361:                            $buttontext = &mt('Save changes');
11362:             }
11363:             if ($numunused) {
11364:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11365:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11366:                            $delete_output.'<br />'."\n";
11367:                            $buttontext = &mt('Save changes');
11368:             }
11369:         } else {
11370:             $output .= $upload_output.'<br />'."\n";
11371:         }
11372:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11373:                    $counter.'" />'."\n";
11374:         if ($actionurl eq '/adm/dependencies') { 
11375:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11376:                        $numnew.'" />'."\n";
11377:         } elsif ($actionurl eq '') {
11378:             $output .=  '<input type="hidden" name="phase" value="three" />';
11379:         }
11380:     } elsif ($applies) {
11381:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11382:         if ($applies > 1) {
11383:             $output .=  
11384:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11385:             if ($numremref) {
11386:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11387:             }
11388:             if ($numinvalid) {
11389:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11390:             }
11391:             if ($numexisting) {
11392:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11393:             }
11394:             $output .= '</ul><br />';
11395:         } elsif ($numremref) {
11396:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11397:         } elsif ($numinvalid) {
11398:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11399:         } elsif ($numexisting) {
11400:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11401:         }
11402:         $output .= $upload_output.'<br />';
11403:     }
11404:     my ($pathchange_output,$chgcount);
11405:     $chgcount = $counter;
11406:     if (keys(%pathchanges) > 0) {
11407:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11408:             if ($counter) {
11409:                 $output .= &embedded_file_element('pathchange',$chgcount,
11410:                                                   $embed_file,\%mapping,
11411:                                                   $allfiles,$codebase,'change');
11412:             } else {
11413:                 $pathchange_output .= 
11414:                     &start_data_table_row().
11415:                     '<td><input type ="checkbox" name="namechange" value="'.
11416:                     $chgcount.'" checked="checked" /></td>'.
11417:                     '<td>'.$mapping{$embed_file}.'</td>'.
11418:                     '<td>'.$embed_file.
11419:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11420:                                            \%mapping,$allfiles,$codebase,'change').
11421:                     '</td>'.&end_data_table_row();
11422:             }
11423:             $numpathchg ++;
11424:             $chgcount ++;
11425:         }
11426:     }
11427:     if (($counter) || ($numunused)) {
11428:         if ($numpathchg) {
11429:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11430:                        $numpathchg.'" />'."\n";
11431:         }
11432:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11433:             ($actionurl eq '/adm/imsimport')) {
11434:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11435:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11436:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11437:         } elsif ($actionurl eq '/adm/dependencies') {
11438:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11439:         }
11440:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11441:     } elsif ($numpathchg) {
11442:         my %pathchange = ();
11443:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11444:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11445:             $output .= '<p>'.&mt('or').'</p>'; 
11446:         }
11447:     }
11448:     return ($output,$counter,$numpathchg);
11449: }
11450: 
11451: =pod
11452: 
11453: =item * clean_path($name)
11454: 
11455: Performs clean-up of directories, subdirectories and filename in an
11456: embedded object, referenced in an HTML file which is being uploaded
11457: to a course or portfolio, where
11458: "Upload embedded images/multimedia files if HTML file" checkbox was
11459: checked.
11460: 
11461: Clean-up is similar to replacements in lonnet::clean_filename()
11462: except each / between sub-directory and next level is preserved.
11463: 
11464: =cut
11465: 
11466: sub clean_path {
11467:     my ($embed_file) = @_;
11468:     $embed_file =~s{^/+}{};
11469:     my @contents;
11470:     if ($embed_file =~ m{/}) {
11471:         @contents = split(/\//,$embed_file);
11472:     } else {
11473:         @contents = ($embed_file);
11474:     }
11475:     my $lastidx = scalar(@contents)-1;
11476:     for (my $i=0; $i<=$lastidx; $i++) {
11477:         $contents[$i]=~s{\\}{/}g;
11478:         $contents[$i]=~s/\s+/\_/g;
11479:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11480:         if ($i == $lastidx) {
11481:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11482:         }
11483:     }
11484:     if ($lastidx > 0) {
11485:         return join('/',@contents);
11486:     } else {
11487:         return $contents[0];
11488:     }
11489: }
11490: 
11491: sub embedded_file_element {
11492:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11493:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11494:                    (ref($codebase) eq 'HASH'));
11495:     my $output;
11496:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11497:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11498:     }
11499:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11500:                &escape($embed_file).'" />';
11501:     unless (($context eq 'upload_embedded') && 
11502:             ($mapping->{$embed_file} eq $embed_file)) {
11503:         $output .='
11504:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11505:     }
11506:     my $attrib;
11507:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11508:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11509:     }
11510:     $output .=
11511:         "\n\t\t".
11512:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11513:         $attrib.'" />';
11514:     if (exists($codebase->{$mapping->{$embed_file}})) {
11515:         $output .=
11516:             "\n\t\t".
11517:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11518:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11519:     }
11520:     return $output;
11521: }
11522: 
11523: sub get_dependency_details {
11524:     my ($currfile,$currsubfile,$embed_file) = @_;
11525:     my ($size,$mtime,$showsize,$showmtime);
11526:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11527:         if ($embed_file =~ m{/}) {
11528:             my ($path,$fname) = split(/\//,$embed_file);
11529:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11530:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11531:             }
11532:         } else {
11533:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11534:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11535:             }
11536:         }
11537:         $showsize = $size/1024.0;
11538:         $showsize = sprintf("%.1f",$showsize);
11539:         if ($mtime > 0) {
11540:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11541:         }
11542:     }
11543:     return ($showsize,$showmtime);
11544: }
11545: 
11546: sub ask_embedded_js {
11547:     return <<"END";
11548: <script type="text/javascript"">
11549: // <![CDATA[
11550: function toggleBrowse(counter) {
11551:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11552:     var fileid = document.getElementById('embedded_item_'+counter);
11553:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11554:     if (chkboxid.checked == true) {
11555:         uploaddivid.style.display='block';
11556:     } else {
11557:         uploaddivid.style.display='none';
11558:         fileid.value = '';
11559:     }
11560: }
11561: // ]]>
11562: </script>
11563: 
11564: END
11565: }
11566: 
11567: sub upload_embedded {
11568:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11569:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11570:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11571:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11572:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11573:         my $orig_uploaded_filename =
11574:             $env{'form.embedded_item_'.$i.'.filename'};
11575:         foreach my $type ('orig','ref','attrib','codebase') {
11576:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11577:                 $env{'form.embedded_'.$type.'_'.$i} =
11578:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11579:             }
11580:         }
11581:         my ($path,$fname) =
11582:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11583:         # no path, whole string is fname
11584:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11585:         $fname = &Apache::lonnet::clean_filename($fname);
11586:         # See if there is anything left
11587:         next if ($fname eq '');
11588: 
11589:         # Check if file already exists as a file or directory.
11590:         my ($state,$msg);
11591:         if ($context eq 'portfolio') {
11592:             my $port_path = $dirpath;
11593:             if ($group ne '') {
11594:                 $port_path = "groups/$group/$port_path";
11595:             }
11596:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11597:                                               $fname,$group,'embedded_item_'.$i,
11598:                                               $dir_root,$port_path,$disk_quota,
11599:                                               $current_disk_usage,$uname,$udom);
11600:             if ($state eq 'will_exceed_quota'
11601:                 || $state eq 'file_locked') {
11602:                 $output .= $msg;
11603:                 next;
11604:             }
11605:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11606:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11607:             if ($state eq 'exists') {
11608:                 $output .= $msg;
11609:                 next;
11610:             }
11611:         }
11612:         # Check if extension is valid
11613:         if (($fname =~ /\.(\w+)$/) &&
11614:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11615:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11616:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11617:             next;
11618:         } elsif (($fname =~ /\.(\w+)$/) &&
11619:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11620:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11621:             next;
11622:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11623:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11624:             next;
11625:         }
11626:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11627:         my $subdir = $path;
11628:         $subdir =~ s{/+$}{};
11629:         if ($context eq 'portfolio') {
11630:             my $result;
11631:             if ($state eq 'existingfile') {
11632:                 $result=
11633:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11634:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11635:             } else {
11636:                 $result=
11637:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11638:                                                     $dirpath.
11639:                                                     $env{'form.currentpath'}.$subdir);
11640:                 if ($result !~ m|^/uploaded/|) {
11641:                     $output .= '<span class="LC_error">'
11642:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11643:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11644:                                .'</span><br />';
11645:                     next;
11646:                 } else {
11647:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11648:                                $path.$fname.'</span>').'<br />';     
11649:                 }
11650:             }
11651:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11652:             my $extendedsubdir = $dirpath.'/'.$subdir;
11653:             $extendedsubdir =~ s{/+$}{};
11654:             my $result =
11655:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11656:             if ($result !~ m|^/uploaded/|) {
11657:                 $output .= '<span class="LC_error">'
11658:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11659:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11660:                            .'</span><br />';
11661:                     next;
11662:             } else {
11663:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11664:                            $path.$fname.'</span>').'<br />';
11665:                 if ($context eq 'syllabus') {
11666:                     &Apache::lonnet::make_public_indefinitely($result);
11667:                 }
11668:             }
11669:         } else {
11670: # Save the file
11671:             my $target = $env{'form.embedded_item_'.$i};
11672:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11673:             my $dest = $fullpath.$fname;
11674:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11675:             my @parts=split(/\//,"$dirpath/$path");
11676:             my $count;
11677:             my $filepath = $dir_root;
11678:             foreach my $subdir (@parts) {
11679:                 $filepath .= "/$subdir";
11680:                 if (!-e $filepath) {
11681:                     mkdir($filepath,0770);
11682:                 }
11683:             }
11684:             my $fh;
11685:             if (!open($fh,'>'.$dest)) {
11686:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11687:                 $output .= '<span class="LC_error">'.
11688:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11689:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11690:                            '</span><br />';
11691:             } else {
11692:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11693:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11694:                     $output .= '<span class="LC_error">'.
11695:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11696:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11697:                               '</span><br />';
11698:                 } else {
11699:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11700:                                $url.'</span>').'<br />';
11701:                     unless ($context eq 'testbank') {
11702:                         $footer .= &mt('View embedded file: [_1]',
11703:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11704:                     }
11705:                 }
11706:                 close($fh);
11707:             }
11708:         }
11709:         if ($env{'form.embedded_ref_'.$i}) {
11710:             $pathchange{$i} = 1;
11711:         }
11712:     }
11713:     if ($output) {
11714:         $output = '<p>'.$output.'</p>';
11715:     }
11716:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11717:     $returnflag = 'ok';
11718:     my $numpathchgs = scalar(keys(%pathchange));
11719:     if ($numpathchgs > 0) {
11720:         if ($context eq 'portfolio') {
11721:             $output .= '<p>'.&mt('or').'</p>';
11722:         } elsif ($context eq 'testbank') {
11723:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11724:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11725:             $returnflag = 'modify_orightml';
11726:         }
11727:     }
11728:     return ($output.$footer,$returnflag,$numpathchgs);
11729: }
11730: 
11731: sub modify_html_form {
11732:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11733:     my $end = 0;
11734:     my $modifyform;
11735:     if ($context eq 'upload_embedded') {
11736:         return unless (ref($pathchange) eq 'HASH');
11737:         if ($env{'form.number_embedded_items'}) {
11738:             $end += $env{'form.number_embedded_items'};
11739:         }
11740:         if ($env{'form.number_pathchange_items'}) {
11741:             $end += $env{'form.number_pathchange_items'};
11742:         }
11743:         if ($end) {
11744:             for (my $i=0; $i<$end; $i++) {
11745:                 if ($i < $env{'form.number_embedded_items'}) {
11746:                     next unless($pathchange->{$i});
11747:                 }
11748:                 $modifyform .=
11749:                     &start_data_table_row().
11750:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11751:                     'checked="checked" /></td>'.
11752:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11753:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11754:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11755:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11756:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11757:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11758:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11759:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11760:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11761:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11762:                     &end_data_table_row();
11763:             }
11764:         }
11765:     } else {
11766:         $modifyform = $pathchgtable;
11767:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11768:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11769:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11770:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11771:         }
11772:     }
11773:     if ($modifyform) {
11774:         if ($actionurl eq '/adm/dependencies') {
11775:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11776:         }
11777:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11778:                '<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".
11779:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11780:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11781:                '</ol></p>'."\n".'<p>'.
11782:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11783:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11784:                &start_data_table()."\n".
11785:                &start_data_table_header_row().
11786:                '<th>'.&mt('Change?').'</th>'.
11787:                '<th>'.&mt('Current reference').'</th>'.
11788:                '<th>'.&mt('Required reference').'</th>'.
11789:                &end_data_table_header_row()."\n".
11790:                $modifyform.
11791:                &end_data_table().'<br />'."\n".$hiddenstate.
11792:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11793:                '</form>'."\n";
11794:     }
11795:     return;
11796: }
11797: 
11798: sub modify_html_refs {
11799:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11800:     my $container;
11801:     if ($context eq 'portfolio') {
11802:         $container = $env{'form.container'};
11803:     } elsif ($context eq 'coursedoc') {
11804:         $container = $env{'form.primaryurl'};
11805:     } elsif ($context eq 'manage_dependencies') {
11806:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11807:         $container = "/$container";
11808:     } elsif ($context eq 'syllabus') {
11809:         $container = $url;
11810:     } else {
11811:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11812:     }
11813:     my (%allfiles,%codebase,$output,$content);
11814:     my @changes = &get_env_multiple('form.namechange');
11815:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
11816:         if (wantarray) {
11817:             return ('',0,0); 
11818:         } else {
11819:             return;
11820:         }
11821:     }
11822:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11823:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11824:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11825:             if (wantarray) {
11826:                 return ('',0,0);
11827:             } else {
11828:                 return;
11829:             }
11830:         } 
11831:         $content = &Apache::lonnet::getfile($container);
11832:         if ($content eq '-1') {
11833:             if (wantarray) {
11834:                 return ('',0,0);
11835:             } else {
11836:                 return;
11837:             }
11838:         }
11839:     } else {
11840:         unless ($container =~ /^\Q$dir_root\E/) {
11841:             if (wantarray) {
11842:                 return ('',0,0);
11843:             } else {
11844:                 return;
11845:             }
11846:         } 
11847:         if (open(my $fh,'<',$container)) {
11848:             $content = join('', <$fh>);
11849:             close($fh);
11850:         } else {
11851:             if (wantarray) {
11852:                 return ('',0,0);
11853:             } else {
11854:                 return;
11855:             }
11856:         }
11857:     }
11858:     my ($count,$codebasecount) = (0,0);
11859:     my $mm = new File::MMagic;
11860:     my $mime_type = $mm->checktype_contents($content);
11861:     if ($mime_type eq 'text/html') {
11862:         my $parse_result = 
11863:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11864:                                                     \%codebase,\$content);
11865:         if ($parse_result eq 'ok') {
11866:             foreach my $i (@changes) {
11867:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11868:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11869:                 if ($allfiles{$ref}) {
11870:                     my $newname =  $orig;
11871:                     my ($attrib_regexp,$codebase);
11872:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11873:                     if ($attrib_regexp =~ /:/) {
11874:                         $attrib_regexp =~ s/\:/|/g;
11875:                     }
11876:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11877:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11878:                         $count += $numchg;
11879:                         $allfiles{$newname} = $allfiles{$ref};
11880:                         delete($allfiles{$ref});
11881:                     }
11882:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11883:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11884:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11885:                         $codebasecount ++;
11886:                     }
11887:                 }
11888:             }
11889:             my $skiprewrites;
11890:             if ($count || $codebasecount) {
11891:                 my $saveresult;
11892:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11893:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11894:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11895:                     if ($url eq $container) {
11896:                         my ($fname) = ($container =~ m{/([^/]+)$});
11897:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11898:                                             $count,'<span class="LC_filename">'.
11899:                                             $fname.'</span>').'</p>';
11900:                     } else {
11901:                          $output = '<p class="LC_error">'.
11902:                                    &mt('Error: update failed for: [_1].',
11903:                                    '<span class="LC_filename">'.
11904:                                    $container.'</span>').'</p>';
11905:                     }
11906:                     if ($context eq 'syllabus') {
11907:                         unless ($saveresult eq 'ok') {
11908:                             $skiprewrites = 1;
11909:                         }
11910:                     }
11911:                 } else {
11912:                     if (open(my $fh,'>',$container)) {
11913:                         print $fh $content;
11914:                         close($fh);
11915:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11916:                                   $count,'<span class="LC_filename">'.
11917:                                   $container.'</span>').'</p>';
11918:                     } else {
11919:                          $output = '<p class="LC_error">'.
11920:                                    &mt('Error: could not update [_1].',
11921:                                    '<span class="LC_filename">'.
11922:                                    $container.'</span>').'</p>';
11923:                     }
11924:                 }
11925:             }
11926:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11927:                 my ($actionurl,$state);
11928:                 $actionurl = "/public/$udom/$uname/syllabus";
11929:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11930:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11931:                                               \%codebase,
11932:                                               {'context' => 'rewrites',
11933:                                                'ignore_remote_references' => 1,});
11934:                 if (ref($mapping) eq 'HASH') {
11935:                     my $rewrites = 0;
11936:                     foreach my $key (keys(%{$mapping})) {
11937:                         next if ($key =~ m{^https?://});
11938:                         my $ref = $mapping->{$key};
11939:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11940:                         my $attrib;
11941:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11942:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11943:                         }
11944:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11945:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11946:                             $rewrites += $numchg;
11947:                         }
11948:                     }
11949:                     if ($rewrites) {
11950:                         my $saveresult;
11951:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11952:                         if ($url eq $container) {
11953:                             my ($fname) = ($container =~ m{/([^/]+)$});
11954:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11955:                                             $count,'<span class="LC_filename">'.
11956:                                             $fname.'</span>').'</p>';
11957:                         } else {
11958:                             $output .= '<p class="LC_error">'.
11959:                                        &mt('Error: could not update links in [_1].',
11960:                                        '<span class="LC_filename">'.
11961:                                        $container.'</span>').'</p>';
11962: 
11963:                         }
11964:                     }
11965:                 }
11966:             }
11967:         } else {
11968:             &logthis('Failed to parse '.$container.
11969:                      ' to modify references: '.$parse_result);
11970:         }
11971:     }
11972:     if (wantarray) {
11973:         return ($output,$count,$codebasecount);
11974:     } else {
11975:         return $output;
11976:     }
11977: }
11978: 
11979: sub check_for_existing {
11980:     my ($path,$fname,$element) = @_;
11981:     my ($state,$msg);
11982:     if (-d $path.'/'.$fname) {
11983:         $state = 'exists';
11984:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11985:     } elsif (-e $path.'/'.$fname) {
11986:         $state = 'exists';
11987:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11988:     }
11989:     if ($state eq 'exists') {
11990:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11991:     }
11992:     return ($state,$msg);
11993: }
11994: 
11995: sub check_for_upload {
11996:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11997:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11998:     my $filesize = length($env{'form.'.$element});
11999:     if (!$filesize) {
12000:         my $msg = '<span class="LC_error">'.
12001:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12002:                       '<span class="LC_filename">'.$fname.'</span>',
12003:                       $filesize).'<br />'.
12004:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12005:                   '</span>';
12006:         return ('zero_bytes',$msg);
12007:     }
12008:     $filesize =  $filesize/1000; #express in k (1024?)
12009:     my $getpropath = 1;
12010:     my ($dirlistref,$listerror) =
12011:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12012:     my $found_file = 0;
12013:     my $locked_file = 0;
12014:     my @lockers;
12015:     my $navmap;
12016:     if ($env{'request.course.id'}) {
12017:         $navmap = Apache::lonnavmaps::navmap->new();
12018:     }
12019:     if (ref($dirlistref) eq 'ARRAY') {
12020:         foreach my $line (@{$dirlistref}) {
12021:             my ($file_name,$rest)=split(/\&/,$line,2);
12022:             if ($file_name eq $fname){
12023:                 $file_name = $path.$file_name;
12024:                 if ($group ne '') {
12025:                     $file_name = $group.$file_name;
12026:                 }
12027:                 $found_file = 1;
12028:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12029:                     foreach my $lock (@lockers) {
12030:                         if (ref($lock) eq 'ARRAY') {
12031:                             my ($symb,$crsid) = @{$lock};
12032:                             if ($crsid eq $env{'request.course.id'}) {
12033:                                 if (ref($navmap)) {
12034:                                     my $res = $navmap->getBySymb($symb);
12035:                                     foreach my $part (@{$res->parts()}) { 
12036:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12037:                                         unless (($slot_status == $res->RESERVED) ||
12038:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12039:                                             $locked_file = 1;
12040:                                         }
12041:                                     }
12042:                                 } else {
12043:                                     $locked_file = 1;
12044:                                 }
12045:                             } else {
12046:                                 $locked_file = 1;
12047:                             }
12048:                         }
12049:                    }
12050:                 } else {
12051:                     my @info = split(/\&/,$rest);
12052:                     my $currsize = $info[6]/1000;
12053:                     if ($currsize < $filesize) {
12054:                         my $extra = $filesize - $currsize;
12055:                         if (($current_disk_usage + $extra) > $disk_quota) {
12056:                             my $msg = '<p class="LC_warning">'.
12057:                                       &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.',
12058:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12059:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12060:                                                    $disk_quota,$current_disk_usage).'</p>';
12061:                             return ('will_exceed_quota',$msg);
12062:                         }
12063:                     }
12064:                 }
12065:             }
12066:         }
12067:     }
12068:     if (($current_disk_usage + $filesize) > $disk_quota){
12069:         my $msg = '<p class="LC_warning">'.
12070:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12071:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12072:         return ('will_exceed_quota',$msg);
12073:     } elsif ($found_file) {
12074:         if ($locked_file) {
12075:             my $msg = '<p class="LC_warning">';
12076:             $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>');
12077:             $msg .= '</p>';
12078:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12079:             return ('file_locked',$msg);
12080:         } else {
12081:             my $msg = '<p class="LC_error">';
12082:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12083:             $msg .= '</p>';
12084:             return ('existingfile',$msg);
12085:         }
12086:     }
12087: }
12088: 
12089: sub check_for_traversal {
12090:     my ($path,$url,$toplevel) = @_;
12091:     my @parts=split(/\//,$path);
12092:     my $cleanpath;
12093:     my $fullpath = $url;
12094:     for (my $i=0;$i<@parts;$i++) {
12095:         next if ($parts[$i] eq '.');
12096:         if ($parts[$i] eq '..') {
12097:             $fullpath =~ s{([^/]+/)$}{};
12098:         } else {
12099:             $fullpath .= $parts[$i].'/';
12100:         }
12101:     }
12102:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12103:         $cleanpath = $1;
12104:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12105:         my $curr_toprel = $1;
12106:         my @parts = split(/\//,$curr_toprel);
12107:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12108:         my @urlparts = split(/\//,$url_toprel);
12109:         my $doubledots;
12110:         my $startdiff = -1;
12111:         for (my $i=0; $i<@urlparts; $i++) {
12112:             if ($startdiff == -1) {
12113:                 unless ($urlparts[$i] eq $parts[$i]) {
12114:                     $startdiff = $i;
12115:                     $doubledots .= '../';
12116:                 }
12117:             } else {
12118:                 $doubledots .= '../';
12119:             }
12120:         }
12121:         if ($startdiff > -1) {
12122:             $cleanpath = $doubledots;
12123:             for (my $i=$startdiff; $i<@parts; $i++) {
12124:                 $cleanpath .= $parts[$i].'/';
12125:             }
12126:         }
12127:     }
12128:     $cleanpath =~ s{(/)$}{};
12129:     return $cleanpath;
12130: }
12131: 
12132: sub is_archive_file {
12133:     my ($mimetype) = @_;
12134:     if (($mimetype eq 'application/octet-stream') ||
12135:         ($mimetype eq 'application/x-stuffit') ||
12136:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12137:         return 1;
12138:     }
12139:     return;
12140: }
12141: 
12142: sub decompress_form {
12143:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12144:     my %lt = &Apache::lonlocal::texthash (
12145:         this => 'This file is an archive file.',
12146:         camt => 'This file is a Camtasia archive file.',
12147:         itsc => 'Its contents are as follows:',
12148:         youm => 'You may wish to extract its contents.',
12149:         extr => 'Extract contents',
12150:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12151:         proa => 'Process automatically?',
12152:         yes  => 'Yes',
12153:         no   => 'No',
12154:         fold => 'Title for folder containing movie',
12155:         movi => 'Title for page containing embedded movie', 
12156:     );
12157:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12158:     my ($is_camtasia,$topdir,%toplevel,@paths);
12159:     my $info = &list_archive_contents($fileloc,\@paths);
12160:     if (@paths) {
12161:         foreach my $path (@paths) {
12162:             $path =~ s{^/}{};
12163:             if ($path =~ m{^([^/]+)/$}) {
12164:                 $topdir = $1;
12165:             }
12166:             if ($path =~ m{^([^/]+)/}) {
12167:                 $toplevel{$1} = $path;
12168:             } else {
12169:                 $toplevel{$path} = $path;
12170:             }
12171:         }
12172:     }
12173:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12174:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12175:                         "$topdir/media/",
12176:                         "$topdir/media/$topdir.mp4",
12177:                         "$topdir/media/FirstFrame.png",
12178:                         "$topdir/media/player.swf",
12179:                         "$topdir/media/swfobject.js",
12180:                         "$topdir/media/expressInstall.swf");
12181:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12182:                          "$topdir/$topdir.mp4",
12183:                          "$topdir/$topdir\_config.xml",
12184:                          "$topdir/$topdir\_controller.swf",
12185:                          "$topdir/$topdir\_embed.css",
12186:                          "$topdir/$topdir\_First_Frame.png",
12187:                          "$topdir/$topdir\_player.html",
12188:                          "$topdir/$topdir\_Thumbnails.png",
12189:                          "$topdir/playerProductInstall.swf",
12190:                          "$topdir/scripts/",
12191:                          "$topdir/scripts/config_xml.js",
12192:                          "$topdir/scripts/handlebars.js",
12193:                          "$topdir/scripts/jquery-1.7.1.min.js",
12194:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12195:                          "$topdir/scripts/modernizr.js",
12196:                          "$topdir/scripts/player-min.js",
12197:                          "$topdir/scripts/swfobject.js",
12198:                          "$topdir/skins/",
12199:                          "$topdir/skins/configuration_express.xml",
12200:                          "$topdir/skins/express_show/",
12201:                          "$topdir/skins/express_show/player-min.css",
12202:                          "$topdir/skins/express_show/spritesheet.png");
12203:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12204:                          "$topdir/$topdir.mp4",
12205:                          "$topdir/$topdir\_config.xml",
12206:                          "$topdir/$topdir\_controller.swf",
12207:                          "$topdir/$topdir\_embed.css",
12208:                          "$topdir/$topdir\_First_Frame.png",
12209:                          "$topdir/$topdir\_player.html",
12210:                          "$topdir/$topdir\_Thumbnails.png",
12211:                          "$topdir/playerProductInstall.swf",
12212:                          "$topdir/scripts/",
12213:                          "$topdir/scripts/config_xml.js",
12214:                          "$topdir/scripts/techsmith-smart-player.min.js",
12215:                          "$topdir/skins/",
12216:                          "$topdir/skins/configuration_express.xml",
12217:                          "$topdir/skins/express_show/",
12218:                          "$topdir/skins/express_show/spritesheet.min.css",
12219:                          "$topdir/skins/express_show/spritesheet.png",
12220:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12221:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12222:         if (@diffs == 0) {
12223:             $is_camtasia = 6;
12224:         } else {
12225:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12226:             if (@diffs == 0) {
12227:                 $is_camtasia = 8;
12228:             } else {
12229:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12230:                 if (@diffs == 0) {
12231:                     $is_camtasia = 8;
12232:                 }
12233:             }
12234:         }
12235:     }
12236:     my $output;
12237:     if ($is_camtasia) {
12238:         $output = <<"ENDCAM";
12239: <script type="text/javascript" language="Javascript">
12240: // <![CDATA[
12241: 
12242: function camtasiaToggle() {
12243:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12244:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12245:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12246:                 document.getElementById('camtasia_titles').style.display='block';
12247:             } else {
12248:                 document.getElementById('camtasia_titles').style.display='none';
12249:             }
12250:         }
12251:     }
12252:     return;
12253: }
12254: 
12255: // ]]>
12256: </script>
12257: <p>$lt{'camt'}</p>
12258: ENDCAM
12259:     } else {
12260:         $output = '<p>'.$lt{'this'};
12261:         if ($info eq '') {
12262:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12263:         } else {
12264:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12265:                        '<div><pre>'.$info.'</pre></div>';
12266:         }
12267:     }
12268:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12269:     my $duplicates;
12270:     my $num = 0;
12271:     if (ref($dirlist) eq 'ARRAY') {
12272:         foreach my $item (@{$dirlist}) {
12273:             if (ref($item) eq 'ARRAY') {
12274:                 if (exists($toplevel{$item->[0]})) {
12275:                     $duplicates .= 
12276:                         &start_data_table_row().
12277:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12278:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12279:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12280:                         'value="1" />'.&mt('Yes').'</label>'.
12281:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12282:                         '<td>'.$item->[0].'</td>';
12283:                     if ($item->[2]) {
12284:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12285:                     } else {
12286:                         $duplicates .= '<td>'.&mt('File').'</td>';
12287:                     }
12288:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12289:                                    '<td>'.
12290:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12291:                                    '</td>'.
12292:                                    &end_data_table_row();
12293:                     $num ++;
12294:                 }
12295:             }
12296:         }
12297:     }
12298:     my $itemcount;
12299:     if (@paths > 0) {
12300:         $itemcount = scalar(@paths);
12301:     } else {
12302:         $itemcount = 1;
12303:     }
12304:     if ($is_camtasia) {
12305:         $output .= $lt{'auto'}.'<br />'.
12306:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12307:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12308:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12309:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12310:                    $lt{'no'}.'</label></span><br />'.
12311:                    '<div id="camtasia_titles" style="display:block">'.
12312:                    &Apache::lonhtmlcommon::start_pick_box().
12313:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12314:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12315:                    &Apache::lonhtmlcommon::row_closure().
12316:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12317:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12318:                    &Apache::lonhtmlcommon::row_closure(1).
12319:                    &Apache::lonhtmlcommon::end_pick_box().
12320:                    '</div>';
12321:     }
12322:     $output .= 
12323:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12324:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12325:         "\n";
12326:     if ($duplicates ne '') {
12327:         $output .= '<p><span class="LC_warning">'.
12328:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12329:                    &start_data_table().
12330:                    &start_data_table_header_row().
12331:                    '<th>'.&mt('Overwrite?').'</th>'.
12332:                    '<th>'.&mt('Name').'</th>'.
12333:                    '<th>'.&mt('Type').'</th>'.
12334:                    '<th>'.&mt('Size').'</th>'.
12335:                    '<th>'.&mt('Last modified').'</th>'.
12336:                    &end_data_table_header_row().
12337:                    $duplicates.
12338:                    &end_data_table().
12339:                    '</p>';
12340:     }
12341:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12342:     if (ref($hiddenelements) eq 'HASH') {
12343:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12344:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12345:         }
12346:     }
12347:     $output .= <<"END";
12348: <br />
12349: <input type="submit" name="decompress" value="$lt{'extr'}" />
12350: </form>
12351: $noextract
12352: END
12353:     return $output;
12354: }
12355: 
12356: sub decompression_utility {
12357:     my ($program) = @_;
12358:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12359:     my $location;
12360:     if (grep(/^\Q$program\E$/,@utilities)) { 
12361:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12362:                          '/usr/sbin/') {
12363:             if (-x $dir.$program) {
12364:                 $location = $dir.$program;
12365:                 last;
12366:             }
12367:         }
12368:     }
12369:     return $location;
12370: }
12371: 
12372: sub list_archive_contents {
12373:     my ($file,$pathsref) = @_;
12374:     my (@cmd,$output);
12375:     my $needsregexp;
12376:     if ($file =~ /\.zip$/) {
12377:         @cmd = (&decompression_utility('unzip'),"-l");
12378:         $needsregexp = 1;
12379:     } elsif (($file =~ m/\.tar\.gz$/) ||
12380:              ($file =~ /\.tgz$/)) {
12381:         @cmd = (&decompression_utility('tar'),"-ztf");
12382:     } elsif ($file =~ /\.tar\.bz2$/) {
12383:         @cmd = (&decompression_utility('tar'),"-jtf");
12384:     } elsif ($file =~ m|\.tar$|) {
12385:         @cmd = (&decompression_utility('tar'),"-tf");
12386:     }
12387:     if (@cmd) {
12388:         undef($!);
12389:         undef($@);
12390:         if (open(my $fh,"-|", @cmd, $file)) {
12391:             while (my $line = <$fh>) {
12392:                 $output .= $line;
12393:                 chomp($line);
12394:                 my $item;
12395:                 if ($needsregexp) {
12396:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12397:                 } else {
12398:                     $item = $line;
12399:                 }
12400:                 if ($item ne '') {
12401:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12402:                         push(@{$pathsref},$item);
12403:                     } 
12404:                 }
12405:             }
12406:             close($fh);
12407:         }
12408:     }
12409:     return $output;
12410: }
12411: 
12412: sub decompress_uploaded_file {
12413:     my ($file,$dir) = @_;
12414:     &Apache::lonnet::appenv({'cgi.file' => $file});
12415:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12416:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12417:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12418:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12419:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12420:     my $decompressed = $env{'cgi.decompressed'};
12421:     &Apache::lonnet::delenv('cgi.file');
12422:     &Apache::lonnet::delenv('cgi.dir');
12423:     &Apache::lonnet::delenv('cgi.decompressed');
12424:     return ($decompressed,$result);
12425: }
12426: 
12427: sub process_decompression {
12428:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12429:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12430:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12431:                &mt('Unexpected file path.').'</p>'."\n";
12432:     }
12433:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12434:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12435:                &mt('Unexpected course context.').'</p>'."\n";
12436:     }
12437:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
12438:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12439:                &mt('Filename contained unexpected characters.').'</p>'."\n";
12440:     }
12441:     my ($dir,$error,$warning,$output);
12442:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12443:         $error = &mt('Filename not a supported archive file type.').
12444:                  '<br />'.&mt('Filename should end with one of: [_1].',
12445:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12446:     } else {
12447:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12448:         if ($docuhome eq 'no_host') {
12449:             $error = &mt('Could not determine home server for course.');
12450:         } else {
12451:             my @ids=&Apache::lonnet::current_machine_ids();
12452:             my $currdir = "$dir_root/$destination";
12453:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12454:                 $dir = &LONCAPA::propath($docudom,$docuname).
12455:                        "$dir_root/$destination";
12456:             } else {
12457:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12458:                        "$dir_root/$docudom/$docuname/$destination";
12459:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12460:                     $error = &mt('Archive file not found.');
12461:                 }
12462:             }
12463:             my (@to_overwrite,@to_skip);
12464:             if ($env{'form.archive_overwrite_total'} > 0) {
12465:                 my $total = $env{'form.archive_overwrite_total'};
12466:                 for (my $i=0; $i<$total; $i++) {
12467:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12468:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12469:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12470:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12471:                     }
12472:                 }
12473:             }
12474:             my $numskip = scalar(@to_skip);
12475:             my $numoverwrite = scalar(@to_overwrite);
12476:             if (($numskip) && (!$numoverwrite)) {
12477:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12478:             } elsif ($dir eq '') {
12479:                 $error = &mt('Directory containing archive file unavailable.');
12480:             } elsif (!$error) {
12481:                 my ($decompressed,$display);
12482:                 if (($numskip) || ($numoverwrite)) {
12483:                     my $tempdir = time.'_'.$$.int(rand(10000));
12484:                     mkdir("$dir/$tempdir",0755);
12485:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12486:                         ($decompressed,$display) =
12487:                             &decompress_uploaded_file($file,"$dir/$tempdir");
12488:                         foreach my $item (@to_skip) {
12489:                             if (($item ne '') && ($item !~ /\.\./)) {
12490:                                 if (-f "$dir/$tempdir/$item") {
12491:                                     unlink("$dir/$tempdir/$item");
12492:                                 } elsif (-d "$dir/$tempdir/$item") {
12493:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12494:                                 }
12495:                             }
12496:                         }
12497:                         foreach my $item (@to_overwrite) {
12498:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12499:                                 if (($item ne '') && ($item !~ /\.\./)) {
12500:                                     if (-f "$dir/$item") {
12501:                                         unlink("$dir/$item");
12502:                                     } elsif (-d "$dir/$item") {
12503:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12504:                                     }
12505:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12506:                                 }
12507:                             }
12508:                         }
12509:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12510:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12511:                         }
12512:                     }
12513:                 } else {
12514:                     ($decompressed,$display) = 
12515:                         &decompress_uploaded_file($file,$dir);
12516:                 }
12517:                 if ($decompressed eq 'ok') {
12518:                     $output = '<p class="LC_info">'.
12519:                               &mt('Files extracted successfully from archive.').
12520:                               '</p>'."\n";
12521:                     my ($warning,$result,@contents);
12522:                     my ($newdirlistref,$newlisterror) =
12523:                         &Apache::lonnet::dirlist($currdir,$docudom,
12524:                                                  $docuname,1);
12525:                     my (%is_dir,%changes,@newitems);
12526:                     my $dirptr = 16384;
12527:                     if (ref($newdirlistref) eq 'ARRAY') {
12528:                         foreach my $dir_line (@{$newdirlistref}) {
12529:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12530:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
12531:                                 push(@newitems,$item);
12532:                                 if ($dirptr&$testdir) {
12533:                                     $is_dir{$item} = 1;
12534:                                 }
12535:                                 $changes{$item} = 1;
12536:                             }
12537:                         }
12538:                     }
12539:                     if (keys(%changes) > 0) {
12540:                         foreach my $item (sort(@newitems)) {
12541:                             if ($changes{$item}) {
12542:                                 push(@contents,$item);
12543:                             }
12544:                         }
12545:                     }
12546:                     if (@contents > 0) {
12547:                         my $wantform;
12548:                         unless ($env{'form.autoextract_camtasia'}) {
12549:                             $wantform = 1;
12550:                         }
12551:                         my (%children,%parent,%dirorder,%titles);
12552:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12553:                                                                 $currdir,\%is_dir,
12554:                                                                 \%children,\%parent,
12555:                                                                 \@contents,\%dirorder,
12556:                                                                 \%titles,$wantform);
12557:                         if ($datatable ne '') {
12558:                             $output .= &archive_options_form('decompressed',$datatable,
12559:                                                              $count,$hiddenelem);
12560:                             my $startcount = 6;
12561:                             $output .= &archive_javascript($startcount,$count,
12562:                                                            \%titles,\%children);
12563:                         }
12564:                         if ($env{'form.autoextract_camtasia'}) {
12565:                             my $version = $env{'form.autoextract_camtasia'};
12566:                             my %displayed;
12567:                             my $total = 1;
12568:                             $env{'form.archive_directory'} = [];
12569:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12570:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12571:                                 $path =~ s{/$}{};
12572:                                 my $item;
12573:                                 if ($path ne '') {
12574:                                     $item = "$path/$titles{$i}";
12575:                                 } else {
12576:                                     $item = $titles{$i};
12577:                                 }
12578:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12579:                                 if ($item eq $contents[0]) {
12580:                                     push(@{$env{'form.archive_directory'}},$i);
12581:                                     $env{'form.archive_'.$i} = 'display';
12582:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12583:                                     $displayed{'folder'} = $i;
12584:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12585:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12586:                                     $env{'form.archive_'.$i} = 'display';
12587:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12588:                                     $displayed{'web'} = $i;
12589:                                 } else {
12590:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12591:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12592:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12593:                                         push(@{$env{'form.archive_directory'}},$i);
12594:                                     }
12595:                                     $env{'form.archive_'.$i} = 'dependency';
12596:                                 }
12597:                                 $total ++;
12598:                             }
12599:                             for (my $i=1; $i<$total; $i++) {
12600:                                 next if ($i == $displayed{'web'});
12601:                                 next if ($i == $displayed{'folder'});
12602:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12603:                             }
12604:                             $env{'form.phase'} = 'decompress_cleanup';
12605:                             $env{'form.archivedelete'} = 1;
12606:                             $env{'form.archive_count'} = $total-1;
12607:                             $output .=
12608:                                 &process_extracted_files('coursedocs',$docudom,
12609:                                                          $docuname,$destination,
12610:                                                          $dir_root,$hiddenelem);
12611:                         }
12612:                     } else {
12613:                         $warning = &mt('No new items extracted from archive file.');
12614:                     }
12615:                 } else {
12616:                     $output = $display;
12617:                     $error = &mt('An error occurred during extraction from the archive file.');
12618:                 }
12619:             }
12620:         }
12621:     }
12622:     if ($error) {
12623:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12624:                    $error.'</p>'."\n";
12625:     }
12626:     if ($warning) {
12627:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12628:     }
12629:     return $output;
12630: }
12631: 
12632: sub get_extracted {
12633:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12634:         $titles,$wantform) = @_;
12635:     my $count = 0;
12636:     my $depth = 0;
12637:     my $datatable;
12638:     my @hierarchy;
12639:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12640:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12641:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12642:     foreach my $item (@{$contents}) {
12643:         $count ++;
12644:         @{$dirorder->{$count}} = @hierarchy;
12645:         $titles->{$count} = $item;
12646:         &archive_hierarchy($depth,$count,$parent,$children);
12647:         if ($wantform) {
12648:             $datatable .= &archive_row($is_dir->{$item},$item,
12649:                                        $currdir,$depth,$count);
12650:         }
12651:         if ($is_dir->{$item}) {
12652:             $depth ++;
12653:             push(@hierarchy,$count);
12654:             $parent->{$depth} = $count;
12655:             $datatable .=
12656:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12657:                                            \$depth,\$count,\@hierarchy,$dirorder,
12658:                                            $children,$parent,$titles,$wantform);
12659:             $depth --;
12660:             pop(@hierarchy);
12661:         }
12662:     }
12663:     return ($count,$datatable);
12664: }
12665: 
12666: sub recurse_extracted_archive {
12667:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12668:         $children,$parent,$titles,$wantform) = @_;
12669:     my $result='';
12670:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12671:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12672:             (ref($dirorder) eq 'HASH')) {
12673:         return $result;
12674:     }
12675:     my $dirptr = 16384;
12676:     my ($newdirlistref,$newlisterror) =
12677:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12678:     if (ref($newdirlistref) eq 'ARRAY') {
12679:         foreach my $dir_line (@{$newdirlistref}) {
12680:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12681:             unless ($item =~ /^\.+$/) {
12682:                 $$count ++;
12683:                 @{$dirorder->{$$count}} = @{$hierarchy};
12684:                 $titles->{$$count} = $item;
12685:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12686: 
12687:                 my $is_dir;
12688:                 if ($dirptr&$testdir) {
12689:                     $is_dir = 1;
12690:                 }
12691:                 if ($wantform) {
12692:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12693:                 }
12694:                 if ($is_dir) {
12695:                     $$depth ++;
12696:                     push(@{$hierarchy},$$count);
12697:                     $parent->{$$depth} = $$count;
12698:                     $result .=
12699:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12700:                                                    $docuname,$depth,$count,
12701:                                                    $hierarchy,$dirorder,$children,
12702:                                                    $parent,$titles,$wantform);
12703:                     $$depth --;
12704:                     pop(@{$hierarchy});
12705:                 }
12706:             }
12707:         }
12708:     }
12709:     return $result;
12710: }
12711: 
12712: sub archive_hierarchy {
12713:     my ($depth,$count,$parent,$children) =@_;
12714:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12715:         if (exists($parent->{$depth})) {
12716:              $children->{$parent->{$depth}} .= $count.':';
12717:         }
12718:     }
12719:     return;
12720: }
12721: 
12722: sub archive_row {
12723:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12724:     my ($name) = ($item =~ m{([^/]+)$});
12725:     my %choices = &Apache::lonlocal::texthash (
12726:                                        'display'    => 'Add as file',
12727:                                        'dependency' => 'Include as dependency',
12728:                                        'discard'    => 'Discard',
12729:                                       );
12730:     if ($is_dir) {
12731:         $choices{'display'} = &mt('Add as folder'); 
12732:     }
12733:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12734:     my $offset = 0;
12735:     foreach my $action ('display','dependency','discard') {
12736:         $offset ++;
12737:         if ($action ne 'display') {
12738:             $offset ++;
12739:         }  
12740:         $output .= '<td><span class="LC_nobreak">'.
12741:                    '<label><input type="radio" name="archive_'.$count.
12742:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12743:         my $text = $choices{$action};
12744:         if ($is_dir) {
12745:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12746:             if ($action eq 'display') {
12747:                 $text = &mt('Add as folder');
12748:             }
12749:         } else {
12750:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12751: 
12752:         }
12753:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12754:         if ($action eq 'dependency') {
12755:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12756:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12757:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12758:                        '<option value=""></option>'."\n".
12759:                        '</select>'."\n".
12760:                        '</div>';
12761:         } elsif ($action eq 'display') {
12762:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12763:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12764:                        '</div>';
12765:         }
12766:         $output .= '</td>';
12767:     }
12768:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12769:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12770:     for (my $i=0; $i<$depth; $i++) {
12771:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12772:     }
12773:     if ($is_dir) {
12774:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12775:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12776:     } else {
12777:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12778:     }
12779:     $output .= '&nbsp;'.$name.'</td>'."\n".
12780:                &end_data_table_row();
12781:     return $output;
12782: }
12783: 
12784: sub archive_options_form {
12785:     my ($form,$display,$count,$hiddenelem) = @_;
12786:     my %lt = &Apache::lonlocal::texthash(
12787:                perm => 'Permanently remove archive file?',
12788:                hows => 'How should each extracted item be incorporated in the course?',
12789:                cont => 'Content actions for all',
12790:                addf => 'Add as folder/file',
12791:                incd => 'Include as dependency for a displayed file',
12792:                disc => 'Discard',
12793:                no   => 'No',
12794:                yes  => 'Yes',
12795:                save => 'Save',
12796:     );
12797:     my $output = <<"END";
12798: <form name="$form" method="post" action="">
12799: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12800: <label>
12801:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12802: </label>
12803: &nbsp;
12804: <label>
12805:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12806: </span>
12807: </p>
12808: <input type="hidden" name="phase" value="decompress_cleanup" />
12809: <br />$lt{'hows'}
12810: <div class="LC_columnSection">
12811:   <fieldset>
12812:     <legend>$lt{'cont'}</legend>
12813:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12814:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12815:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12816:   </fieldset>
12817: </div>
12818: END
12819:     return $output.
12820:            &start_data_table()."\n".
12821:            $display."\n".
12822:            &end_data_table()."\n".
12823:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12824:            $hiddenelem.
12825:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12826:            '</form>';
12827: }
12828: 
12829: sub archive_javascript {
12830:     my ($startcount,$numitems,$titles,$children) = @_;
12831:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12832:     my $maintitle = $env{'form.comment'};
12833:     my $scripttag = <<START;
12834: <script type="text/javascript">
12835: // <![CDATA[
12836: 
12837: function checkAll(form,prefix) {
12838:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12839:     for (var i=0; i < form.elements.length; i++) {
12840:         var id = form.elements[i].id;
12841:         if ((id != '') && (id != undefined)) {
12842:             if (idstr.test(id)) {
12843:                 if (form.elements[i].type == 'radio') {
12844:                     form.elements[i].checked = true;
12845:                     var nostart = i-$startcount;
12846:                     var offset = nostart%7;
12847:                     var count = (nostart-offset)/7;    
12848:                     dependencyCheck(form,count,offset);
12849:                 }
12850:             }
12851:         }
12852:     }
12853: }
12854: 
12855: function propagateCheck(form,count) {
12856:     if (count > 0) {
12857:         var startelement = $startcount + ((count-1) * 7);
12858:         for (var j=1; j<6; j++) {
12859:             if ((j != 2) && (j != 4)) {
12860:                 var item = startelement + j; 
12861:                 if (form.elements[item].type == 'radio') {
12862:                     if (form.elements[item].checked) {
12863:                         containerCheck(form,count,j);
12864:                         break;
12865:                     }
12866:                 }
12867:             }
12868:         }
12869:     }
12870: }
12871: 
12872: numitems = $numitems
12873: var titles = new Array(numitems);
12874: var parents = new Array(numitems);
12875: for (var i=0; i<numitems; i++) {
12876:     parents[i] = new Array;
12877: }
12878: var maintitle = '$maintitle';
12879: 
12880: START
12881: 
12882:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12883:         my @contents = split(/:/,$children->{$container});
12884:         for (my $i=0; $i<@contents; $i ++) {
12885:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12886:         }
12887:     }
12888: 
12889:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12890:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12891:     }
12892: 
12893:     $scripttag .= <<END;
12894: 
12895: function containerCheck(form,count,offset) {
12896:     if (count > 0) {
12897:         dependencyCheck(form,count,offset);
12898:         var item = (offset+$startcount)+7*(count-1);
12899:         form.elements[item].checked = true;
12900:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12901:             if (parents[count].length > 0) {
12902:                 for (var j=0; j<parents[count].length; j++) {
12903:                     containerCheck(form,parents[count][j],offset);
12904:                 }
12905:             }
12906:         }
12907:     }
12908: }
12909: 
12910: function dependencyCheck(form,count,offset) {
12911:     if (count > 0) {
12912:         var chosen = (offset+$startcount)+7*(count-1);
12913:         var depitem = $startcount + ((count-1) * 7) + 4;
12914:         var currtype = form.elements[depitem].type;
12915:         if (form.elements[chosen].value == 'dependency') {
12916:             document.getElementById('arc_depon_'+count).style.display='block'; 
12917:             form.elements[depitem].options.length = 0;
12918:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12919:             for (var i=1; i<=numitems; i++) {
12920:                 if (i == count) {
12921:                     continue;
12922:                 }
12923:                 var startelement = $startcount + (i-1) * 7;
12924:                 for (var j=1; j<6; j++) {
12925:                     if ((j != 2) && (j!= 4)) {
12926:                         var item = startelement + j;
12927:                         if (form.elements[item].type == 'radio') {
12928:                             if (form.elements[item].checked) {
12929:                                 if (form.elements[item].value == 'display') {
12930:                                     var n = form.elements[depitem].options.length;
12931:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12932:                                 }
12933:                             }
12934:                         }
12935:                     }
12936:                 }
12937:             }
12938:         } else {
12939:             document.getElementById('arc_depon_'+count).style.display='none';
12940:             form.elements[depitem].options.length = 0;
12941:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12942:         }
12943:         titleCheck(form,count,offset);
12944:     }
12945: }
12946: 
12947: function propagateSelect(form,count,offset) {
12948:     if (count > 0) {
12949:         var item = (1+offset+$startcount)+7*(count-1);
12950:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12951:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12952:             if (parents[count].length > 0) {
12953:                 for (var j=0; j<parents[count].length; j++) {
12954:                     containerSelect(form,parents[count][j],offset,picked);
12955:                 }
12956:             }
12957:         }
12958:     }
12959: }
12960: 
12961: function containerSelect(form,count,offset,picked) {
12962:     if (count > 0) {
12963:         var item = (offset+$startcount)+7*(count-1);
12964:         if (form.elements[item].type == 'radio') {
12965:             if (form.elements[item].value == 'dependency') {
12966:                 if (form.elements[item+1].type == 'select-one') {
12967:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12968:                         if (form.elements[item+1].options[i].value == picked) {
12969:                             form.elements[item+1].selectedIndex = i;
12970:                             break;
12971:                         }
12972:                     }
12973:                 }
12974:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12975:                     if (parents[count].length > 0) {
12976:                         for (var j=0; j<parents[count].length; j++) {
12977:                             containerSelect(form,parents[count][j],offset,picked);
12978:                         }
12979:                     }
12980:                 }
12981:             }
12982:         }
12983:     }
12984: }
12985: 
12986: function titleCheck(form,count,offset) {
12987:     if (count > 0) {
12988:         var chosen = (offset+$startcount)+7*(count-1);
12989:         var depitem = $startcount + ((count-1) * 7) + 2;
12990:         var currtype = form.elements[depitem].type;
12991:         if (form.elements[chosen].value == 'display') {
12992:             document.getElementById('arc_title_'+count).style.display='block';
12993:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12994:                 document.getElementById('archive_title_'+count).value=maintitle;
12995:             }
12996:         } else {
12997:             document.getElementById('arc_title_'+count).style.display='none';
12998:             if (currtype == 'text') { 
12999:                 document.getElementById('archive_title_'+count).value='';
13000:             }
13001:         }
13002:     }
13003:     return;
13004: }
13005: 
13006: // ]]>
13007: </script>
13008: END
13009:     return $scripttag;
13010: }
13011: 
13012: sub process_extracted_files {
13013:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13014:     my $numitems = $env{'form.archive_count'};
13015:     return if ((!$numitems) || ($numitems =~ /\D/));
13016:     my @ids=&Apache::lonnet::current_machine_ids();
13017:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13018:         %folders,%containers,%mapinner,%prompttofetch);
13019:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13020:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13021:         $prefix = &LONCAPA::propath($docudom,$docuname);
13022:         $pathtocheck = "$dir_root/$destination";
13023:         $dir = $dir_root;
13024:         $ishome = 1;
13025:     } else {
13026:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13027:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13028:         $dir = "$dir_root/$docudom/$docuname";
13029:     }
13030:     my $currdir = "$dir_root/$destination";
13031:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13032:     if ($env{'form.folderpath'}) {
13033:         my @items = split('&',$env{'form.folderpath'});
13034:         $folders{'0'} = $items[-2];
13035:         if ($env{'form.folderpath'} =~ /\:1$/) {
13036:             $containers{'0'}='page';
13037:         } else {
13038:             $containers{'0'}='sequence';
13039:         }
13040:     }
13041:     my @archdirs = &get_env_multiple('form.archive_directory');
13042:     if ($numitems) {
13043:         for (my $i=1; $i<=$numitems; $i++) {
13044:             my $path = $env{'form.archive_content_'.$i};
13045:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13046:                 my $item = $1;
13047:                 $toplevelitems{$item} = $i;
13048:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13049:                     $is_dir{$item} = 1;
13050:                 }
13051:             }
13052:         }
13053:     }
13054:     my ($output,%children,%parent,%titles,%dirorder,$result);
13055:     if (keys(%toplevelitems) > 0) {
13056:         my @contents = sort(keys(%toplevelitems));
13057:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13058:                                            \%parent,\@contents,\%dirorder,\%titles);
13059:     }
13060:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13061:     if ($numitems) {
13062:         for (my $i=1; $i<=$numitems; $i++) {
13063:             next if ($env{'form.archive_'.$i} eq 'dependency');
13064:             my $path = $env{'form.archive_content_'.$i};
13065:             if ($path =~ /^\Q$pathtocheck\E/) {
13066:                 if ($env{'form.archive_'.$i} eq 'discard') {
13067:                     if ($prefix ne '' && $path ne '') {
13068:                         if (-e $prefix.$path) {
13069:                             if ((@archdirs > 0) && 
13070:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13071:                                 $todeletedir{$prefix.$path} = 1;
13072:                             } else {
13073:                                 $todelete{$prefix.$path} = 1;
13074:                             }
13075:                         }
13076:                     }
13077:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13078:                     my ($docstitle,$title,$url,$outer);
13079:                     ($title) = ($path =~ m{/([^/]+)$});
13080:                     $docstitle = $env{'form.archive_title_'.$i};
13081:                     if ($docstitle eq '') {
13082:                         $docstitle = $title;
13083:                     }
13084:                     $outer = 0;
13085:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13086:                         if (@{$dirorder{$i}} > 0) {
13087:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13088:                                 if ($env{'form.archive_'.$item} eq 'display') {
13089:                                     $outer = $item;
13090:                                     last;
13091:                                 }
13092:                             }
13093:                         }
13094:                     }
13095:                     my ($errtext,$fatal) = 
13096:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13097:                                                '/'.$folders{$outer}.'.'.
13098:                                                $containers{$outer});
13099:                     next if ($fatal);
13100:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13101:                         if ($context eq 'coursedocs') {
13102:                             $mapinner{$i} = time;
13103:                             $folders{$i} = 'default_'.$mapinner{$i};
13104:                             $containers{$i} = 'sequence';
13105:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13106:                                       $folders{$i}.'.'.$containers{$i};
13107:                             my $newidx = &LONCAPA::map::getresidx();
13108:                             $LONCAPA::map::resources[$newidx]=
13109:                                 $docstitle.':'.$url.':false:normal:res';
13110:                             push(@LONCAPA::map::order,$newidx);
13111:                             my ($outtext,$errtext) =
13112:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13113:                                                         $docuname.'/'.$folders{$outer}.
13114:                                                         '.'.$containers{$outer},1,1);
13115:                             $newseqid{$i} = $newidx;
13116:                             unless ($errtext) {
13117:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13118:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
13119:                                             '</li>'."\n";
13120:                             }
13121:                         }
13122:                     } else {
13123:                         if ($context eq 'coursedocs') {
13124:                             my $newidx=&LONCAPA::map::getresidx();
13125:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13126:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13127:                                       $title;
13128:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13129:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13130:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13131:                                 }
13132:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13133:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13134:                                 }
13135:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13136:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13137:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13138:                                         unless ($ishome) {
13139:                                             my $fetch = "$newdest{$i}/$title";
13140:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13141:                                             $prompttofetch{$fetch} = 1;
13142:                                         }
13143:                                    }
13144:                                 }
13145:                                 $LONCAPA::map::resources[$newidx]=
13146:                                     $docstitle.':'.$url.':false:normal:res';
13147:                                 push(@LONCAPA::map::order, $newidx);
13148:                                 my ($outtext,$errtext)=
13149:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13150:                                                             $docuname.'/'.$folders{$outer}.
13151:                                                             '.'.$containers{$outer},1,1);
13152:                                 unless ($errtext) {
13153:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13154:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13155:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13156:                                                    '</li>'."\n";
13157:                                     }
13158:                                 }
13159:                             } else {
13160:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13161:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13162:                             }
13163:                         }
13164:                     }
13165:                 }
13166:             } else {
13167:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13168:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13169:             }
13170:         }
13171:         for (my $i=1; $i<=$numitems; $i++) {
13172:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13173:             my $path = $env{'form.archive_content_'.$i};
13174:             if ($path =~ /^\Q$pathtocheck\E/) {
13175:                 my ($title) = ($path =~ m{/([^/]+)$});
13176:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13177:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13178:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13179:                         my ($itemidx,$fullpath,$relpath);
13180:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13181:                             my $container = $dirorder{$referrer{$i}}->[-1];
13182:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13183:                                 if ($dirorder{$i}->[$j] eq $container) {
13184:                                     $itemidx = $j;
13185:                                 }
13186:                             }
13187:                         }
13188:                         if ($itemidx eq '') {
13189:                             $itemidx =  0;
13190:                         }
13191:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13192:                             if ($mapinner{$referrer{$i}}) {
13193:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13194:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13195:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13196:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13197:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13198:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13199:                                             if (!-e $fullpath) {
13200:                                                 mkdir($fullpath,0755);
13201:                                             }
13202:                                         }
13203:                                     } else {
13204:                                         last;
13205:                                     }
13206:                                 }
13207:                             }
13208:                         } elsif ($newdest{$referrer{$i}}) {
13209:                             $fullpath = $newdest{$referrer{$i}};
13210:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13211:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13212:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13213:                                     last;
13214:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13215:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13216:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13217:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13218:                                         if (!-e $fullpath) {
13219:                                             mkdir($fullpath,0755);
13220:                                         }
13221:                                     }
13222:                                 } else {
13223:                                     last;
13224:                                 }
13225:                             }
13226:                         }
13227:                         if ($fullpath ne '') {
13228:                             if (-e "$prefix$path") {
13229:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13230:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13231:                                 }
13232:                             }
13233:                             if (-e "$fullpath/$title") {
13234:                                 my $showpath;
13235:                                 if ($relpath ne '') {
13236:                                     $showpath = "$relpath/$title";
13237:                                 } else {
13238:                                     $showpath = "/$title";
13239:                                 }
13240:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13241:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13242:                                            '</li>'."\n";
13243:                                 unless ($ishome) {
13244:                                     my $fetch = "$fullpath/$title";
13245:                                     $fetch =~ s/^\Q$prefix$dir\E//;
13246:                                     $prompttofetch{$fetch} = 1;
13247:                                 }
13248:                             }
13249:                         }
13250:                     }
13251:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13252:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13253:                                     &HTML::Entities::encode($path,'<>&"'),
13254:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13255:                                 '<br />';
13256:                 }
13257:             } else {
13258:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13259:                                 &HTML::Entities::encode($path)).'<br />';
13260:             }
13261:         }
13262:         if (keys(%todelete)) {
13263:             foreach my $key (keys(%todelete)) {
13264:                 unlink($key);
13265:             }
13266:         }
13267:         if (keys(%todeletedir)) {
13268:             foreach my $key (keys(%todeletedir)) {
13269:                 rmdir($key);
13270:             }
13271:         }
13272:         foreach my $dir (sort(keys(%is_dir))) {
13273:             if (($pathtocheck ne '') && ($dir ne ''))  {
13274:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13275:             }
13276:         }
13277:         if ($result ne '') {
13278:             $output .= '<ul>'."\n".
13279:                        $result."\n".
13280:                        '</ul>';
13281:         }
13282:         unless ($ishome) {
13283:             my $replicationfail;
13284:             foreach my $item (keys(%prompttofetch)) {
13285:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13286:                 unless ($fetchresult eq 'ok') {
13287:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13288:                 }
13289:             }
13290:             if ($replicationfail) {
13291:                 $output .= '<p class="LC_error">'.
13292:                            &mt('Course home server failed to retrieve:').'<ul>'.
13293:                            $replicationfail.
13294:                            '</ul></p>';
13295:             }
13296:         }
13297:     } else {
13298:         $warning = &mt('No items found in archive.');
13299:     }
13300:     if ($error) {
13301:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13302:                    $error.'</p>'."\n";
13303:     }
13304:     if ($warning) {
13305:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13306:     }
13307:     return $output;
13308: }
13309: 
13310: sub cleanup_empty_dirs {
13311:     my ($path) = @_;
13312:     if (($path ne '') && (-d $path)) {
13313:         if (opendir(my $dirh,$path)) {
13314:             my @dircontents = grep(!/^\./,readdir($dirh));
13315:             my $numitems = 0;
13316:             foreach my $item (@dircontents) {
13317:                 if (-d "$path/$item") {
13318:                     &cleanup_empty_dirs("$path/$item");
13319:                     if (-e "$path/$item") {
13320:                         $numitems ++;
13321:                     }
13322:                 } else {
13323:                     $numitems ++;
13324:                 }
13325:             }
13326:             if ($numitems == 0) {
13327:                 rmdir($path);
13328:             }
13329:             closedir($dirh);
13330:         }
13331:     }
13332:     return;
13333: }
13334: 
13335: =pod
13336: 
13337: =item * &get_folder_hierarchy()
13338: 
13339: Provides hierarchy of names of folders/sub-folders containing the current
13340: item,
13341: 
13342: Inputs: 3
13343:      - $navmap - navmaps object
13344: 
13345:      - $map - url for map (either the trigger itself, or map containing
13346:                            the resource, which is the trigger).
13347: 
13348:      - $showitem - 1 => show title for map itself; 0 => do not show.
13349: 
13350: Outputs: 1 @pathitems - array of folder/subfolder names.
13351: 
13352: =cut
13353: 
13354: sub get_folder_hierarchy {
13355:     my ($navmap,$map,$showitem) = @_;
13356:     my @pathitems;
13357:     if (ref($navmap)) {
13358:         my $mapres = $navmap->getResourceByUrl($map);
13359:         if (ref($mapres)) {
13360:             my $pcslist = $mapres->map_hierarchy();
13361:             if ($pcslist ne '') {
13362:                 my @pcs = split(/,/,$pcslist);
13363:                 foreach my $pc (@pcs) {
13364:                     if ($pc == 1) {
13365:                         push(@pathitems,&mt('Main Content'));
13366:                     } else {
13367:                         my $res = $navmap->getByMapPc($pc);
13368:                         if (ref($res)) {
13369:                             my $title = $res->compTitle();
13370:                             $title =~ s/\W+/_/g;
13371:                             if ($title ne '') {
13372:                                 push(@pathitems,$title);
13373:                             }
13374:                         }
13375:                     }
13376:                 }
13377:             }
13378:             if ($showitem) {
13379:                 if ($mapres->{ID} eq '0.0') {
13380:                     push(@pathitems,&mt('Main Content'));
13381:                 } else {
13382:                     my $maptitle = $mapres->compTitle();
13383:                     $maptitle =~ s/\W+/_/g;
13384:                     if ($maptitle ne '') {
13385:                         push(@pathitems,$maptitle);
13386:                     }
13387:                 }
13388:             }
13389:         }
13390:     }
13391:     return @pathitems;
13392: }
13393: 
13394: =pod
13395: 
13396: =item * &get_turnedin_filepath()
13397: 
13398: Determines path in a user's portfolio file for storage of files uploaded
13399: to a specific essayresponse or dropbox item.
13400: 
13401: Inputs: 3 required + 1 optional.
13402: $symb is symb for resource, $uname and $udom are for current user (required).
13403: $caller is optional (can be "submission", if routine is called when storing
13404: an upoaded file when "Submit Answer" button was pressed).
13405: 
13406: Returns array containing $path and $multiresp. 
13407: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13408: than one file upload item.  Callers of routine should append partid as a 
13409: subdirectory to $path in cases where $multiresp is 1.
13410: 
13411: Called by: homework/essayresponse.pm and homework/structuretags.pm
13412: 
13413: =cut
13414: 
13415: sub get_turnedin_filepath {
13416:     my ($symb,$uname,$udom,$caller) = @_;
13417:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13418:     my $turnindir;
13419:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13420:     $turnindir = $userhash{'turnindir'};
13421:     my ($path,$multiresp);
13422:     if ($turnindir eq '') {
13423:         if ($caller eq 'submission') {
13424:             $turnindir = &mt('turned in');
13425:             $turnindir =~ s/\W+/_/g;
13426:             my %newhash = (
13427:                             'turnindir' => $turnindir,
13428:                           );
13429:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13430:         }
13431:     }
13432:     if ($turnindir ne '') {
13433:         $path = '/'.$turnindir.'/';
13434:         my ($multipart,$turnin,@pathitems);
13435:         my $navmap = Apache::lonnavmaps::navmap->new();
13436:         if (defined($navmap)) {
13437:             my $mapres = $navmap->getResourceByUrl($map);
13438:             if (ref($mapres)) {
13439:                 my $pcslist = $mapres->map_hierarchy();
13440:                 if ($pcslist ne '') {
13441:                     foreach my $pc (split(/,/,$pcslist)) {
13442:                         my $res = $navmap->getByMapPc($pc);
13443:                         if (ref($res)) {
13444:                             my $title = $res->compTitle();
13445:                             $title =~ s/\W+/_/g;
13446:                             if ($title ne '') {
13447:                                 if (($pc > 1) && (length($title) > 12)) {
13448:                                     $title = substr($title,0,12);
13449:                                 }
13450:                                 push(@pathitems,$title);
13451:                             }
13452:                         }
13453:                     }
13454:                 }
13455:                 my $maptitle = $mapres->compTitle();
13456:                 $maptitle =~ s/\W+/_/g;
13457:                 if ($maptitle ne '') {
13458:                     if (length($maptitle) > 12) {
13459:                         $maptitle = substr($maptitle,0,12);
13460:                     }
13461:                     push(@pathitems,$maptitle);
13462:                 }
13463:                 unless ($env{'request.state'} eq 'construct') {
13464:                     my $res = $navmap->getBySymb($symb);
13465:                     if (ref($res)) {
13466:                         my $partlist = $res->parts();
13467:                         my $totaluploads = 0;
13468:                         if (ref($partlist) eq 'ARRAY') {
13469:                             foreach my $part (@{$partlist}) {
13470:                                 my @types = $res->responseType($part);
13471:                                 my @ids = $res->responseIds($part);
13472:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13473:                                     if ($types[$i] eq 'essay') {
13474:                                         my $partid = $part.'_'.$ids[$i];
13475:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13476:                                             $totaluploads ++;
13477:                                         }
13478:                                     }
13479:                                 }
13480:                             }
13481:                             if ($totaluploads > 1) {
13482:                                 $multiresp = 1;
13483:                             }
13484:                         }
13485:                     }
13486:                 }
13487:             } else {
13488:                 return;
13489:             }
13490:         } else {
13491:             return;
13492:         }
13493:         my $restitle=&Apache::lonnet::gettitle($symb);
13494:         $restitle =~ s/\W+/_/g;
13495:         if ($restitle eq '') {
13496:             $restitle = ($resurl =~ m{/[^/]+$});
13497:             if ($restitle eq '') {
13498:                 $restitle = time;
13499:             }
13500:         }
13501:         if (length($restitle) > 12) {
13502:             $restitle = substr($restitle,0,12);
13503:         }
13504:         push(@pathitems,$restitle);
13505:         $path .= join('/',@pathitems);
13506:     }
13507:     return ($path,$multiresp);
13508: }
13509: 
13510: =pod
13511: 
13512: =back
13513: 
13514: =head1 CSV Upload/Handling functions
13515: 
13516: =over 4
13517: 
13518: =item * &upfile_store($r)
13519: 
13520: Store uploaded file, $r should be the HTTP Request object,
13521: needs $env{'form.upfile'}
13522: returns $datatoken to be put into hidden field
13523: 
13524: =cut
13525: 
13526: sub upfile_store {
13527:     my $r=shift;
13528:     $env{'form.upfile'}=~s/\r/\n/gs;
13529:     $env{'form.upfile'}=~s/\f/\n/gs;
13530:     $env{'form.upfile'}=~s/\n+/\n/gs;
13531:     $env{'form.upfile'}=~s/\n+$//gs;
13532: 
13533:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13534:                                      '_enroll_'.$env{'request.course.id'}.'_'.
13535:                                      time.'_'.$$);
13536:     return if ($datatoken eq '');
13537: 
13538:     {
13539:         my $datafile = $r->dir_config('lonDaemons').
13540:                            '/tmp/'.$datatoken.'.tmp';
13541:         if ( open(my $fh,'>',$datafile) ) {
13542:             print $fh $env{'form.upfile'};
13543:             close($fh);
13544:         }
13545:     }
13546:     return $datatoken;
13547: }
13548: 
13549: =pod
13550: 
13551: =item * &load_tmp_file($r,$datatoken)
13552: 
13553: Load uploaded file from tmp, $r should be the HTTP Request object,
13554: $datatoken is the name to assign to the temporary file.
13555: sets $env{'form.upfile'} to the contents of the file
13556: 
13557: =cut
13558: 
13559: sub load_tmp_file {
13560:     my ($r,$datatoken) = @_;
13561:     return if ($datatoken eq '');
13562:     my @studentdata=();
13563:     {
13564:         my $studentfile = $r->dir_config('lonDaemons').
13565:                               '/tmp/'.$datatoken.'.tmp';
13566:         if ( open(my $fh,'<',$studentfile) ) {
13567:             @studentdata=<$fh>;
13568:             close($fh);
13569:         }
13570:     }
13571:     $env{'form.upfile'}=join('',@studentdata);
13572: }
13573: 
13574: sub valid_datatoken {
13575:     my ($datatoken) = @_;
13576:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
13577:         return $datatoken;
13578:     }
13579:     return;
13580: }
13581: 
13582: =pod
13583: 
13584: =item * &upfile_record_sep()
13585: 
13586: Separate uploaded file into records
13587: returns array of records,
13588: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13589: 
13590: =cut
13591: 
13592: sub upfile_record_sep {
13593:     if ($env{'form.upfiletype'} eq 'xml') {
13594:     } else {
13595: 	my @records;
13596: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13597: 	    if ($line=~/^\s*$/) { next; }
13598: 	    push(@records,$line);
13599: 	}
13600: 	return @records;
13601:     }
13602: }
13603: 
13604: =pod
13605: 
13606: =item * &record_sep($record)
13607: 
13608: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13609: 
13610: =cut
13611: 
13612: sub takeleft {
13613:     my $index=shift;
13614:     return substr('0000'.$index,-4,4);
13615: }
13616: 
13617: sub record_sep {
13618:     my $record=shift;
13619:     my %components=();
13620:     if ($env{'form.upfiletype'} eq 'xml') {
13621:     } elsif ($env{'form.upfiletype'} eq 'space') {
13622:         my $i=0;
13623:         foreach my $field (split(/\s+/,$record)) {
13624:             $field=~s/^(\"|\')//;
13625:             $field=~s/(\"|\')$//;
13626:             $components{&takeleft($i)}=$field;
13627:             $i++;
13628:         }
13629:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13630:         my $i=0;
13631:         foreach my $field (split(/\t/,$record)) {
13632:             $field=~s/^(\"|\')//;
13633:             $field=~s/(\"|\')$//;
13634:             $components{&takeleft($i)}=$field;
13635:             $i++;
13636:         }
13637:     } else {
13638:         my $separator=',';
13639:         if ($env{'form.upfiletype'} eq 'semisv') {
13640:             $separator=';';
13641:         }
13642:         my $i=0;
13643: # the character we are looking for to indicate the end of a quote or a record 
13644:         my $looking_for=$separator;
13645: # do not add the characters to the fields
13646:         my $ignore=0;
13647: # we just encountered a separator (or the beginning of the record)
13648:         my $just_found_separator=1;
13649: # store the field we are working on here
13650:         my $field='';
13651: # work our way through all characters in record
13652:         foreach my $character ($record=~/(.)/g) {
13653:             if ($character eq $looking_for) {
13654:                if ($character ne $separator) {
13655: # Found the end of a quote, again looking for separator
13656:                   $looking_for=$separator;
13657:                   $ignore=1;
13658:                } else {
13659: # Found a separator, store away what we got
13660:                   $components{&takeleft($i)}=$field;
13661: 	          $i++;
13662:                   $just_found_separator=1;
13663:                   $ignore=0;
13664:                   $field='';
13665:                }
13666:                next;
13667:             }
13668: # single or double quotation marks after a separator indicate beginning of a quote
13669: # we are now looking for the end of the quote and need to ignore separators
13670:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13671:                $looking_for=$character;
13672:                next;
13673:             }
13674: # ignore would be true after we reached the end of a quote
13675:             if ($ignore) { next; }
13676:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13677:             $field.=$character;
13678:             $just_found_separator=0; 
13679:         }
13680: # catch the very last entry, since we never encountered the separator
13681:         $components{&takeleft($i)}=$field;
13682:     }
13683:     return %components;
13684: }
13685: 
13686: ######################################################
13687: ######################################################
13688: 
13689: =pod
13690: 
13691: =item * &upfile_select_html()
13692: 
13693: Return HTML code to select a file from the users machine and specify 
13694: the file type.
13695: 
13696: =cut
13697: 
13698: ######################################################
13699: ######################################################
13700: sub upfile_select_html {
13701:     my %Types = (
13702:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13703:                  semisv => &mt('Semicolon separated values'),
13704:                  space => &mt('Space separated'),
13705:                  tab   => &mt('Tabulator separated'),
13706: #                 xml   => &mt('HTML/XML'),
13707:                  );
13708:     my $Str = '<input type="file" name="upfile" size="50" />'.
13709:         '<br />'.&mt('Type').': <select name="upfiletype">';
13710:     foreach my $type (sort(keys(%Types))) {
13711:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13712:     }
13713:     $Str .= "</select>\n";
13714:     return $Str;
13715: }
13716: 
13717: sub get_samples {
13718:     my ($records,$toget) = @_;
13719:     my @samples=({});
13720:     my $got=0;
13721:     foreach my $rec (@$records) {
13722: 	my %temp = &record_sep($rec);
13723: 	if (! grep(/\S/, values(%temp))) { next; }
13724: 	if (%temp) {
13725: 	    $samples[$got]=\%temp;
13726: 	    $got++;
13727: 	    if ($got == $toget) { last; }
13728: 	}
13729:     }
13730:     return \@samples;
13731: }
13732: 
13733: ######################################################
13734: ######################################################
13735: 
13736: =pod
13737: 
13738: =item * &csv_print_samples($r,$records)
13739: 
13740: Prints a table of sample values from each column uploaded $r is an
13741: Apache Request ref, $records is an arrayref from
13742: &Apache::loncommon::upfile_record_sep
13743: 
13744: =cut
13745: 
13746: ######################################################
13747: ######################################################
13748: sub csv_print_samples {
13749:     my ($r,$records) = @_;
13750:     my $samples = &get_samples($records,5);
13751: 
13752:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13753:               &start_data_table_header_row());
13754:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13755:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13756:     $r->print(&end_data_table_header_row());
13757:     foreach my $hash (@$samples) {
13758: 	$r->print(&start_data_table_row());
13759: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13760: 	    $r->print('<td>');
13761: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13762: 	    $r->print('</td>');
13763: 	}
13764: 	$r->print(&end_data_table_row());
13765:     }
13766:     $r->print(&end_data_table().'<br />'."\n");
13767: }
13768: 
13769: ######################################################
13770: ######################################################
13771: 
13772: =pod
13773: 
13774: =item * &csv_print_select_table($r,$records,$d)
13775: 
13776: Prints a table to create associations between values and table columns.
13777: 
13778: $r is an Apache Request ref,
13779: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13780: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13781: 
13782: =cut
13783: 
13784: ######################################################
13785: ######################################################
13786: sub csv_print_select_table {
13787:     my ($r,$records,$d) = @_;
13788:     my $i=0;
13789:     my $samples = &get_samples($records,1);
13790:     $r->print(&mt('Associate columns with student attributes.')."\n".
13791: 	      &start_data_table().&start_data_table_header_row().
13792:               '<th>'.&mt('Attribute').'</th>'.
13793:               '<th>'.&mt('Column').'</th>'.
13794:               &end_data_table_header_row()."\n");
13795:     foreach my $array_ref (@$d) {
13796: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13797: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13798: 
13799: 	$r->print('<td><select name="f'.$i.'"'.
13800: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13801: 	$r->print('<option value="none"></option>');
13802: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13803: 	    $r->print('<option value="'.$sample.'"'.
13804:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13805:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13806: 	}
13807: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13808: 	$i++;
13809:     }
13810:     $r->print(&end_data_table());
13811:     $i--;
13812:     return $i;
13813: }
13814: 
13815: ######################################################
13816: ######################################################
13817: 
13818: =pod
13819: 
13820: =item * &csv_samples_select_table($r,$records,$d)
13821: 
13822: Prints a table of sample values from the upload and can make associate samples to internal names.
13823: 
13824: $r is an Apache Request ref,
13825: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13826: $d is an array of 2 element arrays (internal name, displayed name)
13827: 
13828: =cut
13829: 
13830: ######################################################
13831: ######################################################
13832: sub csv_samples_select_table {
13833:     my ($r,$records,$d) = @_;
13834:     my $i=0;
13835:     #
13836:     my $max_samples = 5;
13837:     my $samples = &get_samples($records,$max_samples);
13838:     $r->print(&start_data_table().
13839:               &start_data_table_header_row().'<th>'.
13840:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13841:               &end_data_table_header_row());
13842: 
13843:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13844: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13845: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13846: 	foreach my $option (@$d) {
13847: 	    my ($value,$display,$defaultcol)=@{ $option };
13848: 	    $r->print('<option value="'.$value.'"'.
13849:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13850:                       $display.'</option>');
13851: 	}
13852: 	$r->print('</select></td><td>');
13853: 	foreach my $line (0..($max_samples-1)) {
13854: 	    if (defined($samples->[$line]{$key})) { 
13855: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13856: 	    }
13857: 	}
13858: 	$r->print('</td>'.&end_data_table_row());
13859: 	$i++;
13860:     }
13861:     $r->print(&end_data_table());
13862:     $i--;
13863:     return($i);
13864: }
13865: 
13866: ######################################################
13867: ######################################################
13868: 
13869: =pod
13870: 
13871: =item * &clean_excel_name($name)
13872: 
13873: Returns a replacement for $name which does not contain any illegal characters.
13874: 
13875: =cut
13876: 
13877: ######################################################
13878: ######################################################
13879: sub clean_excel_name {
13880:     my ($name) = @_;
13881:     $name =~ s/[:\*\?\/\\]//g;
13882:     if (length($name) > 31) {
13883:         $name = substr($name,0,31);
13884:     }
13885:     return $name;
13886: }
13887: 
13888: =pod
13889: 
13890: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13891: 
13892: Returns either 1 or undef
13893: 
13894: 1 if the part is to be hidden, undef if it is to be shown
13895: 
13896: Arguments are:
13897: 
13898: $id the id of the part to be checked
13899: $symb, optional the symb of the resource to check
13900: $udom, optional the domain of the user to check for
13901: $uname, optional the username of the user to check for
13902: 
13903: =cut
13904: 
13905: sub check_if_partid_hidden {
13906:     my ($id,$symb,$udom,$uname) = @_;
13907:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13908: 					 $symb,$udom,$uname);
13909:     my $truth=1;
13910:     #if the string starts with !, then the list is the list to show not hide
13911:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13912:     my @hiddenlist=split(/,/,$hiddenparts);
13913:     foreach my $checkid (@hiddenlist) {
13914: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13915:     }
13916:     return !$truth;
13917: }
13918: 
13919: 
13920: ############################################################
13921: ############################################################
13922: 
13923: =pod
13924: 
13925: =back 
13926: 
13927: =head1 cgi-bin script and graphing routines
13928: 
13929: =over 4
13930: 
13931: =item * &get_cgi_id()
13932: 
13933: Inputs: none
13934: 
13935: Returns an id which can be used to pass environment variables
13936: to various cgi-bin scripts.  These environment variables will
13937: be removed from the users environment after a given time by
13938: the routine &Apache::lonnet::transfer_profile_to_env.
13939: 
13940: =cut
13941: 
13942: ############################################################
13943: ############################################################
13944: my $uniq=0;
13945: sub get_cgi_id {
13946:     $uniq=($uniq+1)%100000;
13947:     return (time.'_'.$$.'_'.$uniq);
13948: }
13949: 
13950: ############################################################
13951: ############################################################
13952: 
13953: =pod
13954: 
13955: =item * &DrawBarGraph()
13956: 
13957: Facilitates the plotting of data in a (stacked) bar graph.
13958: Puts plot definition data into the users environment in order for 
13959: graph.png to plot it.  Returns an <img> tag for the plot.
13960: The bars on the plot are labeled '1','2',...,'n'.
13961: 
13962: Inputs:
13963: 
13964: =over 4
13965: 
13966: =item $Title: string, the title of the plot
13967: 
13968: =item $xlabel: string, text describing the X-axis of the plot
13969: 
13970: =item $ylabel: string, text describing the Y-axis of the plot
13971: 
13972: =item $Max: scalar, the maximum Y value to use in the plot
13973: If $Max is < any data point, the graph will not be rendered.
13974: 
13975: =item $colors: array ref holding the colors to be used for the data sets when
13976: they are plotted.  If undefined, default values will be used.
13977: 
13978: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13979: 
13980: =item @Values: An array of array references.  Each array reference holds data
13981: to be plotted in a stacked bar chart.
13982: 
13983: =item If the final element of @Values is a hash reference the key/value
13984: pairs will be added to the graph definition.
13985: 
13986: =back
13987: 
13988: Returns:
13989: 
13990: An <img> tag which references graph.png and the appropriate identifying
13991: information for the plot.
13992: 
13993: =cut
13994: 
13995: ############################################################
13996: ############################################################
13997: sub DrawBarGraph {
13998:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13999:     #
14000:     if (! defined($colors)) {
14001:         $colors = ['#33ff00', 
14002:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14003:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14004:                   ]; 
14005:     }
14006:     my $extra_settings = {};
14007:     if (ref($Values[-1]) eq 'HASH') {
14008:         $extra_settings = pop(@Values);
14009:     }
14010:     #
14011:     my $identifier = &get_cgi_id();
14012:     my $id = 'cgi.'.$identifier;        
14013:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14014:         return '';
14015:     }
14016:     #
14017:     my @Labels;
14018:     if (defined($labels)) {
14019:         @Labels = @$labels;
14020:     } else {
14021:         for (my $i=0;$i<@{$Values[0]};$i++) {
14022:             push(@Labels,$i+1);
14023:         }
14024:     }
14025:     #
14026:     my $NumBars = scalar(@{$Values[0]});
14027:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14028:     my %ValuesHash;
14029:     my $NumSets=1;
14030:     foreach my $array (@Values) {
14031:         next if (! ref($array));
14032:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14033:             join(',',@$array);
14034:     }
14035:     #
14036:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14037:     if ($NumBars < 3) {
14038:         $width = 120+$NumBars*32;
14039:         $xskip = 1;
14040:         $bar_width = 30;
14041:     } elsif ($NumBars < 5) {
14042:         $width = 120+$NumBars*20;
14043:         $xskip = 1;
14044:         $bar_width = 20;
14045:     } elsif ($NumBars < 10) {
14046:         $width = 120+$NumBars*15;
14047:         $xskip = 1;
14048:         $bar_width = 15;
14049:     } elsif ($NumBars <= 25) {
14050:         $width = 120+$NumBars*11;
14051:         $xskip = 5;
14052:         $bar_width = 8;
14053:     } elsif ($NumBars <= 50) {
14054:         $width = 120+$NumBars*8;
14055:         $xskip = 5;
14056:         $bar_width = 4;
14057:     } else {
14058:         $width = 120+$NumBars*8;
14059:         $xskip = 5;
14060:         $bar_width = 4;
14061:     }
14062:     #
14063:     $Max = 1 if ($Max < 1);
14064:     if ( int($Max) < $Max ) {
14065:         $Max++;
14066:         $Max = int($Max);
14067:     }
14068:     $Title  = '' if (! defined($Title));
14069:     $xlabel = '' if (! defined($xlabel));
14070:     $ylabel = '' if (! defined($ylabel));
14071:     $ValuesHash{$id.'.title'}    = &escape($Title);
14072:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14073:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14074:     $ValuesHash{$id.'.y_max_value'} = $Max;
14075:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14076:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14077:     $ValuesHash{$id.'.PlotType'} = 'bar';
14078:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14079:     $ValuesHash{$id.'.height'}   = $height;
14080:     $ValuesHash{$id.'.width'}    = $width;
14081:     $ValuesHash{$id.'.xskip'}    = $xskip;
14082:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14083:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14084:     #
14085:     # Deal with other parameters
14086:     while (my ($key,$value) = each(%$extra_settings)) {
14087:         $ValuesHash{$id.'.'.$key} = $value;
14088:     }
14089:     #
14090:     &Apache::lonnet::appenv(\%ValuesHash);
14091:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14092: }
14093: 
14094: ############################################################
14095: ############################################################
14096: 
14097: =pod
14098: 
14099: =item * &DrawXYGraph()
14100: 
14101: Facilitates the plotting of data in an XY graph.
14102: Puts plot definition data into the users environment in order for 
14103: graph.png to plot it.  Returns an <img> tag for the plot.
14104: 
14105: Inputs:
14106: 
14107: =over 4
14108: 
14109: =item $Title: string, the title of the plot
14110: 
14111: =item $xlabel: string, text describing the X-axis of the plot
14112: 
14113: =item $ylabel: string, text describing the Y-axis of the plot
14114: 
14115: =item $Max: scalar, the maximum Y value to use in the plot
14116: If $Max is < any data point, the graph will not be rendered.
14117: 
14118: =item $colors: Array ref containing the hex color codes for the data to be 
14119: plotted in.  If undefined, default values will be used.
14120: 
14121: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14122: 
14123: =item $Ydata: Array ref containing Array refs.  
14124: Each of the contained arrays will be plotted as a separate curve.
14125: 
14126: =item %Values: hash indicating or overriding any default values which are 
14127: passed to graph.png.  
14128: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14129: 
14130: =back
14131: 
14132: Returns:
14133: 
14134: An <img> tag which references graph.png and the appropriate identifying
14135: information for the plot.
14136: 
14137: =cut
14138: 
14139: ############################################################
14140: ############################################################
14141: sub DrawXYGraph {
14142:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14143:     #
14144:     # Create the identifier for the graph
14145:     my $identifier = &get_cgi_id();
14146:     my $id = 'cgi.'.$identifier;
14147:     #
14148:     $Title  = '' if (! defined($Title));
14149:     $xlabel = '' if (! defined($xlabel));
14150:     $ylabel = '' if (! defined($ylabel));
14151:     my %ValuesHash = 
14152:         (
14153:          $id.'.title'  => &escape($Title),
14154:          $id.'.xlabel' => &escape($xlabel),
14155:          $id.'.ylabel' => &escape($ylabel),
14156:          $id.'.y_max_value'=> $Max,
14157:          $id.'.labels'     => join(',',@$Xlabels),
14158:          $id.'.PlotType'   => 'XY',
14159:          );
14160:     #
14161:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14162:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14163:     }
14164:     #
14165:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14166:         return '';
14167:     }
14168:     my $NumSets=1;
14169:     foreach my $array (@{$Ydata}){
14170:         next if (! ref($array));
14171:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14172:     }
14173:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14174:     #
14175:     # Deal with other parameters
14176:     while (my ($key,$value) = each(%Values)) {
14177:         $ValuesHash{$id.'.'.$key} = $value;
14178:     }
14179:     #
14180:     &Apache::lonnet::appenv(\%ValuesHash);
14181:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14182: }
14183: 
14184: ############################################################
14185: ############################################################
14186: 
14187: =pod
14188: 
14189: =item * &DrawXYYGraph()
14190: 
14191: Facilitates the plotting of data in an XY graph with two Y axes.
14192: Puts plot definition data into the users environment in order for 
14193: graph.png to plot it.  Returns an <img> tag for the plot.
14194: 
14195: Inputs:
14196: 
14197: =over 4
14198: 
14199: =item $Title: string, the title of the plot
14200: 
14201: =item $xlabel: string, text describing the X-axis of the plot
14202: 
14203: =item $ylabel: string, text describing the Y-axis of the plot
14204: 
14205: =item $colors: Array ref containing the hex color codes for the data to be 
14206: plotted in.  If undefined, default values will be used.
14207: 
14208: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14209: 
14210: =item $Ydata1: The first data set
14211: 
14212: =item $Min1: The minimum value of the left Y-axis
14213: 
14214: =item $Max1: The maximum value of the left Y-axis
14215: 
14216: =item $Ydata2: The second data set
14217: 
14218: =item $Min2: The minimum value of the right Y-axis
14219: 
14220: =item $Max2: The maximum value of the left Y-axis
14221: 
14222: =item %Values: hash indicating or overriding any default values which are 
14223: passed to graph.png.  
14224: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14225: 
14226: =back
14227: 
14228: Returns:
14229: 
14230: An <img> tag which references graph.png and the appropriate identifying
14231: information for the plot.
14232: 
14233: =cut
14234: 
14235: ############################################################
14236: ############################################################
14237: sub DrawXYYGraph {
14238:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14239:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14240:     #
14241:     # Create the identifier for the graph
14242:     my $identifier = &get_cgi_id();
14243:     my $id = 'cgi.'.$identifier;
14244:     #
14245:     $Title  = '' if (! defined($Title));
14246:     $xlabel = '' if (! defined($xlabel));
14247:     $ylabel = '' if (! defined($ylabel));
14248:     my %ValuesHash = 
14249:         (
14250:          $id.'.title'  => &escape($Title),
14251:          $id.'.xlabel' => &escape($xlabel),
14252:          $id.'.ylabel' => &escape($ylabel),
14253:          $id.'.labels' => join(',',@$Xlabels),
14254:          $id.'.PlotType' => 'XY',
14255:          $id.'.NumSets' => 2,
14256:          $id.'.two_axes' => 1,
14257:          $id.'.y1_max_value' => $Max1,
14258:          $id.'.y1_min_value' => $Min1,
14259:          $id.'.y2_max_value' => $Max2,
14260:          $id.'.y2_min_value' => $Min2,
14261:          );
14262:     #
14263:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14264:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14265:     }
14266:     #
14267:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14268:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14269:         return '';
14270:     }
14271:     my $NumSets=1;
14272:     foreach my $array ($Ydata1,$Ydata2){
14273:         next if (! ref($array));
14274:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14275:     }
14276:     #
14277:     # Deal with other parameters
14278:     while (my ($key,$value) = each(%Values)) {
14279:         $ValuesHash{$id.'.'.$key} = $value;
14280:     }
14281:     #
14282:     &Apache::lonnet::appenv(\%ValuesHash);
14283:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14284: }
14285: 
14286: ############################################################
14287: ############################################################
14288: 
14289: =pod
14290: 
14291: =back 
14292: 
14293: =head1 Statistics helper routines?  
14294: 
14295: Bad place for them but what the hell.
14296: 
14297: =over 4
14298: 
14299: =item * &chartlink()
14300: 
14301: Returns a link to the chart for a specific student.  
14302: 
14303: Inputs:
14304: 
14305: =over 4
14306: 
14307: =item $linktext: The text of the link
14308: 
14309: =item $sname: The students username
14310: 
14311: =item $sdomain: The students domain
14312: 
14313: =back
14314: 
14315: =back
14316: 
14317: =cut
14318: 
14319: ############################################################
14320: ############################################################
14321: sub chartlink {
14322:     my ($linktext, $sname, $sdomain) = @_;
14323:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14324:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14325:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14326:        '">'.$linktext.'</a>';
14327: }
14328: 
14329: #######################################################
14330: #######################################################
14331: 
14332: =pod
14333: 
14334: =head1 Course Environment Routines
14335: 
14336: =over 4
14337: 
14338: =item * &restore_course_settings()
14339: 
14340: =item * &store_course_settings()
14341: 
14342: Restores/Store indicated form parameters from the course environment.
14343: Will not overwrite existing values of the form parameters.
14344: 
14345: Inputs: 
14346: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14347: 
14348: a hash ref describing the data to be stored.  For example:
14349:    
14350: %Save_Parameters = ('Status' => 'scalar',
14351:     'chartoutputmode' => 'scalar',
14352:     'chartoutputdata' => 'scalar',
14353:     'Section' => 'array',
14354:     'Group' => 'array',
14355:     'StudentData' => 'array',
14356:     'Maps' => 'array');
14357: 
14358: Returns: both routines return nothing
14359: 
14360: =back
14361: 
14362: =cut
14363: 
14364: #######################################################
14365: #######################################################
14366: sub store_course_settings {
14367:     return &store_settings($env{'request.course.id'},@_);
14368: }
14369: 
14370: sub store_settings {
14371:     # save to the environment
14372:     # appenv the same items, just to be safe
14373:     my $udom  = $env{'user.domain'};
14374:     my $uname = $env{'user.name'};
14375:     my ($context,$prefix,$Settings) = @_;
14376:     my %SaveHash;
14377:     my %AppHash;
14378:     while (my ($setting,$type) = each(%$Settings)) {
14379:         my $basename = join('.','internal',$context,$prefix,$setting);
14380:         my $envname = 'environment.'.$basename;
14381:         if (exists($env{'form.'.$setting})) {
14382:             # Save this value away
14383:             if ($type eq 'scalar' &&
14384:                 (! exists($env{$envname}) || 
14385:                  $env{$envname} ne $env{'form.'.$setting})) {
14386:                 $SaveHash{$basename} = $env{'form.'.$setting};
14387:                 $AppHash{$envname}   = $env{'form.'.$setting};
14388:             } elsif ($type eq 'array') {
14389:                 my $stored_form;
14390:                 if (ref($env{'form.'.$setting})) {
14391:                     $stored_form = join(',',
14392:                                         map {
14393:                                             &escape($_);
14394:                                         } sort(@{$env{'form.'.$setting}}));
14395:                 } else {
14396:                     $stored_form = 
14397:                         &escape($env{'form.'.$setting});
14398:                 }
14399:                 # Determine if the array contents are the same.
14400:                 if ($stored_form ne $env{$envname}) {
14401:                     $SaveHash{$basename} = $stored_form;
14402:                     $AppHash{$envname}   = $stored_form;
14403:                 }
14404:             }
14405:         }
14406:     }
14407:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14408:                                           $udom,$uname);
14409:     if ($put_result !~ /^(ok|delayed)/) {
14410:         &Apache::lonnet::logthis('unable to save form parameters, '.
14411:                                  'got error:'.$put_result);
14412:     }
14413:     # Make sure these settings stick around in this session, too
14414:     &Apache::lonnet::appenv(\%AppHash);
14415:     return;
14416: }
14417: 
14418: sub restore_course_settings {
14419:     return &restore_settings($env{'request.course.id'},@_);
14420: }
14421: 
14422: sub restore_settings {
14423:     my ($context,$prefix,$Settings) = @_;
14424:     while (my ($setting,$type) = each(%$Settings)) {
14425:         next if (exists($env{'form.'.$setting}));
14426:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14427:             '.'.$setting;
14428:         if (exists($env{$envname})) {
14429:             if ($type eq 'scalar') {
14430:                 $env{'form.'.$setting} = $env{$envname};
14431:             } elsif ($type eq 'array') {
14432:                 $env{'form.'.$setting} = [ 
14433:                                            map { 
14434:                                                &unescape($_); 
14435:                                            } split(',',$env{$envname})
14436:                                            ];
14437:             }
14438:         }
14439:     }
14440: }
14441: 
14442: #######################################################
14443: #######################################################
14444: 
14445: =pod
14446: 
14447: =head1 Domain E-mail Routines  
14448: 
14449: =over 4
14450: 
14451: =item * &build_recipient_list()
14452: 
14453: Build recipient lists for following types of e-mail:
14454: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14455: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14456: module change checking, student/employee ID conflict checks, as
14457: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14458: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14459: 
14460: Inputs:
14461: defmail (scalar - email address of default recipient),
14462: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14463: requestsmail, updatesmail, or idconflictsmail).
14464: 
14465: defdom (domain for which to retrieve configuration settings),
14466: 
14467: origmail (scalar - email address of recipient from loncapa.conf,
14468: i.e., predates configuration by DC via domainprefs.pm
14469: 
14470: $requname username of requester (if mailing type is helpdeskmail)
14471: 
14472: $requdom domain of requester (if mailing type is helpdeskmail)
14473: 
14474: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14475: 
14476: Returns: comma separated list of addresses to which to send e-mail.
14477: 
14478: =back
14479: 
14480: =cut
14481: 
14482: ############################################################
14483: ############################################################
14484: sub build_recipient_list {
14485:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14486:     my @recipients;
14487:     my ($otheremails,$lastresort,$allbcc,$addtext);
14488:     my %domconfig =
14489:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14490:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14491:         if (exists($domconfig{'contacts'}{$mailing})) {
14492:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14493:                 my @contacts = ('adminemail','supportemail');
14494:                 foreach my $item (@contacts) {
14495:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14496:                         my $addr = $domconfig{'contacts'}{$item}; 
14497:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14498:                             push(@recipients,$addr);
14499:                         }
14500:                     }
14501:                 }
14502:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14503:                 if ($mailing eq 'helpdeskmail') {
14504:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14505:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14506:                         my @ok_bccs;
14507:                         foreach my $bcc (@bccs) {
14508:                             $bcc =~ s/^\s+//g;
14509:                             $bcc =~ s/\s+$//g;
14510:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14511:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14512:                                     push(@ok_bccs,$bcc);
14513:                                 }
14514:                             }
14515:                         }
14516:                         if (@ok_bccs > 0) {
14517:                             $allbcc = join(', ',@ok_bccs);
14518:                         }
14519:                     }
14520:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14521:                 }
14522:             }
14523:         } elsif ($origmail ne '') {
14524:             $lastresort = $origmail;
14525:         }
14526:         if ($mailing eq 'helpdeskmail') {
14527:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14528:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14529:                 my ($inststatus,$inststatus_checked);
14530:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14531:                     ($env{'user.domain'} ne 'public')) {
14532:                     $inststatus_checked = 1;
14533:                     $inststatus = $env{'environment.inststatus'};
14534:                 }
14535:                 unless ($inststatus_checked) {
14536:                     if (($requname ne '') && ($requdom ne '')) {
14537:                         if (($requname =~ /^$match_username$/) &&
14538:                             ($requdom =~ /^$match_domain$/) &&
14539:                             (&Apache::lonnet::domain($requdom))) {
14540:                             my $requhome = &Apache::lonnet::homeserver($requname,
14541:                                                                       $requdom);
14542:                             unless ($requhome eq 'no_host') {
14543:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14544:                                 $inststatus = $userenv{'inststatus'};
14545:                                 $inststatus_checked = 1;
14546:                             }
14547:                         }
14548:                     }
14549:                 }
14550:                 unless ($inststatus_checked) {
14551:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14552:                         my %srch = (srchby     => 'email',
14553:                                     srchdomain => $defdom,
14554:                                     srchterm   => $reqemail,
14555:                                     srchtype   => 'exact');
14556:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
14557:                         foreach my $uname (keys(%srch_results)) {
14558:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14559:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14560:                                 $inststatus_checked = 1;
14561:                                 last;
14562:                             }
14563:                         }
14564:                         unless ($inststatus_checked) {
14565:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
14566:                             if ($dirsrchres eq 'ok') {
14567:                                 foreach my $uname (keys(%srch_results)) {
14568:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14569:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14570:                                         $inststatus_checked = 1;
14571:                                         last;
14572:                                     }
14573:                                 }
14574:                             }
14575:                         }
14576:                     }
14577:                 }
14578:                 if ($inststatus ne '') {
14579:                     foreach my $status (split(/\:/,$inststatus)) {
14580:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
14581:                             my @contacts = ('adminemail','supportemail');
14582:                             foreach my $item (@contacts) {
14583:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
14584:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
14585:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
14586:                                         push(@recipients,$addr);
14587:                                     }
14588:                                 }
14589:                             }
14590:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
14591:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
14592:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
14593:                                 my @ok_bccs;
14594:                                 foreach my $bcc (@bccs) {
14595:                                     $bcc =~ s/^\s+//g;
14596:                                     $bcc =~ s/\s+$//g;
14597:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14598:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14599:                                             push(@ok_bccs,$bcc);
14600:                                         }
14601:                                     }
14602:                                 }
14603:                                 if (@ok_bccs > 0) {
14604:                                     $allbcc = join(', ',@ok_bccs);
14605:                                 }
14606:                             }
14607:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
14608:                             last;
14609:                         }
14610:                     }
14611:                 }
14612:             }
14613:         }
14614:     } elsif ($origmail ne '') {
14615:         $lastresort = $origmail;
14616:     }
14617:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14618:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14619:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14620:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14621:             my %what = (
14622:                           perlvar => 1,
14623:                        );
14624:             my $primary = &Apache::lonnet::domain($defdom,'primary');
14625:             if ($primary) {
14626:                 my $gotaddr;
14627:                 my ($result,$returnhash) =
14628:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14629:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14630:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14631:                         $lastresort = $returnhash->{'lonSupportEMail'};
14632:                         $gotaddr = 1;
14633:                     }
14634:                 }
14635:                 unless ($gotaddr) {
14636:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
14637:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
14638:                     unless ($uintdom eq $intdom) {
14639:                         my %domconfig =
14640:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14641:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
14642:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14643:                                 my @contacts = ('adminemail','supportemail');
14644:                                 foreach my $item (@contacts) {
14645:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14646:                                         my $addr = $domconfig{'contacts'}{$item};
14647:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14648:                                             push(@recipients,$addr);
14649:                                         }
14650:                                     }
14651:                                 }
14652:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14653:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14654:                                 }
14655:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14656:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14657:                                     my @ok_bccs;
14658:                                     foreach my $bcc (@bccs) {
14659:                                         $bcc =~ s/^\s+//g;
14660:                                         $bcc =~ s/\s+$//g;
14661:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14662:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14663:                                                 push(@ok_bccs,$bcc);
14664:                                             }
14665:                                         }
14666:                                     }
14667:                                     if (@ok_bccs > 0) {
14668:                                         $allbcc = join(', ',@ok_bccs);
14669:                                     }
14670:                                 }
14671:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14672:                             }
14673:                         }
14674:                     }
14675:                 }
14676:             }
14677:         }
14678:     }
14679:     if (defined($defmail)) {
14680:         if ($defmail ne '') {
14681:             push(@recipients,$defmail);
14682:         }
14683:     }
14684:     if ($otheremails) {
14685:         my @others;
14686:         if ($otheremails =~ /,/) {
14687:             @others = split(/,/,$otheremails);
14688:         } else {
14689:             push(@others,$otheremails);
14690:         }
14691:         foreach my $addr (@others) {
14692:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14693:                 push(@recipients,$addr);
14694:             }
14695:         }
14696:     }
14697:     if ($mailing eq 'helpdeskmail') {
14698:         if ((!@recipients) && ($lastresort ne '')) {
14699:             push(@recipients,$lastresort);
14700:         }
14701:     } elsif ($lastresort ne '') {
14702:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14703:             push(@recipients,$lastresort);
14704:         }
14705:     }
14706:     my $recipientlist = join(',',@recipients);
14707:     if (wantarray) {
14708:         return ($recipientlist,$allbcc,$addtext);
14709:     } else {
14710:         return $recipientlist;
14711:     }
14712: }
14713: 
14714: ############################################################
14715: ############################################################
14716: 
14717: =pod
14718: 
14719: =head1 Course Catalog Routines
14720: 
14721: =over 4
14722: 
14723: =item * &gather_categories()
14724: 
14725: Converts category definitions - keys of categories hash stored in  
14726: coursecategories in configuration.db on the primary library server in a 
14727: domain - to an array.  Also generates javascript and idx hash used to 
14728: generate Domain Coordinator interface for editing Course Categories.
14729: 
14730: Inputs:
14731: 
14732: categories (reference to hash of category definitions).
14733: 
14734: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14735:       categories and subcategories).
14736: 
14737: idx (reference to hash of counters used in Domain Coordinator interface for 
14738:       editing Course Categories).
14739: 
14740: jsarray (reference to array of categories used to create Javascript arrays for
14741:          Domain Coordinator interface for editing Course Categories).
14742: 
14743: Returns: nothing
14744: 
14745: Side effects: populates cats, idx and jsarray. 
14746: 
14747: =cut
14748: 
14749: sub gather_categories {
14750:     my ($categories,$cats,$idx,$jsarray) = @_;
14751:     my %counters;
14752:     my $num = 0;
14753:     foreach my $item (keys(%{$categories})) {
14754:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14755:         if ($container eq '' && $depth == 0) {
14756:             $cats->[$depth][$categories->{$item}] = $cat;
14757:         } else {
14758:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14759:         }
14760:         my ($escitem,$tail) = split(/:/,$item,2);
14761:         if ($counters{$tail} eq '') {
14762:             $counters{$tail} = $num;
14763:             $num ++;
14764:         }
14765:         if (ref($idx) eq 'HASH') {
14766:             $idx->{$item} = $counters{$tail};
14767:         }
14768:         if (ref($jsarray) eq 'ARRAY') {
14769:             push(@{$jsarray->[$counters{$tail}]},$item);
14770:         }
14771:     }
14772:     return;
14773: }
14774: 
14775: =pod
14776: 
14777: =item * &extract_categories()
14778: 
14779: Used to generate breadcrumb trails for course categories.
14780: 
14781: Inputs:
14782: 
14783: categories (reference to hash of category definitions).
14784: 
14785: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14786:       categories and subcategories).
14787: 
14788: trails (reference to array of breacrumb trails for each category).
14789: 
14790: allitems (reference to hash - key is category key 
14791:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14792: 
14793: idx (reference to hash of counters used in Domain Coordinator interface for
14794:       editing Course Categories).
14795: 
14796: jsarray (reference to array of categories used to create Javascript arrays for
14797:          Domain Coordinator interface for editing Course Categories).
14798: 
14799: subcats (reference to hash of arrays containing all subcategories within each 
14800:          category, -recursive)
14801: 
14802: maxd (reference to hash used to hold max depth for all top-level categories).
14803: 
14804: Returns: nothing
14805: 
14806: Side effects: populates trails and allitems hash references.
14807: 
14808: =cut
14809: 
14810: sub extract_categories {
14811:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
14812:     if (ref($categories) eq 'HASH') {
14813:         &gather_categories($categories,$cats,$idx,$jsarray);
14814:         if (ref($cats->[0]) eq 'ARRAY') {
14815:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14816:                 my $name = $cats->[0][$i];
14817:                 my $item = &escape($name).'::0';
14818:                 my $trailstr;
14819:                 if ($name eq 'instcode') {
14820:                     $trailstr = &mt('Official courses (with institutional codes)');
14821:                 } elsif ($name eq 'communities') {
14822:                     $trailstr = &mt('Communities');
14823:                 } else {
14824:                     $trailstr = $name;
14825:                 }
14826:                 if ($allitems->{$item} eq '') {
14827:                     push(@{$trails},$trailstr);
14828:                     $allitems->{$item} = scalar(@{$trails})-1;
14829:                 }
14830:                 my @parents = ($name);
14831:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14832:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14833:                         my $category = $cats->[1]{$name}[$j];
14834:                         if (ref($subcats) eq 'HASH') {
14835:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14836:                         }
14837:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
14838:                     }
14839:                 } else {
14840:                     if (ref($subcats) eq 'HASH') {
14841:                         $subcats->{$item} = [];
14842:                     }
14843:                     if (ref($maxd) eq 'HASH') {
14844:                         $maxd->{$name} = 1;
14845:                     }
14846:                 }
14847:             }
14848:         }
14849:     }
14850:     return;
14851: }
14852: 
14853: =pod
14854: 
14855: =item * &recurse_categories()
14856: 
14857: Recursively used to generate breadcrumb trails for course categories.
14858: 
14859: Inputs:
14860: 
14861: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14862:       categories and subcategories).
14863: 
14864: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14865: 
14866: category (current course category, for which breadcrumb trail is being generated).
14867: 
14868: trails (reference to array of breadcrumb trails for each category).
14869: 
14870: allitems (reference to hash - key is category key
14871:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14872: 
14873: parents (array containing containers directories for current category, 
14874:          back to top level). 
14875: 
14876: Returns: nothing
14877: 
14878: Side effects: populates trails and allitems hash references
14879: 
14880: =cut
14881: 
14882: sub recurse_categories {
14883:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
14884:     my $shallower = $depth - 1;
14885:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14886:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14887:             my $name = $cats->[$depth]{$category}[$k];
14888:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14889:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14890:             if ($allitems->{$item} eq '') {
14891:                 push(@{$trails},$trailstr);
14892:                 $allitems->{$item} = scalar(@{$trails})-1;
14893:             }
14894:             my $deeper = $depth+1;
14895:             push(@{$parents},$category);
14896:             if (ref($subcats) eq 'HASH') {
14897:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14898:                 for (my $j=@{$parents}; $j>=0; $j--) {
14899:                     my $higher;
14900:                     if ($j > 0) {
14901:                         $higher = &escape($parents->[$j]).':'.
14902:                                   &escape($parents->[$j-1]).':'.$j;
14903:                     } else {
14904:                         $higher = &escape($parents->[$j]).'::'.$j;
14905:                     }
14906:                     push(@{$subcats->{$higher}},$subcat);
14907:                 }
14908:             }
14909:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14910:                                 $subcats,$maxd);
14911:             pop(@{$parents});
14912:         }
14913:     } else {
14914:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14915:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
14916:         if ($allitems->{$item} eq '') {
14917:             push(@{$trails},$trailstr);
14918:             $allitems->{$item} = scalar(@{$trails})-1;
14919:         }
14920:         if (ref($maxd) eq 'HASH') {
14921:             if ($depth > $maxd->{$parents->[0]}) {
14922:                 $maxd->{$parents->[0]} = $depth;
14923:             }
14924:         }
14925:     }
14926:     return;
14927: }
14928: 
14929: =pod
14930: 
14931: =item * &assign_categories_table()
14932: 
14933: Create a datatable for display of hierarchical categories in a domain,
14934: with checkboxes to allow a course to be categorized. 
14935: 
14936: Inputs:
14937: 
14938: cathash - reference to hash of categories defined for the domain (from
14939:           configuration.db)
14940: 
14941: currcat - scalar with an & separated list of categories assigned to a course. 
14942: 
14943: type    - scalar contains course type (Course or Community).
14944: 
14945: disabled - scalar (optional) contains disabled="disabled" if input elements are
14946:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14947: 
14948: Returns: $output (markup to be displayed) 
14949: 
14950: =cut
14951: 
14952: sub assign_categories_table {
14953:     my ($cathash,$currcat,$type,$disabled) = @_;
14954:     my $output;
14955:     if (ref($cathash) eq 'HASH') {
14956:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
14957:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
14958:         $maxdepth = scalar(@cats);
14959:         if (@cats > 0) {
14960:             my $itemcount = 0;
14961:             if (ref($cats[0]) eq 'ARRAY') {
14962:                 my @currcategories;
14963:                 if ($currcat ne '') {
14964:                     @currcategories = split('&',$currcat);
14965:                 }
14966:                 my $table;
14967:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14968:                     my $parent = $cats[0][$i];
14969:                     next if ($parent eq 'instcode');
14970:                     if ($type eq 'Community') {
14971:                         next unless ($parent eq 'communities');
14972:                     } else {
14973:                         next if ($parent eq 'communities');
14974:                     }
14975:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14976:                     my $item = &escape($parent).'::0';
14977:                     my $checked = '';
14978:                     if (@currcategories > 0) {
14979:                         if (grep(/^\Q$item\E$/,@currcategories)) {
14980:                             $checked = ' checked="checked"';
14981:                         }
14982:                     }
14983:                     my $parent_title = $parent;
14984:                     if ($parent eq 'communities') {
14985:                         $parent_title = &mt('Communities');
14986:                     }
14987:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14988:                               '<input type="checkbox" name="usecategory" value="'.
14989:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
14990:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14991:                     my $depth = 1;
14992:                     push(@path,$parent);
14993:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
14994:                     pop(@path);
14995:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14996:                     $itemcount ++;
14997:                 }
14998:                 if ($itemcount) {
14999:                     $output = &Apache::loncommon::start_data_table().
15000:                               $table.
15001:                               &Apache::loncommon::end_data_table();
15002:                 }
15003:             }
15004:         }
15005:     }
15006:     return $output;
15007: }
15008: 
15009: =pod
15010: 
15011: =item * &assign_category_rows()
15012: 
15013: Create a datatable row for display of nested categories in a domain,
15014: with checkboxes to allow a course to be categorized,called recursively.
15015: 
15016: Inputs:
15017: 
15018: itemcount - track row number for alternating colors
15019: 
15020: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15021:       categories and subcategories.
15022: 
15023: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15024: 
15025: parent - parent of current category item
15026: 
15027: path - Array containing all categories back up through the hierarchy from the
15028:        current category to the top level.
15029: 
15030: currcategories - reference to array of current categories assigned to the course
15031: 
15032: disabled - scalar (optional) contains disabled="disabled" if input elements are
15033:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15034: 
15035: Returns: $output (markup to be displayed).
15036: 
15037: =cut
15038: 
15039: sub assign_category_rows {
15040:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15041:     my ($text,$name,$item,$chgstr);
15042:     if (ref($cats) eq 'ARRAY') {
15043:         my $maxdepth = scalar(@{$cats});
15044:         if (ref($cats->[$depth]) eq 'HASH') {
15045:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15046:                 my $numchildren = @{$cats->[$depth]{$parent}};
15047:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15048:                 $text .= '<td><table class="LC_data_table">';
15049:                 for (my $j=0; $j<$numchildren; $j++) {
15050:                     $name = $cats->[$depth]{$parent}[$j];
15051:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15052:                     my $deeper = $depth+1;
15053:                     my $checked = '';
15054:                     if (ref($currcategories) eq 'ARRAY') {
15055:                         if (@{$currcategories} > 0) {
15056:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15057:                                 $checked = ' checked="checked"';
15058:                             }
15059:                         }
15060:                     }
15061:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15062:                              '<input type="checkbox" name="usecategory" value="'.
15063:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15064:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15065:                              '</td><td>';
15066:                     if (ref($path) eq 'ARRAY') {
15067:                         push(@{$path},$name);
15068:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15069:                         pop(@{$path});
15070:                     }
15071:                     $text .= '</td></tr>';
15072:                 }
15073:                 $text .= '</table></td>';
15074:             }
15075:         }
15076:     }
15077:     return $text;
15078: }
15079: 
15080: =pod
15081: 
15082: =back
15083: 
15084: =cut
15085: 
15086: ############################################################
15087: ############################################################
15088: 
15089: 
15090: sub commit_customrole {
15091:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15092:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15093:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15094:                          ($end?', ending '.localtime($end):'').': <b>'.
15095:               &Apache::lonnet::assigncustomrole(
15096:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15097:                  '</b><br />';
15098:     return $output;
15099: }
15100: 
15101: sub commit_standardrole {
15102:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15103:     my ($output,$logmsg,$linefeed);
15104:     if ($context eq 'auto') {
15105:         $linefeed = "\n";
15106:     } else {
15107:         $linefeed = "<br />\n";
15108:     }  
15109:     if ($three eq 'st') {
15110:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15111:                                          $one,$two,$sec,$context,$credits);
15112:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15113:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15114:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15115:         } else {
15116:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15117:                ($start?', '.&mt('starting').' '.localtime($start):'').
15118:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15119:             if ($context eq 'auto') {
15120:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15121:             } else {
15122:                $output .= '<b>'.$result.'</b>'.$linefeed.
15123:                &mt('Add to classlist').': <b>ok</b>';
15124:             }
15125:             $output .= $linefeed;
15126:         }
15127:     } else {
15128:         $output = &mt('Assigning').' '.$three.' in '.$url.
15129:                ($start?', '.&mt('starting').' '.localtime($start):'').
15130:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15131:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15132:         if ($context eq 'auto') {
15133:             $output .= $result.$linefeed;
15134:         } else {
15135:             $output .= '<b>'.$result.'</b>'.$linefeed;
15136:         }
15137:     }
15138:     return $output;
15139: }
15140: 
15141: sub commit_studentrole {
15142:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15143:         $credits) = @_;
15144:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15145:     if ($context eq 'auto') {
15146:         $linefeed = "\n";
15147:     } else {
15148:         $linefeed = '<br />'."\n";
15149:     }
15150:     if (defined($one) && defined($two)) {
15151:         my $cid=$one.'_'.$two;
15152:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15153:         my $secchange = 0;
15154:         my $expire_role_result;
15155:         my $modify_section_result;
15156:         if ($oldsec ne '-1') { 
15157:             if ($oldsec ne $sec) {
15158:                 $secchange = 1;
15159:                 my $now = time;
15160:                 my $uurl='/'.$cid;
15161:                 $uurl=~s/\_/\//g;
15162:                 if ($oldsec) {
15163:                     $uurl.='/'.$oldsec;
15164:                 }
15165:                 $oldsecurl = $uurl;
15166:                 $expire_role_result = 
15167:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15168:                 if ($env{'request.course.sec'} ne '') { 
15169:                     if ($expire_role_result eq 'refused') {
15170:                         my @roles = ('st');
15171:                         my @statuses = ('previous');
15172:                         my @roledoms = ($one);
15173:                         my $withsec = 1;
15174:                         my %roleshash = 
15175:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15176:                                               \@statuses,\@roles,\@roledoms,$withsec);
15177:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15178:                             my ($oldstart,$oldend) = 
15179:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15180:                             if ($oldend > 0 && $oldend <= $now) {
15181:                                 $expire_role_result = 'ok';
15182:                             }
15183:                         }
15184:                     }
15185:                 }
15186:                 $result = $expire_role_result;
15187:             }
15188:         }
15189:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15190:             $modify_section_result = 
15191:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15192:                                                            undef,undef,undef,$sec,
15193:                                                            $end,$start,'','',$cid,
15194:                                                            '',$context,$credits);
15195:             if ($modify_section_result =~ /^ok/) {
15196:                 if ($secchange == 1) {
15197:                     if ($sec eq '') {
15198:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15199:                     } else {
15200:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15201:                     }
15202:                 } elsif ($oldsec eq '-1') {
15203:                     if ($sec eq '') {
15204:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15205:                     } else {
15206:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15207:                     }
15208:                 } else {
15209:                     if ($sec eq '') {
15210:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15211:                     } else {
15212:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15213:                     }
15214:                 }
15215:             } else {
15216:                 if ($secchange) {       
15217:                     $$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;
15218:                 } else {
15219:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15220:                 }
15221:             }
15222:             $result = $modify_section_result;
15223:         } elsif ($secchange == 1) {
15224:             if ($oldsec eq '') {
15225:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15226:             } else {
15227:                 $$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;
15228:             }
15229:             if ($expire_role_result eq 'refused') {
15230:                 my $newsecurl = '/'.$cid;
15231:                 $newsecurl =~ s/\_/\//g;
15232:                 if ($sec ne '') {
15233:                     $newsecurl.='/'.$sec;
15234:                 }
15235:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15236:                     if ($sec eq '') {
15237:                         $$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;
15238:                     } else {
15239:                         $$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;
15240:                     }
15241:                 }
15242:             }
15243:         }
15244:     } else {
15245:         $$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;
15246:         $result = "error: incomplete course id\n";
15247:     }
15248:     return $result;
15249: }
15250: 
15251: sub show_role_extent {
15252:     my ($scope,$context,$role) = @_;
15253:     $scope =~ s{^/}{};
15254:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15255:     push(@courseroles,'co');
15256:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15257:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15258:         $scope =~ s{/}{_};
15259:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15260:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15261:         my ($audom,$auname) = split(/\//,$scope);
15262:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15263:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15264:     } else {
15265:         $scope =~ s{/$}{};
15266:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15267:                    &Apache::lonnet::domain($scope,'description').'</span>');
15268:     }
15269: }
15270: 
15271: ############################################################
15272: ############################################################
15273: 
15274: sub check_clone {
15275:     my ($args,$linefeed) = @_;
15276:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15277:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15278:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15279:     my $clonemsg;
15280:     my $can_clone = 0;
15281:     my $lctype = lc($args->{'crstype'});
15282:     if ($lctype ne 'community') {
15283:         $lctype = 'course';
15284:     }
15285:     if ($clonehome eq 'no_host') {
15286:         if ($args->{'crstype'} eq 'Community') {
15287:             $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'});
15288:         } else {
15289:             $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'});
15290:         }     
15291:     } else {
15292: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15293:         if ($args->{'crstype'} eq 'Community') {
15294:             if ($clonedesc{'type'} ne 'Community') {
15295:                  $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'});
15296:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
15297:             }
15298:         }
15299: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15300:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15301: 	    $can_clone = 1;
15302: 	} else {
15303: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15304: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15305:             if ($clonehash{'cloners'} eq '') {
15306:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15307:                 if ($domdefs{'canclone'}) {
15308:                     unless ($domdefs{'canclone'} eq 'none') {
15309:                         if ($domdefs{'canclone'} eq 'domain') {
15310:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15311:                                 $can_clone = 1;
15312:                             }
15313:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15314:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15315:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15316:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15317:                                 $can_clone = 1;
15318:                             }
15319:                         }
15320:                     }
15321:                 }
15322:             } else {
15323: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15324:                 if (grep(/^\*$/,@cloners)) {
15325:                     $can_clone = 1;
15326:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15327:                     $can_clone = 1;
15328:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15329:                     $can_clone = 1;
15330:                 }
15331:                 unless ($can_clone) {
15332:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15333:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15334:                         my (%gotdomdefaults,%gotcodedefaults);
15335:                         foreach my $cloner (@cloners) {
15336:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15337:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15338:                                 my (%codedefaults,@code_order);
15339:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15340:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15341:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15342:                                     }
15343:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15344:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15345:                                     }
15346:                                 } else {
15347:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15348:                                                                             \%codedefaults,
15349:                                                                             \@code_order);
15350:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15351:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15352:                                 }
15353:                                 if (@code_order > 0) {
15354:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15355:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15356:                                                                                 $args->{'crscode'})) {
15357:                                         $can_clone = 1;
15358:                                         last;
15359:                                     }
15360:                                 }
15361:                             }
15362:                         }
15363:                     }
15364:                 }
15365:             }
15366:             unless ($can_clone) {
15367:                 my $ccrole = 'cc';
15368:                 if ($args->{'crstype'} eq 'Community') {
15369:                     $ccrole = 'co';
15370:                 }
15371:                 my %roleshash =
15372:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
15373:                                                   $args->{'ccdomain'},
15374:                                                   'userroles',['active'],[$ccrole],
15375:                                                   [$args->{'clonedomain'}]);
15376:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15377:                     $can_clone = 1;
15378:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15379:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15380:                     $can_clone = 1;
15381:                 }
15382:             }
15383:             unless ($can_clone) {
15384:                 if ($args->{'crstype'} eq 'Community') {
15385:                     $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'});
15386:                 } else {
15387:                     $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'});
15388: 	        }
15389: 	    }
15390:         }
15391:     }
15392:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
15393: }
15394: 
15395: sub construct_course {
15396:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15397:         $cnum,$category,$coderef) = @_;
15398:     my $outcome;
15399:     my $linefeed =  '<br />'."\n";
15400:     if ($context eq 'auto') {
15401:         $linefeed = "\n";
15402:     }
15403: 
15404: #
15405: # Are we cloning?
15406: #
15407:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
15408:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15409: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15410: 	if ($context ne 'auto') {
15411:             if ($clonemsg ne '') {
15412: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15413:             }
15414: 	}
15415: 	$outcome .= $clonemsg.$linefeed;
15416: 
15417:         if (!$can_clone) {
15418: 	    return (0,$outcome);
15419: 	}
15420:     }
15421: 
15422: #
15423: # Open course
15424: #
15425:     my $crstype = lc($args->{'crstype'});
15426:     my %cenv=();
15427:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15428:                                              $args->{'cdescr'},
15429:                                              $args->{'curl'},
15430:                                              $args->{'course_home'},
15431:                                              $args->{'nonstandard'},
15432:                                              $args->{'crscode'},
15433:                                              $args->{'ccuname'}.':'.
15434:                                              $args->{'ccdomain'},
15435:                                              $args->{'crstype'},
15436:                                              $cnum,$context,$category);
15437: 
15438:     # Note: The testing routines depend on this being output; see 
15439:     # Utils::Course. This needs to at least be output as a comment
15440:     # if anyone ever decides to not show this, and Utils::Course::new
15441:     # will need to be suitably modified.
15442:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
15443:     if ($$courseid =~ /^error:/) {
15444:         return (0,$outcome);
15445:     }
15446: 
15447: #
15448: # Check if created correctly
15449: #
15450:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15451:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15452:     if ($crsuhome eq 'no_host') {
15453:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15454:         return (0,$outcome);
15455:     }
15456:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15457: 
15458: #
15459: # Do the cloning
15460: #   
15461:     if ($can_clone && $cloneid) {
15462: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
15463: 	if ($context ne 'auto') {
15464: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15465: 	}
15466: 	$outcome .= $clonemsg.$linefeed;
15467: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15468: # Copy all files
15469: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15470: # Restore URL
15471: 	$cenv{'url'}=$oldcenv{'url'};
15472: # Restore title
15473: 	$cenv{'description'}=$oldcenv{'description'};
15474: # Restore creation date, creator and creation context.
15475:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
15476:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15477:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15478: # Mark as cloned
15479: 	$cenv{'clonedfrom'}=$cloneid;
15480: # Need to clone grading mode
15481:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15482:         $cenv{'grading'}=$newenv{'grading'};
15483: # Do not clone these environment entries
15484:         &Apache::lonnet::del('environment',
15485:                   ['default_enrollment_start_date',
15486:                    'default_enrollment_end_date',
15487:                    'question.email',
15488:                    'policy.email',
15489:                    'comment.email',
15490:                    'pch.users.denied',
15491:                    'plc.users.denied',
15492:                    'hidefromcat',
15493:                    'checkforpriv',
15494:                    'categories'],
15495:                    $$crsudom,$$crsunum);
15496:         if ($args->{'textbook'}) {
15497:             $cenv{'internal.textbook'} = $args->{'textbook'};
15498:         }
15499:     }
15500: 
15501: #
15502: # Set environment (will override cloned, if existing)
15503: #
15504:     my @sections = ();
15505:     my @xlists = ();
15506:     if ($args->{'crstype'}) {
15507:         $cenv{'type'}=$args->{'crstype'};
15508:     }
15509:     if ($args->{'crsid'}) {
15510:         $cenv{'courseid'}=$args->{'crsid'};
15511:     }
15512:     if ($args->{'crscode'}) {
15513:         $cenv{'internal.coursecode'}=$args->{'crscode'};
15514:     }
15515:     if ($args->{'crsquota'} ne '') {
15516:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
15517:     } else {
15518:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15519:     }
15520:     if ($args->{'ccuname'}) {
15521:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15522:                                         ':'.$args->{'ccdomain'};
15523:     } else {
15524:         $cenv{'internal.courseowner'} = $args->{'curruser'};
15525:     }
15526:     if ($args->{'defaultcredits'}) {
15527:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15528:     }
15529:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15530:     if ($args->{'crssections'}) {
15531:         $cenv{'internal.sectionnums'} = '';
15532:         if ($args->{'crssections'} =~ m/,/) {
15533:             @sections = split/,/,$args->{'crssections'};
15534:         } else {
15535:             $sections[0] = $args->{'crssections'};
15536:         }
15537:         if (@sections > 0) {
15538:             foreach my $item (@sections) {
15539:                 my ($sec,$gp) = split/:/,$item;
15540:                 my $class = $args->{'crscode'}.$sec;
15541:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15542:                 $cenv{'internal.sectionnums'} .= $item.',';
15543:                 unless ($addcheck eq 'ok') {
15544:                     push(@badclasses,$class);
15545:                 }
15546:             }
15547:             $cenv{'internal.sectionnums'} =~ s/,$//;
15548:         }
15549:     }
15550: # do not hide course coordinator from staff listing, 
15551: # even if privileged
15552:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15553: # add course coordinator's domain to domains to check for privileged users
15554: # if different to course domain
15555:     if ($$crsudom ne $args->{'ccdomain'}) {
15556:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15557:     }
15558: # add crosslistings
15559:     if ($args->{'crsxlist'}) {
15560:         $cenv{'internal.crosslistings'}='';
15561:         if ($args->{'crsxlist'} =~ m/,/) {
15562:             @xlists = split/,/,$args->{'crsxlist'};
15563:         } else {
15564:             $xlists[0] = $args->{'crsxlist'};
15565:         }
15566:         if (@xlists > 0) {
15567:             foreach my $item (@xlists) {
15568:                 my ($xl,$gp) = split/:/,$item;
15569:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15570:                 $cenv{'internal.crosslistings'} .= $item.',';
15571:                 unless ($addcheck eq 'ok') {
15572:                     push(@badclasses,$xl);
15573:                 }
15574:             }
15575:             $cenv{'internal.crosslistings'} =~ s/,$//;
15576:         }
15577:     }
15578:     if ($args->{'autoadds'}) {
15579:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15580:     }
15581:     if ($args->{'autodrops'}) {
15582:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15583:     }
15584: # check for notification of enrollment changes
15585:     my @notified = ();
15586:     if ($args->{'notify_owner'}) {
15587:         if ($args->{'ccuname'} ne '') {
15588:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15589:         }
15590:     }
15591:     if ($args->{'notify_dc'}) {
15592:         if ($uname ne '') { 
15593:             push(@notified,$uname.':'.$udom);
15594:         }
15595:     }
15596:     if (@notified > 0) {
15597:         my $notifylist;
15598:         if (@notified > 1) {
15599:             $notifylist = join(',',@notified);
15600:         } else {
15601:             $notifylist = $notified[0];
15602:         }
15603:         $cenv{'internal.notifylist'} = $notifylist;
15604:     }
15605:     if (@badclasses > 0) {
15606:         my %lt=&Apache::lonlocal::texthash(
15607:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15608:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15609:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15610:         );
15611:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15612:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
15613:         if ($context eq 'auto') {
15614:             $outcome .= $badclass_msg.$linefeed;
15615:         } else {
15616:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15617:         }
15618:         foreach my $item (@badclasses) {
15619:             if ($context eq 'auto') {
15620:                 $outcome .= " - $item\n";
15621:             } else {
15622:                 $outcome .= "<li>$item</li>\n";
15623:             }
15624:         }
15625:         if ($context eq 'auto') {
15626:             $outcome .= $linefeed;
15627:         } else {
15628:             $outcome .= "</ul><br /><br /></div>\n";
15629:         }
15630:     }
15631:     if ($args->{'no_end_date'}) {
15632:         $args->{'endaccess'} = 0;
15633:     }
15634:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15635:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15636:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15637:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15638:     if ($args->{'showphotos'}) {
15639:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15640:     }
15641:     $cenv{'internal.authtype'} = $args->{'authtype'};
15642:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15643:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15644:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15645:             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'); 
15646:             if ($context eq 'auto') {
15647:                 $outcome .= $krb_msg;
15648:             } else {
15649:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15650:             }
15651:             $outcome .= $linefeed;
15652:         }
15653:     }
15654:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15655:        if ($args->{'setpolicy'}) {
15656:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15657:        }
15658:        if ($args->{'setcontent'}) {
15659:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15660:        }
15661:        if ($args->{'setcomment'}) {
15662:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15663:        }
15664:     }
15665:     if ($args->{'reshome'}) {
15666: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15667: 	$cenv{'reshome'}=~s/\/+$/\//;
15668:     }
15669: #
15670: # course has keyed access
15671: #
15672:     if ($args->{'setkeys'}) {
15673:        $cenv{'keyaccess'}='yes';
15674:     }
15675: # if specified, key authority is not course, but user
15676: # only active if keyaccess is yes
15677:     if ($args->{'keyauth'}) {
15678: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15679: 	$user = &LONCAPA::clean_username($user);
15680: 	$domain = &LONCAPA::clean_username($domain);
15681: 	if ($user ne '' && $domain ne '') {
15682: 	    $cenv{'keyauth'}=$user.':'.$domain;
15683: 	}
15684:     }
15685: 
15686: #
15687: #  generate and store uniquecode (available to course requester), if course should have one.
15688: #
15689:     if ($args->{'uniquecode'}) {
15690:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15691:         if ($code) {
15692:             $cenv{'internal.uniquecode'} = $code;
15693:             my %crsinfo =
15694:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15695:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15696:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15697:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15698:             }
15699:             if (ref($coderef)) {
15700:                 $$coderef = $code;
15701:             }
15702:         }
15703:     }
15704: 
15705:     if ($args->{'disresdis'}) {
15706:         $cenv{'pch.roles.denied'}='st';
15707:     }
15708:     if ($args->{'disablechat'}) {
15709:         $cenv{'plc.roles.denied'}='st';
15710:     }
15711: 
15712:     # Record we've not yet viewed the Course Initialization Helper for this 
15713:     # course
15714:     $cenv{'course.helper.not.run'} = 1;
15715:     #
15716:     # Use new Randomseed
15717:     #
15718:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15719:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15720:     #
15721:     # The encryption code and receipt prefix for this course
15722:     #
15723:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15724:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15725:     #
15726:     # By default, use standard grading
15727:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15728: 
15729:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15730:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15731: #
15732: # Open all assignments
15733: #
15734:     if ($args->{'openall'}) {
15735:        my $opendate = time;
15736:        if ($args->{'openallfrom'} =~ /^\d+$/) {
15737:            $opendate = $args->{'openallfrom'};
15738:        }
15739:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15740:        my %storecontent = ($storeunder         => $opendate,
15741:                            $storeunder.'.type' => 'date_start');
15742:        $outcome .= &mt('All assignments open starting [_1]',
15743:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
15744:                    &Apache::lonnet::cput
15745:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15746:    }
15747: #
15748: # Set first page
15749: #
15750:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15751: 	    || ($cloneid)) {
15752: 	use LONCAPA::map;
15753: 	$outcome .= &mt('Setting first resource').': ';
15754: 
15755: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15756:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15757: 
15758:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15759:         my $title; my $url;
15760:         if ($args->{'firstres'} eq 'syl') {
15761: 	    $title=&mt('Syllabus');
15762:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15763:         } else {
15764:             $title=&mt('Table of Contents');
15765:             $url='/adm/navmaps';
15766:         }
15767: 
15768:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15769: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15770: 
15771: 	if ($errtext) { $fatal=2; }
15772:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15773:     }
15774: 
15775:     return (1,$outcome);
15776: }
15777: 
15778: sub make_unique_code {
15779:     my ($cdom,$cnum) = @_;
15780:     # get lock on uniquecodes db
15781:     my $lockhash = {
15782:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15783:                                                   ':'.$env{'user.domain'},
15784:                    };
15785:     my $tries = 0;
15786:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15787:     my ($code,$error);
15788: 
15789:     while (($gotlock ne 'ok') && ($tries<3)) {
15790:         $tries ++;
15791:         sleep 1;
15792:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15793:     }
15794:     if ($gotlock eq 'ok') {
15795:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15796:         my $gotcode;
15797:         my $attempts = 0;
15798:         while ((!$gotcode) && ($attempts < 100)) {
15799:             $code = &generate_code();
15800:             if (!exists($currcodes{$code})) {
15801:                 $gotcode = 1;
15802:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15803:                     $error = 'nostore';
15804:                 }
15805:             }
15806:             $attempts ++;
15807:         }
15808:         my @del_lock = ($cnum."\0".'uniquecodes');
15809:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15810:     } else {
15811:         $error = 'nolock';
15812:     }
15813:     return ($code,$error);
15814: }
15815: 
15816: sub generate_code {
15817:     my $code;
15818:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15819:     for (my $i=0; $i<6; $i++) {
15820:         my $lettnum = int (rand 2);
15821:         my $item = '';
15822:         if ($lettnum) {
15823:             $item = $letts[int( rand(18) )];
15824:         } else {
15825:             $item = 1+int( rand(8) );
15826:         }
15827:         $code .= $item;
15828:     }
15829:     return $code;
15830: }
15831: 
15832: ############################################################
15833: ############################################################
15834: 
15835: #SD
15836: # only Community and Course, or anything else?
15837: sub course_type {
15838:     my ($cid) = @_;
15839:     if (!defined($cid)) {
15840:         $cid = $env{'request.course.id'};
15841:     }
15842:     if (defined($env{'course.'.$cid.'.type'})) {
15843:         return $env{'course.'.$cid.'.type'};
15844:     } else {
15845:         return 'Course';
15846:     }
15847: }
15848: 
15849: sub group_term {
15850:     my $crstype = &course_type();
15851:     my %names = (
15852:                   'Course' => 'group',
15853:                   'Community' => 'group',
15854:                 );
15855:     return $names{$crstype};
15856: }
15857: 
15858: sub course_types {
15859:     my @types = ('official','unofficial','community','textbook');
15860:     my %typename = (
15861:                          official   => 'Official course',
15862:                          unofficial => 'Unofficial course',
15863:                          community  => 'Community',
15864:                          textbook   => 'Textbook course',
15865:                    );
15866:     return (\@types,\%typename);
15867: }
15868: 
15869: sub icon {
15870:     my ($file)=@_;
15871:     my $curfext = lc((split(/\./,$file))[-1]);
15872:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15873:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15874:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15875: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15876: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15877: 	            $curfext.".gif") {
15878: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15879: 		$curfext.".gif";
15880: 	}
15881:     }
15882:     return &lonhttpdurl($iconname);
15883: } 
15884: 
15885: sub lonhttpdurl {
15886: #
15887: # Had been used for "small fry" static images on separate port 8080.
15888: # Modify here if lightweight http functionality desired again.
15889: # Currently eliminated due to increasing firewall issues.
15890: #
15891:     my ($url)=@_;
15892:     return $url;
15893: }
15894: 
15895: sub connection_aborted {
15896:     my ($r)=@_;
15897:     $r->print(" ");$r->rflush();
15898:     my $c = $r->connection;
15899:     return $c->aborted();
15900: }
15901: 
15902: #    Escapes strings that may have embedded 's that will be put into
15903: #    strings as 'strings'.
15904: sub escape_single {
15905:     my ($input) = @_;
15906:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15907:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15908:     return $input;
15909: }
15910: 
15911: #  Same as escape_single, but escape's "'s  This 
15912: #  can be used for  "strings"
15913: sub escape_double {
15914:     my ($input) = @_;
15915:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15916:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15917:     return $input;
15918: }
15919:  
15920: #   Escapes the last element of a full URL.
15921: sub escape_url {
15922:     my ($url)   = @_;
15923:     my @urlslices = split(/\//, $url,-1);
15924:     my $lastitem = &escape(pop(@urlslices));
15925:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15926: }
15927: 
15928: sub compare_arrays {
15929:     my ($arrayref1,$arrayref2) = @_;
15930:     my (@difference,%count);
15931:     @difference = ();
15932:     %count = ();
15933:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15934:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15935:         foreach my $element (keys(%count)) {
15936:             if ($count{$element} == 1) {
15937:                 push(@difference,$element);
15938:             }
15939:         }
15940:     }
15941:     return @difference;
15942: }
15943: 
15944: sub lon_status_items {
15945:     my %defaults = (
15946:                      E         => 100,
15947:                      W         => 4,
15948:                      N         => 1,
15949:                      U         => 5,
15950:                      threshold => 200,
15951:                      sysmail   => 2500,
15952:                    );
15953:     my %names = (
15954:                    E => 'Errors',
15955:                    W => 'Warnings',
15956:                    N => 'Notices',
15957:                    U => 'Unsent',
15958:                 );
15959:     return (\%defaults,\%names);
15960: }
15961: 
15962: # -------------------------------------------------------- Initialize user login
15963: sub init_user_environment {
15964:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
15965:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15966: 
15967:     my $public=($username eq 'public' && $domain eq 'public');
15968: 
15969: # See if old ID present, if so, remove
15970: 
15971:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15972:     my $now=time;
15973: 
15974:     if ($public) {
15975: 	my $max_public=100;
15976: 	my $oldest;
15977: 	my $oldest_time=0;
15978: 	for(my $next=1;$next<=$max_public;$next++) {
15979: 	    if (-e $lonids."/publicuser_$next.id") {
15980: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15981: 		if ($mtime<$oldest_time || !$oldest_time) {
15982: 		    $oldest_time=$mtime;
15983: 		    $oldest=$next;
15984: 		}
15985: 	    } else {
15986: 		$cookie="publicuser_$next";
15987: 		last;
15988: 	    }
15989: 	}
15990: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
15991:     } else {
15992: 	# if this isn't a robot, kill any existing non-robot sessions
15993: 	if (!$args->{'robot'}) {
15994: 	    opendir(DIR,$lonids);
15995: 	    while ($filename=readdir(DIR)) {
15996: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15997:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
15998:                             &GDBM_READER(),0640)) {
15999:                         my $linkedfile;
16000:                         if (exists($oldenv{'user.linkedenv'})) {
16001:                             $linkedfile = $oldenv{'user.linkedenv'};
16002:                         }
16003:                         untie(%oldenv);
16004:                         if (unlink("$lonids/$filename")) {
16005:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16006:                                 if (-l "$lonids/$linkedfile.id") {
16007:                                     unlink("$lonids/$linkedfile.id");
16008:                                 }
16009:                             }
16010:                         }
16011:                     } else {
16012:                         unlink($lonids.'/'.$filename);
16013:                     }
16014: 		}
16015: 	    }
16016: 	    closedir(DIR);
16017: # If there is a undeleted lockfile for the user's paste buffer remove it.
16018:             my $namespace = 'nohist_courseeditor';
16019:             my $lockingkey = 'paste'."\0".'locked_num';
16020:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16021:                                                 $domain,$username);
16022:             if (exists($lockhash{$lockingkey})) {
16023:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16024:                 unless ($delresult eq 'ok') {
16025:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16026:                 }
16027:             }
16028: 	}
16029: # Give them a new cookie
16030: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16031: 		                   : $now.$$.int(rand(10000)));
16032: 	$cookie="$username\_$id\_$domain\_$authhost";
16033:     
16034: # Initialize roles
16035: 
16036: 	($userroles,$firstaccenv,$timerintenv) = 
16037:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16038:     }
16039: # ------------------------------------ Check browser type and MathML capability
16040: 
16041:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16042:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16043: 
16044: # ------------------------------------------------------------- Get environment
16045: 
16046:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16047:     my ($tmp) = keys(%userenv);
16048:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
16049:     } else {
16050: 	undef(%userenv);
16051:     }
16052:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16053: 	$form->{'interface'}=$userenv{'interface'};
16054:     }
16055:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16056: 
16057: # --------------- Do not trust query string to be put directly into environment
16058:     foreach my $option ('interface','localpath','localres') {
16059:         $form->{$option}=~s/[\n\r\=]//gs;
16060:     }
16061: # --------------------------------------------------------- Write first profile
16062: 
16063:     {
16064:         my $ip = &Apache::lonnet::get_requestor_ip();
16065: 	my %initial_env = 
16066: 	    ("user.name"          => $username,
16067: 	     "user.domain"        => $domain,
16068: 	     "user.home"          => $authhost,
16069: 	     "browser.type"       => $clientbrowser,
16070: 	     "browser.version"    => $clientversion,
16071: 	     "browser.mathml"     => $clientmathml,
16072: 	     "browser.unicode"    => $clientunicode,
16073: 	     "browser.os"         => $clientos,
16074:              "browser.mobile"     => $clientmobile,
16075:              "browser.info"       => $clientinfo,
16076:              "browser.osversion"  => $clientosversion,
16077: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16078: 	     "request.course.fn"  => '',
16079: 	     "request.course.uri" => '',
16080: 	     "request.course.sec" => '',
16081: 	     "request.role"       => 'cm',
16082: 	     "request.role.adv"   => $env{'user.adv'},
16083: 	     "request.host"       => $ip,);
16084: 
16085:         if ($form->{'localpath'}) {
16086: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16087: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16088:         }
16089: 	
16090: 	if ($form->{'interface'}) {
16091: 	    $form->{'interface'}=~s/\W//gs;
16092: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16093: 	    $env{'browser.interface'}=$form->{'interface'};
16094: 	}
16095: 
16096:         if ($form->{'iptoken'}) {
16097:             my $lonhost = $r->dir_config('lonHostID');
16098:             $initial_env{"user.noloadbalance"} = $lonhost;
16099:             $env{'user.noloadbalance'} = $lonhost;
16100:         }
16101: 
16102:         if ($form->{'noloadbalance'}) {
16103:             my @hosts = &Apache::lonnet::current_machine_ids();
16104:             my $hosthere = $form->{'noloadbalance'};
16105:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16106:                 $initial_env{"user.noloadbalance"} = $hosthere;
16107:                 $env{'user.noloadbalance'} = $hosthere;
16108:             }
16109:         }
16110: 
16111:         unless ($domain eq 'public') {
16112:             my %is_adv = ( is_adv => $env{'user.adv'} );
16113:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16114: 
16115:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
16116:                 $userenv{'availabletools.'.$tool} = 
16117:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16118:                                                       undef,\%userenv,\%domdef,\%is_adv);
16119:             }
16120: 
16121:             foreach my $crstype ('official','unofficial','community','textbook') {
16122:                 $userenv{'canrequest.'.$crstype} =
16123:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16124:                                                       'reload','requestcourses',
16125:                                                       \%userenv,\%domdef,\%is_adv);
16126:             }
16127: 
16128:             $userenv{'canrequest.author'} =
16129:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16130:                                                   'reload','requestauthor',
16131:                                                   \%userenv,\%domdef,\%is_adv);
16132:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16133:                                                  $domain,$username);
16134:             my $reqstatus = $reqauthor{'author_status'};
16135:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
16136:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16137:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16138:                                                       $reqauthor{'author'}{'timestamp'};
16139:                 }
16140:             }
16141:         }
16142: 
16143: 	$env{'user.environment'} = "$lonids/$cookie.id";
16144: 
16145: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16146: 		 &GDBM_WRCREAT(),0640)) {
16147: 	    &_add_to_env(\%disk_env,\%initial_env);
16148: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16149: 	    &_add_to_env(\%disk_env,$userroles);
16150:             if (ref($firstaccenv) eq 'HASH') {
16151:                 &_add_to_env(\%disk_env,$firstaccenv);
16152:             }
16153:             if (ref($timerintenv) eq 'HASH') {
16154:                 &_add_to_env(\%disk_env,$timerintenv);
16155:             }
16156: 	    if (ref($args->{'extra_env'})) {
16157: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16158: 	    }
16159: 	    untie(%disk_env);
16160: 	} else {
16161: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16162: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16163: 	    return 'error: '.$!;
16164: 	}
16165:     }
16166:     $env{'request.role'}='cm';
16167:     $env{'request.role.adv'}=$env{'user.adv'};
16168:     $env{'browser.type'}=$clientbrowser;
16169: 
16170:     return $cookie;
16171: 
16172: }
16173: 
16174: sub _add_to_env {
16175:     my ($idf,$env_data,$prefix) = @_;
16176:     if (ref($env_data) eq 'HASH') {
16177:         while (my ($key,$value) = each(%$env_data)) {
16178: 	    $idf->{$prefix.$key} = $value;
16179: 	    $env{$prefix.$key}   = $value;
16180:         }
16181:     }
16182: }
16183: 
16184: # --- Get the symbolic name of a problem and the url
16185: sub get_symb {
16186:     my ($request,$silent) = @_;
16187:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16188:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16189:     if ($symb eq '') {
16190:         if (!$silent) {
16191:             if (ref($request)) { 
16192:                 $request->print("Unable to handle ambiguous references:$url:.");
16193:             }
16194:             return ();
16195:         }
16196:     }
16197:     &Apache::lonenc::check_decrypt(\$symb);
16198:     return ($symb);
16199: }
16200: 
16201: # --------------------------------------------------------------Get annotation
16202: 
16203: sub get_annotation {
16204:     my ($symb,$enc) = @_;
16205: 
16206:     my $key = $symb;
16207:     if (!$enc) {
16208:         $key =
16209:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16210:     }
16211:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16212:     return $annotation{$key};
16213: }
16214: 
16215: sub clean_symb {
16216:     my ($symb,$delete_enc) = @_;
16217: 
16218:     &Apache::lonenc::check_decrypt(\$symb);
16219:     my $enc = $env{'request.enc'};
16220:     if ($delete_enc) {
16221:         delete($env{'request.enc'});
16222:     }
16223: 
16224:     return ($symb,$enc);
16225: }
16226: 
16227: ############################################################
16228: ############################################################
16229: 
16230: =pod
16231: 
16232: =head1 Routines for building display used to search for courses
16233: 
16234: 
16235: =over 4
16236: 
16237: =item * &build_filters()
16238: 
16239: Create markup for a table used to set filters to use when selecting
16240: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16241: and quotacheck.pl
16242: 
16243: 
16244: Inputs:
16245: 
16246: filterlist - anonymous array of fields to include as potential filters
16247: 
16248: crstype - course type
16249: 
16250: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16251:               to pop-open a course selector (will contain "extra element").
16252: 
16253: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16254: 
16255: filter - anonymous hash of criteria and their values
16256: 
16257: action - form action
16258: 
16259: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16260: 
16261: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16262: 
16263: cloneruname - username of owner of new course who wants to clone
16264: 
16265: clonerudom - domain of owner of new course who wants to clone
16266: 
16267: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
16268: 
16269: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16270: 
16271: codedom - domain
16272: 
16273: formname - value of form element named "form".
16274: 
16275: fixeddom - domain, if fixed.
16276: 
16277: prevphase - value to assign to form element named "phase" when going back to the previous screen
16278: 
16279: cnameelement - name of form element in form on opener page which will receive title of selected course
16280: 
16281: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16282: 
16283: cdomelement - name of form element in form on opener page which will receive domain of selected course
16284: 
16285: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16286: 
16287: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16288: 
16289: clonewarning - warning message about missing information for intended course owner when DC creates a course
16290: 
16291: 
16292: Returns: $output - HTML for display of search criteria, and hidden form elements.
16293: 
16294: 
16295: Side Effects: None
16296: 
16297: =cut
16298: 
16299: # ---------------------------------------------- search for courses based on last activity etc.
16300: 
16301: sub build_filters {
16302:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16303:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16304:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16305:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16306:         $clonetext,$clonewarning) = @_;
16307:     my ($list,$jscript);
16308:     my $onchange = 'javascript:updateFilters(this)';
16309:     my ($domainselectform,$sincefilterform,$createdfilterform,
16310:         $ownerdomselectform,$persondomselectform,$instcodeform,
16311:         $typeselectform,$instcodetitle);
16312:     if ($formname eq '') {
16313:         $formname = $caller;
16314:     }
16315:     foreach my $item (@{$filterlist}) {
16316:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16317:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16318:             if ($item eq 'domainfilter') {
16319:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16320:             } elsif ($item eq 'coursefilter') {
16321:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16322:             } elsif ($item eq 'ownerfilter') {
16323:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16324:             } elsif ($item eq 'ownerdomfilter') {
16325:                 $filter->{'ownerdomfilter'} =
16326:                     &LONCAPA::clean_domain($filter->{$item});
16327:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16328:                                                        'ownerdomfilter',1);
16329:             } elsif ($item eq 'personfilter') {
16330:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16331:             } elsif ($item eq 'persondomfilter') {
16332:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16333:                                                         'persondomfilter',1);
16334:             } else {
16335:                 $filter->{$item} =~ s/\W//g;
16336:             }
16337:             if (!$filter->{$item}) {
16338:                 $filter->{$item} = '';
16339:             }
16340:         }
16341:         if ($item eq 'domainfilter') {
16342:             my $allow_blank = 1;
16343:             if ($formname eq 'portform') {
16344:                 $allow_blank=0;
16345:             } elsif ($formname eq 'studentform') {
16346:                 $allow_blank=0;
16347:             }
16348:             if ($fixeddom) {
16349:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16350:                                     ' value="'.$codedom.'" />'.
16351:                                     &Apache::lonnet::domain($codedom,'description');
16352:             } else {
16353:                 $domainselectform = &select_dom_form($filter->{$item},
16354:                                                      'domainfilter',
16355:                                                       $allow_blank,'',$onchange);
16356:             }
16357:         } else {
16358:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16359:         }
16360:     }
16361: 
16362:     # last course activity filter and selection
16363:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16364: 
16365:     # course created filter and selection
16366:     if (exists($filter->{'createdfilter'})) {
16367:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16368:     }
16369: 
16370:     my %lt = &Apache::lonlocal::texthash(
16371:                 'cac' => "$crstype Activity",
16372:                 'ccr' => "$crstype Created",
16373:                 'cde' => "$crstype Title",
16374:                 'cdo' => "$crstype Domain",
16375:                 'ins' => 'Institutional Code',
16376:                 'inc' => 'Institutional Categorization',
16377:                 'cow' => "$crstype Owner/Co-owner",
16378:                 'cop' => "$crstype Personnel Includes",
16379:                 'cog' => 'Type',
16380:              );
16381: 
16382:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16383:         my $typeval = 'Course';
16384:         if ($crstype eq 'Community') {
16385:             $typeval = 'Community';
16386:         }
16387:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16388:     } else {
16389:         $typeselectform =  '<select name="type" size="1"';
16390:         if ($onchange) {
16391:             $typeselectform .= ' onchange="'.$onchange.'"';
16392:         }
16393:         $typeselectform .= '>'."\n";
16394:         foreach my $posstype ('Course','Community') {
16395:             $typeselectform.='<option value="'.$posstype.'"'.
16396:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
16397:         }
16398:         $typeselectform.="</select>";
16399:     }
16400: 
16401:     my ($cloneableonlyform,$cloneabletitle);
16402:     if (exists($filter->{'cloneableonly'})) {
16403:         my $cloneableon = '';
16404:         my $cloneableoff = ' checked="checked"';
16405:         if ($filter->{'cloneableonly'}) {
16406:             $cloneableon = $cloneableoff;
16407:             $cloneableoff = '';
16408:         }
16409:         $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/>&nbsp;'.&mt('Required').'</label>'.('&nbsp;'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' />&nbsp;'.&mt('No restriction').'</label></span>';
16410:         if ($formname eq 'ccrs') {
16411:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16412:         } else {
16413:             $cloneabletitle = &mt('Cloneable by you');
16414:         }
16415:     }
16416:     my $officialjs;
16417:     if ($crstype eq 'Course') {
16418:         if (exists($filter->{'instcodefilter'})) {
16419: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
16420: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16421:             if ($codedom) {
16422:                 $officialjs = 1;
16423:                 ($instcodeform,$jscript,$$numtitlesref) =
16424:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16425:                                                                   $officialjs,$codetitlesref);
16426:                 if ($jscript) {
16427:                     $jscript = '<script type="text/javascript">'."\n".
16428:                                '// <![CDATA['."\n".
16429:                                $jscript."\n".
16430:                                '// ]]>'."\n".
16431:                                '</script>'."\n";
16432:                 }
16433:             }
16434:             if ($instcodeform eq '') {
16435:                 $instcodeform =
16436:                     '<input type="text" name="instcodefilter" size="10" value="'.
16437:                     $list->{'instcodefilter'}.'" />';
16438:                 $instcodetitle = $lt{'ins'};
16439:             } else {
16440:                 $instcodetitle = $lt{'inc'};
16441:             }
16442:             if ($fixeddom) {
16443:                 $instcodetitle .= '<br />('.$codedom.')';
16444:             }
16445:         }
16446:     }
16447:     my $output = qq|
16448: <form method="post" name="filterpicker" action="$action">
16449: <input type="hidden" name="form" value="$formname" />
16450: |;
16451:     if ($formname eq 'modifycourse') {
16452:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16453:                    '<input type="hidden" name="prevphase" value="'.
16454:                    $prevphase.'" />'."\n";
16455:     } elsif ($formname eq 'quotacheck') {
16456:         $output .= qq|
16457: <input type="hidden" name="sortby" value="" />
16458: <input type="hidden" name="sortorder" value="" />
16459: |;
16460:     } else {
16461:         my $name_input;
16462:         if ($cnameelement ne '') {
16463:             $name_input = '<input type="hidden" name="cnameelement" value="'.
16464:                           $cnameelement.'" />';
16465:         }
16466:         $output .= qq|
16467: <input type="hidden" name="cnumelement" value="$cnumelement" />
16468: <input type="hidden" name="cdomelement" value="$cdomelement" />
16469: $name_input
16470: $roleelement
16471: $multelement
16472: $typeelement
16473: |;
16474:         if ($formname eq 'portform') {
16475:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16476:         }
16477:     }
16478:     if ($fixeddom) {
16479:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16480:     }
16481:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16482:     if ($sincefilterform) {
16483:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16484:                   .$sincefilterform
16485:                   .&Apache::lonhtmlcommon::row_closure();
16486:     }
16487:     if ($createdfilterform) {
16488:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16489:                   .$createdfilterform
16490:                   .&Apache::lonhtmlcommon::row_closure();
16491:     }
16492:     if ($domainselectform) {
16493:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16494:                   .$domainselectform
16495:                   .&Apache::lonhtmlcommon::row_closure();
16496:     }
16497:     if ($typeselectform) {
16498:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16499:             $output .= $typeselectform;
16500:         } else {
16501:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16502:                       .$typeselectform
16503:                       .&Apache::lonhtmlcommon::row_closure();
16504:         }
16505:     }
16506:     if ($instcodeform) {
16507:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16508:                   .$instcodeform
16509:                   .&Apache::lonhtmlcommon::row_closure();
16510:     }
16511:     if (exists($filter->{'ownerfilter'})) {
16512:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16513:                    '<table><tr><td>'.&mt('Username').'<br />'.
16514:                    '<input type="text" name="ownerfilter" size="20" value="'.
16515:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16516:                    $ownerdomselectform.'</td></tr></table>'.
16517:                    &Apache::lonhtmlcommon::row_closure();
16518:     }
16519:     if (exists($filter->{'personfilter'})) {
16520:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16521:                    '<table><tr><td>'.&mt('Username').'<br />'.
16522:                    '<input type="text" name="personfilter" size="20" value="'.
16523:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16524:                    $persondomselectform.'</td></tr></table>'.
16525:                    &Apache::lonhtmlcommon::row_closure();
16526:     }
16527:     if (exists($filter->{'coursefilter'})) {
16528:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16529:                   .'<input type="text" name="coursefilter" size="25" value="'
16530:                   .$list->{'coursefilter'}.'" />'
16531:                   .&Apache::lonhtmlcommon::row_closure();
16532:     }
16533:     if ($cloneableonlyform) {
16534:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16535:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16536:     }
16537:     if (exists($filter->{'descriptfilter'})) {
16538:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16539:                   .'<input type="text" name="descriptfilter" size="40" value="'
16540:                   .$list->{'descriptfilter'}.'" />'
16541:                   .&Apache::lonhtmlcommon::row_closure(1);
16542:     }
16543:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16544:                '<input type="hidden" name="updater" value="" />'."\n".
16545:                '<input type="submit" name="gosearch" value="'.
16546:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16547:     return $jscript.$clonewarning.$output;
16548: }
16549: 
16550: =pod
16551: 
16552: =item * &timebased_select_form()
16553: 
16554: Create markup for a dropdown list used to select a time-based
16555: filter e.g., Course Activity, Course Created, when searching for courses
16556: or communities
16557: 
16558: Inputs:
16559: 
16560: item - name of form element (sincefilter or createdfilter)
16561: 
16562: filter - anonymous hash of criteria and their values
16563: 
16564: Returns: HTML for a select box contained a blank, then six time selections,
16565:          with value set in incoming form variables currently selected.
16566: 
16567: Side Effects: None
16568: 
16569: =cut
16570: 
16571: sub timebased_select_form {
16572:     my ($item,$filter) = @_;
16573:     if (ref($filter) eq 'HASH') {
16574:         $filter->{$item} =~ s/[^\d-]//g;
16575:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16576:         return &select_form(
16577:                             $filter->{$item},
16578:                             $item,
16579:                             {      '-1' => '',
16580:                                 '86400' => &mt('today'),
16581:                                '604800' => &mt('last week'),
16582:                               '2592000' => &mt('last month'),
16583:                               '7776000' => &mt('last three months'),
16584:                              '15552000' => &mt('last six months'),
16585:                              '31104000' => &mt('last year'),
16586:                     'select_form_order' =>
16587:                            ['-1','86400','604800','2592000','7776000',
16588:                             '15552000','31104000']});
16589:     }
16590: }
16591: 
16592: =pod
16593: 
16594: =item * &js_changer()
16595: 
16596: Create script tag containing Javascript used to submit course search form
16597: when course type or domain is changed, and also to hide 'Searching ...' on
16598: page load completion for page showing search result.
16599: 
16600: Inputs: None
16601: 
16602: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16603: 
16604: Side Effects: None
16605: 
16606: =cut
16607: 
16608: sub js_changer {
16609:     return <<ENDJS;
16610: <script type="text/javascript">
16611: // <![CDATA[
16612: function updateFilters(caller) {
16613:     if (typeof(caller) != "undefined") {
16614:         document.filterpicker.updater.value = caller.name;
16615:     }
16616:     document.filterpicker.submit();
16617: }
16618: 
16619: function hideSearching() {
16620:     if (document.getElementById('searching')) {
16621:         document.getElementById('searching').style.display = 'none';
16622:     }
16623:     return;
16624: }
16625: 
16626: // ]]>
16627: </script>
16628: 
16629: ENDJS
16630: }
16631: 
16632: =pod
16633: 
16634: =item * &search_courses()
16635: 
16636: Process selected filters form course search form and pass to lonnet::courseiddump
16637: to retrieve a hash for which keys are courseIDs which match the selected filters.
16638: 
16639: Inputs:
16640: 
16641: dom - domain being searched
16642: 
16643: type - course type ('Course' or 'Community' or '.' if any).
16644: 
16645: filter - anonymous hash of criteria and their values
16646: 
16647: numtitles - for institutional codes - number of categories
16648: 
16649: cloneruname - optional username of new course owner
16650: 
16651: clonerudom - optional domain of new course owner
16652: 
16653: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16654:             (used when DC is using course creation form)
16655: 
16656: codetitles - reference to array of titles of components in institutional codes (official courses).
16657: 
16658: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16659:            (and so can clone automatically)
16660: 
16661: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16662: 
16663: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16664:               courses to clone
16665: 
16666: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16667: 
16668: 
16669: Side Effects: None
16670: 
16671: =cut
16672: 
16673: 
16674: sub search_courses {
16675:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16676:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16677:     my (%courses,%showcourses,$cloner);
16678:     if (($filter->{'ownerfilter'} ne '') ||
16679:         ($filter->{'ownerdomfilter'} ne '')) {
16680:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16681:                                        $filter->{'ownerdomfilter'};
16682:     }
16683:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16684:         if (!$filter->{$item}) {
16685:             $filter->{$item}='.';
16686:         }
16687:     }
16688:     my $now = time;
16689:     my $timefilter =
16690:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16691:     my ($createdbefore,$createdafter);
16692:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16693:         $createdbefore = $now;
16694:         $createdafter = $now-$filter->{'createdfilter'};
16695:     }
16696:     my ($instcodefilter,$regexpok);
16697:     if ($numtitles) {
16698:         if ($env{'form.official'} eq 'on') {
16699:             $instcodefilter =
16700:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16701:             $regexpok = 1;
16702:         } elsif ($env{'form.official'} eq 'off') {
16703:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16704:             unless ($instcodefilter eq '') {
16705:                 $regexpok = -1;
16706:             }
16707:         }
16708:     } else {
16709:         $instcodefilter = $filter->{'instcodefilter'};
16710:     }
16711:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16712:     if ($type eq '') { $type = '.'; }
16713: 
16714:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16715:         $cloner = $cloneruname.':'.$clonerudom;
16716:     }
16717:     %courses = &Apache::lonnet::courseiddump($dom,
16718:                                              $filter->{'descriptfilter'},
16719:                                              $timefilter,
16720:                                              $instcodefilter,
16721:                                              $filter->{'combownerfilter'},
16722:                                              $filter->{'coursefilter'},
16723:                                              undef,undef,$type,$regexpok,undef,undef,
16724:                                              undef,undef,$cloner,$cc_clone,
16725:                                              $filter->{'cloneableonly'},
16726:                                              $createdbefore,$createdafter,undef,
16727:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16728:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16729:         my $ccrole;
16730:         if ($type eq 'Community') {
16731:             $ccrole = 'co';
16732:         } else {
16733:             $ccrole = 'cc';
16734:         }
16735:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16736:                                                      $filter->{'persondomfilter'},
16737:                                                      'userroles',undef,
16738:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16739:                                                      $dom);
16740:         foreach my $role (keys(%rolehash)) {
16741:             my ($cnum,$cdom,$courserole) = split(':',$role);
16742:             my $cid = $cdom.'_'.$cnum;
16743:             if (exists($courses{$cid})) {
16744:                 if (ref($courses{$cid}) eq 'HASH') {
16745:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16746:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16747:                             push(@{$courses{$cid}{roles}},$courserole);
16748:                         }
16749:                     } else {
16750:                         $courses{$cid}{roles} = [$courserole];
16751:                     }
16752:                     $showcourses{$cid} = $courses{$cid};
16753:                 }
16754:             }
16755:         }
16756:         %courses = %showcourses;
16757:     }
16758:     return %courses;
16759: }
16760: 
16761: =pod
16762: 
16763: =back
16764: 
16765: =head1 Routines for version requirements for current course.
16766: 
16767: =over 4
16768: 
16769: =item * &check_release_required()
16770: 
16771: Compares required LON-CAPA version with version on server, and
16772: if required version is newer looks for a server with the required version.
16773: 
16774: Looks first at servers in user's owen domain; if none suitable, looks at
16775: servers in course's domain are permitted to host sessions for user's domain.
16776: 
16777: Inputs:
16778: 
16779: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16780: 
16781: $courseid - Course ID of current course
16782: 
16783: $rolecode - User's current role in course (for switchserver query string).
16784: 
16785: $required - LON-CAPA version needed by course (format: Major.Minor).
16786: 
16787: 
16788: Returns:
16789: 
16790: $switchserver - query string tp append to /adm/switchserver call (if
16791:                 current server's LON-CAPA version is too old.
16792: 
16793: $warning - Message is displayed if no suitable server could be found.
16794: 
16795: =cut
16796: 
16797: sub check_release_required {
16798:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16799:     my ($switchserver,$warning);
16800:     if ($required ne '') {
16801:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16802:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16803:         if ($reqdmajor ne '' && $reqdminor ne '') {
16804:             my $otherserver;
16805:             if (($major eq '' && $minor eq '') ||
16806:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16807:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16808:                 my $switchlcrev =
16809:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16810:                                                            $userdomserver);
16811:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16812:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16813:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16814:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16815:                     if ($cdom ne $env{'user.domain'}) {
16816:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16817:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16818:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16819:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16820:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16821:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16822:                         my $canhost =
16823:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16824:                                                               $coursedomserver,
16825:                                                               $remoterev,
16826:                                                               $udomdefaults{'remotesessions'},
16827:                                                               $defdomdefaults{'hostedsessions'});
16828: 
16829:                         if ($canhost) {
16830:                             $otherserver = $coursedomserver;
16831:                         } else {
16832:                             $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
16833:                         }
16834:                     } else {
16835:                         $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
16836:                     }
16837:                 } else {
16838:                     $otherserver = $userdomserver;
16839:                 }
16840:             }
16841:             if ($otherserver ne '') {
16842:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16843:             }
16844:         }
16845:     }
16846:     return ($switchserver,$warning);
16847: }
16848: 
16849: =pod
16850: 
16851: =item * &check_release_result()
16852: 
16853: Inputs:
16854: 
16855: $switchwarning - Warning message if no suitable server found to host session.
16856: 
16857: $switchserver - query string to append to /adm/switchserver containing lonHostID
16858:                 and current role.
16859: 
16860: Returns: HTML to display with information about requirement to switch server.
16861:          Either displaying warning with link to Roles/Courses screen or
16862:          display link to switchserver.
16863: 
16864: =cut
16865: 
16866: sub check_release_result {
16867:     my ($switchwarning,$switchserver) = @_;
16868:     my $output = &start_page('Selected course unavailable on this server').
16869:                  '<p class="LC_warning">';
16870:     if ($switchwarning) {
16871:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16872:         if (&show_course()) {
16873:             $output .= &mt('Display courses');
16874:         } else {
16875:             $output .= &mt('Display roles');
16876:         }
16877:         $output .= '</a>';
16878:     } elsif ($switchserver) {
16879:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16880:                    '<br />'.
16881:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16882:                    &mt('Switch Server').
16883:                    '</a>';
16884:     }
16885:     $output .= '</p>'.&end_page();
16886:     return $output;
16887: }
16888: 
16889: =pod
16890: 
16891: =item * &needs_coursereinit()
16892: 
16893: Determine if course contents stored for user's session needs to be
16894: refreshed, because content has changed since "Big Hash" last tied.
16895: 
16896: Check for change is made if time last checked is more than 10 minutes ago
16897: (by default).
16898: 
16899: Inputs:
16900: 
16901: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16902: 
16903: $interval (optional) - Time which may elapse (in s) between last check for content
16904:                        change in current course. (default: 600 s).
16905: 
16906: Returns: an array; first element is:
16907: 
16908: =over 4
16909: 
16910: 'switch' - if content updates mean user's session
16911:            needs to be switched to a server running a newer LON-CAPA version
16912: 
16913: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16914:            on current server hosting user's session
16915: 
16916: ''       - if no action required.
16917: 
16918: =back
16919: 
16920: If first item element is 'switch':
16921: 
16922: second item is $switchwarning - Warning message if no suitable server found to host session.
16923: 
16924: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16925:                               and current role.
16926: 
16927: otherwise: no other elements returned.
16928: 
16929: =back
16930: 
16931: =cut
16932: 
16933: sub needs_coursereinit {
16934:     my ($loncaparev,$interval) = @_;
16935:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16936:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16937:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16938:     my $now = time;
16939:     if ($interval eq '') {
16940:         $interval = 600;
16941:     }
16942:     if (($now-$env{'request.course.timechecked'})>$interval) {
16943:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16944:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16945:         if ($lastchange > $env{'request.course.tied'}) {
16946:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16947:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16948:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16949:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16950:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16951:                                              $curr_reqd_hash{'internal.releaserequired'}});
16952:                     my ($switchserver,$switchwarning) =
16953:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16954:                                                 $curr_reqd_hash{'internal.releaserequired'});
16955:                     if ($switchwarning ne '' || $switchserver ne '') {
16956:                         return ('switch',$switchwarning,$switchserver);
16957:                     }
16958:                 }
16959:             }
16960:             return ('update');
16961:         }
16962:     }
16963:     return ();
16964: }
16965: 
16966: sub update_content_constraints {
16967:     my ($cdom,$cnum,$chome,$cid) = @_;
16968:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16969:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16970:     my %checkresponsetypes;
16971:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16972:         my ($item,$name,$value) = split(/:/,$key);
16973:         if ($item eq 'resourcetag') {
16974:             if ($name eq 'responsetype') {
16975:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16976:             }
16977:         }
16978:     }
16979:     my $navmap = Apache::lonnavmaps::navmap->new();
16980:     if (defined($navmap)) {
16981:         my %allresponses;
16982:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16983:             my %responses = $res->responseTypes();
16984:             foreach my $key (keys(%responses)) {
16985:                 next unless(exists($checkresponsetypes{$key}));
16986:                 $allresponses{$key} += $responses{$key};
16987:             }
16988:         }
16989:         foreach my $key (keys(%allresponses)) {
16990:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16991:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16992:                 ($reqdmajor,$reqdminor) = ($major,$minor);
16993:             }
16994:         }
16995:         undef($navmap);
16996:     }
16997:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16998:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16999:     }
17000:     return;
17001: }
17002: 
17003: sub allmaps_incourse {
17004:     my ($cdom,$cnum,$chome,$cid) = @_;
17005:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17006:         $cid = $env{'request.course.id'};
17007:         $cdom = $env{'course.'.$cid.'.domain'};
17008:         $cnum = $env{'course.'.$cid.'.num'};
17009:         $chome = $env{'course.'.$cid.'.home'};
17010:     }
17011:     my %allmaps = ();
17012:     my $lastchange =
17013:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17014:     if ($lastchange > $env{'request.course.tied'}) {
17015:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17016:         unless ($ferr) {
17017:             &update_content_constraints($cdom,$cnum,$chome,$cid);
17018:         }
17019:     }
17020:     my $navmap = Apache::lonnavmaps::navmap->new();
17021:     if (defined($navmap)) {
17022:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17023:             $allmaps{$res->src()} = 1;
17024:         }
17025:     }
17026:     return \%allmaps;
17027: }
17028: 
17029: sub parse_supplemental_title {
17030:     my ($title) = @_;
17031: 
17032:     my ($foldertitle,$renametitle);
17033:     if ($title =~ /&amp;&amp;&amp;/) {
17034:         $title = &HTML::Entites::decode($title);
17035:     }
17036:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17037:         $renametitle=$4;
17038:         my ($time,$uname,$udom) = ($1,$2,$3);
17039:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17040:         my $name =  &plainname($uname,$udom);
17041:         $name = &HTML::Entities::encode($name,'"<>&\'');
17042:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17043:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17044:             $name.': <br />'.$foldertitle;
17045:     }
17046:     if (wantarray) {
17047:         return ($title,$foldertitle,$renametitle);
17048:     }
17049:     return $title;
17050: }
17051: 
17052: sub recurse_supplemental {
17053:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
17054:     if ($suppmap) {
17055:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17056:         if ($fatal) {
17057:             $errors ++;
17058:         } else {
17059:             if ($#LONCAPA::map::resources > 0) {
17060:                 foreach my $res (@LONCAPA::map::resources) {
17061:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17062:                     if (($src ne '') && ($status eq 'res')) {
17063:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17064:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
17065:                         } else {
17066:                             $numfiles ++;
17067:                         }
17068:                     }
17069:                 }
17070:             }
17071:         }
17072:     }
17073:     return ($numfiles,$errors);
17074: }
17075: 
17076: sub symb_to_docspath {
17077:     my ($symb,$navmapref) = @_;
17078:     return unless ($symb && ref($navmapref));
17079:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17080:     if ($resurl=~/\.(sequence|page)$/) {
17081:         $mapurl=$resurl;
17082:     } elsif ($resurl eq 'adm/navmaps') {
17083:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17084:     }
17085:     my $mapresobj;
17086:     unless (ref($$navmapref)) {
17087:         $$navmapref = Apache::lonnavmaps::navmap->new();
17088:     }
17089:     if (ref($$navmapref)) {
17090:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17091:     }
17092:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17093:     my $type=$2;
17094:     my $path;
17095:     if (ref($mapresobj)) {
17096:         my $pcslist = $mapresobj->map_hierarchy();
17097:         if ($pcslist ne '') {
17098:             foreach my $pc (split(/,/,$pcslist)) {
17099:                 next if ($pc <= 1);
17100:                 my $res = $$navmapref->getByMapPc($pc);
17101:                 if (ref($res)) {
17102:                     my $thisurl = $res->src();
17103:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17104:                     my $thistitle = $res->title();
17105:                     $path .= '&'.
17106:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17107:                              &escape($thistitle).
17108:                              ':'.$res->randompick().
17109:                              ':'.$res->randomout().
17110:                              ':'.$res->encrypted().
17111:                              ':'.$res->randomorder().
17112:                              ':'.$res->is_page();
17113:                 }
17114:             }
17115:         }
17116:         $path =~ s/^\&//;
17117:         my $maptitle = $mapresobj->title();
17118:         if ($mapurl eq 'default') {
17119:             $maptitle = 'Main Content';
17120:         }
17121:         $path .= (($path ne '')? '&' : '').
17122:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17123:                  &escape($maptitle).
17124:                  ':'.$mapresobj->randompick().
17125:                  ':'.$mapresobj->randomout().
17126:                  ':'.$mapresobj->encrypted().
17127:                  ':'.$mapresobj->randomorder().
17128:                  ':'.$mapresobj->is_page();
17129:     } else {
17130:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17131:         my $ispage = (($type eq 'page')? 1 : '');
17132:         if ($mapurl eq 'default') {
17133:             $maptitle = 'Main Content';
17134:         }
17135:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17136:                 &escape($maptitle).':::::'.$ispage;
17137:     }
17138:     unless ($mapurl eq 'default') {
17139:         $path = 'default&'.
17140:                 &escape('Main Content').
17141:                 ':::::&'.$path;
17142:     }
17143:     return $path;
17144: }
17145: 
17146: sub captcha_display {
17147:     my ($context,$lonhost,$defdom) = @_;
17148:     my ($output,$error);
17149:     my ($captcha,$pubkey,$privkey,$version) =
17150:         &get_captcha_config($context,$lonhost,$defdom);
17151:     if ($captcha eq 'original') {
17152:         $output = &create_captcha();
17153:         unless ($output) {
17154:             $error = 'captcha';
17155:         }
17156:     } elsif ($captcha eq 'recaptcha') {
17157:         $output = &create_recaptcha($pubkey,$version);
17158:         unless ($output) {
17159:             $error = 'recaptcha';
17160:         }
17161:     }
17162:     return ($output,$error,$captcha,$version);
17163: }
17164: 
17165: sub captcha_response {
17166:     my ($context,$lonhost,$defdom) = @_;
17167:     my ($captcha_chk,$captcha_error);
17168:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
17169:     if ($captcha eq 'original') {
17170:         ($captcha_chk,$captcha_error) = &check_captcha();
17171:     } elsif ($captcha eq 'recaptcha') {
17172:         $captcha_chk = &check_recaptcha($privkey,$version);
17173:     } else {
17174:         $captcha_chk = 1;
17175:     }
17176:     return ($captcha_chk,$captcha_error);
17177: }
17178: 
17179: sub get_captcha_config {
17180:     my ($context,$lonhost,$dom_in_effect) = @_;
17181:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17182:     my $hostname = &Apache::lonnet::hostname($lonhost);
17183:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17184:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17185:     if ($context eq 'usercreation') {
17186:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17187:         if (ref($domconfig{$context}) eq 'HASH') {
17188:             $hashtocheck = $domconfig{$context}{'cancreate'};
17189:             if (ref($hashtocheck) eq 'HASH') {
17190:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17191:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17192:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17193:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17194:                     }
17195:                     if ($privkey && $pubkey) {
17196:                         $captcha = 'recaptcha';
17197:                         $version = $hashtocheck->{'recaptchaversion'};
17198:                         if ($version ne '2') {
17199:                             $version = 1;
17200:                         }
17201:                     } else {
17202:                         $captcha = 'original';
17203:                     }
17204:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17205:                     $captcha = 'original';
17206:                 }
17207:             }
17208:         } else {
17209:             $captcha = 'captcha';
17210:         }
17211:     } elsif ($context eq 'login') {
17212:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17213:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17214:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17215:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17216:             if ($privkey && $pubkey) {
17217:                 $captcha = 'recaptcha';
17218:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17219:                 if ($version ne '2') {
17220:                     $version = 1;
17221:                 }
17222:             } else {
17223:                 $captcha = 'original';
17224:             }
17225:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17226:             $captcha = 'original';
17227:         }
17228:     } elsif ($context eq 'passwords') {
17229:         if ($dom_in_effect) {
17230:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
17231:             if ($passwdconf{'captcha'} eq 'recaptcha') {
17232:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
17233:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
17234:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
17235:                 }
17236:                 if ($privkey && $pubkey) {
17237:                     $captcha = 'recaptcha';
17238:                     $version = $passwdconf{'recaptchaversion'};
17239:                     if ($version ne '2') {
17240:                         $version = 1;
17241:                     }
17242:                 } else {
17243:                     $captcha = 'original';
17244:                 }
17245:             } elsif ($passwdconf{'captcha'} ne 'notused') {
17246:                 $captcha = 'original';
17247:             }
17248:         }
17249:     }
17250:     return ($captcha,$pubkey,$privkey,$version);
17251: }
17252: 
17253: sub create_captcha {
17254:     my %captcha_params = &captcha_settings();
17255:     my ($output,$maxtries,$tries) = ('',10,0);
17256:     while ($tries < $maxtries) {
17257:         $tries ++;
17258:         my $captcha = Authen::Captcha->new (
17259:                                            output_folder => $captcha_params{'output_dir'},
17260:                                            data_folder   => $captcha_params{'db_dir'},
17261:                                           );
17262:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17263: 
17264:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17265:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17266:                       '<span class="LC_nobreak">'.
17267:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17268:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17269:                       '</span><br />'.
17270:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17271:             last;
17272:         }
17273:     }
17274:     if ($output eq '') {
17275:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
17276:     }
17277:     return $output;
17278: }
17279: 
17280: sub captcha_settings {
17281:     my %captcha_params = (
17282:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17283:                            www_output_dir => "/captchaspool",
17284:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17285:                            numchars       => '5',
17286:                          );
17287:     return %captcha_params;
17288: }
17289: 
17290: sub check_captcha {
17291:     my ($captcha_chk,$captcha_error);
17292:     my $code = $env{'form.code'};
17293:     my $md5sum = $env{'form.crypt'};
17294:     my %captcha_params = &captcha_settings();
17295:     my $captcha = Authen::Captcha->new(
17296:                       output_folder => $captcha_params{'output_dir'},
17297:                       data_folder   => $captcha_params{'db_dir'},
17298:                   );
17299:     $captcha_chk = $captcha->check_code($code,$md5sum);
17300:     my %captcha_hash = (
17301:                         0       => 'Code not checked (file error)',
17302:                        -1      => 'Failed: code expired',
17303:                        -2      => 'Failed: invalid code (not in database)',
17304:                        -3      => 'Failed: invalid code (code does not match crypt)',
17305:     );
17306:     if ($captcha_chk != 1) {
17307:         $captcha_error = $captcha_hash{$captcha_chk}
17308:     }
17309:     return ($captcha_chk,$captcha_error);
17310: }
17311: 
17312: sub create_recaptcha {
17313:     my ($pubkey,$version) = @_;
17314:     if ($version >= 2) {
17315:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
17316:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
17317:     } else {
17318:         my $use_ssl;
17319:         if ($ENV{'SERVER_PORT'} == 443) {
17320:             $use_ssl = 1;
17321:         }
17322:         my $captcha = Captcha::reCAPTCHA->new;
17323:         return $captcha->get_options_setter({theme => 'white'})."\n".
17324:                $captcha->get_html($pubkey,undef,$use_ssl).
17325:                &mt('If the text is hard to read, [_1] will replace them.',
17326:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17327:                '<br /><br />';
17328:      }
17329: }
17330: 
17331: sub check_recaptcha {
17332:     my ($privkey,$version) = @_;
17333:     my $captcha_chk;
17334:     my $ip = &Apache::lonnet::get_requestor_ip(); 
17335:     if ($version >= 2) {
17336:         my $ua = LWP::UserAgent->new;
17337:         $ua->timeout(10);
17338:         my %info = (
17339:                      secret   => $privkey,
17340:                      response => $env{'form.g-recaptcha-response'},
17341:                      remoteip => $ip,
17342:                    );
17343:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17344:         if ($response->is_success)  {
17345:             my $data = JSON::DWIW->from_json($response->decoded_content);
17346:             if (ref($data) eq 'HASH') {
17347:                 if ($data->{'success'}) {
17348:                     $captcha_chk = 1;
17349:                 }
17350:             }
17351:         }
17352:     } else {
17353:         my $captcha = Captcha::reCAPTCHA->new;
17354:         my $captcha_result =
17355:             $captcha->check_answer(
17356:                                     $privkey,
17357:                                     $ip,
17358:                                     $env{'form.recaptcha_challenge_field'},
17359:                                     $env{'form.recaptcha_response_field'},
17360:                                   );
17361:         if ($captcha_result->{is_valid}) {
17362:             $captcha_chk = 1;
17363:         }
17364:     }
17365:     return $captcha_chk;
17366: }
17367: 
17368: sub emailusername_info {
17369:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17370:     my %titles = &Apache::lonlocal::texthash (
17371:                      lastname      => 'Last Name',
17372:                      firstname     => 'First Name',
17373:                      institution   => 'School/college/university',
17374:                      location      => "School's city, state/province, country",
17375:                      web           => "School's web address",
17376:                      officialemail => 'E-mail address at institution (if different)',
17377:                      id            => 'Student/Employee ID',
17378:                  );
17379:     return (\@fields,\%titles);
17380: }
17381: 
17382: sub cleanup_html {
17383:     my ($incoming) = @_;
17384:     my $outgoing;
17385:     if ($incoming ne '') {
17386:         $outgoing = $incoming;
17387:         $outgoing =~ s/;/&#059;/g;
17388:         $outgoing =~ s/\#/&#035;/g;
17389:         $outgoing =~ s/\&/&#038;/g;
17390:         $outgoing =~ s/</&#060;/g;
17391:         $outgoing =~ s/>/&#062;/g;
17392:         $outgoing =~ s/\(/&#040/g;
17393:         $outgoing =~ s/\)/&#041;/g;
17394:         $outgoing =~ s/"/&#034;/g;
17395:         $outgoing =~ s/'/&#039;/g;
17396:         $outgoing =~ s/\$/&#036;/g;
17397:         $outgoing =~ s{/}{&#047;}g;
17398:         $outgoing =~ s/=/&#061;/g;
17399:         $outgoing =~ s/\\/&#092;/g
17400:     }
17401:     return $outgoing;
17402: }
17403: 
17404: # Checks for critical messages and returns a redirect url if one exists.
17405: # $interval indicates how often to check for messages.
17406: sub critical_redirect {
17407:     my ($interval) = @_;
17408:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
17409:         return ();
17410:     }
17411:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
17412:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
17413:                                         $env{'user.name'});
17414:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17415:         my $redirecturl;
17416:         if ($what[0]) {
17417:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
17418:                 $redirecturl='/adm/email?critical=display';
17419:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
17420:                 return (1, $url);
17421:             }
17422:         }
17423:     }
17424:     return ();
17425: }
17426: 
17427: # Use:
17428: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17429: #
17430: ##################################################
17431: #          password associated functions         #
17432: ##################################################
17433: sub des_keys {
17434:     # Make a new key for DES encryption.
17435:     # Each key has two parts which are returned separately.
17436:     # Please note:  Each key must be passed through the &hex function
17437:     # before it is output to the web browser.  The hex versions cannot
17438:     # be used to decrypt.
17439:     my @hexstr=('0','1','2','3','4','5','6','7',
17440:                 '8','9','a','b','c','d','e','f');
17441:     my $lkey='';
17442:     for (0..7) {
17443:         $lkey.=$hexstr[rand(15)];
17444:     }
17445:     my $ukey='';
17446:     for (0..7) {
17447:         $ukey.=$hexstr[rand(15)];
17448:     }
17449:     return ($lkey,$ukey);
17450: }
17451: 
17452: sub des_decrypt {
17453:     my ($key,$cyphertext) = @_;
17454:     my $keybin=pack("H16",$key);
17455:     my $cypher;
17456:     if ($Crypt::DES::VERSION>=2.03) {
17457:         $cypher=new Crypt::DES $keybin;
17458:     } else {
17459:         $cypher=new DES $keybin;
17460:     }
17461:     my $plaintext='';
17462:     my $cypherlength = length($cyphertext);
17463:     my $numchunks = int($cypherlength/32);
17464:     for (my $j=0; $j<$numchunks; $j++) {
17465:         my $start = $j*32;
17466:         my $cypherblock = substr($cyphertext,$start,32);
17467:         my $chunk =
17468:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17469:         $chunk .=
17470:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17471:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17472:         $plaintext .= $chunk;
17473:     }
17474:     return $plaintext;
17475: }
17476: 
17477: sub is_nonframeable {
17478:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
17479:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
17480:     return if (($remprotocol eq '') || ($remhost eq ''));
17481: 
17482:     $remprotocol = lc($remprotocol);
17483:     $remhost = lc($remhost);
17484:     my $remport = 80;
17485:     if ($remprotocol eq 'https') {
17486:         $remport = 443;
17487:     }
17488:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
17489:     if ($cached) {
17490:         unless ($nocache) {
17491:             if ($result) {
17492:                 return 1;
17493:             } else {
17494:                 return 0;
17495:             }
17496:         }
17497:     }
17498:     my $uselink;
17499:     my $request = new HTTP::Request('HEAD',$url);
17500:     my $ua = LWP::UserAgent->new;
17501:     $ua->timeout(5);
17502:     my $response=$ua->request($request);
17503:     if ($response->is_success()) {
17504:         my $secpolicy = lc($response->header('content-security-policy'));
17505:         my $xframeop = lc($response->header('x-frame-options'));
17506:         $secpolicy =~ s/^\s+|\s+$//g;
17507:         $xframeop =~ s/^\s+|\s+$//g;
17508:         if (($secpolicy ne '') || ($xframeop ne '')) {
17509:             my $remotehost = $remprotocol.'://'.$remhost;
17510:             my ($origin,$protocol,$port);
17511:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
17512:                 $port = $ENV{'SERVER_PORT'};
17513:             } else {
17514:                 $port = 80;
17515:             }
17516:             if ($absolute eq '') {
17517:                 $protocol = 'http:';
17518:                 if ($port == 443) {
17519:                     $protocol = 'https:';
17520:                 }
17521:                 $origin = $protocol.'//'.lc($hostname);
17522:             } else {
17523:                 $origin = lc($absolute);
17524:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
17525:             }
17526:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
17527:                 my $framepolicy = $1;
17528:                 $framepolicy =~ s/^\s+|\s+$//g;
17529:                 my @policies = split(/\s+/,$framepolicy);
17530:                 if (@policies) {
17531:                     if (grep(/^\Q'none'\E$/,@policies)) {
17532:                         $uselink = 1;
17533:                     } else {
17534:                         $uselink = 1;
17535:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
17536:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
17537:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
17538:                             undef($uselink);
17539:                         }
17540:                         if ($uselink) {
17541:                             if (grep(/^\Q'self'\E$/,@policies)) {
17542:                                 if (($origin ne '') && ($remotehost eq $origin)) {
17543:                                     undef($uselink);
17544:                                 }
17545:                             }
17546:                         }
17547:                         if ($uselink) {
17548:                             my @possok;
17549:                             if ($ip ne '') {
17550:                                 push(@possok,$ip);
17551:                             }
17552:                             my $hoststr = '';
17553:                             foreach my $part (reverse(split(/\./,$hostname))) {
17554:                                 if ($hoststr eq '') {
17555:                                     $hoststr = $part;
17556:                                 } else {
17557:                                     $hoststr = "$part.$hoststr";
17558:                                 }
17559:                                 if ($hoststr eq $hostname) {
17560:                                     push(@possok,$hostname);
17561:                                 } else {
17562:                                     push(@possok,"*.$hoststr");
17563:                                 }
17564:                             }
17565:                             if (@possok) {
17566:                                 foreach my $poss (@possok) {
17567:                                     last if (!$uselink);
17568:                                     foreach my $policy (@policies) {
17569:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
17570:                                             undef($uselink);
17571:                                             last;
17572:                                         }
17573:                                     }
17574:                                 }
17575:                             }
17576:                         }
17577:                     }
17578:                 }
17579:             } elsif ($xframeop ne '') {
17580:                 $uselink = 1;
17581:                 my @policies = split(/\s*,\s*/,$xframeop);
17582:                 if (@policies) {
17583:                     unless (grep(/^deny$/,@policies)) {
17584:                         if ($origin ne '') {
17585:                             if (grep(/^sameorigin$/,@policies)) {
17586:                                 if ($remotehost eq $origin) {
17587:                                     undef($uselink);
17588:                                 }
17589:                             }
17590:                             if ($uselink) {
17591:                                 foreach my $policy (@policies) {
17592:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
17593:                                         my $allowfrom = $1;
17594:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
17595:                                             undef($uselink);
17596:                                             last;
17597:                                         }
17598:                                     }
17599:                                 }
17600:                             }
17601:                         }
17602:                     }
17603:                 }
17604:             }
17605:         }
17606:     }
17607:     if ($nocache) {
17608:         if ($cached) {
17609:             my $devalidate;
17610:             if ($uselink && !$result) {
17611:                 $devalidate = 1;
17612:             } elsif (!$uselink && $result) {
17613:                 $devalidate = 1;
17614:             }
17615:             if ($devalidate) {
17616:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
17617:             }
17618:         }
17619:     } else {
17620:         if ($uselink) {
17621:             $result = 1;
17622:         } else {
17623:             $result = 0;
17624:         }
17625:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
17626:     }
17627:     return $uselink;
17628: }
17629: 
17630: 1;
17631: __END__;
17632: 

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