File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1425: download - view: text, annotated - select for diffs
Sun Dec 31 23:03:40 2023 UTC (5 months, 4 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Add POD for two subroutines moved from lonwrapper.pm in rev. 1.1420.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1425 2023/12/31 23:03:40 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # 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::lonnavmaps();
   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 LONCAPA::ltiutils;
   75: use LONCAPA::LWPReq;
   76: use LONCAPA::map();
   77: use HTTP::Request;
   78: use DateTime::TimeZone;
   79: use DateTime::Locale;
   80: use Encode();
   81: use Text::Aspell;
   82: use Authen::Captcha;
   83: use Captcha::reCAPTCHA;
   84: use JSON::DWIW;
   85: use Crypt::DES;
   86: use DynaLoader; # for Crypt::DES version
   87: use MIME::Lite;
   88: use MIME::Types;
   89: use File::Copy();
   90: use File::Path();
   91: use String::CRC32();
   92: use Short::URL();
   93: 
   94: # ---------------------------------------------- Designs
   95: use vars qw(%defaultdesign);
   96: 
   97: my $readit;
   98: 
   99: 
  100: ##
  101: ## Global Variables
  102: ##
  103: 
  104: 
  105: # ----------------------------------------------- SSI with retries:
  106: #
  107: 
  108: =pod
  109: 
  110: =head1 Server Side include with retries:
  111: 
  112: =over 4
  113: 
  114: =item * &ssi_with_retries(resource,retries form)
  115: 
  116: Performs an ssi with some number of retries.  Retries continue either
  117: until the result is ok or until the retry count supplied by the
  118: caller is exhausted.  
  119: 
  120: Inputs:
  121: 
  122: =over 4
  123: 
  124: resource   - Identifies the resource to insert.
  125: 
  126: retries    - Count of the number of retries allowed.
  127: 
  128: form       - Hash that identifies the rendering options.
  129: 
  130: =back
  131: 
  132: Returns:
  133: 
  134: =over 4
  135: 
  136: content    - The content of the response.  If retries were exhausted this is empty.
  137: 
  138: response   - The response from the last attempt (which may or may not have been successful.
  139: 
  140: =back
  141: 
  142: =back
  143: 
  144: =cut
  145: 
  146: sub ssi_with_retries {
  147:     my ($resource, $retries, %form) = @_;
  148: 
  149: 
  150:     my $ok = 0;			# True if we got a good response.
  151:     my $content;
  152:     my $response;
  153: 
  154:     # Try to get the ssi done. within the retries count:
  155: 
  156:     do {
  157: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  158: 	$ok      = $response->is_success;
  159:         if (!$ok) {
  160:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  161:         }
  162: 	$retries--;
  163:     } while (!$ok && ($retries > 0));
  164: 
  165:     if (!$ok) {
  166: 	$content = '';		# On error return an empty content.
  167:     }
  168:     return ($content, $response);
  169: 
  170: }
  171: 
  172: 
  173: 
  174: # ----------------------------------------------- Filetypes/Languages/Copyright
  175: my %language;
  176: my %supported_language;
  177: my %supported_codes;
  178: my %latex_language;		# For choosing hyphenation in <transl..>
  179: my %latex_language_bykey;	# for choosing hyphenation from metadata
  180: my %cprtag;
  181: my %scprtag;
  182: my %fe; my %fd; my %fm;
  183: my %category_extensions;
  184: 
  185: # ---------------------------------------------- Thesaurus variables
  186: #
  187: # %Keywords:
  188: #      A hash used by &keyword to determine if a word is considered a keyword.
  189: # $thesaurus_db_file 
  190: #      Scalar containing the full path to the thesaurus database.
  191: 
  192: my %Keywords;
  193: my $thesaurus_db_file;
  194: 
  195: #
  196: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  197: # thesaurus.tab, and filecategories.tab.
  198: #
  199: BEGIN {
  200:     # Variable initialization
  201:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  202:     #
  203:     unless ($readit) {
  204: # ------------------------------------------------------------------- languages
  205:     {
  206:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  207:                                    '/language.tab';
  208:         if ( open(my $fh,'<',$langtabfile) ) {
  209:             while (my $line = <$fh>) {
  210:                 next if ($line=~/^\#/);
  211:                 chomp($line);
  212:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  213:                 $language{$key}=$val.' - '.$enc;
  214:                 if ($sup) {
  215:                     $supported_language{$key}=$sup;
  216: 		    $supported_codes{$key}   = $code;
  217:                 }
  218: 		if ($latex) {
  219: 		    $latex_language_bykey{$key} = $latex;
  220: 		    $latex_language{$code} = $latex;
  221: 		}
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: # ------------------------------------------------------------------ copyrights
  227:     {
  228:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  229:                                   '/copyright.tab';
  230:         if ( open (my $fh,'<',$copyrightfile) ) {
  231:             while (my $line = <$fh>) {
  232:                 next if ($line=~/^\#/);
  233:                 chomp($line);
  234:                 my ($key,$val)=(split(/\s+/,$line,2));
  235:                 $cprtag{$key}=$val;
  236:             }
  237:             close($fh);
  238:         }
  239:     }
  240: # ----------------------------------------------------------- source copyrights
  241:     {
  242:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  243:                                   '/source_copyright.tab';
  244:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  245:             while (my $line = <$fh>) {
  246:                 next if ($line =~ /^\#/);
  247:                 chomp($line);
  248:                 my ($key,$val)=(split(/\s+/,$line,2));
  249:                 $scprtag{$key}=$val;
  250:             }
  251:             close($fh);
  252:         }
  253:     }
  254: 
  255: # -------------------------------------------------------------- default domain designs
  256:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  257:     my $designfile = $designdir.'/default.tab';
  258:     if ( open (my $fh,'<',$designfile) ) {
  259:         while (my $line = <$fh>) {
  260:             next if ($line =~ /^\#/);
  261:             chomp($line);
  262:             my ($key,$val)=(split(/\=/,$line));
  263:             if ($val) { $defaultdesign{$key}=$val; }
  264:         }
  265:         close($fh);
  266:     }
  267: 
  268: # ------------------------------------------------------------- file categories
  269:     {
  270:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  271:                                   '/filecategories.tab';
  272:         if ( open (my $fh,'<',$categoryfile) ) {
  273: 	    while (my $line = <$fh>) {
  274: 		next if ($line =~ /^\#/);
  275: 		chomp($line);
  276:                 my ($extension,$category)=(split(/\s+/,$line,2));
  277:                 push(@{$category_extensions{lc($category)}},$extension);
  278:             }
  279:             close($fh);
  280:         }
  281: 
  282:     }
  283: # ------------------------------------------------------------------ file types
  284:     {
  285:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  286:                '/filetypes.tab';
  287:         if ( open (my $fh,'<',$typesfile) ) {
  288:             while (my $line = <$fh>) {
  289: 		next if ($line =~ /^\#/);
  290: 		chomp($line);
  291:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  292:                 if ($descr ne '') {
  293:                     $fe{$ending}=lc($emb);
  294:                     $fd{$ending}=$descr;
  295:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  296:                 }
  297:             }
  298:             close($fh);
  299:         }
  300:     }
  301:     &Apache::lonnet::logthis(
  302:              "<span style='color:yellow;'>INFO: Read file types</span>");
  303:     $readit=1;
  304:     }  # end of unless($readit) 
  305:     
  306: }
  307: 
  308: ###############################################################
  309: ##           HTML and Javascript Helper Functions            ##
  310: ###############################################################
  311: 
  312: =pod 
  313: 
  314: =head1 HTML and Javascript Functions
  315: 
  316: =over 4
  317: 
  318: =item * &browser_and_searcher_javascript()
  319: 
  320: X<browsing, javascript>X<searching, javascript>Returns a string
  321: containing javascript with two functions, C<openbrowser> and
  322: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  323: tags.
  324: 
  325: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  326: 
  327: inputs: formname, elementname, only, omit
  328: 
  329: formname and elementname indicate the name of the html form and name of
  330: the element that the results of the browsing selection are to be placed in. 
  331: 
  332: Specifying 'only' will restrict the browser to displaying only files
  333: with the given extension.  Can be a comma separated list.
  334: 
  335: Specifying 'omit' will restrict the browser to NOT displaying files
  336: with the given extension.  Can be a comma separated list.
  337: 
  338: =item * &opensearcher(formname,elementname) [javascript]
  339: 
  340: Inputs: formname, elementname
  341: 
  342: formname and elementname specify the name of the html form and the name
  343: of the element the selection from the search results will be placed in.
  344: 
  345: =cut
  346: 
  347: sub browser_and_searcher_javascript {
  348:     my ($mode)=@_;
  349:     if (!defined($mode)) { $mode='edit'; }
  350:     my $resurl=&escape_single(&lastresurl());
  351:     return <<END;
  352: // <!-- BEGIN LON-CAPA Internal
  353:     var editbrowser = null;
  354:     function openbrowser(formname,elementname,only,omit,titleelement) {
  355:         var url = '$resurl/?';
  356:         if (editbrowser == null) {
  357:             url += 'launch=1&';
  358:         }
  359:         url += 'catalogmode=interactive&';
  360:         url += 'mode=$mode&';
  361:         url += 'inhibitmenu=yes&';
  362:         url += 'form=' + formname + '&';
  363:         if (only != null) {
  364:             url += 'only=' + only + '&';
  365:         } else {
  366:             url += 'only=&';
  367: 	}
  368:         if (omit != null) {
  369:             url += 'omit=' + omit + '&';
  370:         } else {
  371:             url += 'omit=&';
  372: 	}
  373:         if (titleelement != null) {
  374:             url += 'titleelement=' + titleelement + '&';
  375:         } else {
  376: 	    url += 'titleelement=&';
  377: 	}
  378:         url += 'element=' + elementname + '';
  379:         var title = 'Browser';
  380:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  381:         options += ',width=700,height=600';
  382:         editbrowser = open(url,title,options,'1');
  383:         editbrowser.focus();
  384:     }
  385:     var editsearcher;
  386:     function opensearcher(formname,elementname,titleelement) {
  387:         var url = '/adm/searchcat?';
  388:         if (editsearcher == null) {
  389:             url += 'launch=1&';
  390:         }
  391:         url += 'catalogmode=interactive&';
  392:         url += 'mode=$mode&';
  393:         url += 'form=' + formname + '&';
  394:         if (titleelement != null) {
  395:             url += 'titleelement=' + titleelement + '&';
  396:         } else {
  397: 	    url += 'titleelement=&';
  398: 	}
  399:         url += 'element=' + elementname + '';
  400:         var title = 'Search';
  401:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  402:         options += ',width=700,height=600';
  403:         editsearcher = open(url,title,options,'1');
  404:         editsearcher.focus();
  405:     }
  406: // END LON-CAPA Internal -->
  407: END
  408: }
  409: 
  410: sub lastresurl {
  411:     if ($env{'environment.lastresurl'}) {
  412: 	return $env{'environment.lastresurl'}
  413:     } else {
  414: 	return '/res';
  415:     }
  416: }
  417: 
  418: sub storeresurl {
  419:     my $resurl=&Apache::lonnet::clutter(shift);
  420:     unless ($resurl=~/^\/res/) { return 0; }
  421:     $resurl=~s/\/$//;
  422:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  423:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  424:     return 1;
  425: }
  426: 
  427: sub studentbrowser_javascript {
  428:    unless (
  429:             (($env{'request.course.id'}) && 
  430:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  431: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  432: 					  '/'.$env{'request.course.sec'})
  433: 	      ))
  434:          || ($env{'request.role'}=~/^(au|dc|su)/)
  435:           ) { return ''; }  
  436:    return (<<'ENDSTDBRW');
  437: <script type="text/javascript" language="Javascript">
  438: // <![CDATA[
  439:     var stdeditbrowser;
  440:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
  441:         var url = '/adm/pickstudent?';
  442:         var filter;
  443: 	if (!ignorefilter) {
  444: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  445: 	}
  446:         if (filter != null) {
  447:            if (filter != '') {
  448:                url += 'filter='+filter+'&';
  449: 	   }
  450:         }
  451:         url += 'form=' + formname + '&unameelement='+uname+
  452:                                     '&udomelement='+udom+
  453:                                     '&clicker='+clicker;
  454: 	if (roleflag) { url+="&roles=1"; }
  455:         if (courseadv == 'condition') {
  456:             if (document.getElementById('courseadv')) {
  457:                 courseadv = document.getElementById('courseadv').value;
  458:             }
  459:         }
  460:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  461:         if (uident !== '') { url+="&identelement="+uident; } 
  462:         var title = 'Student_Browser';
  463:         var options = 'scrollbars=1,resizable=1,menubar=0';
  464:         options += ',width=700,height=600';
  465:         stdeditbrowser = open(url,title,options,'1');
  466:         stdeditbrowser.focus();
  467:     }
  468: // ]]>
  469: </script>
  470: ENDSTDBRW
  471: }
  472: 
  473: sub resourcebrowser_javascript {
  474:    unless ($env{'request.course.id'}) { return ''; }
  475:    return (<<'ENDRESBRW');
  476: <script type="text/javascript" language="Javascript">
  477: // <![CDATA[
  478:     var reseditbrowser;
  479:     function openresbrowser(formname,reslink) {
  480:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  481:         var title = 'Resource_Browser';
  482:         var options = 'scrollbars=1,resizable=1,menubar=0';
  483:         options += ',width=700,height=500';
  484:         reseditbrowser = open(url,title,options,'1');
  485:         reseditbrowser.focus();
  486:     }
  487: // ]]>
  488: </script>
  489: ENDRESBRW
  490: }
  491: 
  492: sub selectstudent_link {
  493:    my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
  494:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  495:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  496:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  497:    if ($env{'request.course.id'}) {  
  498:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  499: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  500: 					'/'.$env{'request.course.sec'})) {
  501: 	   return '';
  502:        }
  503:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  504:        if ($courseadv eq 'only') {
  505:            $callargs .= ",'',1,'$courseadv'";
  506:        } elsif ($courseadv eq 'none') {
  507:            $callargs .= ",'','','$courseadv'";
  508:        } elsif ($courseadv eq 'condition') {
  509:            $callargs .= ",'','','$courseadv'";
  510:        } elsif ($identelem ne '') {
  511:            $callargs .= ",'','',''";
  512:        }
  513:        if ($identelem ne '') {
  514:            $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
  515:        }
  516:        return '<span class="LC_nobreak">'.
  517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  518:               &mt('Select User').'</a></span>';
  519:    }
  520:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  521:        $callargs .= ",'',1"; 
  522:        return '<span class="LC_nobreak">'.
  523:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  524:               &mt('Select User').'</a></span>';
  525:    }
  526:    return '';
  527: }
  528: 
  529: sub selectresource_link {
  530:    my ($form,$reslink,$arg)=@_;
  531:    
  532:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  533:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  534:    unless ($env{'request.course.id'}) { return $arg; }
  535:    return '<span class="LC_nobreak">'.
  536:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  537:               $arg.'</a></span>';
  538: }
  539: 
  540: 
  541: 
  542: sub authorbrowser_javascript {
  543:     return <<"ENDAUTHORBRW";
  544: <script type="text/javascript" language="JavaScript">
  545: // <![CDATA[
  546: var stdeditbrowser;
  547: 
  548: function openauthorbrowser(formname,udom) {
  549:     var url = '/adm/pickauthor?';
  550:     url += 'form='+formname+'&roledom='+udom;
  551:     var title = 'Author_Browser';
  552:     var options = 'scrollbars=1,resizable=1,menubar=0';
  553:     options += ',width=700,height=600';
  554:     stdeditbrowser = open(url,title,options,'1');
  555:     stdeditbrowser.focus();
  556: }
  557: 
  558: // ]]>
  559: </script>
  560: ENDAUTHORBRW
  561: }
  562: 
  563: sub coursebrowser_javascript {
  564:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  565:         $credits_element,$instcode) = @_;
  566:     my $wintitle = 'Course_Browser';
  567:     if ($crstype eq 'Community') {
  568:         $wintitle = 'Community_Browser';
  569:     }
  570:     my $id_functions = &javascript_index_functions();
  571:     my $output = '
  572: <script type="text/javascript" language="JavaScript">
  573: // <![CDATA[
  574:     var stdeditbrowser;'."\n";
  575: 
  576:     $output .= <<"ENDSTDBRW";
  577:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  578:         var url = '/adm/pickcourse?';
  579:         var formid = getFormIdByName(formname);
  580:         var domainfilter = getDomainFromSelectbox(formname,udom);
  581:         if (domainfilter != null) {
  582:            if (domainfilter != '') {
  583:                url += 'domainfilter='+domainfilter+'&';
  584: 	   }
  585:         }
  586:         url += 'form=' + formname + '&cnumelement='+uname+
  587: 	                            '&cdomelement='+udom+
  588:                                     '&cnameelement='+desc;
  589:         if (extra_element !=null && extra_element != '') {
  590:             if (formname == 'rolechoice' || formname == 'studentform') {
  591:                 url += '&roleelement='+extra_element;
  592:                 if (domainfilter == null || domainfilter == '') {
  593:                     url += '&domainfilter='+extra_element;
  594:                 }
  595:             }
  596:             else {
  597:                 if (formname == 'portform') {
  598:                     url += '&setroles='+extra_element;
  599:                 } else {
  600:                     if (formname == 'rules') {
  601:                         url += '&fixeddom='+extra_element; 
  602:                     }
  603:                 }
  604:             }     
  605:         }
  606:         if (type != null && type != '') {
  607:             url += '&type='+type;
  608:         }
  609:         if (type_elem != null && type_elem != '') {
  610:             url += '&typeelement='+type_elem;
  611:         }
  612:         if (formname == 'ccrs') {
  613:             var ownername = document.forms[formid].ccuname.value;
  614:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  615:             url += '&cloner='+ownername+':'+ownerdom;
  616:             if (type == 'Course') {
  617:                 url += '&crscode='+document.forms[formid].crscode.value;
  618:             }
  619:         }
  620:         if (formname == 'requestcrs') {
  621:             url += '&crsdom=$domainfilter&crscode=$instcode';
  622:         }
  623:         if (multflag !=null && multflag != '') {
  624:             url += '&multiple='+multflag;
  625:         }
  626:         var title = '$wintitle';
  627:         var options = 'scrollbars=1,resizable=1,menubar=0';
  628:         options += ',width=700,height=600';
  629:         stdeditbrowser = open(url,title,options,'1');
  630:         stdeditbrowser.focus();
  631:     }
  632: $id_functions
  633: ENDSTDBRW
  634:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  635:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  636:                                       $credits_element);
  637:     }
  638:     $output .= '
  639: // ]]>
  640: </script>';
  641:     return $output;
  642: }
  643: 
  644: sub javascript_index_functions {
  645:     return <<"ENDJS";
  646: 
  647: function getFormIdByName(formname) {
  648:     for (var i=0;i<document.forms.length;i++) {
  649:         if (document.forms[i].name == formname) {
  650:             return i;
  651:         }
  652:     }
  653:     return -1;
  654: }
  655: 
  656: function getIndexByName(formid,item) {
  657:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  658:         if (document.forms[formid].elements[i].name == item) {
  659:             return i;
  660:         }
  661:     }
  662:     return -1;
  663: }
  664: 
  665: function getDomainFromSelectbox(formname,udom) {
  666:     var userdom;
  667:     var formid = getFormIdByName(formname);
  668:     if (formid > -1) {
  669:         var domid = getIndexByName(formid,udom);
  670:         if (domid > -1) {
  671:             if (document.forms[formid].elements[domid].type == 'select-one') {
  672:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  673:             }
  674:             if (document.forms[formid].elements[domid].type == 'hidden') {
  675:                 userdom=document.forms[formid].elements[domid].value;
  676:             }
  677:         }
  678:     }
  679:     return userdom;
  680: }
  681: 
  682: ENDJS
  683: 
  684: }
  685: 
  686: sub javascript_array_indexof {
  687:     return <<ENDJS;
  688: <script type="text/javascript" language="JavaScript">
  689: // <![CDATA[
  690: 
  691: if (!Array.prototype.indexOf) {
  692:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  693:         "use strict";
  694:         if (this === void 0 || this === null) {
  695:             throw new TypeError();
  696:         }
  697:         var t = Object(this);
  698:         var len = t.length >>> 0;
  699:         if (len === 0) {
  700:             return -1;
  701:         }
  702:         var n = 0;
  703:         if (arguments.length > 0) {
  704:             n = Number(arguments[1]);
  705:             if (n !== n) { // shortcut for verifying if it is NaN
  706:                 n = 0;
  707:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  708:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  709:             }
  710:         }
  711:         if (n >= len) {
  712:             return -1;
  713:         }
  714:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  715:         for (; k < len; k++) {
  716:             if (k in t && t[k] === searchElement) {
  717:                 return k;
  718:             }
  719:         }
  720:         return -1;
  721:     }
  722: }
  723: 
  724: // ]]>
  725: </script>
  726: 
  727: ENDJS
  728: 
  729: }
  730: 
  731: sub userbrowser_javascript {
  732:     my $id_functions = &javascript_index_functions();
  733:     return <<"ENDUSERBRW";
  734: 
  735: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  736:     var url = '/adm/pickuser?';
  737:     var userdom = getDomainFromSelectbox(formname,udom);
  738:     if (userdom != null) {
  739:        if (userdom != '') {
  740:            url += 'srchdom='+userdom+'&';
  741:        }
  742:     }
  743:     url += 'form=' + formname + '&unameelement='+uname+
  744:                                 '&udomelement='+udom+
  745:                                 '&ulastelement='+ulast+
  746:                                 '&ufirstelement='+ufirst+
  747:                                 '&uemailelement='+uemail+
  748:                                 '&hideudomelement='+hideudom+
  749:                                 '&coursedom='+crsdom;
  750:     if ((caller != null) && (caller != undefined)) {
  751:         url += '&caller='+caller;
  752:     }
  753:     var title = 'User_Browser';
  754:     var options = 'scrollbars=1,resizable=1,menubar=0';
  755:     options += ',width=700,height=600';
  756:     var stdeditbrowser = open(url,title,options,'1');
  757:     stdeditbrowser.focus();
  758: }
  759: 
  760: function fix_domain (formname,udom,origdom,uname) {
  761:     var formid = getFormIdByName(formname);
  762:     if (formid > -1) {
  763:         var unameid = getIndexByName(formid,uname);
  764:         var domid = getIndexByName(formid,udom);
  765:         var hidedomid = getIndexByName(formid,origdom);
  766:         if (hidedomid > -1) {
  767:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  768:             var unameval = document.forms[formid].elements[unameid].value;
  769:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  770:                 if (domid > -1) {
  771:                     var slct = document.forms[formid].elements[domid];
  772:                     if (slct.type == 'select-one') {
  773:                         var i;
  774:                         for (i=0;i<slct.length;i++) {
  775:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  776:                         }
  777:                     }
  778:                     if (slct.type == 'hidden') {
  779:                         slct.value = fixeddom;
  780:                     }
  781:                 }
  782:             }
  783:         }
  784:     }
  785:     return;
  786: }
  787: 
  788: $id_functions
  789: ENDUSERBRW
  790: }
  791: 
  792: sub setsec_javascript {
  793:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  794:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  795:         $communityrolestr);
  796:     if ($role_element ne '') {
  797:         my @allroles = ('st','ta','ep','in','ad');
  798:         foreach my $crstype ('Course','Community') {
  799:             if ($crstype eq 'Community') {
  800:                 foreach my $role (@allroles) {
  801:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  802:                 }
  803:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  804:             } else {
  805:                 foreach my $role (@allroles) {
  806:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  807:                 }
  808:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  809:             }
  810:         }
  811:         $rolestr = '"'.join('","',@allroles).'"';
  812:         $courserolestr = '"'.join('","',@courserolenames).'"';
  813:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  814:     }
  815:     my $setsections = qq|
  816: function setSect(sectionlist) {
  817:     var sectionsArray = new Array();
  818:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  819:         sectionsArray = sectionlist.split(",");
  820:     }
  821:     var numSections = sectionsArray.length;
  822:     document.$formname.$sec_element.length = 0;
  823:     if (numSections == 0) {
  824:         document.$formname.$sec_element.multiple=false;
  825:         document.$formname.$sec_element.size=1;
  826:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  827:     } else {
  828:         if (numSections == 1) {
  829:             document.$formname.$sec_element.multiple=false;
  830:             document.$formname.$sec_element.size=1;
  831:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  832:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  833:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  834:         } else {
  835:             for (var i=0; i<numSections; i++) {
  836:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  837:             }
  838:             document.$formname.$sec_element.multiple=true
  839:             if (numSections < 3) {
  840:                 document.$formname.$sec_element.size=numSections;
  841:             } else {
  842:                 document.$formname.$sec_element.size=3;
  843:             }
  844:             document.$formname.$sec_element.options[0].selected = false
  845:         }
  846:     }
  847: }
  848: 
  849: function setRole(crstype) {
  850: |;
  851:     if ($role_element eq '') {
  852:         $setsections .= '    return;
  853: }
  854: ';
  855:     } else {
  856:         $setsections .= qq|
  857:     var elementLength = document.$formname.$role_element.length;
  858:     var allroles = Array($rolestr);
  859:     var courserolenames = Array($courserolestr);
  860:     var communityrolenames = Array($communityrolestr);
  861:     if (elementLength != undefined) {
  862:         if (document.$formname.$role_element.options[5].value == 'cc') {
  863:             if (crstype == 'Course') {
  864:                 return;
  865:             } else {
  866:                 allroles[5] = 'co';
  867:                 for (var i=0; i<6; i++) {
  868:                     document.$formname.$role_element.options[i].value = allroles[i];
  869:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  870:                 }
  871:             }
  872:         } else {
  873:             if (crstype == 'Community') {
  874:                 return;
  875:             } else {
  876:                 allroles[5] = 'cc';
  877:                 for (var i=0; i<6; i++) {
  878:                     document.$formname.$role_element.options[i].value = allroles[i];
  879:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  880:                 }
  881:             }
  882:         }
  883:     }
  884:     return;
  885: }
  886: |;
  887:     }
  888:     if ($credits_element) {
  889:         $setsections .= qq|
  890: function setCredits(defaultcredits) {
  891:     document.$formname.$credits_element.value = defaultcredits;
  892:     return;
  893: }
  894: |;
  895:     }
  896:     return $setsections;
  897: }
  898: 
  899: sub selectcourse_link {
  900:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  901:        $typeelement) = @_;
  902:    my $type = $selecttype;
  903:    my $linktext = &mt('Select Course');
  904:    if ($selecttype eq 'Community') {
  905:        $linktext = &mt('Select Community');
  906:    } elsif ($selecttype eq 'Placement') {
  907:        $linktext = &mt('Select Placement Test'); 
  908:    } elsif ($selecttype eq 'Course/Community') {
  909:        $linktext = &mt('Select Course/Community');
  910:        $type = '';
  911:    } elsif ($selecttype eq 'Select') {
  912:        $linktext = &mt('Select');
  913:        $type = '';
  914:    }
  915:    return '<span class="LC_nobreak">'
  916:          ."<a href='"
  917:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  918:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  919:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  920:          ."'>".$linktext.'</a>'
  921:          .'</span>';
  922: }
  923: 
  924: sub selectauthor_link {
  925:    my ($form,$udom)=@_;
  926:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  927:           &mt('Select Author').'</a>';
  928: }
  929: 
  930: sub selectuser_link {
  931:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  932:         $coursedom,$linktext,$caller) = @_;
  933:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  934:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  935:            ');">'.$linktext.'</a>';
  936: }
  937: 
  938: sub check_uncheck_jscript {
  939:     my $jscript = <<"ENDSCRT";
  940: function checkAll(field) {
  941:     if (field.length > 0) {
  942:         for (i = 0; i < field.length; i++) {
  943:             if (!field[i].disabled) { 
  944:                 field[i].checked = true;
  945:             }
  946:         }
  947:     } else {
  948:         if (!field.disabled) { 
  949:             field.checked = true;
  950:         }
  951:     }
  952: }
  953:  
  954: function uncheckAll(field) {
  955:     if (field.length > 0) {
  956:         for (i = 0; i < field.length; i++) {
  957:             field[i].checked = false ;
  958:         }
  959:     } else {
  960:         field.checked = false ;
  961:     }
  962: }
  963: ENDSCRT
  964:     return $jscript;
  965: }
  966: 
  967: sub select_timezone {
  968:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
  969:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
  970:    if ($includeempty) {
  971:        $output .= '<option value=""';
  972:        if (($selected eq '') || ($selected eq 'local')) {
  973:            $output .= ' selected="selected" ';
  974:        }
  975:        $output .= '> </option>';
  976:    }
  977:    my @timezones = DateTime::TimeZone->all_names;
  978:    foreach my $tzone (@timezones) {
  979:        $output.= '<option value="'.$tzone.'"';
  980:        if ($tzone eq $selected) {
  981:            $output.=' selected="selected"';
  982:        }
  983:        $output.=">$tzone</option>\n";
  984:    }
  985:    $output.="</select>";
  986:    return $output;
  987: }
  988: 
  989: sub select_datelocale {
  990:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  991:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  992:     if ($includeempty) {
  993:         $output .= '<option value=""';
  994:         if ($selected eq '') {
  995:             $output .= ' selected="selected" ';
  996:         }
  997:         $output .= '> </option>';
  998:     }
  999:     my @languages = &Apache::lonlocal::preferred_languages();
 1000:     my (@possibles,%locale_names);
 1001:     my @locales = DateTime::Locale->ids();
 1002:     foreach my $id (@locales) {
 1003:         if ($id ne '') {
 1004:             my ($en_terr,$native_terr);
 1005:             my $loc = DateTime::Locale->load($id);
 1006:             if (ref($loc)) {
 1007:                 $en_terr = $loc->name();
 1008:                 $native_terr = $loc->native_name();
 1009:                 if (grep(/^en$/,@languages) || !@languages) {
 1010:                     if ($en_terr ne '') {
 1011:                         $locale_names{$id} = '('.$en_terr.')';
 1012:                     } elsif ($native_terr ne '') {
 1013:                         $locale_names{$id} = $native_terr;
 1014:                     }
 1015:                 } else {
 1016:                     if ($native_terr ne '') {
 1017:                         $locale_names{$id} = $native_terr.' ';
 1018:                     } elsif ($en_terr ne '') {
 1019:                         $locale_names{$id} = '('.$en_terr.')';
 1020:                     }
 1021:                 }
 1022:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1023:                 push(@possibles,$id);
 1024:             } 
 1025:         }
 1026:     }
 1027:     foreach my $item (sort(@possibles)) {
 1028:         $output.= '<option value="'.$item.'"';
 1029:         if ($item eq $selected) {
 1030:             $output.=' selected="selected"';
 1031:         }
 1032:         $output.=">$item";
 1033:         if ($locale_names{$item} ne '') {
 1034:             $output.='  '.$locale_names{$item};
 1035:         }
 1036:         $output.="</option>\n";
 1037:     }
 1038:     $output.="</select>";
 1039:     return $output;
 1040: }
 1041: 
 1042: sub select_language {
 1043:     my ($name,$selected,$includeempty,$noedit) = @_;
 1044:     my %langchoices;
 1045:     if ($includeempty) {
 1046:         %langchoices = ('' => 'No language preference');
 1047:     }
 1048:     foreach my $id (&languageids()) {
 1049:         my $code = &supportedlanguagecode($id);
 1050:         if ($code) {
 1051:             $langchoices{$code} = &plainlanguagedescription($id);
 1052:         }
 1053:     }
 1054:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1055:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1056: }
 1057: 
 1058: =pod
 1059: 
 1060: 
 1061: =item * &list_languages()
 1062: 
 1063: Returns an array reference that is suitable for use in language prompters.
 1064: Each array element is itself a two element array.  The first element
 1065: is the language code.  The second element a descsriptiuon of the 
 1066: language itself.  This is suitable for use in e.g.
 1067: &Apache::edit::select_arg (once dereferenced that is).
 1068: 
 1069: =cut 
 1070: 
 1071: sub list_languages {
 1072:     my @lang_choices;
 1073: 
 1074:     foreach my $id (&languageids()) {
 1075: 	my $code = &supportedlanguagecode($id);
 1076: 	if ($code) {
 1077: 	    my $selector    = $supported_codes{$id};
 1078: 	    my $description = &plainlanguagedescription($id);
 1079: 	    push(@lang_choices, [$selector, $description]);
 1080: 	}
 1081:     }
 1082:     return \@lang_choices;
 1083: }
 1084: 
 1085: =pod
 1086: 
 1087: =item * &linked_select_forms(...)
 1088: 
 1089: linked_select_forms returns a string containing a <script></script> block
 1090: and html for two <select> menus.  The select menus will be linked in that
 1091: changing the value of the first menu will result in new values being placed
 1092: in the second menu.  The values in the select menu will appear in alphabetical
 1093: order unless a defined order is provided.
 1094: 
 1095: linked_select_forms takes the following ordered inputs:
 1096: 
 1097: =over 4
 1098: 
 1099: =item * $formname, the name of the <form> tag
 1100: 
 1101: =item * $middletext, the text which appears between the <select> tags
 1102: 
 1103: =item * $firstdefault, the default value for the first menu
 1104: 
 1105: =item * $firstselectname, the name of the first <select> tag
 1106: 
 1107: =item * $secondselectname, the name of the second <select> tag
 1108: 
 1109: =item * $hashref, a reference to a hash containing the data for the menus.
 1110: 
 1111: =item * $menuorder, the order of values in the first menu
 1112: 
 1113: =item * $onchangefirst, additional javascript call to execute for an onchange
 1114:         event for the first <select> tag
 1115: 
 1116: =item * $onchangesecond, additional javascript call to execute for an onchange
 1117:         event for the second <select> tag
 1118: 
 1119: =item * $suffix, to differentiate separate uses of select2data javascript
 1120:         objects in a page.
 1121: 
 1122: =back 
 1123: 
 1124: Below is an example of such a hash.  Only the 'text', 'default', and 
 1125: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1126: values for the first select menu.  The text that coincides with the 
 1127: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1128: and text for the second menu are given in the hash pointed to by 
 1129: $menu{$choice1}->{'select2'}.  
 1130: 
 1131:  my %menu = ( A1 => { text =>"Choice A1" ,
 1132:                        default => "B3",
 1133:                        select2 => { 
 1134:                            B1 => "Choice B1",
 1135:                            B2 => "Choice B2",
 1136:                            B3 => "Choice B3",
 1137:                            B4 => "Choice B4"
 1138:                            },
 1139:                        order => ['B4','B3','B1','B2'],
 1140:                    },
 1141:                A2 => { text =>"Choice A2" ,
 1142:                        default => "C2",
 1143:                        select2 => { 
 1144:                            C1 => "Choice C1",
 1145:                            C2 => "Choice C2",
 1146:                            C3 => "Choice C3"
 1147:                            },
 1148:                        order => ['C2','C1','C3'],
 1149:                    },
 1150:                A3 => { text =>"Choice A3" ,
 1151:                        default => "D6",
 1152:                        select2 => { 
 1153:                            D1 => "Choice D1",
 1154:                            D2 => "Choice D2",
 1155:                            D3 => "Choice D3",
 1156:                            D4 => "Choice D4",
 1157:                            D5 => "Choice D5",
 1158:                            D6 => "Choice D6",
 1159:                            D7 => "Choice D7"
 1160:                            },
 1161:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1162:                    }
 1163:                );
 1164: 
 1165: =cut
 1166: 
 1167: sub linked_select_forms {
 1168:     my ($formname,
 1169:         $middletext,
 1170:         $firstdefault,
 1171:         $firstselectname,
 1172:         $secondselectname, 
 1173:         $hashref,
 1174:         $menuorder,
 1175:         $onchangefirst,
 1176:         $onchangesecond,
 1177:         $suffix
 1178:         ) = @_;
 1179:     my $second = "document.$formname.$secondselectname";
 1180:     my $first = "document.$formname.$firstselectname";
 1181:     # output the javascript to do the changing
 1182:     my $result = '';
 1183:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1184:     $result.="// <![CDATA[\n";
 1185:     $result.="var select2data${suffix} = new Object();\n";
 1186:     $" = '","';
 1187:     my $debug = '';
 1188:     foreach my $s1 (sort(keys(%$hashref))) {
 1189:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1190:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1191:             $hashref->{$s1}->{'default'}."');\n";
 1192:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1193:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1194:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1195:             @s2values = @{$hashref->{$s1}->{'order'}};
 1196:         }
 1197:         $result.="\"@s2values\");\n";
 1198:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1199:         my @s2texts;
 1200:         foreach my $value (@s2values) {
 1201:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1202:         }
 1203:         $result.="\"@s2texts\");\n";
 1204:     }
 1205:     $"=' ';
 1206:     $result.= <<"END";
 1207: 
 1208: function select1${suffix}_changed() {
 1209:     // Determine new choice
 1210:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1211:     // update select2
 1212:     var values     = select2data${suffix}[newvalue].values;
 1213:     var texts      = select2data${suffix}[newvalue].texts;
 1214:     var select2def = select2data${suffix}[newvalue].def;
 1215:     var i;
 1216:     // out with the old
 1217:     $second.options.length = 0;
 1218:     // in with the new
 1219:     for (i=0;i<values.length; i++) {
 1220:         $second.options[i] = new Option(values[i]);
 1221:         $second.options[i].value = values[i];
 1222:         $second.options[i].text = texts[i];
 1223:         if (values[i] == select2def) {
 1224:             $second.options[i].selected = true;
 1225:         }
 1226:     }
 1227: }
 1228: // ]]>
 1229: </script>
 1230: END
 1231:     # output the initial values for the selection lists
 1232:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1233:     my @order = sort(keys(%{$hashref}));
 1234:     if (ref($menuorder) eq 'ARRAY') {
 1235:         @order = @{$menuorder};
 1236:     }
 1237:     foreach my $value (@order) {
 1238:         $result.="    <option value=\"$value\" ";
 1239:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1240:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1241:     }
 1242:     $result .= "</select>\n";
 1243:     my %select2;
 1244:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
 1245:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
 1246:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1247:         }
 1248:     }
 1249:     $result .= $middletext;
 1250:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1251:     if ($onchangesecond) {
 1252:         $result .= ' onchange="'.$onchangesecond.'"';
 1253:     }
 1254:     $result .= ">\n";
 1255:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1256:     
 1257:     my @secondorder = sort(keys(%select2));
 1258:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1259:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1260:     }
 1261:     foreach my $value (@secondorder) {
 1262:         $result.="    <option value=\"$value\" ";        
 1263:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1264:         $result.=">".&mt($select2{$value})."</option>\n";
 1265:     }
 1266:     $result .= "</select>\n";
 1267:     #    return $debug;
 1268:     return $result;
 1269: }   #  end of sub linked_select_forms {
 1270: 
 1271: =pod
 1272: 
 1273: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
 1274: 
 1275: Returns a string corresponding to an HTML link to the given help
 1276: $topic, where $topic corresponds to the name of a .tex file in
 1277: /home/httpd/html/adm/help/tex, with underscores replaced by
 1278: spaces. 
 1279: 
 1280: $text will optionally be linked to the same topic, allowing you to
 1281: link text in addition to the graphic. If you do not want to link
 1282: text, but wish to specify one of the later parameters, pass an
 1283: empty string. 
 1284: 
 1285: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1286: the link will not open a new window. If false, the link will open
 1287: a new window using Javascript. (Default is false.) 
 1288: 
 1289: $width and $height are optional numerical parameters that will
 1290: override the width and height of the popped up window, which may
 1291: be useful for certain help topics with big pictures included.
 1292: 
 1293: $imgid is the id of the img tag used for the help icon. This may be
 1294: used in a javascript call to switch the image src.  See 
 1295: lonhtmlcommon::htmlareaselectactive() for an example.
 1296: 
 1297: $links_target will optionally be set to a target (_top, _parent or _self).
 1298: 
 1299: =cut
 1300: 
 1301: sub help_open_topic {
 1302:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
 1303:     $text = "" if (not defined $text);
 1304:     $stayOnPage = 0 if (not defined $stayOnPage);
 1305:     $width = 500 if (not defined $width);
 1306:     $height = 400 if (not defined $height);
 1307:     my $filename = $topic;
 1308:     $filename =~ s/ /_/g;
 1309: 
 1310:     my $template = "";
 1311:     my $link;
 1312:     
 1313:     $topic=~s/\W/\_/g;
 1314: 
 1315:     if (!$stayOnPage) {
 1316: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1317:     } elsif ($stayOnPage eq 'popup') {
 1318:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1319:     } else {
 1320: 	$link = "/adm/help/${filename}.hlp";
 1321:     }
 1322: 
 1323:     # Add the text
 1324:     my $target = ' target="_top"';
 1325:     if ($links_target) {
 1326:         $target = ' target="'.$links_target.'"';
 1327:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1328:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1329:         $target = '';
 1330:     }
 1331:     if ($text ne "") {
 1332: 	$template.='<span class="LC_help_open_topic">'
 1333:                   .'<a'.$target.' href="'.$link.'">'
 1334:                   .$text.'</a>';
 1335:     }
 1336: 
 1337:     # (Always) Add the graphic
 1338:     my $title = &mt('Online Help');
 1339:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1340:     if ($imgid ne '') {
 1341:         $imgid = ' id="'.$imgid.'"';
 1342:     }
 1343:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1344:               .'<img src="'.$helpicon.'" border="0"'
 1345:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1346:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1347:               .' /></a>';
 1348:     if ($text ne "") {	
 1349:         $template.='</span>';
 1350:     }
 1351:     return $template;
 1352: 
 1353: }
 1354: 
 1355: # This is a quicky function for Latex cheatsheet editing, since it 
 1356: # appears in at least four places
 1357: sub helpLatexCheatsheet {
 1358:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1359:     my $out;
 1360:     my $addOther = '';
 1361:     if ($topic) {
 1362: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1363:     }
 1364:     $out = '<span>' # Start cheatsheet
 1365: 	  .$addOther
 1366:           .'<span>'
 1367: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1368: 	  .'</span> <span>'
 1369: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1370: 	  .'</span>';
 1371:     unless ($not_author) {
 1372:         $out .= '<span>'
 1373:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1374:                .'</span> <span>'
 1375:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1376: 	       .'</span>';
 1377:     }
 1378:     $out .= '</span>'; # End cheatsheet
 1379:     return $out;
 1380: }
 1381: 
 1382: sub general_help {
 1383:     my $helptopic='Student_Intro';
 1384:     if ($env{'request.role'}=~/^(ca|au)/) {
 1385: 	$helptopic='Authoring_Intro';
 1386:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1387: 	$helptopic='Course_Coordination_Intro';
 1388:     } elsif ($env{'request.role'}=~/^dc/) {
 1389:         $helptopic='Domain_Coordination_Intro';
 1390:     }
 1391:     return $helptopic;
 1392: }
 1393: 
 1394: sub update_help_link {
 1395:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1396:     my $origurl = $ENV{'REQUEST_URI'};
 1397:     $origurl=~s|^/~|/priv/|;
 1398:     my $timestamp = time;
 1399:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1400:         $$datum = &escape($$datum);
 1401:     }
 1402: 
 1403:     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";
 1404:     my $output .= <<"ENDOUTPUT";
 1405: <script type="text/javascript">
 1406: // <![CDATA[
 1407: banner_link = '$banner_link';
 1408: // ]]>
 1409: </script>
 1410: ENDOUTPUT
 1411:     return $output;
 1412: }
 1413: 
 1414: # now just updates the help link and generates a blue icon
 1415: sub help_open_menu {
 1416:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
 1417: 	= @_;    
 1418:     $stayOnPage = 1;
 1419:     my $output;
 1420:     if ($component_help) {
 1421: 	if (!$text) {
 1422: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1423: 				       $width,$height,'',$links_target);
 1424: 	} else {
 1425: 	    my $help_text;
 1426: 	    $help_text=&unescape($topic);
 1427: 	    $output='<table><tr><td>'.
 1428: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1429: 				 $width,$height,'',$links_target).'</td></tr></table>';
 1430: 	}
 1431:     }
 1432:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1433:     return $output.$banner_link;
 1434: }
 1435: 
 1436: sub top_nav_help {
 1437:     my ($text,$linkattr) = @_;
 1438:     $text = &mt($text);
 1439:     my $stay_on_page = 1;
 1440: 
 1441:     my ($link,$banner_link);
 1442:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1443:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1444: 	                         : "javascript:helpMenu('open')";
 1445:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1446:     }
 1447:     my $title = &mt('Get help');
 1448:     if ($link) {
 1449:         return <<"END";
 1450: $banner_link
 1451: <a href="$link" title="$title" $linkattr>$text</a>
 1452: END
 1453:     } else {
 1454:         return '&nbsp;'.$text.'&nbsp;';
 1455:     }
 1456: }
 1457: 
 1458: sub help_menu_js {
 1459:     my ($httphost) = @_;
 1460:     my $stayOnPage = 1;
 1461:     my $width = 620;
 1462:     my $height = 600;
 1463:     my $helptopic=&general_help();
 1464:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1465:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1466:     my $start_page =
 1467:         &Apache::loncommon::start_page('Help Menu', undef,
 1468: 				       {'frameset'    => 1,
 1469: 					'js_ready'    => 1,
 1470:                                         'use_absolute' => $httphost,
 1471: 					'add_entries' => {
 1472: 					    'border' => '0', 
 1473: 					    'rows'   => "110,*",},});
 1474:     my $end_page =
 1475:         &Apache::loncommon::end_page({'frameset' => 1,
 1476: 				      'js_ready' => 1,});
 1477: 
 1478:     my $template .= <<"ENDTEMPLATE";
 1479: <script type="text/javascript">
 1480: // <![CDATA[
 1481: // <!-- BEGIN LON-CAPA Internal
 1482: var banner_link = '';
 1483: function helpMenu(target) {
 1484:     var caller = this;
 1485:     if (target == 'open') {
 1486:         var newWindow = null;
 1487:         try {
 1488:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1489:         }
 1490:         catch(error) {
 1491:             writeHelp(caller);
 1492:             return;
 1493:         }
 1494:         if (newWindow) {
 1495:             caller = newWindow;
 1496:         }
 1497:     }
 1498:     writeHelp(caller);
 1499:     return;
 1500: }
 1501: function writeHelp(caller) {
 1502:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1503:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1504:     caller.document.close();
 1505:     caller.focus();
 1506: }
 1507: // END LON-CAPA Internal -->
 1508: // ]]>
 1509: </script>
 1510: ENDTEMPLATE
 1511:     return $template;
 1512: }
 1513: 
 1514: sub help_open_bug {
 1515:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1516:     unless ($env{'user.adv'}) { return ''; }
 1517:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1518:     $text = "" if (not defined $text);
 1519: 	$stayOnPage=1;
 1520:     $width = 600 if (not defined $width);
 1521:     $height = 600 if (not defined $height);
 1522: 
 1523:     $topic=~s/\W+/\+/g;
 1524:     my $link='';
 1525:     my $template='';
 1526:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1527: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1528:     if (!$stayOnPage)
 1529:     {
 1530: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1531:     }
 1532:     else
 1533:     {
 1534: 	$link = $url;
 1535:     }
 1536: 
 1537:     my $target = '_top';
 1538:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1539:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1540:         $target = '_blank';
 1541:     }
 1542: 
 1543:     # Add the text
 1544:     if ($text ne "")
 1545:     {
 1546: 	$template .= 
 1547:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1548:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1549:     }
 1550: 
 1551:     # Add the graphic
 1552:     my $title = &mt('Report a Bug');
 1553:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1554:     $template .= <<"ENDTEMPLATE";
 1555:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1556: ENDTEMPLATE
 1557:     if ($text ne '') { $template.='</td></tr></table>' };
 1558:     return $template;
 1559: 
 1560: }
 1561: 
 1562: sub help_open_faq {
 1563:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1564:     unless ($env{'user.adv'}) { return ''; }
 1565:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1566:     $text = "" if (not defined $text);
 1567: 	$stayOnPage=1;
 1568:     $width = 350 if (not defined $width);
 1569:     $height = 400 if (not defined $height);
 1570: 
 1571:     $topic=~s/\W+/\+/g;
 1572:     my $link='';
 1573:     my $template='';
 1574:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1575:     if (!$stayOnPage)
 1576:     {
 1577: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1578:     }
 1579:     else
 1580:     {
 1581: 	$link = $url;
 1582:     }
 1583: 
 1584:     # Add the text
 1585:     if ($text ne "")
 1586:     {
 1587: 	$template .= 
 1588:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1589:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1590:     }
 1591: 
 1592:     # Add the graphic
 1593:     my $title = &mt('View the FAQ');
 1594:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1595:     $template .= <<"ENDTEMPLATE";
 1596:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1597: ENDTEMPLATE
 1598:     if ($text ne '') { $template.='</td></tr></table>' };
 1599:     return $template;
 1600: 
 1601: }
 1602: 
 1603: ###############################################################
 1604: ###############################################################
 1605: 
 1606: =pod
 1607: 
 1608: =item * &change_content_javascript():
 1609: 
 1610: This and the next function allow you to create small sections of an
 1611: otherwise static HTML page that you can update on the fly with
 1612: Javascript, even in Netscape 4.
 1613: 
 1614: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1615: must be written to the HTML page once. It will prove the Javascript
 1616: function "change(name, content)". Calling the change function with the
 1617: name of the section 
 1618: you want to update, matching the name passed to C<changable_area>, and
 1619: the new content you want to put in there, will put the content into
 1620: that area.
 1621: 
 1622: B<Note>: Netscape 4 only reserves enough space for the changable area
 1623: to contain room for the original contents. You need to "make space"
 1624: for whatever changes you wish to make, and be B<sure> to check your
 1625: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1626: it's adequate for updating a one-line status display, but little more.
 1627: This script will set the space to 100% width, so you only need to
 1628: worry about height in Netscape 4.
 1629: 
 1630: Modern browsers are much less limiting, and if you can commit to the
 1631: user not using Netscape 4, this feature may be used freely with
 1632: pretty much any HTML.
 1633: 
 1634: =cut
 1635: 
 1636: sub change_content_javascript {
 1637:     # If we're on Netscape 4, we need to use Layer-based code
 1638:     if ($env{'browser.type'} eq 'netscape' &&
 1639: 	$env{'browser.version'} =~ /^4\./) {
 1640: 	return (<<NETSCAPE4);
 1641: 	function change(name, content) {
 1642: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1643: 	    doc.open();
 1644: 	    doc.write(content);
 1645: 	    doc.close();
 1646: 	}
 1647: NETSCAPE4
 1648:     } else {
 1649: 	# Otherwise, we need to use semi-standards-compliant code
 1650: 	# (technically, "innerHTML" isn't standard but the equivalent
 1651: 	# is really scary, and every useful browser supports it
 1652: 	return (<<DOMBASED);
 1653: 	function change(name, content) {
 1654: 	    element = document.getElementById(name);
 1655: 	    element.innerHTML = content;
 1656: 	}
 1657: DOMBASED
 1658:     }
 1659: }
 1660: 
 1661: =pod
 1662: 
 1663: =item * &changable_area($name,$origContent):
 1664: 
 1665: This provides a "changable area" that can be modified on the fly via
 1666: the Javascript code provided in C<change_content_javascript>. $name is
 1667: the name you will use to reference the area later; do not repeat the
 1668: same name on a given HTML page more then once. $origContent is what
 1669: the area will originally contain, which can be left blank.
 1670: 
 1671: =cut
 1672: 
 1673: sub changable_area {
 1674:     my ($name, $origContent) = @_;
 1675: 
 1676:     if ($env{'browser.type'} eq 'netscape' &&
 1677: 	$env{'browser.version'} =~ /^4\./) {
 1678: 	# If this is netscape 4, we need to use the Layer tag
 1679: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1680:     } else {
 1681: 	return "<span id='$name'>$origContent</span>";
 1682:     }
 1683: }
 1684: 
 1685: =pod
 1686: 
 1687: =item * &viewport_geometry_js 
 1688: 
 1689: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1690: 
 1691: =cut
 1692: 
 1693: 
 1694: sub viewport_geometry_js { 
 1695:     return <<"GEOMETRY";
 1696: var Geometry = {};
 1697: function init_geometry() {
 1698:     if (Geometry.init) { return };
 1699:     Geometry.init=1;
 1700:     if (window.innerHeight) {
 1701:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1702:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1703:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1704:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1705:     }
 1706:     else if (document.documentElement && document.documentElement.clientHeight) {
 1707:         Geometry.getViewportHeight =
 1708:             function() { return document.documentElement.clientHeight; };
 1709:         Geometry.getViewportWidth =
 1710:             function() { return document.documentElement.clientWidth; };
 1711: 
 1712:         Geometry.getHorizontalScroll =
 1713:             function() { return document.documentElement.scrollLeft; };
 1714:         Geometry.getVerticalScroll =
 1715:             function() { return document.documentElement.scrollTop; };
 1716:     }
 1717:     else if (document.body.clientHeight) {
 1718:         Geometry.getViewportHeight =
 1719:             function() { return document.body.clientHeight; };
 1720:         Geometry.getViewportWidth =
 1721:             function() { return document.body.clientWidth; };
 1722:         Geometry.getHorizontalScroll =
 1723:             function() { return document.body.scrollLeft; };
 1724:         Geometry.getVerticalScroll =
 1725:             function() { return document.body.scrollTop; };
 1726:     }
 1727: }
 1728: 
 1729: GEOMETRY
 1730: }
 1731: 
 1732: =pod
 1733: 
 1734: =item * &viewport_size_js()
 1735: 
 1736: 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. 
 1737: 
 1738: =cut
 1739: 
 1740: sub viewport_size_js {
 1741:     my $geometry = &viewport_geometry_js();
 1742:     return <<"DIMS";
 1743: 
 1744: $geometry
 1745: 
 1746: function getViewportDims(width,height) {
 1747:     init_geometry();
 1748:     width.value = Geometry.getViewportWidth();
 1749:     height.value = Geometry.getViewportHeight();
 1750:     return;
 1751: }
 1752: 
 1753: DIMS
 1754: }
 1755: 
 1756: =pod
 1757: 
 1758: =item * &resize_textarea_js()
 1759: 
 1760: emits the needed javascript to resize a textarea to be as big as possible
 1761: 
 1762: creates a function resize_textrea that takes two IDs first should be
 1763: the id of the element to resize, second should be the id of a div that
 1764: surrounds everything that comes after the textarea, this routine needs
 1765: to be attached to the <body> for the onload and onresize events.
 1766: 
 1767: =cut
 1768: 
 1769: sub resize_textarea_js {
 1770:     my $geometry = &viewport_geometry_js();
 1771:     return <<"RESIZE";
 1772:     <script type="text/javascript">
 1773: // <![CDATA[
 1774: $geometry
 1775: 
 1776: function getX(element) {
 1777:     var x = 0;
 1778:     while (element) {
 1779: 	x += element.offsetLeft;
 1780: 	element = element.offsetParent;
 1781:     }
 1782:     return x;
 1783: }
 1784: function getY(element) {
 1785:     var y = 0;
 1786:     while (element) {
 1787: 	y += element.offsetTop;
 1788: 	element = element.offsetParent;
 1789:     }
 1790:     return y;
 1791: }
 1792: 
 1793: 
 1794: function resize_textarea(textarea_id,bottom_id) {
 1795:     init_geometry();
 1796:     var textarea        = document.getElementById(textarea_id);
 1797:     //alert(textarea);
 1798: 
 1799:     var textarea_top    = getY(textarea);
 1800:     var textarea_height = textarea.offsetHeight;
 1801:     var bottom          = document.getElementById(bottom_id);
 1802:     var bottom_top      = getY(bottom);
 1803:     var bottom_height   = bottom.offsetHeight;
 1804:     var window_height   = Geometry.getViewportHeight();
 1805:     var fudge           = 23;
 1806:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1807:     if (new_height < 300) {
 1808: 	new_height = 300;
 1809:     }
 1810:     textarea.style.height=new_height+'px';
 1811: }
 1812: // ]]>
 1813: </script>
 1814: RESIZE
 1815: 
 1816: }
 1817: 
 1818: sub colorfuleditor_js {
 1819:     my $browse_or_search;
 1820:     my $respath;
 1821:     my ($cnum,$cdom) = &crsauthor_url();
 1822:     if ($cnum) {
 1823:         $respath = "/res/$cdom/$cnum/";
 1824:         my %js_lt = &Apache::lonlocal::texthash(
 1825:             sunm => 'Sub-directory name',
 1826:             save => 'Save page to make this permanent',
 1827:         );
 1828:         &js_escape(\%js_lt);
 1829:         my $showfile_js = &show_crsfiles_js();
 1830:         $browse_or_search = <<"END";
 1831: 
 1832:     $showfile_js
 1833: 
 1834:     function toggleChooser(form,element,titleid,only,search) {
 1835:         var disp = 'none';
 1836:         if (document.getElementById('chooser_'+element)) {
 1837:             var curr = document.getElementById('chooser_'+element).style.display;
 1838:             if (curr == 'none') {
 1839:                 disp='inline';
 1840:                 if (form.elements['chooser_'+element].length) {
 1841:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1842:                         form.elements['chooser_'+element][i].checked = false;
 1843:                     }
 1844:                 }
 1845:                 toggleResImport(form,element);
 1846:             }
 1847:             document.getElementById('chooser_'+element).style.display = disp;
 1848:             var dirsel = '';
 1849:             var filesel = '';
 1850:             if (document.getElementById('chooser_'+element+'_crsres')) {
 1851:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
 1852:                 if (currcrsres == 'none') {
 1853:                     dirsel = 'coursepath_'+element;
 1854:                     var filesel = 'coursefile_'+element;
 1855:                     var include;
 1856:                     if (document.getElementById('crsres_include_'+element)) {
 1857:                         include = document.getElementById('crsres_include_'+element).value;
 1858:                     }
 1859:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
 1860:                 }
 1861:             }
 1862:             if (document.getElementById('chooser_'+element+'_upload')) {
 1863:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
 1864:                 if (currcrsupload == 'none') {
 1865:                     dirsel = 'crsauthorpath_'+element;
 1866:                     filesel = '';
 1867:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
 1868:                 }
 1869:             }
 1870:         }
 1871:     }
 1872: 
 1873:     function toggleCrsFile(form,element) {
 1874:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1875:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1876:             if (curr == 'none') {
 1877:                 if (document.getElementById('coursepath_'+element)) {
 1878:                     var numdirs;
 1879:                     if (document.getElementById('coursepath_'+element).length) {
 1880:                         numdirs = document.getElementById('coursepath_'+element).length;
 1881:                     }
 1882:                     if ((document.getElementById('hascrsres_'+element)) &&
 1883:                         (document.getElementById('nocrsres_'+element))) {
 1884:                         if (numdirs) {
 1885:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
 1886:                             document.getElementById('nocrsres_'+element).style.display='none';
 1887:                         } else {
 1888:                             document.getElementById('hascrsres_'+element).style.display='none';
 1889:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
 1890:                         }
 1891:                     }
 1892:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1893:                     if (numdirs > 1) {
 1894:                         var selelem = form.elements['coursefile_'+element];
 1895:                         var i, len = selelem.options.length -1;
 1896:                         if (len >=0) {
 1897:                             for (i = len; i >= 0; i--) {
 1898:                                 selelem.remove(i);
 1899:                             }
 1900:                             selelem.options[0] = new Option('','');
 1901:                         }
 1902:                     }
 1903:                 }
 1904:             }
 1905:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1906:         }
 1907:         if (document.getElementById('chooser_'+element+'_upload')) {
 1908:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1909:             if (document.getElementById('uploadcrsres_'+element)) {
 1910:                 document.getElementById('uploadcrsres_'+element).value = '';
 1911:             }
 1912:         }
 1913:         return;
 1914:     }
 1915: 
 1916:     function toggleCrsUpload(form,element) {
 1917:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1918:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1919:         }
 1920:         if (document.getElementById('chooser_'+element+'_upload')) {
 1921:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1922:             if (curr == 'none') {
 1923:                 form.elements['newsubdir_'+element][0].checked = true;
 1924:                 toggleNewsubdir(form,element);
 1925:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1926:                 if (document.getElementById('uploadcrsres_'+element)) {
 1927:                     document.getElementById('uploadcrsres_'+element).value = '';
 1928:                 }
 1929:             }
 1930:         }
 1931:         return;
 1932:     }
 1933: 
 1934:     function toggleResImport(form,element) {
 1935:         var choices = new Array('crsres','upload');
 1936:         for (var i=0; i<choices.length; i++) {
 1937:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1938:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1939:             }
 1940:         }
 1941:     }
 1942: 
 1943:     function toggleNewsubdir(form,element) {
 1944:         var newsub = form.elements['newsubdir_'+element];
 1945:         if (newsub) {
 1946:             if (newsub.length) {
 1947:                 for (var j=0; j<newsub.length; j++) {
 1948:                     if (newsub[j].checked) {
 1949:                         if (document.getElementById('newsubdirname_'+element)) {
 1950:                             if (newsub[j].value == '1') {
 1951:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1952:                                 if (document.getElementById('newsubdir_'+element)) {
 1953:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1954:                                 }
 1955:                             } else {
 1956:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1957:                                 document.getElementById('newsubdirname_'+element).value = "";
 1958:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1959:                             }
 1960:                         }
 1961:                         break; 
 1962:                     }
 1963:                 }
 1964:             }
 1965:         }
 1966:     }
 1967: 
 1968:     function updateCrsFile(form,element) {
 1969:         var directory = form.elements['coursepath_'+element];
 1970:         var filename = form.elements['coursefile_'+element];
 1971:         var path = directory.options[directory.selectedIndex].value;
 1972:         var file = filename.options[filename.selectedIndex].value;
 1973:         if (file != '') {
 1974:             form.elements[element].value = '$respath';
 1975:             if (path == '/') {
 1976:                 form.elements[element].value += file;
 1977:             } else {
 1978:                 form.elements[element].value += path+'/'+file;
 1979:             }
 1980:             unClean();
 1981:             if (document.getElementById('previewimg_'+element)) {
 1982:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1983:                 var newsrc = document.getElementById('previewimg_'+element).src; 
 1984:             }
 1985:             if (document.getElementById('showimg_'+element)) {
 1986:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1987:             }
 1988:         }
 1989:         toggleChooser(form,element);
 1990:         return;
 1991:     }
 1992: 
 1993:     function uploadDone(suffix,name) {
 1994:         if (name) {
 1995: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1996:             unClean();
 1997:             toggleChooser(document.forms["lonhomework"],suffix);
 1998:         }
 1999:     }
 2000: 
 2001: \$(document).ready(function(){
 2002: 
 2003:     \$(document).delegate('form :submit', 'click', function( event ) {
 2004:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 2005:             var buttonId = this.id;
 2006:             var suffix = buttonId.toString();
 2007:             suffix = suffix.replace(/^crsupload_/,'');
 2008:             event.preventDefault();
 2009:             document.lonhomework.target = 'crsupload_target_'+suffix;
 2010:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 2011:             \$(this.form).submit();
 2012:             document.lonhomework.target = '';
 2013:             if (document.getElementById('crsuploadto_'+suffix)) {
 2014:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 2015:             }
 2016:             return false;
 2017:         }
 2018:     });
 2019: });
 2020: END
 2021:     }
 2022:     return <<"COLORFULEDIT"
 2023: <script type="text/javascript">
 2024: // <![CDATA[>
 2025:     function fold_box(curDepth, lastresource){
 2026: 
 2027:     // we need a list because there can be several blocks you need to fold in one tag
 2028:         var block = document.getElementsByName('foldblock_'+curDepth);
 2029:     // but there is only one folding button per tag
 2030:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 2031: 
 2032:         if(block.item(0).style.display == 'none'){
 2033: 
 2034:             foldbutton.value = '@{[&mt("Hide")]}';
 2035:             for (i = 0; i < block.length; i++){
 2036:                 block.item(i).style.display = '';
 2037:             }
 2038:         }else{
 2039: 
 2040:             foldbutton.value = '@{[&mt("Show")]}';
 2041:             for (i = 0; i < block.length; i++){
 2042:                 // block.item(i).style.visibility = 'collapse';
 2043:                 block.item(i).style.display = 'none';
 2044:             }
 2045:         };
 2046:         saveState(lastresource);
 2047:     }
 2048: 
 2049:     function saveState (lastresource) {
 2050: 
 2051:         var tag_list = getTagList();
 2052:         if(tag_list != null){
 2053:             var timestamp = new Date().getTime();
 2054:             var key = lastresource;
 2055: 
 2056:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 2057:             // starting with timestamp
 2058:             var value = timestamp+';';
 2059: 
 2060:             // building the list of key-value pairs
 2061:             for(var i = 0; i < tag_list.length; i++){
 2062:                 value += tag_list[i]+',';
 2063:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 2064:             }
 2065: 
 2066:             // only iterate whole storage if nothing to override
 2067:             if(localStorage.getItem(key) == null){        
 2068: 
 2069:                 // prevent storage from growing large
 2070:                 if(localStorage.length > 50){
 2071:                     var regex_getTimestamp = /^(?:\d)+;/;
 2072:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2073:                     var oldest_key;
 2074:                     
 2075:                     for(var i = 1; i < localStorage.length; i++){
 2076:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2077:                             oldest_key = localStorage.key(i);
 2078:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2079:                         }
 2080:                     }
 2081:                     localStorage.removeItem(oldest_key);
 2082:                 }
 2083:             }
 2084:             localStorage.setItem(key,value);
 2085:         }
 2086:     }
 2087: 
 2088:     // restore folding status of blocks (on page load)
 2089:     function restoreState (lastresource) {
 2090:         if(localStorage.getItem(lastresource) != null){
 2091:             var key = lastresource;
 2092:             var value = localStorage.getItem(key);
 2093:             var regex_delTimestamp = /^\d+;/;
 2094: 
 2095:             value.replace(regex_delTimestamp, '');
 2096: 
 2097:             var valueArr = value.split(';');
 2098:             var pairs;
 2099:             var elements;
 2100:             for (var i = 0; i < valueArr.length; i++){
 2101:                 pairs = valueArr[i].split(',');
 2102:                 elements = document.getElementsByName(pairs[0]);
 2103: 
 2104:                 for (var j = 0; j < elements.length; j++){  
 2105:                     elements[j].style.display = pairs[1];
 2106:                     if (pairs[1] == "none"){
 2107:                         var regex_id = /([_\\d]+)\$/;
 2108:                         regex_id.exec(pairs[0]);
 2109:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2110:                     }
 2111:                 }
 2112:             }
 2113:         }
 2114:     }
 2115: 
 2116:     function getTagList () {
 2117:         
 2118:         var stringToSearch = document.lonhomework.innerHTML;
 2119: 
 2120:         var ret = new Array();
 2121:         var regex_findBlock = /(foldblock_.*?)"/g;
 2122:         var tag_list = stringToSearch.match(regex_findBlock);
 2123: 
 2124:         if(tag_list != null){
 2125:             for(var i = 0; i < tag_list.length; i++){            
 2126:                 ret.push(tag_list[i].replace(/"/, ''));
 2127:             }
 2128:         }
 2129:         return ret;
 2130:     }
 2131: 
 2132:     function saveScrollPosition (resource) {
 2133:         var tag_list = getTagList();
 2134: 
 2135:         // we dont always want to jump to the first block
 2136:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2137:         if(\$(window).scrollTop() > 170){
 2138:             if(tag_list != null){
 2139:                 var result;
 2140:                 for(var i = 0; i < tag_list.length; i++){
 2141:                     if(isElementInViewport(tag_list[i])){
 2142:                         result += tag_list[i]+';';
 2143:                     }
 2144:                 }
 2145:                 sessionStorage.setItem('anchor_'+resource, result);
 2146:             }
 2147:         } else {
 2148:             // we dont need to save zero, just delete the item to leave everything tidy
 2149:             sessionStorage.removeItem('anchor_'+resource);
 2150:         }
 2151:     }
 2152: 
 2153:     function restoreScrollPosition(resource){
 2154: 
 2155:         var elem = sessionStorage.getItem('anchor_'+resource);
 2156:         if(elem != null){
 2157:             var tag_list = elem.split(';');
 2158:             var elem_list;
 2159: 
 2160:             for(var i = 0; i < tag_list.length; i++){
 2161:                 elem_list = document.getElementsByName(tag_list[i]);
 2162:                 
 2163:                 if(elem_list.length > 0){
 2164:                     elem = elem_list[0];
 2165:                     break;
 2166:                 }
 2167:             }
 2168:             elem.scrollIntoView();
 2169:         }
 2170:     }
 2171: 
 2172:     function isElementInViewport(el) {
 2173: 
 2174:         // change to last element instead of first
 2175:         var elem = document.getElementsByName(el);
 2176:         var rect = elem[0].getBoundingClientRect();
 2177: 
 2178:         return (
 2179:             rect.top >= 0 &&
 2180:             rect.left >= 0 &&
 2181:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2182:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2183:         );
 2184:     }
 2185:     
 2186:     function autosize(depth){
 2187:         var cmInst = window['cm'+depth];
 2188:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2189: 
 2190:         // is fixed size, switching to dynamic
 2191:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2192:             cmInst.setSize("","auto");
 2193:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2194:             sessionStorage.setItem("autosized_"+depth, "yes");
 2195: 
 2196:         // is dynamic size, switching to fixed
 2197:         } else {
 2198:             cmInst.setSize("","300px");
 2199:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2200:             sessionStorage.removeItem("autosized_"+depth);
 2201:         }
 2202:     }
 2203: 
 2204: $browse_or_search
 2205: 
 2206: // ]]>
 2207: </script>
 2208: COLORFULEDIT
 2209: }
 2210: 
 2211: sub xmleditor_js {
 2212:     return <<XMLEDIT
 2213: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2214: <script type="text/javascript">
 2215: // <![CDATA[>
 2216: 
 2217:     function saveScrollPosition (resource) {
 2218: 
 2219:         var scrollPos = \$(window).scrollTop();
 2220:         sessionStorage.setItem(resource,scrollPos);
 2221:     }
 2222: 
 2223:     function restoreScrollPosition(resource){
 2224: 
 2225:         var scrollPos = sessionStorage.getItem(resource);
 2226:         \$(window).scrollTop(scrollPos);
 2227:     }
 2228: 
 2229:     // unless internet explorer
 2230:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2231: 
 2232:         \$(document).ready(function() {
 2233:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2234:         });
 2235:     }
 2236: 
 2237:     // inserts text at cursor position into codemirror (xml editor only)
 2238:     function insertText(text){
 2239:         cm.focus();
 2240:         var curPos = cm.getCursor();
 2241:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2242:     }
 2243: // ]]>
 2244: </script>
 2245: XMLEDIT
 2246: }
 2247: 
 2248: sub insert_folding_button {
 2249:     my $curDepth = $Apache::lonxml::curdepth;
 2250:     my $lastresource = $env{'request.ambiguous'};
 2251: 
 2252:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2253:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2254: }
 2255: 
 2256: sub crsauthor_url {
 2257:     my ($url) = @_;
 2258:     if ($url eq '') {
 2259:         $url = $ENV{'REQUEST_URI'};
 2260:     }
 2261:     my ($cnum,$cdom);
 2262:     if ($env{'request.course.id'}) {
 2263:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2264:         if ($audom ne '' && $auname ne '') {
 2265:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2266:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2267:                 $cnum = $auname;
 2268:                 $cdom = $audom;
 2269:             }
 2270:         }
 2271:     }
 2272:     return ($cnum,$cdom);
 2273: }
 2274: 
 2275: sub import_crsauthor_form {
 2276:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2277:     return (0) unless ($env{'request.course.id'});
 2278:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2279:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2280:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2281:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2282:     my @ids=&Apache::lonnet::current_machine_ids();
 2283:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
 2284: 
 2285:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2286:         $is_home = 1;
 2287:     }
 2288:     $toppath = "/priv/$cdom/$cnum";
 2289:     my $nonemptydir = 1;
 2290:     my $js_only;
 2291:     if ($only) {
 2292:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
 2293:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
 2294:     }
 2295:     $exclude = &Apache::lonnet::priv_exclude();
 2296:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
 2297:     my $numdirs = scalar(keys(%files));
 2298:     my %lt = &Apache::lonlocal::texthash (
 2299:         fnam => 'Filename',
 2300:         dire => 'Directory',
 2301:         se   => 'Select',
 2302:     );
 2303:     $output = $lt{'dire'}.':&nbsp;'.
 2304:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
 2305:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
 2306:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
 2307:     if ($files{'/'}) {
 2308:         $output .= '<option value="/">/</option>'."\n";
 2309:     }
 2310:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2311:         next if ($key eq '/');
 2312:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
 2313:     }
 2314:     $output .= '</select><br />'."\n".
 2315:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
 2316:                '<option value="" selected="selected"></option>'."\n".
 2317:                '</select>'."\n".
 2318:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
 2319:     return ($numdirs,$output);
 2320: }
 2321: 
 2322: sub show_crsfiles_js {
 2323:     my $excluderef = &Apache::lonnet::priv_exclude();
 2324:     my $se = &js_escape(&mt('Select'));
 2325:     my $exclude;
 2326:     if (ref($excluderef) eq 'HASH') {
 2327:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
 2328:     }
 2329:     my $js = <<"END";
 2330: 
 2331: 
 2332:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
 2333:         var relpath = '';
 2334:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2335:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
 2336:             if (currdir == '') {
 2337:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2338:                     selelem = form.elements[filesel];
 2339:                     var j, numfiles = selelem.options.length -1;
 2340:                     if (numfiles >=0) {
 2341:                         for (j = numfiles; j >= 0; j--) {
 2342:                             selelem.remove(j);
 2343:                         }
 2344:                     }
 2345:                     if (selelem.options.length == 0) {
 2346:                         selelem.options[selelem.options.length] = new Option('','');
 2347:                         selelem.selectedIndex = 0;
 2348:                     }
 2349:                 }
 2350:                 return;
 2351:             } else {
 2352:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
 2353:             }
 2354:         }
 2355:         var http = new XMLHttpRequest();
 2356:         var url = "/adm/courseauthor";
 2357:         var crsrole = "$env{'request.role'}";
 2358:         var exclude = '';
 2359:         if (exc) {
 2360:             exclude = '$exclude';
 2361:         }
 2362:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
 2363:         http.open("POST", url, true);
 2364:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 2365:         http.onreadystatechange = function() {
 2366:             if (http.readyState == 4 && http.status == 200) {
 2367:                 var data = JSON.parse(http.responseText);
 2368:                 var selelem;
 2369:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2370:                     if (Array.isArray(data.dirs)) {
 2371:                         selelem = form.elements[dirsel];
 2372:                         var i, numdirs = selelem.options.length -1;
 2373:                         if (numdirs >=0) {
 2374:                             for (i = numdirs; i >= 0; i--) {
 2375:                                 selelem.remove(i);
 2376:                             }
 2377:                         }
 2378:                         var len = data.dirs.length;
 2379:                         if (len) {
 2380:                             selelem.options[selelem.options.length] = new Option('$se','');
 2381:                             var j;
 2382:                             for (j = 0; j < len; j++) {
 2383:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
 2384:                             }
 2385:                             selelem.selectedIndex = 0;
 2386:                         }
 2387:                         if (!setfile) {
 2388:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2389:                                 selelem = form.elements[filesel];
 2390:                                 var j, numfiles = selelem.options.length -1;
 2391:                                 if (numfiles >=0) {
 2392:                                     for (j = numfiles; j >= 0; j--) {
 2393:                                         selelem.remove(j);
 2394:                                     }
 2395:                                 }
 2396:                                 if (selelem.options.length == 0) {
 2397:                                     selelem.options[selelem.options.length] = new Option('','');
 2398:                                     selelem.selectedIndex = 0;
 2399:                                 }
 2400:                             }
 2401:                         }
 2402:                     }
 2403:                 }
 2404:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2405:                     selelem = form.elements[filesel];
 2406:                     var i, numfiles = selelem.options.length -1;
 2407:                     if (numfiles >=0) {
 2408:                         for (i = numfiles; i >= 0; i--) {
 2409:                             selelem.remove(i);
 2410:                         }
 2411:                     }
 2412:                     var x;
 2413:                     for (x in data.files) {
 2414:                         if (Array.isArray(data.files[x])) {
 2415:                             if (data.files[x].length > 1) {
 2416:                                 selelem.options[selelem.options.length] = new Option('$se','');
 2417:                             }
 2418:                             var len = data.files[x].length;
 2419:                             if (len) {
 2420:                                 var k;
 2421:                                 for (k = 0; k < len; k++) {
 2422:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
 2423:                                 }
 2424:                                 selelem.selectedIndex = 0;
 2425:                             }
 2426:                         }
 2427:                     }
 2428:                     if (selelem.options.length == 0) {
 2429:                         selelem.options[selelem.options.length] = new Option('','');
 2430:                         selelem.selectedIndex = 0;
 2431:                     }
 2432:                 }
 2433:             }
 2434:         }
 2435:         http.send(params);
 2436:     }
 2437: END
 2438: }
 2439: 
 2440: =pod
 2441: 
 2442: =item * &iframe_wrapper_headjs()
 2443: 
 2444: emits javascript containing two global vars to facilitate handling of resizing
 2445: by code in iframe_wrapper_resizejs() used when an iframe is present in a page
 2446: with standard LON-CAPA menus.
 2447: 
 2448: =cut
 2449: 
 2450: #
 2451: # Where iframe is in use, if window.onload() executes before the custom resize function
 2452: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
 2453: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
 2454: # do not obscure the Functions menu.
 2455: #
 2456: 
 2457: sub iframe_wrapper_headjs {
 2458:     return <<"ENDJS";
 2459: <script type="text/javascript">
 2460: // <![CDATA[
 2461: var LCnotready = 0;
 2462: var LCresizedef = 0;
 2463: // ]]>
 2464: </script>
 2465: 
 2466: ENDJS
 2467: 
 2468: }
 2469: 
 2470: =pod
 2471: 
 2472: =item * &iframe_wrapper_resizejs()
 2473: 
 2474: emits javascript used to handle resizing for a page containing
 2475: an iframe, to ensure that the iframe does not obscure any
 2476: standard LON-CAPA menu items.
 2477: 
 2478: =back
 2479: 
 2480: =cut
 2481: 
 2482: #
 2483: # jQuery to use when iframe is in use and a page resize occurs.
 2484: # This script will ensure that the iframe does not obscure any
 2485: # standard LON-CAPA inline menus (primary, secondary, and/or
 2486: # breadcrumbs and Functions menus. Expects javascript from
 2487: # &iframe_wrapper_headjs() to be in head portion of the web page,
 2488: # e.g., by inclusion in second arg passed to &start_page().
 2489: #
 2490: 
 2491: sub iframe_wrapper_resizejs {
 2492:     my $offset = 5;
 2493:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
 2494:     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
 2495:         $offset = 0;
 2496:     }
 2497:     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
 2498:     \$(document).ready( function() {
 2499:         \$(window).unbind('resize').resize(function(){
 2500:             var header = null;
 2501:             var offset = $offset;
 2502:             var height = 0;
 2503:             var hdrtop = 0;
 2504:             if (\$('div.LC_menus_content:first').length) {
 2505:                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
 2506:                     header = \$('div.LC_menus_content:first');
 2507:                     offset = 12;
 2508:                 }
 2509:             } else if (\$('div.LC_head_subbox:first').length) {
 2510:                 header = \$('div.LC_head_subbox:first');
 2511:                 offset = 9;
 2512:             } else {
 2513:                 if (\$('#LC_breadcrumbs').length) {
 2514:                     header = \$('#LC_breadcrumbs');
 2515:                 }
 2516:             }
 2517:             if (header != null && header.length) {
 2518:                 height = header.height();
 2519:                 hdrtop = header.position().top;
 2520:             }
 2521:             var pos = height + hdrtop + offset;
 2522:             \$('.LC_iframecontainer').css('top', pos);
 2523:         });
 2524:         LCresizedef = 1;
 2525:         if (LCnotready == 1) {
 2526:             LCnotready = 0;
 2527:             \$(window).trigger('resize');
 2528:         }
 2529:     });
 2530:     window.onload = function(){
 2531:          if (LCresizedef) {
 2532:              LCnotready = 0;
 2533:              \$(window).trigger('resize');
 2534:          } else {
 2535:              LCnotready = 1;
 2536:          }
 2537:     };
 2538: SCRIPT
 2539: 
 2540: }
 2541: 
 2542: =pod
 2543: 
 2544: =head1 Excel and CSV file utility routines
 2545: 
 2546: =cut
 2547: 
 2548: ###############################################################
 2549: ###############################################################
 2550: 
 2551: =pod
 2552: 
 2553: =over 4
 2554: 
 2555: =item * &csv_translate($text) 
 2556: 
 2557: Translate $text to allow it to be output as a 'comma separated values' 
 2558: format.
 2559: 
 2560: =cut
 2561: 
 2562: ###############################################################
 2563: ###############################################################
 2564: sub csv_translate {
 2565:     my $text = shift;
 2566:     $text =~ s/\"/\"\"/g;
 2567:     $text =~ s/\n/ /g;
 2568:     return $text;
 2569: }
 2570: 
 2571: ###############################################################
 2572: ###############################################################
 2573: 
 2574: =pod
 2575: 
 2576: =item * &define_excel_formats()
 2577: 
 2578: Define some commonly used Excel cell formats.
 2579: 
 2580: Currently supported formats:
 2581: 
 2582: =over 4
 2583: 
 2584: =item header
 2585: 
 2586: =item bold
 2587: 
 2588: =item h1
 2589: 
 2590: =item h2
 2591: 
 2592: =item h3
 2593: 
 2594: =item h4
 2595: 
 2596: =item i
 2597: 
 2598: =item date
 2599: 
 2600: =back
 2601: 
 2602: Inputs: $workbook
 2603: 
 2604: Returns: $format, a hash reference.
 2605: 
 2606: 
 2607: =cut
 2608: 
 2609: ###############################################################
 2610: ###############################################################
 2611: sub define_excel_formats {
 2612:     my ($workbook) = @_;
 2613:     my $format;
 2614:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2615:                                                 bottom    => 1,
 2616:                                                 align     => 'center');
 2617:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2618:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2619:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2620:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2621:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2622:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2623:     $format->{'date'} = $workbook->add_format(num_format=>
 2624:                                             'mm/dd/yyyy hh:mm:ss');
 2625:     return $format;
 2626: }
 2627: 
 2628: ###############################################################
 2629: ###############################################################
 2630: 
 2631: =pod
 2632: 
 2633: =item * &create_workbook()
 2634: 
 2635: Create an Excel worksheet.  If it fails, output message on the
 2636: request object and return undefs.
 2637: 
 2638: Inputs: Apache request object
 2639: 
 2640: Returns (undef) on failure, 
 2641:     Excel worksheet object, scalar with filename, and formats 
 2642:     from &Apache::loncommon::define_excel_formats on success
 2643: 
 2644: =cut
 2645: 
 2646: ###############################################################
 2647: ###############################################################
 2648: sub create_workbook {
 2649:     my ($r) = @_;
 2650:         #
 2651:     # Create the excel spreadsheet
 2652:     my $filename = '/prtspool/'.
 2653:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2654:         time.'_'.rand(1000000000).'.xls';
 2655:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2656:     if (! defined($workbook)) {
 2657:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2658:         $r->print(
 2659:             '<p class="LC_error">'
 2660:            .&mt('Problems occurred in creating the new Excel file.')
 2661:            .' '.&mt('This error has been logged.')
 2662:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2663:            .'</p>'
 2664:         );
 2665:         return (undef);
 2666:     }
 2667:     #
 2668:     $workbook->set_tempdir(LONCAPA::tempdir());
 2669:     #
 2670:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2671:     return ($workbook,$filename,$format);
 2672: }
 2673: 
 2674: ###############################################################
 2675: ###############################################################
 2676: 
 2677: =pod
 2678: 
 2679: =item * &create_text_file()
 2680: 
 2681: Create a file to write to and eventually make available to the user.
 2682: If file creation fails, outputs an error message on the request object and 
 2683: return undefs.
 2684: 
 2685: Inputs: Apache request object, and file suffix
 2686: 
 2687: Returns (undef) on failure, 
 2688:     Filehandle and filename on success.
 2689: 
 2690: =cut
 2691: 
 2692: ###############################################################
 2693: ###############################################################
 2694: sub create_text_file {
 2695:     my ($r,$suffix) = @_;
 2696:     if (! defined($suffix)) { $suffix = 'txt'; };
 2697:     my $fh;
 2698:     my $filename = '/prtspool/'.
 2699:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2700:         time.'_'.rand(1000000000).'.'.$suffix;
 2701:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2702:     if (! defined($fh)) {
 2703:         $r->log_error("Couldn't open $filename for output $!");
 2704:         $r->print(
 2705:             '<p class="LC_error">'
 2706:            .&mt('Problems occurred in creating the output file.')
 2707:            .' '.&mt('This error has been logged.')
 2708:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2709:            .'</p>'
 2710:         );
 2711:     }
 2712:     return ($fh,$filename)
 2713: }
 2714: 
 2715: 
 2716: =pod 
 2717: 
 2718: =back
 2719: 
 2720: =cut
 2721: 
 2722: ###############################################################
 2723: ##        Home server <option> list generating code          ##
 2724: ###############################################################
 2725: 
 2726: # ------------------------------------------
 2727: 
 2728: sub domain_select {
 2729:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2730:     my @possdoms;
 2731:     if (ref($incdoms) eq 'ARRAY') {
 2732:         @possdoms = @{$incdoms};
 2733:     } else {
 2734:         @possdoms = &Apache::lonnet::all_domains();
 2735:     }
 2736: 
 2737:     my %domains=map { 
 2738: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2739:     } @possdoms;
 2740: 
 2741:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2742:         foreach my $dom (@{$excdoms}) {
 2743:             delete($domains{$dom});
 2744:         }
 2745:     }
 2746: 
 2747:     if ($multiple) {
 2748: 	$domains{''}=&mt('Any domain');
 2749: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2750: 	return &multiple_select_form($name,$value,4,\%domains);
 2751:     } else {
 2752: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2753: 	return &select_form($name,$value,\%domains);
 2754:     }
 2755: }
 2756: 
 2757: #-------------------------------------------
 2758: 
 2759: =pod
 2760: 
 2761: =head1 Routines for form select boxes
 2762: 
 2763: =over 4
 2764: 
 2765: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2766: 
 2767: Returns a string containing a <select> element int multiple mode
 2768: 
 2769: 
 2770: Args:
 2771:   $name - name of the <select> element
 2772:   $value - scalar or array ref of values that should already be selected
 2773:   $size - number of rows long the select element is
 2774:   $hash - the elements should be 'option' => 'shown text'
 2775:           (shown text should already have been &mt())
 2776:   $order - (optional) array ref of the order to show the elements in
 2777: 
 2778: =cut
 2779: 
 2780: #-------------------------------------------
 2781: sub multiple_select_form {
 2782:     my ($name,$value,$size,$hash,$order)=@_;
 2783:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2784:     my $output='';
 2785:     if (! defined($size)) {
 2786:         $size = 4;
 2787:         if (scalar(keys(%$hash))<4) {
 2788:             $size = scalar(keys(%$hash));
 2789:         }
 2790:     }
 2791:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2792:     my @order;
 2793:     if (ref($order) eq 'ARRAY')  {
 2794:         @order = @{$order};
 2795:     } else {
 2796:         @order = sort(keys(%$hash));
 2797:     }
 2798:     if (exists($$hash{'select_form_order'})) {
 2799:         @order = @{$$hash{'select_form_order'}};
 2800:     }
 2801:         
 2802:     foreach my $key (@order) {
 2803:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2804:         $output.='selected="selected" ' if ($selected{$key});
 2805:         $output.='>'.$hash->{$key}."</option>\n";
 2806:     }
 2807:     $output.="</select>\n";
 2808:     return $output;
 2809: }
 2810: 
 2811: #-------------------------------------------
 2812: 
 2813: =pod
 2814: 
 2815: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2816: 
 2817: Returns a string containing a <select name='$name' size='1'> form to 
 2818: allow a user to select options from a ref to a hash containing:
 2819: option_name => displayed text. An optional $onchange can include
 2820: a javascript onchange item, e.g., onchange="this.form.submit();".
 2821: An optional arg -- $readonly -- if true will cause the select form
 2822: to be disabled, e.g., for the case where an instructor has a section-
 2823: specific role, and is viewing/modifying parameters. 
 2824: 
 2825: See lonrights.pm for an example invocation and use.
 2826: 
 2827: =cut
 2828: 
 2829: #-------------------------------------------
 2830: sub select_form {
 2831:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2832:     return unless (ref($hashref) eq 'HASH');
 2833:     if ($onchange) {
 2834:         $onchange = ' onchange="'.$onchange.'"';
 2835:     }
 2836:     my $disabled;
 2837:     if ($readonly) {
 2838:         $disabled = ' disabled="disabled"';
 2839:     }
 2840:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2841:     my @keys;
 2842:     if (exists($hashref->{'select_form_order'})) {
 2843: 	@keys=@{$hashref->{'select_form_order'}};
 2844:     } else {
 2845: 	@keys=sort(keys(%{$hashref}));
 2846:     }
 2847:     foreach my $key (@keys) {
 2848:         $selectform.=
 2849: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2850:             ($key eq $def ? 'selected="selected" ' : '').
 2851:                 ">".$hashref->{$key}."</option>\n";
 2852:     }
 2853:     $selectform.="</select>";
 2854:     return $selectform;
 2855: }
 2856: 
 2857: # For display filters
 2858: 
 2859: sub display_filter {
 2860:     my ($context) = @_;
 2861:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2862:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2863:     my $phraseinput = 'hidden';
 2864:     my $includeinput = 'hidden';
 2865:     my ($checked,$includetypestext);
 2866:     if ($env{'form.displayfilter'} eq 'containing') {
 2867:         $phraseinput = 'text'; 
 2868:         if ($context eq 'parmslog') {
 2869:             $includeinput = 'checkbox';
 2870:             if ($env{'form.includetypes'}) {
 2871:                 $checked = ' checked="checked"';
 2872:             }
 2873:             $includetypestext = &mt('Include parameter types');
 2874:         }
 2875:     } else {
 2876:         $includetypestext = '&nbsp;';
 2877:     }
 2878:     my ($additional,$secondid,$thirdid);
 2879:     if ($context eq 'parmslog') {
 2880:         $additional = 
 2881:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2882:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2883:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2884:             '</label>';
 2885:         $secondid = 'includetypes';
 2886:         $thirdid = 'includetypestext';
 2887:     }
 2888:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2889:                                                     '$secondid','$thirdid')";
 2890:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2891: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
 2892: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2893: 	   '</label></span> <span class="LC_nobreak">'.
 2894:            &mt('Filter: [_1]',
 2895: 	   &select_form($env{'form.displayfilter'},
 2896: 			'displayfilter',
 2897: 			{'currentfolder' => 'Current folder/page',
 2898: 			 'containing' => 'Containing phrase',
 2899: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2900: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2901:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2902:                          '" />'.$additional;
 2903: }
 2904: 
 2905: sub display_filter_js {
 2906:     my $includetext = &mt('Include parameter types');
 2907:     return <<"ENDJS";
 2908:   
 2909: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2910:     var firstType = 'hidden';
 2911:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2912:         firstType = 'text';
 2913:     }
 2914:     firstObject = document.getElementById(firstid);
 2915:     if (typeof(firstObject) == 'object') {
 2916:         if (firstObject.type != firstType) {
 2917:             changeInputType(firstObject,firstType);
 2918:         }
 2919:     }
 2920:     if (context == 'parmslog') {
 2921:         var secondType = 'hidden';
 2922:         if (firstType == 'text') {
 2923:             secondType = 'checkbox';
 2924:         }
 2925:         secondObject = document.getElementById(secondid);  
 2926:         if (typeof(secondObject) == 'object') {
 2927:             if (secondObject.type != secondType) {
 2928:                 changeInputType(secondObject,secondType);
 2929:             }
 2930:         }
 2931:         var textItem = document.getElementById(thirdid);
 2932:         var currtext = textItem.innerHTML;
 2933:         var newtext;
 2934:         if (firstType == 'text') {
 2935:             newtext = '$includetext';
 2936:         } else {
 2937:             newtext = '&nbsp;';
 2938:         }
 2939:         if (currtext != newtext) {
 2940:             textItem.innerHTML = newtext;
 2941:         }
 2942:     }
 2943:     return;
 2944: }
 2945: 
 2946: function changeInputType(oldObject,newType) {
 2947:     var newObject = document.createElement('input');
 2948:     newObject.type = newType;
 2949:     if (oldObject.size) {
 2950:         newObject.size = oldObject.size;
 2951:     }
 2952:     if (oldObject.value) {
 2953:         newObject.value = oldObject.value;
 2954:     }
 2955:     if (oldObject.name) {
 2956:         newObject.name = oldObject.name;
 2957:     }
 2958:     if (oldObject.id) {
 2959:         newObject.id = oldObject.id;
 2960:     }
 2961:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2962:     return;
 2963: }
 2964: 
 2965: ENDJS
 2966: }
 2967: 
 2968: sub gradeleveldescription {
 2969:     my $gradelevel=shift;
 2970:     my %gradelevels=(0 => 'Not specified',
 2971: 		     1 => 'Grade 1',
 2972: 		     2 => 'Grade 2',
 2973: 		     3 => 'Grade 3',
 2974: 		     4 => 'Grade 4',
 2975: 		     5 => 'Grade 5',
 2976: 		     6 => 'Grade 6',
 2977: 		     7 => 'Grade 7',
 2978: 		     8 => 'Grade 8',
 2979: 		     9 => 'Grade 9',
 2980: 		     10 => 'Grade 10',
 2981: 		     11 => 'Grade 11',
 2982: 		     12 => 'Grade 12',
 2983: 		     13 => 'Grade 13',
 2984: 		     14 => '100 Level',
 2985: 		     15 => '200 Level',
 2986: 		     16 => '300 Level',
 2987: 		     17 => '400 Level',
 2988: 		     18 => 'Graduate Level');
 2989:     return &mt($gradelevels{$gradelevel});
 2990: }
 2991: 
 2992: sub select_level_form {
 2993:     my ($deflevel,$name)=@_;
 2994:     unless ($deflevel) { $deflevel=0; }
 2995:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2996:     for (my $i=0; $i<=18; $i++) {
 2997:         $selectform.="<option value=\"$i\" ".
 2998:             ($i==$deflevel ? 'selected="selected" ' : '').
 2999:                 ">".&gradeleveldescription($i)."</option>\n";
 3000:     }
 3001:     $selectform.="</select>";
 3002:     return $selectform;
 3003: }
 3004: 
 3005: #-------------------------------------------
 3006: 
 3007: =pod
 3008: 
 3009: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 3010: 
 3011: Returns a string containing a <select name='$name' size='1'> form to 
 3012: allow a user to select the domain to preform an operation in.  
 3013: See loncreateuser.pm for an example invocation and use.
 3014: 
 3015: If the $includeempty flag is set, it also includes an empty choice ("no domain
 3016: selected");
 3017: 
 3018: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 3019: 
 3020: 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.
 3021: 
 3022: The optional $incdoms is a reference to an array of domains which will be the only available options.
 3023: 
 3024: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 3025: 
 3026: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 3027: 
 3028: =cut
 3029: 
 3030: #-------------------------------------------
 3031: sub select_dom_form {
 3032:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 3033:     if ($onchange) {
 3034:         $onchange = ' onchange="'.$onchange.'"';
 3035:     }
 3036:     if ($disabled) {
 3037:         $disabled = ' disabled="disabled"';
 3038:     }
 3039:     my (@domains,%exclude);
 3040:     if (ref($incdoms) eq 'ARRAY') {
 3041:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 3042:     } else {
 3043:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 3044:     }
 3045:     if ($includeempty) { @domains=('',@domains); }
 3046:     if (ref($excdoms) eq 'ARRAY') {
 3047:         map { $exclude{$_} = 1; } @{$excdoms}; 
 3048:     }
 3049:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 3050:     foreach my $dom (@domains) {
 3051:         next if ($exclude{$dom});
 3052:         $selectdomain.="<option value=\"$dom\" ".
 3053:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 3054:         if ($showdomdesc) {
 3055:             if ($dom ne '') {
 3056:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 3057:                 if ($domdesc ne '') {
 3058:                     $selectdomain .= ' ('.$domdesc.')';
 3059:                 }
 3060:             } 
 3061:         }
 3062:         $selectdomain .= "</option>\n";
 3063:     }
 3064:     $selectdomain.="</select>";
 3065:     return $selectdomain;
 3066: }
 3067: 
 3068: #-------------------------------------------
 3069: 
 3070: =pod
 3071: 
 3072: =item * &home_server_form_item($domain,$name,$defaultflag)
 3073: 
 3074: input: 4 arguments (two required, two optional) - 
 3075:     $domain - domain of new user
 3076:     $name - name of form element
 3077:     $default - Value of 'default' causes a default item to be first 
 3078:                             option, and selected by default. 
 3079:     $hide - Value of 'hide' causes hiding of the name of the server, 
 3080:                             if 1 server found, or default, if 0 found.
 3081: output: returns 2 items: 
 3082: (a) form element which contains either:
 3083:    (i) <select name="$name">
 3084:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 3085:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 3086:        </select>
 3087:        form item if there are multiple library servers in $domain, or
 3088:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 3089:        if there is only one library server in $domain.
 3090: 
 3091: (b) number of library servers found.
 3092: 
 3093: See loncreateuser.pm for example of use.
 3094: 
 3095: =cut
 3096: 
 3097: #-------------------------------------------
 3098: sub home_server_form_item {
 3099:     my ($domain,$name,$default,$hide) = @_;
 3100:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 3101:     my $result;
 3102:     my $numlib = keys(%servers);
 3103:     if ($numlib > 1) {
 3104:         $result .= '<select name="'.$name.'" />'."\n";
 3105:         if ($default) {
 3106:             $result .= '<option value="default" selected="selected">'.&mt('default').
 3107:                        '</option>'."\n";
 3108:         }
 3109:         foreach my $hostid (sort(keys(%servers))) {
 3110:             $result.= '<option value="'.$hostid.'">'.
 3111: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 3112:         }
 3113:         $result .= '</select>'."\n";
 3114:     } elsif ($numlib == 1) {
 3115:         my $hostid;
 3116:         foreach my $item (keys(%servers)) {
 3117:             $hostid = $item;
 3118:         }
 3119:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 3120:                    $hostid.'" />';
 3121:                    if (!$hide) {
 3122:                        $result .= $hostid.' '.$servers{$hostid};
 3123:                    }
 3124:                    $result .= "\n";
 3125:     } elsif ($default) {
 3126:         $result .= '<input type="hidden" name="'.$name.
 3127:                    '" value="default" />';
 3128:                    if (!$hide) {
 3129:                        $result .= &mt('default');
 3130:                    }
 3131:                    $result .= "\n";
 3132:     }
 3133:     return ($result,$numlib);
 3134: }
 3135: 
 3136: =pod
 3137: 
 3138: =back 
 3139: 
 3140: =cut
 3141: 
 3142: ###############################################################
 3143: ##                  Decoding User Agent                      ##
 3144: ###############################################################
 3145: 
 3146: =pod
 3147: 
 3148: =head1 Decoding the User Agent
 3149: 
 3150: =over 4
 3151: 
 3152: =item * &decode_user_agent()
 3153: 
 3154: Inputs: $r
 3155: 
 3156: Outputs:
 3157: 
 3158: =over 4
 3159: 
 3160: =item * $httpbrowser
 3161: 
 3162: =item * $clientbrowser
 3163: 
 3164: =item * $clientversion
 3165: 
 3166: =item * $clientmathml
 3167: 
 3168: =item * $clientunicode
 3169: 
 3170: =item * $clientos
 3171: 
 3172: =item * $clientmobile
 3173: 
 3174: =item * $clientinfo
 3175: 
 3176: =item * $clientosversion
 3177: 
 3178: =back
 3179: 
 3180: =back 
 3181: 
 3182: =cut
 3183: 
 3184: ###############################################################
 3185: ###############################################################
 3186: sub decode_user_agent {
 3187:     my ($r)=@_;
 3188:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 3189:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 3190:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 3191:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 3192:     my $clientbrowser='unknown';
 3193:     my $clientversion='0';
 3194:     my $clientmathml='';
 3195:     my $clientunicode='0';
 3196:     my $clientmobile=0;
 3197:     my $clientosversion='';
 3198:     for (my $i=0;$i<=$#browsertype;$i++) {
 3199:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 3200: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 3201: 	    $clientbrowser=$bname;
 3202:             $httpbrowser=~/$vreg/i;
 3203: 	    $clientversion=$1;
 3204:             $clientmathml=($clientversion>=$minv);
 3205:             $clientunicode=($clientversion>=$univ);
 3206: 	}
 3207:     }
 3208:     my $clientos='unknown';
 3209:     my $clientinfo;
 3210:     if (($httpbrowser=~/linux/i) ||
 3211:         ($httpbrowser=~/unix/i) ||
 3212:         ($httpbrowser=~/ux/i) ||
 3213:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 3214:     if (($httpbrowser=~/vax/i) ||
 3215:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 3216:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 3217:     if (($httpbrowser=~/mac/i) ||
 3218:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 3219:     if ($httpbrowser=~/win/i) {
 3220:         $clientos='win';
 3221:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 3222:             $clientosversion = $1;
 3223:         }
 3224:     }
 3225:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3226:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3227:         $clientmobile=lc($1);
 3228:     }
 3229:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3230:         $clientinfo = 'firefox-'.$1;
 3231:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3232:         $clientinfo = 'chromeframe-'.$1;
 3233:     }
 3234:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3235:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3236:             $clientosversion);
 3237: }
 3238: 
 3239: ###############################################################
 3240: ##    Authentication changing form generation subroutines    ##
 3241: ###############################################################
 3242: ##
 3243: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3244: ## hash, and have reasonable default values.
 3245: ##
 3246: ##    formname = the name given in the <form> tag.
 3247: #-------------------------------------------
 3248: 
 3249: =pod
 3250: 
 3251: =head1 Authentication Routines
 3252: 
 3253: =over 4
 3254: 
 3255: =item * &authform_xxxxxx()
 3256: 
 3257: The authform_xxxxxx subroutines provide javascript and html forms which 
 3258: handle some of the conveniences required for authentication forms.  
 3259: This is not an optimal method, but it works.  
 3260: 
 3261: =over 4
 3262: 
 3263: =item * authform_header
 3264: 
 3265: =item * authform_authorwarning
 3266: 
 3267: =item * authform_nochange
 3268: 
 3269: =item * authform_kerberos
 3270: 
 3271: =item * authform_internal
 3272: 
 3273: =item * authform_filesystem
 3274: 
 3275: =item * authform_lti
 3276: 
 3277: =back
 3278: 
 3279: See loncreateuser.pm for invocation and use examples.
 3280: 
 3281: =cut
 3282: 
 3283: #-------------------------------------------
 3284: sub authform_header{  
 3285:     my %in = (
 3286:         formname => 'cu',
 3287:         kerb_def_dom => '',
 3288:         @_,
 3289:     );
 3290:     $in{'formname'} = 'document.' . $in{'formname'};
 3291:     my $result='';
 3292: 
 3293: #---------------------------------------------- Code for upper case translation
 3294:     my $Javascript_toUpperCase;
 3295:     unless ($in{kerb_def_dom}) {
 3296:         $Javascript_toUpperCase =<<"END";
 3297:         switch (choice) {
 3298:            case 'krb': currentform.elements[choicearg].value =
 3299:                currentform.elements[choicearg].value.toUpperCase();
 3300:                break;
 3301:            default:
 3302:         }
 3303: END
 3304:     } else {
 3305:         $Javascript_toUpperCase = "";
 3306:     }
 3307: 
 3308:     my $radioval = "'nochange'";
 3309:     if (defined($in{'curr_authtype'})) {
 3310:         if ($in{'curr_authtype'} ne '') {
 3311:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3312:         }
 3313:     }
 3314:     my $argfield = 'null';
 3315:     if (defined($in{'mode'})) {
 3316:         if ($in{'mode'} eq 'modifycourse')  {
 3317:             if (defined($in{'curr_autharg'})) {
 3318:                 if ($in{'curr_autharg'} ne '') {
 3319:                     $argfield = "'$in{'curr_autharg'}'";
 3320:                 }
 3321:             }
 3322:         }
 3323:     }
 3324: 
 3325:     $result.=<<"END";
 3326: var current = new Object();
 3327: current.radiovalue = $radioval;
 3328: current.argfield = $argfield;
 3329: 
 3330: function changed_radio(choice,currentform) {
 3331:     var choicearg = choice + 'arg';
 3332:     // If a radio button in changed, we need to change the argfield
 3333:     if (current.radiovalue != choice) {
 3334:         current.radiovalue = choice;
 3335:         if (current.argfield != null) {
 3336:             currentform.elements[current.argfield].value = '';
 3337:         }
 3338:         if (choice == 'nochange') {
 3339:             current.argfield = null;
 3340:         } else {
 3341:             current.argfield = choicearg;
 3342:             switch(choice) {
 3343:                 case 'krb': 
 3344:                     currentform.elements[current.argfield].value = 
 3345:                         "$in{'kerb_def_dom'}";
 3346:                 break;
 3347:               default:
 3348:                 break;
 3349:             }
 3350:         }
 3351:     }
 3352:     return;
 3353: }
 3354: 
 3355: function changed_text(choice,currentform) {
 3356:     var choicearg = choice + 'arg';
 3357:     if (currentform.elements[choicearg].value !='') {
 3358:         $Javascript_toUpperCase
 3359:         // clear old field
 3360:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3361:             currentform.elements[current.argfield].value = '';
 3362:         }
 3363:         current.argfield = choicearg;
 3364:     }
 3365:     set_auth_radio_buttons(choice,currentform);
 3366:     return;
 3367: }
 3368: 
 3369: function set_auth_radio_buttons(newvalue,currentform) {
 3370:     var numauthchoices = currentform.login.length;
 3371:     if (typeof numauthchoices  == "undefined") {
 3372:         return;
 3373:     } 
 3374:     var i=0;
 3375:     while (i < numauthchoices) {
 3376:         if (currentform.login[i].value == newvalue) { break; }
 3377:         i++;
 3378:     }
 3379:     if (i == numauthchoices) {
 3380:         return;
 3381:     }
 3382:     current.radiovalue = newvalue;
 3383:     currentform.login[i].checked = true;
 3384:     return;
 3385: }
 3386: END
 3387:     return $result;
 3388: }
 3389: 
 3390: sub authform_authorwarning {
 3391:     my $result='';
 3392:     $result='<i>'.
 3393:         &mt('As a general rule, only authors or co-authors should be '.
 3394:             'filesystem authenticated '.
 3395:             '(which allows access to the server filesystem).')."</i>\n";
 3396:     return $result;
 3397: }
 3398: 
 3399: sub authform_nochange {
 3400:     my %in = (
 3401:               formname => 'document.cu',
 3402:               kerb_def_dom => 'MSU.EDU',
 3403:               @_,
 3404:           );
 3405:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3406:     my $result;
 3407:     if (!$authnum) {
 3408:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3409:     } else {
 3410:         $result = '<label>'.&mt('[_1] Do not change login data',
 3411:                   '<input type="radio" name="login" value="nochange" '.
 3412:                   'checked="checked" onclick="'.
 3413:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3414: 	    '</label>';
 3415:     }
 3416:     return $result;
 3417: }
 3418: 
 3419: sub authform_kerberos {
 3420:     my %in = (
 3421:               formname => 'document.cu',
 3422:               kerb_def_dom => 'MSU.EDU',
 3423:               kerb_def_auth => 'krb4',
 3424:               @_,
 3425:               );
 3426:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3427:         $autharg,$jscall,$disabled);
 3428:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3429:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3430:        $check5 = ' checked="checked"';
 3431:     } else {
 3432:        $check4 = ' checked="checked"';
 3433:     }
 3434:     if ($in{'readonly'}) {
 3435:         $disabled = ' disabled="disabled"';
 3436:     }
 3437:     $krbarg = $in{'kerb_def_dom'};
 3438:     if (defined($in{'curr_authtype'})) {
 3439:         if ($in{'curr_authtype'} eq 'krb') {
 3440:             $krbcheck = ' checked="checked"';
 3441:             if (defined($in{'mode'})) {
 3442:                 if ($in{'mode'} eq 'modifyuser') {
 3443:                     $krbcheck = '';
 3444:                 }
 3445:             }
 3446:             if (defined($in{'curr_kerb_ver'})) {
 3447:                 if ($in{'curr_krb_ver'} eq '5') {
 3448:                     $check5 = ' checked="checked"';
 3449:                     $check4 = '';
 3450:                 } else {
 3451:                     $check4 = ' checked="checked"';
 3452:                     $check5 = '';
 3453:                 }
 3454:             }
 3455:             if (defined($in{'curr_autharg'})) {
 3456:                 $krbarg = $in{'curr_autharg'};
 3457:             }
 3458:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3459:                 if (defined($in{'curr_autharg'})) {
 3460:                     $result = 
 3461:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3462:         $in{'curr_autharg'},$krbver);
 3463:                 } else {
 3464:                     $result =
 3465:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3466:                 }
 3467:                 return $result; 
 3468:             }
 3469:         }
 3470:     } else {
 3471:         if ($authnum == 1) {
 3472:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3473:         }
 3474:     }
 3475:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3476:         return;
 3477:     } elsif ($authtype eq '') {
 3478:         if (defined($in{'mode'})) {
 3479:             if ($in{'mode'} eq 'modifycourse') {
 3480:                 if ($authnum == 1) {
 3481:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3482:                 }
 3483:             }
 3484:         }
 3485:     }
 3486:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3487:     if ($authtype eq '') {
 3488:         $authtype = '<input type="radio" name="login" value="krb" '.
 3489:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3490:                     $krbcheck.$disabled.' />';
 3491:     }
 3492:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3493:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3494:          $in{'curr_authtype'} eq 'krb5') ||
 3495:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3496:          $in{'curr_authtype'} eq 'krb4')) {
 3497:         $result .= &mt
 3498:         ('[_1] Kerberos authenticated with domain [_2] '.
 3499:          '[_3] Version 4 [_4] Version 5 [_5]',
 3500:          '<label>'.$authtype,
 3501:          '</label><input type="text" size="10" name="krbarg" '.
 3502:              'value="'.$krbarg.'" '.
 3503:              'onchange="'.$jscall.'"'.$disabled.' />',
 3504:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3505:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3506: 	 '</label>');
 3507:     } elsif ($can_assign{'krb4'}) {
 3508:         $result .= &mt
 3509:         ('[_1] Kerberos authenticated with domain [_2] '.
 3510:          '[_3] Version 4 [_4]',
 3511:          '<label>'.$authtype,
 3512:          '</label><input type="text" size="10" name="krbarg" '.
 3513:              'value="'.$krbarg.'" '.
 3514:              'onchange="'.$jscall.'"'.$disabled.' />',
 3515:          '<label><input type="hidden" name="krbver" value="4" />',
 3516:          '</label>');
 3517:     } elsif ($can_assign{'krb5'}) {
 3518:         $result .= &mt
 3519:         ('[_1] Kerberos authenticated with domain [_2] '.
 3520:          '[_3] Version 5 [_4]',
 3521:          '<label>'.$authtype,
 3522:          '</label><input type="text" size="10" name="krbarg" '.
 3523:              'value="'.$krbarg.'" '.
 3524:              'onchange="'.$jscall.'"'.$disabled.' />',
 3525:          '<label><input type="hidden" name="krbver" value="5" />',
 3526:          '</label>');
 3527:     }
 3528:     return $result;
 3529: }
 3530: 
 3531: sub authform_internal {
 3532:     my %in = (
 3533:                 formname => 'document.cu',
 3534:                 kerb_def_dom => 'MSU.EDU',
 3535:                 @_,
 3536:                 );
 3537:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3538:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3539:     if ($in{'readonly'}) {
 3540:         $disabled = ' disabled="disabled"';
 3541:     }
 3542:     if (defined($in{'curr_authtype'})) {
 3543:         if ($in{'curr_authtype'} eq 'int') {
 3544:             if ($can_assign{'int'}) {
 3545:                 $intcheck = 'checked="checked" ';
 3546:                 if (defined($in{'mode'})) {
 3547:                     if ($in{'mode'} eq 'modifyuser') {
 3548:                         $intcheck = '';
 3549:                     }
 3550:                 }
 3551:                 if (defined($in{'curr_autharg'})) {
 3552:                     $intarg = $in{'curr_autharg'};
 3553:                 }
 3554:             } else {
 3555:                 $result = &mt('Currently internally authenticated.');
 3556:                 return $result;
 3557:             }
 3558:         }
 3559:     } else {
 3560:         if ($authnum == 1) {
 3561:             $authtype = '<input type="hidden" name="login" value="int" />';
 3562:         }
 3563:     }
 3564:     if (!$can_assign{'int'}) {
 3565:         return;
 3566:     } elsif ($authtype eq '') {
 3567:         if (defined($in{'mode'})) {
 3568:             if ($in{'mode'} eq 'modifycourse') {
 3569:                 if ($authnum == 1) {
 3570:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3571:                 }
 3572:             }
 3573:         }
 3574:     }
 3575:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3576:     if ($authtype eq '') {
 3577:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3578:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3579:     }
 3580:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3581:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3582:     $result = &mt
 3583:         ('[_1] Internally authenticated (with initial password [_2])',
 3584:          '<label>'.$authtype,'</label>'.$autharg);
 3585:     $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>';
 3586:     return $result;
 3587: }
 3588: 
 3589: sub authform_local {
 3590:     my %in = (
 3591:               formname => 'document.cu',
 3592:               kerb_def_dom => 'MSU.EDU',
 3593:               @_,
 3594:               );
 3595:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3596:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3597:     if ($in{'readonly'}) {
 3598:         $disabled = ' disabled="disabled"';
 3599:     } 
 3600:     if (defined($in{'curr_authtype'})) {
 3601:         if ($in{'curr_authtype'} eq 'loc') {
 3602:             if ($can_assign{'loc'}) {
 3603:                 $loccheck = 'checked="checked" ';
 3604:                 if (defined($in{'mode'})) {
 3605:                     if ($in{'mode'} eq 'modifyuser') {
 3606:                         $loccheck = '';
 3607:                     }
 3608:                 }
 3609:                 if (defined($in{'curr_autharg'})) {
 3610:                     $locarg = $in{'curr_autharg'};
 3611:                 }
 3612:             } else {
 3613:                 $result = &mt('Currently using local (institutional) authentication.');
 3614:                 return $result;
 3615:             }
 3616:         }
 3617:     } else {
 3618:         if ($authnum == 1) {
 3619:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3620:         }
 3621:     }
 3622:     if (!$can_assign{'loc'}) {
 3623:         return;
 3624:     } elsif ($authtype eq '') {
 3625:         if (defined($in{'mode'})) {
 3626:             if ($in{'mode'} eq 'modifycourse') {
 3627:                 if ($authnum == 1) {
 3628:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3629:                 }
 3630:             }
 3631:         }
 3632:     }
 3633:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3634:     if ($authtype eq '') {
 3635:         $authtype = '<input type="radio" name="login" value="loc" '.
 3636:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3637:                     $jscall.'"'.$disabled.' />';
 3638:     }
 3639:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3640:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3641:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3642:                   '<label>'.$authtype,'</label>'.$autharg);
 3643:     return $result;
 3644: }
 3645: 
 3646: sub authform_filesystem {
 3647:     my %in = (
 3648:               formname => 'document.cu',
 3649:               kerb_def_dom => 'MSU.EDU',
 3650:               @_,
 3651:               );
 3652:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3653:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3654:     if ($in{'readonly'}) {
 3655:         $disabled = ' disabled="disabled"';
 3656:     }
 3657:     if (defined($in{'curr_authtype'})) {
 3658:         if ($in{'curr_authtype'} eq 'fsys') {
 3659:             if ($can_assign{'fsys'}) {
 3660:                 $fsyscheck = 'checked="checked" ';
 3661:                 if (defined($in{'mode'})) {
 3662:                     if ($in{'mode'} eq 'modifyuser') {
 3663:                         $fsyscheck = '';
 3664:                     }
 3665:                 }
 3666:             } else {
 3667:                 $result = &mt('Currently Filesystem Authenticated.');
 3668:                 return $result;
 3669:             }
 3670:         }
 3671:     } else {
 3672:         if ($authnum == 1) {
 3673:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3674:         }
 3675:     }
 3676:     if (!$can_assign{'fsys'}) {
 3677:         return;
 3678:     } elsif ($authtype eq '') {
 3679:         if (defined($in{'mode'})) {
 3680:             if ($in{'mode'} eq 'modifycourse') {
 3681:                 if ($authnum == 1) {
 3682:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3683:                 }
 3684:             }
 3685:         }
 3686:     }
 3687:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3688:     if ($authtype eq '') {
 3689:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3690:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3691:                     $jscall.'"'.$disabled.' />';
 3692:     }
 3693:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3694:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3695:     $result = &mt
 3696:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3697:          '<label>'.$authtype,'</label>'.$autharg);
 3698:     return $result;
 3699: }
 3700: 
 3701: sub authform_lti {
 3702:     my %in = (
 3703:               formname => 'document.cu',
 3704:               kerb_def_dom => 'MSU.EDU',
 3705:               @_,
 3706:               );
 3707:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3708:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3709:     if ($in{'readonly'}) {
 3710:         $disabled = ' disabled="disabled"';
 3711:     }
 3712:     if (defined($in{'curr_authtype'})) {
 3713:         if ($in{'curr_authtype'} eq 'lti') {
 3714:             if ($can_assign{'lti'}) {
 3715:                 $lticheck = 'checked="checked" ';
 3716:                 if (defined($in{'mode'})) {
 3717:                     if ($in{'mode'} eq 'modifyuser') {
 3718:                         $lticheck = '';
 3719:                     }
 3720:                 }
 3721:             } else {
 3722:                 $result = &mt('Currently LTI Authenticated.');
 3723:                 return $result;
 3724:             }
 3725:         }
 3726:     } else {
 3727:         if ($authnum == 1) {
 3728:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3729:         }
 3730:     }
 3731:     if (!$can_assign{'lti'}) {
 3732:         return;
 3733:     } elsif ($authtype eq '') {
 3734:         if (defined($in{'mode'})) {
 3735:             if ($in{'mode'} eq 'modifycourse') {
 3736:                 if ($authnum == 1) {
 3737:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3738:                 }
 3739:             }
 3740:         }
 3741:     }
 3742:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3743:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3744:         $authtype = '<input type="radio" name="login" value="lti" '.
 3745:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3746:                     $jscall.'"'.$disabled.' />';
 3747:     }
 3748:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3749:     if ($authtype) {
 3750:         $result = &mt('[_1] LTI Authenticated',
 3751:                       '<label>'.$authtype.'</label>'.$autharg);
 3752:     } else {
 3753:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3754:                   $autharg;
 3755:     }
 3756:     return $result;
 3757: }
 3758: 
 3759: sub get_assignable_auth {
 3760:     my ($dom) = @_;
 3761:     if ($dom eq '') {
 3762:         $dom = $env{'request.role.domain'};
 3763:     }
 3764:     my %can_assign = (
 3765:                           krb4 => 1,
 3766:                           krb5 => 1,
 3767:                           int  => 1,
 3768:                           loc  => 1,
 3769:                           lti  => 1,
 3770:                      );
 3771:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3772:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3773:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3774:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3775:             my $context;
 3776:             if ($env{'request.role'} =~ /^au/) {
 3777:                 $context = 'author';
 3778:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3779:                 $context = 'domain';
 3780:             } elsif ($env{'request.course.id'}) {
 3781:                 $context = 'course';
 3782:             }
 3783:             if ($context) {
 3784:                 if (ref($authhash->{$context}) eq 'HASH') {
 3785:                    %can_assign = %{$authhash->{$context}}; 
 3786:                 }
 3787:             }
 3788:         }
 3789:     }
 3790:     my $authnum = 0;
 3791:     foreach my $key (keys(%can_assign)) {
 3792:         if ($can_assign{$key}) {
 3793:             $authnum ++;
 3794:         }
 3795:     }
 3796:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3797:         $authnum --;
 3798:     }
 3799:     return ($authnum,%can_assign);
 3800: }
 3801: 
 3802: sub check_passwd_rules {
 3803:     my ($domain,$plainpass) = @_;
 3804:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3805:     my ($min,$max,@chars,@brokerule,$warning);
 3806:     $min = $Apache::lonnet::passwdmin;
 3807:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3808:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3809:             if ($passwdconf{'min'} > $min) {
 3810:                 $min = $passwdconf{'min'};
 3811:             }
 3812:         }
 3813:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3814:             $max = $passwdconf{'max'};
 3815:         }
 3816:         @chars = @{$passwdconf{'chars'}};
 3817:     }
 3818:     if (($min) && (length($plainpass) < $min)) {
 3819:         push(@brokerule,'min');
 3820:     }
 3821:     if (($max) && (length($plainpass) > $max)) {
 3822:         push(@brokerule,'max');
 3823:     }
 3824:     if (@chars) {
 3825:         my %rules;
 3826:         map { $rules{$_} = 1; } @chars;
 3827:         if ($rules{'uc'}) {
 3828:             unless ($plainpass =~ /[A-Z]/) {
 3829:                 push(@brokerule,'uc');
 3830:             }
 3831:         }
 3832:         if ($rules{'lc'}) {
 3833:             unless ($plainpass =~ /[a-z]/) {
 3834:                 push(@brokerule,'lc');
 3835:             }
 3836:         }
 3837:         if ($rules{'num'}) {
 3838:             unless ($plainpass =~ /\d/) {
 3839:                 push(@brokerule,'num');
 3840:             }
 3841:         }
 3842:         if ($rules{'spec'}) {
 3843:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3844:                 push(@brokerule,'spec');
 3845:             }
 3846:         }
 3847:     }
 3848:     if (@brokerule) {
 3849:         my %rulenames = &Apache::lonlocal::texthash(
 3850:             uc   => 'At least one upper case letter',
 3851:             lc   => 'At least one lower case letter',
 3852:             num  => 'At least one number',
 3853:             spec => 'At least one non-alphanumeric',
 3854:         );
 3855:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3856:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3857:         $rulenames{'num'} .= ': 0123456789';
 3858:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3859:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3860:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3861:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3862:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3863:             if (grep(/^$rule$/,@brokerule)) {
 3864:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3865:             }
 3866:         }
 3867:         $warning .= '</ul>';
 3868:     }
 3869:     if (wantarray) {
 3870:         return @brokerule;
 3871:     }
 3872:     return $warning;
 3873: }
 3874: 
 3875: sub passwd_validation_js {
 3876:     my ($currpasswdval,$domain,$context,$id) = @_;
 3877:     my (%passwdconf,$alertmsg);
 3878:     if ($context eq 'linkprot') {
 3879:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3880:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3881:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3882:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3883:             }
 3884:         }
 3885:         if ($id eq 'add') {
 3886:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3887:         } elsif ($id =~ /^\d+$/) {
 3888:             my $pos = $id+1;
 3889:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3890:         } else {
 3891:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3892:         }
 3893:     } else {
 3894:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3895:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3896:     }
 3897:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3898:     $numrules = 0;
 3899:     $min = $Apache::lonnet::passwdmin;
 3900:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3901:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3902:             if ($passwdconf{'min'} > $min) {
 3903:                 $min = $passwdconf{'min'};
 3904:             }
 3905:         }
 3906:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3907:             $max = $passwdconf{'max'};
 3908:             $numrules ++;
 3909:         }
 3910:         @chars = @{$passwdconf{'chars'}};
 3911:         if (@chars) {
 3912:             $numrules ++;
 3913:         }
 3914:     }
 3915:     if ($min > 0) {
 3916:         $numrules ++;
 3917:     }
 3918:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3919:         if ($min) {
 3920:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3921:         }
 3922:         if ($max) {
 3923:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3924:         }
 3925:         my (@charalerts,@charrules);
 3926:         if (@chars) {
 3927:             if (grep(/^uc$/,@chars)) {
 3928:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3929:                 push(@charrules,'uc');
 3930:             }
 3931:             if (grep(/^lc$/,@chars)) {
 3932:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3933:                 push(@charrules,'lc');
 3934:             }
 3935:             if (grep(/^num$/,@chars)) {
 3936:                 push(@charalerts,&mt('contain at least one number'));
 3937:                 push(@charrules,'num');
 3938:             }
 3939:             if (grep(/^spec$/,@chars)) {
 3940:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 3941:                 push(@charrules,'spec');
 3942:             }
 3943:         }
 3944:         $intargjs = qq|            var rulesmsg = '';\n|.
 3945:                     qq|            var currpwval = $currpasswdval;\n|;
 3946:             if ($min) {
 3947:                 $intargjs .= qq|
 3948:             if (currpwval.length < $min) {
 3949:                 rulesmsg += ' - $alert{min}';
 3950:             }
 3951: |;
 3952:             }
 3953:             if ($max) {
 3954:                 $intargjs .= qq|
 3955:             if (currpwval.length > $max) {
 3956:                 rulesmsg += ' - $alert{max}';
 3957:             }
 3958: |;
 3959:             }
 3960:             if (@chars > 0) {
 3961:                 my $charrulestr = '"'.join('","',@charrules).'"';
 3962:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 3963:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 3964:                              qq|            var charrules = new Array($charrulestr);\n|.
 3965:                              qq|            var charalerts = new Array($charalertstr);\n|;
 3966:                 my %rules;
 3967:                 map { $rules{$_} = 1; } @chars;
 3968:                 if ($rules{'uc'}) {
 3969:                     $intargjs .= qq|
 3970:             var ucRegExp = /[A-Z]/;
 3971:             if (!ucRegExp.test(currpwval)) {
 3972:                 brokerules.push('uc');
 3973:             }
 3974: |;
 3975:                 }
 3976:                 if ($rules{'lc'}) {
 3977:                     $intargjs .= qq|
 3978:             var lcRegExp = /[a-z]/;
 3979:             if (!lcRegExp.test(currpwval)) {
 3980:                 brokerules.push('lc');
 3981:             }
 3982: |;
 3983:                 }
 3984:                 if ($rules{'num'}) {
 3985:                      $intargjs .= qq|
 3986:             var numRegExp = /[0-9]/;
 3987:             if (!numRegExp.test(currpwval)) {
 3988:                 brokerules.push('num');
 3989:             }
 3990: |;
 3991:                 }
 3992:                 if ($rules{'spec'}) {
 3993:                      $intargjs .= q|
 3994:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 3995:             if (!specRegExp.test(currpwval)) {
 3996:                 brokerules.push('spec');
 3997:             }
 3998: |;
 3999:                 }
 4000:                 $intargjs .= qq|
 4001:             if (brokerules.length > 0) {
 4002:                 for (var i=0; i<brokerules.length; i++) {
 4003:                     for (var j=0; j<charrules.length; j++) {
 4004:                         if (brokerules[i] == charrules[j]) {
 4005:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 4006:                             break;
 4007:                         }
 4008:                     }
 4009:                 }
 4010:             }
 4011: |;
 4012:             }
 4013:             $intargjs .= qq|
 4014:             if (rulesmsg != '') {
 4015:                 rulesmsg = '$alertmsg'+rulesmsg;
 4016:                 alert(rulesmsg);
 4017:                 return false;
 4018:             }
 4019: |;
 4020:     }
 4021:     return ($numrules,$intargjs);
 4022: }
 4023: 
 4024: ###############################################################
 4025: ##    Get Kerberos Defaults for Domain                 ##
 4026: ###############################################################
 4027: ##
 4028: ## Returns default kerberos version and an associated argument
 4029: ## as listed in file domain.tab. If not listed, provides
 4030: ## appropriate default domain and kerberos version.
 4031: ##
 4032: #-------------------------------------------
 4033: 
 4034: =pod
 4035: 
 4036: =item * &get_kerberos_defaults()
 4037: 
 4038: get_kerberos_defaults($target_domain) returns the default kerberos
 4039: version and domain. If not found, it defaults to version 4 and the 
 4040: domain of the server.
 4041: 
 4042: =over 4
 4043: 
 4044: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 4045: 
 4046: =back
 4047: 
 4048: =back
 4049: 
 4050: =cut
 4051: 
 4052: #-------------------------------------------
 4053: sub get_kerberos_defaults {
 4054:     my $domain=shift;
 4055:     my ($krbdef,$krbdefdom);
 4056:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 4057:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 4058:         $krbdef = $domdefaults{'auth_def'};
 4059:         $krbdefdom = $domdefaults{'auth_arg_def'};
 4060:     } else {
 4061:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 4062:         my $krbdefdom=$1;
 4063:         $krbdefdom=~tr/a-z/A-Z/;
 4064:         $krbdef = "krb4";
 4065:     }
 4066:     return ($krbdef,$krbdefdom);
 4067: }
 4068: 
 4069: 
 4070: ###############################################################
 4071: ##                Thesaurus Functions                        ##
 4072: ###############################################################
 4073: 
 4074: =pod
 4075: 
 4076: =head1 Thesaurus Functions
 4077: 
 4078: =over 4
 4079: 
 4080: =item * &initialize_keywords()
 4081: 
 4082: Initializes the package variable %Keywords if it is empty.  Uses the
 4083: package variable $thesaurus_db_file.
 4084: 
 4085: =cut
 4086: 
 4087: ###################################################
 4088: 
 4089: sub initialize_keywords {
 4090:     return 1 if (scalar keys(%Keywords));
 4091:     # If we are here, %Keywords is empty, so fill it up
 4092:     #   Make sure the file we need exists...
 4093:     if (! -e $thesaurus_db_file) {
 4094:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 4095:                                  " failed because it does not exist");
 4096:         return 0;
 4097:     }
 4098:     #   Set up the hash as a database
 4099:     my %thesaurus_db;
 4100:     if (! tie(%thesaurus_db,'GDBM_File',
 4101:               $thesaurus_db_file,&GDBM_READER(),0640)){
 4102:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 4103:                                  $thesaurus_db_file);
 4104:         return 0;
 4105:     } 
 4106:     #  Get the average number of appearances of a word.
 4107:     my $avecount = $thesaurus_db{'average.count'};
 4108:     #  Put keywords (those that appear > average) into %Keywords
 4109:     while (my ($word,$data)=each (%thesaurus_db)) {
 4110:         my ($count,undef) = split /:/,$data;
 4111:         $Keywords{$word}++ if ($count > $avecount);
 4112:     }
 4113:     untie %thesaurus_db;
 4114:     # Remove special values from %Keywords.
 4115:     foreach my $value ('total.count','average.count') {
 4116:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 4117:   }
 4118:     return 1;
 4119: }
 4120: 
 4121: ###################################################
 4122: 
 4123: =pod
 4124: 
 4125: =item * &keyword($word)
 4126: 
 4127: Returns true if $word is a keyword.  A keyword is a word that appears more 
 4128: than the average number of times in the thesaurus database.  Calls 
 4129: &initialize_keywords
 4130: 
 4131: =cut
 4132: 
 4133: ###################################################
 4134: 
 4135: sub keyword {
 4136:     return if (!&initialize_keywords());
 4137:     my $word=lc(shift());
 4138:     $word=~s/\W//g;
 4139:     return exists($Keywords{$word});
 4140: }
 4141: 
 4142: ###############################################################
 4143: 
 4144: =pod 
 4145: 
 4146: =item * &get_related_words()
 4147: 
 4148: Look up a word in the thesaurus.  Takes a scalar argument and returns
 4149: an array of words.  If the keyword is not in the thesaurus, an empty array
 4150: will be returned.  The order of the words returned is determined by the
 4151: database which holds them.
 4152: 
 4153: Uses global $thesaurus_db_file.
 4154: 
 4155: 
 4156: =cut
 4157: 
 4158: ###############################################################
 4159: sub get_related_words {
 4160:     my $keyword = shift;
 4161:     my %thesaurus_db;
 4162:     if (! -e $thesaurus_db_file) {
 4163:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 4164:                                  "failed because the file does not exist");
 4165:         return ();
 4166:     }
 4167:     if (! tie(%thesaurus_db,'GDBM_File',
 4168:               $thesaurus_db_file,&GDBM_READER(),0640)){
 4169:         return ();
 4170:     } 
 4171:     my @Words=();
 4172:     my $count=0;
 4173:     if (exists($thesaurus_db{$keyword})) {
 4174: 	# The first element is the number of times
 4175: 	# the word appears.  We do not need it now.
 4176: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 4177: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 4178: 	my $threshold=$mostfrequentcount/10;
 4179:         foreach my $possibleword (@RelatedWords) {
 4180:             my ($word,$wordcount)=split(/\,/,$possibleword);
 4181:             if ($wordcount>$threshold) {
 4182: 		push(@Words,$word);
 4183:                 $count++;
 4184:                 if ($count>10) { last; }
 4185: 	    }
 4186:         }
 4187:     }
 4188:     untie %thesaurus_db;
 4189:     return @Words;
 4190: }
 4191: ###############################################################
 4192: #
 4193: #  Spell checking
 4194: #
 4195: 
 4196: =pod
 4197: 
 4198: =back
 4199: 
 4200: =head1 Spell checking
 4201: 
 4202: =over 4
 4203: 
 4204: =item * &check_spelling($wordlist $language)
 4205: 
 4206: Takes a string containing words and feeds it to an external
 4207: spellcheck program via a pipeline. Returns a string containing
 4208: them mis-spelled words.
 4209: 
 4210: Parameters:
 4211: 
 4212: =over 4
 4213: 
 4214: =item - $wordlist
 4215: 
 4216: String that will be fed into the spellcheck program.
 4217: 
 4218: =item - $language
 4219: 
 4220: Language string that specifies the language for which the spell
 4221: check will be performed.
 4222: 
 4223: =back
 4224: 
 4225: =back
 4226: 
 4227: Note: This sub assumes that aspell is installed.
 4228: 
 4229: 
 4230: =cut
 4231: 
 4232: 
 4233: sub check_spelling {
 4234:     my ($wordlist, $language) = @_;
 4235:     my @misspellings;
 4236:     
 4237:     # Generate the speller and set the langauge.
 4238:     # if explicitly selected:
 4239: 
 4240:     my $speller = Text::Aspell->new;
 4241:     if ($language) {
 4242: 	$speller->set_option('lang', $language);
 4243:     }
 4244: 
 4245:     # Turn the word list into an array of words by splittingon whitespace
 4246: 
 4247:     my @words = split(/\s+/, $wordlist);
 4248: 
 4249:     foreach my $word (@words) {
 4250: 	if(! $speller->check($word)) {
 4251: 	    push(@misspellings, $word);
 4252: 	}
 4253:     }
 4254:     return join(' ', @misspellings);
 4255:     
 4256: }
 4257: 
 4258: # -------------------------------------------------------------- Plaintext name
 4259: =pod
 4260: 
 4261: =head1 User Name Functions
 4262: 
 4263: =over 4
 4264: 
 4265: =item * &plainname($uname,$udom,$first)
 4266: 
 4267: Takes a users logon name and returns it as a string in
 4268: "first middle last generation" form 
 4269: if $first is set to 'lastname' then it returns it as
 4270: 'lastname generation, firstname middlename' if their is a lastname
 4271: 
 4272: =cut
 4273: 
 4274: 
 4275: ###############################################################
 4276: sub plainname {
 4277:     my ($uname,$udom,$first)=@_;
 4278:     return if (!defined($uname) || !defined($udom));
 4279:     my %names=&getnames($uname,$udom);
 4280:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 4281: 					  $names{'middlename'},
 4282: 					  $names{'lastname'},
 4283: 					  $names{'generation'},$first);
 4284:     $name=~s/^\s+//;
 4285:     $name=~s/\s+$//;
 4286:     $name=~s/\s+/ /g;
 4287:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 4288:     return $name;
 4289: }
 4290: 
 4291: # -------------------------------------------------------------------- Nickname
 4292: =pod
 4293: 
 4294: =item * &nickname($uname,$udom)
 4295: 
 4296: Gets a users name and returns it as a string as
 4297: 
 4298: "&quot;nickname&quot;"
 4299: 
 4300: if the user has a nickname or
 4301: 
 4302: "first middle last generation"
 4303: 
 4304: if the user does not
 4305: 
 4306: =cut
 4307: 
 4308: sub nickname {
 4309:     my ($uname,$udom)=@_;
 4310:     return if (!defined($uname) || !defined($udom));
 4311:     my %names=&getnames($uname,$udom);
 4312:     my $name=$names{'nickname'};
 4313:     if ($name) {
 4314:        $name='&quot;'.$name.'&quot;'; 
 4315:     } else {
 4316:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 4317: 	     $names{'lastname'}.' '.$names{'generation'};
 4318:        $name=~s/\s+$//;
 4319:        $name=~s/\s+/ /g;
 4320:     }
 4321:     return $name;
 4322: }
 4323: 
 4324: sub getnames {
 4325:     my ($uname,$udom)=@_;
 4326:     return if (!defined($uname) || !defined($udom));
 4327:     if ($udom eq 'public' && $uname eq 'public') {
 4328: 	return ('lastname' => &mt('Public'));
 4329:     }
 4330:     my $id=$uname.':'.$udom;
 4331:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 4332:     if ($cached) {
 4333: 	return %{$names};
 4334:     } else {
 4335: 	my %loadnames=&Apache::lonnet::get('environment',
 4336:                     ['firstname','middlename','lastname','generation','nickname'],
 4337: 					 $udom,$uname);
 4338: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 4339: 	return %loadnames;
 4340:     }
 4341: }
 4342: 
 4343: # -------------------------------------------------------------------- getemails
 4344: 
 4345: =pod
 4346: 
 4347: =item * &getemails($uname,$udom)
 4348: 
 4349: Gets a user's email information and returns it as a hash with keys:
 4350: notification, critnotification, permanentemail
 4351: 
 4352: For notification and critnotification, values are comma-separated lists 
 4353: of e-mail addresses; for permanentemail, value is a single e-mail address.
 4354:  
 4355: 
 4356: =cut
 4357: 
 4358: 
 4359: sub getemails {
 4360:     my ($uname,$udom)=@_;
 4361:     if ($udom eq 'public' && $uname eq 'public') {
 4362: 	return;
 4363:     }
 4364:     if (!$udom) { $udom=$env{'user.domain'}; }
 4365:     if (!$uname) { $uname=$env{'user.name'}; }
 4366:     my $id=$uname.':'.$udom;
 4367:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 4368:     if ($cached) {
 4369: 	return %{$names};
 4370:     } else {
 4371: 	my %loadnames=&Apache::lonnet::get('environment',
 4372:                     			   ['notification','critnotification',
 4373: 					    'permanentemail'],
 4374: 					   $udom,$uname);
 4375: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4376: 	return %loadnames;
 4377:     }
 4378: }
 4379: 
 4380: sub flush_email_cache {
 4381:     my ($uname,$udom)=@_;
 4382:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4383:     if (!$uname) { $uname=$env{'user.name'};   }
 4384:     return if ($udom eq 'public' && $uname eq 'public');
 4385:     my $id=$uname.':'.$udom;
 4386:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4387: }
 4388: 
 4389: # -------------------------------------------------------------------- getlangs
 4390: 
 4391: =pod
 4392: 
 4393: =item * &getlangs($uname,$udom)
 4394: 
 4395: Gets a user's language preference and returns it as a hash with key:
 4396: language.
 4397: 
 4398: =cut
 4399: 
 4400: 
 4401: sub getlangs {
 4402:     my ($uname,$udom) = @_;
 4403:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4404:     if (!$uname) { $uname=$env{'user.name'};   }
 4405:     my $id=$uname.':'.$udom;
 4406:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4407:     if ($cached) {
 4408:         return %{$langs};
 4409:     } else {
 4410:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4411:                                            $udom,$uname);
 4412:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4413:         return %loadlangs;
 4414:     }
 4415: }
 4416: 
 4417: sub flush_langs_cache {
 4418:     my ($uname,$udom)=@_;
 4419:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4420:     if (!$uname) { $uname=$env{'user.name'};   }
 4421:     return if ($udom eq 'public' && $uname eq 'public');
 4422:     my $id=$uname.':'.$udom;
 4423:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4424: }
 4425: 
 4426: # ------------------------------------------------------------------ Screenname
 4427: 
 4428: =pod
 4429: 
 4430: =item * &screenname($uname,$udom)
 4431: 
 4432: Gets a users screenname and returns it as a string
 4433: 
 4434: =cut
 4435: 
 4436: sub screenname {
 4437:     my ($uname,$udom)=@_;
 4438:     if ($uname eq $env{'user.name'} &&
 4439: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4440:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4441:     return $names{'screenname'};
 4442: }
 4443: 
 4444: 
 4445: # ------------------------------------------------------------- Confirm Wrapper
 4446: =pod
 4447: 
 4448: =item * &confirmwrapper($message)
 4449: 
 4450: Wrap messages about completion of operation in box
 4451: 
 4452: =cut
 4453: 
 4454: sub confirmwrapper {
 4455:     my ($message)=@_;
 4456:     if ($message) {
 4457:         return "\n".'<div class="LC_confirm_box">'."\n"
 4458:                .$message."\n"
 4459:                .'</div>'."\n";
 4460:     } else {
 4461:         return $message;
 4462:     }
 4463: }
 4464: 
 4465: # ------------------------------------------------------------- Message Wrapper
 4466: 
 4467: sub messagewrapper {
 4468:     my ($link,$username,$domain,$subject,$text)=@_;
 4469:     return 
 4470:         '<a href="/adm/email?compose=individual&amp;'.
 4471:         'recname='.$username.'&amp;recdom='.$domain.
 4472: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4473:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4474: }
 4475: 
 4476: # --------------------------------------------------------------- Notes Wrapper
 4477: 
 4478: sub noteswrapper {
 4479:     my ($link,$un,$do)=@_;
 4480:     return 
 4481: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4482: }
 4483: 
 4484: # ------------------------------------------------------------- Aboutme Wrapper
 4485: 
 4486: sub aboutmewrapper {
 4487:     my ($link,$username,$domain,$target,$class)=@_;
 4488:     if (!defined($username)  && !defined($domain)) {
 4489:         return;
 4490:     }
 4491:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4492: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4493: }
 4494: 
 4495: # ------------------------------------------------------------ Syllabus Wrapper
 4496: 
 4497: sub syllabuswrapper {
 4498:     my ($linktext,$coursedir,$domain)=@_;
 4499:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4500: }
 4501: 
 4502: # -----------------------------------------------------------------------------
 4503: 
 4504: sub aboutme_on {
 4505:     my ($uname,$udom)=@_;
 4506:     unless ($uname) { $uname=$env{'user.name'}; }
 4507:     unless ($udom)  { $udom=$env{'user.domain'}; }
 4508:     return if ($udom eq 'public' && $uname eq 'public');
 4509:     my $hashkey=$uname.':'.$udom;
 4510:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
 4511:     if ($cached) {
 4512:         return $aboutme;
 4513:     }
 4514:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
 4515:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
 4516:     return $aboutme;
 4517: }
 4518: 
 4519: sub devalidate_aboutme_cache {
 4520:     my ($uname,$udom)=@_;
 4521:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4522:     if (!$uname) { $uname=$env{'user.name'};   }
 4523:     return if ($udom eq 'public' && $uname eq 'public');
 4524:     my $id=$uname.':'.$udom;
 4525:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
 4526: }
 4527: 
 4528: sub track_student_link {
 4529:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4530:     my $link ="/adm/trackstudent?";
 4531:     my $title = 'View recent activity';
 4532:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4533:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4534:         $link .= "selected_student=$sname:$sdom";
 4535:         $title .= ' of this student';
 4536:     } 
 4537:     if (defined($target) && $target !~ /^\s*$/) {
 4538:         $target = qq{target="$target"};
 4539:     } else {
 4540:         $target = '';
 4541:     }
 4542:     if ($start) { $link.='&amp;start='.$start; }
 4543:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4544:     $title = &mt($title);
 4545:     $linktext = &mt($linktext);
 4546:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4547: 	&help_open_topic('View_recent_activity');
 4548: }
 4549: 
 4550: sub slot_reservations_link {
 4551:     my ($linktext,$sname,$sdom,$target) = @_;
 4552:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4553:     my $title = 'View slot reservation history';
 4554:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4555:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4556:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4557:         $title .= ' of this student';
 4558:     }
 4559:     if (defined($target) && $target !~ /^\s*$/) {
 4560:         $target = qq{target="$target"};
 4561:     } else {
 4562:         $target = '';
 4563:     }
 4564:     $title = &mt($title);
 4565:     $linktext = &mt($linktext);
 4566:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4567: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4568: 
 4569: }
 4570: 
 4571: # ===================================================== Display a student photo
 4572: 
 4573: 
 4574: sub student_image_tag {
 4575:     my ($domain,$user)=@_;
 4576:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4577:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4578: 	return '<img src="'.$imgsrc.'" align="right" />';
 4579:     } else {
 4580: 	return '';
 4581:     }
 4582: }
 4583: 
 4584: =pod
 4585: 
 4586: =back
 4587: 
 4588: =head1 Access .tab File Data
 4589: 
 4590: =over 4
 4591: 
 4592: =item * &languageids() 
 4593: 
 4594: returns list of all language ids
 4595: 
 4596: =cut
 4597: 
 4598: sub languageids {
 4599:     return sort(keys(%language));
 4600: }
 4601: 
 4602: =pod
 4603: 
 4604: =item * &languagedescription() 
 4605: 
 4606: returns description of a specified language id
 4607: 
 4608: =cut
 4609: 
 4610: sub languagedescription {
 4611:     my $code=shift;
 4612:     return  ($supported_language{$code}?'* ':'').
 4613:             $language{$code}.
 4614: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4615: }
 4616: 
 4617: =pod
 4618: 
 4619: =item * &plainlanguagedescription
 4620: 
 4621: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4622: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4623: 
 4624: =cut
 4625: 
 4626: sub plainlanguagedescription {
 4627:     my $code=shift;
 4628:     return $language{$code};
 4629: }
 4630: 
 4631: =pod
 4632: 
 4633: =item * &supportedlanguagecode
 4634: 
 4635: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4636: code.
 4637: 
 4638: =cut
 4639: 
 4640: sub supportedlanguagecode {
 4641:     my $code=shift;
 4642:     return $supported_language{$code};
 4643: }
 4644: 
 4645: =pod
 4646: 
 4647: =item * &latexlanguage()
 4648: 
 4649: Given a language key code returns the correspondnig language to use
 4650: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4651: is no supported hyphenation for the language code.
 4652: 
 4653: =cut
 4654: 
 4655: sub latexlanguage {
 4656:     my $code = shift;
 4657:     return $latex_language{$code};
 4658: }
 4659: 
 4660: =pod
 4661: 
 4662: =item * &latexhyphenation()
 4663: 
 4664: Same as above but what's supplied is the language as it might be stored
 4665: in the metadata.
 4666: 
 4667: =cut
 4668: 
 4669: sub latexhyphenation {
 4670:     my $key = shift;
 4671:     return $latex_language_bykey{$key};
 4672: }
 4673: 
 4674: =pod
 4675: 
 4676: =item * &copyrightids() 
 4677: 
 4678: returns list of all copyrights
 4679: 
 4680: =cut
 4681: 
 4682: sub copyrightids {
 4683:     return sort(keys(%cprtag));
 4684: }
 4685: 
 4686: =pod
 4687: 
 4688: =item * &copyrightdescription() 
 4689: 
 4690: returns description of a specified copyright id
 4691: 
 4692: =cut
 4693: 
 4694: sub copyrightdescription {
 4695:     return &mt($cprtag{shift(@_)});
 4696: }
 4697: 
 4698: =pod
 4699: 
 4700: =item * &source_copyrightids() 
 4701: 
 4702: returns list of all source copyrights
 4703: 
 4704: =cut
 4705: 
 4706: sub source_copyrightids {
 4707:     return sort(keys(%scprtag));
 4708: }
 4709: 
 4710: =pod
 4711: 
 4712: =item * &source_copyrightdescription() 
 4713: 
 4714: returns description of a specified source copyright id
 4715: 
 4716: =cut
 4717: 
 4718: sub source_copyrightdescription {
 4719:     return &mt($scprtag{shift(@_)});
 4720: }
 4721: 
 4722: =pod
 4723: 
 4724: =item * &filecategories() 
 4725: 
 4726: returns list of all file categories
 4727: 
 4728: =cut
 4729: 
 4730: sub filecategories {
 4731:     return sort(keys(%category_extensions));
 4732: }
 4733: 
 4734: =pod
 4735: 
 4736: =item * &filecategorytypes() 
 4737: 
 4738: returns list of file types belonging to a given file
 4739: category
 4740: 
 4741: =cut
 4742: 
 4743: sub filecategorytypes {
 4744:     my ($cat) = @_;
 4745:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4746:         return @{$category_extensions{lc($cat)}};
 4747:     } else {
 4748:         return ();
 4749:     }
 4750: }
 4751: 
 4752: =pod
 4753: 
 4754: =item * &fileembstyle() 
 4755: 
 4756: returns embedding style for a specified file type
 4757: 
 4758: =cut
 4759: 
 4760: sub fileembstyle {
 4761:     return $fe{lc(shift(@_))};
 4762: }
 4763: 
 4764: sub filemimetype {
 4765:     return $fm{lc(shift(@_))};
 4766: }
 4767: 
 4768: 
 4769: sub filecategoryselect {
 4770:     my ($name,$value)=@_;
 4771:     return &select_form($value,$name,
 4772:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4773: }
 4774: 
 4775: =pod
 4776: 
 4777: =item * &filedescription() 
 4778: 
 4779: returns description for a specified file type
 4780: 
 4781: =cut
 4782: 
 4783: sub filedescription {
 4784:     my $file_description = $fd{lc(shift())};
 4785:     $file_description =~ s:([\[\]]):~$1:g;
 4786:     return &mt($file_description);
 4787: }
 4788: 
 4789: =pod
 4790: 
 4791: =item * &filedescriptionex() 
 4792: 
 4793: returns description for a specified file type with
 4794: extra formatting
 4795: 
 4796: =cut
 4797: 
 4798: sub filedescriptionex {
 4799:     my $ex=shift;
 4800:     my $file_description = $fd{lc($ex)};
 4801:     $file_description =~ s:([\[\]]):~$1:g;
 4802:     return '.'.$ex.' '.&mt($file_description);
 4803: }
 4804: 
 4805: # End of .tab access
 4806: =pod
 4807: 
 4808: =back
 4809: 
 4810: =cut
 4811: 
 4812: # ------------------------------------------------------------------ File Types
 4813: sub fileextensions {
 4814:     return sort(keys(%fe));
 4815: }
 4816: 
 4817: # ----------------------------------------------------------- Display Languages
 4818: # returns a hash with all desired display languages
 4819: #
 4820: 
 4821: sub display_languages {
 4822:     my %languages=();
 4823:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4824: 	$languages{$lang}=1;
 4825:     }
 4826:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4827:     if ($env{'form.displaylanguage'}) {
 4828: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4829: 	    $languages{$lang}=1;
 4830:         }
 4831:     }
 4832:     return %languages;
 4833: }
 4834: 
 4835: sub languages {
 4836:     my ($possible_langs) = @_;
 4837:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4838:     if (!ref($possible_langs)) {
 4839: 	if( wantarray ) {
 4840: 	    return @preferred_langs;
 4841: 	} else {
 4842: 	    return $preferred_langs[0];
 4843: 	}
 4844:     }
 4845:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4846:     my @preferred_possibilities;
 4847:     foreach my $preferred_lang (@preferred_langs) {
 4848: 	if (exists($possibilities{$preferred_lang})) {
 4849: 	    push(@preferred_possibilities, $preferred_lang);
 4850: 	}
 4851:     }
 4852:     if( wantarray ) {
 4853: 	return @preferred_possibilities;
 4854:     }
 4855:     return $preferred_possibilities[0];
 4856: }
 4857: 
 4858: sub user_lang {
 4859:     my ($touname,$toudom,$fromcid) = @_;
 4860:     my @userlangs;
 4861:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4862:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4863:                     $env{'course.'.$fromcid.'.languages'}));
 4864:     } else {
 4865:         my %langhash = &getlangs($touname,$toudom);
 4866:         if ($langhash{'languages'} ne '') {
 4867:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4868:         } else {
 4869:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4870:             if ($domdefs{'lang_def'} ne '') {
 4871:                 @userlangs = ($domdefs{'lang_def'});
 4872:             }
 4873:         }
 4874:     }
 4875:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4876:     my $user_lh = Apache::localize->get_handle(@languages);
 4877:     return $user_lh;
 4878: }
 4879: 
 4880: 
 4881: ###############################################################
 4882: ##               Student Answer Attempts                     ##
 4883: ###############################################################
 4884: 
 4885: =pod
 4886: 
 4887: =head1 Alternate Problem Views
 4888: 
 4889: =over 4
 4890: 
 4891: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4892:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4893: 
 4894: Return string with previous attempt on problem. Arguments:
 4895: 
 4896: =over 4
 4897: 
 4898: =item * $symb: Problem, including path
 4899: 
 4900: =item * $username: username of the desired student
 4901: 
 4902: =item * $domain: domain of the desired student
 4903: 
 4904: =item * $course: Course ID
 4905: 
 4906: =item * $getattempt: Leave blank for all attempts, otherwise put
 4907:     something
 4908: 
 4909: =item * $regexp: if string matches this regexp, the string will be
 4910:     sent to $gradesub
 4911: 
 4912: =item * $gradesub: routine that processes the string if it matches $regexp
 4913: 
 4914: =item * $usec: section of the desired student
 4915: 
 4916: =item * $identifier: counter for student (multiple students one problem) or 
 4917:     problem (one student; whole sequence).
 4918: 
 4919: =back
 4920: 
 4921: The output string is a table containing all desired attempts, if any.
 4922: 
 4923: =cut
 4924: 
 4925: sub get_previous_attempt {
 4926:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4927:   my $prevattempts='';
 4928:   no strict 'refs';
 4929:   if ($symb) {
 4930:     my (%returnhash)=
 4931:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4932:     if ($returnhash{'version'}) {
 4933:       my %lasthash=();
 4934:       my $version;
 4935:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4936:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4937:             if ($key =~ /\.rawrndseed$/) {
 4938:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4939:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4940:             } else {
 4941:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4942:             }
 4943:         }
 4944:       }
 4945:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4946:       $prevattempts.='<th>'.&mt('History').'</th>';
 4947:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4948:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4949:       foreach my $key (sort(keys(%lasthash))) {
 4950: 	my ($ign,@parts) = split(/\./,$key);
 4951: 	if ($#parts > 0) {
 4952: 	  my $data=$parts[-1];
 4953:           next if ($data eq 'foilorder');
 4954: 	  pop(@parts);
 4955:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4956:           if ($data eq 'type') {
 4957:               unless ($showsurv) {
 4958:                   my $id = join(',',@parts);
 4959:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4960:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4961:                       $lasthidden{$ign.'.'.$id} = 1;
 4962:                   }
 4963:               }
 4964:               if ($identifier ne '') {
 4965:                   my $id = join(',',@parts);
 4966:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4967:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4968:                       $hidestatus{$ign.'.'.$id} = 1;
 4969:                   }
 4970:               }
 4971:           } elsif ($data eq 'regrader') {
 4972:               if (($identifier ne '') && (@parts)) {
 4973:                   my $id = join(',',@parts);
 4974:                   $regraded{$ign.'.'.$id} = 1;
 4975:               }
 4976:           } 
 4977: 	} else {
 4978: 	  if ($#parts == 0) {
 4979: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4980: 	  } else {
 4981: 	    $prevattempts.='<th>'.$ign.'</th>';
 4982: 	  }
 4983: 	}
 4984:       }
 4985:       $prevattempts.=&end_data_table_header_row();
 4986:       if ($getattempt eq '') {
 4987:         my (%solved,%resets,%probstatus);
 4988:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4989:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4990:                 foreach my $id (keys(%regraded)) {
 4991:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4992:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4993:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4994:                         push(@{$resets{$id}},$version);
 4995:                     }
 4996:                 }
 4997:             }
 4998:         }
 4999: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 5000:             my (@hidden,@unsolved);
 5001:             if (%typeparts) {
 5002:                 foreach my $id (keys(%typeparts)) {
 5003:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 5004:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 5005:                         push(@hidden,$id);
 5006:                     } elsif ($identifier ne '') {
 5007:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 5008:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 5009:                                 ($hidestatus{$id})) {
 5010:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 5011:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 5012:                                 push(@{$solved{$id}},$version);
 5013:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 5014:                                      (ref($solved{$id}) eq 'ARRAY')) {
 5015:                                 my $skip;
 5016:                                 if (ref($resets{$id}) eq 'ARRAY') {
 5017:                                     foreach my $reset (@{$resets{$id}}) {
 5018:                                         if ($reset > $solved{$id}[-1]) {
 5019:                                             $skip=1;
 5020:                                             last;
 5021:                                         }
 5022:                                     }
 5023:                                 }
 5024:                                 unless ($skip) {
 5025:                                     my ($ign,$partslist) = split(/\./,$id,2);
 5026:                                     push(@unsolved,$partslist);
 5027:                                 }
 5028:                             }
 5029:                         }
 5030:                     }
 5031:                 }
 5032:             }
 5033:             $prevattempts.=&start_data_table_row().
 5034:                            '<td>'.&mt('Transaction [_1]',$version);
 5035:             if (@unsolved) {
 5036:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 5037:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 5038:                                  &mt('Hide').'</label></span>';
 5039:             }
 5040:             $prevattempts .= '</td>';
 5041:             if (@hidden) {
 5042:                 foreach my $key (sort(keys(%lasthash))) {
 5043:                     next if ($key =~ /\.foilorder$/);
 5044:                     my $hide;
 5045:                     foreach my $id (@hidden) {
 5046:                         if ($key =~ /^\Q$id\E/) {
 5047:                             $hide = 1;
 5048:                             last;
 5049:                         }
 5050:                     }
 5051:                     if ($hide) {
 5052:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 5053:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 5054:                             my $value = &format_previous_attempt_value($key,
 5055:                                              $returnhash{$version.':'.$key});
 5056:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5057:                         } else {
 5058:                             $prevattempts.='<td>&nbsp;</td>';
 5059:                         }
 5060:                     } else {
 5061:                         if ($key =~ /\./) {
 5062:                             my $value = $returnhash{$version.':'.$key};
 5063:                             if ($key =~ /\.rndseed$/) {
 5064:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 5065:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 5066:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 5067:                                 }
 5068:                             }
 5069:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 5070:                                            '&nbsp;</td>';
 5071:                         } else {
 5072:                             $prevattempts.='<td>&nbsp;</td>';
 5073:                         }
 5074:                     }
 5075:                 }
 5076:             } else {
 5077: 	        foreach my $key (sort(keys(%lasthash))) {
 5078:                     next if ($key =~ /\.foilorder$/);
 5079:                     my $value = $returnhash{$version.':'.$key};
 5080:                     if ($key =~ /\.rndseed$/) {
 5081:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 5082:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 5083:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 5084:                         }
 5085:                     }
 5086:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 5087:                                    '&nbsp;</td>';
 5088: 	        }
 5089:             }
 5090: 	    $prevattempts.=&end_data_table_row();
 5091: 	 }
 5092:       }
 5093:       my @currhidden = keys(%lasthidden);
 5094:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 5095:       foreach my $key (sort(keys(%lasthash))) {
 5096:           next if ($key =~ /\.foilorder$/);
 5097:           if (%typeparts) {
 5098:               my $hidden;
 5099:               foreach my $id (@currhidden) {
 5100:                   if ($key =~ /^\Q$id\E/) {
 5101:                       $hidden = 1;
 5102:                       last;
 5103:                   }
 5104:               }
 5105:               if ($hidden) {
 5106:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 5107:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 5108:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5109:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5110:                           $value = &$gradesub($value);
 5111:                       }
 5112:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 5113:                   } else {
 5114:                       $prevattempts.='<td>&nbsp;</td>';
 5115:                   }
 5116:               } else {
 5117:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5118:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5119:                       $value = &$gradesub($value);
 5120:                   }
 5121:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5122:               }
 5123:           } else {
 5124: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5125: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5126:                   $value = &$gradesub($value);
 5127:               }
 5128: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5129:           }
 5130:       }
 5131:       $prevattempts.= &end_data_table_row().&end_data_table();
 5132:     } else {
 5133:       my $msg;
 5134:       if ($symb =~ /ext\.tool$/) {
 5135:           $msg = &mt('No grade passed back.');
 5136:       } else {
 5137:           $msg = &mt('Nothing submitted - no attempts.');
 5138:       }
 5139:       $prevattempts=
 5140: 	  &start_data_table().&start_data_table_row().
 5141: 	  '<td>'.$msg.'</td>'.
 5142: 	  &end_data_table_row().&end_data_table();
 5143:     }
 5144:   } else {
 5145:     $prevattempts=
 5146: 	  &start_data_table().&start_data_table_row().
 5147: 	  '<td>'.&mt('No data.').'</td>'.
 5148: 	  &end_data_table_row().&end_data_table();
 5149:   }
 5150: }
 5151: 
 5152: sub format_previous_attempt_value {
 5153:     my ($key,$value) = @_;
 5154:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 5155:         $value = &Apache::lonlocal::locallocaltime($value);
 5156:     } elsif (ref($value) eq 'ARRAY') {
 5157:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 5158:     } elsif ($key =~ /answerstring$/) {
 5159:         my %answers = &Apache::lonnet::str2hash($value);
 5160:         my @answer = %answers;
 5161:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 5162:         my @anskeys = sort(keys(%answers));
 5163:         if (@anskeys == 1) {
 5164:             my $answer = $answers{$anskeys[0]};
 5165:             if ($answer =~ m{\0}) {
 5166:                 $answer =~ s{\0}{,}g;
 5167:             }
 5168:             my $tag_internal_answer_name = 'INTERNAL';
 5169:             if ($anskeys[0] eq $tag_internal_answer_name) {
 5170:                 $value = $answer; 
 5171:             } else {
 5172:                 $value = $anskeys[0].'='.$answer;
 5173:             }
 5174:         } else {
 5175:             foreach my $ans (@anskeys) {
 5176:                 my $answer = $answers{$ans};
 5177:                 if ($answer =~ m{\0}) {
 5178:                     $answer =~ s{\0}{,}g;
 5179:                 }
 5180:                 $value .=  $ans.'='.$answer.'<br />';;
 5181:             } 
 5182:         }
 5183:     } else {
 5184:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 5185:     }
 5186:     return $value;
 5187: }
 5188: 
 5189: 
 5190: sub relative_to_absolute {
 5191:     my ($url,$output)=@_;
 5192:     my $parser=HTML::TokeParser->new(\$output);
 5193:     my $token;
 5194:     my $thisdir=$url;
 5195:     my @rlinks=();
 5196:     while ($token=$parser->get_token) {
 5197: 	if ($token->[0] eq 'S') {
 5198: 	    if ($token->[1] eq 'a') {
 5199: 		if ($token->[2]->{'href'}) {
 5200: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 5201: 		}
 5202: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 5203: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 5204: 	    } elsif ($token->[1] eq 'base') {
 5205: 		$thisdir=$token->[2]->{'href'};
 5206: 	    }
 5207: 	}
 5208:     }
 5209:     $thisdir=~s-/[^/]*$--;
 5210:     foreach my $link (@rlinks) {
 5211: 	unless (($link=~/^https?\:\/\//i) ||
 5212: 		($link=~/^\//) ||
 5213: 		($link=~/^javascript:/i) ||
 5214: 		($link=~/^mailto:/i) ||
 5215: 		($link=~/^\#/)) {
 5216: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 5217: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 5218: 	}
 5219:     }
 5220: # -------------------------------------------------- Deal with Applet codebases
 5221:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 5222:     return $output;
 5223: }
 5224: 
 5225: =pod
 5226: 
 5227: =item * &get_student_view()
 5228: 
 5229: show a snapshot of what student was looking at
 5230: 
 5231: =cut
 5232: 
 5233: sub get_student_view {
 5234:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 5235:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5236:   my (%form);
 5237:   my @elements=('symb','courseid','domain','username');
 5238:   foreach my $element (@elements) {
 5239:       $form{'grade_'.$element}=eval '$'.$element #'
 5240:   }
 5241:   if (defined($moreenv)) {
 5242:       %form=(%form,%{$moreenv});
 5243:   }
 5244:   if (defined($target)) { $form{'grade_target'} = $target; }
 5245:   $feedurl=&Apache::lonnet::clutter($feedurl);
 5246:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 5247:       $feedurl =~ s{^/adm/wrapper}{};
 5248:   }
 5249:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 5250:   $userview=~s/\<body[^\>]*\>//gi;
 5251:   $userview=~s/\<\/body\>//gi;
 5252:   $userview=~s/\<html\>//gi;
 5253:   $userview=~s/\<\/html\>//gi;
 5254:   $userview=~s/\<head\>//gi;
 5255:   $userview=~s/\<\/head\>//gi;
 5256:   $userview=~s/action\s*\=/would_be_action\=/gi;
 5257:   $userview=&relative_to_absolute($feedurl,$userview);
 5258:   if (wantarray) {
 5259:      return ($userview,$response);
 5260:   } else {
 5261:      return $userview;
 5262:   }
 5263: }
 5264: 
 5265: sub get_student_view_with_retries {
 5266:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 5267: 
 5268:     my $ok = 0;                 # True if we got a good response.
 5269:     my $content;
 5270:     my $response;
 5271: 
 5272:     # Try to get the student_view done. within the retries count:
 5273:     
 5274:     do {
 5275:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 5276:          $ok      = $response->is_success;
 5277:          if (!$ok) {
 5278:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 5279:          }
 5280:          $retries--;
 5281:     } while (!$ok && ($retries > 0));
 5282:     
 5283:     if (!$ok) {
 5284:        $content = '';          # On error return an empty content.
 5285:     }
 5286:     if (wantarray) {
 5287:        return ($content, $response);
 5288:     } else {
 5289:        return $content;
 5290:     }
 5291: }
 5292: 
 5293: sub css_links {
 5294:     my ($currsymb,$level) = @_;
 5295:     my ($links,@symbs,%cssrefs,%httpref);
 5296:     if ($level eq 'map') {
 5297:         my $navmap = Apache::lonnavmaps::navmap->new();
 5298:         if (ref($navmap)) {
 5299:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 5300:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 5301:             foreach my $res (@resources) {
 5302:                 if (ref($res) && $res->symb()) {
 5303:                     push(@symbs,$res->symb());
 5304:                 }
 5305:             }
 5306:         }
 5307:     } else {
 5308:         @symbs = ($currsymb);
 5309:     }
 5310:     foreach my $symb (@symbs) {
 5311:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 5312:         if ($css_href =~ /\S/) {
 5313:             unless ($css_href =~ m{https?://}) {
 5314:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 5315:                 my $proburl =  &Apache::lonnet::clutter($url);
 5316:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 5317:                 unless ($css_href =~ m{^/}) {
 5318:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 5319:                 }
 5320:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 5321:                     unless (($httpref{'httpref.'.$css_href}) ||
 5322:                             (&Apache::lonnet::is_on_map($css_href))) {
 5323:                         my $thisurl = $proburl;
 5324:                         if ($env{'httpref.'.$proburl}) {
 5325:                             $thisurl = $env{'httpref.'.$proburl};
 5326:                         }
 5327:                         $httpref{'httpref.'.$css_href} = $thisurl;
 5328:                     }
 5329:                 }
 5330:             }
 5331:             $cssrefs{$css_href} = 1;
 5332:         }
 5333:     }
 5334:     if (keys(%httpref)) {
 5335:         &Apache::lonnet::appenv(\%httpref);
 5336:     }
 5337:     if (keys(%cssrefs)) {
 5338:         foreach my $css_href (keys(%cssrefs)) {
 5339:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 5340:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 5341:         }
 5342:     }
 5343:     return $links;
 5344: }
 5345: 
 5346: =pod
 5347: 
 5348: =item * &get_student_answers() 
 5349: 
 5350: show a snapshot of how student was answering problem
 5351: 
 5352: =cut
 5353: 
 5354: sub get_student_answers {
 5355:   my ($symb,$username,$domain,$courseid,%form) = @_;
 5356:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5357:   my (%moreenv);
 5358:   my @elements=('symb','courseid','domain','username');
 5359:   foreach my $element (@elements) {
 5360:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 5361:   }
 5362:   $moreenv{'grade_target'}='answer';
 5363:   %moreenv=(%form,%moreenv);
 5364:   $feedurl = &Apache::lonnet::clutter($feedurl);
 5365:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 5366:   return $userview;
 5367: }
 5368: 
 5369: =pod
 5370: 
 5371: =item * &submlink()
 5372: 
 5373: Inputs: $text $uname $udom $symb $target
 5374: 
 5375: Returns: A link to grades.pm such as to see the SUBM view of a student
 5376: 
 5377: =cut
 5378: 
 5379: ###############################################
 5380: sub submlink {
 5381:     my ($text,$uname,$udom,$symb,$target)=@_;
 5382:     if (!($uname && $udom)) {
 5383: 	(my $cursymb, my $courseid,$udom,$uname)=
 5384: 	    &Apache::lonnet::whichuser($symb);
 5385: 	if (!$symb) { $symb=$cursymb; }
 5386:     }
 5387:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5388:     $symb=&escape($symb);
 5389:     if ($target) { $target=" target=\"$target\""; }
 5390:     return
 5391:         '<a href="/adm/grades?command=submission'.
 5392:         '&amp;symb='.$symb.
 5393:         '&amp;student='.$uname.
 5394:         '&amp;userdom='.$udom.'"'.
 5395:         $target.'>'.$text.'</a>';
 5396: }
 5397: ##############################################
 5398: 
 5399: =pod
 5400: 
 5401: =item * &pgrdlink()
 5402: 
 5403: Inputs: $text $uname $udom $symb $target
 5404: 
 5405: Returns: A link to grades.pm such as to see the PGRD view of a student
 5406: 
 5407: =cut
 5408: 
 5409: ###############################################
 5410: sub pgrdlink {
 5411:     my $link=&submlink(@_);
 5412:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 5413:     return $link;
 5414: }
 5415: ##############################################
 5416: 
 5417: =pod
 5418: 
 5419: =item * &pprmlink()
 5420: 
 5421: Inputs: $text $uname $udom $symb $target
 5422: 
 5423: Returns: A link to parmset.pm such as to see the PPRM view of a
 5424: student and a specific resource
 5425: 
 5426: =cut
 5427: 
 5428: ###############################################
 5429: sub pprmlink {
 5430:     my ($text,$uname,$udom,$symb,$target)=@_;
 5431:     if (!($uname && $udom)) {
 5432: 	(my $cursymb, my $courseid,$udom,$uname)=
 5433: 	    &Apache::lonnet::whichuser($symb);
 5434: 	if (!$symb) { $symb=$cursymb; }
 5435:     }
 5436:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5437:     $symb=&escape($symb);
 5438:     if ($target) { $target="target=\"$target\""; }
 5439:     return '<a href="/adm/parmset?command=set&amp;'.
 5440: 	'symb='.$symb.'&amp;uname='.$uname.
 5441: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 5442: }
 5443: ##############################################
 5444: 
 5445: =pod
 5446: 
 5447: =back
 5448: 
 5449: =cut
 5450: 
 5451: ###############################################
 5452: 
 5453: 
 5454: sub timehash {
 5455:     my ($thistime) = @_;
 5456:     my $timezone = &Apache::lonlocal::gettimezone();
 5457:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5458:                      ->set_time_zone($timezone);
 5459:     my $wday = $dt->day_of_week();
 5460:     if ($wday == 7) { $wday = 0; }
 5461:     return ( 'second' => $dt->second(),
 5462:              'minute' => $dt->minute(),
 5463:              'hour'   => $dt->hour(),
 5464:              'day'     => $dt->day_of_month(),
 5465:              'month'   => $dt->month(),
 5466:              'year'    => $dt->year(),
 5467:              'weekday' => $wday,
 5468:              'dayyear' => $dt->day_of_year(),
 5469:              'dlsav'   => $dt->is_dst() );
 5470: }
 5471: 
 5472: sub utc_string {
 5473:     my ($date)=@_;
 5474:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5475: }
 5476: 
 5477: sub maketime {
 5478:     my %th=@_;
 5479:     my ($epoch_time,$timezone,$dt);
 5480:     $timezone = &Apache::lonlocal::gettimezone();
 5481:     eval {
 5482:         $dt = DateTime->new( year   => $th{'year'},
 5483:                              month  => $th{'month'},
 5484:                              day    => $th{'day'},
 5485:                              hour   => $th{'hour'},
 5486:                              minute => $th{'minute'},
 5487:                              second => $th{'second'},
 5488:                              time_zone => $timezone,
 5489:                          );
 5490:     };
 5491:     if (!$@) {
 5492:         $epoch_time = $dt->epoch;
 5493:         if ($epoch_time) {
 5494:             return $epoch_time;
 5495:         }
 5496:     }
 5497:     return POSIX::mktime(
 5498:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5499:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5500: }
 5501: 
 5502: #########################################
 5503: 
 5504: sub findallcourses {
 5505:     my ($roles,$uname,$udom) = @_;
 5506:     my %roles;
 5507:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5508:     my %courses;
 5509:     my $now=time;
 5510:     if (!defined($uname)) {
 5511:         $uname = $env{'user.name'};
 5512:     }
 5513:     if (!defined($udom)) {
 5514:         $udom = $env{'user.domain'};
 5515:     }
 5516:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5517:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5518:         if (!%roles) {
 5519:             %roles = (
 5520:                        cc => 1,
 5521:                        co => 1,
 5522:                        in => 1,
 5523:                        ep => 1,
 5524:                        ta => 1,
 5525:                        cr => 1,
 5526:                        st => 1,
 5527:              );
 5528:         }
 5529:         foreach my $entry (keys(%roleshash)) {
 5530:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5531:             if ($trole =~ /^cr/) { 
 5532:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5533:             } else {
 5534:                 next if (!exists($roles{$trole}));
 5535:             }
 5536:             if ($tend) {
 5537:                 next if ($tend < $now);
 5538:             }
 5539:             if ($tstart) {
 5540:                 next if ($tstart > $now);
 5541:             }
 5542:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5543:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5544:             my $value = $trole.'/'.$cdom.'/';
 5545:             if ($secpart eq '') {
 5546:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5547:                 $sec = 'none';
 5548:                 $value .= $cnum.'/';
 5549:             } else {
 5550:                 $cnum = $cnumpart;
 5551:                 ($sec,$role) = split(/_/,$secpart);
 5552:                 $value .= $cnum.'/'.$sec;
 5553:             }
 5554:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5555:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5556:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5557:                 }
 5558:             } else {
 5559:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5560:             }
 5561:         }
 5562:     } else {
 5563:         foreach my $key (keys(%env)) {
 5564: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5565:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5566: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5567: 	        next if ($role eq 'ca' || $role eq 'aa');
 5568: 	        next if (%roles && !exists($roles{$role}));
 5569: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5570:                 my $active=1;
 5571:                 if ($starttime) {
 5572: 		    if ($now<$starttime) { $active=0; }
 5573:                 }
 5574:                 if ($endtime) {
 5575:                     if ($now>$endtime) { $active=0; }
 5576:                 }
 5577:                 if ($active) {
 5578:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5579:                     if ($sec eq '') {
 5580:                         $sec = 'none';
 5581:                     } else {
 5582:                         $value .= $sec;
 5583:                     }
 5584:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5585:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5586:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5587:                         }
 5588:                     } else {
 5589:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5590:                     }
 5591:                 }
 5592:             }
 5593:         }
 5594:     }
 5595:     return %courses;
 5596: }
 5597: 
 5598: ###############################################
 5599: 
 5600: sub blockcheck {
 5601:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5602:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 5603:         my ($has_evb,$check_ipaccess);
 5604:         my $dom = $env{'user.domain'};
 5605:         if ($env{'request.course.id'}) {
 5606:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5607:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5608:             my $checkrole = "cm./$cdom/$cnum";
 5609:             my $sec = $env{'request.course.sec'};
 5610:             if ($sec ne '') {
 5611:                 $checkrole .= "/$sec";
 5612:             }
 5613:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 5614:                 ($env{'request.role'} !~ /^st/)) {
 5615:                 $has_evb = 1;
 5616:             }
 5617:             unless ($has_evb) {
 5618:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 5619:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 5620:                     if ($udom eq $cdom) {
 5621:                         $check_ipaccess = 1;
 5622:                     }
 5623:                 }
 5624:             }
 5625:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 5626:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 5627:             my $checkrole;
 5628:             if ($env{'request.role.domain'} eq '') {
 5629:                 $checkrole = "cm./$env{'user.domain'}/";
 5630:             } else {
 5631:                 $checkrole = "cm./$env{'request.role.domain'}/";
 5632:             }
 5633:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 5634:                 $has_evb = 1;
 5635:             }
 5636:         }
 5637:         unless ($has_evb || $check_ipaccess) {
 5638:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 5639:             if (($dom eq 'public') && ($activity eq 'port')) {
 5640:                 $dom = $udom;
 5641:             }
 5642:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 5643:                 $check_ipaccess = 1;
 5644:             } else {
 5645:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 5646:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 5647:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 5648:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 5649:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 5650:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 5651:                         $check_ipaccess = 1;
 5652:                     }
 5653:                 }
 5654:             }
 5655:         }
 5656:         if ($check_ipaccess) {
 5657:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 5658:             unless (defined($cached)) {
 5659:                 my %domconfig =
 5660:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 5661:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 5662:             }
 5663:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 5664:                 foreach my $id (keys(%{$ipaccessref})) {
 5665:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 5666:                         my $range = $ipaccessref->{$id}->{'ip'};
 5667:                         if ($range) {
 5668:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 5669:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 5670:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 5671:                                         return ('','','',$id,$dom);
 5672:                                         last;
 5673:                                     }
 5674:                                 }
 5675:                             }
 5676:                         }
 5677:                     }
 5678:                 }
 5679:             }
 5680:         }
 5681:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5682:             return ();
 5683:         }
 5684:     }
 5685:     if (defined($udom) && defined($uname)) {
 5686:         # If uname and udom are for a course, check for blocks in the course.
 5687:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5688:             my ($startblock,$endblock,$triggerblock) =
 5689:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5690:             return ($startblock,$endblock,$triggerblock);
 5691:         }
 5692:     } else {
 5693:         $udom = $env{'user.domain'};
 5694:         $uname = $env{'user.name'};
 5695:     }
 5696: 
 5697:     my $startblock = 0;
 5698:     my $endblock = 0;
 5699:     my $triggerblock = '';
 5700:     my %live_courses;
 5701:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5702:         %live_courses = &findallcourses(undef,$uname,$udom);
 5703:     }
 5704: 
 5705:     # If uname is for a user, and activity is course-specific, i.e.,
 5706:     # boards, chat or groups, check for blocking in current course only.
 5707: 
 5708:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5709:          $activity eq 'groups' || $activity eq 'printout' ||
 5710:          $activity eq 'search' || $activity eq 'reinit' ||
 5711:          $activity eq 'alert') &&
 5712:         ($env{'request.course.id'})) {
 5713:         foreach my $key (keys(%live_courses)) {
 5714:             if ($key ne $env{'request.course.id'}) {
 5715:                 delete($live_courses{$key});
 5716:             }
 5717:         }
 5718:     }
 5719: 
 5720:     my $otheruser = 0;
 5721:     my %own_courses;
 5722:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5723:         # Resource belongs to user other than current user.
 5724:         $otheruser = 1;
 5725:         # Gather courses for current user
 5726:         %own_courses = 
 5727:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5728:     }
 5729: 
 5730:     # Gather active course roles - course coordinator, instructor, 
 5731:     # exam proctor, ta, student, or custom role.
 5732: 
 5733:     foreach my $course (keys(%live_courses)) {
 5734:         my ($cdom,$cnum);
 5735:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5736:             $cdom = $env{'course.'.$course.'.domain'};
 5737:             $cnum = $env{'course.'.$course.'.num'};
 5738:         } else {
 5739:             ($cdom,$cnum) = split(/_/,$course); 
 5740:         }
 5741:         my $no_ownblock = 0;
 5742:         my $no_userblock = 0;
 5743:         if ($otheruser && $activity ne 'com') {
 5744:             # Check if current user has 'evb' priv for this
 5745:             if (defined($own_courses{$course})) {
 5746:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5747:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5748:                     if ($sec ne 'none') {
 5749:                         $checkrole .= '/'.$sec;
 5750:                     }
 5751:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5752:                         $no_ownblock = 1;
 5753:                         last;
 5754:                     }
 5755:                 }
 5756:             }
 5757:             # if they have 'evb' priv and are currently not playing student
 5758:             next if (($no_ownblock) &&
 5759:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5760:         }
 5761:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5762:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5763:             if ($sec ne 'none') {
 5764:                 $checkrole .= '/'.$sec;
 5765:             }
 5766:             if ($otheruser) {
 5767:                 # Resource belongs to user other than current user.
 5768:                 # Assemble privs for that user, and check for 'evb' priv.
 5769:                 my (%allroles,%userroles);
 5770:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5771:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5772:                         my ($trole,$tdom,$tnum,$tsec);
 5773:                         if ($entry =~ /^cr/) {
 5774:                             ($trole,$tdom,$tnum,$tsec) = 
 5775:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5776:                         } else {
 5777:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5778:                         }
 5779:                         my ($spec,$area,$trest);
 5780:                         $area = '/'.$tdom.'/'.$tnum;
 5781:                         $trest = $tnum;
 5782:                         if ($tsec ne '') {
 5783:                             $area .= '/'.$tsec;
 5784:                             $trest .= '/'.$tsec;
 5785:                         }
 5786:                         $spec = $trole.'.'.$area;
 5787:                         if ($trole =~ /^cr/) {
 5788:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5789:                                                               $tdom,$spec,$trest,$area);
 5790:                         } else {
 5791:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5792:                                                                 $tdom,$spec,$trest,$area);
 5793:                         }
 5794:                     }
 5795:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5796:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5797:                         if ($1) {
 5798:                             $no_userblock = 1;
 5799:                             last;
 5800:                         }
 5801:                     }
 5802:                 }
 5803:             } else {
 5804:                 # Resource belongs to current user
 5805:                 # Check for 'evb' priv via lonnet::allowed().
 5806:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5807:                     $no_ownblock = 1;
 5808:                     last;
 5809:                 }
 5810:             }
 5811:         }
 5812:         # if they have the evb priv and are currently not playing student
 5813:         next if (($no_ownblock) &&
 5814:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5815:         next if ($no_userblock);
 5816: 
 5817:         # Retrieve blocking times and identity of blocker for course
 5818:         # of specified user, unless user has 'evb' privilege.
 5819: 
 5820:         my ($start,$end,$trigger) = 
 5821:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5822:         if (($start != 0) && 
 5823:             (($startblock == 0) || ($startblock > $start))) {
 5824:             $startblock = $start;
 5825:             if ($trigger ne '') {
 5826:                 $triggerblock = $trigger;
 5827:             }
 5828:         }
 5829:         if (($end != 0)  &&
 5830:             (($endblock == 0) || ($endblock < $end))) {
 5831:             $endblock = $end;
 5832:             if ($trigger ne '') {
 5833:                 $triggerblock = $trigger;
 5834:             }
 5835:         }
 5836:     }
 5837:     return ($startblock,$endblock,$triggerblock);
 5838: }
 5839: 
 5840: sub get_blocks {
 5841:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5842:     my $startblock = 0;
 5843:     my $endblock = 0;
 5844:     my $triggerblock = '';
 5845:     my $course = $cdom.'_'.$cnum;
 5846:     $setters->{$course} = {};
 5847:     $setters->{$course}{'staff'} = [];
 5848:     $setters->{$course}{'times'} = [];
 5849:     $setters->{$course}{'triggers'} = [];
 5850:     my (@blockers,%triggered);
 5851:     my $now = time;
 5852:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5853:     if ($activity eq 'docs') {
 5854:         my ($blocked,$nosymbcache,$noenccheck);
 5855:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5856:             $blocked = 1;
 5857:             $nosymbcache = 1;
 5858:             $noenccheck = 1;
 5859:         }
 5860:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5861:         foreach my $block (@blockers) {
 5862:             if ($block =~ /^firstaccess____(.+)$/) {
 5863:                 my $item = $1;
 5864:                 my $type = 'map';
 5865:                 my $timersymb = $item;
 5866:                 if ($item eq 'course') {
 5867:                     $type = 'course';
 5868:                 } elsif ($item =~ /___\d+___/) {
 5869:                     $type = 'resource';
 5870:                 } else {
 5871:                     $timersymb = &Apache::lonnet::symbread($item);
 5872:                 }
 5873:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5874:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5875:                 $triggered{$block} = {
 5876:                                        start => $start,
 5877:                                        end   => $end,
 5878:                                        type  => $type,
 5879:                                      };
 5880:             }
 5881:         }
 5882:     } else {
 5883:         foreach my $block (keys(%commblocks)) {
 5884:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5885:                 my ($start,$end) = ($1,$2);
 5886:                 if ($start <= time && $end >= time) {
 5887:                     if (ref($commblocks{$block}) eq 'HASH') {
 5888:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5889:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5890:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5891:                                     push(@blockers,$block);
 5892:                                 }
 5893:                             }
 5894:                         }
 5895:                     }
 5896:                 }
 5897:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5898:                 my $item = $1;
 5899:                 my $timersymb = $item; 
 5900:                 my $type = 'map';
 5901:                 if ($item eq 'course') {
 5902:                     $type = 'course';
 5903:                 } elsif ($item =~ /___\d+___/) {
 5904:                     $type = 'resource';
 5905:                 } else {
 5906:                     $timersymb = &Apache::lonnet::symbread($item);
 5907:                 }
 5908:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5909:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5910:                 if ($start && $end) {
 5911:                     if (($start <= time) && ($end >= time)) {
 5912:                         if (ref($commblocks{$block}) eq 'HASH') {
 5913:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5914:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5915:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5916:                                         push(@blockers,$block);
 5917:                                         $triggered{$block} = {
 5918:                                                                start => $start,
 5919:                                                                end   => $end,
 5920:                                                                type  => $type,
 5921:                                                              };
 5922:                                     }
 5923:                                 }
 5924:                             }
 5925:                         }
 5926:                     }
 5927:                 }
 5928:             }
 5929:         }
 5930:     }
 5931:     foreach my $blocker (@blockers) {
 5932:         my ($staff_name,$staff_dom,$title,$blocks) =
 5933:             &parse_block_record($commblocks{$blocker});
 5934:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5935:         my ($start,$end,$triggertype);
 5936:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5937:             ($start,$end) = ($1,$2);
 5938:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5939:             $start = $triggered{$blocker}{'start'};
 5940:             $end = $triggered{$blocker}{'end'};
 5941:             $triggertype = $triggered{$blocker}{'type'};
 5942:         }
 5943:         if ($start) {
 5944:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5945:             if ($triggertype) {
 5946:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5947:             } else {
 5948:                 push(@{$$setters{$course}{'triggers'}},0);
 5949:             }
 5950:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5951:                 $startblock = $start;
 5952:                 if ($triggertype) {
 5953:                     $triggerblock = $blocker;
 5954:                 }
 5955:             }
 5956:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5957:                $endblock = $end;
 5958:                if ($triggertype) {
 5959:                    $triggerblock = $blocker;
 5960:                }
 5961:             }
 5962:         }
 5963:     }
 5964:     return ($startblock,$endblock,$triggerblock);
 5965: }
 5966: 
 5967: sub parse_block_record {
 5968:     my ($record) = @_;
 5969:     my ($setuname,$setudom,$title,$blocks);
 5970:     if (ref($record) eq 'HASH') {
 5971:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5972:         $title = &unescape($record->{'event'});
 5973:         $blocks = $record->{'blocks'};
 5974:     } else {
 5975:         my @data = split(/:/,$record,3);
 5976:         if (scalar(@data) eq 2) {
 5977:             $title = $data[1];
 5978:             ($setuname,$setudom) = split(/@/,$data[0]);
 5979:         } else {
 5980:             ($setuname,$setudom,$title) = @data;
 5981:         }
 5982:         $blocks = { 'com' => 'on' };
 5983:     }
 5984:     return ($setuname,$setudom,$title,$blocks);
 5985: }
 5986: 
 5987: sub blocking_status {
 5988:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5989:     my %setters;
 5990: 
 5991: # check for active blocking
 5992:     if ($clientip eq '') {
 5993:         $clientip = &Apache::lonnet::get_requestor_ip();
 5994:     }
 5995:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5996:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5997:     my $blocked = 0;
 5998:     if (($startblock && $endblock) || ($by_ip)) {
 5999:         $blocked = 1;
 6000:     }
 6001: 
 6002: # caller just wants to know whether a block is active
 6003:     if (!wantarray) { return $blocked; }
 6004: 
 6005: # build a link to a popup window containing the details
 6006:     my $querystring  = "?activity=$activity";
 6007: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 6008:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 6009:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 6010:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 6011:     } elsif ($activity eq 'docs') {
 6012:         my $showurl = &Apache::lonenc::check_encrypt($url);
 6013:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 6014:         if ($symb) {
 6015:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 6016:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 6017:         }
 6018:     }
 6019: 
 6020:     my $output .= <<'END_MYBLOCK';
 6021: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 6022:     var options = "width=" + w + ",height=" + h + ",";
 6023:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 6024:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 6025:     var newWin = window.open(url, wdwName, options);
 6026:     newWin.focus();
 6027: }
 6028: END_MYBLOCK
 6029: 
 6030:     $output = Apache::lonhtmlcommon::scripttag($output);
 6031:   
 6032:     my $popupUrl = "/adm/blockingstatus/$querystring";
 6033:     my $text = &mt('Communication Blocked');
 6034:     my $class = 'LC_comblock';
 6035:     if ($activity eq 'docs') {
 6036:         $text = &mt('Content Access Blocked');
 6037:         $class = '';
 6038:     } elsif ($activity eq 'printout') {
 6039:         $text = &mt('Printing Blocked');
 6040:     } elsif ($activity eq 'passwd') {
 6041:         $text = &mt('Password Changing Blocked');
 6042:     } elsif ($activity eq 'grades') {
 6043:         $text = &mt('Gradebook Blocked');
 6044:     } elsif ($activity eq 'search') {
 6045:         $text = &mt('Search Blocked');
 6046:     } elsif ($activity eq 'alert') {
 6047:         $text = &mt('Checking Critical Messages Blocked');
 6048:     } elsif ($activity eq 'reinit') {
 6049:         $text = &mt('Checking Course Update Blocked');
 6050:     } elsif ($activity eq 'about') {
 6051:         $text = &mt('Access to User Information Pages Blocked');
 6052:     } elsif ($activity eq 'wishlist') {
 6053:         $text = &mt('Access to Stored Links Blocked');
 6054:     } elsif ($activity eq 'annotate') {
 6055:         $text = &mt('Access to Annotations Blocked');
 6056:     }
 6057:     $output .= <<"END_BLOCK";
 6058: <div class='$class'>
 6059:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 6060:   title='$text'>
 6061:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 6062:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 6063:   title='$text'>$text</a>
 6064: </div>
 6065: 
 6066: END_BLOCK
 6067: 
 6068:     return ($blocked, $output);
 6069: }
 6070: 
 6071: ###############################################
 6072: 
 6073: sub check_ip_acc {
 6074:     my ($acc,$clientip)=@_;
 6075:     &Apache::lonxml::debug("acc is $acc");
 6076:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 6077:         return 1;
 6078:     }
 6079:     my ($ip,$allowed);
 6080:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 6081:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 6082:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 6083:     } else {
 6084:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 6085:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 6086:     }
 6087: 
 6088:     my $name;
 6089:     my %access = (
 6090:                      allowfrom => 1,
 6091:                      denyfrom  => 0,
 6092:                  );
 6093:     my @allows;
 6094:     my @denies;
 6095:     foreach my $item (split(',',$acc)) {
 6096:         $item =~ s/^\s*//;
 6097:         $item =~ s/\s*$//;
 6098:         my $pattern;
 6099:         if ($item =~ /^\!(.+)$/) {
 6100:             push(@denies,$1);
 6101:         } else {
 6102:             push(@allows,$item);
 6103:         }
 6104:    }
 6105:    my $numdenies = scalar(@denies);
 6106:    my $numallows = scalar(@allows);
 6107:    my $count = 0;
 6108:    foreach my $pattern (@denies,@allows) {
 6109:         $count ++; 
 6110:         my $acctype = 'allowfrom';
 6111:         if ($count <= $numdenies) {
 6112:             $acctype = 'denyfrom';
 6113:         }
 6114:         if ($pattern =~ /\*$/) {
 6115:             #35.8.*
 6116:             $pattern=~s/\*//;
 6117:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6118:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 6119:             #35.8.3.[34-56]
 6120:             my $low=$2;
 6121:             my $high=$3;
 6122:             $pattern=$1;
 6123:             if ($ip =~ /^\Q$pattern\E/) {
 6124:                 my $last=(split(/\./,$ip))[3];
 6125:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 6126:             }
 6127:         } elsif ($pattern =~ /^\*/) {
 6128:             #*.msu.edu
 6129:             $pattern=~s/\*//;
 6130:             if (!defined($name)) {
 6131:                 use Socket;
 6132:                 my $netaddr=inet_aton($ip);
 6133:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6134:             }
 6135:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6136:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 6137:             #127.0.0.1
 6138:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6139:         } else {
 6140:             #some.name.com
 6141:             if (!defined($name)) {
 6142:                 use Socket;
 6143:                 my $netaddr=inet_aton($ip);
 6144:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6145:             }
 6146:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6147:         }
 6148:         if ($allowed =~ /^(0|1)$/) { last; }
 6149:     }
 6150:     if ($allowed eq '') {
 6151:         if ($numdenies && !$numallows) {
 6152:             $allowed = 1;
 6153:         } else {
 6154:             $allowed = 0;
 6155:         }
 6156:     }
 6157:     return $allowed;
 6158: }
 6159: 
 6160: ###############################################
 6161: 
 6162: =pod
 6163: 
 6164: =head1 Domain Template Functions
 6165: 
 6166: =over 4
 6167: 
 6168: =item * &determinedomain()
 6169: 
 6170: Inputs: $domain (usually will be undef)
 6171: 
 6172: Returns: Determines which domain should be used for designs
 6173: 
 6174: =cut
 6175: 
 6176: ###############################################
 6177: sub determinedomain {
 6178:     my $domain=shift;
 6179:     if (! $domain) {
 6180:         # Determine domain if we have not been given one
 6181:         $domain = &Apache::lonnet::default_login_domain();
 6182:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 6183:         if ($env{'request.role.domain'}) { 
 6184:             $domain=$env{'request.role.domain'}; 
 6185:         }
 6186:     }
 6187:     return $domain;
 6188: }
 6189: ###############################################
 6190: 
 6191: sub devalidate_domconfig_cache {
 6192:     my ($udom)=@_;
 6193:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 6194: }
 6195: 
 6196: # ---------------------- Get domain configuration for a domain
 6197: sub get_domainconf {
 6198:     my ($udom) = @_;
 6199:     my $cachetime=1800;
 6200:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 6201:     if (defined($cached)) { return %{$result}; }
 6202: 
 6203:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 6204: 					     ['login','rolecolors','autoenroll'],$udom);
 6205:     my (%designhash,%legacy);
 6206:     if (keys(%domconfig) > 0) {
 6207:         if (ref($domconfig{'login'}) eq 'HASH') {
 6208:             if (keys(%{$domconfig{'login'}})) {
 6209:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 6210:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6211:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 6212:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6213:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 6214:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 6215:                                         if ($key eq 'loginvia') {
 6216:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 6217:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 6218:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 6219:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 6220: 
 6221:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 6222:                                                 } else {
 6223:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 6224:                                                 }
 6225:                                             }
 6226:                                         } elsif ($key eq 'headtag') {
 6227:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 6228:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 6229:                                             }
 6230:                                         }
 6231:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 6232:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 6233:                                         }
 6234:                                     }
 6235:                                 }
 6236:                             }
 6237:                         } elsif ($key eq 'saml') {
 6238:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6239:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 6240:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 6241:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 6242:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 6243:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 6244:                                         }
 6245:                                     }
 6246:                                 }
 6247:                             }
 6248:                         } else {
 6249:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 6250:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 6251:                                     $domconfig{'login'}{$key}{$img};
 6252:                             }
 6253:                         }
 6254:                     } else {
 6255:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 6256:                     }
 6257:                 }
 6258:             } else {
 6259:                 $legacy{'login'} = 1;
 6260:             }
 6261:         } else {
 6262:             $legacy{'login'} = 1;
 6263:         }
 6264:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 6265:             if (keys(%{$domconfig{'rolecolors'}})) {
 6266:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 6267:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 6268:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 6269:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 6270:                         }
 6271:                     }
 6272:                 }
 6273:             } else {
 6274:                 $legacy{'rolecolors'} = 1;
 6275:             }
 6276:         } else {
 6277:             $legacy{'rolecolors'} = 1;
 6278:         }
 6279:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6280:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 6281:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 6282:             }
 6283:         }
 6284:         if (keys(%legacy) > 0) {
 6285:             my %legacyhash = &get_legacy_domconf($udom);
 6286:             foreach my $item (keys(%legacyhash)) {
 6287:                 if ($item =~ /^\Q$udom\E\.login/) {
 6288:                     if ($legacy{'login'}) { 
 6289:                         $designhash{$item} = $legacyhash{$item};
 6290:                     }
 6291:                 } else {
 6292:                     if ($legacy{'rolecolors'}) {
 6293:                         $designhash{$item} = $legacyhash{$item};
 6294:                     }
 6295:                 }
 6296:             }
 6297:         }
 6298:     } else {
 6299:         %designhash = &get_legacy_domconf($udom); 
 6300:     }
 6301:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 6302: 				  $cachetime);
 6303:     return %designhash;
 6304: }
 6305: 
 6306: sub get_legacy_domconf {
 6307:     my ($udom) = @_;
 6308:     my %legacyhash;
 6309:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 6310:     my $designfile =  $designdir.'/'.$udom.'.tab';
 6311:     if (-e $designfile) {
 6312:         if ( open (my $fh,'<',$designfile) ) {
 6313:             while (my $line = <$fh>) {
 6314:                 next if ($line =~ /^\#/);
 6315:                 chomp($line);
 6316:                 my ($key,$val)=(split(/\=/,$line));
 6317:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 6318:             }
 6319:             close($fh);
 6320:         }
 6321:     }
 6322:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 6323:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 6324:     }
 6325:     return %legacyhash;
 6326: }
 6327: 
 6328: =pod
 6329: 
 6330: =item * &domainlogo()
 6331: 
 6332: Inputs: $domain (usually will be undef)
 6333: 
 6334: Returns: A link to a domain logo, if the domain logo exists.
 6335: If the domain logo does not exist, a description of the domain.
 6336: 
 6337: =cut
 6338: 
 6339: ###############################################
 6340: sub domainlogo {
 6341:     my $domain = &determinedomain(shift);
 6342:     my %designhash = &get_domainconf($domain);    
 6343:     # See if there is a logo
 6344:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 6345:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 6346:         if ($imgsrc =~ m{^/(adm|res)/}) {
 6347: 	    if ($imgsrc =~ m{^/res/}) {
 6348: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 6349: 		&Apache::lonnet::repcopy($local_name);
 6350: 	    }
 6351: 	   $imgsrc = &lonhttpdurl($imgsrc);
 6352:         }
 6353:         my $alttext = $domain;
 6354:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 6355:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 6356:         }
 6357:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 6358:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 6359:         return &Apache::lonnet::domain($domain,'description');
 6360:     } else {
 6361:         return '';
 6362:     }
 6363: }
 6364: ##############################################
 6365: 
 6366: =pod
 6367: 
 6368: =item * &designparm()
 6369: 
 6370: Inputs: $which parameter; $domain (usually will be undef)
 6371: 
 6372: Returns: value of designparamter $which
 6373: 
 6374: =cut
 6375: 
 6376: 
 6377: ##############################################
 6378: sub designparm {
 6379:     my ($which,$domain)=@_;
 6380:     if (exists($env{'environment.color.'.$which})) {
 6381:         return $env{'environment.color.'.$which};
 6382:     }
 6383:     $domain=&determinedomain($domain);
 6384:     my %domdesign;
 6385:     unless ($domain eq 'public') {
 6386:         %domdesign = &get_domainconf($domain);
 6387:     }
 6388:     my $output;
 6389:     if ($domdesign{$domain.'.'.$which} ne '') {
 6390:         $output = $domdesign{$domain.'.'.$which};
 6391:     } else {
 6392:         $output = $defaultdesign{$which};
 6393:     }
 6394:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 6395:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 6396:         if ($output =~ m{^/(adm|res)/}) {
 6397:             if ($output =~ m{^/res/}) {
 6398:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 6399:                 &Apache::lonnet::repcopy($local_name);
 6400:             }
 6401:             $output = &lonhttpdurl($output);
 6402:         }
 6403:     }
 6404:     return $output;
 6405: }
 6406: 
 6407: ##############################################
 6408: =pod
 6409: 
 6410: =item * &authorspace()
 6411: 
 6412: Inputs: $url (usually will be undef).
 6413: 
 6414: Returns: Path to Authoring Space containing the resource or 
 6415:          directory being viewed (or for which action is being taken). 
 6416:          If $url is provided, and begins /priv/<domain>/<uname>
 6417:          the path will be that portion of the $context argument.
 6418:          Otherwise the path will be for the author space of the current
 6419:          user when the current role is author, or for that of the 
 6420:          co-author/assistant co-author space when the current role 
 6421:          is co-author or assistant co-author.
 6422: 
 6423: =cut
 6424: 
 6425: sub authorspace {
 6426:     my ($url) = @_;
 6427:     if ($url ne '') {
 6428:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 6429:            return $1;
 6430:         }
 6431:     }
 6432:     my $caname = '';
 6433:     my $cadom = '';
 6434:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 6435:         ($cadom,$caname) =
 6436:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 6437:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 6438:         $caname = $env{'user.name'};
 6439:         $cadom = $env{'user.domain'};
 6440:     }
 6441:     if (($caname ne '') && ($cadom ne '')) {
 6442:         return "/priv/$cadom/$caname/";
 6443:     }
 6444:     return;
 6445: }
 6446: 
 6447: ##############################################
 6448: =pod
 6449: 
 6450: =item * &head_subbox()
 6451: 
 6452: Inputs: $content (contains HTML code with page functions, etc.)
 6453: 
 6454: Returns: HTML div with $content
 6455:          To be included in page header
 6456: 
 6457: =cut
 6458: 
 6459: sub head_subbox {
 6460:     my ($content)=@_;
 6461:     my $output =
 6462:         '<div class="LC_head_subbox">'
 6463:        .$content
 6464:        .'</div>'
 6465: }
 6466: 
 6467: ##############################################
 6468: =pod
 6469: 
 6470: =item * &CSTR_pageheader()
 6471: 
 6472: Input: (optional) filename from which breadcrumb trail is built.
 6473:        In most cases no input as needed, as $env{'request.filename'}
 6474:        is appropriate for use in building the breadcrumb trail.
 6475:        frameset flag
 6476:        If page header is being requested for use in a frameset, then
 6477:        the second (option) argument -- frameset will be true, and
 6478:        the target attribute set for links should be target="_parent".
 6479:        If $title is supplied as the thitd arg, that will be used to 
 6480:        the left of the breadcrumbs tail for the current path.
 6481: 
 6482: Returns: HTML div with CSTR path and recent box
 6483:          To be included on Authoring Space pages
 6484: 
 6485: =cut
 6486: 
 6487: sub CSTR_pageheader {
 6488:     my ($trailfile,$frameset,$title) = @_;
 6489:     if ($trailfile eq '') {
 6490:         $trailfile = $env{'request.filename'};
 6491:     }
 6492: 
 6493: # this is for resources; directories have customtitle, and crumbs
 6494: # and select recent are created in lonpubdir.pm
 6495: 
 6496:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 6497:     my ($udom,$uname,$thisdisfn)=
 6498:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 6499:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 6500:     $formaction =~ s{/+}{/}g;
 6501: 
 6502:     my $parentpath = '';
 6503:     my $lastitem = '';
 6504:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 6505:         $parentpath = $1;
 6506:         $lastitem = $2;
 6507:     } else {
 6508:         $lastitem = $thisdisfn;
 6509:     }
 6510: 
 6511:     my $crsauthor;
 6512:     if (($env{'request.course.id'}) &&
 6513:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 6514:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 6515:         $crsauthor = 1;
 6516:         if ($title eq '') {
 6517:             $title = &mt('Course Authoring Space');
 6518:         }
 6519:     } elsif ($title eq '') {
 6520:         $title = &mt('Authoring Space');
 6521:     }
 6522: 
 6523:     my ($target,$crumbtarget) = (' target="_top"','_top');
 6524:     if ($frameset) {
 6525:         $target = ' target="_parent"';
 6526:         $crumbtarget = '_parent';
 6527:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 6528:         $target = '';
 6529:         $crumbtarget = '';
 6530:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 6531:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 6532:         $crumbtarget = $env{'request.deeplink.target'};
 6533:     }
 6534: 
 6535:     my $output =
 6536:          '<div>'
 6537:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 6538:         .'<b>'.$title.'</b> '
 6539:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 6540:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 6541: 
 6542:     if ($lastitem) {
 6543:         $output .=
 6544:              '<span class="LC_filename">'
 6545:             .$lastitem
 6546:             .'</span>';
 6547:     }
 6548: 
 6549:     if ($crsauthor) {
 6550:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
 6551:     } else {
 6552:         $output .=
 6553:              '<br />'
 6554:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 6555:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 6556:             .'</form>'
 6557:             .&Apache::lonmenu::constspaceform($frameset);
 6558:     }
 6559:     $output .= '</div>';
 6560: 
 6561:     return $output;
 6562: }
 6563: 
 6564: ##############################################
 6565: =pod
 6566: 
 6567: =item * &nocodemirror()
 6568: 
 6569: Input: None
 6570: 
 6571: Returns: 1 if CodeMirror is deactivated based on
 6572:          user's preference, or domain default,
 6573:          if user indicated use of default.
 6574: 
 6575: =cut
 6576: 
 6577: sub nocodemirror {
 6578:     my $nocodem = $env{'environment.nocodemirror'};
 6579:     unless ($nocodem) {
 6580:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 6581:         if ($domdefs{'nocodemirror'}) {
 6582:             $nocodem = 'yes';
 6583:         }
 6584:     }
 6585:     if ($nocodem eq 'yes') {
 6586:         return 1;
 6587:     }
 6588:     return;
 6589: }
 6590: 
 6591: ##############################################
 6592: =pod
 6593: 
 6594: =item * &permitted_editors()
 6595: 
 6596: Input: $uri (optional)
 6597: 
 6598: Returns: %editors hash in which keys are editors
 6599:          permitted in current Authoring Space.
 6600:          Value for each key is 1. Possible keys
 6601:          are: edit, xml, and daxe. If no specific
 6602:          set of editors has been set for the Author
 6603:          who owns the Authoring Space, then the
 6604:          domain default will be used.  If no domain
 6605:          default has been set, then the keys will be
 6606:          edit and xml.
 6607: 
 6608: =cut
 6609: 
 6610: sub permitted_editors {
 6611:     my ($uri) = @_;
 6612:     my ($is_author,$is_coauthor,$auname,$audom,%editors);
 6613:     if ($env{'request.role'} =~ m{^au\./}) {
 6614:         $is_author = 1;
 6615:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
 6616:         ($audom,$auname) = ($1,$2);
 6617:         if (($audom ne '') && ($auname ne '')) {
 6618:             if (($env{'user.domain'} eq $audom) &&
 6619:                 ($env{'user.name'} eq $auname)) {
 6620:                 $is_author = 1;
 6621:             } else {
 6622:                 $is_coauthor = 1;
 6623:             }
 6624:         }
 6625:     } elsif ($env{'request.course.id'}) {
 6626:         if ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
 6627:             ($audom,$auname) = ($1,$2);
 6628:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
 6629:             ($audom,$auname) = ($1,$2);
 6630:         } elsif (($uri eq '/daxesave') &&
 6631:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
 6632:             ($audom,$auname) = ($1,$2);
 6633:         }
 6634:         if (($audom ne '') && ($auname ne '')) {
 6635:             if (($env{'user.domain'} eq $audom) &&
 6636:                 ($env{'user.name'} eq $auname)) {
 6637:                 $is_author = 1;
 6638:             } else {
 6639:                 $is_coauthor = 1;
 6640:             }
 6641:         }
 6642:     }
 6643:     if ($is_author) {
 6644:         if (exists($env{'environment.editors'})) {
 6645:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
 6646:         } else {
 6647:             %editors = ( edit => 1,
 6648:                          xml => 1,
 6649:                        );
 6650:         }
 6651:     } elsif ($is_coauthor) {
 6652:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
 6653:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
 6654:         } else {
 6655:             %editors = ( edit => 1,
 6656:                          xml => 1,
 6657:                        );
 6658:         }
 6659:     } else {
 6660:         %editors = ( edit => 1,
 6661:                      xml => 1,
 6662:                    );
 6663:     }
 6664:     return %editors;
 6665: }
 6666: 
 6667: ###############################################
 6668: ###############################################
 6669: 
 6670: =pod
 6671: 
 6672: =back
 6673: 
 6674: =head1 HTML Helpers
 6675: 
 6676: =over 4
 6677: 
 6678: =item * &bodytag()
 6679: 
 6680: Returns a uniform header for LON-CAPA web pages.
 6681: 
 6682: Inputs: 
 6683: 
 6684: =over 4
 6685: 
 6686: =item * $title, A title to be displayed on the page.
 6687: 
 6688: =item * $function, the current role (can be undef).
 6689: 
 6690: =item * $addentries, extra parameters for the <body> tag.
 6691: 
 6692: =item * $bodyonly, if defined, only return the <body> tag.
 6693: 
 6694: =item * $domain, if defined, force a given domain.
 6695: 
 6696: =item * $forcereg, if page should register as content page (relevant for 
 6697:             text interface only)
 6698: 
 6699: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6700:                      navigational links
 6701: 
 6702: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6703: 
 6704: =item * $args, optional argument valid values are
 6705:             no_auto_mt_title -> prevents &mt()ing the title arg
 6706:             use_absolute     -> for external resource or syllabus, this will
 6707:                                 contain https://<hostname> if server uses
 6708:                                 https (as per hosts.tab), but request is for http
 6709:             hostname         -> hostname, from $r->hostname().
 6710: 
 6711: =item * $advtoolsref, optional argument, ref to an array containing
 6712:             inlineremote items to be added in "Functions" menu below
 6713:             breadcrumbs.
 6714: 
 6715: =item * $ltiscope, optional argument, will be one of: resource, map or
 6716:             course, if LON-CAPA is in LTI Provider context. Value is
 6717:             the scope of use, i.e., launch was for access to a single, a map
 6718:             or the entire course.
 6719: 
 6720: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6721:             context, this will contain the URL for the landing item in
 6722:             the course, after launch from an LTI Consumer
 6723: 
 6724: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6725:             context, this will contain a reference to hash of items
 6726:             to be included in the page header and/or inline menu.
 6727: 
 6728: =item * $menucoll, optional argument, if specific menu collection is in
 6729:             effect, either set as the default for the course, or set for
 6730:             the deeplink paramater for $env{'request.deeplink.login'}
 6731:             then $menucoll will be the number of that collection. 
 6732: 
 6733: =item * $menuref, optional argument, reference to a hash, containing the
 6734:             menu options included for the menu in effect, based on the
 6735:             configuration for the numbered menu collection in use.  
 6736: 
 6737: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 6738:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 6739:             if so, $showncrumbsref is set there to 1, and will propagate back
 6740:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 6741:             being called a second time.
 6742: 
 6743: =back
 6744: 
 6745: Returns: A uniform header for LON-CAPA web pages.  
 6746: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6747: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6748: other decorations will be returned.
 6749: 
 6750: =cut
 6751: 
 6752: sub bodytag {
 6753:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6754:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
 6755:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 6756: 
 6757:     my $public;
 6758:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6759:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6760:         $public = 1;
 6761:     }
 6762:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6763:     my $httphost = $args->{'use_absolute'};
 6764:     my $hostname = $args->{'hostname'};
 6765: 
 6766:     $function = &get_users_function() if (!$function);
 6767:     my $img =    &designparm($function.'.img',$domain);
 6768:     my $font =   &designparm($function.'.font',$domain);
 6769:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6770: 
 6771:     my %design = ( 'style'   => 'margin-top: 0',
 6772: 		   'bgcolor' => $pgbg,
 6773: 		   'text'    => $font,
 6774:                    'alink'   => &designparm($function.'.alink',$domain),
 6775: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6776: 		   'link'    => &designparm($function.'.link',$domain),);
 6777:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6778: 
 6779:  # role and realm
 6780:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6781:     if ($realm) {
 6782:         $realm = '/'.$realm;
 6783:     }
 6784:     if ($role eq 'ca') {
 6785:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6786:         $realm = &plainname($rname,$rdom);
 6787:     } 
 6788: # realm
 6789:     my ($cid,$sec);
 6790:     if ($env{'request.course.id'}) {
 6791:         $cid = $env{'request.course.id'};
 6792:         if ($env{'request.course.sec'}) {
 6793:             $sec = $env{'request.course.sec'};
 6794:         }
 6795:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 6796:         if (&Apache::lonnet::is_course($1,$2)) {
 6797:             $cid = $1.'_'.$2;
 6798:             $sec = $3;
 6799:         }
 6800:     }
 6801:     if ($cid) {
 6802:         if ($env{'request.role'} !~ /^cr/) {
 6803:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6804:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6805:             if ($env{'request.role.desc'}) {
 6806:                 $role = $env{'request.role.desc'};
 6807:             } else {
 6808:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6809:             }
 6810:         } else {
 6811:             $role = (split(/\//,$role,4))[-1]; 
 6812:         }
 6813:         if ($sec) {
 6814:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6815:         }   
 6816: 	$realm = $env{'course.'.$cid.'.description'};
 6817:     } else {
 6818:         $role = &Apache::lonnet::plaintext($role);
 6819:     }
 6820: 
 6821:     if (!$realm) { $realm='&nbsp;'; }
 6822: 
 6823:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6824: 
 6825: # construct main body tag
 6826:     my $bodytag = "<body $extra_body_attr>".
 6827: 	&Apache::lontexconvert::init_math_support();
 6828: 
 6829:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6830: 
 6831:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6832:         return $bodytag;
 6833:     }
 6834: 
 6835:     if ($public) {
 6836: 	undef($role);
 6837:     }
 6838: 
 6839:     my $showcrstitle = 1;
 6840:     if (($cid) && ($env{'request.lti.login'})) {
 6841:         if (ref($ltimenu) eq 'HASH') {
 6842:             unless ($ltimenu->{'role'}) {
 6843:                 undef($role);
 6844:             }
 6845:             unless ($ltimenu->{'coursetitle'}) {
 6846:                 $realm='&nbsp;';
 6847:                 $showcrstitle = 0;
 6848:             }
 6849:         }
 6850:     } elsif (($cid) && ($menucoll)) {
 6851:         if (ref($menuref) eq 'HASH') {
 6852:             unless ($menuref->{'role'}) {
 6853:                 undef($role);
 6854:             }
 6855:             unless ($menuref->{'crs'}) {
 6856:                 $realm='&nbsp;';
 6857:                 $showcrstitle = 0;
 6858:             }
 6859:         }
 6860:     }
 6861: 
 6862:     my $titleinfo = '<h1>'.$title.'</h1>';
 6863:     #
 6864:     # Extra info if you are the DC
 6865:     my $dc_info = '';
 6866:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6867:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6868:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6869:         $dc_info =~ s/\s+$//;
 6870:     }
 6871: 
 6872:     my $crstype;
 6873:     if ($cid) {
 6874:         $crstype = $env{'course.'.$cid.'.type'};
 6875:     } elsif ($args->{'crstype'}) {
 6876:         $crstype = $args->{'crstype'};
 6877:     }
 6878:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6879:         undef($role);
 6880:     } else {
 6881:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6882:     }
 6883: 
 6884:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6885: 
 6886:         #    if ($env{'request.state'} eq 'construct') {
 6887:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6888:         #    }
 6889: 
 6890:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6891:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6892: 
 6893:         if ($args->{'collapsible_header'} ne '') {
 6894:             my $alttext = &mt('menu state: collapsed');
 6895:             my $tooltip = &mt('display standard menus');
 6896:             $bodytag .= <<"END";
 6897: <div id="LC_expandingContainer" style="display:inline;">
 6898: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
 6899: <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/collapsed.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
 6900: <div class="LC_menus_content hidden">
 6901: END
 6902:         }
 6903:         unless ($args->{'no_primary_menu'}) {
 6904:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6905:                                                               $args->{'links_disabled'},
 6906:                                                               $args->{'links_target'},
 6907:                                                               $args->{'collapsible_header'});
 6908: 
 6909:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6910:                 if ($dc_info) {
 6911:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6912:                 }
 6913:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6914:                                <em>$realm</em> $dc_info</div>|;
 6915:                 return $bodytag;
 6916:             }
 6917: 
 6918:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6919:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6920:             }
 6921: 
 6922:             $bodytag .= $right;
 6923: 
 6924:             if ($dc_info) {
 6925:                 $dc_info = &dc_courseid_toggle($dc_info);
 6926:             }
 6927:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6928:         }
 6929: 
 6930:         #if directed to not display the secondary menu, don't.  
 6931:         if ($args->{'no_secondary_menu'}) {
 6932:             return $bodytag;
 6933:         }
 6934:         #don't show menus for public users
 6935:         if (!$public){
 6936:             unless ($args->{'no_inline_menu'}) {
 6937:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6938:                                                             $args->{'no_primary_menu'},
 6939:                                                             $menucoll,$menuref,
 6940:                                                             $args->{'links_disabled'},
 6941:                                                             $args->{'links_target'});
 6942:             }
 6943:             $bodytag .= Apache::lonmenu::serverform();
 6944:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6945:             if ($env{'request.state'} eq 'construct') {
 6946:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6947:                                 $args->{'bread_crumbs'},'','',$hostname,
 6948:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6949:             } elsif ($forcereg) {
 6950:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6951:                                 $args->{'group'},$args->{'hide_buttons'},
 6952:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6953:             } else {
 6954:                 $bodytag .= 
 6955:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6956:                                                         $forcereg,$args->{'group'},
 6957:                                                         $args->{'bread_crumbs'},
 6958:                                                         $advtoolsref,'',$hostname);
 6959:             }
 6960:         }else{
 6961:             # this is to seperate menu from content when there's no secondary
 6962:             # menu. Especially needed for public accessible ressources.
 6963:             $bodytag .= '<hr style="clear:both" />';
 6964:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6965:         }
 6966:         if ($args->{'collapsible_header'} ne '') {
 6967:             $bodytag .= $args->{'collapsible_header'}.
 6968:                         '<div id="LC_collapsible_separator"></div>'.
 6969:                         '</div></div>';
 6970:         }
 6971:         return $bodytag;
 6972: }
 6973: 
 6974: sub dc_courseid_toggle {
 6975:     my ($dc_info) = @_;
 6976:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6977:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6978:            &mt('(More ...)').'</a></span>'.
 6979:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6980: }
 6981: 
 6982: sub make_attr_string {
 6983:     my ($register,$attr_ref) = @_;
 6984: 
 6985:     if ($attr_ref && !ref($attr_ref)) {
 6986: 	die("addentries Must be a hash ref ".
 6987: 	    join(':',caller(1))." ".
 6988: 	    join(':',caller(0))." ");
 6989:     }
 6990: 
 6991:     if ($register) {
 6992: 	my ($on_load,$on_unload);
 6993: 	foreach my $key (keys(%{$attr_ref})) {
 6994: 	    if      (lc($key) eq 'onload') {
 6995: 		$on_load.=$attr_ref->{$key}.';';
 6996: 		delete($attr_ref->{$key});
 6997: 
 6998: 	    } elsif (lc($key) eq 'onunload') {
 6999: 		$on_unload.=$attr_ref->{$key}.';';
 7000: 		delete($attr_ref->{$key});
 7001: 	    }
 7002: 	}
 7003: 	$attr_ref->{'onload'}  = $on_load;
 7004: 	$attr_ref->{'onunload'}= $on_unload;
 7005:     }
 7006: 
 7007:     my $attr_string;
 7008:     foreach my $attr (sort(keys(%$attr_ref))) {
 7009: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 7010:     }
 7011:     return $attr_string;
 7012: }
 7013: 
 7014: 
 7015: ###############################################
 7016: ###############################################
 7017: 
 7018: =pod
 7019: 
 7020: =item * &endbodytag()
 7021: 
 7022: Returns a uniform footer for LON-CAPA web pages.
 7023: 
 7024: Inputs: 1 - optional reference to an args hash
 7025: If in the hash, key for noredirectlink has a value which evaluates to true,
 7026: a 'Continue' link is not displayed if the page contains an
 7027: internal redirect in the <head></head> section,
 7028: i.e., $env{'internal.head.redirect'} exists   
 7029: 
 7030: =cut
 7031: 
 7032: sub endbodytag {
 7033:     my ($args) = @_;
 7034:     my $endbodytag;
 7035:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 7036:         $endbodytag='</body>';
 7037:     }
 7038:     if ( exists( $env{'internal.head.redirect'} ) ) {
 7039:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 7040:             my ($endbodyjs,$idattr);
 7041:             if ($env{'internal.head.to_opener'}) {
 7042:                 my $linkid = 'LC_continue_link';
 7043:                 $idattr = ' id="'.$linkid.'"';
 7044:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 7045:                 $endbodyjs=<<ENDJS;
 7046: <script type="text/javascript">
 7047: // <![CDATA[
 7048: function ebFunction(evt) {
 7049:     evt.preventDefault();
 7050:     var dest = '$redirect_for_js';
 7051:     if (window.opener != null && !window.opener.closed) {
 7052:         window.opener.location.href=dest;
 7053:         window.close();
 7054:     } else {
 7055:         window.location.href=dest;
 7056:     }
 7057:     return false;
 7058: }
 7059: 
 7060: \$(document).ready(function () {
 7061:   if (document.getElementById('$linkid')) {
 7062:     var clickelem = document.getElementById('$linkid');
 7063:     clickelem.addEventListener('click',ebFunction,false);
 7064:   }
 7065: });
 7066: // ]]>
 7067: </script>
 7068: ENDJS
 7069:             }
 7070: 	    $endbodytag=
 7071: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 7072: 	        &mt('Continue').'</a>'.
 7073: 	        $endbodytag;
 7074:         }
 7075:     }
 7076:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
 7077:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
 7078:     }
 7079:     return $endbodytag;
 7080: }
 7081: 
 7082: =pod
 7083: 
 7084: =item * &standard_css()
 7085: 
 7086: Returns a style sheet
 7087: 
 7088: Inputs: (all optional)
 7089:             domain         -> force to color decorate a page for a specific
 7090:                                domain
 7091:             function       -> force usage of a specific rolish color scheme
 7092:             bgcolor        -> override the default page bgcolor
 7093: 
 7094: =cut
 7095: 
 7096: sub standard_css {
 7097:     my ($function,$domain,$bgcolor) = @_;
 7098:     $function  = &get_users_function() if (!$function);
 7099:     my $img    = &designparm($function.'.img',   $domain);
 7100:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 7101:     my $font   = &designparm($function.'.font',  $domain);
 7102:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 7103: #second colour for later usage
 7104:     my $sidebg = &designparm($function.'.sidebg',$domain);
 7105:     my $pgbg_or_bgcolor =
 7106: 	         $bgcolor ||
 7107: 	         &designparm($function.'.pgbg',  $domain);
 7108:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 7109:     my $alink  = &designparm($function.'.alink', $domain);
 7110:     my $vlink  = &designparm($function.'.vlink', $domain);
 7111:     my $link   = &designparm($function.'.link',  $domain);
 7112: 
 7113:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 7114:     my $mono                 = 'monospace';
 7115:     my $data_table_head      = $sidebg;
 7116:     my $data_table_light     = '#FAFAFA';
 7117:     my $data_table_dark      = '#E0E0E0';
 7118:     my $data_table_darker    = '#CCCCCC';
 7119:     my $data_table_highlight = '#FFFF00';
 7120:     my $mail_new             = '#FFBB77';
 7121:     my $mail_new_hover       = '#DD9955';
 7122:     my $mail_read            = '#BBBB77';
 7123:     my $mail_read_hover      = '#999944';
 7124:     my $mail_replied         = '#AAAA88';
 7125:     my $mail_replied_hover   = '#888855';
 7126:     my $mail_other           = '#99BBBB';
 7127:     my $mail_other_hover     = '#669999';
 7128:     my $table_header         = '#DDDDDD';
 7129:     my $feedback_link_bg     = '#BBBBBB';
 7130:     my $lg_border_color      = '#C8C8C8';
 7131:     my $button_hover         = '#BF2317';
 7132: 
 7133:     my $border = ($env{'browser.type'} eq 'explorer' ||
 7134:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 7135:                                              : '0 3px 0 4px';
 7136: 
 7137: 
 7138:     return <<END;
 7139: 
 7140: /* needed for iframe to allow 100% height in FF */
 7141: body, html { 
 7142:     margin: 0;
 7143:     padding: 0 0.5%;
 7144:     height: 99%; /* to avoid scrollbars */
 7145: }
 7146: 
 7147: body {
 7148:   font-family: $sans;
 7149:   line-height:130%;
 7150:   font-size:0.83em;
 7151:   color:$font;
 7152: }
 7153: 
 7154: a:focus,
 7155: a:focus img {
 7156:   color: red;
 7157: }
 7158: 
 7159: form, .inline {
 7160:   display: inline;
 7161: }
 7162: 
 7163: .LC_menus_content.shown{
 7164:   display: inline;
 7165: }
 7166: 
 7167: .LC_menus_content.hidden {
 7168:   display: none;
 7169: }
 7170: 
 7171: .LC_right {
 7172:   text-align:right;
 7173: }
 7174: 
 7175: .LC_middle {
 7176:   vertical-align:middle;
 7177: }
 7178: 
 7179: .LC_floatleft {
 7180:   float: left;
 7181: }
 7182: 
 7183: .LC_floatright {
 7184:   float: right;
 7185: }
 7186: 
 7187: .LC_400Box {
 7188:   width:400px;
 7189: }
 7190: 
 7191: #LC_collapsible_separator {
 7192:     border: 1px solid black;
 7193:     width: 99.9%;
 7194:     height: 0px;
 7195: }
 7196: 
 7197: .LC_iframecontainer {
 7198:     width: 98%;
 7199:     margin: 0;
 7200:     position: fixed;
 7201:     top: 8.5em;
 7202:     bottom: 0;
 7203: }
 7204: 
 7205: .LC_iframecontainer iframe{
 7206:     border: none;
 7207:     width: 100%;
 7208:     height: 100%;
 7209: }
 7210: 
 7211: .LC_filename {
 7212:   font-family: $mono;
 7213:   white-space:pre;
 7214:   font-size: 120%;
 7215: }
 7216: 
 7217: .LC_fileicon {
 7218:   border: none;
 7219:   height: 1.3em;
 7220:   vertical-align: text-bottom;
 7221:   margin-right: 0.3em;
 7222:   text-decoration:none;
 7223: }
 7224: 
 7225: .LC_setting {
 7226:   text-decoration:underline;
 7227: }
 7228: 
 7229: .LC_error {
 7230:   color: red;
 7231: }
 7232: 
 7233: .LC_warning {
 7234:   color: darkorange;
 7235: }
 7236: 
 7237: .LC_diff_removed {
 7238:   color: red;
 7239: }
 7240: 
 7241: .LC_info,
 7242: .LC_success,
 7243: .LC_diff_added {
 7244:   color: green;
 7245: }
 7246: 
 7247: div.LC_confirm_box {
 7248:   background-color: #FAFAFA;
 7249:   border: 1px solid $lg_border_color;
 7250:   margin-right: 0;
 7251:   padding: 5px;
 7252: }
 7253: 
 7254: div.LC_confirm_box .LC_error img,
 7255: div.LC_confirm_box .LC_success img {
 7256:   vertical-align: middle;
 7257: }
 7258: 
 7259: .LC_maxwidth {
 7260:   max-width: 100%;
 7261:   height: auto;
 7262: }
 7263: 
 7264: .LC_textsize_mobile {
 7265:   \@media only screen and (max-device-width: 480px) {
 7266:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 7267:   }
 7268: }
 7269: 
 7270: .LC_icon {
 7271:   border: none;
 7272:   vertical-align: middle;
 7273: }
 7274: 
 7275: .LC_docs_spacer {
 7276:   width: 25px;
 7277:   height: 1px;
 7278:   border: none;
 7279: }
 7280: 
 7281: .LC_internal_info {
 7282:   color: #999999;
 7283: }
 7284: 
 7285: .LC_discussion {
 7286:   background: $data_table_dark;
 7287:   border: 1px solid black;
 7288:   margin: 2px;
 7289: }
 7290: 
 7291: .LC_disc_action_left {
 7292:   background: $sidebg;
 7293:   text-align: left;
 7294:   padding: 4px;
 7295:   margin: 2px;
 7296: }
 7297: 
 7298: .LC_disc_action_right {
 7299:   background: $sidebg;
 7300:   text-align: right;
 7301:   padding: 4px;
 7302:   margin: 2px;
 7303: }
 7304: 
 7305: .LC_disc_new_item {
 7306:   background: white;
 7307:   border: 2px solid red;
 7308:   margin: 4px;
 7309:   padding: 4px;
 7310: }
 7311: 
 7312: .LC_disc_old_item {
 7313:   background: white;
 7314:   margin: 4px;
 7315:   padding: 4px;
 7316: }
 7317: 
 7318: table.LC_pastsubmission {
 7319:   border: 1px solid black;
 7320:   margin: 2px;
 7321: }
 7322: 
 7323: table#LC_menubuttons {
 7324:   width: 100%;
 7325:   background: $pgbg;
 7326:   border: 2px;
 7327:   border-collapse: separate;
 7328:   padding: 0;
 7329: }
 7330: 
 7331: table#LC_title_bar a {
 7332:   color: $fontmenu;
 7333: }
 7334: 
 7335: table#LC_title_bar {
 7336:   clear: both;
 7337:   display: none;
 7338: }
 7339: 
 7340: table#LC_title_bar,
 7341: table.LC_breadcrumbs, /* obsolete? */
 7342: table#LC_title_bar.LC_with_remote {
 7343:   width: 100%;
 7344:   border-color: $pgbg;
 7345:   border-style: solid;
 7346:   border-width: $border;
 7347:   background: $pgbg;
 7348:   color: $fontmenu;
 7349:   border-collapse: collapse;
 7350:   padding: 0;
 7351:   margin: 0;
 7352: }
 7353: 
 7354: ul.LC_breadcrumb_tools_outerlist {
 7355:     margin: 0;
 7356:     padding: 0;
 7357:     position: relative;
 7358:     list-style: none;
 7359: }
 7360: ul.LC_breadcrumb_tools_outerlist li {
 7361:     display: inline;
 7362: }
 7363: 
 7364: .LC_breadcrumb_tools_navigation {
 7365:     padding: 0;
 7366:     margin: 0;
 7367:     float: left;
 7368: }
 7369: .LC_breadcrumb_tools_tools {
 7370:     padding: 0;
 7371:     margin: 0;
 7372:     float: right;
 7373: }
 7374: 
 7375: .LC_placement_prog {
 7376:     padding-right: 20px;
 7377:     font-weight: bold;
 7378:     font-size: 90%;
 7379: }
 7380: 
 7381: table#LC_title_bar td {
 7382:   background: $tabbg;
 7383: }
 7384: 
 7385: table#LC_menubuttons img {
 7386:   border: none;
 7387: }
 7388: 
 7389: .LC_breadcrumbs_component {
 7390:   float: right;
 7391:   margin: 0 1em;
 7392: }
 7393: .LC_breadcrumbs_component img {
 7394:   vertical-align: middle;
 7395: }
 7396: 
 7397: .LC_breadcrumbs_hoverable {
 7398:   background: $sidebg;
 7399: }
 7400: 
 7401: td.LC_table_cell_checkbox {
 7402:   text-align: center;
 7403: }
 7404: 
 7405: .LC_fontsize_small {
 7406:   font-size: 70%;
 7407: }
 7408: 
 7409: #LC_breadcrumbs {
 7410:   clear:both;
 7411:   background: $sidebg;
 7412:   border-bottom: 1px solid $lg_border_color;
 7413:   line-height: 2.5em;
 7414:   overflow: hidden;
 7415:   margin: 0;
 7416:   padding: 0;
 7417:   text-align: left;
 7418: }
 7419: 
 7420: .LC_head_subbox, .LC_actionbox {
 7421:   clear:both;
 7422:   background: #F8F8F8; /* $sidebg; */
 7423:   border: 1px solid $sidebg;
 7424:   margin: 0 0 10px 0;
 7425:   padding: 3px;
 7426:   text-align: left;
 7427: }
 7428: 
 7429: .LC_fontsize_medium {
 7430:   font-size: 85%;
 7431: }
 7432: 
 7433: .LC_fontsize_large {
 7434:   font-size: 120%;
 7435: }
 7436: 
 7437: .LC_menubuttons_inline_text {
 7438:   color: $font;
 7439:   font-size: 90%;
 7440:   padding-left:3px;
 7441: }
 7442: 
 7443: .LC_menubuttons_inline_text img{
 7444:   vertical-align: middle;
 7445: }
 7446: 
 7447: li.LC_menubuttons_inline_text img {
 7448:   cursor:pointer;
 7449:   text-decoration: none;
 7450: }
 7451: 
 7452: .LC_menubuttons_link {
 7453:   text-decoration: none;
 7454: }
 7455: 
 7456: .LC_menubuttons_category {
 7457:   color: $font;
 7458:   background: $pgbg;
 7459:   font-size: larger;
 7460:   font-weight: bold;
 7461: }
 7462: 
 7463: td.LC_menubuttons_text {
 7464:   color: $font;
 7465: }
 7466: 
 7467: .LC_current_location {
 7468:   background: $tabbg;
 7469: }
 7470: 
 7471: td.LC_zero_height {
 7472:   line-height: 0; 
 7473:   cellpadding: 0;
 7474: }
 7475: 
 7476: table.LC_data_table {
 7477:   border: 1px solid #000000;
 7478:   border-collapse: separate;
 7479:   border-spacing: 1px;
 7480:   background: $pgbg;
 7481: }
 7482: 
 7483: .LC_data_table_dense {
 7484:   font-size: small;
 7485: }
 7486: 
 7487: table.LC_nested_outer {
 7488:   border: 1px solid #000000;
 7489:   border-collapse: collapse;
 7490:   border-spacing: 0;
 7491:   width: 100%;
 7492: }
 7493: 
 7494: table.LC_innerpickbox,
 7495: table.LC_nested {
 7496:   border: none;
 7497:   border-collapse: collapse;
 7498:   border-spacing: 0;
 7499:   width: 100%;
 7500: }
 7501: 
 7502: table.LC_data_table tr th,
 7503: table.LC_calendar tr th,
 7504: table.LC_prior_tries tr th,
 7505: table.LC_innerpickbox tr th {
 7506:   font-weight: bold;
 7507:   background-color: $data_table_head;
 7508:   color:$fontmenu;
 7509:   font-size:90%;
 7510: }
 7511: 
 7512: table.LC_innerpickbox tr th,
 7513: table.LC_innerpickbox tr td {
 7514:   vertical-align: top;
 7515: }
 7516: 
 7517: table.LC_data_table tr.LC_info_row > td {
 7518:   background-color: #CCCCCC;
 7519:   font-weight: bold;
 7520:   text-align: left;
 7521: }
 7522: 
 7523: table.LC_data_table tr.LC_odd_row > td {
 7524:   background-color: $data_table_light;
 7525:   padding: 2px;
 7526:   vertical-align: top;
 7527: }
 7528: 
 7529: table.LC_pick_box tr > td.LC_odd_row {
 7530:   background-color: $data_table_light;
 7531:   vertical-align: top;
 7532: }
 7533: 
 7534: table.LC_data_table tr.LC_even_row > td {
 7535:   background-color: $data_table_dark;
 7536:   padding: 2px;
 7537:   vertical-align: top;
 7538: }
 7539: 
 7540: table.LC_pick_box tr > td.LC_even_row {
 7541:   background-color: $data_table_dark;
 7542:   vertical-align: top;
 7543: }
 7544: 
 7545: table.LC_data_table tr.LC_data_table_highlight td {
 7546:   background-color: $data_table_darker;
 7547: }
 7548: 
 7549: table.LC_data_table tr td.LC_leftcol_header {
 7550:   background-color: $data_table_head;
 7551:   font-weight: bold;
 7552: }
 7553: 
 7554: table.LC_data_table tr.LC_empty_row td,
 7555: table.LC_nested tr.LC_empty_row td {
 7556:   font-weight: bold;
 7557:   font-style: italic;
 7558:   text-align: center;
 7559:   padding: 8px;
 7560: }
 7561: 
 7562: table.LC_data_table tr.LC_empty_row td,
 7563: table.LC_data_table tr.LC_footer_row td {
 7564:   background-color: $sidebg;
 7565: }
 7566: 
 7567: table.LC_nested tr.LC_empty_row td {
 7568:   background-color: #FFFFFF;
 7569: }
 7570: 
 7571: table.LC_caption {
 7572: }
 7573: 
 7574: table.LC_nested tr.LC_empty_row td {
 7575:   padding: 4ex
 7576: }
 7577: 
 7578: table.LC_nested_outer tr th {
 7579:   font-weight: bold;
 7580:   color:$fontmenu;
 7581:   background-color: $data_table_head;
 7582:   font-size: small;
 7583:   border-bottom: 1px solid #000000;
 7584: }
 7585: 
 7586: table.LC_nested_outer tr td.LC_subheader {
 7587:   background-color: $data_table_head;
 7588:   font-weight: bold;
 7589:   font-size: small;
 7590:   border-bottom: 1px solid #000000;
 7591:   text-align: right;
 7592: }
 7593: 
 7594: table.LC_nested tr.LC_info_row td {
 7595:   background-color: #CCCCCC;
 7596:   font-weight: bold;
 7597:   font-size: small;
 7598:   text-align: center;
 7599: }
 7600: 
 7601: table.LC_nested tr.LC_info_row td.LC_left_item,
 7602: table.LC_nested_outer tr th.LC_left_item {
 7603:   text-align: left;
 7604: }
 7605: 
 7606: table.LC_nested td {
 7607:   background-color: #FFFFFF;
 7608:   font-size: small;
 7609: }
 7610: 
 7611: table.LC_nested_outer tr th.LC_right_item,
 7612: table.LC_nested tr.LC_info_row td.LC_right_item,
 7613: table.LC_nested tr.LC_odd_row td.LC_right_item,
 7614: table.LC_nested tr td.LC_right_item {
 7615:   text-align: right;
 7616: }
 7617: 
 7618: table.LC_nested tr.LC_odd_row td {
 7619:   background-color: #EEEEEE;
 7620: }
 7621: 
 7622: table.LC_createuser {
 7623: }
 7624: 
 7625: table.LC_createuser tr.LC_section_row td {
 7626:   font-size: small;
 7627: }
 7628: 
 7629: table.LC_createuser tr.LC_info_row td  {
 7630:   background-color: #CCCCCC;
 7631:   font-weight: bold;
 7632:   text-align: center;
 7633: }
 7634: 
 7635: table.LC_calendar {
 7636:   border: 1px solid #000000;
 7637:   border-collapse: collapse;
 7638:   width: 98%;
 7639: }
 7640: 
 7641: table.LC_calendar_pickdate {
 7642:   font-size: xx-small;
 7643: }
 7644: 
 7645: table.LC_calendar tr td {
 7646:   border: 1px solid #000000;
 7647:   vertical-align: top;
 7648:   width: 14%;
 7649: }
 7650: 
 7651: table.LC_calendar tr td.LC_calendar_day_empty {
 7652:   background-color: $data_table_dark;
 7653: }
 7654: 
 7655: table.LC_calendar tr td.LC_calendar_day_current {
 7656:   background-color: $data_table_highlight;
 7657: }
 7658: 
 7659: table.LC_data_table tr td.LC_mail_new {
 7660:   background-color: $mail_new;
 7661: }
 7662: 
 7663: table.LC_data_table tr.LC_mail_new:hover {
 7664:   background-color: $mail_new_hover;
 7665: }
 7666: 
 7667: table.LC_data_table tr td.LC_mail_read {
 7668:   background-color: $mail_read;
 7669: }
 7670: 
 7671: /*
 7672: table.LC_data_table tr.LC_mail_read:hover {
 7673:   background-color: $mail_read_hover;
 7674: }
 7675: */
 7676: 
 7677: table.LC_data_table tr td.LC_mail_replied {
 7678:   background-color: $mail_replied;
 7679: }
 7680: 
 7681: /*
 7682: table.LC_data_table tr.LC_mail_replied:hover {
 7683:   background-color: $mail_replied_hover;
 7684: }
 7685: */
 7686: 
 7687: table.LC_data_table tr td.LC_mail_other {
 7688:   background-color: $mail_other;
 7689: }
 7690: 
 7691: /*
 7692: table.LC_data_table tr.LC_mail_other:hover {
 7693:   background-color: $mail_other_hover;
 7694: }
 7695: */
 7696: 
 7697: table.LC_data_table tr > td.LC_browser_file,
 7698: table.LC_data_table tr > td.LC_browser_file_published {
 7699:   background: #AAEE77;
 7700: }
 7701: 
 7702: table.LC_data_table tr > td.LC_browser_file_locked,
 7703: table.LC_data_table tr > td.LC_browser_file_unpublished {
 7704:   background: #FFAA99;
 7705: }
 7706: 
 7707: table.LC_data_table tr > td.LC_browser_file_obsolete {
 7708:   background: #888888;
 7709: }
 7710: 
 7711: table.LC_data_table tr > td.LC_browser_file_modified,
 7712: table.LC_data_table tr > td.LC_browser_file_metamodified {
 7713:   background: #F8F866;
 7714: }
 7715: 
 7716: table.LC_data_table tr.LC_browser_folder > td {
 7717:   background: #E0E8FF;
 7718: }
 7719: 
 7720: table.LC_data_table tr > td.LC_roles_is {
 7721:   /* background: #77FF77; */
 7722: }
 7723: 
 7724: table.LC_data_table tr > td.LC_roles_future {
 7725:   border-right: 8px solid #FFFF77;
 7726: }
 7727: 
 7728: table.LC_data_table tr > td.LC_roles_will {
 7729:   border-right: 8px solid #FFAA77;
 7730: }
 7731: 
 7732: table.LC_data_table tr > td.LC_roles_expired {
 7733:   border-right: 8px solid #FF7777;
 7734: }
 7735: 
 7736: table.LC_data_table tr > td.LC_roles_will_not {
 7737:   border-right: 8px solid #AAFF77;
 7738: }
 7739: 
 7740: table.LC_data_table tr > td.LC_roles_selected {
 7741:   border-right: 8px solid #11CC55;
 7742: }
 7743: 
 7744: span.LC_current_location {
 7745:   font-size:larger;
 7746:   background: $pgbg;
 7747: }
 7748: 
 7749: span.LC_current_nav_location {
 7750:   font-weight:bold;
 7751:   background: $sidebg;
 7752: }
 7753: 
 7754: span.LC_parm_menu_item {
 7755:   font-size: larger;
 7756: }
 7757: 
 7758: span.LC_parm_scope_all {
 7759:   color: red;
 7760: }
 7761: 
 7762: span.LC_parm_scope_folder {
 7763:   color: green;
 7764: }
 7765: 
 7766: span.LC_parm_scope_resource {
 7767:   color: orange;
 7768: }
 7769: 
 7770: span.LC_parm_part {
 7771:   color: blue;
 7772: }
 7773: 
 7774: span.LC_parm_folder,
 7775: span.LC_parm_symb {
 7776:   font-size: x-small;
 7777:   font-family: $mono;
 7778:   color: #AAAAAA;
 7779: }
 7780: 
 7781: ul.LC_parm_parmlist li {
 7782:   display: inline-block;
 7783:   padding: 0.3em 0.8em;
 7784:   vertical-align: top;
 7785:   width: 150px;
 7786:   border-top:1px solid $lg_border_color;
 7787: }
 7788: 
 7789: td.LC_parm_overview_level_menu,
 7790: td.LC_parm_overview_map_menu,
 7791: td.LC_parm_overview_parm_selectors,
 7792: td.LC_parm_overview_restrictions  {
 7793:   border: 1px solid black;
 7794:   border-collapse: collapse;
 7795: }
 7796: 
 7797: span.LC_parm_recursive,
 7798: td.LC_parm_recursive {
 7799:   font-weight: bold;
 7800:   font-size: smaller;
 7801: }
 7802: 
 7803: table.LC_parm_overview_restrictions td {
 7804:   border-width: 1px 4px 1px 4px;
 7805:   border-style: solid;
 7806:   border-color: $pgbg;
 7807:   text-align: center;
 7808: }
 7809: 
 7810: table.LC_parm_overview_restrictions th {
 7811:   background: $tabbg;
 7812:   border-width: 1px 4px 1px 4px;
 7813:   border-style: solid;
 7814:   border-color: $pgbg;
 7815: }
 7816: 
 7817: table#LC_helpmenu {
 7818:   border: none;
 7819:   height: 55px;
 7820:   border-spacing: 0;
 7821: }
 7822: 
 7823: table#LC_helpmenu fieldset legend {
 7824:   font-size: larger;
 7825: }
 7826: 
 7827: table#LC_helpmenu_links {
 7828:   width: 100%;
 7829:   border: 1px solid black;
 7830:   background: $pgbg;
 7831:   padding: 0;
 7832:   border-spacing: 1px;
 7833: }
 7834: 
 7835: table#LC_helpmenu_links tr td {
 7836:   padding: 1px;
 7837:   background: $tabbg;
 7838:   text-align: center;
 7839:   font-weight: bold;
 7840: }
 7841: 
 7842: table#LC_helpmenu_links a:link,
 7843: table#LC_helpmenu_links a:visited,
 7844: table#LC_helpmenu_links a:active {
 7845:   text-decoration: none;
 7846:   color: $font;
 7847: }
 7848: 
 7849: table#LC_helpmenu_links a:hover {
 7850:   text-decoration: underline;
 7851:   color: $vlink;
 7852: }
 7853: 
 7854: .LC_chrt_popup_exists {
 7855:   border: 1px solid #339933;
 7856:   margin: -1px;
 7857: }
 7858: 
 7859: .LC_chrt_popup_up {
 7860:   border: 1px solid yellow;
 7861:   margin: -1px;
 7862: }
 7863: 
 7864: .LC_chrt_popup {
 7865:   border: 1px solid #8888FF;
 7866:   background: #CCCCFF;
 7867: }
 7868: 
 7869: table.LC_pick_box {
 7870:   border-collapse: separate;
 7871:   background: white;
 7872:   border: 1px solid black;
 7873:   border-spacing: 1px;
 7874: }
 7875: 
 7876: table.LC_pick_box td.LC_pick_box_title {
 7877:   background: $sidebg;
 7878:   font-weight: bold;
 7879:   text-align: left;
 7880:   vertical-align: top;
 7881:   width: 184px;
 7882:   padding: 8px;
 7883: }
 7884: 
 7885: table.LC_pick_box td.LC_pick_box_value {
 7886:   text-align: left;
 7887:   padding: 8px;
 7888: }
 7889: 
 7890: table.LC_pick_box td.LC_pick_box_select {
 7891:   text-align: left;
 7892:   padding: 8px;
 7893: }
 7894: 
 7895: table.LC_pick_box td.LC_pick_box_separator {
 7896:   padding: 0;
 7897:   height: 1px;
 7898:   background: black;
 7899: }
 7900: 
 7901: table.LC_pick_box td.LC_pick_box_submit {
 7902:   text-align: right;
 7903: }
 7904: 
 7905: table.LC_pick_box td.LC_evenrow_value {
 7906:   text-align: left;
 7907:   padding: 8px;
 7908:   background-color: $data_table_light;
 7909: }
 7910: 
 7911: table.LC_pick_box td.LC_oddrow_value {
 7912:   text-align: left;
 7913:   padding: 8px;
 7914:   background-color: $data_table_light;
 7915: }
 7916: 
 7917: span.LC_helpform_receipt_cat {
 7918:   font-weight: bold;
 7919: }
 7920: 
 7921: table.LC_group_priv_box {
 7922:   background: white;
 7923:   border: 1px solid black;
 7924:   border-spacing: 1px;
 7925: }
 7926: 
 7927: table.LC_group_priv_box td.LC_pick_box_title {
 7928:   background: $tabbg;
 7929:   font-weight: bold;
 7930:   text-align: right;
 7931:   width: 184px;
 7932: }
 7933: 
 7934: table.LC_group_priv_box td.LC_groups_fixed {
 7935:   background: $data_table_light;
 7936:   text-align: center;
 7937: }
 7938: 
 7939: table.LC_group_priv_box td.LC_groups_optional {
 7940:   background: $data_table_dark;
 7941:   text-align: center;
 7942: }
 7943: 
 7944: table.LC_group_priv_box td.LC_groups_functionality {
 7945:   background: $data_table_darker;
 7946:   text-align: center;
 7947:   font-weight: bold;
 7948: }
 7949: 
 7950: table.LC_group_priv td {
 7951:   text-align: left;
 7952:   padding: 0;
 7953: }
 7954: 
 7955: .LC_navbuttons {
 7956:   margin: 2ex 0ex 2ex 0ex;
 7957: }
 7958: 
 7959: .LC_topic_bar {
 7960:   font-weight: bold;
 7961:   background: $tabbg;
 7962:   margin: 1em 0em 1em 2em;
 7963:   padding: 3px;
 7964:   font-size: 1.2em;
 7965: }
 7966: 
 7967: .LC_topic_bar span {
 7968:   left: 0.5em;
 7969:   position: absolute;
 7970:   vertical-align: middle;
 7971:   font-size: 1.2em;
 7972: }
 7973: 
 7974: table.LC_course_group_status {
 7975:   margin: 20px;
 7976: }
 7977: 
 7978: table.LC_status_selector td {
 7979:   vertical-align: top;
 7980:   text-align: center;
 7981:   padding: 4px;
 7982: }
 7983: 
 7984: div.LC_feedback_link {
 7985:   clear: both;
 7986:   background: $sidebg;
 7987:   width: 100%;
 7988:   padding-bottom: 10px;
 7989:   border: 1px $tabbg solid;
 7990:   height: 22px;
 7991:   line-height: 22px;
 7992:   padding-top: 5px;
 7993: }
 7994: 
 7995: div.LC_feedback_link img {
 7996:   height: 22px;
 7997:   vertical-align:middle;
 7998: }
 7999: 
 8000: div.LC_feedback_link a {
 8001:   text-decoration: none;
 8002: }
 8003: 
 8004: div.LC_comblock {
 8005:   display:inline;
 8006:   color:$font;
 8007:   font-size:90%;
 8008: }
 8009: 
 8010: div.LC_feedback_link div.LC_comblock {
 8011:   padding-left:5px;
 8012: }
 8013: 
 8014: div.LC_feedback_link div.LC_comblock a {
 8015:   color:$font;
 8016: }
 8017: 
 8018: span.LC_feedback_link {
 8019:   /* background: $feedback_link_bg; */
 8020:   font-size: larger;
 8021: }
 8022: 
 8023: span.LC_message_link {
 8024:   /* background: $feedback_link_bg; */
 8025:   font-size: larger;
 8026:   position: absolute;
 8027:   right: 1em;
 8028: }
 8029: 
 8030: table.LC_prior_tries {
 8031:   border: 1px solid #000000;
 8032:   border-collapse: separate;
 8033:   border-spacing: 1px;
 8034: }
 8035: 
 8036: table.LC_prior_tries td {
 8037:   padding: 2px;
 8038: }
 8039: 
 8040: .LC_answer_correct {
 8041:   background: lightgreen;
 8042:   color: darkgreen;
 8043:   padding: 6px;
 8044: }
 8045: 
 8046: .LC_answer_charged_try {
 8047:   background: #FFAAAA;
 8048:   color: darkred;
 8049:   padding: 6px;
 8050: }
 8051: 
 8052: .LC_answer_not_charged_try,
 8053: .LC_answer_no_grade,
 8054: .LC_answer_late {
 8055:   background: lightyellow;
 8056:   color: black;
 8057:   padding: 6px;
 8058: }
 8059: 
 8060: .LC_answer_previous {
 8061:   background: lightblue;
 8062:   color: darkblue;
 8063:   padding: 6px;
 8064: }
 8065: 
 8066: .LC_answer_no_message {
 8067:   background: #FFFFFF;
 8068:   color: black;
 8069:   padding: 6px;
 8070: }
 8071: 
 8072: .LC_answer_unknown,
 8073: .LC_answer_warning {
 8074:   background: orange;
 8075:   color: black;
 8076:   padding: 6px;
 8077: }
 8078: 
 8079: span.LC_prior_numerical,
 8080: span.LC_prior_string,
 8081: span.LC_prior_custom,
 8082: span.LC_prior_reaction,
 8083: span.LC_prior_math {
 8084:   font-family: $mono;
 8085:   white-space: pre;
 8086: }
 8087: 
 8088: span.LC_prior_string {
 8089:   font-family: $mono;
 8090:   white-space: pre;
 8091: }
 8092: 
 8093: table.LC_prior_option {
 8094:   width: 100%;
 8095:   border-collapse: collapse;
 8096: }
 8097: 
 8098: table.LC_prior_rank,
 8099: table.LC_prior_match {
 8100:   border-collapse: collapse;
 8101: }
 8102: 
 8103: table.LC_prior_option tr td,
 8104: table.LC_prior_rank tr td,
 8105: table.LC_prior_match tr td {
 8106:   border: 1px solid #000000;
 8107: }
 8108: 
 8109: .LC_nobreak {
 8110:   white-space: nowrap;
 8111: }
 8112: 
 8113: span.LC_cusr_emph {
 8114:   font-style: italic;
 8115: }
 8116: 
 8117: span.LC_cusr_subheading {
 8118:   font-weight: normal;
 8119:   font-size: 85%;
 8120: }
 8121: 
 8122: div.LC_docs_entry_move {
 8123:   border: 1px solid #BBBBBB;
 8124:   background: #DDDDDD;
 8125:   width: 22px;
 8126:   padding: 1px;
 8127:   margin: 0;
 8128: }
 8129: 
 8130: table.LC_data_table tr > td.LC_docs_entry_commands,
 8131: table.LC_data_table tr > td.LC_docs_entry_parameter {
 8132:   font-size: x-small;
 8133: }
 8134: 
 8135: .LC_docs_entry_parameter {
 8136:   white-space: nowrap;
 8137: }
 8138: 
 8139: .LC_docs_copy {
 8140:   color: #000099;
 8141: }
 8142: 
 8143: .LC_docs_cut {
 8144:   color: #550044;
 8145: }
 8146: 
 8147: .LC_docs_rename {
 8148:   color: #009900;
 8149: }
 8150: 
 8151: .LC_docs_remove {
 8152:   color: #990000;
 8153: }
 8154: 
 8155: .LC_docs_alias {
 8156:   color: #440055;  
 8157: }
 8158: 
 8159: .LC_domprefs_email,
 8160: .LC_docs_alias_name,
 8161: .LC_docs_reinit_warn,
 8162: .LC_docs_ext_edit {
 8163:   font-size: x-small;
 8164: }
 8165: 
 8166: table.LC_docs_adddocs td,
 8167: table.LC_docs_adddocs th {
 8168:   border: 1px solid #BBBBBB;
 8169:   padding: 4px;
 8170:   background: #DDDDDD;
 8171: }
 8172: 
 8173: table.LC_sty_begin {
 8174:   background: #BBFFBB;
 8175: }
 8176: 
 8177: table.LC_sty_end {
 8178:   background: #FFBBBB;
 8179: }
 8180: 
 8181: table.LC_double_column {
 8182:   border-width: 0;
 8183:   border-collapse: collapse;
 8184:   width: 100%;
 8185:   padding: 2px;
 8186: }
 8187: 
 8188: table.LC_double_column tr td.LC_left_col {
 8189:   top: 2px;
 8190:   left: 2px;
 8191:   width: 47%;
 8192:   vertical-align: top;
 8193: }
 8194: 
 8195: table.LC_double_column tr td.LC_right_col {
 8196:   top: 2px;
 8197:   right: 2px;
 8198:   width: 47%;
 8199:   vertical-align: top;
 8200: }
 8201: 
 8202: div.LC_left_float {
 8203:   float: left;
 8204:   padding-right: 5%;
 8205:   padding-bottom: 4px;
 8206: }
 8207: 
 8208: div.LC_clear_float_header {
 8209:   padding-bottom: 2px;
 8210: }
 8211: 
 8212: div.LC_clear_float_footer {
 8213:   padding-top: 10px;
 8214:   clear: both;
 8215: }
 8216: 
 8217: div.LC_grade_show_user {
 8218: /*  border-left: 5px solid $sidebg; */
 8219:   border-top: 5px solid #000000;
 8220:   margin: 50px 0 0 0;
 8221:   padding: 15px 0 5px 10px;
 8222: }
 8223: 
 8224: div.LC_grade_show_user_odd_row {
 8225: /*  border-left: 5px solid #000000; */
 8226: }
 8227: 
 8228: div.LC_grade_show_user div.LC_Box {
 8229:   margin-right: 50px;
 8230: }
 8231: 
 8232: div.LC_grade_submissions,
 8233: div.LC_grade_message_center,
 8234: div.LC_grade_info_links {
 8235:   margin: 5px;
 8236:   width: 99%;
 8237:   background: #FFFFFF;
 8238: }
 8239: 
 8240: div.LC_grade_submissions_header,
 8241: div.LC_grade_message_center_header {
 8242:   font-weight: bold;
 8243:   font-size: large;
 8244: }
 8245: 
 8246: div.LC_grade_submissions_body,
 8247: div.LC_grade_message_center_body {
 8248:   border: 1px solid black;
 8249:   width: 99%;
 8250:   background: #FFFFFF;
 8251: }
 8252: 
 8253: table.LC_scantron_action {
 8254:   width: 100%;
 8255: }
 8256: 
 8257: table.LC_scantron_action tr th {
 8258:   font-weight:bold;
 8259:   font-style:normal;
 8260: }
 8261: 
 8262: .LC_edit_problem_header,
 8263: div.LC_edit_problem_footer {
 8264:   font-weight: normal;
 8265:   font-size:  medium;
 8266:   margin: 2px;
 8267:   background-color: $sidebg;
 8268: }
 8269: 
 8270: div.LC_edit_problem_header,
 8271: div.LC_edit_problem_header div,
 8272: div.LC_edit_problem_footer,
 8273: div.LC_edit_problem_footer div,
 8274: div.LC_edit_problem_editxml_header,
 8275: div.LC_edit_problem_editxml_header div {
 8276:   z-index: 100;
 8277: }
 8278: 
 8279: div.LC_edit_problem_header_title {
 8280:   font-weight: bold;
 8281:   font-size: larger;
 8282:   background: $tabbg;
 8283:   padding: 3px;
 8284:   margin: 0 0 5px 0;
 8285: }
 8286: 
 8287: table.LC_edit_problem_header_title {
 8288:   width: 100%;
 8289:   background: $tabbg;
 8290: }
 8291: 
 8292: div.LC_edit_actionbar {
 8293:     background-color: $sidebg;
 8294:     margin: 0;
 8295:     padding: 0;
 8296:     line-height: 200%;
 8297: }
 8298: 
 8299: div.LC_edit_actionbar div{
 8300:     padding: 0;
 8301:     margin: 0;
 8302:     display: inline-block;
 8303: }
 8304: 
 8305: .LC_edit_opt {
 8306:   padding-left: 1em;
 8307:   white-space: nowrap;
 8308: }
 8309: 
 8310: .LC_edit_problem_latexhelper{
 8311:     text-align: right;
 8312: }
 8313: 
 8314: #LC_edit_problem_colorful div{
 8315:     margin-left: 40px;
 8316: }
 8317: 
 8318: #LC_edit_problem_codemirror div{
 8319:     margin-left: 0px;
 8320: }
 8321: 
 8322: img.stift {
 8323:   border-width: 0;
 8324:   vertical-align: middle;
 8325: }
 8326: 
 8327: table td.LC_mainmenu_col_fieldset {
 8328:   vertical-align: top;
 8329: }
 8330: 
 8331: div.LC_createcourse {
 8332:   margin: 10px 10px 10px 10px;
 8333: }
 8334: 
 8335: .LC_dccid {
 8336:   float: right;
 8337:   margin: 0.2em 0 0 0;
 8338:   padding: 0;
 8339:   font-size: 90%;
 8340:   display:none;
 8341: }
 8342: 
 8343: ol.LC_primary_menu a:hover,
 8344: ol#LC_MenuBreadcrumbs a:hover,
 8345: ol#LC_PathBreadcrumbs a:hover,
 8346: ul#LC_secondary_menu a:hover,
 8347: .LC_FormSectionClearButton input:hover
 8348: ul.LC_TabContent   li:hover a {
 8349:   color:$button_hover;
 8350:   text-decoration:none;
 8351: }
 8352: 
 8353: h1 {
 8354:   padding: 0;
 8355:   line-height:130%;
 8356: }
 8357: 
 8358: h2,
 8359: h3,
 8360: h4,
 8361: h5,
 8362: h6 {
 8363:   margin: 5px 0 5px 0;
 8364:   padding: 0;
 8365:   line-height:130%;
 8366: }
 8367: 
 8368: .LC_hcell {
 8369:   padding:3px 15px 3px 15px;
 8370:   margin: 0;
 8371:   background-color:$tabbg;
 8372:   color:$fontmenu;
 8373:   border-bottom:solid 1px $lg_border_color;
 8374: }
 8375: 
 8376: .LC_Box > .LC_hcell {
 8377:   margin: 0 -10px 10px -10px;
 8378: }
 8379: 
 8380: .LC_noBorder {
 8381:   border: 0;
 8382: }
 8383: 
 8384: .LC_FormSectionClearButton input {
 8385:   background-color:transparent;
 8386:   border: none;
 8387:   cursor:pointer;
 8388:   text-decoration:underline;
 8389: }
 8390: 
 8391: .LC_help_open_topic {
 8392:   color: #FFFFFF;
 8393:   background-color: #EEEEFF;
 8394:   margin: 1px;
 8395:   padding: 4px;
 8396:   border: 1px solid #000033;
 8397:   white-space: nowrap;
 8398:   /* vertical-align: middle; */
 8399: }
 8400: 
 8401: dl,
 8402: ul,
 8403: div,
 8404: fieldset {
 8405:   margin: 10px 10px 10px 0;
 8406:   /* overflow: hidden; */
 8407: }
 8408: 
 8409: fieldset#LC_selectuser {
 8410:     margin: 0;
 8411:     padding: 0;
 8412: }
 8413: 
 8414: article.geogebraweb div {
 8415:     margin: 0;
 8416: }
 8417: 
 8418: fieldset > legend {
 8419:   font-weight: bold;
 8420:   padding: 0 5px 0 5px;
 8421: }
 8422: 
 8423: #LC_nav_bar {
 8424:   float: left;
 8425:   background-color: $pgbg_or_bgcolor;
 8426:   margin: 0 0 2px 0;
 8427: }
 8428: 
 8429: #LC_realm {
 8430:   margin: 0.2em 0 0 0;
 8431:   padding: 0;
 8432:   font-weight: bold;
 8433:   text-align: center;
 8434:   background-color: $pgbg_or_bgcolor;
 8435: }
 8436: 
 8437: #LC_nav_bar em {
 8438:   font-weight: bold;
 8439:   font-style: normal;
 8440: }
 8441: 
 8442: ol.LC_primary_menu {
 8443:   margin: 0;
 8444:   padding: 0;
 8445: }
 8446: 
 8447: ol#LC_PathBreadcrumbs {
 8448:   margin: 0;
 8449: }
 8450: 
 8451: ol.LC_primary_menu li {
 8452:   color: RGB(80, 80, 80);
 8453:   vertical-align: middle;
 8454:   text-align: left;
 8455:   list-style: none;
 8456:   position: relative;
 8457:   float: left;
 8458:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 8459:   line-height: 1.5em;
 8460: }
 8461: 
 8462: ol.LC_primary_menu li a,
 8463: ol.LC_primary_menu li p {
 8464:   display: block;
 8465:   margin: 0;
 8466:   padding: 0 5px 0 10px;
 8467:   text-decoration: none;
 8468: }
 8469: 
 8470: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 8471:   display: inline-block;
 8472:   width: 95%;
 8473:   text-align: left;
 8474: }
 8475: 
 8476: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 8477:   display: inline-block;	
 8478:   width: 5%;
 8479:   float: right;
 8480:   text-align: right;
 8481:   font-size: 70%;
 8482: }
 8483: 
 8484: ol.LC_primary_menu ul {
 8485:   display: none;
 8486:   width: 15em;
 8487:   background-color: $data_table_light;
 8488:   position: absolute;
 8489:   top: 100%;
 8490: }
 8491: 
 8492: ol.LC_primary_menu ul ul {
 8493:   left: 100%;
 8494:   top: 0;
 8495: }
 8496: 
 8497: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 8498:   display: block;
 8499:   position: absolute;
 8500:   margin: 0;
 8501:   padding: 0;
 8502:   z-index: 2;
 8503: }
 8504: 
 8505: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 8506: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 8507:   font-size: 90%;
 8508:   vertical-align: top;
 8509:   float: none;
 8510:   border-left: 1px solid black;
 8511:   border-right: 1px solid black;
 8512: /* A dark bottom border to visualize different menu options; 
 8513: overwritten in the create_submenu routine for the last border-bottom of the menu */
 8514:   border-bottom: 1px solid $data_table_dark; 
 8515: }
 8516: 
 8517: ol.LC_primary_menu li li p:hover {
 8518:   color:$button_hover;
 8519:   text-decoration:none;
 8520:   background-color:$data_table_dark;
 8521: }
 8522: 
 8523: ol.LC_primary_menu li li a:hover {
 8524:    color:$button_hover;
 8525:    background-color:$data_table_dark;
 8526: }
 8527: 
 8528: /* Font-size equal to the size of the predecessors*/
 8529: ol.LC_primary_menu li:hover li li {
 8530:   font-size: 100%;
 8531: }
 8532: 
 8533: ol.LC_primary_menu li img {
 8534:   vertical-align: bottom;
 8535:   height: 1.1em;
 8536:   margin: 0.2em 0 0 0;
 8537: }
 8538: 
 8539: ol.LC_primary_menu a {
 8540:   color: RGB(80, 80, 80);
 8541:   text-decoration: none;
 8542: }
 8543: 
 8544: ol.LC_primary_menu a.LC_new_message {
 8545:   font-weight:bold;
 8546:   color: darkred;
 8547: }
 8548: 
 8549: ol.LC_docs_parameters {
 8550:   margin-left: 0;
 8551:   padding: 0;
 8552:   list-style: none;
 8553: }
 8554: 
 8555: ol.LC_docs_parameters li {
 8556:   margin: 0;
 8557:   padding-right: 20px;
 8558:   display: inline;
 8559: }
 8560: 
 8561: ol.LC_docs_parameters li:before {
 8562:   content: "\\002022 \\0020";
 8563: }
 8564: 
 8565: li.LC_docs_parameters_title {
 8566:   font-weight: bold;
 8567: }
 8568: 
 8569: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 8570:   content: "";
 8571: }
 8572: 
 8573: ul#LC_secondary_menu {
 8574:   clear: right;
 8575:   color: $fontmenu;
 8576:   background: $tabbg;
 8577:   list-style: none;
 8578:   padding: 0;
 8579:   margin: 0;
 8580:   width: 100%;
 8581:   text-align: left;
 8582:   float: left;
 8583: }
 8584: 
 8585: ul#LC_secondary_menu li {
 8586:   font-weight: bold;
 8587:   line-height: 1.8em;
 8588:   border-right: 1px solid black;
 8589:   float: left;
 8590: }
 8591: 
 8592: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 8593:   background-color: $data_table_light;
 8594: }
 8595: 
 8596: ul#LC_secondary_menu li a {
 8597:   padding: 0 0.8em;
 8598: }
 8599: 
 8600: ul#LC_secondary_menu li ul {
 8601:   display: none;
 8602: }
 8603: 
 8604: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 8605:   display: block;
 8606:   position: absolute;
 8607:   margin: 0;
 8608:   padding: 0;
 8609:   list-style:none;
 8610:   float: none;
 8611:   background-color: $data_table_light;
 8612:   z-index: 2;
 8613:   margin-left: -1px;
 8614: }
 8615: 
 8616: ul#LC_secondary_menu li ul li {
 8617:   font-size: 90%;
 8618:   vertical-align: top;
 8619:   border-left: 1px solid black;
 8620:   border-right: 1px solid black;
 8621:   background-color: $data_table_light;
 8622:   list-style:none;
 8623:   float: none;
 8624: }
 8625: 
 8626: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 8627:   background-color: $data_table_dark;
 8628: }
 8629: 
 8630: ul.LC_TabContent {
 8631:   display:block;
 8632:   background: $sidebg;
 8633:   border-bottom: solid 1px $lg_border_color;
 8634:   list-style:none;
 8635:   margin: -1px -10px 0 -10px;
 8636:   padding: 0;
 8637: }
 8638: 
 8639: ul.LC_TabContent li,
 8640: ul.LC_TabContentBigger li {
 8641:   float:left;
 8642: }
 8643: 
 8644: ul#LC_secondary_menu li a {
 8645:   color: $fontmenu;
 8646:   text-decoration: none;
 8647: }
 8648: 
 8649: ul.LC_TabContent {
 8650:   min-height:20px;
 8651: }
 8652: 
 8653: ul.LC_TabContent li {
 8654:   vertical-align:middle;
 8655:   padding: 0 16px 0 10px;
 8656:   background-color:$tabbg;
 8657:   border-bottom:solid 1px $lg_border_color;
 8658:   border-left: solid 1px $font;
 8659: }
 8660: 
 8661: ul.LC_TabContent .right {
 8662:   float:right;
 8663: }
 8664: 
 8665: ul.LC_TabContent li a,
 8666: ul.LC_TabContent li {
 8667:   color:rgb(47,47,47);
 8668:   text-decoration:none;
 8669:   font-size:95%;
 8670:   font-weight:bold;
 8671:   min-height:20px;
 8672: }
 8673: 
 8674: ul.LC_TabContent li a:hover,
 8675: ul.LC_TabContent li a:focus {
 8676:   color: $button_hover;
 8677:   background:none;
 8678:   outline:none;
 8679: }
 8680: 
 8681: ul.LC_TabContent li:hover {
 8682:   color: $button_hover;
 8683:   cursor:pointer;
 8684: }
 8685: 
 8686: ul.LC_TabContent li.active {
 8687:   color: $font;
 8688:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 8689:   border-bottom:solid 1px #FFFFFF;
 8690:   cursor: default;
 8691: }
 8692: 
 8693: ul.LC_TabContent li.active a {
 8694:   color:$font;
 8695:   background:#FFFFFF;
 8696:   outline: none;
 8697: }
 8698: 
 8699: ul.LC_TabContent li.goback {
 8700:   float: left;
 8701:   border-left: none;
 8702: }
 8703: 
 8704: #maincoursedoc {
 8705:   clear:both;
 8706: }
 8707: 
 8708: ul.LC_TabContentBigger {
 8709:   display:block;
 8710:   list-style:none;
 8711:   padding: 0;
 8712: }
 8713: 
 8714: ul.LC_TabContentBigger li {
 8715:   vertical-align:bottom;
 8716:   height: 30px;
 8717:   font-size:110%;
 8718:   font-weight:bold;
 8719:   color: #737373;
 8720: }
 8721: 
 8722: ul.LC_TabContentBigger li.active {
 8723:   position: relative;
 8724:   top: 1px;
 8725: }
 8726: 
 8727: ul.LC_TabContentBigger li a {
 8728:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 8729:   height: 30px;
 8730:   line-height: 30px;
 8731:   text-align: center;
 8732:   display: block;
 8733:   text-decoration: none;
 8734:   outline: none;  
 8735: }
 8736: 
 8737: ul.LC_TabContentBigger li.active a {
 8738:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8739:   color:$font;
 8740: }
 8741: 
 8742: ul.LC_TabContentBigger li b {
 8743:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8744:   display: block;
 8745:   float: left;
 8746:   padding: 0 30px;
 8747:   border-bottom: 1px solid $lg_border_color;
 8748: }
 8749: 
 8750: ul.LC_TabContentBigger li:hover b {
 8751:   color:$button_hover;
 8752: }
 8753: 
 8754: ul.LC_TabContentBigger li.active b {
 8755:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8756:   color:$font;
 8757:   border: 0;
 8758: }
 8759: 
 8760: 
 8761: ul.LC_CourseBreadcrumbs {
 8762:   background: $sidebg;
 8763:   height: 2em;
 8764:   padding-left: 10px;
 8765:   margin: 0;
 8766:   list-style-position: inside;
 8767: }
 8768: 
 8769: ol#LC_MenuBreadcrumbs,
 8770: ol#LC_PathBreadcrumbs {
 8771:   padding-left: 10px;
 8772:   margin: 0;
 8773:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8774: }
 8775: 
 8776: ol#LC_MenuBreadcrumbs li,
 8777: ol#LC_PathBreadcrumbs li,
 8778: ul.LC_CourseBreadcrumbs li {
 8779:   display: inline;
 8780:   white-space: normal;  
 8781: }
 8782: 
 8783: ol#LC_MenuBreadcrumbs li a,
 8784: ul.LC_CourseBreadcrumbs li a {
 8785:   text-decoration: none;
 8786:   font-size:90%;
 8787: }
 8788: 
 8789: ol#LC_MenuBreadcrumbs h1 {
 8790:   display: inline;
 8791:   font-size: 90%;
 8792:   line-height: 2.5em;
 8793:   margin: 0;
 8794:   padding: 0;
 8795: }
 8796: 
 8797: ol#LC_PathBreadcrumbs li a {
 8798:   text-decoration:none;
 8799:   font-size:100%;
 8800:   font-weight:bold;
 8801: }
 8802: 
 8803: .LC_Box {
 8804:   border: solid 1px $lg_border_color;
 8805:   padding: 0 10px 10px 10px;
 8806: }
 8807: 
 8808: .LC_DocsBox {
 8809:   border: solid 1px $lg_border_color;
 8810:   padding: 0 0 10px 10px;
 8811: }
 8812: 
 8813: .LC_AboutMe_Image {
 8814:   float:left;
 8815:   margin-right:10px;
 8816: }
 8817: 
 8818: .LC_Clear_AboutMe_Image {
 8819:   clear:left;
 8820: }
 8821: 
 8822: dl.LC_ListStyleClean dt {
 8823:   padding-right: 5px;
 8824:   display: table-header-group;
 8825: }
 8826: 
 8827: dl.LC_ListStyleClean dd {
 8828:   display: table-row;
 8829: }
 8830: 
 8831: .LC_ListStyleClean,
 8832: .LC_ListStyleSimple,
 8833: .LC_ListStyleNormal,
 8834: .LC_ListStyleSpecial {
 8835:   /* display:block; */
 8836:   list-style-position: inside;
 8837:   list-style-type: none;
 8838:   overflow: hidden;
 8839:   padding: 0;
 8840: }
 8841: 
 8842: .LC_ListStyleSimple li,
 8843: .LC_ListStyleSimple dd,
 8844: .LC_ListStyleNormal li,
 8845: .LC_ListStyleNormal dd,
 8846: .LC_ListStyleSpecial li,
 8847: .LC_ListStyleSpecial dd {
 8848:   margin: 0;
 8849:   padding: 5px 5px 5px 10px;
 8850:   clear: both;
 8851: }
 8852: 
 8853: .LC_ListStyleClean li,
 8854: .LC_ListStyleClean dd {
 8855:   padding-top: 0;
 8856:   padding-bottom: 0;
 8857: }
 8858: 
 8859: .LC_ListStyleSimple dd,
 8860: .LC_ListStyleSimple li {
 8861:   border-bottom: solid 1px $lg_border_color;
 8862: }
 8863: 
 8864: .LC_ListStyleSpecial li,
 8865: .LC_ListStyleSpecial dd {
 8866:   list-style-type: none;
 8867:   background-color: RGB(220, 220, 220);
 8868:   margin-bottom: 4px;
 8869: }
 8870: 
 8871: table.LC_SimpleTable {
 8872:   margin:5px;
 8873:   border:solid 1px $lg_border_color;
 8874: }
 8875: 
 8876: table.LC_SimpleTable tr {
 8877:   padding: 0;
 8878:   border:solid 1px $lg_border_color;
 8879: }
 8880: 
 8881: table.LC_SimpleTable thead {
 8882:   background:rgb(220,220,220);
 8883: }
 8884: 
 8885: div.LC_columnSection {
 8886:   display: block;
 8887:   clear: both;
 8888:   overflow: hidden;
 8889:   margin: 0;
 8890: }
 8891: 
 8892: div.LC_columnSection>* {
 8893:   float: left;
 8894:   margin: 10px 20px 10px 0;
 8895:   overflow:hidden;
 8896: }
 8897: 
 8898: table em {
 8899:   font-weight: bold;
 8900:   font-style: normal;
 8901: }
 8902: 
 8903: table.LC_tableBrowseRes,
 8904: table.LC_tableOfContent {
 8905:   border:none;
 8906:   border-spacing: 1px;
 8907:   padding: 3px;
 8908:   background-color: #FFFFFF;
 8909:   font-size: 90%;
 8910: }
 8911: 
 8912: table.LC_tableOfContent {
 8913:   border-collapse: collapse;
 8914: }
 8915: 
 8916: table.LC_tableBrowseRes a,
 8917: table.LC_tableOfContent a {
 8918:   background-color: transparent;
 8919:   text-decoration: none;
 8920: }
 8921: 
 8922: table.LC_tableOfContent img {
 8923:   border: none;
 8924:   height: 1.3em;
 8925:   vertical-align: text-bottom;
 8926:   margin-right: 0.3em;
 8927: }
 8928: 
 8929: a#LC_content_toolbar_firsthomework {
 8930:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8931: }
 8932: 
 8933: a#LC_content_toolbar_everything {
 8934:   background-image:url(/res/adm/pages/show-all.gif);
 8935: }
 8936: 
 8937: a#LC_content_toolbar_uncompleted {
 8938:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8939: }
 8940: 
 8941: #LC_content_toolbar_clearbubbles {
 8942:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8943: }
 8944: 
 8945: a#LC_content_toolbar_changefolder {
 8946:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8947: }
 8948: 
 8949: a#LC_content_toolbar_changefolder_toggled {
 8950:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8951: }
 8952: 
 8953: a#LC_content_toolbar_edittoplevel {
 8954:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8955: }
 8956: 
 8957: a#LC_content_toolbar_printout {
 8958:   background-image:url(/res/adm/pages/printout.gif);
 8959: }
 8960: 
 8961: ul#LC_toolbar li a:hover {
 8962:   background-position: bottom center;
 8963: }
 8964: 
 8965: ul#LC_toolbar {
 8966:   padding: 0;
 8967:   margin: 2px;
 8968:   list-style:none;
 8969:   position:relative;
 8970:   background-color:white;
 8971:   overflow: auto;
 8972: }
 8973: 
 8974: ul#LC_toolbar li {
 8975:   border:1px solid white;
 8976:   padding: 0;
 8977:   margin: 0;
 8978:   float: left;
 8979:   display:inline;
 8980:   vertical-align:middle;
 8981:   white-space: nowrap;
 8982: }
 8983: 
 8984: 
 8985: a.LC_toolbarItem {
 8986:   display:block;
 8987:   padding: 0;
 8988:   margin: 0;
 8989:   height: 32px;
 8990:   width: 32px;
 8991:   color:white;
 8992:   border: none;
 8993:   background-repeat:no-repeat;
 8994:   background-color:transparent;
 8995: }
 8996: 
 8997: ul.LC_funclist {
 8998:     margin: 0;
 8999:     padding: 0.5em 1em 0.5em 0;
 9000: }
 9001: 
 9002: ul.LC_funclist > li:first-child {
 9003:     font-weight:bold; 
 9004:     margin-left:0.8em;
 9005: }
 9006: 
 9007: ul.LC_funclist + ul.LC_funclist {
 9008:     /* 
 9009:        left border as a seperator if we have more than
 9010:        one list 
 9011:     */
 9012:     border-left: 1px solid $sidebg;
 9013:     /* 
 9014:        this hides the left border behind the border of the 
 9015:        outer box if element is wrapped to the next 'line' 
 9016:     */
 9017:     margin-left: -1px;
 9018: }
 9019: 
 9020: ul.LC_funclist li {
 9021:   display: inline;
 9022:   white-space: nowrap;
 9023:   margin: 0 0 0 25px;
 9024:   line-height: 150%;
 9025: }
 9026: 
 9027: .LC_hidden {
 9028:   display: none;
 9029: }
 9030: 
 9031: .LCmodal-overlay {
 9032: 		position:fixed;
 9033: 		top:0;
 9034: 		right:0;
 9035: 		bottom:0;
 9036: 		left:0;
 9037: 		height:100%;
 9038: 		width:100%;
 9039: 		margin:0;
 9040: 		padding:0;
 9041: 		background:#999;
 9042: 		opacity:.75;
 9043: 		filter: alpha(opacity=75);
 9044: 		-moz-opacity: 0.75;
 9045: 		z-index:101;
 9046: }
 9047: 
 9048: * html .LCmodal-overlay {   
 9049: 		position: absolute;
 9050: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 9051: }
 9052: 
 9053: .LCmodal-window {
 9054: 		position:fixed;
 9055: 		top:50%;
 9056: 		left:50%;
 9057: 		margin:0;
 9058: 		padding:0;
 9059: 		z-index:102;
 9060: 	}
 9061: 
 9062: * html .LCmodal-window {
 9063: 		position:absolute;
 9064: }
 9065: 
 9066: .LCclose-window {
 9067: 		position:absolute;
 9068: 		width:32px;
 9069: 		height:32px;
 9070: 		right:8px;
 9071: 		top:8px;
 9072: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 9073: 		text-indent:-99999px;
 9074: 		overflow:hidden;
 9075: 		cursor:pointer;
 9076: }
 9077: 
 9078: .LCisDisabled {
 9079:   cursor: not-allowed;
 9080:   opacity: 0.5;
 9081: }
 9082: 
 9083: a[aria-disabled="true"] {
 9084:   color: currentColor;
 9085:   display: inline-block;  /* For IE11/ MS Edge bug */
 9086:   pointer-events: none;
 9087:   text-decoration: none;
 9088: }
 9089: 
 9090: pre.LC_wordwrap {
 9091:   white-space: pre-wrap;
 9092:   white-space: -moz-pre-wrap;
 9093:   white-space: -pre-wrap;
 9094:   white-space: -o-pre-wrap;
 9095:   word-wrap: break-word;
 9096: }
 9097: 
 9098: /*
 9099:   styles used for response display
 9100: */
 9101: div.LC_radiofoil, div.LC_rankfoil {
 9102:   margin: .5em 0em .5em 0em;
 9103: }
 9104: table.LC_itemgroup {
 9105:   margin-top: 1em;
 9106: }
 9107: 
 9108: /*
 9109:   styles used by TTH when "Default set of options to pass to tth/m
 9110:   when converting TeX" in course settings has been set
 9111: 
 9112:   option passed: -t
 9113: 
 9114: */
 9115: 
 9116: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 9117: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 9118: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 9119: td div.norm {line-height:normal;}
 9120: 
 9121: /*
 9122:   option passed -y3
 9123: */
 9124: 
 9125: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 9126: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 9127: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 9128: 
 9129: /*
 9130:   sections with roles, for content only
 9131: */
 9132: section[class^="role-"] {
 9133:   padding-left: 10px;
 9134:   padding-right: 5px;
 9135:   margin-top: 8px;
 9136:   margin-bottom: 8px;
 9137:   border: 1px solid #2A4;
 9138:   border-radius: 5px;
 9139:   box-shadow: 0px 1px 1px #BBB;
 9140: }
 9141: section[class^="role-"]>h1 {
 9142:   position: relative;
 9143:   margin: 0px;
 9144:   padding-top: 10px;
 9145:   padding-left: 40px;
 9146: }
 9147: section[class^="role-"]>h1:before {
 9148:   position: absolute;
 9149:   left: -5px;
 9150:   top: 5px;
 9151: }
 9152: section.role-activity>h1:before {
 9153:   content:url('/adm/daxe/images/section_icons/activity.png');
 9154: }
 9155: section.role-advice>h1:before {
 9156:   content:url('/adm/daxe/images/section_icons/advice.png');
 9157: }
 9158: section.role-bibliography>h1:before {
 9159:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 9160: }
 9161: section.role-citation>h1:before {
 9162:   content:url('/adm/daxe/images/section_icons/citation.png');
 9163: }
 9164: section.role-conclusion>h1:before {
 9165:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 9166: }
 9167: section.role-definition>h1:before {
 9168:   content:url('/adm/daxe/images/section_icons/definition.png');
 9169: }
 9170: section.role-demonstration>h1:before {
 9171:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 9172: }
 9173: section.role-example>h1:before {
 9174:   content:url('/adm/daxe/images/section_icons/example.png');
 9175: }
 9176: section.role-explanation>h1:before {
 9177:   content:url('/adm/daxe/images/section_icons/explanation.png');
 9178: }
 9179: section.role-introduction>h1:before {
 9180:   content:url('/adm/daxe/images/section_icons/introduction.png');
 9181: }
 9182: section.role-method>h1:before {
 9183:   content:url('/adm/daxe/images/section_icons/method.png');
 9184: }
 9185: section.role-more_information>h1:before {
 9186:   content:url('/adm/daxe/images/section_icons/more_information.png');
 9187: }
 9188: section.role-objectives>h1:before {
 9189:   content:url('/adm/daxe/images/section_icons/objectives.png');
 9190: }
 9191: section.role-prerequisites>h1:before {
 9192:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 9193: }
 9194: section.role-remark>h1:before {
 9195:   content:url('/adm/daxe/images/section_icons/remark.png');
 9196: }
 9197: section.role-reminder>h1:before {
 9198:   content:url('/adm/daxe/images/section_icons/reminder.png');
 9199: }
 9200: section.role-summary>h1:before {
 9201:   content:url('/adm/daxe/images/section_icons/summary.png');
 9202: }
 9203: section.role-syntax>h1:before {
 9204:   content:url('/adm/daxe/images/section_icons/syntax.png');
 9205: }
 9206: section.role-warning>h1:before {
 9207:   content:url('/adm/daxe/images/section_icons/warning.png');
 9208: }
 9209: 
 9210: #LC_minitab_header {
 9211:   float:left;
 9212:   width:100%;
 9213:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 9214:   font-size:93%;
 9215:   line-height:normal;
 9216:   margin: 0.5em 0 0.5em 0;
 9217: }
 9218: #LC_minitab_header ul {
 9219:   margin:0;
 9220:   padding:10px 10px 0;
 9221:   list-style:none;
 9222: }
 9223: #LC_minitab_header li {
 9224:   float:left;
 9225:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 9226:   margin:0;
 9227:   padding:0 0 0 9px;
 9228: }
 9229: #LC_minitab_header a {
 9230:   display:block;
 9231:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 9232:   padding:5px 15px 4px 6px;
 9233: }
 9234: #LC_minitab_header #LC_current_minitab {
 9235:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 9236: }
 9237: #LC_minitab_header #LC_current_minitab a {
 9238:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 9239:   padding-bottom:5px;
 9240: }
 9241: 
 9242: 
 9243: END
 9244: }
 9245: 
 9246: =pod
 9247: 
 9248: =item * &headtag()
 9249: 
 9250: Returns a uniform footer for LON-CAPA web pages.
 9251: 
 9252: Inputs: $title - optional title for the head
 9253:         $head_extra - optional extra HTML to put inside the <head>
 9254:         $args - optional arguments
 9255:             force_register - if is true call registerurl so the remote is 
 9256:                              informed
 9257:             redirect       -> array ref of
 9258:                                    1- seconds before redirect occurs
 9259:                                    2- url to redirect to
 9260:                                    3- whether the side effect should occur
 9261:                            (side effect of setting 
 9262:                                $env{'internal.head.redirect'} to the url 
 9263:                                redirected to)
 9264:                                    4- whether the redirect target should be
 9265:                                       the opener of the current (pop-up)
 9266:                                       window (side effect of setting
 9267:                                       $env{'internal.head.to_opener'} to
 9268:                                       1, if true.
 9269:                                    5- whether encrypt check should be skipped
 9270:             domain         -> force to color decorate a page for a specific
 9271:                                domain
 9272:             function       -> force usage of a specific rolish color scheme
 9273:             bgcolor        -> override the default page bgcolor
 9274:             no_auto_mt_title
 9275:                            -> prevent &mt()ing the title arg
 9276: 
 9277: =cut
 9278: 
 9279: sub headtag {
 9280:     my ($title,$head_extra,$args) = @_;
 9281:     
 9282:     my $function = $args->{'function'} || &get_users_function();
 9283:     my $domain   = $args->{'domain'}   || &determinedomain();
 9284:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 9285:     my $httphost = $args->{'use_absolute'};
 9286:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 9287: 		   $Apache::lonnet::perlvar{'lonVersion'},
 9288: 		   #time(),
 9289: 		   $env{'environment.color.timestamp'},
 9290: 		   $function,$domain,$bgcolor);
 9291: 
 9292:     $url = '/adm/css/'.&escape($url).'.css';
 9293: 
 9294:     my $result =
 9295: 	'<head>'.
 9296: 	&font_settings($args);
 9297: 
 9298:     my $inhibitprint;
 9299:     if ($args->{'print_suppress'}) {
 9300:         $inhibitprint = &print_suppression();
 9301:     }
 9302: 
 9303:     if (!$args->{'frameset'}) {
 9304: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 9305:     }
 9306:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 9307:         $result .= Apache::lonxml::display_title();
 9308:     }
 9309:     if (!$args->{'no_nav_bar'} 
 9310: 	&& !$args->{'only_body'}
 9311: 	&& !$args->{'frameset'}) {
 9312: 	$result .= &help_menu_js($httphost);
 9313:         $result.=&modal_window();
 9314:         $result.=&togglebox_script();
 9315:         $result.=&wishlist_window();
 9316:         $result.=&LCprogressbarUpdate_script();
 9317:     } else {
 9318:         if ($args->{'add_modal'}) {
 9319:            $result.=&modal_window();
 9320:         }
 9321:         if ($args->{'add_wishlist'}) {
 9322:            $result.=&wishlist_window();
 9323:         }
 9324:         if ($args->{'add_togglebox'}) {
 9325:            $result.=&togglebox_script();
 9326:         }
 9327:         if ($args->{'add_progressbar'}) {
 9328:            $result.=&LCprogressbarUpdate_script();
 9329:         }
 9330:     }
 9331:     if (ref($args->{'redirect'})) {
 9332: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 9333:         if (!$skip_enc_check) {
 9334:             $url = &Apache::lonenc::check_encrypt($url);
 9335:         }
 9336: 	if (!$inhibit_continue) {
 9337: 	    $env{'internal.head.redirect'} = $url;
 9338: 	}
 9339: 	$result.=<<"ADDMETA";
 9340: <meta http-equiv="pragma" content="no-cache" />
 9341: ADDMETA
 9342:         if ($to_opener) {
 9343:             $env{'internal.head.to_opener'} = 1;
 9344:             my $dest = &js_escape($url);
 9345:             my $timeout = int($time * 1000);
 9346:             $result .=<<"ENDJS";
 9347: <script type="text/javascript">
 9348: // <![CDATA[
 9349: function LC_To_Opener() {
 9350:     var dest = '$dest';
 9351:     if (dest != '') {
 9352:         if (window.opener != null && !window.opener.closed) {
 9353:             window.opener.location.href=dest;
 9354:             window.close();
 9355:         } else {
 9356:             window.location.href=dest;
 9357:         }
 9358:     }
 9359: }
 9360: \$(document).ready(function () {
 9361:     setTimeout('LC_To_Opener()',$timeout);
 9362: });
 9363: // ]]>
 9364: </script>
 9365: ENDJS
 9366:         } else {
 9367:             $result.=<<"ADDMETA";
 9368: <meta http-equiv="Refresh" content="$time; url=$url" />
 9369: ADDMETA
 9370:         }
 9371:     } else {
 9372:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 9373:             my $requrl = $env{'request.uri'};
 9374:             if ($requrl eq '') {
 9375:                 $requrl = $ENV{'REQUEST_URI'};
 9376:                 $requrl =~ s/\?.+$//;
 9377:             }
 9378:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 9379:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 9380:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 9381:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 9382:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 9383:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 9384:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 9385:                     my ($offload,$offloadoth);
 9386:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 9387:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 9388:                             $offload = 1;
 9389:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9390:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9391:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9392:                                     $offloadoth = 1;
 9393:                                     $dom_in_use = $env{'user.domain'};
 9394:                                 }
 9395:                             }
 9396:                         }
 9397:                     }
 9398:                     unless ($offload) {
 9399:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 9400:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 9401:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9402:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9403:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9404:                                         $offload = 1;
 9405:                                         $offloadoth = 1;
 9406:                                         $dom_in_use = $env{'user.domain'};
 9407:                                     }
 9408:                                 }
 9409:                             }
 9410:                         }
 9411:                     }
 9412:                     if ($offload) {
 9413:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 9414:                         if (($newserver eq '') && ($offloadoth)) {
 9415:                             my @domains = &Apache::lonnet::current_machine_domains();
 9416:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 9417:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 9418:                             }
 9419:                         }
 9420:                         if (($newserver) && ($newserver ne $lonhost)) {
 9421:                             my $numsec = 5;
 9422:                             my $timeout = $numsec * 1000;
 9423:                             my ($newurl,$locknum,%locks,$msg);
 9424:                             if ($env{'request.role.adv'}) {
 9425:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 9426:                             }
 9427:                             my $disable_submit = 0;
 9428:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 9429:                                 $disable_submit = 1;
 9430:                             }
 9431:                             if ($locknum) {
 9432:                                 my @lockinfo = sort(values(%locks));
 9433:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 9434:                                        join(", ",sort(values(%locks)))."\n";
 9435:                                 if (&show_course()) {
 9436:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 9437:                                 } else {
 9438:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 9439:                                 }
 9440:                             } else {
 9441:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 9442:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 9443:                                 }
 9444:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 9445:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 9446:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 9447:                                     $newurl .= '&role='.$env{'request.role'};
 9448:                                 }
 9449:                                 if ($env{'request.symb'}) {
 9450:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 9451:                                     if ($shownsymb =~ m{^/enc/}) {
 9452:                                         my $reqdmajor = 2;
 9453:                                         my $reqdminor = 11;
 9454:                                         my $reqdsubminor = 3;
 9455:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 9456:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 9457:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 9458:                                         if (($major eq '' && $minor eq '') ||
 9459:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 9460:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 9461:                                              ($reqdsubminor > $subminor))))) {
 9462:                                             undef($shownsymb);
 9463:                                         }
 9464:                                     }
 9465:                                     if ($shownsymb) {
 9466:                                         &js_escape(\$shownsymb);
 9467:                                         $newurl .= '&symb='.$shownsymb;
 9468:                                     }
 9469:                                 } else {
 9470:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 9471:                                     &js_escape(\$shownurl);
 9472:                                     $newurl .= '&origurl='.$shownurl;
 9473:                                 }
 9474:                             }
 9475:                             &js_escape(\$msg);
 9476:                             $result.=<<OFFLOAD
 9477: <meta http-equiv="pragma" content="no-cache" />
 9478: <script type="text/javascript">
 9479: // <![CDATA[
 9480: function LC_Offload_Now() {
 9481:     var dest = "$newurl";
 9482:     if (dest != '') {
 9483:         window.location.href="$newurl";
 9484:     }
 9485: }
 9486: \$(document).ready(function () {
 9487:     window.alert('$msg');
 9488:     if ($disable_submit) {
 9489:         \$(".LC_hwk_submit").prop("disabled", true);
 9490:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 9491:     }
 9492:     setTimeout('LC_Offload_Now()', $timeout);
 9493: });
 9494: // ]]>
 9495: </script>
 9496: OFFLOAD
 9497:                         }
 9498:                     }
 9499:                 }
 9500:             }
 9501:         }
 9502:     }
 9503:     if (!defined($title)) {
 9504: 	$title = 'The LearningOnline Network with CAPA';
 9505:     }
 9506:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 9507:     $result .= '<title> LON-CAPA '.$title.'</title>'
 9508: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 9509:     if (!$args->{'frameset'}) {
 9510:         $result .= ' /';
 9511:     }
 9512:     $result .= '>' 
 9513:         .$inhibitprint
 9514: 	.$head_extra;
 9515:     my $clientmobile;
 9516:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 9517:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 9518:     } else {
 9519:         $clientmobile = $env{'browser.mobile'};
 9520:     }
 9521:     if ($clientmobile) {
 9522:         $result .= '
 9523: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 9524: <meta name="apple-mobile-web-app-capable" content="yes" />';
 9525:     }
 9526:     $result .= '<meta name="google" content="notranslate" />'."\n";
 9527:     return $result.'</head>';
 9528: }
 9529: 
 9530: =pod
 9531: 
 9532: =item * &font_settings()
 9533: 
 9534: Returns neccessary <meta> to set the proper encoding
 9535: 
 9536: Inputs: optional reference to HASH -- $args passed to &headtag()
 9537: 
 9538: =cut
 9539: 
 9540: sub font_settings {
 9541:     my ($args) = @_;
 9542:     my $headerstring='';
 9543:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 9544:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 9545:         $headerstring.=
 9546:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 9547:         if (!$args->{'frameset'}) {
 9548: 	    $headerstring.= ' /';
 9549:         }
 9550: 	$headerstring .= '>'."\n";
 9551:     }
 9552:     return $headerstring;
 9553: }
 9554: 
 9555: =pod
 9556: 
 9557: =item * &print_suppression()
 9558: 
 9559: In course context returns css which causes the body to be blank when media="print",
 9560: if printout generation is unavailable for the current resource.
 9561: 
 9562: This could be because:
 9563: 
 9564: (a) printstartdate is in the future
 9565: 
 9566: (b) printenddate is in the past
 9567: 
 9568: (c) there is an active exam block with "printout"
 9569: functionality blocked
 9570: 
 9571: Users with pav, pfo or evb privileges are exempt.
 9572: 
 9573: Inputs: none
 9574: 
 9575: =cut
 9576: 
 9577: 
 9578: sub print_suppression {
 9579:     my $noprint;
 9580:     if ($env{'request.course.id'}) {
 9581:         my $scope = $env{'request.course.id'};
 9582:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9583:             (&Apache::lonnet::allowed('pfo',$scope))) {
 9584:             return;
 9585:         }
 9586:         if ($env{'request.course.sec'} ne '') {
 9587:             $scope .= "/$env{'request.course.sec'}";
 9588:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9589:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 9590:                 return;
 9591:             }
 9592:         }
 9593:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9594:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9595:         my $clientip = &Apache::lonnet::get_requestor_ip();
 9596:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 9597:         if ($blocked) {
 9598:             my $checkrole = "cm./$cdom/$cnum";
 9599:             if ($env{'request.course.sec'} ne '') {
 9600:                 $checkrole .= "/$env{'request.course.sec'}";
 9601:             }
 9602:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 9603:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 9604:                 $noprint = 1;
 9605:             }
 9606:         }
 9607:         unless ($noprint) {
 9608:             my $symb = &Apache::lonnet::symbread();
 9609:             if ($symb ne '') {
 9610:                 my $navmap = Apache::lonnavmaps::navmap->new();
 9611:                 if (ref($navmap)) {
 9612:                     my $res = $navmap->getBySymb($symb);
 9613:                     if (ref($res)) {
 9614:                         if (!$res->resprintable()) {
 9615:                             $noprint = 1;
 9616:                         }
 9617:                     }
 9618:                 }
 9619:             }
 9620:         }
 9621:         if ($noprint) {
 9622:             return <<"ENDSTYLE";
 9623: <style type="text/css" media="print">
 9624:     body { display:none }
 9625: </style>
 9626: ENDSTYLE
 9627:         }
 9628:     }
 9629:     return;
 9630: }
 9631: 
 9632: =pod
 9633: 
 9634: =item * &xml_begin()
 9635: 
 9636: Returns the needed doctype and <html>
 9637: 
 9638: Inputs: none
 9639: 
 9640: =cut
 9641: 
 9642: sub xml_begin {
 9643:     my ($is_frameset) = @_;
 9644:     my $output='';
 9645: 
 9646:     if ($env{'browser.mathml'}) {
 9647: 	$output='<?xml version="1.0"?>'
 9648:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 9649: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 9650:             
 9651: #	    .'<!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">] >'
 9652: 	    .'<!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">'
 9653:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 9654: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 9655:     } elsif ($is_frameset) {
 9656:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 9657:                 '<html>'."\n";
 9658:     } else {
 9659: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 9660:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 9661:     }
 9662:     return $output;
 9663: }
 9664: 
 9665: =pod
 9666: 
 9667: =item * &start_page()
 9668: 
 9669: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 9670: 
 9671: Inputs:
 9672: 
 9673: =over 4
 9674: 
 9675: $title - optional title for the page
 9676: 
 9677: $head_extra - optional extra HTML to incude inside the <head>
 9678: 
 9679: $args - additional optional args supported are:
 9680: 
 9681: =over 8
 9682: 
 9683:              only_body      -> is true will set &bodytag() onlybodytag
 9684:                                     arg on
 9685:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 9686:              add_entries    -> additional attributes to add to the  <body>
 9687:              domain         -> force to color decorate a page for a 
 9688:                                     specific domain
 9689:              function       -> force usage of a specific rolish color
 9690:                                     scheme
 9691:              redirect       -> see &headtag()
 9692:              bgcolor        -> override the default page bg color
 9693:              js_ready       -> return a string ready for being used in 
 9694:                                     a javascript writeln
 9695:              html_encode    -> return a string ready for being used in 
 9696:                                     a html attribute
 9697:              force_register -> if is true will turn on the &bodytag()
 9698:                                     $forcereg arg
 9699:              frameset       -> if true will start with a <frameset>
 9700:                                     rather than <body>
 9701:              skip_phases    -> hash ref of 
 9702:                                     head -> skip the <html><head> generation
 9703:                                     body -> skip all <body> generation
 9704:              no_auto_mt_title -> prevent &mt()ing the title arg
 9705:              bread_crumbs ->             Array containing breadcrumbs
 9706:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 9707:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 9708:                                     to lonhtmlcommon::breadcrumbs
 9709:              group          -> includes the current group, if page is for a 
 9710:                                specific group
 9711:              use_absolute   -> for request for external resource or syllabus, this
 9712:                                will contain https://<hostname> if server uses
 9713:                                https (as per hosts.tab), but request is for http
 9714:              hostname       -> hostname, originally from $r->hostname(), (optional).
 9715:              links_disabled -> Links in primary and secondary menus are disabled
 9716:                                (Can enable them once page has loaded - see lonroles.pm
 9717:                                for an example).
 9718:              links_target   -> Target for links, e.g., _parent (optional).
 9719: 
 9720: =back
 9721: 
 9722: =back
 9723: 
 9724: =cut
 9725: 
 9726: sub start_page {
 9727:     my ($title,$head_extra,$args) = @_;
 9728:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 9729: 
 9730:     $env{'internal.start_page'}++;
 9731:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 9732: 
 9733:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 9734:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 9735:     }
 9736: 
 9737:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 9738:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 9739:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 9740:                 $args->{'no_primary_menu'} = 1;
 9741:             }
 9742:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 9743:                 $args->{'no_inline_menu'} = 1;
 9744:             }
 9745:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 9746:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 9747:             }
 9748:         } else {
 9749:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9750:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 9751:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 9752:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 9753:                     $args->{'no_primary_menu'} = 1;
 9754:                 }
 9755:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 9756:                     $args->{'no_inline_menu'} = 1;
 9757:                 }
 9758:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 9759:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 9760:                 }
 9761:             }
 9762:         }
 9763:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 9764:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 9765:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 9766:     } elsif ($env{'request.course.id'}) {
 9767:         my $expiretime=600;
 9768:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 9769:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 9770:         }
 9771:         my ($deeplinkmenu,$menuref);
 9772:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 9773:         if ($menucoll) {
 9774:             if (ref($menuref) eq 'HASH') {
 9775:                 %menu = %{$menuref};
 9776:             }
 9777:             if ($menu{'top'} eq 'n') {
 9778:                 $args->{'no_primary_menu'} = 1;
 9779:             }
 9780:             if ($menu{'inline'} eq 'n') {
 9781:                 unless (&Apache::lonnet::allowed('opa')) {
 9782:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9783:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9784:                     my $crstype = &course_type();
 9785:                     my $now = time;
 9786:                     my $ccrole;
 9787:                     if ($crstype eq 'Community') {
 9788:                         $ccrole = 'co';
 9789:                     } else {
 9790:                         $ccrole = 'cc';
 9791:                     }
 9792:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 9793:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 9794:                         if ((($start) && ($start<0)) ||
 9795:                             (($end) && ($end<$now))  ||
 9796:                             (($start) && ($now<$start))) {
 9797:                             $args->{'no_inline_menu'} = 1;
 9798:                         }
 9799:                     } else {
 9800:                         $args->{'no_inline_menu'} = 1;
 9801:                     }
 9802:                 }
 9803:             }
 9804:         }
 9805:     }
 9806: 
 9807:     my $showncrumbs;
 9808:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 9809: 	if ($args->{'frameset'}) {
 9810: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 9811: 						$args->{'add_entries'});
 9812: 	    $result .= "\n<frameset $attr_string>\n";
 9813:         } else {
 9814:             $result .=
 9815:                 &bodytag($title, 
 9816:                          $args->{'function'},       $args->{'add_entries'},
 9817:                          $args->{'only_body'},      $args->{'domain'},
 9818:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 9819:                          $args->{'bgcolor'},        $args,
 9820:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
 9821:                          \%menu,\$showncrumbs);
 9822:         }
 9823:     }
 9824: 
 9825:     if ($args->{'js_ready'}) {
 9826: 		$result = &js_ready($result);
 9827:     }
 9828:     if ($args->{'html_encode'}) {
 9829: 		$result = &html_encode($result);
 9830:     }
 9831: 
 9832:     # Preparation for new and consistent functionlist at top of screen
 9833:     # if ($args->{'functionlist'}) {
 9834:     #            $result .= &build_functionlist();
 9835:     #}
 9836: 
 9837:     # Don't add anything more if only_body wanted or in const space
 9838:     return $result if    $args->{'only_body'} 
 9839:                       || $env{'request.state'} eq 'construct';
 9840: 
 9841:     #Breadcrumbs
 9842:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 9843:         unless ($showncrumbs) {
 9844: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 9845: 		#if any br links exists, add them to the breadcrumbs
 9846: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9847: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9848: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9849: 			}
 9850: 		}
 9851:                 # if @advtools array contains items add then to the breadcrumbs
 9852:                 if (@advtools > 0) {
 9853:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9854:                 }
 9855:                 my $menulink;
 9856:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9857:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9858:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 9859:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 9860:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 9861:                      (!$env{'request.role.adv'}))) {
 9862:                     $menulink = 0;
 9863:                 } else {
 9864:                     undef($menulink);
 9865:                 }
 9866:                 my $linkprotout;
 9867:                 if ($env{'request.deeplink.login'}) {
 9868:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 9869:                     if ($linkprotout) {
 9870:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 9871:                     }
 9872:                 }
 9873: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9874: 		if(exists($args->{'bread_crumbs_component'})){
 9875: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9876:                 } else {
 9877: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9878: 		}
 9879:         }
 9880:     }
 9881:     return $result;
 9882: }
 9883: 
 9884: sub end_page {
 9885:     my ($args) = @_;
 9886:     $env{'internal.end_page'}++;
 9887:     my $result;
 9888:     if ($args->{'discussion'}) {
 9889: 	my ($target,$parser);
 9890: 	if (ref($args->{'discussion'})) {
 9891: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9892: 				$args->{'discussion'}{'parser'});
 9893: 	}
 9894: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9895:     }
 9896:     if ($args->{'frameset'}) {
 9897: 	$result .= '</frameset>';
 9898:     } else {
 9899: 	$result .= &endbodytag($args);
 9900:     }
 9901:     unless ($args->{'notbody'}) {
 9902:         $result .= "\n</html>";
 9903:     }
 9904: 
 9905:     if ($args->{'js_ready'}) {
 9906: 	$result = &js_ready($result);
 9907:     }
 9908: 
 9909:     if ($args->{'html_encode'}) {
 9910: 	$result = &html_encode($result);
 9911:     }
 9912: 
 9913:     return $result;
 9914: }
 9915: 
 9916: sub menucoll_in_effect {
 9917:     my ($menucoll,$deeplinkmenu,%menu);
 9918:     if ($env{'request.course.id'}) {
 9919:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9920:         if ($env{'request.deeplink.login'}) {
 9921:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9922:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9923:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9924:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9925:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9926:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9927:                     if (ref($navmap)) {
 9928:                         $deeplink = $navmap->get_mapparam(undef,
 9929:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9930:                                                           '0.deeplink');
 9931:                     } else {
 9932:                         $check_login_symb = 1;
 9933:                     }
 9934:                 } else {
 9935:                     my $symb = &Apache::lonnet::symbread();
 9936:                     if ($symb) {
 9937:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9938:                     } else {
 9939:                         $check_login_symb = 1;
 9940:                     }
 9941:                 }
 9942:             } else {
 9943:                 $check_login_symb = 1;
 9944:             }
 9945:             if ($check_login_symb) {
 9946:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9947:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9948:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9949:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9950:                     if (ref($navmap)) {
 9951:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9952:                     }
 9953:                 } else {
 9954:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9955:                 }
 9956:             }
 9957:             if ($deeplink ne '') {
 9958:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9959:                 if ($display =~ /^\d+$/) {
 9960:                     $deeplinkmenu = 1;
 9961:                     $menucoll = $display;
 9962:                 }
 9963:             }
 9964:         }
 9965:         if ($menucoll) {
 9966:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9967:         }
 9968:     }
 9969:     return ($menucoll,$deeplinkmenu,\%menu);
 9970: }
 9971: 
 9972: sub deeplink_login_symb {
 9973:     my ($cnum,$cdom) = @_;
 9974:     my $login_symb;
 9975:     if ($env{'request.deeplink.login'}) {
 9976:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9977:     }
 9978:     return $login_symb;
 9979: }
 9980: 
 9981: sub symb_from_tinyurl {
 9982:     my ($url,$cnum,$cdom) = @_;
 9983:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9984:         my $key = $1;
 9985:         my ($tinyurl,$login);
 9986:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9987:         if (defined($cached)) {
 9988:             $tinyurl = $result;
 9989:         } else {
 9990:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9991:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9992:             if ($currtiny{$key} ne '') {
 9993:                 $tinyurl = $currtiny{$key};
 9994:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9995:             }
 9996:         }
 9997:         if ($tinyurl ne '') {
 9998:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9999:             if (wantarray) {
10000:                 return ($cnumreq,$symb);
10001:             } elsif ($cnumreq eq $cnum) {
10002:                 return $symb;
10003:             }
10004:         }
10005:     }
10006:     if (wantarray) {
10007:         return ();
10008:     } else {
10009:         return;
10010:     }
10011: }
10012: 
10013: sub usable_exttools {
10014:     my %tooltypes;
10015:     if ($env{'request.course.id'}) {
10016:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
10017:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
10018:                %tooltypes = (
10019:                              crs => 1,
10020:                              dom => 1,
10021:                             );
10022:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
10023:                $tooltypes{'crs'} = 1;
10024:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
10025:                $tooltypes{'dom'} = 1;
10026:            }
10027:         } else {
10028:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10029:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10030:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
10031:             if ($crstype eq '') {
10032:                 $crstype = 'course';
10033:             }
10034:             if ($crstype eq 'course') {
10035:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
10036:                     $crstype = 'official';
10037:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
10038:                     $crstype = 'textbook';
10039:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
10040:                     $crstype = 'lti';
10041:                 } else {
10042:                     $crstype = 'unofficial';
10043:                 }
10044:             }
10045:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
10046:             if ($domdefaults{$crstype.'domexttool'}) {
10047:                 $tooltypes{'dom'} = 1;
10048:             }
10049:             if ($domdefaults{$crstype.'exttool'}) {
10050:                 $tooltypes{'crs'} = 1;
10051:             }
10052:         }
10053:     }
10054:     return %tooltypes;
10055: }
10056: 
10057: sub wishlist_window {
10058:     return(<<'ENDWISHLIST');
10059: <script type="text/javascript">
10060: // <![CDATA[
10061: // <!-- BEGIN LON-CAPA Internal
10062: function set_wishlistlink(title, path) {
10063:     if (!title) {
10064:         title = document.title;
10065:         title = title.replace(/^LON-CAPA /,'');
10066:     }
10067:     title = encodeURIComponent(title);
10068:     title = title.replace("'","\\\'");
10069:     if (!path) {
10070:         path = location.pathname;
10071:     }
10072:     path = encodeURIComponent(path);
10073:     path = path.replace("'","\\\'");
10074:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
10075:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
10076: }
10077: // END LON-CAPA Internal -->
10078: // ]]>
10079: </script>
10080: ENDWISHLIST
10081: }
10082: 
10083: sub modal_window {
10084:     return(<<'ENDMODAL');
10085: <script type="text/javascript">
10086: // <![CDATA[
10087: // <!-- BEGIN LON-CAPA Internal
10088: var modalWindow = {
10089: 	parent:"body",
10090: 	windowId:null,
10091: 	content:null,
10092: 	width:null,
10093: 	height:null,
10094: 	close:function()
10095: 	{
10096: 	        $(".LCmodal-window").remove();
10097: 	        $(".LCmodal-overlay").remove();
10098: 	},
10099: 	open:function()
10100: 	{
10101: 		var modal = "";
10102: 		modal += "<div class=\"LCmodal-overlay\"></div>";
10103: 		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;\">";
10104: 		modal += this.content;
10105: 		modal += "</div>";	
10106: 
10107: 		$(this.parent).append(modal);
10108: 
10109: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
10110: 		$(".LCclose-window").click(function(){modalWindow.close();});
10111: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
10112: 	}
10113: };
10114: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
10115: 	{
10116:                 source = source.replace(/'/g,"&#39;");
10117: 		modalWindow.windowId = "myModal";
10118: 		modalWindow.width = width;
10119: 		modalWindow.height = height;
10120: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
10121: 		modalWindow.open();
10122: 	};
10123: // END LON-CAPA Internal -->
10124: // ]]>
10125: </script>
10126: ENDMODAL
10127: }
10128: 
10129: sub modal_link {
10130:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
10131:     unless ($width) { $width=480; }
10132:     unless ($height) { $height=400; }
10133:     unless ($scrolling) { $scrolling='yes'; }
10134:     unless ($transparency) { $transparency='true'; }
10135: 
10136:     my $target_attr;
10137:     if (defined($target)) {
10138:         $target_attr = 'target="'.$target.'"';
10139:     }
10140:     return <<"ENDLINK";
10141: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
10142: ENDLINK
10143: }
10144: 
10145: sub modal_adhoc_script {
10146:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
10147:     my $mathjax;
10148:     if ($possmathjax) {
10149:         $mathjax = <<'ENDJAX';
10150:                if (typeof MathJax == 'object') {
10151:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
10152:                }
10153: ENDJAX
10154:     }
10155:     return (<<ENDADHOC);
10156: <script type="text/javascript">
10157: // <![CDATA[
10158:         var $funcname = function()
10159:         {
10160:                 modalWindow.windowId = "myModal";
10161:                 modalWindow.width = $width;
10162:                 modalWindow.height = $height;
10163:                 modalWindow.content = '$content';
10164:                 modalWindow.open();
10165:                 $mathjax
10166:         };  
10167: // ]]>
10168: </script>
10169: ENDADHOC
10170: }
10171: 
10172: sub modal_adhoc_inner {
10173:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
10174:     my $innerwidth=$width-20;
10175:     $content=&js_ready(
10176:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
10177:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
10178:                  $content.
10179:                  &end_scrollbox().
10180:                  &end_page()
10181:              );
10182:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
10183: }
10184: 
10185: sub modal_adhoc_window {
10186:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
10187:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
10188:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
10189: }
10190: 
10191: sub modal_adhoc_launch {
10192:     my ($funcname,$width,$height,$content)=@_;
10193:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
10194: <script type="text/javascript">
10195: // <![CDATA[
10196: $funcname();
10197: // ]]>
10198: </script>
10199: ENDLAUNCH
10200: }
10201: 
10202: sub modal_adhoc_close {
10203:     return (<<ENDCLOSE);
10204: <script type="text/javascript">
10205: // <![CDATA[
10206: modalWindow.close();
10207: // ]]>
10208: </script>
10209: ENDCLOSE
10210: }
10211: 
10212: sub togglebox_script {
10213:    return(<<ENDTOGGLE);
10214: <script type="text/javascript"> 
10215: // <![CDATA[
10216: function LCtoggleDisplay(id,hidetext,showtext) {
10217:    link = document.getElementById(id + "link").childNodes[0];
10218:    with (document.getElementById(id).style) {
10219:       if (display == "none" ) {
10220:           display = "inline";
10221:           link.nodeValue = hidetext;
10222:         } else {
10223:           display = "none";
10224:           link.nodeValue = showtext;
10225:        }
10226:    }
10227: }
10228: // ]]>
10229: </script>
10230: ENDTOGGLE
10231: }
10232: 
10233: sub start_togglebox {
10234:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
10235:     unless ($heading) { $heading=''; } else { $heading.=' '; }
10236:     unless ($showtext) { $showtext=&mt('show'); }
10237:     unless ($hidetext) { $hidetext=&mt('hide'); }
10238:     unless ($headerbg) { $headerbg='#FFFFFF'; }
10239:     return &start_data_table().
10240:            &start_data_table_header_row().
10241:            '<td bgcolor="'.$headerbg.'">'.$heading.
10242:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
10243:            $showtext.'\')">'.$showtext.'</a>]</td>'.
10244:            &end_data_table_header_row().
10245:            '<tr id="'.$id.'" style="display:none""><td>';
10246: }
10247: 
10248: sub end_togglebox {
10249:     return '</td></tr>'.&end_data_table();
10250: }
10251: 
10252: sub LCprogressbar_script {
10253:    my ($id,$number_to_do)=@_;
10254:    if ($number_to_do) {
10255:        return(<<ENDPROGRESS);
10256: <script type="text/javascript">
10257: // <![CDATA[
10258: \$('#progressbar$id').progressbar({
10259:   value: 0,
10260:   change: function(event, ui) {
10261:     var newVal = \$(this).progressbar('option', 'value');
10262:     \$('.pblabel', this).text(LCprogressTxt);
10263:   }
10264: });
10265: // ]]>
10266: </script>
10267: ENDPROGRESS
10268:    } else {
10269:        return(<<ENDPROGRESS);
10270: <script type="text/javascript">
10271: // <![CDATA[
10272: \$('#progressbar$id').progressbar({
10273:   value: false,
10274:   create: function(event, ui) {
10275:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
10276:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
10277:   }
10278: });
10279: // ]]>
10280: </script>
10281: ENDPROGRESS
10282:    }
10283: }
10284: 
10285: sub LCprogressbarUpdate_script {
10286:    return(<<ENDPROGRESSUPDATE);
10287: <style type="text/css">
10288: .ui-progressbar { position:relative; }
10289: .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%; }
10290: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
10291: </style>
10292: <script type="text/javascript">
10293: // <![CDATA[
10294: var LCprogressTxt='---';
10295: 
10296: function LCupdateProgress(percent,progresstext,id,maxnum) {
10297:    LCprogressTxt=progresstext;
10298:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
10299:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
10300:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
10301:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
10302:    } else {
10303:        \$('#progressbar'+id).progressbar('value',percent);
10304:    }
10305: }
10306: // ]]>
10307: </script>
10308: ENDPROGRESSUPDATE
10309: }
10310: 
10311: my $LClastpercent;
10312: my $LCidcnt;
10313: my $LCcurrentid;
10314: 
10315: sub LCprogressbar {
10316:     my ($r,$number_to_do,$preamble)=@_;
10317:     $LClastpercent=0;
10318:     $LCidcnt++;
10319:     $LCcurrentid=$$.'_'.$LCidcnt;
10320:     my ($starting,$content);
10321:     if ($number_to_do) {
10322:         $starting=&mt('Starting');
10323:         $content=(<<ENDPROGBAR);
10324: $preamble
10325:   <div id="progressbar$LCcurrentid">
10326:     <span class="pblabel">$starting</span>
10327:   </div>
10328: ENDPROGBAR
10329:     } else {
10330:         $starting=&mt('Loading...');
10331:         $LClastpercent='false';
10332:         $content=(<<ENDPROGBAR);
10333: $preamble
10334:   <div id="progressbar$LCcurrentid">
10335:       <div class="progress-label">$starting</div>
10336:   </div>
10337: ENDPROGBAR
10338:     }
10339:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
10340: }
10341: 
10342: sub LCprogressbarUpdate {
10343:     my ($r,$val,$text,$number_to_do)=@_;
10344:     if ($number_to_do) {
10345:         unless ($val) { 
10346:             if ($LClastpercent) {
10347:                 $val=$LClastpercent;
10348:             } else {
10349:                 $val=0;
10350:             }
10351:         }
10352:         if ($val<0) { $val=0; }
10353:         if ($val>100) { $val=0; }
10354:         $LClastpercent=$val;
10355:         unless ($text) { $text=$val.'%'; }
10356:     } else {
10357:         $val = 'false';
10358:     }
10359:     $text=&js_ready($text);
10360:     &r_print($r,<<ENDUPDATE);
10361: <script type="text/javascript">
10362: // <![CDATA[
10363: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
10364: // ]]>
10365: </script>
10366: ENDUPDATE
10367: }
10368: 
10369: sub LCprogressbarClose {
10370:     my ($r)=@_;
10371:     $LClastpercent=0;
10372:     &r_print($r,<<ENDCLOSE);
10373: <script type="text/javascript">
10374: // <![CDATA[
10375: \$("#progressbar$LCcurrentid").hide('slow'); 
10376: // ]]>
10377: </script>
10378: ENDCLOSE
10379: }
10380: 
10381: sub r_print {
10382:     my ($r,$to_print)=@_;
10383:     if ($r) {
10384:       $r->print($to_print);
10385:       $r->rflush();
10386:     } else {
10387:       print($to_print);
10388:     }
10389: }
10390: 
10391: sub html_encode {
10392:     my ($result) = @_;
10393: 
10394:     $result = &HTML::Entities::encode($result,'<>&"');
10395:     
10396:     return $result;
10397: }
10398: 
10399: sub js_ready {
10400:     my ($result) = @_;
10401: 
10402:     $result =~ s/[\n\r]/ /xmsg;
10403:     $result =~ s/\\/\\\\/xmsg;
10404:     $result =~ s/'/\\'/xmsg;
10405:     $result =~ s{</}{<\\/}xmsg;
10406:     
10407:     return $result;
10408: }
10409: 
10410: sub validate_page {
10411:     if (  exists($env{'internal.start_page'})
10412: 	  &&     $env{'internal.start_page'} > 1) {
10413: 	&Apache::lonnet::logthis('start_page called multiple times '.
10414: 				 $env{'internal.start_page'}.' '.
10415: 				 $ENV{'request.filename'});
10416:     }
10417:     if (  exists($env{'internal.end_page'})
10418: 	  &&     $env{'internal.end_page'} > 1) {
10419: 	&Apache::lonnet::logthis('end_page called multiple times '.
10420: 				 $env{'internal.end_page'}.' '.
10421: 				 $env{'request.filename'});
10422:     }
10423:     if (     exists($env{'internal.start_page'})
10424: 	&& ! exists($env{'internal.end_page'})) {
10425: 	&Apache::lonnet::logthis('start_page called without end_page '.
10426: 				 $env{'request.filename'});
10427:     }
10428:     if (   ! exists($env{'internal.start_page'})
10429: 	&&   exists($env{'internal.end_page'})) {
10430: 	&Apache::lonnet::logthis('end_page called without start_page'.
10431: 				 $env{'request.filename'});
10432:     }
10433: }
10434: 
10435: 
10436: sub start_scrollbox {
10437:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
10438:     unless ($outerwidth) { $outerwidth='520px'; }
10439:     unless ($width) { $width='500px'; }
10440:     unless ($height) { $height='200px'; }
10441:     my ($table_id,$div_id,$tdcol);
10442:     if ($id ne '') {
10443:         $table_id = ' id="table_'.$id.'"';
10444:         $div_id = ' id="div_'.$id.'"';
10445:     }
10446:     if ($bgcolor ne '') {
10447:         $tdcol = "background-color: $bgcolor;";
10448:     }
10449:     my $nicescroll_js;
10450:     if ($env{'browser.mobile'}) {
10451:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
10452:     }
10453:     return <<"END";
10454: $nicescroll_js
10455: 
10456: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
10457: <div style="overflow:auto; width:$width; height:$height;"$div_id>
10458: END
10459: }
10460: 
10461: sub end_scrollbox {
10462:     return '</div></td></tr></table>';
10463: }
10464: 
10465: sub nicescroll_javascript {
10466:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10467:     my %options;
10468:     if (ref($cursor) eq 'HASH') {
10469:         %options = %{$cursor};
10470:     }
10471:     unless ($options{'railalign'} =~ /^left|right$/) {
10472:         $options{'railalign'} = 'left';
10473:     }
10474:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10475:         my $function  = &get_users_function();
10476:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10477:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10478:             $options{'cursorcolor'} = '#00F';
10479:         }
10480:     }
10481:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10482:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10483:             $options{'cursoropacity'}='1.0';
10484:         }
10485:     } else {
10486:         $options{'cursoropacity'}='1.0';
10487:     }
10488:     if ($options{'cursorfixedheight'} eq 'none') {
10489:         delete($options{'cursorfixedheight'});
10490:     } else {
10491:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10492:     }
10493:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10494:         delete($options{'railoffset'});
10495:     }
10496:     my @niceoptions;
10497:     while (my($key,$value) = each(%options)) {
10498:         if ($value =~ /^\{.+\}$/) {
10499:             push(@niceoptions,$key.':'.$value);
10500:         } else {
10501:             push(@niceoptions,$key.':"'.$value.'"');
10502:         }
10503:     }
10504:     my $nicescroll_js = '
10505: $(document).ready(
10506:       function() {
10507:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10508:       }
10509: );
10510: ';
10511:     if ($framecheck) {
10512:         $nicescroll_js .= '
10513: function expand_div(caller) {
10514:     if (top === self) {
10515:         document.getElementById("'.$id.'").style.width = "auto";
10516:         document.getElementById("'.$id.'").style.height = "auto";
10517:     } else {
10518:         try {
10519:             if (parent.frames) {
10520:                 if (parent.frames.length > 1) {
10521:                     var framesrc = parent.frames[1].location.href;
10522:                     var currsrc = framesrc.replace(/\#.*$/,"");
10523:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
10524:                         document.getElementById("'.$id.'").style.width = "auto";
10525:                         document.getElementById("'.$id.'").style.height = "auto";
10526:                     }
10527:                 }
10528:             }
10529:         } catch (e) {
10530:             return;
10531:         }
10532:     }
10533:     return;
10534: }
10535: ';
10536:     }
10537:     if ($needjsready) {
10538:         $nicescroll_js = '
10539: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10540:     } else {
10541:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10542:     }
10543:     return $nicescroll_js;
10544: }
10545: 
10546: sub simple_error_page {
10547:     my ($r,$title,$msg,$args) = @_;
10548:     my %displayargs;
10549:     if (ref($args) eq 'HASH') {
10550:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10551:         if ($args->{'only_body'}) {
10552:             $displayargs{'only_body'} = 1;
10553:         }
10554:         if ($args->{'no_nav_bar'}) {
10555:             $displayargs{'no_nav_bar'} = 1;
10556:         }
10557:     } else {
10558:         $msg = &mt($msg);
10559:     }
10560: 
10561:     my $page =
10562: 	&Apache::loncommon::start_page($title,'',\%displayargs).
10563: 	'<p class="LC_error">'.$msg.'</p>'.
10564: 	&Apache::loncommon::end_page();
10565:     if (ref($r)) {
10566: 	$r->print($page);
10567: 	return;
10568:     }
10569:     return $page;
10570: }
10571: 
10572: {
10573:     my @row_count;
10574: 
10575:     sub start_data_table_count {
10576:         unshift(@row_count, 0);
10577:         return;
10578:     }
10579: 
10580:     sub end_data_table_count {
10581:         shift(@row_count);
10582:         return;
10583:     }
10584: 
10585:     sub start_data_table {
10586: 	my ($add_class,$id) = @_;
10587: 	my $css_class = (join(' ','LC_data_table',$add_class));
10588:         my $table_id;
10589:         if (defined($id)) {
10590:             $table_id = ' id="'.$id.'"';
10591:         }
10592: 	&start_data_table_count();
10593: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10594:     }
10595: 
10596:     sub end_data_table {
10597: 	&end_data_table_count();
10598: 	return '</table>'."\n";;
10599:     }
10600: 
10601:     sub start_data_table_row {
10602: 	my ($add_class, $id) = @_;
10603: 	$row_count[0]++;
10604: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10605: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10606:         $id = (' id="'.$id.'"') unless ($id eq '');
10607:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10608:     }
10609:     
10610:     sub continue_data_table_row {
10611: 	my ($add_class, $id) = @_;
10612: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10613: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10614:         $id = (' id="'.$id.'"') unless ($id eq '');
10615:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10616:     }
10617: 
10618:     sub end_data_table_row {
10619: 	return '</tr>'."\n";;
10620:     }
10621: 
10622:     sub start_data_table_empty_row {
10623: #	$row_count[0]++;
10624: 	return  '<tr class="LC_empty_row" >'."\n";;
10625:     }
10626: 
10627:     sub end_data_table_empty_row {
10628: 	return '</tr>'."\n";;
10629:     }
10630: 
10631:     sub start_data_table_header_row {
10632: 	return  '<tr class="LC_header_row">'."\n";;
10633:     }
10634: 
10635:     sub end_data_table_header_row {
10636: 	return '</tr>'."\n";;
10637:     }
10638: 
10639:     sub data_table_caption {
10640:         my $caption = shift;
10641:         return "<caption class=\"LC_caption\">$caption</caption>";
10642:     }
10643: }
10644: 
10645: =pod
10646: 
10647: =item * &inhibit_menu_check($arg)
10648: 
10649: Checks for a inhibitmenu state and generates output to preserve it
10650: 
10651: Inputs:         $arg - can be any of
10652:                      - undef - in which case the return value is a string 
10653:                                to add  into arguments list of a uri
10654:                      - 'input' - in which case the return value is a HTML
10655:                                  <form> <input> field of type hidden to
10656:                                  preserve the value
10657:                      - a url - in which case the return value is the url with
10658:                                the neccesary cgi args added to preserve the
10659:                                inhibitmenu state
10660:                      - a ref to a url - no return value, but the string is
10661:                                         updated to include the neccessary cgi
10662:                                         args to preserve the inhibitmenu state
10663: 
10664: =cut
10665: 
10666: sub inhibit_menu_check {
10667:     my ($arg) = @_;
10668:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10669:     if ($arg eq 'input') {
10670: 	if ($env{'form.inhibitmenu'}) {
10671: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10672: 	} else {
10673: 	    return
10674: 	}
10675:     }
10676:     if ($env{'form.inhibitmenu'}) {
10677: 	if (ref($arg)) {
10678: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10679: 	} elsif ($arg eq '') {
10680: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10681: 	} else {
10682: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10683: 	}
10684:     }
10685:     if (!ref($arg)) {
10686: 	return $arg;
10687:     }
10688: }
10689: 
10690: ###############################################
10691: 
10692: =pod
10693: 
10694: =back
10695: 
10696: =head1 User Information Routines
10697: 
10698: =over 4
10699: 
10700: =item * &get_users_function()
10701: 
10702: Used by &bodytag to determine the current users primary role.
10703: Returns either 'student','coordinator','admin', or 'author'.
10704: 
10705: =cut
10706: 
10707: ###############################################
10708: sub get_users_function {
10709:     my $function = 'norole';
10710:     if ($env{'request.role'}=~/^(st)/) {
10711:         $function='student';
10712:     }
10713:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10714:         $function='coordinator';
10715:     }
10716:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10717:         $function='admin';
10718:     }
10719:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10720:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10721:         $function='author';
10722:     }
10723:     return $function;
10724: }
10725: 
10726: ###############################################
10727: 
10728: =pod
10729: 
10730: =item * &show_course()
10731: 
10732: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10733: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10734: 
10735: Inputs:
10736: None
10737: 
10738: Outputs:
10739: Scalar: 1 if 'Course' to be used, 0 otherwise.
10740: 
10741: =cut
10742: 
10743: ###############################################
10744: sub show_course {
10745:     my ($udom,$uname) = @_;
10746:     if (($udom ne '') && ($uname ne '')) {
10747:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
10748:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
10749:                 return 0;
10750:             } else {
10751:                 return 1;
10752:             }
10753:         }
10754:     }
10755:     my $course = !$env{'user.adv'};
10756:     if (!$env{'user.adv'}) {
10757:         foreach my $env (keys(%env)) {
10758:             next if ($env !~ m/^user\.priv\./);
10759:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10760:                 $course = 0;
10761:                 last;
10762:             }
10763:         }
10764:     }
10765:     return $course;
10766: }
10767: 
10768: ###############################################
10769: 
10770: =pod
10771: 
10772: =item * &check_user_status()
10773: 
10774: Determines current status of supplied role for a
10775: specific user. Roles can be active, previous or future.
10776: 
10777: Inputs: 
10778: user's domain, user's username, course's domain,
10779: course's number, optional section ID.
10780: 
10781: Outputs:
10782: role status: active, previous or future. 
10783: 
10784: =cut
10785: 
10786: sub check_user_status {
10787:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10788:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10789:     my @uroles = keys(%userinfo);
10790:     my $srchstr;
10791:     my $active_chk = 'none';
10792:     my $now = time;
10793:     if (@uroles > 0) {
10794:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10795:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10796:         } else {
10797:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10798:         }
10799:         if (grep/^\Q$srchstr\E$/,@uroles) {
10800:             my $role_end = 0;
10801:             my $role_start = 0;
10802:             $active_chk = 'active';
10803:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10804:                 $role_end = $1;
10805:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10806:                     $role_start = $1;
10807:                 }
10808:             }
10809:             if ($role_start > 0) {
10810:                 if ($now < $role_start) {
10811:                     $active_chk = 'future';
10812:                 }
10813:             }
10814:             if ($role_end > 0) {
10815:                 if ($now > $role_end) {
10816:                     $active_chk = 'previous';
10817:                 }
10818:             }
10819:         }
10820:     }
10821:     return $active_chk;
10822: }
10823: 
10824: ###############################################
10825: 
10826: =pod
10827: 
10828: =item * &get_sections()
10829: 
10830: Determines all the sections for a course including
10831: sections with students and sections containing other roles.
10832: Incoming parameters: 
10833: 
10834: 1. domain
10835: 2. course number 
10836: 3. reference to array containing roles for which sections should 
10837: be gathered (optional).
10838: 4. reference to array containing status types for which sections 
10839: should be gathered (optional).
10840: 
10841: If the third argument is undefined, sections are gathered for any role. 
10842: If the fourth argument is undefined, sections are gathered for any status.
10843: Permissible values are 'active' or 'future' or 'previous'.
10844:  
10845: Returns section hash (keys are section IDs, values are
10846: number of users in each section), subject to the
10847: optional roles filter, optional status filter 
10848: 
10849: =cut
10850: 
10851: ###############################################
10852: sub get_sections {
10853:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10854:     if (!defined($cdom) || !defined($cnum)) {
10855:         my $cid =  $env{'request.course.id'};
10856: 
10857: 	return if (!defined($cid));
10858: 
10859:         $cdom = $env{'course.'.$cid.'.domain'};
10860:         $cnum = $env{'course.'.$cid.'.num'};
10861:     }
10862: 
10863:     my %sectioncount;
10864:     my $now = time;
10865: 
10866:     my $check_students = 1;
10867:     my $only_students = 0;
10868:     if (ref($possible_roles) eq 'ARRAY') {
10869:         if (grep(/^st$/,@{$possible_roles})) {
10870:             if (@{$possible_roles} == 1) {
10871:                 $only_students = 1;
10872:             }
10873:         } else {
10874:             $check_students = 0;
10875:         }
10876:     }
10877: 
10878:     if ($check_students) { 
10879: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10880: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
10881: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
10882:         my $start_index = &Apache::loncoursedata::CL_START();
10883:         my $end_index = &Apache::loncoursedata::CL_END();
10884:         my $status;
10885: 	while (my ($student,$data) = each(%$classlist)) {
10886: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10887: 				                     $data->[$status_index],
10888:                                                      $data->[$start_index],
10889:                                                      $data->[$end_index]);
10890:             if ($stu_status eq 'Active') {
10891:                 $status = 'active';
10892:             } elsif ($end < $now) {
10893:                 $status = 'previous';
10894:             } elsif ($start > $now) {
10895:                 $status = 'future';
10896:             } 
10897: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
10898:                 if ((!defined($possible_status)) || (($status ne '') && 
10899:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
10900: 		    $sectioncount{$section}++;
10901:                 }
10902: 	    }
10903: 	}
10904:     }
10905:     if ($only_students) {
10906:         return %sectioncount;
10907:     }
10908:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10909:     foreach my $user (sort(keys(%courseroles))) {
10910: 	if ($user !~ /^(\w{2})/) { next; }
10911: 	my ($role) = ($user =~ /^(\w{2})/);
10912: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10913: 	my ($section,$status);
10914: 	if ($role eq 'cr' &&
10915: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10916: 	    $section=$1;
10917: 	}
10918: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10919: 	if (!defined($section) || $section eq '-1') { next; }
10920:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10921:         if ($end == -1 && $start == -1) {
10922:             next; #deleted role
10923:         }
10924:         if (!defined($possible_status)) { 
10925:             $sectioncount{$section}++;
10926:         } else {
10927:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10928:                 $status = 'active';
10929:             } elsif ($end < $now) {
10930:                 $status = 'future';
10931:             } elsif ($start > $now) {
10932:                 $status = 'previous';
10933:             }
10934:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10935:                 $sectioncount{$section}++;
10936:             }
10937:         }
10938:     }
10939:     return %sectioncount;
10940: }
10941: 
10942: ###############################################
10943: 
10944: =pod
10945: 
10946: =item * &get_course_users()
10947: 
10948: Retrieves usernames:domains for users in the specified course
10949: with specific role(s), and access status. 
10950: 
10951: Incoming parameters:
10952: 1. course domain
10953: 2. course number
10954: 3. access status: users must have - either active, 
10955: previous, future, or all.
10956: 4. reference to array of permissible roles
10957: 5. reference to array of section restrictions (optional)
10958: 6. reference to results object (hash of hashes).
10959: 7. reference to optional userdata hash
10960: 8. reference to optional statushash
10961: 9. flag if privileged users (except those set to unhide in
10962:    course settings) should be excluded    
10963: Keys of top level results hash are roles.
10964: Keys of inner hashes are username:domain, with 
10965: values set to access type.
10966: Optional userdata hash returns an array with arguments in the 
10967: same order as loncoursedata::get_classlist() for student data.
10968: 
10969: Optional statushash returns
10970: 
10971: Entries for end, start, section and status are blank because
10972: of the possibility of multiple values for non-student roles.
10973: 
10974: =cut
10975: 
10976: ###############################################
10977: 
10978: sub get_course_users {
10979:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10980:     my %idx = ();
10981:     my %seclists;
10982: 
10983:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10984:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10985:     $idx{end} = &Apache::loncoursedata::CL_END();
10986:     $idx{start} = &Apache::loncoursedata::CL_START();
10987:     $idx{id} = &Apache::loncoursedata::CL_ID();
10988:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10989:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10990:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10991: 
10992:     if (grep(/^st$/,@{$roles})) {
10993:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10994:         my $now = time;
10995:         foreach my $student (keys(%{$classlist})) {
10996:             my $match = 0;
10997:             my $secmatch = 0;
10998:             my $section = $$classlist{$student}[$idx{section}];
10999:             my $status = $$classlist{$student}[$idx{status}];
11000:             if ($section eq '') {
11001:                 $section = 'none';
11002:             }
11003:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
11004:                 if (grep(/^all$/,@{$sections})) {
11005:                     $secmatch = 1;
11006:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
11007:                     if (grep(/^none$/,@{$sections})) {
11008:                         $secmatch = 1;
11009:                     }
11010:                 } else {  
11011: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
11012: 		        $secmatch = 1;
11013:                     }
11014: 		}
11015:                 if (!$secmatch) {
11016:                     next;
11017:                 }
11018:             }
11019:             if (defined($$types{'active'})) {
11020:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
11021:                     push(@{$$users{st}{$student}},'active');
11022:                     $match = 1;
11023:                 }
11024:             }
11025:             if (defined($$types{'previous'})) {
11026:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
11027:                     push(@{$$users{st}{$student}},'previous');
11028:                     $match = 1;
11029:                 }
11030:             }
11031:             if (defined($$types{'future'})) {
11032:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
11033:                     push(@{$$users{st}{$student}},'future');
11034:                     $match = 1;
11035:                 }
11036:             }
11037:             if ($match) {
11038:                 push(@{$seclists{$student}},$section);
11039:                 if (ref($userdata) eq 'HASH') {
11040:                     $$userdata{$student} = $$classlist{$student};
11041:                 }
11042:                 if (ref($statushash) eq 'HASH') {
11043:                     $statushash->{$student}{'st'}{$section} = $status;
11044:                 }
11045:             }
11046:         }
11047:     }
11048:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
11049:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11050:         my $now = time;
11051:         my %displaystatus = ( previous => 'Expired',
11052:                               active   => 'Active',
11053:                               future   => 'Future',
11054:                             );
11055:         my (%nothide,@possdoms);
11056:         if ($hidepriv) {
11057:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
11058:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
11059:                 if ($user !~ /:/) {
11060:                     $nothide{join(':',split(/[\@]/,$user))}=1;
11061:                 } else {
11062:                     $nothide{$user} = 1;
11063:                 }
11064:             }
11065:             my @possdoms = ($cdom);
11066:             if ($coursehash{'checkforpriv'}) {
11067:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
11068:             }
11069:         }
11070:         foreach my $person (sort(keys(%coursepersonnel))) {
11071:             my $match = 0;
11072:             my $secmatch = 0;
11073:             my $status;
11074:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
11075:             $user =~ s/:$//;
11076:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
11077:             if ($end == -1 || $start == -1) {
11078:                 next;
11079:             }
11080:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
11081:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
11082:                 my ($uname,$udom) = split(/:/,$user);
11083:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
11084:                     if (grep(/^all$/,@{$sections})) {
11085:                         $secmatch = 1;
11086:                     } elsif ($usec eq '') {
11087:                         if (grep(/^none$/,@{$sections})) {
11088:                             $secmatch = 1;
11089:                         }
11090:                     } else {
11091:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
11092:                             $secmatch = 1;
11093:                         }
11094:                     }
11095:                     if (!$secmatch) {
11096:                         next;
11097:                     }
11098:                 }
11099:                 if ($usec eq '') {
11100:                     $usec = 'none';
11101:                 }
11102:                 if ($uname ne '' && $udom ne '') {
11103:                     if ($hidepriv) {
11104:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
11105:                             (!$nothide{$uname.':'.$udom})) {
11106:                             next;
11107:                         }
11108:                     }
11109:                     if ($end > 0 && $end < $now) {
11110:                         $status = 'previous';
11111:                     } elsif ($start > $now) {
11112:                         $status = 'future';
11113:                     } else {
11114:                         $status = 'active';
11115:                     }
11116:                     foreach my $type (keys(%{$types})) { 
11117:                         if ($status eq $type) {
11118:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
11119:                                 push(@{$$users{$role}{$user}},$type);
11120:                             }
11121:                             $match = 1;
11122:                         }
11123:                     }
11124:                     if (($match) && (ref($userdata) eq 'HASH')) {
11125:                         if (!exists($$userdata{$uname.':'.$udom})) {
11126: 			    &get_user_info($udom,$uname,\%idx,$userdata);
11127:                         }
11128:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
11129:                             push(@{$seclists{$uname.':'.$udom}},$usec);
11130:                         }
11131:                         if (ref($statushash) eq 'HASH') {
11132:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
11133:                         }
11134:                     }
11135:                 }
11136:             }
11137:         }
11138:         if (grep(/^ow$/,@{$roles})) {
11139:             if ((defined($cdom)) && (defined($cnum))) {
11140:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
11141:                 if ( defined($csettings{'internal.courseowner'}) ) {
11142:                     my $owner = $csettings{'internal.courseowner'};
11143:                     next if ($owner eq '');
11144:                     my ($ownername,$ownerdom);
11145:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
11146:                         $ownername = $1;
11147:                         $ownerdom = $2;
11148:                     } else {
11149:                         $ownername = $owner;
11150:                         $ownerdom = $cdom;
11151:                         $owner = $ownername.':'.$ownerdom;
11152:                     }
11153:                     @{$$users{'ow'}{$owner}} = 'any';
11154:                     if (defined($userdata) && 
11155: 			!exists($$userdata{$owner})) {
11156: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
11157:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
11158:                             push(@{$seclists{$owner}},'none');
11159:                         }
11160:                         if (ref($statushash) eq 'HASH') {
11161:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
11162:                         }
11163: 		    }
11164:                 }
11165:             }
11166:         }
11167:         foreach my $user (keys(%seclists)) {
11168:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
11169:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
11170:         }
11171:     }
11172:     return;
11173: }
11174: 
11175: sub get_user_info {
11176:     my ($udom,$uname,$idx,$userdata) = @_;
11177:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
11178: 	&plainname($uname,$udom,'lastname');
11179:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
11180:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
11181:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
11182:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
11183:     return;
11184: }
11185: 
11186: ###############################################
11187: 
11188: =pod
11189: 
11190: =item * &get_user_quota()
11191: 
11192: Retrieves quota assigned for storage of user files.
11193: Default is to report quota for portfolio files.
11194: 
11195: Incoming parameters:
11196: 1. user's username
11197: 2. user's domain
11198: 3. quota name - portfolio, author, or course
11199:    (if no quota name provided, defaults to portfolio).
11200: 4. crstype - official, unofficial, textbook, placement or community, 
11201:    if quota name is course
11202: 
11203: Returns:
11204: 1. Disk quota (in MB) assigned to student.
11205: 2. (Optional) Type of setting: custom or default
11206:    (individually assigned or default for user's 
11207:    institutional status).
11208: 3. (Optional) - User's institutional status (e.g., faculty, staff
11209:    or student - types as defined in localenroll::inst_usertypes 
11210:    for user's domain, which determines default quota for user.
11211: 4. (Optional) - Default quota which would apply to the user.
11212: 
11213: If a value has been stored in the user's environment, 
11214: it will return that, otherwise it returns the maximal default
11215: defined for the user's institutional status(es) in the domain.
11216: 
11217: =cut
11218: 
11219: ###############################################
11220: 
11221: 
11222: sub get_user_quota {
11223:     my ($uname,$udom,$quotaname,$crstype) = @_;
11224:     my ($quota,$quotatype,$settingstatus,$defquota);
11225:     if (!defined($udom)) {
11226:         $udom = $env{'user.domain'};
11227:     }
11228:     if (!defined($uname)) {
11229:         $uname = $env{'user.name'};
11230:     }
11231:     if (($udom eq '' || $uname eq '') ||
11232:         ($udom eq 'public') && ($uname eq 'public')) {
11233:         $quota = 0;
11234:         $quotatype = 'default';
11235:         $defquota = 0; 
11236:     } else {
11237:         my $inststatus;
11238:         if ($quotaname eq 'course') {
11239:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
11240:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
11241:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
11242:             } else {
11243:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
11244:                 $quota = $cenv{'internal.uploadquota'};
11245:             }
11246:         } else {
11247:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
11248:                 if ($quotaname eq 'author') {
11249:                     $quota = $env{'environment.authorquota'};
11250:                 } else {
11251:                     $quota = $env{'environment.portfolioquota'};
11252:                 }
11253:                 $inststatus = $env{'environment.inststatus'};
11254:             } else {
11255:                 my %userenv = 
11256:                     &Apache::lonnet::get('environment',['portfolioquota',
11257:                                          'authorquota','inststatus'],$udom,$uname);
11258:                 my ($tmp) = keys(%userenv);
11259:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11260:                     if ($quotaname eq 'author') {
11261:                         $quota = $userenv{'authorquota'};
11262:                     } else {
11263:                         $quota = $userenv{'portfolioquota'};
11264:                     }
11265:                     $inststatus = $userenv{'inststatus'};
11266:                 } else {
11267:                     undef(%userenv);
11268:                 }
11269:             }
11270:         }
11271:         if ($quota eq '' || wantarray) {
11272:             if ($quotaname eq 'course') {
11273:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
11274:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
11275:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
11276:                     ($crstype eq 'placement')) { 
11277:                     $defquota = $domdefs{$crstype.'quota'};
11278:                 }
11279:                 if ($defquota eq '') {
11280:                     $defquota = 500;
11281:                 }
11282:             } else {
11283:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
11284:             }
11285:             if ($quota eq '') {
11286:                 $quota = $defquota;
11287:                 $quotatype = 'default';
11288:             } else {
11289:                 $quotatype = 'custom';
11290:             }
11291:         }
11292:     }
11293:     if (wantarray) {
11294:         return ($quota,$quotatype,$settingstatus,$defquota);
11295:     } else {
11296:         return $quota;
11297:     }
11298: }
11299: 
11300: ###############################################
11301: 
11302: =pod
11303: 
11304: =item * &default_quota()
11305: 
11306: Retrieves default quota assigned for storage of user portfolio files,
11307: given an (optional) user's institutional status.
11308: 
11309: Incoming parameters:
11310: 
11311: 1. domain
11312: 2. (Optional) institutional status(es).  This is a : separated list of 
11313:    status types (e.g., faculty, staff, student etc.)
11314:    which apply to the user for whom the default is being retrieved.
11315:    If the institutional status string in undefined, the domain
11316:    default quota will be returned.
11317: 3.  quota name - portfolio, author, or course
11318:    (if no quota name provided, defaults to portfolio).
11319: 
11320: Returns:
11321: 
11322: 1. Default disk quota (in MB) for user portfolios in the domain.
11323: 2. (Optional) institutional type which determined the value of the
11324:    default quota.
11325: 
11326: If a value has been stored in the domain's configuration db,
11327: it will return that, otherwise it returns 20 (for backwards 
11328: compatibility with domains which have not set up a configuration
11329: db file; the original statically defined portfolio quota was 20 MB). 
11330: 
11331: If the user's status includes multiple types (e.g., staff and student),
11332: the largest default quota which applies to the user determines the
11333: default quota returned.
11334: 
11335: =cut
11336: 
11337: ###############################################
11338: 
11339: 
11340: sub default_quota {
11341:     my ($udom,$inststatus,$quotaname) = @_;
11342:     my ($defquota,$settingstatus);
11343:     my %quotahash = &Apache::lonnet::get_dom('configuration',
11344:                                             ['quotas'],$udom);
11345:     my $key = 'defaultquota';
11346:     if ($quotaname eq 'author') {
11347:         $key = 'authorquota';
11348:     }
11349:     if (ref($quotahash{'quotas'}) eq 'HASH') {
11350:         if ($inststatus ne '') {
11351:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
11352:             foreach my $item (@statuses) {
11353:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11354:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
11355:                         if ($defquota eq '') {
11356:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11357:                             $settingstatus = $item;
11358:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
11359:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11360:                             $settingstatus = $item;
11361:                         }
11362:                     }
11363:                 } elsif ($key eq 'defaultquota') {
11364:                     if ($quotahash{'quotas'}{$item} ne '') {
11365:                         if ($defquota eq '') {
11366:                             $defquota = $quotahash{'quotas'}{$item};
11367:                             $settingstatus = $item;
11368:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
11369:                             $defquota = $quotahash{'quotas'}{$item};
11370:                             $settingstatus = $item;
11371:                         }
11372:                     }
11373:                 }
11374:             }
11375:         }
11376:         if ($defquota eq '') {
11377:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11378:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
11379:             } elsif ($key eq 'defaultquota') {
11380:                 $defquota = $quotahash{'quotas'}{'default'};
11381:             }
11382:             $settingstatus = 'default';
11383:             if ($defquota eq '') {
11384:                 if ($quotaname eq 'author') {
11385:                     $defquota = 500;
11386:                 }
11387:             }
11388:         }
11389:     } else {
11390:         $settingstatus = 'default';
11391:         if ($quotaname eq 'author') {
11392:             $defquota = 500;
11393:         } else {
11394:             $defquota = 20;
11395:         }
11396:     }
11397:     if (wantarray) {
11398:         return ($defquota,$settingstatus);
11399:     } else {
11400:         return $defquota;
11401:     }
11402: }
11403: 
11404: ###############################################
11405: 
11406: =pod
11407: 
11408: =item * &excess_filesize_warning()
11409: 
11410: Returns warning message if upload of file to authoring space, or copying
11411: of existing file within authoring space will cause quota for the authoring
11412: space to be exceeded.
11413: 
11414: Same, if upload of a file directly to a course/community via Course Editor
11415: will cause quota for uploaded content for the course to be exceeded.
11416: 
11417: Inputs: 7 
11418: 1. username or coursenum
11419: 2. domain
11420: 3. context ('author' or 'course')
11421: 4. filename of file for which action is being requested
11422: 5. filesize (kB) of file
11423: 6. action being taken: copy or upload.
11424: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
11425: 
11426: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
11427:          otherwise return null.
11428: 
11429: =back
11430: 
11431: =cut
11432: 
11433: sub excess_filesize_warning {
11434:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
11435:     my $current_disk_usage = 0;
11436:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
11437:     if ($context eq 'author') {
11438:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
11439:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
11440:     } else {
11441:         foreach my $subdir ('docs','supplemental') {
11442:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
11443:         }
11444:     }
11445:     $disk_quota = int($disk_quota * 1000);
11446:     if (($current_disk_usage + $filesize) > $disk_quota) {
11447:         return '<p class="LC_warning">'.
11448:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
11449:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
11450:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11451:                             $disk_quota,$current_disk_usage).
11452:                '</p>';
11453:     }
11454:     return;
11455: }
11456: 
11457: ###############################################
11458: 
11459: 
11460: 
11461: 
11462: sub get_secgrprole_info {
11463:     my ($cdom,$cnum,$needroles,$type)  = @_;
11464:     my %sections_count = &get_sections($cdom,$cnum);
11465:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
11466:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
11467:     my @groups = sort(keys(%curr_groups));
11468:     my $allroles = [];
11469:     my $rolehash;
11470:     my $accesshash = {
11471:                      active => 'Currently has access',
11472:                      future => 'Will have future access',
11473:                      previous => 'Previously had access',
11474:                   };
11475:     if ($needroles) {
11476:         $rolehash = {'all' => 'all'};
11477:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11478: 	if (&Apache::lonnet::error(%user_roles)) {
11479: 	    undef(%user_roles);
11480: 	}
11481:         foreach my $item (keys(%user_roles)) {
11482:             my ($role)=split(/\:/,$item,2);
11483:             if ($role eq 'cr') { next; }
11484:             if ($role =~ /^cr/) {
11485:                 $$rolehash{$role} = (split('/',$role))[3];
11486:             } else {
11487:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11488:             }
11489:         }
11490:         foreach my $key (sort(keys(%{$rolehash}))) {
11491:             push(@{$allroles},$key);
11492:         }
11493:         push (@{$allroles},'st');
11494:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11495:     }
11496:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11497: }
11498: 
11499: sub user_picker {
11500:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11501:     my $currdom = $dom;
11502:     my @alldoms = &Apache::lonnet::all_domains();
11503:     if (@alldoms == 1) {
11504:         my %domsrch = &Apache::lonnet::get_dom('configuration',
11505:                                                ['directorysrch'],$alldoms[0]);
11506:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11507:         my $showdom = $domdesc;
11508:         if ($showdom eq '') {
11509:             $showdom = $dom;
11510:         }
11511:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11512:             if ((!$domsrch{'directorysrch'}{'available'}) &&
11513:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11514:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11515:             }
11516:         }
11517:     }
11518:     my %curr_selected = (
11519:                         srchin => 'dom',
11520:                         srchby => 'lastname',
11521:                       );
11522:     my $srchterm;
11523:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11524:         if ($srch->{'srchby'} ne '') {
11525:             $curr_selected{'srchby'} = $srch->{'srchby'};
11526:         }
11527:         if ($srch->{'srchin'} ne '') {
11528:             $curr_selected{'srchin'} = $srch->{'srchin'};
11529:         }
11530:         if ($srch->{'srchtype'} ne '') {
11531:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
11532:         }
11533:         if ($srch->{'srchdomain'} ne '') {
11534:             $currdom = $srch->{'srchdomain'};
11535:         }
11536:         $srchterm = $srch->{'srchterm'};
11537:     }
11538:     my %html_lt=&Apache::lonlocal::texthash(
11539:                     'usr'       => 'Search criteria',
11540:                     'doma'      => 'Domain/institution to search',
11541:                     'uname'     => 'username',
11542:                     'lastname'  => 'last name',
11543:                     'lastfirst' => 'last name, first name',
11544:                     'crs'       => 'in this course',
11545:                     'dom'       => 'in selected LON-CAPA domain', 
11546:                     'alc'       => 'all LON-CAPA',
11547:                     'instd'     => 'in institutional directory for selected domain',
11548:                     'exact'     => 'is',
11549:                     'contains'  => 'contains',
11550:                     'begins'    => 'begins with',
11551:                                        );
11552:     my %js_lt=&Apache::lonlocal::texthash(
11553:                     'youm'      => "You must include some text to search for.",
11554:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11555:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11556:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
11557:                     'ymcd'      => "You must choose a domain when using a domain search.",
11558:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
11559:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
11560:                      'thfo'     => "The following need to be corrected before the search can be run:",
11561:                                        );
11562:     &html_escape(\%html_lt);
11563:     &js_escape(\%js_lt);
11564:     my $domform;
11565:     my $allow_blank = 1;
11566:     if ($fixeddom) {
11567:         $allow_blank = 0;
11568:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11569:     } else {
11570:         my $defdom = $env{'request.role.domain'};
11571:         my ($trusted,$untrusted);
11572:         if (($context eq 'requestcrs') || ($context eq 'course')) {
11573:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11574:         } elsif ($context eq 'author') {
11575:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11576:         } elsif ($context eq 'domain') {
11577:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11578:         }
11579:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11580:     }
11581:     my $srchinsel = ' <select name="srchin">';
11582: 
11583:     my @srchins = ('crs','dom','alc','instd');
11584: 
11585:     foreach my $option (@srchins) {
11586:         # FIXME 'alc' option unavailable until 
11587:         #       loncreateuser::print_user_query_page()
11588:         #       has been completed.
11589:         next if ($option eq 'alc');
11590:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
11591:         next if ($option eq 'crs' && !$env{'request.course.id'});
11592:         next if (($option eq 'instd') && ($noinstd));
11593:         if ($curr_selected{'srchin'} eq $option) {
11594:             $srchinsel .= ' 
11595:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11596:         } else {
11597:             $srchinsel .= '
11598:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11599:         }
11600:     }
11601:     $srchinsel .= "\n  </select>\n";
11602: 
11603:     my $srchbysel =  ' <select name="srchby">';
11604:     foreach my $option ('lastname','lastfirst','uname') {
11605:         if ($curr_selected{'srchby'} eq $option) {
11606:             $srchbysel .= '
11607:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11608:         } else {
11609:             $srchbysel .= '
11610:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11611:          }
11612:     }
11613:     $srchbysel .= "\n  </select>\n";
11614: 
11615:     my $srchtypesel = ' <select name="srchtype">';
11616:     foreach my $option ('begins','contains','exact') {
11617:         if ($curr_selected{'srchtype'} eq $option) {
11618:             $srchtypesel .= '
11619:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11620:         } else {
11621:             $srchtypesel .= '
11622:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11623:         }
11624:     }
11625:     $srchtypesel .= "\n  </select>\n";
11626: 
11627:     my ($newuserscript,$new_user_create);
11628:     my $context_dom = $env{'request.role.domain'};
11629:     if ($context eq 'requestcrs') {
11630:         if ($env{'form.coursedom'} ne '') { 
11631:             $context_dom = $env{'form.coursedom'};
11632:         }
11633:     }
11634:     if ($forcenewuser) {
11635:         if (ref($srch) eq 'HASH') {
11636:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11637:                 if ($cancreate) {
11638:                     $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>';
11639:                 } else {
11640:                     my $helplink = 'javascript:helpMenu('."'display'".')';
11641:                     my %usertypetext = (
11642:                         official   => 'institutional',
11643:                         unofficial => 'non-institutional',
11644:                     );
11645:                     $new_user_create = '<p class="LC_warning">'
11646:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11647:                                       .' '
11648:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11649:                                           ,'<a href="'.$helplink.'">','</a>')
11650:                                       .'</p><br />';
11651:                 }
11652:             }
11653:         }
11654: 
11655:         $newuserscript = <<"ENDSCRIPT";
11656: 
11657: function setSearch(createnew,callingForm) {
11658:     if (createnew == 1) {
11659:         for (var i=0; i<callingForm.srchby.length; i++) {
11660:             if (callingForm.srchby.options[i].value == 'uname') {
11661:                 callingForm.srchby.selectedIndex = i;
11662:             }
11663:         }
11664:         for (var i=0; i<callingForm.srchin.length; i++) {
11665:             if ( callingForm.srchin.options[i].value == 'dom') {
11666: 		callingForm.srchin.selectedIndex = i;
11667:             }
11668:         }
11669:         for (var i=0; i<callingForm.srchtype.length; i++) {
11670:             if (callingForm.srchtype.options[i].value == 'exact') {
11671:                 callingForm.srchtype.selectedIndex = i;
11672:             }
11673:         }
11674:         for (var i=0; i<callingForm.srchdomain.length; i++) {
11675:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
11676:                 callingForm.srchdomain.selectedIndex = i;
11677:             }
11678:         }
11679:     }
11680: }
11681: ENDSCRIPT
11682: 
11683:     }
11684: 
11685:     my $output = <<"END_BLOCK";
11686: <script type="text/javascript">
11687: // <![CDATA[
11688: function validateEntry(callingForm) {
11689: 
11690:     var checkok = 1;
11691:     var srchin;
11692:     for (var i=0; i<callingForm.srchin.length; i++) {
11693: 	if ( callingForm.srchin[i].checked ) {
11694: 	    srchin = callingForm.srchin[i].value;
11695: 	}
11696:     }
11697: 
11698:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11699:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11700:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11701:     var srchterm =  callingForm.srchterm.value;
11702:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11703:     var msg = "";
11704: 
11705:     if (srchterm == "") {
11706:         checkok = 0;
11707:         msg += "$js_lt{'youm'}\\n";
11708:     }
11709: 
11710:     if (srchtype== 'begins') {
11711:         if (srchterm.length < 2) {
11712:             checkok = 0;
11713:             msg += "$js_lt{'thte'}\\n";
11714:         }
11715:     }
11716: 
11717:     if (srchtype== 'contains') {
11718:         if (srchterm.length < 3) {
11719:             checkok = 0;
11720:             msg += "$js_lt{'thet'}\\n";
11721:         }
11722:     }
11723:     if (srchin == 'instd') {
11724:         if (srchdomain == '') {
11725:             checkok = 0;
11726:             msg += "$js_lt{'yomc'}\\n";
11727:         }
11728:     }
11729:     if (srchin == 'dom') {
11730:         if (srchdomain == '') {
11731:             checkok = 0;
11732:             msg += "$js_lt{'ymcd'}\\n";
11733:         }
11734:     }
11735:     if (srchby == 'lastfirst') {
11736:         if (srchterm.indexOf(",") == -1) {
11737:             checkok = 0;
11738:             msg += "$js_lt{'whus'}\\n";
11739:         }
11740:         if (srchterm.indexOf(",") == srchterm.length -1) {
11741:             checkok = 0;
11742:             msg += "$js_lt{'whse'}\\n";
11743:         }
11744:     }
11745:     if (checkok == 0) {
11746:         alert("$js_lt{'thfo'}\\n"+msg);
11747:         return;
11748:     }
11749:     if (checkok == 1) {
11750:         callingForm.submit();
11751:     }
11752: }
11753: 
11754: $newuserscript
11755: 
11756: // ]]>
11757: </script>
11758: 
11759: $new_user_create
11760: 
11761: END_BLOCK
11762: 
11763:     $output .= &Apache::lonhtmlcommon::start_pick_box().
11764:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11765:                $domform.
11766:                &Apache::lonhtmlcommon::row_closure().
11767:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11768:                $srchbysel.
11769:                $srchtypesel. 
11770:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11771:                $srchinsel.
11772:                &Apache::lonhtmlcommon::row_closure(1). 
11773:                &Apache::lonhtmlcommon::end_pick_box().
11774:                '<br />';
11775:     return ($output,1);
11776: }
11777: 
11778: sub user_rule_check {
11779:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11780:     my ($response,%inst_response);
11781:     if (ref($usershash) eq 'HASH') {
11782:         if (keys(%{$usershash}) > 1) {
11783:             my (%by_username,%by_id,%userdoms);
11784:             my $checkid; 
11785:             if (ref($checks) eq 'HASH') {
11786:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11787:                     $checkid = 1;
11788:                 }
11789:             }
11790:             foreach my $user (keys(%{$usershash})) {
11791:                 my ($uname,$udom) = split(/:/,$user);
11792:                 if ($checkid) {
11793:                     if (ref($usershash->{$user}) eq 'HASH') {
11794:                         if ($usershash->{$user}->{'id'} ne '') {
11795:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
11796:                             $userdoms{$udom} = 1;
11797:                             if (ref($inst_results) eq 'HASH') {
11798:                                 $inst_results->{$uname.':'.$udom} = {};
11799:                             }
11800:                         }
11801:                     }
11802:                 } else {
11803:                     $by_username{$udom}{$uname} = 1;
11804:                     $userdoms{$udom} = 1;
11805:                     if (ref($inst_results) eq 'HASH') {
11806:                         $inst_results->{$uname.':'.$udom} = {};
11807:                     }
11808:                 }
11809:             }
11810:             foreach my $udom (keys(%userdoms)) {
11811:                 if (!$got_rules->{$udom}) {
11812:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
11813:                                                              ['usercreation'],$udom);
11814:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11815:                         foreach my $item ('username','id') {
11816:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11817:                                 $$curr_rules{$udom}{$item} =
11818:                                     $domconfig{'usercreation'}{$item.'_rule'};
11819:                             }
11820:                         }
11821:                     }
11822:                     $got_rules->{$udom} = 1;
11823:                 }
11824:             }
11825:             if ($checkid) {
11826:                 foreach my $udom (keys(%by_id)) {
11827:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11828:                     if ($outcome eq 'ok') {
11829:                         foreach my $id (keys(%{$by_id{$udom}})) {
11830:                             my $uname = $by_id{$udom}{$id};
11831:                             $inst_response{$uname.':'.$udom} = $outcome;
11832:                         }
11833:                         if (ref($results) eq 'HASH') {
11834:                             foreach my $uname (keys(%{$results})) {
11835:                                 if (exists($inst_response{$uname.':'.$udom})) {
11836:                                     $inst_response{$uname.':'.$udom} = $outcome;
11837:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
11838:                                 }
11839:                             }
11840:                         }
11841:                     }
11842:                 }
11843:             } else {
11844:                 foreach my $udom (keys(%by_username)) {
11845:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11846:                     if ($outcome eq 'ok') {
11847:                         foreach my $uname (keys(%{$by_username{$udom}})) {
11848:                             $inst_response{$uname.':'.$udom} = $outcome;
11849:                         }
11850:                         if (ref($results) eq 'HASH') {
11851:                             foreach my $uname (keys(%{$results})) {
11852:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
11853:                             }
11854:                         }
11855:                     }
11856:                 }
11857:             }
11858:         } elsif (keys(%{$usershash}) == 1) {
11859:             my $user = (keys(%{$usershash}))[0];
11860:             my ($uname,$udom) = split(/:/,$user);
11861:             if (($udom ne '') && ($uname ne '')) {
11862:                 if (ref($usershash->{$user}) eq 'HASH') {
11863:                     if (ref($checks) eq 'HASH') {
11864:                         if (defined($checks->{'username'})) {
11865:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
11866:                                 &Apache::lonnet::get_instuser($udom,$uname);
11867:                         } elsif (defined($checks->{'id'})) {
11868:                             if ($usershash->{$user}->{'id'} ne '') {
11869:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11870:                                     &Apache::lonnet::get_instuser($udom,undef,
11871:                                                                   $usershash->{$user}->{'id'});
11872:                             } else {
11873:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11874:                                     &Apache::lonnet::get_instuser($udom,$uname);
11875:                             }
11876:                         }
11877:                     } else {
11878:                        ($inst_response{$user},%{$inst_results->{$user}}) =
11879:                             &Apache::lonnet::get_instuser($udom,$uname);
11880:                        return;
11881:                     }
11882:                     if (!$got_rules->{$udom}) {
11883:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
11884:                                                                  ['usercreation'],$udom);
11885:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
11886:                             foreach my $item ('username','id') {
11887:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11888:                                    $$curr_rules{$udom}{$item} = 
11889:                                        $domconfig{'usercreation'}{$item.'_rule'};
11890:                                 }
11891:                             }
11892:                         }
11893:                         $got_rules->{$udom} = 1;
11894:                     }
11895:                 }
11896:             } else {
11897:                 return;
11898:             }
11899:         } else {
11900:             return;
11901:         }
11902:         foreach my $user (keys(%{$usershash})) {
11903:             my ($uname,$udom) = split(/:/,$user);
11904:             next if (($udom eq '') || ($uname eq ''));
11905:             my $id;
11906:             if (ref($inst_results) eq 'HASH') {
11907:                 if (ref($inst_results->{$user}) eq 'HASH') {
11908:                     $id = $inst_results->{$user}->{'id'};
11909:                 }
11910:             }
11911:             if ($id eq '') { 
11912:                 if (ref($usershash->{$user})) {
11913:                     $id = $usershash->{$user}->{'id'};
11914:                 }
11915:             }
11916:             foreach my $item (keys(%{$checks})) {
11917:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
11918:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11919:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
11920:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11921:                                                                              $$curr_rules{$udom}{$item});
11922:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11923:                                 if ($rule_check{$rule}) {
11924:                                     $$rulematch{$user}{$item} = $rule;
11925:                                     if ($inst_response{$user} eq 'ok') {
11926:                                         if (ref($inst_results) eq 'HASH') {
11927:                                             if (ref($inst_results->{$user}) eq 'HASH') {
11928:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
11929:                                                     $$alerts{$item}{$udom}{$uname} = 1;
11930:                                                 } elsif ($item eq 'id') {
11931:                                                     if ($inst_results->{$user}->{'id'} eq '') {
11932:                                                         $$alerts{$item}{$udom}{$uname} = 1;
11933:                                                     }
11934:                                                 }
11935:                                             }
11936:                                         }
11937:                                     }
11938:                                     last;
11939:                                 }
11940:                             }
11941:                         }
11942:                     }
11943:                 }
11944:             }
11945:         }
11946:     }
11947:     return;
11948: }
11949: 
11950: sub user_rule_formats {
11951:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11952:     my %text = ( 
11953:                  'username' => 'Usernames',
11954:                  'id'       => 'IDs',
11955:                );
11956:     my $output;
11957:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11958:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11959:         if (@{$ruleorder} > 0) {
11960:             $output = '<br />'.
11961:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11962:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11963:                       ' <ul>';
11964:             foreach my $rule (@{$ruleorder}) {
11965:                 if (ref($curr_rules) eq 'ARRAY') {
11966:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11967:                         if (ref($rules->{$rule}) eq 'HASH') {
11968:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11969:                                         $rules->{$rule}{'desc'}.'</li>';
11970:                         }
11971:                     }
11972:                 }
11973:             }
11974:             $output .= '</ul>';
11975:         }
11976:     }
11977:     return $output;
11978: }
11979: 
11980: sub instrule_disallow_msg {
11981:     my ($checkitem,$domdesc,$count,$mode) = @_;
11982:     my $response;
11983:     my %text = (
11984:                   item   => 'username',
11985:                   items  => 'usernames',
11986:                   match  => 'matches',
11987:                   do     => 'does',
11988:                   action => 'a username',
11989:                   one    => 'one',
11990:                );
11991:     if ($count > 1) {
11992:         $text{'item'} = 'usernames';
11993:         $text{'match'} ='match';
11994:         $text{'do'} = 'do';
11995:         $text{'action'} = 'usernames',
11996:         $text{'one'} = 'ones';
11997:     }
11998:     if ($checkitem eq 'id') {
11999:         $text{'items'} = 'IDs';
12000:         $text{'item'} = 'ID';
12001:         $text{'action'} = 'an ID';
12002:         if ($count > 1) {
12003:             $text{'item'} = 'IDs';
12004:             $text{'action'} = 'IDs';
12005:         }
12006:     }
12007:     $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 />';
12008:     if ($mode eq 'upload') {
12009:         if ($checkitem eq 'username') {
12010:             $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'}.");
12011:         } elsif ($checkitem eq 'id') {
12012:             $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.");
12013:         }
12014:     } elsif ($mode eq 'selfcreate') {
12015:         if ($checkitem eq 'id') {
12016:             $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.");
12017:         }
12018:     } else {
12019:         if ($checkitem eq 'username') {
12020:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
12021:         } elsif ($checkitem eq 'id') {
12022:             $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.");
12023:         }
12024:     }
12025:     return $response;
12026: }
12027: 
12028: sub personal_data_fieldtitles {
12029:     my %fieldtitles = &Apache::lonlocal::texthash (
12030:                         id => 'Student/Employee ID',
12031:                         permanentemail => 'E-mail address',
12032:                         lastname => 'Last Name',
12033:                         firstname => 'First Name',
12034:                         middlename => 'Middle Name',
12035:                         generation => 'Generation',
12036:                         gen => 'Generation',
12037:                         inststatus => 'Affiliation',
12038:                    );
12039:     return %fieldtitles;
12040: }
12041: 
12042: sub sorted_inst_types {
12043:     my ($dom) = @_;
12044:     my ($usertypes,$order);
12045:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
12046:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
12047:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
12048:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
12049:     } else {
12050:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
12051:     }
12052:     my $othertitle = &mt('All users');
12053:     if ($env{'request.course.id'}) {
12054:         $othertitle  = &mt('Any users');
12055:     }
12056:     my @types;
12057:     if (ref($order) eq 'ARRAY') {
12058:         @types = @{$order};
12059:     }
12060:     if (@types == 0) {
12061:         if (ref($usertypes) eq 'HASH') {
12062:             @types = sort(keys(%{$usertypes}));
12063:         }
12064:     }
12065:     if (keys(%{$usertypes}) > 0) {
12066:         $othertitle = &mt('Other users');
12067:     }
12068:     return ($othertitle,$usertypes,\@types);
12069: }
12070: 
12071: sub get_institutional_codes {
12072:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
12073: # Get complete list of course sections to update
12074:     my @currsections = ();
12075:     my @currxlists = ();
12076:     my (%unclutteredsec,%unclutteredlcsec);
12077:     my $coursecode = $$settings{'internal.coursecode'};
12078:     my $crskey = $crs.':'.$coursecode;
12079:     @{$unclutteredsec{$crskey}} = ();
12080:     @{$unclutteredlcsec{$crskey}} = ();
12081: 
12082:     if ($$settings{'internal.sectionnums'} ne '') {
12083:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
12084:     }
12085: 
12086:     if ($$settings{'internal.crosslistings'} ne '') {
12087:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
12088:     }
12089: 
12090:     if (@currxlists > 0) {
12091:         foreach my $xl (@currxlists) {
12092:             if ($xl =~ /^([^:]+):(\w*)$/) {
12093:                 unless (grep/^$1$/,@{$allcourses}) {
12094:                     push(@{$allcourses},$1);
12095:                     $$LC_code{$1} = $2;
12096:                 }
12097:             }
12098:         }
12099:     }
12100: 
12101:     if (@currsections > 0) {
12102:         foreach my $sec (@currsections) {
12103:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
12104:                 my $instsec = $1;
12105:                 my $lc_sec = $2;
12106:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
12107:                     push(@{$unclutteredsec{$crskey}},$instsec);
12108:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
12109:                 }
12110:             }
12111:         }
12112:     }
12113: 
12114:     if (@{$unclutteredsec{$crskey}} > 0) {
12115:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
12116:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
12117:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
12118:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
12119:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
12120:                     push(@{$allcourses},$sec);
12121:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
12122:                 }
12123:             }
12124:         }
12125:     }
12126:     return;
12127: }
12128: 
12129: sub get_standard_codeitems {
12130:     return ('Year','Semester','Department','Number','Section');
12131: }
12132: 
12133: =pod
12134: 
12135: =head1 Slot Helpers
12136: 
12137: =over 4
12138: 
12139: =item * sorted_slots()
12140: 
12141: Sorts an array of slot names in order of an optional sort key,
12142: default sort is by slot start time (earliest first). 
12143: 
12144: Inputs:
12145: 
12146: =over 4
12147: 
12148: slotsarr  - Reference to array of unsorted slot names.
12149: 
12150: slots     - Reference to hash of hash, where outer hash keys are slot names.
12151: 
12152: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
12153: 
12154: =back
12155: 
12156: Returns:
12157: 
12158: =over 4
12159: 
12160: sorted   - An array of slot names sorted by a specified sort key 
12161:            (default sort key is start time of the slot).
12162: 
12163: =back
12164: 
12165: =cut
12166: 
12167: 
12168: sub sorted_slots {
12169:     my ($slotsarr,$slots,$sortkey) = @_;
12170:     if ($sortkey eq '') {
12171:         $sortkey = 'starttime';
12172:     }
12173:     my @sorted;
12174:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
12175:         @sorted =
12176:             sort {
12177:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
12178:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
12179:                      }
12180:                      if (ref($slots->{$a})) { return -1;}
12181:                      if (ref($slots->{$b})) { return 1;}
12182:                      return 0;
12183:                  } @{$slotsarr};
12184:     }
12185:     return @sorted;
12186: }
12187: 
12188: =pod
12189: 
12190: =item * get_future_slots()
12191: 
12192: Inputs:
12193: 
12194: =over 4
12195: 
12196: cnum - course number
12197: 
12198: cdom - course domain
12199: 
12200: now - current UNIX time
12201: 
12202: symb - optional symb
12203: 
12204: =back
12205: 
12206: Returns:
12207: 
12208: =over 4
12209: 
12210: sorted_reservable - ref to array of student_schedulable slots currently 
12211:                     reservable, ordered by end date of reservation period.
12212: 
12213: reservable_now - ref to hash of student_schedulable slots currently
12214:                  reservable.
12215: 
12216:     Keys in inner hash are:
12217:     (a) symb: either blank or symb to which slot use is restricted.
12218:     (b) endreserve: end date of reservation period.
12219:     (c) uniqueperiod: start,end dates when slot is to be uniquely
12220:         selected.
12221: 
12222: sorted_future - ref to array of student_schedulable slots reservable in
12223:                 the future, ordered by start date of reservation period.
12224: 
12225: future_reservable - ref to hash of student_schedulable slots reservable
12226:                     in the future.
12227: 
12228:     Keys in inner hash are:
12229:     (a) symb: either blank or symb to which slot use is restricted.
12230:     (b) startreserve: start date of reservation period.
12231:     (c) uniqueperiod: start,end dates when slot is to be uniquely
12232:         selected.
12233: 
12234: =back
12235: 
12236: =cut
12237: 
12238: sub get_future_slots {
12239:     my ($cnum,$cdom,$now,$symb) = @_;
12240:     my $map;
12241:     if ($symb) {
12242:         ($map) = &Apache::lonnet::decode_symb($symb);
12243:     }
12244:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
12245:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
12246:     foreach my $slot (keys(%slots)) {
12247:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
12248:         if ($symb) {
12249:             if ($slots{$slot}->{'symb'} ne '') {
12250:                 my $canuse;
12251:                 my %oksymbs;
12252:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
12253:                 map { $oksymbs{$_} = 1; } @slotsymbs;
12254:                 if ($oksymbs{$symb}) {
12255:                     $canuse = 1;
12256:                 } else {
12257:                     foreach my $item (@slotsymbs) {
12258:                         if ($item =~ /\.(page|sequence)$/) {
12259:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
12260:                             if (($map ne '') && ($map eq $sloturl)) {
12261:                                 $canuse = 1;
12262:                                 last;
12263:                             }
12264:                         }
12265:                     }
12266:                 }
12267:                 next unless ($canuse);
12268:             }
12269:         }
12270:         if (($slots{$slot}->{'starttime'} > $now) &&
12271:             ($slots{$slot}->{'endtime'} > $now)) {
12272:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
12273:                 my $userallowed = 0;
12274:                 if ($slots{$slot}->{'allowedsections'}) {
12275:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
12276:                     if (!defined($env{'request.role.sec'})
12277:                         && grep(/^No section assigned$/,@allowed_sec)) {
12278:                         $userallowed=1;
12279:                     } else {
12280:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
12281:                             $userallowed=1;
12282:                         }
12283:                     }
12284:                     unless ($userallowed) {
12285:                         if (defined($env{'request.course.groups'})) {
12286:                             my @groups = split(/:/,$env{'request.course.groups'});
12287:                             foreach my $group (@groups) {
12288:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
12289:                                     $userallowed=1;
12290:                                     last;
12291:                                 }
12292:                             }
12293:                         }
12294:                     }
12295:                 }
12296:                 if ($slots{$slot}->{'allowedusers'}) {
12297:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
12298:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
12299:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
12300:                         $userallowed = 1;
12301:                     }
12302:                 }
12303:                 next unless($userallowed);
12304:             }
12305:             my $startreserve = $slots{$slot}->{'startreserve'};
12306:             my $endreserve = $slots{$slot}->{'endreserve'};
12307:             my $symb = $slots{$slot}->{'symb'};
12308:             my $uniqueperiod;
12309:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
12310:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
12311:             }
12312:             if (($startreserve < $now) &&
12313:                 (!$endreserve || $endreserve > $now)) {
12314:                 my $lastres = $endreserve;
12315:                 if (!$lastres) {
12316:                     $lastres = $slots{$slot}->{'starttime'};
12317:                 }
12318:                 $reservable_now{$slot} = {
12319:                                            symb       => $symb,
12320:                                            endreserve => $lastres,
12321:                                            uniqueperiod => $uniqueperiod,
12322:                                          };
12323:             } elsif (($startreserve > $now) &&
12324:                      (!$endreserve || $endreserve > $startreserve)) {
12325:                 $future_reservable{$slot} = {
12326:                                               symb         => $symb,
12327:                                               startreserve => $startreserve,
12328:                                               uniqueperiod => $uniqueperiod,
12329:                                             };
12330:             }
12331:         }
12332:     }
12333:     my @unsorted_reservable = keys(%reservable_now);
12334:     if (@unsorted_reservable > 0) {
12335:         @sorted_reservable = 
12336:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
12337:     }
12338:     my @unsorted_future = keys(%future_reservable);
12339:     if (@unsorted_future > 0) {
12340:         @sorted_future =
12341:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
12342:     }
12343:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
12344: }
12345: 
12346: =pod
12347: 
12348: =back
12349: 
12350: =head1 HTTP Helpers
12351: 
12352: =over 4
12353: 
12354: =item * &get_unprocessed_cgi($query,$possible_names)
12355: 
12356: Modify the %env hash to contain unprocessed CGI form parameters held in
12357: $query.  The parameters listed in $possible_names (an array reference),
12358: will be set in $env{'form.name'} if they do not already exist.
12359: 
12360: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
12361: $possible_names is an ref to an array of form element names.  As an example:
12362: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
12363: will result in $env{'form.uname'} and $env{'form.udom'} being set.
12364: 
12365: =cut
12366: 
12367: sub get_unprocessed_cgi {
12368:   my ($query,$possible_names)= @_;
12369:   # $Apache::lonxml::debug=1;
12370:   foreach my $pair (split(/&/,$query)) {
12371:     my ($name, $value) = split(/=/,$pair);
12372:     $name = &unescape($name);
12373:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
12374:       $value =~ tr/+/ /;
12375:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
12376:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
12377:     }
12378:   }
12379: }
12380: 
12381: =pod
12382: 
12383: =item * &cacheheader() 
12384: 
12385: returns cache-controlling header code
12386: 
12387: =cut
12388: 
12389: sub cacheheader {
12390:     unless ($env{'request.method'} eq 'GET') { return ''; }
12391:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
12392:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
12393:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
12394:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
12395:     return $output;
12396: }
12397: 
12398: =pod
12399: 
12400: =item * &no_cache($r) 
12401: 
12402: specifies header code to not have cache
12403: 
12404: =cut
12405: 
12406: sub no_cache {
12407:     my ($r) = @_;
12408:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
12409: 	$env{'request.method'} ne 'GET') { return ''; }
12410:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
12411:     $r->no_cache(1);
12412:     $r->header_out("Expires" => $date);
12413:     $r->header_out("Pragma" => "no-cache");
12414: }
12415: 
12416: sub content_type {
12417:     my ($r,$type,$charset) = @_;
12418:     if ($r) {
12419: 	#  Note that printout.pl calls this with undef for $r.
12420: 	&no_cache($r);
12421:     }
12422:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
12423:     unless ($charset) {
12424: 	$charset=&Apache::lonlocal::current_encoding;
12425:     }
12426:     if ($charset) { $type.='; charset='.$charset; }
12427:     if ($r) {
12428: 	$r->content_type($type);
12429:     } else {
12430: 	print("Content-type: $type\n\n");
12431:     }
12432: }
12433: 
12434: =pod
12435: 
12436: =item * &add_to_env($name,$value) 
12437: 
12438: adds $name to the %env hash with value
12439: $value, if $name already exists, the entry is converted to an array
12440: reference and $value is added to the array.
12441: 
12442: =cut
12443: 
12444: sub add_to_env {
12445:   my ($name,$value)=@_;
12446:   if (defined($env{$name})) {
12447:     if (ref($env{$name})) {
12448:       #already have multiple values
12449:       push(@{ $env{$name} },$value);
12450:     } else {
12451:       #first time seeing multiple values, convert hash entry to an arrayref
12452:       my $first=$env{$name};
12453:       undef($env{$name});
12454:       push(@{ $env{$name} },$first,$value);
12455:     }
12456:   } else {
12457:     $env{$name}=$value;
12458:   }
12459: }
12460: 
12461: =pod
12462: 
12463: =item * &get_env_multiple($name) 
12464: 
12465: gets $name from the %env hash, it seemlessly handles the cases where multiple
12466: values may be defined and end up as an array ref.
12467: 
12468: returns an array of values
12469: 
12470: =cut
12471: 
12472: sub get_env_multiple {
12473:     my ($name) = @_;
12474:     my @values;
12475:     if (defined($env{$name})) {
12476:         # exists is it an array
12477:         if (ref($env{$name})) {
12478:             @values=@{ $env{$name} };
12479:         } else {
12480:             $values[0]=$env{$name};
12481:         }
12482:     }
12483:     return(@values);
12484: }
12485: 
12486: # Looks at given dependencies, and returns something depending on the context.
12487: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
12488: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
12489: # For all other contexts, returns ($output, $counter, $numpathchg).
12490: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
12491: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
12492: # $numpathchg: integer with the number of cleaned up dependency paths.
12493: # \%existing: hash reference clean path -> 1 only for existing dependencies.
12494: # \%mapping: hash reference clean path -> original path for all dependencies.
12495: # @param {string} actionurl - The path to the handler, indicative of the context.
12496: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
12497: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
12498: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
12499: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
12500: # @return {Array} - array depending on the context (not a reference)
12501: sub ask_for_embedded_content {
12502:     # NOTE: documentation was added afterwards, it could be wrong
12503:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
12504:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
12505:         %currsubfile,%unused,$rem);
12506:     my $counter = 0;
12507:     my $numnew = 0;
12508:     my $numremref = 0;
12509:     my $numinvalid = 0;
12510:     my $numpathchg = 0;
12511:     my $numexisting = 0;
12512:     my $numunused = 0;
12513:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
12514:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
12515:     my $heading = &mt('Upload embedded files');
12516:     my $buttontext = &mt('Upload');
12517: 
12518:     # fills these variables based on the context:
12519:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
12520:     # $path, $fileloc, $title, $rem, $filename
12521:     if ($env{'request.course.id'}) {
12522:         if ($actionurl eq '/adm/dependencies') {
12523:             $navmap = Apache::lonnavmaps::navmap->new();
12524:         }
12525:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12526:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12527:     }
12528:     if (($actionurl eq '/adm/portfolio') || 
12529:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12530:         my $current_path='/';
12531:         if ($env{'form.currentpath'}) {
12532:             $current_path = $env{'form.currentpath'};
12533:         }
12534:         if ($actionurl eq '/adm/coursegrp_portfolio') {
12535:             $udom = $cdom;
12536:             $uname = $cnum;
12537:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12538:         } else {
12539:             $udom = $env{'user.domain'};
12540:             $uname = $env{'user.name'};
12541:             $url = '/userfiles/portfolio';
12542:         }
12543:         $toplevel = $url.'/';
12544:         $url .= $current_path;
12545:         $getpropath = 1;
12546:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12547:              ($actionurl eq '/adm/imsimport')) { 
12548:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12549:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12550:         $toplevel = $url;
12551:         if ($rest ne '') {
12552:             $url .= $rest;
12553:         }
12554:     } elsif ($actionurl eq '/adm/coursedocs') {
12555:         if (ref($args) eq 'HASH') {
12556:             $url = $args->{'docs_url'};
12557:             $toplevel = $url;
12558:             if ($args->{'context'} eq 'paste') {
12559:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12560:                 ($path) = 
12561:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12562:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12563:                 $fileloc =~ s{^/}{};
12564:             }
12565:         }
12566:     } elsif ($actionurl eq '/adm/dependencies')  {
12567:         if ($env{'request.course.id'} ne '') {
12568:             if (ref($args) eq 'HASH') {
12569:                 $url = $args->{'docs_url'};
12570:                 $title = $args->{'docs_title'};
12571:                 $toplevel = $url; 
12572:                 unless ($toplevel =~ m{^/}) {
12573:                     $toplevel = "/$url";
12574:                 }
12575:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12576:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12577:                     $path = $1;
12578:                 } else {
12579:                     ($path) =
12580:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12581:                 }
12582:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
12583:                     $fileloc = $toplevel;
12584:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12585:                     my ($udom,$uname,$fname) =
12586:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12587:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12588:                 } else {
12589:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12590:                 }
12591:                 $fileloc =~ s{^/}{};
12592:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12593:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12594:             }
12595:         }
12596:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12597:         $udom = $cdom;
12598:         $uname = $cnum;
12599:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12600:         $toplevel = $url;
12601:         $path = $url;
12602:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12603:         $fileloc =~ s{^/}{};
12604:     }
12605:     
12606:     # parses the dependency paths to get some info
12607:     # fills $newfiles, $mapping, $subdependencies, $dependencies
12608:     # $newfiles: hash URL -> 1 for new files or external URLs
12609:     # (will be completed later)
12610:     # $mapping:
12611:     #   for external URLs: external URL -> external URL
12612:     #   for relative paths: clean path -> original path
12613:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12614:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12615:     foreach my $file (keys(%{$allfiles})) {
12616:         my $embed_file;
12617:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12618:             $embed_file = $1;
12619:         } else {
12620:             $embed_file = $file;
12621:         }
12622:         my ($absolutepath,$cleaned_file);
12623:         if ($embed_file =~ m{^\w+://}) {
12624:             $cleaned_file = $embed_file;
12625:             $newfiles{$cleaned_file} = 1;
12626:             $mapping{$cleaned_file} = $embed_file;
12627:         } else {
12628:             $cleaned_file = &clean_path($embed_file);
12629:             if ($embed_file =~ m{^/}) {
12630:                 $absolutepath = $embed_file;
12631:             }
12632:             if ($cleaned_file =~ m{/}) {
12633:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12634:                 $path = &check_for_traversal($path,$url,$toplevel);
12635:                 my $item = $fname;
12636:                 if ($path ne '') {
12637:                     $item = $path.'/'.$fname;
12638:                     $subdependencies{$path}{$fname} = 1;
12639:                 } else {
12640:                     $dependencies{$item} = 1;
12641:                 }
12642:                 if ($absolutepath) {
12643:                     $mapping{$item} = $absolutepath;
12644:                 } else {
12645:                     $mapping{$item} = $embed_file;
12646:                 }
12647:             } else {
12648:                 $dependencies{$embed_file} = 1;
12649:                 if ($absolutepath) {
12650:                     $mapping{$cleaned_file} = $absolutepath;
12651:                 } else {
12652:                     $mapping{$cleaned_file} = $embed_file;
12653:                 }
12654:             }
12655:         }
12656:     }
12657:     
12658:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12659:     # and lists
12660:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12661:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12662:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12663:     #                                    the path had to be cleaned up
12664:     # $existing: hash clean path -> 1 if the file exists
12665:     # $numexisting: number of keys in $existing
12666:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12667:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12668:     #                                      dependency subdirectories that are
12669:     #                                      not listed as dependencies, with some exceptions using $rem
12670:     my $dirptr = 16384;
12671:     foreach my $path (keys(%subdependencies)) {
12672:         $currsubfile{$path} = {};
12673:         if (($actionurl eq '/adm/portfolio') || 
12674:             ($actionurl eq '/adm/coursegrp_portfolio')) {
12675:             my ($sublistref,$listerror) =
12676:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12677:             if (ref($sublistref) eq 'ARRAY') {
12678:                 foreach my $line (@{$sublistref}) {
12679:                     my ($file_name,$rest) = split(/\&/,$line,2);
12680:                     $currsubfile{$path}{$file_name} = 1;
12681:                 }
12682:             }
12683:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12684:             if (opendir(my $dir,$url.'/'.$path)) {
12685:                 my @subdir_list = grep(!/^\./,readdir($dir));
12686:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12687:             }
12688:         } elsif (($actionurl eq '/adm/dependencies') ||
12689:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12690:                   ($args->{'context'} eq 'paste')) ||
12691:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12692:             if ($env{'request.course.id'} ne '') {
12693:                 my $dir;
12694:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12695:                     $dir = $fileloc;
12696:                 } else {
12697:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12698:                 }
12699:                 if ($dir ne '') {
12700:                     my ($sublistref,$listerror) =
12701:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12702:                     if (ref($sublistref) eq 'ARRAY') {
12703:                         foreach my $line (@{$sublistref}) {
12704:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12705:                                 undef,$mtime)=split(/\&/,$line,12);
12706:                             unless (($testdir&$dirptr) ||
12707:                                     ($file_name =~ /^\.\.?$/)) {
12708:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
12709:                             }
12710:                         }
12711:                     }
12712:                 }
12713:             }
12714:         }
12715:         foreach my $file (keys(%{$subdependencies{$path}})) {
12716:             if (exists($currsubfile{$path}{$file})) {
12717:                 my $item = $path.'/'.$file;
12718:                 unless ($mapping{$item} eq $item) {
12719:                     $pathchanges{$item} = 1;
12720:                 }
12721:                 $existing{$item} = 1;
12722:                 $numexisting ++;
12723:             } else {
12724:                 $newfiles{$path.'/'.$file} = 1;
12725:             }
12726:         }
12727:         if ($actionurl eq '/adm/dependencies') {
12728:             foreach my $path (keys(%currsubfile)) {
12729:                 if (ref($currsubfile{$path}) eq 'HASH') {
12730:                     foreach my $file (keys(%{$currsubfile{$path}})) {
12731:                          unless ($subdependencies{$path}{$file}) {
12732:                              next if (($rem ne '') &&
12733:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
12734:                                        (ref($navmap) &&
12735:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12736:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12737:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
12738:                              $unused{$path.'/'.$file} = 1; 
12739:                          }
12740:                     }
12741:                 }
12742:             }
12743:         }
12744:     }
12745:     
12746:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
12747:     # for files in $url or $fileloc (target directory) in some contexts
12748:     my %currfile;
12749:     if (($actionurl eq '/adm/portfolio') ||
12750:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12751:         my ($dirlistref,$listerror) =
12752:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12753:         if (ref($dirlistref) eq 'ARRAY') {
12754:             foreach my $line (@{$dirlistref}) {
12755:                 my ($file_name,$rest) = split(/\&/,$line,2);
12756:                 $currfile{$file_name} = 1;
12757:             }
12758:         }
12759:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12760:         if (opendir(my $dir,$url)) {
12761:             my @dir_list = grep(!/^\./,readdir($dir));
12762:             map {$currfile{$_} = 1;} @dir_list;
12763:         }
12764:     } elsif (($actionurl eq '/adm/dependencies') ||
12765:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12766:               ($args->{'context'} eq 'paste')) ||
12767:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12768:         if ($env{'request.course.id'} ne '') {
12769:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12770:             if ($dir ne '') {
12771:                 my ($dirlistref,$listerror) =
12772:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12773:                 if (ref($dirlistref) eq 'ARRAY') {
12774:                     foreach my $line (@{$dirlistref}) {
12775:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12776:                             $size,undef,$mtime)=split(/\&/,$line,12);
12777:                         unless (($testdir&$dirptr) ||
12778:                                 ($file_name =~ /^\.\.?$/)) {
12779:                             $currfile{$file_name} = [$size,$mtime];
12780:                         }
12781:                     }
12782:                 }
12783:             }
12784:         }
12785:     }
12786:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12787:     # are not in subdirectories, using $currfile
12788:     foreach my $file (keys(%dependencies)) {
12789:         if (exists($currfile{$file})) {
12790:             unless ($mapping{$file} eq $file) {
12791:                 $pathchanges{$file} = 1;
12792:             }
12793:             $existing{$file} = 1;
12794:             $numexisting ++;
12795:         } else {
12796:             $newfiles{$file} = 1;
12797:         }
12798:     }
12799:     foreach my $file (keys(%currfile)) {
12800:         unless (($file eq $filename) ||
12801:                 ($file eq $filename.'.bak') ||
12802:                 ($dependencies{$file})) {
12803:             if ($actionurl eq '/adm/dependencies') {
12804:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12805:                     next if (($rem ne '') &&
12806:                              (($env{"httpref.$rem".$file} ne '') ||
12807:                               (ref($navmap) &&
12808:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
12809:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12810:                                 ($navmap->getResourceByUrl($rem.$1)))))));
12811:                 }
12812:             }
12813:             $unused{$file} = 1;
12814:         }
12815:     }
12816:     
12817:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12818:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12819:         ($args->{'context'} eq 'paste')) {
12820:         $counter = scalar(keys(%existing));
12821:         $numpathchg = scalar(keys(%pathchanges));
12822:         return ($output,$counter,$numpathchg,\%existing);
12823:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
12824:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12825:         $counter = scalar(keys(%existing));
12826:         $numpathchg = scalar(keys(%pathchanges));
12827:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
12828:     }
12829:     
12830:     # returns HTML otherwise, with dependency results and to ask for more uploads
12831:     
12832:     # $upload_output: missing dependencies (with upload form)
12833:     # $modify_output: uploaded dependencies (in use)
12834:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12835:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12836:         if ($actionurl eq '/adm/dependencies') {
12837:             next if ($embed_file =~ m{^\w+://});
12838:         }
12839:         $upload_output .= &start_data_table_row().
12840:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12841:                           '<span class="LC_filename">'.$embed_file.'</span>';
12842:         unless ($mapping{$embed_file} eq $embed_file) {
12843:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12844:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12845:         }
12846:         $upload_output .= '</td>';
12847:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
12848:             $upload_output.='<td align="right">'.
12849:                             '<span class="LC_info LC_fontsize_medium">'.
12850:                             &mt("URL points to web address").'</span>';
12851:             $numremref++;
12852:         } elsif ($args->{'error_on_invalid_names'}
12853:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12854:             $upload_output.='<td align="right"><span class="LC_warning">'.
12855:                             &mt('Invalid characters').'</span>';
12856:             $numinvalid++;
12857:         } else {
12858:             $upload_output .= '<td>'.
12859:                               &embedded_file_element('upload_embedded',$counter,
12860:                                                      $embed_file,\%mapping,
12861:                                                      $allfiles,$codebase,'upload');
12862:             $counter ++;
12863:             $numnew ++;
12864:         }
12865:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12866:     }
12867:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12868:         if ($actionurl eq '/adm/dependencies') {
12869:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12870:             $modify_output .= &start_data_table_row().
12871:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12872:                               '<img src="'.&icon($embed_file).'" border="0" />'.
12873:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
12874:                               '<td>'.$size.'</td>'.
12875:                               '<td>'.$mtime.'</td>'.
12876:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
12877:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12878:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12879:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12880:                               &embedded_file_element('upload_embedded',$counter,
12881:                                                      $embed_file,\%mapping,
12882:                                                      $allfiles,$codebase,'modify').
12883:                               '</div></td>'.
12884:                               &end_data_table_row()."\n";
12885:             $counter ++;
12886:         } else {
12887:             $upload_output .= &start_data_table_row().
12888:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12889:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
12890:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12891:                               &Apache::loncommon::end_data_table_row()."\n";
12892:         }
12893:     }
12894:     my $delidx = $counter;
12895:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12896:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12897:         $delete_output .= &start_data_table_row().
12898:                           '<td><img src="'.&icon($oldfile).'" />'.
12899:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
12900:                           '<td>'.$size.'</td>'.
12901:                           '<td>'.$mtime.'</td>'.
12902:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
12903:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12904:                           &embedded_file_element('upload_embedded',$delidx,
12905:                                                  $oldfile,\%mapping,$allfiles,
12906:                                                  $codebase,'delete').'</td>'.
12907:                           &end_data_table_row()."\n"; 
12908:         $numunused ++;
12909:         $delidx ++;
12910:     }
12911:     if ($upload_output) {
12912:         $upload_output = &start_data_table().
12913:                          $upload_output.
12914:                          &end_data_table()."\n";
12915:     }
12916:     if ($modify_output) {
12917:         $modify_output = &start_data_table().
12918:                          &start_data_table_header_row().
12919:                          '<th>'.&mt('File').'</th>'.
12920:                          '<th>'.&mt('Size (KB)').'</th>'.
12921:                          '<th>'.&mt('Modified').'</th>'.
12922:                          '<th>'.&mt('Upload replacement?').'</th>'.
12923:                          &end_data_table_header_row().
12924:                          $modify_output.
12925:                          &end_data_table()."\n";
12926:     }
12927:     if ($delete_output) {
12928:         $delete_output = &start_data_table().
12929:                          &start_data_table_header_row().
12930:                          '<th>'.&mt('File').'</th>'.
12931:                          '<th>'.&mt('Size (KB)').'</th>'.
12932:                          '<th>'.&mt('Modified').'</th>'.
12933:                          '<th>'.&mt('Delete?').'</th>'.
12934:                          &end_data_table_header_row().
12935:                          $delete_output.
12936:                          &end_data_table()."\n";
12937:     }
12938:     my $applies = 0;
12939:     if ($numremref) {
12940:         $applies ++;
12941:     }
12942:     if ($numinvalid) {
12943:         $applies ++;
12944:     }
12945:     if ($numexisting) {
12946:         $applies ++;
12947:     }
12948:     if ($counter || $numunused) {
12949:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12950:                   ' method="post" enctype="multipart/form-data">'."\n".
12951:                   $state.'<h3>'.$heading.'</h3>'; 
12952:         if ($actionurl eq '/adm/dependencies') {
12953:             if ($numnew) {
12954:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12955:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12956:                            $upload_output.'<br />'."\n";
12957:             }
12958:             if ($numexisting) {
12959:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12960:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12961:                            $modify_output.'<br />'."\n";
12962:                            $buttontext = &mt('Save changes');
12963:             }
12964:             if ($numunused) {
12965:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
12966:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12967:                            $delete_output.'<br />'."\n";
12968:                            $buttontext = &mt('Save changes');
12969:             }
12970:         } else {
12971:             $output .= $upload_output.'<br />'."\n";
12972:         }
12973:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12974:                    $counter.'" />'."\n";
12975:         if ($actionurl eq '/adm/dependencies') { 
12976:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12977:                        $numnew.'" />'."\n";
12978:         } elsif ($actionurl eq '') {
12979:             $output .=  '<input type="hidden" name="phase" value="three" />';
12980:         }
12981:     } elsif ($applies) {
12982:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12983:         if ($applies > 1) {
12984:             $output .=  
12985:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12986:             if ($numremref) {
12987:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12988:             }
12989:             if ($numinvalid) {
12990:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12991:             }
12992:             if ($numexisting) {
12993:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12994:             }
12995:             $output .= '</ul><br />';
12996:         } elsif ($numremref) {
12997:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12998:         } elsif ($numinvalid) {
12999:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
13000:         } elsif ($numexisting) {
13001:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
13002:         }
13003:         $output .= $upload_output.'<br />';
13004:     }
13005:     my ($pathchange_output,$chgcount);
13006:     $chgcount = $counter;
13007:     if (keys(%pathchanges) > 0) {
13008:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
13009:             if ($counter) {
13010:                 $output .= &embedded_file_element('pathchange',$chgcount,
13011:                                                   $embed_file,\%mapping,
13012:                                                   $allfiles,$codebase,'change');
13013:             } else {
13014:                 $pathchange_output .= 
13015:                     &start_data_table_row().
13016:                     '<td><input type ="checkbox" name="namechange" value="'.
13017:                     $chgcount.'" checked="checked" /></td>'.
13018:                     '<td>'.$mapping{$embed_file}.'</td>'.
13019:                     '<td>'.$embed_file.
13020:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
13021:                                            \%mapping,$allfiles,$codebase,'change').
13022:                     '</td>'.&end_data_table_row();
13023:             }
13024:             $numpathchg ++;
13025:             $chgcount ++;
13026:         }
13027:     }
13028:     if (($counter) || ($numunused)) {
13029:         if ($numpathchg) {
13030:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
13031:                        $numpathchg.'" />'."\n";
13032:         }
13033:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
13034:             ($actionurl eq '/adm/imsimport')) {
13035:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
13036:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
13037:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
13038:         } elsif ($actionurl eq '/adm/dependencies') {
13039:             $output .= '<input type="hidden" name="action" value="process_changes" />';
13040:         }
13041:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
13042:     } elsif ($numpathchg) {
13043:         my %pathchange = ();
13044:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
13045:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13046:             $output .= '<p>'.&mt('or').'</p>'; 
13047:         }
13048:     }
13049:     return ($output,$counter,$numpathchg);
13050: }
13051: 
13052: =pod
13053: 
13054: =item * clean_path($name)
13055: 
13056: Performs clean-up of directories, subdirectories and filename in an
13057: embedded object, referenced in an HTML file which is being uploaded
13058: to a course or portfolio, where 
13059: "Upload embedded images/multimedia files if HTML file" checkbox was
13060: checked.
13061: 
13062: Clean-up is similar to replacements in lonnet::clean_filename()
13063: except each / between sub-directory and next level is preserved.
13064: 
13065: =cut
13066: 
13067: sub clean_path {
13068:     my ($embed_file) = @_;
13069:     $embed_file =~s{^/+}{};
13070:     my @contents;
13071:     if ($embed_file =~ m{/}) {
13072:         @contents = split(/\//,$embed_file);
13073:     } else {
13074:         @contents = ($embed_file);
13075:     }
13076:     my $lastidx = scalar(@contents)-1;
13077:     for (my $i=0; $i<=$lastidx; $i++) { 
13078:         $contents[$i]=~s{\\}{/}g;
13079:         $contents[$i]=~s/\s+/\_/g;
13080:         $contents[$i]=~s{[^/\w\.\-]}{}g;
13081:         if ($i == $lastidx) {
13082:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
13083:         }
13084:     }
13085:     if ($lastidx > 0) {
13086:         return join('/',@contents);
13087:     } else {
13088:         return $contents[0];
13089:     }
13090: }
13091: 
13092: sub embedded_file_element {
13093:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
13094:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
13095:                    (ref($codebase) eq 'HASH'));
13096:     my $output;
13097:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
13098:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
13099:     }
13100:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
13101:                &escape($embed_file).'" />';
13102:     unless (($context eq 'upload_embedded') && 
13103:             ($mapping->{$embed_file} eq $embed_file)) {
13104:         $output .='
13105:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
13106:     }
13107:     my $attrib;
13108:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
13109:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
13110:     }
13111:     $output .=
13112:         "\n\t\t".
13113:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
13114:         $attrib.'" />';
13115:     if (exists($codebase->{$mapping->{$embed_file}})) {
13116:         $output .=
13117:             "\n\t\t".
13118:             '<input name="codebase_'.$num.'" type="hidden" value="'.
13119:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
13120:     }
13121:     return $output;
13122: }
13123: 
13124: sub get_dependency_details {
13125:     my ($currfile,$currsubfile,$embed_file) = @_;
13126:     my ($size,$mtime,$showsize,$showmtime);
13127:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
13128:         if ($embed_file =~ m{/}) {
13129:             my ($path,$fname) = split(/\//,$embed_file);
13130:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
13131:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
13132:             }
13133:         } else {
13134:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
13135:                 ($size,$mtime) = @{$currfile->{$embed_file}};
13136:             }
13137:         }
13138:         $showsize = $size/1024.0;
13139:         $showsize = sprintf("%.1f",$showsize);
13140:         if ($mtime > 0) {
13141:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
13142:         }
13143:     }
13144:     return ($showsize,$showmtime);
13145: }
13146: 
13147: sub ask_embedded_js {
13148:     return <<"END";
13149: <script type="text/javascript"">
13150: // <![CDATA[
13151: function toggleBrowse(counter) {
13152:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
13153:     var fileid = document.getElementById('embedded_item_'+counter);
13154:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
13155:     if (chkboxid.checked == true) {
13156:         uploaddivid.style.display='block';
13157:     } else {
13158:         uploaddivid.style.display='none';
13159:         fileid.value = '';
13160:     }
13161: }
13162: // ]]>
13163: </script>
13164: 
13165: END
13166: }
13167: 
13168: sub upload_embedded {
13169:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
13170:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
13171:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
13172:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
13173:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
13174:         my $orig_uploaded_filename =
13175:             $env{'form.embedded_item_'.$i.'.filename'};
13176:         foreach my $type ('orig','ref','attrib','codebase') {
13177:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
13178:                 $env{'form.embedded_'.$type.'_'.$i} =
13179:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
13180:             }
13181:         }
13182:         my ($path,$fname) =
13183:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
13184:         # no path, whole string is fname
13185:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
13186:         $fname = &Apache::lonnet::clean_filename($fname);
13187:         # See if there is anything left
13188:         next if ($fname eq '');
13189: 
13190:         # Check if file already exists as a file or directory.
13191:         my ($state,$msg);
13192:         if ($context eq 'portfolio') {
13193:             my $port_path = $dirpath;
13194:             if ($group ne '') {
13195:                 $port_path = "groups/$group/$port_path";
13196:             }
13197:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
13198:                                               $fname,$group,'embedded_item_'.$i,
13199:                                               $dir_root,$port_path,$disk_quota,
13200:                                               $current_disk_usage,$uname,$udom);
13201:             if ($state eq 'will_exceed_quota'
13202:                 || $state eq 'file_locked') {
13203:                 $output .= $msg;
13204:                 next;
13205:             }
13206:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
13207:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
13208:             if ($state eq 'exists') {
13209:                 $output .= $msg;
13210:                 next;
13211:             }
13212:         }
13213:         # Check if extension is valid
13214:         if (($fname =~ /\.(\w+)$/) &&
13215:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
13216:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
13217:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
13218:             next;
13219:         } elsif (($fname =~ /\.(\w+)$/) &&
13220:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
13221:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
13222:             next;
13223:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
13224:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
13225:             next;
13226:         }
13227:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
13228:         my $subdir = $path;
13229:         $subdir =~ s{/+$}{};
13230:         if ($context eq 'portfolio') {
13231:             my $result;
13232:             if ($state eq 'existingfile') {
13233:                 $result=
13234:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
13235:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
13236:             } else {
13237:                 $result=
13238:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
13239:                                                     $dirpath.
13240:                                                     $env{'form.currentpath'}.$subdir);
13241:                 if ($result !~ m|^/uploaded/|) {
13242:                     $output .= '<span class="LC_error">'
13243:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13244:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13245:                                .'</span><br />';
13246:                     next;
13247:                 } else {
13248:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13249:                                $path.$fname.'</span>').'<br />';     
13250:                 }
13251:             }
13252:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
13253:             my $extendedsubdir = $dirpath.'/'.$subdir;
13254:             $extendedsubdir =~ s{/+$}{};
13255:             my $result =
13256:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
13257:             if ($result !~ m|^/uploaded/|) {
13258:                 $output .= '<span class="LC_error">'
13259:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13260:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13261:                            .'</span><br />';
13262:                     next;
13263:             } else {
13264:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13265:                            $path.$fname.'</span>').'<br />';
13266:                 if ($context eq 'syllabus') {
13267:                     &Apache::lonnet::make_public_indefinitely($result);
13268:                 }
13269:             }
13270:         } else {
13271: # Save the file
13272:             my $target = $env{'form.embedded_item_'.$i};
13273:             my $fullpath = $dir_root.$dirpath.'/'.$path;
13274:             my $dest = $fullpath.$fname;
13275:             my $url = $url_root.$dirpath.'/'.$path.$fname;
13276:             my @parts=split(/\//,"$dirpath/$path");
13277:             my $count;
13278:             my $filepath = $dir_root;
13279:             foreach my $subdir (@parts) {
13280:                 $filepath .= "/$subdir";
13281:                 if (!-e $filepath) {
13282:                     mkdir($filepath,0770);
13283:                 }
13284:             }
13285:             my $fh;
13286:             if (!open($fh,'>'.$dest)) {
13287:                 &Apache::lonnet::logthis('Failed to create '.$dest);
13288:                 $output .= '<span class="LC_error">'.
13289:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
13290:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13291:                            '</span><br />';
13292:             } else {
13293:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
13294:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
13295:                     $output .= '<span class="LC_error">'.
13296:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
13297:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13298:                               '</span><br />';
13299:                 } else {
13300:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13301:                                $url.'</span>').'<br />';
13302:                     unless ($context eq 'testbank') {
13303:                         $footer .= &mt('View embedded file: [_1]',
13304:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
13305:                     }
13306:                 }
13307:                 close($fh);
13308:             }
13309:         }
13310:         if ($env{'form.embedded_ref_'.$i}) {
13311:             $pathchange{$i} = 1;
13312:         }
13313:     }
13314:     if ($output) {
13315:         $output = '<p>'.$output.'</p>';
13316:     }
13317:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
13318:     $returnflag = 'ok';
13319:     my $numpathchgs = scalar(keys(%pathchange));
13320:     if ($numpathchgs > 0) {
13321:         if ($context eq 'portfolio') {
13322:             $output .= '<p>'.&mt('or').'</p>';
13323:         } elsif ($context eq 'testbank') {
13324:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
13325:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
13326:             $returnflag = 'modify_orightml';
13327:         }
13328:     }
13329:     return ($output.$footer,$returnflag,$numpathchgs);
13330: }
13331: 
13332: sub modify_html_form {
13333:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
13334:     my $end = 0;
13335:     my $modifyform;
13336:     if ($context eq 'upload_embedded') {
13337:         return unless (ref($pathchange) eq 'HASH');
13338:         if ($env{'form.number_embedded_items'}) {
13339:             $end += $env{'form.number_embedded_items'};
13340:         }
13341:         if ($env{'form.number_pathchange_items'}) {
13342:             $end += $env{'form.number_pathchange_items'};
13343:         }
13344:         if ($end) {
13345:             for (my $i=0; $i<$end; $i++) {
13346:                 if ($i < $env{'form.number_embedded_items'}) {
13347:                     next unless($pathchange->{$i});
13348:                 }
13349:                 $modifyform .=
13350:                     &start_data_table_row().
13351:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
13352:                     'checked="checked" /></td>'.
13353:                     '<td>'.$env{'form.embedded_ref_'.$i}.
13354:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
13355:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
13356:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
13357:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
13358:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
13359:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
13360:                     '<td>'.$env{'form.embedded_orig_'.$i}.
13361:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
13362:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
13363:                     &end_data_table_row();
13364:             }
13365:         }
13366:     } else {
13367:         $modifyform = $pathchgtable;
13368:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
13369:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
13370:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13371:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
13372:         }
13373:     }
13374:     if ($modifyform) {
13375:         if ($actionurl eq '/adm/dependencies') {
13376:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
13377:         }
13378:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
13379:                '<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".
13380:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
13381:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
13382:                '</ol></p>'."\n".'<p>'.
13383:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
13384:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
13385:                &start_data_table()."\n".
13386:                &start_data_table_header_row().
13387:                '<th>'.&mt('Change?').'</th>'.
13388:                '<th>'.&mt('Current reference').'</th>'.
13389:                '<th>'.&mt('Required reference').'</th>'.
13390:                &end_data_table_header_row()."\n".
13391:                $modifyform.
13392:                &end_data_table().'<br />'."\n".$hiddenstate.
13393:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
13394:                '</form>'."\n";
13395:     }
13396:     return;
13397: }
13398: 
13399: sub modify_html_refs {
13400:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
13401:     my $container;
13402:     if ($context eq 'portfolio') {
13403:         $container = $env{'form.container'};
13404:     } elsif ($context eq 'coursedoc') {
13405:         $container = $env{'form.primaryurl'};
13406:     } elsif ($context eq 'manage_dependencies') {
13407:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
13408:         $container = "/$container";
13409:     } elsif ($context eq 'syllabus') {
13410:         $container = $url;
13411:     } else {
13412:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
13413:     }
13414:     my (%allfiles,%codebase,$output,$content);
13415:     my @changes = &get_env_multiple('form.namechange');
13416:     unless ((@changes > 0) || ($context eq 'syllabus')) {
13417:         if (wantarray) {
13418:             return ('',0,0); 
13419:         } else {
13420:             return;
13421:         }
13422:     }
13423:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13424:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13425:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
13426:             if (wantarray) {
13427:                 return ('',0,0);
13428:             } else {
13429:                 return;
13430:             }
13431:         } 
13432:         $content = &Apache::lonnet::getfile($container);
13433:         if ($content eq '-1') {
13434:             if (wantarray) {
13435:                 return ('',0,0);
13436:             } else {
13437:                 return;
13438:             }
13439:         }
13440:     } else {
13441:         unless ($container =~ /^\Q$dir_root\E/) {
13442:             if (wantarray) {
13443:                 return ('',0,0);
13444:             } else {
13445:                 return;
13446:             }
13447:         } 
13448:         if (open(my $fh,'<',$container)) {
13449:             $content = join('', <$fh>);
13450:             close($fh);
13451:         } else {
13452:             if (wantarray) {
13453:                 return ('',0,0);
13454:             } else {
13455:                 return;
13456:             }
13457:         }
13458:     }
13459:     my ($count,$codebasecount) = (0,0);
13460:     my $mm = new File::MMagic;
13461:     my $mime_type = $mm->checktype_contents($content);
13462:     if ($mime_type eq 'text/html') {
13463:         my $parse_result = 
13464:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
13465:                                                     \%codebase,\$content);
13466:         if ($parse_result eq 'ok') {
13467:             foreach my $i (@changes) {
13468:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
13469:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
13470:                 if ($allfiles{$ref}) {
13471:                     my $newname =  $orig;
13472:                     my ($attrib_regexp,$codebase);
13473:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
13474:                     if ($attrib_regexp =~ /:/) {
13475:                         $attrib_regexp =~ s/\:/|/g;
13476:                     }
13477:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13478:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13479:                         $count += $numchg;
13480:                         $allfiles{$newname} = $allfiles{$ref};
13481:                         delete($allfiles{$ref});
13482:                     }
13483:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
13484:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
13485:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
13486:                         $codebasecount ++;
13487:                     }
13488:                 }
13489:             }
13490:             my $skiprewrites;
13491:             if ($count || $codebasecount) {
13492:                 my $saveresult;
13493:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13494:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13495:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13496:                     if ($url eq $container) {
13497:                         my ($fname) = ($container =~ m{/([^/]+)$});
13498:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13499:                                             $count,'<span class="LC_filename">'.
13500:                                             $fname.'</span>').'</p>';
13501:                     } else {
13502:                          $output = '<p class="LC_error">'.
13503:                                    &mt('Error: update failed for: [_1].',
13504:                                    '<span class="LC_filename">'.
13505:                                    $container.'</span>').'</p>';
13506:                     }
13507:                     if ($context eq 'syllabus') {
13508:                         unless ($saveresult eq 'ok') {
13509:                             $skiprewrites = 1;
13510:                         }
13511:                     }
13512:                 } else {
13513:                     if (open(my $fh,'>',$container)) {
13514:                         print $fh $content;
13515:                         close($fh);
13516:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13517:                                   $count,'<span class="LC_filename">'.
13518:                                   $container.'</span>').'</p>';
13519:                     } else {
13520:                          $output = '<p class="LC_error">'.
13521:                                    &mt('Error: could not update [_1].',
13522:                                    '<span class="LC_filename">'.
13523:                                    $container.'</span>').'</p>';
13524:                     }
13525:                 }
13526:             }
13527:             if (($context eq 'syllabus') && (!$skiprewrites)) {
13528:                 my ($actionurl,$state);
13529:                 $actionurl = "/public/$udom/$uname/syllabus";
13530:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
13531:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
13532:                                               \%codebase,
13533:                                               {'context' => 'rewrites',
13534:                                                'ignore_remote_references' => 1,});
13535:                 if (ref($mapping) eq 'HASH') {
13536:                     my $rewrites = 0;
13537:                     foreach my $key (keys(%{$mapping})) {
13538:                         next if ($key =~ m{^https?://});
13539:                         my $ref = $mapping->{$key};
13540:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13541:                         my $attrib;
13542:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13543:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13544:                         }
13545:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13546:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13547:                             $rewrites += $numchg;
13548:                         }
13549:                     }
13550:                     if ($rewrites) {
13551:                         my $saveresult; 
13552:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13553:                         if ($url eq $container) {
13554:                             my ($fname) = ($container =~ m{/([^/]+)$});
13555:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13556:                                             $count,'<span class="LC_filename">'.
13557:                                             $fname.'</span>').'</p>';
13558:                         } else {
13559:                             $output .= '<p class="LC_error">'.
13560:                                        &mt('Error: could not update links in [_1].',
13561:                                        '<span class="LC_filename">'.
13562:                                        $container.'</span>').'</p>';
13563: 
13564:                         }
13565:                     }
13566:                 }
13567:             }
13568:         } else {
13569:             &logthis('Failed to parse '.$container.
13570:                      ' to modify references: '.$parse_result);
13571:         }
13572:     }
13573:     if (wantarray) {
13574:         return ($output,$count,$codebasecount);
13575:     } else {
13576:         return $output;
13577:     }
13578: }
13579: 
13580: sub check_for_existing {
13581:     my ($path,$fname,$element) = @_;
13582:     my ($state,$msg);
13583:     if (-d $path.'/'.$fname) {
13584:         $state = 'exists';
13585:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13586:     } elsif (-e $path.'/'.$fname) {
13587:         $state = 'exists';
13588:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13589:     }
13590:     if ($state eq 'exists') {
13591:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
13592:     }
13593:     return ($state,$msg);
13594: }
13595: 
13596: sub check_for_upload {
13597:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13598:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13599:     my $filesize = length($env{'form.'.$element});
13600:     if (!$filesize) {
13601:         my $msg = '<span class="LC_error">'.
13602:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
13603:                       '<span class="LC_filename">'.$fname.'</span>',
13604:                       $filesize).'<br />'.
13605:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13606:                   '</span>';
13607:         return ('zero_bytes',$msg);
13608:     }
13609:     $filesize =  $filesize/1000; #express in k (1024?)
13610:     my $getpropath = 1;
13611:     my ($dirlistref,$listerror) =
13612:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13613:     my $found_file = 0;
13614:     my $locked_file = 0;
13615:     my @lockers;
13616:     my $navmap;
13617:     if ($env{'request.course.id'}) {
13618:         $navmap = Apache::lonnavmaps::navmap->new();
13619:     }
13620:     if (ref($dirlistref) eq 'ARRAY') {
13621:         foreach my $line (@{$dirlistref}) {
13622:             my ($file_name,$rest)=split(/\&/,$line,2);
13623:             if ($file_name eq $fname){
13624:                 $file_name = $path.$file_name;
13625:                 if ($group ne '') {
13626:                     $file_name = $group.$file_name;
13627:                 }
13628:                 $found_file = 1;
13629:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13630:                     foreach my $lock (@lockers) {
13631:                         if (ref($lock) eq 'ARRAY') {
13632:                             my ($symb,$crsid) = @{$lock};
13633:                             if ($crsid eq $env{'request.course.id'}) {
13634:                                 if (ref($navmap)) {
13635:                                     my $res = $navmap->getBySymb($symb);
13636:                                     foreach my $part (@{$res->parts()}) { 
13637:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13638:                                         unless (($slot_status == $res->RESERVED) ||
13639:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
13640:                                             $locked_file = 1;
13641:                                         }
13642:                                     }
13643:                                 } else {
13644:                                     $locked_file = 1;
13645:                                 }
13646:                             } else {
13647:                                 $locked_file = 1;
13648:                             }
13649:                         }
13650:                    }
13651:                 } else {
13652:                     my @info = split(/\&/,$rest);
13653:                     my $currsize = $info[6]/1000;
13654:                     if ($currsize < $filesize) {
13655:                         my $extra = $filesize - $currsize;
13656:                         if (($current_disk_usage + $extra) > $disk_quota) {
13657:                             my $msg = '<p class="LC_warning">'.
13658:                                       &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.',
13659:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13660:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13661:                                                    $disk_quota,$current_disk_usage).'</p>';
13662:                             return ('will_exceed_quota',$msg);
13663:                         }
13664:                     }
13665:                 }
13666:             }
13667:         }
13668:     }
13669:     if (($current_disk_usage + $filesize) > $disk_quota){
13670:         my $msg = '<p class="LC_warning">'.
13671:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13672:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13673:         return ('will_exceed_quota',$msg);
13674:     } elsif ($found_file) {
13675:         if ($locked_file) {
13676:             my $msg = '<p class="LC_warning">';
13677:             $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>');
13678:             $msg .= '</p>';
13679:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13680:             return ('file_locked',$msg);
13681:         } else {
13682:             my $msg = '<p class="LC_error">';
13683:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13684:             $msg .= '</p>';
13685:             return ('existingfile',$msg);
13686:         }
13687:     }
13688: }
13689: 
13690: sub check_for_traversal {
13691:     my ($path,$url,$toplevel) = @_;
13692:     my @parts=split(/\//,$path);
13693:     my $cleanpath;
13694:     my $fullpath = $url;
13695:     for (my $i=0;$i<@parts;$i++) {
13696:         next if ($parts[$i] eq '.');
13697:         if ($parts[$i] eq '..') {
13698:             $fullpath =~ s{([^/]+/)$}{};
13699:         } else {
13700:             $fullpath .= $parts[$i].'/';
13701:         }
13702:     }
13703:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
13704:         $cleanpath = $1;
13705:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13706:         my $curr_toprel = $1;
13707:         my @parts = split(/\//,$curr_toprel);
13708:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13709:         my @urlparts = split(/\//,$url_toprel);
13710:         my $doubledots;
13711:         my $startdiff = -1;
13712:         for (my $i=0; $i<@urlparts; $i++) {
13713:             if ($startdiff == -1) {
13714:                 unless ($urlparts[$i] eq $parts[$i]) {
13715:                     $startdiff = $i;
13716:                     $doubledots .= '../';
13717:                 }
13718:             } else {
13719:                 $doubledots .= '../';
13720:             }
13721:         }
13722:         if ($startdiff > -1) {
13723:             $cleanpath = $doubledots;
13724:             for (my $i=$startdiff; $i<@parts; $i++) {
13725:                 $cleanpath .= $parts[$i].'/';
13726:             }
13727:         }
13728:     }
13729:     $cleanpath =~ s{(/)$}{};
13730:     return $cleanpath;
13731: }
13732: 
13733: sub is_archive_file {
13734:     my ($mimetype) = @_;
13735:     if (($mimetype eq 'application/octet-stream') ||
13736:         ($mimetype eq 'application/x-stuffit') ||
13737:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13738:         return 1;
13739:     }
13740:     return;
13741: }
13742: 
13743: sub decompress_form {
13744:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13745:     my %lt = &Apache::lonlocal::texthash (
13746:         this => 'This file is an archive file.',
13747:         camt => 'This file is a Camtasia archive file.',
13748:         itsc => 'Its contents are as follows:',
13749:         youm => 'You may wish to extract its contents.',
13750:         extr => 'Extract contents',
13751:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13752:         proa => 'Process automatically?',
13753:         yes  => 'Yes',
13754:         no   => 'No',
13755:         fold => 'Title for folder containing movie',
13756:         movi => 'Title for page containing embedded movie', 
13757:     );
13758:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13759:     my ($is_camtasia,$topdir,%toplevel,@paths);
13760:     my $info = &list_archive_contents($fileloc,\@paths);
13761:     if (@paths) {
13762:         foreach my $path (@paths) {
13763:             $path =~ s{^/}{};
13764:             if ($path =~ m{^([^/]+)/$}) {
13765:                 $topdir = $1;
13766:             }
13767:             if ($path =~ m{^([^/]+)/}) {
13768:                 $toplevel{$1} = $path;
13769:             } else {
13770:                 $toplevel{$path} = $path;
13771:             }
13772:         }
13773:     }
13774:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13775:         my @camtasia6 = ("$topdir/","$topdir/index.html",
13776:                         "$topdir/media/",
13777:                         "$topdir/media/$topdir.mp4",
13778:                         "$topdir/media/FirstFrame.png",
13779:                         "$topdir/media/player.swf",
13780:                         "$topdir/media/swfobject.js",
13781:                         "$topdir/media/expressInstall.swf");
13782:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13783:                          "$topdir/$topdir.mp4",
13784:                          "$topdir/$topdir\_config.xml",
13785:                          "$topdir/$topdir\_controller.swf",
13786:                          "$topdir/$topdir\_embed.css",
13787:                          "$topdir/$topdir\_First_Frame.png",
13788:                          "$topdir/$topdir\_player.html",
13789:                          "$topdir/$topdir\_Thumbnails.png",
13790:                          "$topdir/playerProductInstall.swf",
13791:                          "$topdir/scripts/",
13792:                          "$topdir/scripts/config_xml.js",
13793:                          "$topdir/scripts/handlebars.js",
13794:                          "$topdir/scripts/jquery-1.7.1.min.js",
13795:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13796:                          "$topdir/scripts/modernizr.js",
13797:                          "$topdir/scripts/player-min.js",
13798:                          "$topdir/scripts/swfobject.js",
13799:                          "$topdir/skins/",
13800:                          "$topdir/skins/configuration_express.xml",
13801:                          "$topdir/skins/express_show/",
13802:                          "$topdir/skins/express_show/player-min.css",
13803:                          "$topdir/skins/express_show/spritesheet.png");
13804:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13805:                          "$topdir/$topdir.mp4",
13806:                          "$topdir/$topdir\_config.xml",
13807:                          "$topdir/$topdir\_controller.swf",
13808:                          "$topdir/$topdir\_embed.css",
13809:                          "$topdir/$topdir\_First_Frame.png",
13810:                          "$topdir/$topdir\_player.html",
13811:                          "$topdir/$topdir\_Thumbnails.png",
13812:                          "$topdir/playerProductInstall.swf",
13813:                          "$topdir/scripts/",
13814:                          "$topdir/scripts/config_xml.js",
13815:                          "$topdir/scripts/techsmith-smart-player.min.js",
13816:                          "$topdir/skins/",
13817:                          "$topdir/skins/configuration_express.xml",
13818:                          "$topdir/skins/express_show/",
13819:                          "$topdir/skins/express_show/spritesheet.min.css",
13820:                          "$topdir/skins/express_show/spritesheet.png",
13821:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
13822:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
13823:         if (@diffs == 0) {
13824:             $is_camtasia = 6;
13825:         } else {
13826:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13827:             if (@diffs == 0) {
13828:                 $is_camtasia = 8;
13829:             } else {
13830:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13831:                 if (@diffs == 0) {
13832:                     $is_camtasia = 8;
13833:                 }
13834:             }
13835:         }
13836:     }
13837:     my $output;
13838:     if ($is_camtasia) {
13839:         $output = <<"ENDCAM";
13840: <script type="text/javascript" language="Javascript">
13841: // <![CDATA[
13842: 
13843: function camtasiaToggle() {
13844:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13845:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13846:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13847:                 document.getElementById('camtasia_titles').style.display='block';
13848:             } else {
13849:                 document.getElementById('camtasia_titles').style.display='none';
13850:             }
13851:         }
13852:     }
13853:     return;
13854: }
13855: 
13856: // ]]>
13857: </script>
13858: <p>$lt{'camt'}</p>
13859: ENDCAM
13860:     } else {
13861:         $output = '<p>'.$lt{'this'};
13862:         if ($info eq '') {
13863:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
13864:         } else {
13865:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13866:                        '<div><pre>'.$info.'</pre></div>';
13867:         }
13868:     }
13869:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13870:     my $duplicates;
13871:     my $num = 0;
13872:     if (ref($dirlist) eq 'ARRAY') {
13873:         foreach my $item (@{$dirlist}) {
13874:             if (ref($item) eq 'ARRAY') {
13875:                 if (exists($toplevel{$item->[0]})) {
13876:                     $duplicates .= 
13877:                         &start_data_table_row().
13878:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13879:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
13880:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
13881:                         'value="1" />'.&mt('Yes').'</label>'.
13882:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13883:                         '<td>'.$item->[0].'</td>';
13884:                     if ($item->[2]) {
13885:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
13886:                     } else {
13887:                         $duplicates .= '<td>'.&mt('File').'</td>';
13888:                     }
13889:                     $duplicates .= '<td>'.$item->[3].'</td>'.
13890:                                    '<td>'.
13891:                                    &Apache::lonlocal::locallocaltime($item->[4]).
13892:                                    '</td>'.
13893:                                    &end_data_table_row();
13894:                     $num ++;
13895:                 }
13896:             }
13897:         }
13898:     }
13899:     my $itemcount;
13900:     if (@paths > 0) {
13901:         $itemcount = scalar(@paths);
13902:     } else {
13903:         $itemcount = 1;
13904:     }
13905:     if ($is_camtasia) {
13906:         $output .= $lt{'auto'}.'<br />'.
13907:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13908:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13909:                    $lt{'yes'}.'</label>&nbsp;<label>'.
13910:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13911:                    $lt{'no'}.'</label></span><br />'.
13912:                    '<div id="camtasia_titles" style="display:block">'.
13913:                    &Apache::lonhtmlcommon::start_pick_box().
13914:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13915:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13916:                    &Apache::lonhtmlcommon::row_closure().
13917:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13918:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13919:                    &Apache::lonhtmlcommon::row_closure(1).
13920:                    &Apache::lonhtmlcommon::end_pick_box().
13921:                    '</div>';
13922:     }
13923:     $output .= 
13924:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13925:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13926:         "\n";
13927:     if ($duplicates ne '') {
13928:         $output .= '<p><span class="LC_warning">'.
13929:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
13930:                    &start_data_table().
13931:                    &start_data_table_header_row().
13932:                    '<th>'.&mt('Overwrite?').'</th>'.
13933:                    '<th>'.&mt('Name').'</th>'.
13934:                    '<th>'.&mt('Type').'</th>'.
13935:                    '<th>'.&mt('Size').'</th>'.
13936:                    '<th>'.&mt('Last modified').'</th>'.
13937:                    &end_data_table_header_row().
13938:                    $duplicates.
13939:                    &end_data_table().
13940:                    '</p>';
13941:     }
13942:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13943:     if (ref($hiddenelements) eq 'HASH') {
13944:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13945:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13946:         }
13947:     }
13948:     $output .= <<"END";
13949: <br />
13950: <input type="submit" name="decompress" value="$lt{'extr'}" />
13951: </form>
13952: $noextract
13953: END
13954:     return $output;
13955: }
13956: 
13957: sub decompression_utility {
13958:     my ($program) = @_;
13959:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
13960:     my $location;
13961:     if (grep(/^\Q$program\E$/,@utilities)) { 
13962:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13963:                          '/usr/sbin/') {
13964:             if (-x $dir.$program) {
13965:                 $location = $dir.$program;
13966:                 last;
13967:             }
13968:         }
13969:     }
13970:     return $location;
13971: }
13972: 
13973: sub list_archive_contents {
13974:     my ($file,$pathsref) = @_;
13975:     my (@cmd,$output);
13976:     my $needsregexp;
13977:     if ($file =~ /\.zip$/) {
13978:         @cmd = (&decompression_utility('unzip'),"-l");
13979:         $needsregexp = 1;
13980:     } elsif (($file =~ m/\.tar\.gz$/) ||
13981:              ($file =~ /\.tgz$/)) {
13982:         @cmd = (&decompression_utility('tar'),"-ztf");
13983:     } elsif ($file =~ /\.tar\.bz2$/) {
13984:         @cmd = (&decompression_utility('tar'),"-jtf");
13985:     } elsif ($file =~ m|\.tar$|) {
13986:         @cmd = (&decompression_utility('tar'),"-tf");
13987:     }
13988:     if (@cmd) {
13989:         undef($!);
13990:         undef($@);
13991:         if (open(my $fh,"-|", @cmd, $file)) {
13992:             while (my $line = <$fh>) {
13993:                 $output .= $line;
13994:                 chomp($line);
13995:                 my $item;
13996:                 if ($needsregexp) {
13997:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
13998:                 } else {
13999:                     $item = $line;
14000:                 }
14001:                 if ($item ne '') {
14002:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
14003:                         push(@{$pathsref},$item);
14004:                     } 
14005:                 }
14006:             }
14007:             close($fh);
14008:         }
14009:     }
14010:     return $output;
14011: }
14012: 
14013: sub decompress_uploaded_file {
14014:     my ($file,$dir) = @_;
14015:     &Apache::lonnet::appenv({'cgi.file' => $file});
14016:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
14017:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
14018:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
14019:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
14020:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
14021:     my $decompressed = $env{'cgi.decompressed'};
14022:     &Apache::lonnet::delenv('cgi.file');
14023:     &Apache::lonnet::delenv('cgi.dir');
14024:     &Apache::lonnet::delenv('cgi.decompressed');
14025:     return ($decompressed,$result);
14026: }
14027: 
14028: sub process_decompression {
14029:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
14030:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
14031:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14032:                &mt('Unexpected file path.').'</p>'."\n";
14033:     }
14034:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
14035:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14036:                &mt('Unexpected course context.').'</p>'."\n";
14037:     }
14038:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
14039:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14040:                &mt('Filename contained unexpected characters.').'</p>'."\n";
14041:     }
14042:     my ($dir,$error,$warning,$output);
14043:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
14044:         $error = &mt('Filename not a supported archive file type.').
14045:                  '<br />'.&mt('Filename should end with one of: [_1].',
14046:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
14047:     } else {
14048:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14049:         if ($docuhome eq 'no_host') {
14050:             $error = &mt('Could not determine home server for course.');
14051:         } else {
14052:             my @ids=&Apache::lonnet::current_machine_ids();
14053:             my $currdir = "$dir_root/$destination";
14054:             if (grep(/^\Q$docuhome\E$/,@ids)) {
14055:                 $dir = &LONCAPA::propath($docudom,$docuname).
14056:                        "$dir_root/$destination";
14057:             } else {
14058:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
14059:                        "$dir_root/$docudom/$docuname/$destination";
14060:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
14061:                     $error = &mt('Archive file not found.');
14062:                 }
14063:             }
14064:             my (@to_overwrite,@to_skip);
14065:             if ($env{'form.archive_overwrite_total'} > 0) {
14066:                 my $total = $env{'form.archive_overwrite_total'};
14067:                 for (my $i=0; $i<$total; $i++) {
14068:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
14069:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
14070:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
14071:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
14072:                     }
14073:                 }
14074:             }
14075:             my $numskip = scalar(@to_skip);
14076:             my $numoverwrite = scalar(@to_overwrite);
14077:             if (($numskip) && (!$numoverwrite)) { 
14078:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
14079:             } elsif ($dir eq '') {
14080:                 $error = &mt('Directory containing archive file unavailable.');
14081:             } elsif (!$error) {
14082:                 my ($decompressed,$display);
14083:                 if (($numskip) || ($numoverwrite)) {
14084:                     my $tempdir = time.'_'.$$.int(rand(10000));
14085:                     mkdir("$dir/$tempdir",0755);
14086:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
14087:                         ($decompressed,$display) = 
14088:                             &decompress_uploaded_file($file,"$dir/$tempdir");
14089:                         foreach my $item (@to_skip) {
14090:                             if (($item ne '') && ($item !~ /\.\./)) {
14091:                                 if (-f "$dir/$tempdir/$item") { 
14092:                                     unlink("$dir/$tempdir/$item");
14093:                                 } elsif (-d "$dir/$tempdir/$item") {
14094:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
14095:                                 }
14096:                             }
14097:                         }
14098:                         foreach my $item (@to_overwrite) {
14099:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
14100:                                 if (($item ne '') && ($item !~ /\.\./)) {
14101:                                     if (-f "$dir/$item") {
14102:                                         unlink("$dir/$item");
14103:                                     } elsif (-d "$dir/$item") {
14104:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
14105:                                     }
14106:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
14107:                                 }
14108:                             }
14109:                         }
14110:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
14111:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
14112:                         }
14113:                     }
14114:                 } else {
14115:                     ($decompressed,$display) = 
14116:                         &decompress_uploaded_file($file,$dir);
14117:                 }
14118:                 if ($decompressed eq 'ok') {
14119:                     $output = '<p class="LC_info">'.
14120:                               &mt('Files extracted successfully from archive.').
14121:                               '</p>'."\n";
14122:                     my ($warning,$result,@contents);
14123:                     my ($newdirlistref,$newlisterror) =
14124:                         &Apache::lonnet::dirlist($currdir,$docudom,
14125:                                                  $docuname,1);
14126:                     my (%is_dir,%changes,@newitems);
14127:                     my $dirptr = 16384;
14128:                     if (ref($newdirlistref) eq 'ARRAY') {
14129:                         foreach my $dir_line (@{$newdirlistref}) {
14130:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14131:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
14132:                                 push(@newitems,$item);
14133:                                 if ($dirptr&$testdir) {
14134:                                     $is_dir{$item} = 1;
14135:                                 }
14136:                                 $changes{$item} = 1;
14137:                             }
14138:                         }
14139:                     }
14140:                     if (keys(%changes) > 0) {
14141:                         foreach my $item (sort(@newitems)) {
14142:                             if ($changes{$item}) {
14143:                                 push(@contents,$item);
14144:                             }
14145:                         }
14146:                     }
14147:                     if (@contents > 0) {
14148:                         my $wantform;
14149:                         unless ($env{'form.autoextract_camtasia'}) {
14150:                             $wantform = 1;
14151:                         }
14152:                         my (%children,%parent,%dirorder,%titles);
14153:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
14154:                                                                 $currdir,\%is_dir,
14155:                                                                 \%children,\%parent,
14156:                                                                 \@contents,\%dirorder,
14157:                                                                 \%titles,$wantform);
14158:                         if ($datatable ne '') {
14159:                             $output .= &archive_options_form('decompressed',$datatable,
14160:                                                              $count,$hiddenelem);
14161:                             my $startcount = 6;
14162:                             $output .= &archive_javascript($startcount,$count,
14163:                                                            \%titles,\%children);
14164:                         }
14165:                         if ($env{'form.autoextract_camtasia'}) {
14166:                             my $version = $env{'form.autoextract_camtasia'};
14167:                             my %displayed;
14168:                             my $total = 1;
14169:                             $env{'form.archive_directory'} = [];
14170:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
14171:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
14172:                                 $path =~ s{/$}{};
14173:                                 my $item;
14174:                                 if ($path ne '') {
14175:                                     $item = "$path/$titles{$i}";
14176:                                 } else {
14177:                                     $item = $titles{$i};
14178:                                 }
14179:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
14180:                                 if ($item eq $contents[0]) {
14181:                                     push(@{$env{'form.archive_directory'}},$i);
14182:                                     $env{'form.archive_'.$i} = 'display';
14183:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
14184:                                     $displayed{'folder'} = $i;
14185:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
14186:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
14187:                                     $env{'form.archive_'.$i} = 'display';
14188:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
14189:                                     $displayed{'web'} = $i;
14190:                                 } else {
14191:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
14192:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
14193:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
14194:                                         push(@{$env{'form.archive_directory'}},$i);
14195:                                     }
14196:                                     $env{'form.archive_'.$i} = 'dependency';
14197:                                 }
14198:                                 $total ++;
14199:                             }
14200:                             for (my $i=1; $i<$total; $i++) {
14201:                                 next if ($i == $displayed{'web'});
14202:                                 next if ($i == $displayed{'folder'});
14203:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
14204:                             }
14205:                             $env{'form.phase'} = 'decompress_cleanup';
14206:                             $env{'form.archivedelete'} = 1;
14207:                             $env{'form.archive_count'} = $total-1;
14208:                             $output .=
14209:                                 &process_extracted_files('coursedocs',$docudom,
14210:                                                          $docuname,$destination,
14211:                                                          $dir_root,$hiddenelem);
14212:                         }
14213:                     } else {
14214:                         $warning = &mt('No new items extracted from archive file.');
14215:                     }
14216:                 } else {
14217:                     $output = $display;
14218:                     $error = &mt('An error occurred during extraction from the archive file.');
14219:                 }
14220:             }
14221:         }
14222:     }
14223:     if ($error) {
14224:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14225:                    $error.'</p>'."\n";
14226:     }
14227:     if ($warning) {
14228:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14229:     }
14230:     return $output;
14231: }
14232: 
14233: sub get_extracted {
14234:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
14235:         $titles,$wantform) = @_;
14236:     my $count = 0;
14237:     my $depth = 0;
14238:     my $datatable;
14239:     my @hierarchy;
14240:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
14241:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
14242:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
14243:     foreach my $item (@{$contents}) {
14244:         $count ++;
14245:         @{$dirorder->{$count}} = @hierarchy;
14246:         $titles->{$count} = $item;
14247:         &archive_hierarchy($depth,$count,$parent,$children);
14248:         if ($wantform) {
14249:             $datatable .= &archive_row($is_dir->{$item},$item,
14250:                                        $currdir,$depth,$count);
14251:         }
14252:         if ($is_dir->{$item}) {
14253:             $depth ++;
14254:             push(@hierarchy,$count);
14255:             $parent->{$depth} = $count;
14256:             $datatable .=
14257:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
14258:                                            \$depth,\$count,\@hierarchy,$dirorder,
14259:                                            $children,$parent,$titles,$wantform);
14260:             $depth --;
14261:             pop(@hierarchy);
14262:         }
14263:     }
14264:     return ($count,$datatable);
14265: }
14266: 
14267: sub recurse_extracted_archive {
14268:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
14269:         $children,$parent,$titles,$wantform) = @_;
14270:     my $result='';
14271:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
14272:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
14273:             (ref($dirorder) eq 'HASH')) {
14274:         return $result;
14275:     }
14276:     my $dirptr = 16384;
14277:     my ($newdirlistref,$newlisterror) =
14278:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
14279:     if (ref($newdirlistref) eq 'ARRAY') {
14280:         foreach my $dir_line (@{$newdirlistref}) {
14281:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14282:             unless ($item =~ /^\.+$/) {
14283:                 $$count ++;
14284:                 @{$dirorder->{$$count}} = @{$hierarchy};
14285:                 $titles->{$$count} = $item;
14286:                 &archive_hierarchy($$depth,$$count,$parent,$children);
14287: 
14288:                 my $is_dir;
14289:                 if ($dirptr&$testdir) {
14290:                     $is_dir = 1;
14291:                 }
14292:                 if ($wantform) {
14293:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
14294:                 }
14295:                 if ($is_dir) {
14296:                     $$depth ++;
14297:                     push(@{$hierarchy},$$count);
14298:                     $parent->{$$depth} = $$count;
14299:                     $result .=
14300:                         &recurse_extracted_archive("$currdir/$item",$docudom,
14301:                                                    $docuname,$depth,$count,
14302:                                                    $hierarchy,$dirorder,$children,
14303:                                                    $parent,$titles,$wantform);
14304:                     $$depth --;
14305:                     pop(@{$hierarchy});
14306:                 }
14307:             }
14308:         }
14309:     }
14310:     return $result;
14311: }
14312: 
14313: sub archive_hierarchy {
14314:     my ($depth,$count,$parent,$children) =@_;
14315:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
14316:         if (exists($parent->{$depth})) {
14317:              $children->{$parent->{$depth}} .= $count.':';
14318:         }
14319:     }
14320:     return;
14321: }
14322: 
14323: sub archive_row {
14324:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
14325:     my ($name) = ($item =~ m{([^/]+)$});
14326:     my %choices = &Apache::lonlocal::texthash (
14327:                                        'display'    => 'Add as file',
14328:                                        'dependency' => 'Include as dependency',
14329:                                        'discard'    => 'Discard',
14330:                                       );
14331:     if ($is_dir) {
14332:         $choices{'display'} = &mt('Add as folder'); 
14333:     }
14334:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
14335:     my $offset = 0;
14336:     foreach my $action ('display','dependency','discard') {
14337:         $offset ++;
14338:         if ($action ne 'display') {
14339:             $offset ++;
14340:         }  
14341:         $output .= '<td><span class="LC_nobreak">'.
14342:                    '<label><input type="radio" name="archive_'.$count.
14343:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
14344:         my $text = $choices{$action};
14345:         if ($is_dir) {
14346:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
14347:             if ($action eq 'display') {
14348:                 $text = &mt('Add as folder');
14349:             }
14350:         } else {
14351:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
14352: 
14353:         }
14354:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
14355:         if ($action eq 'dependency') {
14356:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
14357:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
14358:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
14359:                        '<option value=""></option>'."\n".
14360:                        '</select>'."\n".
14361:                        '</div>';
14362:         } elsif ($action eq 'display') {
14363:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
14364:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
14365:                        '</div>';
14366:         }
14367:         $output .= '</td>';
14368:     }
14369:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
14370:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
14371:     for (my $i=0; $i<$depth; $i++) {
14372:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
14373:     }
14374:     if ($is_dir) {
14375:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
14376:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
14377:     } else {
14378:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
14379:     }
14380:     $output .= '&nbsp;'.$name.'</td>'."\n".
14381:                &end_data_table_row();
14382:     return $output;
14383: }
14384: 
14385: sub archive_options_form {
14386:     my ($form,$display,$count,$hiddenelem) = @_;
14387:     my %lt = &Apache::lonlocal::texthash(
14388:                perm => 'Permanently remove archive file?',
14389:                hows => 'How should each extracted item be incorporated in the course?',
14390:                cont => 'Content actions for all',
14391:                addf => 'Add as folder/file',
14392:                incd => 'Include as dependency for a displayed file',
14393:                disc => 'Discard',
14394:                no   => 'No',
14395:                yes  => 'Yes',
14396:                save => 'Save',
14397:     );
14398:     my $output = <<"END";
14399: <form name="$form" method="post" action="">
14400: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
14401: <label>
14402:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
14403: </label>
14404: &nbsp;
14405: <label>
14406:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
14407: </span>
14408: </p>
14409: <input type="hidden" name="phase" value="decompress_cleanup" />
14410: <br />$lt{'hows'}
14411: <div class="LC_columnSection">
14412:   <fieldset>
14413:     <legend>$lt{'cont'}</legend>
14414:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
14415:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
14416:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
14417:   </fieldset>
14418: </div>
14419: END
14420:     return $output.
14421:            &start_data_table()."\n".
14422:            $display."\n".
14423:            &end_data_table()."\n".
14424:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
14425:            $hiddenelem.
14426:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
14427:            '</form>';
14428: }
14429: 
14430: sub archive_javascript {
14431:     my ($startcount,$numitems,$titles,$children) = @_;
14432:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
14433:     my $maintitle = $env{'form.comment'};
14434:     my $scripttag = <<START;
14435: <script type="text/javascript">
14436: // <![CDATA[
14437: 
14438: function checkAll(form,prefix) {
14439:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
14440:     for (var i=0; i < form.elements.length; i++) {
14441:         var id = form.elements[i].id;
14442:         if ((id != '') && (id != undefined)) {
14443:             if (idstr.test(id)) {
14444:                 if (form.elements[i].type == 'radio') {
14445:                     form.elements[i].checked = true;
14446:                     var nostart = i-$startcount;
14447:                     var offset = nostart%7;
14448:                     var count = (nostart-offset)/7;    
14449:                     dependencyCheck(form,count,offset);
14450:                 }
14451:             }
14452:         }
14453:     }
14454: }
14455: 
14456: function propagateCheck(form,count) {
14457:     if (count > 0) {
14458:         var startelement = $startcount + ((count-1) * 7);
14459:         for (var j=1; j<6; j++) {
14460:             if ((j != 2) && (j != 4)) {
14461:                 var item = startelement + j; 
14462:                 if (form.elements[item].type == 'radio') {
14463:                     if (form.elements[item].checked) {
14464:                         containerCheck(form,count,j);
14465:                         break;
14466:                     }
14467:                 }
14468:             }
14469:         }
14470:     }
14471: }
14472: 
14473: numitems = $numitems
14474: var titles = new Array(numitems);
14475: var parents = new Array(numitems);
14476: for (var i=0; i<numitems; i++) {
14477:     parents[i] = new Array;
14478: }
14479: var maintitle = '$maintitle';
14480: 
14481: START
14482: 
14483:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
14484:         my @contents = split(/:/,$children->{$container});
14485:         for (my $i=0; $i<@contents; $i ++) {
14486:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
14487:         }
14488:     }
14489: 
14490:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
14491:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
14492:     }
14493: 
14494:     $scripttag .= <<END;
14495: 
14496: function containerCheck(form,count,offset) {
14497:     if (count > 0) {
14498:         dependencyCheck(form,count,offset);
14499:         var item = (offset+$startcount)+7*(count-1);
14500:         form.elements[item].checked = true;
14501:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
14502:             if (parents[count].length > 0) {
14503:                 for (var j=0; j<parents[count].length; j++) {
14504:                     containerCheck(form,parents[count][j],offset);
14505:                 }
14506:             }
14507:         }
14508:     }
14509: }
14510: 
14511: function dependencyCheck(form,count,offset) {
14512:     if (count > 0) {
14513:         var chosen = (offset+$startcount)+7*(count-1);
14514:         var depitem = $startcount + ((count-1) * 7) + 4;
14515:         var currtype = form.elements[depitem].type;
14516:         if (form.elements[chosen].value == 'dependency') {
14517:             document.getElementById('arc_depon_'+count).style.display='block'; 
14518:             form.elements[depitem].options.length = 0;
14519:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14520:             for (var i=1; i<=numitems; i++) {
14521:                 if (i == count) {
14522:                     continue;
14523:                 }
14524:                 var startelement = $startcount + (i-1) * 7;
14525:                 for (var j=1; j<6; j++) {
14526:                     if ((j != 2) && (j!= 4)) {
14527:                         var item = startelement + j;
14528:                         if (form.elements[item].type == 'radio') {
14529:                             if (form.elements[item].checked) {
14530:                                 if (form.elements[item].value == 'display') {
14531:                                     var n = form.elements[depitem].options.length;
14532:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
14533:                                 }
14534:                             }
14535:                         }
14536:                     }
14537:                 }
14538:             }
14539:         } else {
14540:             document.getElementById('arc_depon_'+count).style.display='none';
14541:             form.elements[depitem].options.length = 0;
14542:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14543:         }
14544:         titleCheck(form,count,offset);
14545:     }
14546: }
14547: 
14548: function propagateSelect(form,count,offset) {
14549:     if (count > 0) {
14550:         var item = (1+offset+$startcount)+7*(count-1);
14551:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
14552:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14553:             if (parents[count].length > 0) {
14554:                 for (var j=0; j<parents[count].length; j++) {
14555:                     containerSelect(form,parents[count][j],offset,picked);
14556:                 }
14557:             }
14558:         }
14559:     }
14560: }
14561: 
14562: function containerSelect(form,count,offset,picked) {
14563:     if (count > 0) {
14564:         var item = (offset+$startcount)+7*(count-1);
14565:         if (form.elements[item].type == 'radio') {
14566:             if (form.elements[item].value == 'dependency') {
14567:                 if (form.elements[item+1].type == 'select-one') {
14568:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
14569:                         if (form.elements[item+1].options[i].value == picked) {
14570:                             form.elements[item+1].selectedIndex = i;
14571:                             break;
14572:                         }
14573:                     }
14574:                 }
14575:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14576:                     if (parents[count].length > 0) {
14577:                         for (var j=0; j<parents[count].length; j++) {
14578:                             containerSelect(form,parents[count][j],offset,picked);
14579:                         }
14580:                     }
14581:                 }
14582:             }
14583:         }
14584:     }
14585: }
14586: 
14587: function titleCheck(form,count,offset) {
14588:     if (count > 0) {
14589:         var chosen = (offset+$startcount)+7*(count-1);
14590:         var depitem = $startcount + ((count-1) * 7) + 2;
14591:         var currtype = form.elements[depitem].type;
14592:         if (form.elements[chosen].value == 'display') {
14593:             document.getElementById('arc_title_'+count).style.display='block';
14594:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14595:                 document.getElementById('archive_title_'+count).value=maintitle;
14596:             }
14597:         } else {
14598:             document.getElementById('arc_title_'+count).style.display='none';
14599:             if (currtype == 'text') { 
14600:                 document.getElementById('archive_title_'+count).value='';
14601:             }
14602:         }
14603:     }
14604:     return;
14605: }
14606: 
14607: // ]]>
14608: </script>
14609: END
14610:     return $scripttag;
14611: }
14612: 
14613: sub process_extracted_files {
14614:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14615:     my $numitems = $env{'form.archive_count'};
14616:     return if ((!$numitems) || ($numitems =~ /\D/));
14617:     my @ids=&Apache::lonnet::current_machine_ids();
14618:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14619:         %folders,%containers,%mapinner,%prompttofetch);
14620:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14621:     if (grep(/^\Q$docuhome\E$/,@ids)) {
14622:         $prefix = &LONCAPA::propath($docudom,$docuname);
14623:         $pathtocheck = "$dir_root/$destination";
14624:         $dir = $dir_root;
14625:         $ishome = 1;
14626:     } else {
14627:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14628:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14629:         $dir = "$dir_root/$docudom/$docuname";
14630:     }
14631:     my $currdir = "$dir_root/$destination";
14632:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14633:     if ($env{'form.folderpath'}) {
14634:         my @items = split('&',$env{'form.folderpath'});
14635:         $folders{'0'} = $items[-2];
14636:         if ($env{'form.folderpath'} =~ /\:1$/) {
14637:             $containers{'0'}='page';
14638:         } else {  
14639:             $containers{'0'}='sequence';
14640:         }
14641:     }
14642:     my @archdirs = &get_env_multiple('form.archive_directory');
14643:     if ($numitems) {
14644:         for (my $i=1; $i<=$numitems; $i++) {
14645:             my $path = $env{'form.archive_content_'.$i};
14646:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14647:                 my $item = $1;
14648:                 $toplevelitems{$item} = $i;
14649:                 if (grep(/^\Q$i\E$/,@archdirs)) {
14650:                     $is_dir{$item} = 1;
14651:                 }
14652:             }
14653:         }
14654:     }
14655:     my ($output,%children,%parent,%titles,%dirorder,$result);
14656:     if (keys(%toplevelitems) > 0) {
14657:         my @contents = sort(keys(%toplevelitems));
14658:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14659:                                            \%parent,\@contents,\%dirorder,\%titles);
14660:     }
14661:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14662:     if ($numitems) {
14663:         for (my $i=1; $i<=$numitems; $i++) {
14664:             next if ($env{'form.archive_'.$i} eq 'dependency');
14665:             my $path = $env{'form.archive_content_'.$i};
14666:             if ($path =~ /^\Q$pathtocheck\E/) {
14667:                 if ($env{'form.archive_'.$i} eq 'discard') {
14668:                     if ($prefix ne '' && $path ne '') {
14669:                         if (-e $prefix.$path) {
14670:                             if ((@archdirs > 0) && 
14671:                                 (grep(/^\Q$i\E$/,@archdirs))) {
14672:                                 $todeletedir{$prefix.$path} = 1;
14673:                             } else {
14674:                                 $todelete{$prefix.$path} = 1;
14675:                             }
14676:                         }
14677:                     }
14678:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
14679:                     my ($docstitle,$title,$url,$outer);
14680:                     ($title) = ($path =~ m{/([^/]+)$});
14681:                     $docstitle = $env{'form.archive_title_'.$i};
14682:                     if ($docstitle eq '') {
14683:                         $docstitle = $title;
14684:                     }
14685:                     $outer = 0;
14686:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14687:                         if (@{$dirorder{$i}} > 0) {
14688:                             foreach my $item (reverse(@{$dirorder{$i}})) {
14689:                                 if ($env{'form.archive_'.$item} eq 'display') {
14690:                                     $outer = $item;
14691:                                     last;
14692:                                 }
14693:                             }
14694:                         }
14695:                     }
14696:                     my ($errtext,$fatal) = 
14697:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14698:                                                '/'.$folders{$outer}.'.'.
14699:                                                $containers{$outer});
14700:                     next if ($fatal);
14701:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14702:                         if ($context eq 'coursedocs') {
14703:                             $mapinner{$i} = time;
14704:                             $folders{$i} = 'default_'.$mapinner{$i};
14705:                             $containers{$i} = 'sequence';
14706:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14707:                                       $folders{$i}.'.'.$containers{$i};
14708:                             my $newidx = &LONCAPA::map::getresidx();
14709:                             $LONCAPA::map::resources[$newidx]=
14710:                                 $docstitle.':'.$url.':false:normal:res';
14711:                             push(@LONCAPA::map::order,$newidx);
14712:                             my ($outtext,$errtext) =
14713:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14714:                                                         $docuname.'/'.$folders{$outer}.
14715:                                                         '.'.$containers{$outer},1,1);
14716:                             $newseqid{$i} = $newidx;
14717:                             unless ($errtext) {
14718:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
14719:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
14720:                                             '</li>'."\n";
14721:                             }
14722:                         }
14723:                     } else {
14724:                         if ($context eq 'coursedocs') {
14725:                             my $newidx=&LONCAPA::map::getresidx();
14726:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14727:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14728:                                       $title;
14729:                             if (($outer !~ /\D/) &&
14730:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
14731:                                 ($newidx !~ /\D/)) {
14732:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14733:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14734:                                 }
14735:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14736:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14737:                                 }
14738:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14739:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14740:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14741:                                         unless ($ishome) {
14742:                                             my $fetch = "$newdest{$i}/$title";
14743:                                             $fetch =~ s/^\Q$prefix$dir\E//;
14744:                                             $prompttofetch{$fetch} = 1;
14745:                                         }
14746:                                     }
14747:                                 }
14748:                                 $LONCAPA::map::resources[$newidx]=
14749:                                     $docstitle.':'.$url.':false:normal:res';
14750:                                 push(@LONCAPA::map::order, $newidx);
14751:                                 my ($outtext,$errtext)=
14752:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14753:                                                             $docuname.'/'.$folders{$outer}.
14754:                                                             '.'.$containers{$outer},1,1);
14755:                                 unless ($errtext) {
14756:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14757:                                         $result .= '<li>'.&mt('File: [_1] added to course',
14758:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
14759:                                                    '</li>'."\n";
14760:                                     }
14761:                                 }
14762:                             } else {
14763:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14764:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
14765:                             }
14766:                         }
14767:                     }
14768:                 }
14769:             } else {
14770:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14771:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
14772:             }
14773:         }
14774:         for (my $i=1; $i<=$numitems; $i++) {
14775:             next unless ($env{'form.archive_'.$i} eq 'dependency');
14776:             my $path = $env{'form.archive_content_'.$i};
14777:             if ($path =~ /^\Q$pathtocheck\E/) {
14778:                 my ($title) = ($path =~ m{/([^/]+)$});
14779:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14780:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14781:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14782:                         my ($itemidx,$fullpath,$relpath);
14783:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14784:                             my $container = $dirorder{$referrer{$i}}->[-1];
14785:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14786:                                 if ($dirorder{$i}->[$j] eq $container) {
14787:                                     $itemidx = $j;
14788:                                 }
14789:                             }
14790:                         }
14791:                         if ($itemidx eq '') {
14792:                             $itemidx =  0;
14793:                         } 
14794:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14795:                             if ($mapinner{$referrer{$i}}) {
14796:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14797:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14798:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14799:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14800:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14801:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14802:                                             if (!-e $fullpath) {
14803:                                                 mkdir($fullpath,0755);
14804:                                             }
14805:                                         }
14806:                                     } else {
14807:                                         last;
14808:                                     }
14809:                                 }
14810:                             }
14811:                         } elsif ($newdest{$referrer{$i}}) {
14812:                             $fullpath = $newdest{$referrer{$i}};
14813:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14814:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14815:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14816:                                     last;
14817:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14818:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14819:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14820:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14821:                                         if (!-e $fullpath) {
14822:                                             mkdir($fullpath,0755);
14823:                                         }
14824:                                     }
14825:                                 } else {
14826:                                     last;
14827:                                 }
14828:                             }
14829:                         }
14830:                         if ($fullpath ne '') {
14831:                             if (-e "$prefix$path") {
14832:                                 unless (rename("$prefix$path","$fullpath/$title")) {
14833:                                      $warning .= &mt('Failed to rename dependency').'<br />';
14834:                                 }
14835:                             }
14836:                             if (-e "$fullpath/$title") {
14837:                                 my $showpath;
14838:                                 if ($relpath ne '') {
14839:                                     $showpath = "$relpath/$title";
14840:                                 } else {
14841:                                     $showpath = "/$title";
14842:                                 } 
14843:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
14844:                                                       &HTML::Entities::encode($showpath,'<>&"')).
14845:                                            '</li>'."\n";
14846:                                 unless ($ishome) {
14847:                                     my $fetch = "$fullpath/$title";
14848:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
14849:                                     $prompttofetch{$fetch} = 1;
14850:                                 }
14851:                             }
14852:                         }
14853:                     }
14854:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14855:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14856:                                     &HTML::Entities::encode($path,'<>&"'),
14857:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14858:                                 '<br />';
14859:                 }
14860:             } else {
14861:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14862:                                 &HTML::Entities::encode($path)).'<br />';
14863:             }
14864:         }
14865:         if (keys(%todelete)) {
14866:             foreach my $key (keys(%todelete)) {
14867:                 unlink($key);
14868:             }
14869:         }
14870:         if (keys(%todeletedir)) {
14871:             foreach my $key (keys(%todeletedir)) {
14872:                 rmdir($key);
14873:             }
14874:         }
14875:         foreach my $dir (sort(keys(%is_dir))) {
14876:             if (($pathtocheck ne '') && ($dir ne ''))  {
14877:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14878:             }
14879:         }
14880:         if ($result ne '') {
14881:             $output .= '<ul>'."\n".
14882:                        $result."\n".
14883:                        '</ul>';
14884:         }
14885:         unless ($ishome) {
14886:             my $replicationfail;
14887:             foreach my $item (keys(%prompttofetch)) {
14888:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14889:                 unless ($fetchresult eq 'ok') {
14890:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
14891:                 }
14892:             }
14893:             if ($replicationfail) {
14894:                 $output .= '<p class="LC_error">'.
14895:                            &mt('Course home server failed to retrieve:').'<ul>'.
14896:                            $replicationfail.
14897:                            '</ul></p>';
14898:             }
14899:         }
14900:     } else {
14901:         $warning = &mt('No items found in archive.');
14902:     }
14903:     if ($error) {
14904:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14905:                    $error.'</p>'."\n";
14906:     }
14907:     if ($warning) {
14908:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14909:     }
14910:     return $output;
14911: }
14912: 
14913: sub cleanup_empty_dirs {
14914:     my ($path) = @_;
14915:     if (($path ne '') && (-d $path)) {
14916:         if (opendir(my $dirh,$path)) {
14917:             my @dircontents = grep(!/^\./,readdir($dirh));
14918:             my $numitems = 0;
14919:             foreach my $item (@dircontents) {
14920:                 if (-d "$path/$item") {
14921:                     &cleanup_empty_dirs("$path/$item");
14922:                     if (-e "$path/$item") {
14923:                         $numitems ++;
14924:                     }
14925:                 } else {
14926:                     $numitems ++;
14927:                 }
14928:             }
14929:             if ($numitems == 0) {
14930:                 rmdir($path);
14931:             }
14932:             closedir($dirh);
14933:         }
14934:     }
14935:     return;
14936: }
14937: 
14938: =pod
14939: 
14940: =item * &get_folder_hierarchy()
14941: 
14942: Provides hierarchy of names of folders/sub-folders containing the current
14943: item,
14944: 
14945: Inputs: 3
14946:      - $navmap - navmaps object
14947: 
14948:      - $map - url for map (either the trigger itself, or map containing
14949:                            the resource, which is the trigger).
14950: 
14951:      - $showitem - 1 => show title for map itself; 0 => do not show.
14952: 
14953: Outputs: 1 @pathitems - array of folder/subfolder names.
14954: 
14955: =cut
14956: 
14957: sub get_folder_hierarchy {
14958:     my ($navmap,$map,$showitem) = @_;
14959:     my @pathitems;
14960:     if (ref($navmap)) {
14961:         my $mapres = $navmap->getResourceByUrl($map);
14962:         if (ref($mapres)) {
14963:             my $pcslist = $mapres->map_hierarchy();
14964:             if ($pcslist ne '') {
14965:                 my @pcs = split(/,/,$pcslist);
14966:                 foreach my $pc (@pcs) {
14967:                     if ($pc == 1) {
14968:                         push(@pathitems,&mt('Main Content'));
14969:                     } else {
14970:                         my $res = $navmap->getByMapPc($pc);
14971:                         if (ref($res)) {
14972:                             my $title = $res->compTitle();
14973:                             $title =~ s/\W+/_/g;
14974:                             if ($title ne '') {
14975:                                 push(@pathitems,$title);
14976:                             }
14977:                         }
14978:                     }
14979:                 }
14980:             }
14981:             if ($showitem) {
14982:                 if ($mapres->{ID} eq '0.0') {
14983:                     push(@pathitems,&mt('Main Content'));
14984:                 } else {
14985:                     my $maptitle = $mapres->compTitle();
14986:                     $maptitle =~ s/\W+/_/g;
14987:                     if ($maptitle ne '') {
14988:                         push(@pathitems,$maptitle);
14989:                     }
14990:                 }
14991:             }
14992:         }
14993:     }
14994:     return @pathitems;
14995: }
14996: 
14997: =pod
14998: 
14999: =item * &get_turnedin_filepath()
15000: 
15001: Determines path in a user's portfolio file for storage of files uploaded
15002: to a specific essayresponse or dropbox item.
15003: 
15004: Inputs: 3 required + 1 optional.
15005: $symb is symb for resource, $uname and $udom are for current user (required).
15006: $caller is optional (can be "submission", if routine is called when storing
15007: an upoaded file when "Submit Answer" button was pressed).
15008: 
15009: Returns array containing $path and $multiresp. 
15010: $path is path in portfolio.  $multiresp is 1 if this resource contains more
15011: than one file upload item.  Callers of routine should append partid as a 
15012: subdirectory to $path in cases where $multiresp is 1.
15013: 
15014: Called by: homework/essayresponse.pm and homework/structuretags.pm
15015: 
15016: =cut
15017: 
15018: sub get_turnedin_filepath {
15019:     my ($symb,$uname,$udom,$caller) = @_;
15020:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
15021:     my $turnindir;
15022:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
15023:     $turnindir = $userhash{'turnindir'};
15024:     my ($path,$multiresp);
15025:     if ($turnindir eq '') {
15026:         if ($caller eq 'submission') {
15027:             $turnindir = &mt('turned in');
15028:             $turnindir =~ s/\W+/_/g;
15029:             my %newhash = (
15030:                             'turnindir' => $turnindir,
15031:                           );
15032:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
15033:         }
15034:     }
15035:     if ($turnindir ne '') {
15036:         $path = '/'.$turnindir.'/';
15037:         my ($multipart,$turnin,@pathitems);
15038:         my $navmap = Apache::lonnavmaps::navmap->new();
15039:         if (defined($navmap)) {
15040:             my $mapres = $navmap->getResourceByUrl($map);
15041:             if (ref($mapres)) {
15042:                 my $pcslist = $mapres->map_hierarchy();
15043:                 if ($pcslist ne '') {
15044:                     foreach my $pc (split(/,/,$pcslist)) {
15045:                         my $res = $navmap->getByMapPc($pc);
15046:                         if (ref($res)) {
15047:                             my $title = $res->compTitle();
15048:                             $title =~ s/\W+/_/g;
15049:                             if ($title ne '') {
15050:                                 if (($pc > 1) && (length($title) > 12)) {
15051:                                     $title = substr($title,0,12);
15052:                                 }
15053:                                 push(@pathitems,$title);
15054:                             }
15055:                         }
15056:                     }
15057:                 }
15058:                 my $maptitle = $mapres->compTitle();
15059:                 $maptitle =~ s/\W+/_/g;
15060:                 if ($maptitle ne '') {
15061:                     if (length($maptitle) > 12) {
15062:                         $maptitle = substr($maptitle,0,12);
15063:                     }
15064:                     push(@pathitems,$maptitle);
15065:                 }
15066:                 unless ($env{'request.state'} eq 'construct') {
15067:                     my $res = $navmap->getBySymb($symb);
15068:                     if (ref($res)) {
15069:                         my $partlist = $res->parts();
15070:                         my $totaluploads = 0;
15071:                         if (ref($partlist) eq 'ARRAY') {
15072:                             foreach my $part (@{$partlist}) {
15073:                                 my @types = $res->responseType($part);
15074:                                 my @ids = $res->responseIds($part);
15075:                                 for (my $i=0; $i < scalar(@ids); $i++) {
15076:                                     if ($types[$i] eq 'essay') {
15077:                                         my $partid = $part.'_'.$ids[$i];
15078:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
15079:                                             $totaluploads ++;
15080:                                         }
15081:                                     }
15082:                                 }
15083:                             }
15084:                             if ($totaluploads > 1) {
15085:                                 $multiresp = 1;
15086:                             }
15087:                         }
15088:                     }
15089:                 }
15090:             } else {
15091:                 return;
15092:             }
15093:         } else {
15094:             return;
15095:         }
15096:         my $restitle=&Apache::lonnet::gettitle($symb);
15097:         $restitle =~ s/\W+/_/g;
15098:         if ($restitle eq '') {
15099:             $restitle = ($resurl =~ m{/[^/]+$});
15100:             if ($restitle eq '') {
15101:                 $restitle = time;
15102:             }
15103:         }
15104:         if (length($restitle) > 12) {
15105:             $restitle = substr($restitle,0,12);
15106:         }
15107:         push(@pathitems,$restitle);
15108:         $path .= join('/',@pathitems);
15109:     }
15110:     return ($path,$multiresp);
15111: }
15112: 
15113: =pod
15114: 
15115: =back
15116: 
15117: =head1 CSV Upload/Handling functions
15118: 
15119: =over 4
15120: 
15121: =item * &upfile_store($r)
15122: 
15123: Store uploaded file, $r should be the HTTP Request object,
15124: needs $env{'form.upfile'}
15125: returns $datatoken to be put into hidden field
15126: 
15127: =cut
15128: 
15129: sub upfile_store {
15130:     my $r=shift;
15131:     $env{'form.upfile'}=~s/\r/\n/gs;
15132:     $env{'form.upfile'}=~s/\f/\n/gs;
15133:     $env{'form.upfile'}=~s/\n+/\n/gs;
15134:     $env{'form.upfile'}=~s/\n+$//gs;
15135: 
15136:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
15137:                                      '_enroll_'.$env{'request.course.id'}.'_'.
15138:                                      time.'_'.$$);
15139:     return if ($datatoken eq '');
15140: 
15141:     {
15142:         my $datafile = $r->dir_config('lonDaemons').
15143:                            '/tmp/'.$datatoken.'.tmp';
15144:         if ( open(my $fh,'>',$datafile) ) {
15145:             print $fh $env{'form.upfile'};
15146:             close($fh);
15147:         }
15148:     }
15149:     return $datatoken;
15150: }
15151: 
15152: =pod
15153: 
15154: =item * &load_tmp_file($r,$datatoken)
15155: 
15156: Load uploaded file from tmp, $r should be the HTTP Request object,
15157: $datatoken is the name to assign to the temporary file.
15158: sets $env{'form.upfile'} to the contents of the file
15159: 
15160: =cut
15161: 
15162: sub load_tmp_file {
15163:     my ($r,$datatoken) = @_;
15164:     return if ($datatoken eq '');
15165:     my @studentdata=();
15166:     {
15167:         my $studentfile = $r->dir_config('lonDaemons').
15168:                               '/tmp/'.$datatoken.'.tmp';
15169:         if ( open(my $fh,'<',$studentfile) ) {
15170:             @studentdata=<$fh>;
15171:             close($fh);
15172:         }
15173:     }
15174:     $env{'form.upfile'}=join('',@studentdata);
15175: }
15176: 
15177: sub valid_datatoken {
15178:     my ($datatoken) = @_;
15179:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
15180:         return $datatoken;
15181:     }
15182:     return;
15183: }
15184: 
15185: =pod
15186: 
15187: =item * &upfile_record_sep()
15188: 
15189: Separate uploaded file into records
15190: returns array of records,
15191: needs $env{'form.upfile'} and $env{'form.upfiletype'}
15192: 
15193: =cut
15194: 
15195: sub upfile_record_sep {
15196:     if ($env{'form.upfiletype'} eq 'xml') {
15197:     } else {
15198: 	my @records;
15199: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
15200: 	    if ($line=~/^\s*$/) { next; }
15201: 	    push(@records,$line);
15202: 	}
15203: 	return @records;
15204:     }
15205: }
15206: 
15207: =pod
15208: 
15209: =item * &record_sep($record)
15210: 
15211: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
15212: 
15213: =cut
15214: 
15215: sub takeleft {
15216:     my $index=shift;
15217:     return substr('0000'.$index,-4,4);
15218: }
15219: 
15220: sub record_sep {
15221:     my $record=shift;
15222:     my %components=();
15223:     if ($env{'form.upfiletype'} eq 'xml') {
15224:     } elsif ($env{'form.upfiletype'} eq 'space') {
15225:         my $i=0;
15226:         foreach my $field (split(/\s+/,$record)) {
15227:             $field=~s/^(\"|\')//;
15228:             $field=~s/(\"|\')$//;
15229:             $components{&takeleft($i)}=$field;
15230:             $i++;
15231:         }
15232:     } elsif ($env{'form.upfiletype'} eq 'tab') {
15233:         my $i=0;
15234:         foreach my $field (split(/\t/,$record)) {
15235:             $field=~s/^(\"|\')//;
15236:             $field=~s/(\"|\')$//;
15237:             $components{&takeleft($i)}=$field;
15238:             $i++;
15239:         }
15240:     } else {
15241:         my $separator=',';
15242:         if ($env{'form.upfiletype'} eq 'semisv') {
15243:             $separator=';';
15244:         }
15245:         my $i=0;
15246: # the character we are looking for to indicate the end of a quote or a record 
15247:         my $looking_for=$separator;
15248: # do not add the characters to the fields
15249:         my $ignore=0;
15250: # we just encountered a separator (or the beginning of the record)
15251:         my $just_found_separator=1;
15252: # store the field we are working on here
15253:         my $field='';
15254: # work our way through all characters in record
15255:         foreach my $character ($record=~/(.)/g) {
15256:             if ($character eq $looking_for) {
15257:                if ($character ne $separator) {
15258: # Found the end of a quote, again looking for separator
15259:                   $looking_for=$separator;
15260:                   $ignore=1;
15261:                } else {
15262: # Found a separator, store away what we got
15263:                   $components{&takeleft($i)}=$field;
15264: 	          $i++;
15265:                   $just_found_separator=1;
15266:                   $ignore=0;
15267:                   $field='';
15268:                }
15269:                next;
15270:             }
15271: # single or double quotation marks after a separator indicate beginning of a quote
15272: # we are now looking for the end of the quote and need to ignore separators
15273:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
15274:                $looking_for=$character;
15275:                next;
15276:             }
15277: # ignore would be true after we reached the end of a quote
15278:             if ($ignore) { next; }
15279:             if (($just_found_separator) && ($character=~/\s/)) { next; }
15280:             $field.=$character;
15281:             $just_found_separator=0; 
15282:         }
15283: # catch the very last entry, since we never encountered the separator
15284:         $components{&takeleft($i)}=$field;
15285:     }
15286:     return %components;
15287: }
15288: 
15289: ######################################################
15290: ######################################################
15291: 
15292: =pod
15293: 
15294: =item * &upfile_select_html()
15295: 
15296: Return HTML code to select a file from the users machine and specify 
15297: the file type.
15298: 
15299: =cut
15300: 
15301: ######################################################
15302: ######################################################
15303: sub upfile_select_html {
15304:     my %Types = (
15305:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
15306:                  semisv => &mt('Semicolon separated values'),
15307:                  space => &mt('Space separated'),
15308:                  tab   => &mt('Tabulator separated'),
15309: #                 xml   => &mt('HTML/XML'),
15310:                  );
15311:     my $Str = '<input type="file" name="upfile" size="50" />'.
15312:         '<br />'.&mt('Type').': <select name="upfiletype">';
15313:     foreach my $type (sort(keys(%Types))) {
15314:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
15315:     }
15316:     $Str .= "</select>\n";
15317:     return $Str;
15318: }
15319: 
15320: sub get_samples {
15321:     my ($records,$toget) = @_;
15322:     my @samples=({});
15323:     my $got=0;
15324:     foreach my $rec (@$records) {
15325: 	my %temp = &record_sep($rec);
15326: 	if (! grep(/\S/, values(%temp))) { next; }
15327: 	if (%temp) {
15328: 	    $samples[$got]=\%temp;
15329: 	    $got++;
15330: 	    if ($got == $toget) { last; }
15331: 	}
15332:     }
15333:     return \@samples;
15334: }
15335: 
15336: ######################################################
15337: ######################################################
15338: 
15339: =pod
15340: 
15341: =item * &csv_print_samples($r,$records)
15342: 
15343: Prints a table of sample values from each column uploaded $r is an
15344: Apache Request ref, $records is an arrayref from
15345: &Apache::loncommon::upfile_record_sep
15346: 
15347: =cut
15348: 
15349: ######################################################
15350: ######################################################
15351: sub csv_print_samples {
15352:     my ($r,$records) = @_;
15353:     my $samples = &get_samples($records,5);
15354: 
15355:     $r->print(&mt('Samples').'<br />'.&start_data_table().
15356:               &start_data_table_header_row());
15357:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
15358:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
15359:     $r->print(&end_data_table_header_row());
15360:     foreach my $hash (@$samples) {
15361: 	$r->print(&start_data_table_row());
15362: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15363: 	    $r->print('<td>');
15364: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
15365: 	    $r->print('</td>');
15366: 	}
15367: 	$r->print(&end_data_table_row());
15368:     }
15369:     $r->print(&end_data_table().'<br />'."\n");
15370: }
15371: 
15372: ######################################################
15373: ######################################################
15374: 
15375: =pod
15376: 
15377: =item * &csv_print_select_table($r,$records,$d)
15378: 
15379: Prints a table to create associations between values and table columns.
15380: 
15381: $r is an Apache Request ref,
15382: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15383: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
15384: 
15385: =cut
15386: 
15387: ######################################################
15388: ######################################################
15389: sub csv_print_select_table {
15390:     my ($r,$records,$d) = @_;
15391:     my $i=0;
15392:     my $samples = &get_samples($records,1);
15393:     $r->print(&mt('Associate columns with student attributes.')."\n".
15394: 	      &start_data_table().&start_data_table_header_row().
15395:               '<th>'.&mt('Attribute').'</th>'.
15396:               '<th>'.&mt('Column').'</th>'.
15397:               &end_data_table_header_row()."\n");
15398:     foreach my $array_ref (@$d) {
15399: 	my ($value,$display,$defaultcol)=@{ $array_ref };
15400: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
15401: 
15402: 	$r->print('<td><select name="f'.$i.'"'.
15403: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15404: 	$r->print('<option value="none"></option>');
15405: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15406: 	    $r->print('<option value="'.$sample.'"'.
15407:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
15408:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
15409: 	}
15410: 	$r->print('</select></td>'.&end_data_table_row()."\n");
15411: 	$i++;
15412:     }
15413:     $r->print(&end_data_table());
15414:     $i--;
15415:     return $i;
15416: }
15417: 
15418: ######################################################
15419: ######################################################
15420: 
15421: =pod
15422: 
15423: =item * &csv_samples_select_table($r,$records,$d)
15424: 
15425: Prints a table of sample values from the upload and can make associate samples to internal names.
15426: 
15427: $r is an Apache Request ref,
15428: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15429: $d is an array of 2 element arrays (internal name, displayed name)
15430: 
15431: =cut
15432: 
15433: ######################################################
15434: ######################################################
15435: sub csv_samples_select_table {
15436:     my ($r,$records,$d) = @_;
15437:     my $i=0;
15438:     #
15439:     my $max_samples = 5;
15440:     my $samples = &get_samples($records,$max_samples);
15441:     $r->print(&start_data_table().
15442:               &start_data_table_header_row().'<th>'.
15443:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
15444:               &end_data_table_header_row());
15445: 
15446:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
15447: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
15448: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15449: 	foreach my $option (@$d) {
15450: 	    my ($value,$display,$defaultcol)=@{ $option };
15451: 	    $r->print('<option value="'.$value.'"'.
15452:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
15453:                       $display.'</option>');
15454: 	}
15455: 	$r->print('</select></td><td>');
15456: 	foreach my $line (0..($max_samples-1)) {
15457: 	    if (defined($samples->[$line]{$key})) { 
15458: 		$r->print($samples->[$line]{$key}."<br />\n"); 
15459: 	    }
15460: 	}
15461: 	$r->print('</td>'.&end_data_table_row());
15462: 	$i++;
15463:     }
15464:     $r->print(&end_data_table());
15465:     $i--;
15466:     return($i);
15467: }
15468: 
15469: ######################################################
15470: ######################################################
15471: 
15472: =pod
15473: 
15474: =item * &clean_excel_name($name)
15475: 
15476: Returns a replacement for $name which does not contain any illegal characters.
15477: 
15478: =cut
15479: 
15480: ######################################################
15481: ######################################################
15482: sub clean_excel_name {
15483:     my ($name) = @_;
15484:     $name =~ s/[:\*\?\/\\]//g;
15485:     if (length($name) > 31) {
15486:         $name = substr($name,0,31);
15487:     }
15488:     return $name;
15489: }
15490: 
15491: =pod
15492: 
15493: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
15494: 
15495: Returns either 1 or undef
15496: 
15497: 1 if the part is to be hidden, undef if it is to be shown
15498: 
15499: Arguments are:
15500: 
15501: $id the id of the part to be checked
15502: $symb, optional the symb of the resource to check
15503: $udom, optional the domain of the user to check for
15504: $uname, optional the username of the user to check for
15505: 
15506: =cut
15507: 
15508: sub check_if_partid_hidden {
15509:     my ($id,$symb,$udom,$uname) = @_;
15510:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
15511: 					 $symb,$udom,$uname);
15512:     my $truth=1;
15513:     #if the string starts with !, then the list is the list to show not hide
15514:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
15515:     my @hiddenlist=split(/,/,$hiddenparts);
15516:     foreach my $checkid (@hiddenlist) {
15517: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
15518:     }
15519:     return !$truth;
15520: }
15521: 
15522: 
15523: ############################################################
15524: ############################################################
15525: 
15526: =pod
15527: 
15528: =back 
15529: 
15530: =head1 cgi-bin script and graphing routines
15531: 
15532: =over 4
15533: 
15534: =item * &get_cgi_id()
15535: 
15536: Inputs: none
15537: 
15538: Returns an id which can be used to pass environment variables
15539: to various cgi-bin scripts.  These environment variables will
15540: be removed from the users environment after a given time by
15541: the routine &Apache::lonnet::transfer_profile_to_env.
15542: 
15543: =cut
15544: 
15545: ############################################################
15546: ############################################################
15547: my $uniq=0;
15548: sub get_cgi_id {
15549:     $uniq=($uniq+1)%100000;
15550:     return (time.'_'.$$.'_'.$uniq);
15551: }
15552: 
15553: ############################################################
15554: ############################################################
15555: 
15556: =pod
15557: 
15558: =item * &DrawBarGraph()
15559: 
15560: Facilitates the plotting of data in a (stacked) bar graph.
15561: Puts plot definition data into the users environment in order for 
15562: graph.png to plot it.  Returns an <img> tag for the plot.
15563: The bars on the plot are labeled '1','2',...,'n'.
15564: 
15565: Inputs:
15566: 
15567: =over 4
15568: 
15569: =item $Title: string, the title of the plot
15570: 
15571: =item $xlabel: string, text describing the X-axis of the plot
15572: 
15573: =item $ylabel: string, text describing the Y-axis of the plot
15574: 
15575: =item $Max: scalar, the maximum Y value to use in the plot
15576: If $Max is < any data point, the graph will not be rendered.
15577: 
15578: =item $colors: array ref holding the colors to be used for the data sets when
15579: they are plotted.  If undefined, default values will be used.
15580: 
15581: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15582: 
15583: =item @Values: An array of array references.  Each array reference holds data
15584: to be plotted in a stacked bar chart.
15585: 
15586: =item If the final element of @Values is a hash reference the key/value
15587: pairs will be added to the graph definition.
15588: 
15589: =back
15590: 
15591: Returns:
15592: 
15593: An <img> tag which references graph.png and the appropriate identifying
15594: information for the plot.
15595: 
15596: =cut
15597: 
15598: ############################################################
15599: ############################################################
15600: sub DrawBarGraph {
15601:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15602:     #
15603:     if (! defined($colors)) {
15604:         $colors = ['#33ff00', 
15605:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15606:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15607:                   ]; 
15608:     }
15609:     my $extra_settings = {};
15610:     if (ref($Values[-1]) eq 'HASH') {
15611:         $extra_settings = pop(@Values);
15612:     }
15613:     #
15614:     my $identifier = &get_cgi_id();
15615:     my $id = 'cgi.'.$identifier;        
15616:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
15617:         return '';
15618:     }
15619:     #
15620:     my @Labels;
15621:     if (defined($labels)) {
15622:         @Labels = @$labels;
15623:     } else {
15624:         for (my $i=0;$i<@{$Values[0]};$i++) {
15625:             push(@Labels,$i+1);
15626:         }
15627:     }
15628:     #
15629:     my $NumBars = scalar(@{$Values[0]});
15630:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15631:     my %ValuesHash;
15632:     my $NumSets=1;
15633:     foreach my $array (@Values) {
15634:         next if (! ref($array));
15635:         $ValuesHash{$id.'.data.'.$NumSets++} = 
15636:             join(',',@$array);
15637:     }
15638:     #
15639:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15640:     if ($NumBars < 3) {
15641:         $width = 120+$NumBars*32;
15642:         $xskip = 1;
15643:         $bar_width = 30;
15644:     } elsif ($NumBars < 5) {
15645:         $width = 120+$NumBars*20;
15646:         $xskip = 1;
15647:         $bar_width = 20;
15648:     } elsif ($NumBars < 10) {
15649:         $width = 120+$NumBars*15;
15650:         $xskip = 1;
15651:         $bar_width = 15;
15652:     } elsif ($NumBars <= 25) {
15653:         $width = 120+$NumBars*11;
15654:         $xskip = 5;
15655:         $bar_width = 8;
15656:     } elsif ($NumBars <= 50) {
15657:         $width = 120+$NumBars*8;
15658:         $xskip = 5;
15659:         $bar_width = 4;
15660:     } else {
15661:         $width = 120+$NumBars*8;
15662:         $xskip = 5;
15663:         $bar_width = 4;
15664:     }
15665:     #
15666:     $Max = 1 if ($Max < 1);
15667:     if ( int($Max) < $Max ) {
15668:         $Max++;
15669:         $Max = int($Max);
15670:     }
15671:     $Title  = '' if (! defined($Title));
15672:     $xlabel = '' if (! defined($xlabel));
15673:     $ylabel = '' if (! defined($ylabel));
15674:     $ValuesHash{$id.'.title'}    = &escape($Title);
15675:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
15676:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
15677:     $ValuesHash{$id.'.y_max_value'} = $Max;
15678:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
15679:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
15680:     $ValuesHash{$id.'.PlotType'} = 'bar';
15681:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15682:     $ValuesHash{$id.'.height'}   = $height;
15683:     $ValuesHash{$id.'.width'}    = $width;
15684:     $ValuesHash{$id.'.xskip'}    = $xskip;
15685:     $ValuesHash{$id.'.bar_width'} = $bar_width;
15686:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
15687:     #
15688:     # Deal with other parameters
15689:     while (my ($key,$value) = each(%$extra_settings)) {
15690:         $ValuesHash{$id.'.'.$key} = $value;
15691:     }
15692:     #
15693:     &Apache::lonnet::appenv(\%ValuesHash);
15694:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15695: }
15696: 
15697: ############################################################
15698: ############################################################
15699: 
15700: =pod
15701: 
15702: =item * &DrawXYGraph()
15703: 
15704: Facilitates the plotting of data in an XY graph.
15705: Puts plot definition data into the users environment in order for 
15706: graph.png to plot it.  Returns an <img> tag for the plot.
15707: 
15708: Inputs:
15709: 
15710: =over 4
15711: 
15712: =item $Title: string, the title of the plot
15713: 
15714: =item $xlabel: string, text describing the X-axis of the plot
15715: 
15716: =item $ylabel: string, text describing the Y-axis of the plot
15717: 
15718: =item $Max: scalar, the maximum Y value to use in the plot
15719: If $Max is < any data point, the graph will not be rendered.
15720: 
15721: =item $colors: Array ref containing the hex color codes for the data to be 
15722: plotted in.  If undefined, default values will be used.
15723: 
15724: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15725: 
15726: =item $Ydata: Array ref containing Array refs.  
15727: Each of the contained arrays will be plotted as a separate curve.
15728: 
15729: =item %Values: hash indicating or overriding any default values which are 
15730: passed to graph.png.  
15731: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15732: 
15733: =back
15734: 
15735: Returns:
15736: 
15737: An <img> tag which references graph.png and the appropriate identifying
15738: information for the plot.
15739: 
15740: =cut
15741: 
15742: ############################################################
15743: ############################################################
15744: sub DrawXYGraph {
15745:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15746:     #
15747:     # Create the identifier for the graph
15748:     my $identifier = &get_cgi_id();
15749:     my $id = 'cgi.'.$identifier;
15750:     #
15751:     $Title  = '' if (! defined($Title));
15752:     $xlabel = '' if (! defined($xlabel));
15753:     $ylabel = '' if (! defined($ylabel));
15754:     my %ValuesHash = 
15755:         (
15756:          $id.'.title'  => &escape($Title),
15757:          $id.'.xlabel' => &escape($xlabel),
15758:          $id.'.ylabel' => &escape($ylabel),
15759:          $id.'.y_max_value'=> $Max,
15760:          $id.'.labels'     => join(',',@$Xlabels),
15761:          $id.'.PlotType'   => 'XY',
15762:          );
15763:     #
15764:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15765:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15766:     }
15767:     #
15768:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15769:         return '';
15770:     }
15771:     my $NumSets=1;
15772:     foreach my $array (@{$Ydata}){
15773:         next if (! ref($array));
15774:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15775:     }
15776:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15777:     #
15778:     # Deal with other parameters
15779:     while (my ($key,$value) = each(%Values)) {
15780:         $ValuesHash{$id.'.'.$key} = $value;
15781:     }
15782:     #
15783:     &Apache::lonnet::appenv(\%ValuesHash);
15784:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15785: }
15786: 
15787: ############################################################
15788: ############################################################
15789: 
15790: =pod
15791: 
15792: =item * &DrawXYYGraph()
15793: 
15794: Facilitates the plotting of data in an XY graph with two Y axes.
15795: Puts plot definition data into the users environment in order for 
15796: graph.png to plot it.  Returns an <img> tag for the plot.
15797: 
15798: Inputs:
15799: 
15800: =over 4
15801: 
15802: =item $Title: string, the title of the plot
15803: 
15804: =item $xlabel: string, text describing the X-axis of the plot
15805: 
15806: =item $ylabel: string, text describing the Y-axis of the plot
15807: 
15808: =item $colors: Array ref containing the hex color codes for the data to be 
15809: plotted in.  If undefined, default values will be used.
15810: 
15811: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15812: 
15813: =item $Ydata1: The first data set
15814: 
15815: =item $Min1: The minimum value of the left Y-axis
15816: 
15817: =item $Max1: The maximum value of the left Y-axis
15818: 
15819: =item $Ydata2: The second data set
15820: 
15821: =item $Min2: The minimum value of the right Y-axis
15822: 
15823: =item $Max2: The maximum value of the left Y-axis
15824: 
15825: =item %Values: hash indicating or overriding any default values which are 
15826: passed to graph.png.  
15827: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15828: 
15829: =back
15830: 
15831: Returns:
15832: 
15833: An <img> tag which references graph.png and the appropriate identifying
15834: information for the plot.
15835: 
15836: =cut
15837: 
15838: ############################################################
15839: ############################################################
15840: sub DrawXYYGraph {
15841:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15842:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
15843:     #
15844:     # Create the identifier for the graph
15845:     my $identifier = &get_cgi_id();
15846:     my $id = 'cgi.'.$identifier;
15847:     #
15848:     $Title  = '' if (! defined($Title));
15849:     $xlabel = '' if (! defined($xlabel));
15850:     $ylabel = '' if (! defined($ylabel));
15851:     my %ValuesHash = 
15852:         (
15853:          $id.'.title'  => &escape($Title),
15854:          $id.'.xlabel' => &escape($xlabel),
15855:          $id.'.ylabel' => &escape($ylabel),
15856:          $id.'.labels' => join(',',@$Xlabels),
15857:          $id.'.PlotType' => 'XY',
15858:          $id.'.NumSets' => 2,
15859:          $id.'.two_axes' => 1,
15860:          $id.'.y1_max_value' => $Max1,
15861:          $id.'.y1_min_value' => $Min1,
15862:          $id.'.y2_max_value' => $Max2,
15863:          $id.'.y2_min_value' => $Min2,
15864:          );
15865:     #
15866:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15867:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15868:     }
15869:     #
15870:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15871:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15872:         return '';
15873:     }
15874:     my $NumSets=1;
15875:     foreach my $array ($Ydata1,$Ydata2){
15876:         next if (! ref($array));
15877:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15878:     }
15879:     #
15880:     # Deal with other parameters
15881:     while (my ($key,$value) = each(%Values)) {
15882:         $ValuesHash{$id.'.'.$key} = $value;
15883:     }
15884:     #
15885:     &Apache::lonnet::appenv(\%ValuesHash);
15886:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15887: }
15888: 
15889: ############################################################
15890: ############################################################
15891: 
15892: =pod
15893: 
15894: =back 
15895: 
15896: =head1 Statistics helper routines?  
15897: 
15898: Bad place for them but what the hell.
15899: 
15900: =over 4
15901: 
15902: =item * &chartlink()
15903: 
15904: Returns a link to the chart for a specific student.  
15905: 
15906: Inputs:
15907: 
15908: =over 4
15909: 
15910: =item $linktext: The text of the link
15911: 
15912: =item $sname: The students username
15913: 
15914: =item $sdomain: The students domain
15915: 
15916: =back
15917: 
15918: =back
15919: 
15920: =cut
15921: 
15922: ############################################################
15923: ############################################################
15924: sub chartlink {
15925:     my ($linktext, $sname, $sdomain) = @_;
15926:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15927:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
15928:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
15929:        '">'.$linktext.'</a>';
15930: }
15931: 
15932: #######################################################
15933: #######################################################
15934: 
15935: =pod
15936: 
15937: =head1 Course Environment Routines
15938: 
15939: =over 4
15940: 
15941: =item * &restore_course_settings()
15942: 
15943: =item * &store_course_settings()
15944: 
15945: Restores/Store indicated form parameters from the course environment.
15946: Will not overwrite existing values of the form parameters.
15947: 
15948: Inputs: 
15949: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15950: 
15951: a hash ref describing the data to be stored.  For example:
15952:    
15953: %Save_Parameters = ('Status' => 'scalar',
15954:     'chartoutputmode' => 'scalar',
15955:     'chartoutputdata' => 'scalar',
15956:     'Section' => 'array',
15957:     'Group' => 'array',
15958:     'StudentData' => 'array',
15959:     'Maps' => 'array');
15960: 
15961: Returns: both routines return nothing
15962: 
15963: =back
15964: 
15965: =cut
15966: 
15967: #######################################################
15968: #######################################################
15969: sub store_course_settings {
15970:     return &store_settings($env{'request.course.id'},@_);
15971: }
15972: 
15973: sub store_settings {
15974:     # save to the environment
15975:     # appenv the same items, just to be safe
15976:     my $udom  = $env{'user.domain'};
15977:     my $uname = $env{'user.name'};
15978:     my ($context,$prefix,$Settings) = @_;
15979:     my %SaveHash;
15980:     my %AppHash;
15981:     while (my ($setting,$type) = each(%$Settings)) {
15982:         my $basename = join('.','internal',$context,$prefix,$setting);
15983:         my $envname = 'environment.'.$basename;
15984:         if (exists($env{'form.'.$setting})) {
15985:             # Save this value away
15986:             if ($type eq 'scalar' &&
15987:                 (! exists($env{$envname}) || 
15988:                  $env{$envname} ne $env{'form.'.$setting})) {
15989:                 $SaveHash{$basename} = $env{'form.'.$setting};
15990:                 $AppHash{$envname}   = $env{'form.'.$setting};
15991:             } elsif ($type eq 'array') {
15992:                 my $stored_form;
15993:                 if (ref($env{'form.'.$setting})) {
15994:                     $stored_form = join(',',
15995:                                         map {
15996:                                             &escape($_);
15997:                                         } sort(@{$env{'form.'.$setting}}));
15998:                 } else {
15999:                     $stored_form = 
16000:                         &escape($env{'form.'.$setting});
16001:                 }
16002:                 # Determine if the array contents are the same.
16003:                 if ($stored_form ne $env{$envname}) {
16004:                     $SaveHash{$basename} = $stored_form;
16005:                     $AppHash{$envname}   = $stored_form;
16006:                 }
16007:             }
16008:         }
16009:     }
16010:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
16011:                                           $udom,$uname);
16012:     if ($put_result !~ /^(ok|delayed)/) {
16013:         &Apache::lonnet::logthis('unable to save form parameters, '.
16014:                                  'got error:'.$put_result);
16015:     }
16016:     # Make sure these settings stick around in this session, too
16017:     &Apache::lonnet::appenv(\%AppHash);
16018:     return;
16019: }
16020: 
16021: sub restore_course_settings {
16022:     return &restore_settings($env{'request.course.id'},@_);
16023: }
16024: 
16025: sub restore_settings {
16026:     my ($context,$prefix,$Settings) = @_;
16027:     while (my ($setting,$type) = each(%$Settings)) {
16028:         next if (exists($env{'form.'.$setting}));
16029:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
16030:             '.'.$setting;
16031:         if (exists($env{$envname})) {
16032:             if ($type eq 'scalar') {
16033:                 $env{'form.'.$setting} = $env{$envname};
16034:             } elsif ($type eq 'array') {
16035:                 $env{'form.'.$setting} = [ 
16036:                                            map { 
16037:                                                &unescape($_); 
16038:                                            } split(',',$env{$envname})
16039:                                            ];
16040:             }
16041:         }
16042:     }
16043: }
16044: 
16045: #######################################################
16046: #######################################################
16047: 
16048: =pod
16049: 
16050: =head1 Domain E-mail Routines  
16051: 
16052: =over 4
16053: 
16054: =item * &build_recipient_list()
16055: 
16056: Build recipient lists for following types of e-mail:
16057: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
16058: (d) Help requests, (e) Course requests needing approval, (f) loncapa
16059: module change checking, student/employee ID conflict checks, as
16060: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
16061: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
16062: 
16063: Inputs:
16064: defmail (scalar - email address of default recipient), 
16065: mailing type (scalar: errormail, packagesmail, helpdeskmail,
16066: requestsmail, updatesmail, or idconflictsmail).
16067: 
16068: defdom (domain for which to retrieve configuration settings),
16069: 
16070: origmail (scalar - email address of recipient from loncapa.conf, 
16071: i.e., predates configuration by DC via domainprefs.pm
16072: 
16073: $requname username of requester (if mailing type is helpdeskmail)
16074: 
16075: $requdom domain of requester (if mailing type is helpdeskmail)
16076: 
16077: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
16078: 
16079: 
16080: Returns: comma separated list of addresses to which to send e-mail.
16081: 
16082: =back
16083: 
16084: =cut
16085: 
16086: ############################################################
16087: ############################################################
16088: sub build_recipient_list {
16089:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
16090:     my @recipients;
16091:     my ($otheremails,$lastresort,$allbcc,$addtext);
16092:     my %domconfig =
16093:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
16094:     if (ref($domconfig{'contacts'}) eq 'HASH') {
16095:         if (exists($domconfig{'contacts'}{$mailing})) {
16096:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
16097:                 my @contacts = ('adminemail','supportemail');
16098:                 foreach my $item (@contacts) {
16099:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
16100:                         my $addr = $domconfig{'contacts'}{$item}; 
16101:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
16102:                             push(@recipients,$addr);
16103:                         }
16104:                     }
16105:                 }
16106:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
16107:                 if ($mailing eq 'helpdeskmail') {
16108:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
16109:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
16110:                         my @ok_bccs;
16111:                         foreach my $bcc (@bccs) {
16112:                             $bcc =~ s/^\s+//g;
16113:                             $bcc =~ s/\s+$//g;
16114:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16115:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16116:                                     push(@ok_bccs,$bcc);
16117:                                 }
16118:                             }
16119:                         }
16120:                         if (@ok_bccs > 0) {
16121:                             $allbcc = join(', ',@ok_bccs);
16122:                         }
16123:                     }
16124:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
16125:                 }
16126:             }
16127:         } elsif ($origmail ne '') {
16128:             $lastresort = $origmail;
16129:         }
16130:         if ($mailing eq 'helpdeskmail') {
16131:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
16132:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
16133:                 my ($inststatus,$inststatus_checked);
16134:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
16135:                     ($env{'user.domain'} ne 'public')) {
16136:                     $inststatus_checked = 1;
16137:                     $inststatus = $env{'environment.inststatus'};
16138:                 }
16139:                 unless ($inststatus_checked) {
16140:                     if (($requname ne '') && ($requdom ne '')) {
16141:                         if (($requname =~ /^$match_username$/) &&
16142:                             ($requdom =~ /^$match_domain$/) &&
16143:                             (&Apache::lonnet::domain($requdom))) {
16144:                             my $requhome = &Apache::lonnet::homeserver($requname,
16145:                                                                       $requdom);
16146:                             unless ($requhome eq 'no_host') {
16147:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
16148:                                 $inststatus = $userenv{'inststatus'};
16149:                                 $inststatus_checked = 1;
16150:                             }
16151:                         }
16152:                     }
16153:                 }
16154:                 unless ($inststatus_checked) {
16155:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
16156:                         my %srch = (srchby     => 'email',
16157:                                     srchdomain => $defdom,
16158:                                     srchterm   => $reqemail,
16159:                                     srchtype   => 'exact');
16160:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
16161:                         foreach my $uname (keys(%srch_results)) {
16162:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
16163:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
16164:                                 $inststatus_checked = 1;
16165:                                 last;
16166:                             }
16167:                         }
16168:                         unless ($inststatus_checked) {
16169:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
16170:                             if ($dirsrchres eq 'ok') {
16171:                                 foreach my $uname (keys(%srch_results)) {
16172:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
16173:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
16174:                                         $inststatus_checked = 1;
16175:                                         last;
16176:                                     }
16177:                                 }
16178:                             }
16179:                         }
16180:                     }
16181:                 }
16182:                 if ($inststatus ne '') {
16183:                     foreach my $status (split(/\:/,$inststatus)) {
16184:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
16185:                             my @contacts = ('adminemail','supportemail');
16186:                             foreach my $item (@contacts) {
16187:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
16188:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
16189:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
16190:                                         push(@recipients,$addr);
16191:                                     }
16192:                                 }
16193:                             }
16194:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
16195:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
16196:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
16197:                                 my @ok_bccs;
16198:                                 foreach my $bcc (@bccs) {
16199:                                     $bcc =~ s/^\s+//g;
16200:                                     $bcc =~ s/\s+$//g;
16201:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16202:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16203:                                             push(@ok_bccs,$bcc);
16204:                                         }
16205:                                     }
16206:                                 }
16207:                                 if (@ok_bccs > 0) {
16208:                                     $allbcc = join(', ',@ok_bccs);
16209:                                 }
16210:                             }
16211:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
16212:                             last;
16213:                         }
16214:                     }
16215:                 }
16216:             }
16217:         }
16218:     } elsif ($origmail ne '') {
16219:         $lastresort = $origmail;
16220:     }
16221:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
16222:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
16223:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
16224:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
16225:             my %what = (
16226:                           perlvar => 1,
16227:                        );
16228:             my $primary = &Apache::lonnet::domain($defdom,'primary');
16229:             if ($primary) {
16230:                 my $gotaddr;
16231:                 my ($result,$returnhash) =
16232:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
16233:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
16234:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
16235:                         $lastresort = $returnhash->{'lonSupportEMail'};
16236:                         $gotaddr = 1;
16237:                     }
16238:                 }
16239:                 unless ($gotaddr) {
16240:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
16241:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
16242:                     unless ($uintdom eq $intdom) {
16243:                         my %domconfig =
16244:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
16245:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
16246:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
16247:                                 my @contacts = ('adminemail','supportemail');
16248:                                 foreach my $item (@contacts) {
16249:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
16250:                                         my $addr = $domconfig{'contacts'}{$item};
16251:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
16252:                                             push(@recipients,$addr);
16253:                                         }
16254:                                     }
16255:                                 }
16256:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
16257:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
16258:                                 }
16259:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
16260:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
16261:                                     my @ok_bccs;
16262:                                     foreach my $bcc (@bccs) {
16263:                                         $bcc =~ s/^\s+//g;
16264:                                         $bcc =~ s/\s+$//g;
16265:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16266:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16267:                                                 push(@ok_bccs,$bcc);
16268:                                             }
16269:                                         }
16270:                                     }
16271:                                     if (@ok_bccs > 0) {
16272:                                         $allbcc = join(', ',@ok_bccs);
16273:                                     }
16274:                                 }
16275:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
16276:                             }
16277:                         }
16278:                     }
16279:                 }
16280:             }
16281:         }
16282:     }
16283:     if (defined($defmail)) {
16284:         if ($defmail ne '') {
16285:             push(@recipients,$defmail);
16286:         }
16287:     }
16288:     if ($otheremails) {
16289:         my @others;
16290:         if ($otheremails =~ /,/) {
16291:             @others = split(/,/,$otheremails);
16292:         } else {
16293:             push(@others,$otheremails);
16294:         }
16295:         foreach my $addr (@others) {
16296:             if (!grep(/^\Q$addr\E$/,@recipients)) {
16297:                 push(@recipients,$addr);
16298:             }
16299:         }
16300:     }
16301:     if ($mailing eq 'helpdeskmail') {
16302:         if ((!@recipients) && ($lastresort ne '')) {
16303:             push(@recipients,$lastresort);
16304:         }
16305:     } elsif ($lastresort ne '') {
16306:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
16307:             push(@recipients,$lastresort);
16308:         }
16309:     }
16310:     my $recipientlist = join(',',@recipients);
16311:     if (wantarray) {
16312:         return ($recipientlist,$allbcc,$addtext);
16313:     } else {
16314:         return $recipientlist;
16315:     }
16316: }
16317: 
16318: ############################################################
16319: ############################################################
16320: 
16321: =pod
16322: 
16323: =over 4
16324: 
16325: =item * &mime_email()
16326: 
16327: Sends an email with a possible attachment
16328: 
16329: Inputs:
16330: 
16331: =over 4
16332: 
16333: from -              Sender's email address
16334: 
16335: replyto -           Reply-To email address
16336: 
16337: to -                Email address of recipient
16338: 
16339: subject -           Subject of email
16340: 
16341: body -              Body of email
16342: 
16343: cc_string -         Carbon copy email address
16344: 
16345: bcc -               Blind carbon copy email address
16346: 
16347: attachment_path -   Path of file to be attached
16348: 
16349: file_name -         Name of file to be attached
16350: 
16351: attachment_text -   The body of an attachment of type "TEXT"
16352: 
16353: =back
16354: 
16355: =back
16356: 
16357: =cut
16358: 
16359: ############################################################
16360: ############################################################
16361: 
16362: sub mime_email {
16363:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
16364:         $file_name,$attachment_text) = @_;
16365:  
16366:     my $msg = MIME::Lite->new(
16367:              From    => $from,
16368:              To      => $to,
16369:              Subject => $subject,
16370:              Type    =>'TEXT',
16371:              Data    => $body,
16372:              );
16373:     if ($replyto ne '') {
16374:         $msg->add("Reply-To" => $replyto);
16375:     }
16376:     if ($cc_string ne '') {
16377:         $msg->add("Cc" => $cc_string);
16378:     }
16379:     if ($bcc ne '') {
16380:         $msg->add("Bcc" => $bcc);
16381:     }
16382:     $msg->attr("content-type"         => "text/plain");
16383:     $msg->attr("content-type.charset" => "UTF-8");
16384:     # Attach file if given
16385:     if ($attachment_path) {
16386:         unless ($file_name) {
16387:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
16388:         }
16389:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
16390:         $msg->attach(Type     => $type,
16391:                      Path     => $attachment_path,
16392:                      Filename => $file_name
16393:                      );
16394:     # Otherwise attach text if given
16395:     } elsif ($attachment_text) {
16396:         $msg->attach(Type => 'TEXT',
16397:                      Data => $attachment_text);
16398:     }
16399:     # Send it
16400:     $msg->send('sendmail');
16401: }
16402: 
16403: ############################################################
16404: ############################################################
16405: 
16406: =pod
16407: 
16408: =head1 Course Catalog Routines
16409: 
16410: =over 4
16411: 
16412: =item * &gather_categories()
16413: 
16414: Converts category definitions - keys of categories hash stored in  
16415: coursecategories in configuration.db on the primary library server in a 
16416: domain - to an array.  Also generates javascript and idx hash used to 
16417: generate Domain Coordinator interface for editing Course Categories.
16418: 
16419: Inputs:
16420: 
16421: categories (reference to hash of category definitions).
16422: 
16423: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16424:       categories and subcategories).
16425: 
16426: idx (reference to hash of counters used in Domain Coordinator interface for 
16427:       editing Course Categories).
16428: 
16429: jsarray (reference to array of categories used to create Javascript arrays for
16430:          Domain Coordinator interface for editing Course Categories).
16431: 
16432: Returns: nothing
16433: 
16434: Side effects: populates cats, idx and jsarray. 
16435: 
16436: =cut
16437: 
16438: sub gather_categories {
16439:     my ($categories,$cats,$idx,$jsarray) = @_;
16440:     my %counters;
16441:     my $num = 0;
16442:     foreach my $item (keys(%{$categories})) {
16443:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16444:         if ($container eq '' && $depth == 0) {
16445:             $cats->[$depth][$categories->{$item}] = $cat;
16446:         } else {
16447:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
16448:         }
16449:         my ($escitem,$tail) = split(/:/,$item,2);
16450:         if ($counters{$tail} eq '') {
16451:             $counters{$tail} = $num;
16452:             $num ++;
16453:         }
16454:         if (ref($idx) eq 'HASH') {
16455:             $idx->{$item} = $counters{$tail};
16456:         }
16457:         if (ref($jsarray) eq 'ARRAY') {
16458:             push(@{$jsarray->[$counters{$tail}]},$item);
16459:         }
16460:     }
16461:     return;
16462: }
16463: 
16464: =pod
16465: 
16466: =item * &extract_categories()
16467: 
16468: Used to generate breadcrumb trails for course categories.
16469: 
16470: Inputs:
16471: 
16472: categories (reference to hash of category definitions).
16473: 
16474: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16475:       categories and subcategories).
16476: 
16477: trails (reference to array of breacrumb trails for each category).
16478: 
16479: allitems (reference to hash - key is category key 
16480:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16481: 
16482: idx (reference to hash of counters used in Domain Coordinator interface for
16483:       editing Course Categories).
16484: 
16485: jsarray (reference to array of categories used to create Javascript arrays for
16486:          Domain Coordinator interface for editing Course Categories).
16487: 
16488: subcats (reference to hash of arrays containing all subcategories within each 
16489:          category, -recursive)
16490: 
16491: maxd (reference to hash used to hold max depth for all top-level categories).
16492: 
16493: Returns: nothing
16494: 
16495: Side effects: populates trails and allitems hash references.
16496: 
16497: =cut
16498: 
16499: sub extract_categories {
16500:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
16501:     if (ref($categories) eq 'HASH') {
16502:         &gather_categories($categories,$cats,$idx,$jsarray);
16503:         if (ref($cats->[0]) eq 'ARRAY') {
16504:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
16505:                 my $name = $cats->[0][$i];
16506:                 my $item = &escape($name).'::0';
16507:                 my $trailstr;
16508:                 if ($name eq 'instcode') {
16509:                     $trailstr = &mt('Official courses (with institutional codes)');
16510:                 } elsif ($name eq 'communities') {
16511:                     $trailstr = &mt('Communities');
16512:                 } elsif ($name eq 'placement') {
16513:                     $trailstr = &mt('Placement Tests');
16514:                 } else {
16515:                     $trailstr = $name;
16516:                 }
16517:                 if ($allitems->{$item} eq '') {
16518:                     push(@{$trails},$trailstr);
16519:                     $allitems->{$item} = scalar(@{$trails})-1;
16520:                 }
16521:                 my @parents = ($name);
16522:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
16523:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
16524:                         my $category = $cats->[1]{$name}[$j];
16525:                         if (ref($subcats) eq 'HASH') {
16526:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
16527:                         }
16528:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
16529:                     }
16530:                 } else {
16531:                     if (ref($subcats) eq 'HASH') {
16532:                         $subcats->{$item} = [];
16533:                     }
16534:                     if (ref($maxd) eq 'HASH') {
16535:                         $maxd->{$name} = 1;
16536:                     }
16537:                 }
16538:             }
16539:         }
16540:     }
16541:     return;
16542: }
16543: 
16544: =pod
16545: 
16546: =item * &recurse_categories()
16547: 
16548: Recursively used to generate breadcrumb trails for course categories.
16549: 
16550: Inputs:
16551: 
16552: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16553:       categories and subcategories).
16554: 
16555: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16556: 
16557: category (current course category, for which breadcrumb trail is being generated).
16558: 
16559: trails (reference to array of breadcrumb trails for each category).
16560: 
16561: allitems (reference to hash - key is category key
16562:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16563: 
16564: parents (array containing containers directories for current category, 
16565:          back to top level). 
16566: 
16567: Returns: nothing
16568: 
16569: Side effects: populates trails and allitems hash references
16570: 
16571: =cut
16572: 
16573: sub recurse_categories {
16574:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16575:     my $shallower = $depth - 1;
16576:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16577:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16578:             my $name = $cats->[$depth]{$category}[$k];
16579:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16580:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
16581:             if ($allitems->{$item} eq '') {
16582:                 push(@{$trails},$trailstr);
16583:                 $allitems->{$item} = scalar(@{$trails})-1;
16584:             }
16585:             my $deeper = $depth+1;
16586:             push(@{$parents},$category);
16587:             if (ref($subcats) eq 'HASH') {
16588:                 my $subcat = &escape($name).':'.$category.':'.$depth;
16589:                 for (my $j=@{$parents}; $j>=0; $j--) {
16590:                     my $higher;
16591:                     if ($j > 0) {
16592:                         $higher = &escape($parents->[$j]).':'.
16593:                                   &escape($parents->[$j-1]).':'.$j;
16594:                     } else {
16595:                         $higher = &escape($parents->[$j]).'::'.$j;
16596:                     }
16597:                     push(@{$subcats->{$higher}},$subcat);
16598:                 }
16599:             }
16600:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16601:                                 $subcats,$maxd);
16602:             pop(@{$parents});
16603:         }
16604:     } else {
16605:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16606:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
16607:         if ($allitems->{$item} eq '') {
16608:             push(@{$trails},$trailstr);
16609:             $allitems->{$item} = scalar(@{$trails})-1;
16610:         }
16611:         if (ref($maxd) eq 'HASH') {
16612:             if ($depth > $maxd->{$parents->[0]}) {
16613:                 $maxd->{$parents->[0]} = $depth;
16614:             }
16615:         }
16616:     }
16617:     return;
16618: }
16619: 
16620: =pod
16621: 
16622: =item * &assign_categories_table()
16623: 
16624: Create a datatable for display of hierarchical categories in a domain,
16625: with checkboxes to allow a course to be categorized. 
16626: 
16627: Inputs:
16628: 
16629: cathash - reference to hash of categories defined for the domain (from
16630:           configuration.db)
16631: 
16632: currcat - scalar with an & separated list of categories assigned to a course. 
16633: 
16634: type    - scalar contains course type (Course or Community).
16635: 
16636: disabled - scalar (optional) contains disabled="disabled" if input elements are
16637:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16638: 
16639: Returns: $output (markup to be displayed) 
16640: 
16641: =cut
16642: 
16643: sub assign_categories_table {
16644:     my ($cathash,$currcat,$type,$disabled) = @_;
16645:     my $output;
16646:     if (ref($cathash) eq 'HASH') {
16647:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16648:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16649:         $maxdepth = scalar(@cats);
16650:         if (@cats > 0) {
16651:             my $itemcount = 0;
16652:             if (ref($cats[0]) eq 'ARRAY') {
16653:                 my @currcategories;
16654:                 if ($currcat ne '') {
16655:                     @currcategories = split('&',$currcat);
16656:                 }
16657:                 my $table;
16658:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
16659:                     my $parent = $cats[0][$i];
16660:                     next if ($parent eq 'instcode');
16661:                     if ($type eq 'Community') {
16662:                         next unless ($parent eq 'communities');
16663:                     } elsif ($type eq 'Placement') {
16664:                         next unless ($parent eq 'placement');
16665:                     } else {
16666:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
16667:                     }
16668:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16669:                     my $item = &escape($parent).'::0';
16670:                     my $checked = '';
16671:                     if (@currcategories > 0) {
16672:                         if (grep(/^\Q$item\E$/,@currcategories)) {
16673:                             $checked = ' checked="checked"';
16674:                         }
16675:                     }
16676:                     my $parent_title = $parent;
16677:                     if ($parent eq 'communities') {
16678:                         $parent_title = &mt('Communities');
16679:                     } elsif ($parent eq 'placement') {
16680:                         $parent_title = &mt('Placement Tests');
16681:                     }
16682:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16683:                               '<input type="checkbox" name="usecategory" value="'.
16684:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16685:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16686:                     my $depth = 1;
16687:                     push(@path,$parent);
16688:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16689:                     pop(@path);
16690:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16691:                     $itemcount ++;
16692:                 }
16693:                 if ($itemcount) {
16694:                     $output = &Apache::loncommon::start_data_table().
16695:                               $table.
16696:                               &Apache::loncommon::end_data_table();
16697:                 }
16698:             }
16699:         }
16700:     }
16701:     return $output;
16702: }
16703: 
16704: =pod
16705: 
16706: =item * &assign_category_rows()
16707: 
16708: Create a datatable row for display of nested categories in a domain,
16709: with checkboxes to allow a course to be categorized,called recursively.
16710: 
16711: Inputs:
16712: 
16713: itemcount - track row number for alternating colors
16714: 
16715: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16716:       categories and subcategories.
16717: 
16718: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16719: 
16720: parent - parent of current category item
16721: 
16722: path - Array containing all categories back up through the hierarchy from the
16723:        current category to the top level.
16724: 
16725: currcategories - reference to array of current categories assigned to the course
16726: 
16727: disabled - scalar (optional) contains disabled="disabled" if input elements are
16728:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16729: 
16730: Returns: $output (markup to be displayed).
16731: 
16732: =cut
16733: 
16734: sub assign_category_rows {
16735:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16736:     my ($text,$name,$item,$chgstr);
16737:     if (ref($cats) eq 'ARRAY') {
16738:         my $maxdepth = scalar(@{$cats});
16739:         if (ref($cats->[$depth]) eq 'HASH') {
16740:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16741:                 my $numchildren = @{$cats->[$depth]{$parent}};
16742:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16743:                 $text .= '<td><table class="LC_data_table">';
16744:                 for (my $j=0; $j<$numchildren; $j++) {
16745:                     $name = $cats->[$depth]{$parent}[$j];
16746:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
16747:                     my $deeper = $depth+1;
16748:                     my $checked = '';
16749:                     if (ref($currcategories) eq 'ARRAY') {
16750:                         if (@{$currcategories} > 0) {
16751:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
16752:                                 $checked = ' checked="checked"';
16753:                             }
16754:                         }
16755:                     }
16756:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
16757:                              '<input type="checkbox" name="usecategory" value="'.
16758:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16759:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
16760:                              '</td><td>';
16761:                     if (ref($path) eq 'ARRAY') {
16762:                         push(@{$path},$name);
16763:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16764:                         pop(@{$path});
16765:                     }
16766:                     $text .= '</td></tr>';
16767:                 }
16768:                 $text .= '</table></td>';
16769:             }
16770:         }
16771:     }
16772:     return $text;
16773: }
16774: 
16775: =pod
16776: 
16777: =back
16778: 
16779: =cut
16780: 
16781: ############################################################
16782: ############################################################
16783: 
16784: 
16785: sub commit_customrole {
16786:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
16787:     my $result = &Apache::lonnet::assigncustomrole(
16788:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
16789:                      $context,$othdomby,$requester);
16790:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16791:                          ($start?', '.&mt('starting').' '.localtime($start):'').
16792:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
16793:     if (wantarray) {
16794:         return ($output,$result);
16795:     } else {
16796:         return $output;
16797:     }
16798: }
16799: 
16800: sub commit_standardrole {
16801:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
16802:         $othdomby,$requester) = @_;
16803:     my ($output,$logmsg,$linefeed,$result);
16804:     if ($context eq 'auto') {
16805:         $linefeed = "\n";
16806:     } else {
16807:         $linefeed = "<br />\n";
16808:     }  
16809:     if ($three eq 'st') {
16810:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16811:                                       $one,$two,$sec,$context,$credits,$othdomby,
16812:                                       $requester);
16813:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
16814:             ($result eq 'unknown_course') || ($result eq 'refused')) {
16815:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
16816:         } else {
16817:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16818:                ($start?', '.&mt('starting').' '.localtime($start):'').
16819:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16820:             if ($context eq 'auto') {
16821:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16822:             } else {
16823:                $output .= '<b>'.$result.'</b>'.$linefeed.
16824:                &mt('Add to classlist').': <b>ok</b>';
16825:             }
16826:             $output .= $linefeed;
16827:         }
16828:     } else {
16829:         $output = &mt('Assigning').' '.$three.' in '.$url.
16830:                ($start?', '.&mt('starting').' '.localtime($start):'').
16831:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16832:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
16833:                                               '','',$context,$othdomby,$requester);
16834:         if ($context eq 'auto') {
16835:             $output .= $result.$linefeed;
16836:         } else {
16837:             $output .= '<b>'.$result.'</b>'.$linefeed;
16838:         }
16839:     }
16840:     if (wantarray) {
16841:         return ($output,$result);
16842:     } else {
16843:         return $output;
16844:     }
16845: }
16846: 
16847: sub commit_studentrole {
16848:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16849:         $credits,$othdomby,$requester) = @_;
16850:     my ($result,$linefeed,$oldsecurl,$newsecurl);
16851:     if ($context eq 'auto') {
16852:         $linefeed = "\n";
16853:     } else {
16854:         $linefeed = '<br />'."\n";
16855:     }
16856:     if (defined($one) && defined($two)) {
16857:         my $cid=$one.'_'.$two;
16858:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16859:         my $secchange = 0;
16860:         my $expire_role_result;
16861:         my $modify_section_result;
16862:         if ($oldsec ne '-1') { 
16863:             if ($oldsec ne $sec) {
16864:                 $secchange = 1;
16865:                 my $now = time;
16866:                 my $uurl='/'.$cid;
16867:                 $uurl=~s/\_/\//g;
16868:                 if ($oldsec) {
16869:                     $uurl.='/'.$oldsec;
16870:                 }
16871:                 $oldsecurl = $uurl;
16872:                 $expire_role_result = 
16873:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
16874:                                                 '','','',$context,$othdomby,$requester);
16875:                 if ($env{'request.course.sec'} ne '') {
16876:                     if ($expire_role_result eq 'refused') {
16877:                         my @roles = ('st');
16878:                         my @statuses = ('previous');
16879:                         my @roledoms = ($one);
16880:                         my $withsec = 1;
16881:                         my %roleshash = 
16882:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16883:                                               \@statuses,\@roles,\@roledoms,$withsec);
16884:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16885:                             my ($oldstart,$oldend) = 
16886:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16887:                             if ($oldend > 0 && $oldend <= $now) {
16888:                                 $expire_role_result = 'ok';
16889:                             }
16890:                         }
16891:                     }
16892:                 }
16893:                 $result = $expire_role_result;
16894:             }
16895:         }
16896:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16897:             $modify_section_result = 
16898:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16899:                                                            undef,undef,undef,$sec,
16900:                                                            $end,$start,'','',$cid,
16901:                                                            '',$context,$credits,'',
16902:                                                            $othdomby,$requester);
16903:             if ($modify_section_result =~ /^ok/) {
16904:                 if ($secchange == 1) {
16905:                     if ($sec eq '') {
16906:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16907:                     } else {
16908:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16909:                     }
16910:                 } elsif ($oldsec eq '-1') {
16911:                     if ($sec eq '') {
16912:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16913:                     } else {
16914:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16915:                     }
16916:                 } else {
16917:                     if ($sec eq '') {
16918:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16919:                     } else {
16920:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16921:                     }
16922:                 }
16923:             } else {
16924:                 if ($secchange) { 
16925:                     $$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;
16926:                 } else {
16927:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16928:                 }
16929:             }
16930:             $result = $modify_section_result;
16931:         } elsif ($secchange == 1) {
16932:             if ($oldsec eq '') {
16933:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16934:             } else {
16935:                 $$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;
16936:             }
16937:             if ($expire_role_result eq 'refused') {
16938:                 my $newsecurl = '/'.$cid;
16939:                 $newsecurl =~ s/\_/\//g;
16940:                 if ($sec ne '') {
16941:                     $newsecurl.='/'.$sec;
16942:                 }
16943:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16944:                     if ($sec eq '') {
16945:                         $$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;
16946:                     } else {
16947:                         $$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;
16948:                     }
16949:                 }
16950:             }
16951:         }
16952:     } else {
16953:         $$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;
16954:         $result = "error: incomplete course id\n";
16955:     }
16956:     return $result;
16957: }
16958: 
16959: sub show_role_extent {
16960:     my ($scope,$context,$role) = @_;
16961:     $scope =~ s{^/}{};
16962:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16963:     push(@courseroles,'co');
16964:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16965:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16966:         $scope =~ s{/}{_};
16967:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16968:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16969:         my ($audom,$auname) = split(/\//,$scope);
16970:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16971:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
16972:     } else {
16973:         $scope =~ s{/$}{};
16974:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16975:                    &Apache::lonnet::domain($scope,'description').'</span>');
16976:     }
16977: }
16978: 
16979: ############################################################
16980: ############################################################
16981: 
16982: sub check_clone {
16983:     my ($args,$linefeed) = @_;
16984:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16985:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16986:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16987:     my $clonetitle;
16988:     my @clonemsg;
16989:     my $can_clone = 0;
16990:     my $lctype = lc($args->{'crstype'});
16991:     if ($lctype ne 'community') {
16992:         $lctype = 'course';
16993:     }
16994:     if ($clonehome eq 'no_host') {
16995:         if ($args->{'crstype'} eq 'Community') {
16996:             push(@clonemsg,({
16997:                               mt => 'No new community created.',
16998:                               args => [],
16999:                             },
17000:                             {
17001:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
17002:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
17003:                             }));
17004:         } else {
17005:             push(@clonemsg,({
17006:                               mt => 'No new course created.',
17007:                               args => [],
17008:                             },
17009:                             {
17010:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
17011:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
17012:                             }));
17013:         }
17014:     } else {
17015: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
17016:         $clonetitle = $clonedesc{'description'};
17017:         if ($args->{'crstype'} eq 'Community') {
17018:             if ($clonedesc{'type'} ne 'Community') {
17019:                 push(@clonemsg,({
17020:                                   mt => 'No new community created.',
17021:                                   args => [],
17022:                                 },
17023:                                 {
17024:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
17025:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
17026:                                 }));
17027:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
17028:             }
17029:         }
17030: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
17031:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
17032: 	    $can_clone = 1;
17033: 	} else {
17034: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
17035: 						 $args->{'clonedomain'},$args->{'clonecourse'});
17036:             if ($clonehash{'cloners'} eq '') {
17037:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
17038:                 if ($domdefs{'canclone'}) {
17039:                     unless ($domdefs{'canclone'} eq 'none') {
17040:                         if ($domdefs{'canclone'} eq 'domain') {
17041:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
17042:                                 $can_clone = 1;
17043:                             }
17044:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
17045:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
17046:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
17047:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
17048:                                 $can_clone = 1;
17049:                             }
17050:                         }
17051:                     }
17052:                 }
17053:             } else {
17054: 	        my @cloners = split(/,/,$clonehash{'cloners'});
17055:                 if (grep(/^\*$/,@cloners)) {
17056:                     $can_clone = 1;
17057:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
17058:                     $can_clone = 1;
17059:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
17060:                     $can_clone = 1;
17061:                 }
17062:                 unless ($can_clone) {
17063:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
17064:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
17065:                         my (%gotdomdefaults,%gotcodedefaults);
17066:                         foreach my $cloner (@cloners) {
17067:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
17068:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
17069:                                 my (%codedefaults,@code_order);
17070:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
17071:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
17072:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
17073:                                     }
17074:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
17075:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
17076:                                     }
17077:                                 } else {
17078:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
17079:                                                                             \%codedefaults,
17080:                                                                             \@code_order);
17081:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
17082:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
17083:                                 }
17084:                                 if (@code_order > 0) {
17085:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
17086:                                                                                 $cloner,$clonehash{'internal.coursecode'},
17087:                                                                                 $args->{'crscode'})) {
17088:                                         $can_clone = 1;
17089:                                         last;
17090:                                     }
17091:                                 }
17092:                             }
17093:                         }
17094:                     }
17095:                 }
17096:             }
17097:             unless ($can_clone) {
17098:                 my $ccrole = 'cc';
17099:                 if ($args->{'crstype'} eq 'Community') {
17100:                     $ccrole = 'co';
17101:                 }
17102: 	        my %roleshash =
17103: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
17104: 					          $args->{'ccdomain'},
17105:                                                   'userroles',['active'],[$ccrole],
17106: 					          [$args->{'clonedomain'}]);
17107: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
17108:                     $can_clone = 1;
17109:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
17110:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
17111:                     $can_clone = 1;
17112:                 }
17113:             }
17114:             unless ($can_clone) {
17115:                 if ($args->{'crstype'} eq 'Community') {
17116:                     push(@clonemsg,({
17117:                                       mt => 'No new community created.',
17118:                                       args => [],
17119:                                     },
17120:                                     {
17121:                                       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]).',
17122:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
17123:                                     }));
17124:                 } else {
17125:                     push(@clonemsg,({
17126:                                       mt => 'No new course created.',
17127:                                       args => [],
17128:                                     },
17129:                                     {
17130:                                       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]).',
17131:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
17132:                                     }));
17133:                 }
17134: 	    }
17135:         }
17136:     }
17137:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
17138: }
17139: 
17140: sub construct_course {
17141:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
17142:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
17143:     my ($outcome,$msgref,$clonemsgref);
17144:     my $linefeed =  '<br />'."\n";
17145:     if ($context eq 'auto') {
17146:         $linefeed = "\n";
17147:     }
17148: 
17149: #
17150: # Are we cloning?
17151: #
17152:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
17153:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
17154: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
17155:         if (!$can_clone) {
17156: 	    return (0,$outcome,$clonemsgref);
17157: 	}
17158:     }
17159: 
17160: #
17161: # Open course
17162: #
17163:     my $showncrstype;
17164:     if ($args->{'crstype'} eq 'Placement') {
17165:         $showncrstype = 'placement test'; 
17166:     } else {  
17167:         $showncrstype = lc($args->{'crstype'});
17168:     }
17169:     my %cenv=();
17170:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
17171:                                              $args->{'cdescr'},
17172:                                              $args->{'curl'},
17173:                                              $args->{'course_home'},
17174:                                              $args->{'nonstandard'},
17175:                                              $args->{'crscode'},
17176:                                              $args->{'ccuname'}.':'.
17177:                                              $args->{'ccdomain'},
17178:                                              $args->{'crstype'},
17179:                                              $cnum,$context,$category,
17180:                                              $callercontext);
17181: 
17182:     # Note: The testing routines depend on this being output; see 
17183:     # Utils::Course. This needs to at least be output as a comment
17184:     # if anyone ever decides to not show this, and Utils::Course::new
17185:     # will need to be suitably modified.
17186:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
17187:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
17188:     } else {
17189:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
17190:     }
17191:     if ($$courseid =~ /^error:/) {
17192:         return (0,$outcome,$clonemsgref);
17193:     }
17194: 
17195: #
17196: # Check if created correctly
17197: #
17198:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
17199:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
17200:     if ($crsuhome eq 'no_host') {
17201:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
17202:             $outcome .= &mt_user($user_lh,
17203:                             'Course creation failed, unrecognized course home server.');
17204:         } else {
17205:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
17206:         }
17207:         $outcome .= $linefeed;
17208:         return (0,$outcome,$clonemsgref);
17209:     }
17210:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
17211: 
17212: #
17213: # Do the cloning
17214: #   
17215:     my @clonemsg;
17216:     if ($can_clone && $cloneid) {
17217:         push(@clonemsg,
17218:                       {
17219:                           mt => 'Created [_1] by cloning from [_2]',
17220:                           args => [$showncrstype,$clonetitle],
17221:                       });
17222: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
17223: # Copy all files
17224:         my @info =
17225: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
17226: 	                                             $args->{'dateshift'},$args->{'crscode'},
17227:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
17228:                                                      $args->{'tinyurls'});
17229:         if (@info) {
17230:             push(@clonemsg,@info);
17231:         }
17232: # Restore URL
17233: 	$cenv{'url'}=$oldcenv{'url'};
17234: # Restore title
17235: 	$cenv{'description'}=$oldcenv{'description'};
17236: # Restore creation date, creator and creation context.
17237:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
17238:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
17239:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
17240: # Mark as cloned
17241: 	$cenv{'clonedfrom'}=$cloneid;
17242: # Need to clone grading mode
17243:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
17244:         $cenv{'grading'}=$newenv{'grading'};
17245: # Do not clone these environment entries
17246:         &Apache::lonnet::del('environment',
17247:                   ['default_enrollment_start_date',
17248:                    'default_enrollment_end_date',
17249:                    'question.email',
17250:                    'policy.email',
17251:                    'comment.email',
17252:                    'pch.users.denied',
17253:                    'plc.users.denied',
17254:                    'hidefromcat',
17255:                    'checkforpriv',
17256:                    'categories'],
17257:                    $$crsudom,$$crsunum);
17258:         if ($args->{'textbook'}) {
17259:             $cenv{'internal.textbook'} = $args->{'textbook'};
17260:         }
17261:     }
17262: 
17263: #
17264: # Set environment (will override cloned, if existing)
17265: #
17266:     my @sections = ();
17267:     my @xlists = ();
17268:     if ($args->{'crstype'}) {
17269:         $cenv{'type'}=$args->{'crstype'};
17270:     }
17271:     if ($args->{'lti'}) {
17272:         $cenv{'internal.lti'}=$args->{'lti'};
17273:     }
17274:     if ($args->{'crsid'}) {
17275:         $cenv{'courseid'}=$args->{'crsid'};
17276:     }
17277:     if ($args->{'crscode'}) {
17278:         $cenv{'internal.coursecode'}=$args->{'crscode'};
17279:     }
17280:     if ($args->{'crsquota'} ne '') {
17281:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
17282:     } else {
17283:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
17284:     }
17285:     if ($args->{'ccuname'}) {
17286:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
17287:                                         ':'.$args->{'ccdomain'};
17288:     } else {
17289:         $cenv{'internal.courseowner'} = $args->{'curruser'};
17290:     }
17291:     if ($args->{'defaultcredits'}) {
17292:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
17293:     }
17294:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
17295:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
17296:     if ($args->{'crssections'}) {
17297:         $cenv{'internal.sectionnums'} = '';
17298:         if ($args->{'crssections'} =~ m/,/) {
17299:             @sections = split/,/,$args->{'crssections'};
17300:         } else {
17301:             $sections[0] = $args->{'crssections'};
17302:         }
17303:         if (@sections > 0) {
17304:             foreach my $item (@sections) {
17305:                 my ($sec,$gp) = split/:/,$item;
17306:                 my $class = $args->{'crscode'}.$sec;
17307:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
17308:                 $cenv{'internal.sectionnums'} .= $item.',';
17309:                 if ($addcheck eq 'ok') {
17310:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17311:                         push(@oklcsecs,$gp);
17312:                     }
17313:                 } else {
17314:                     push(@badclasses,$class);
17315:                 }
17316:             }
17317:             $cenv{'internal.sectionnums'} =~ s/,$//;
17318:         }
17319:     }
17320: # do not hide course coordinator from staff listing, 
17321: # even if privileged
17322:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17323: # add course coordinator's domain to domains to check for privileged users
17324: # if different to course domain
17325:     if ($$crsudom ne $args->{'ccdomain'}) {
17326:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
17327:     }
17328: # add crosslistings
17329:     if ($args->{'crsxlist'}) {
17330:         $cenv{'internal.crosslistings'}='';
17331:         if ($args->{'crsxlist'} =~ m/,/) {
17332:             @xlists = split/,/,$args->{'crsxlist'};
17333:         } else {
17334:             $xlists[0] = $args->{'crsxlist'};
17335:         }
17336:         if (@xlists > 0) {
17337:             foreach my $item (@xlists) {
17338:                 my ($xl,$gp) = split/:/,$item;
17339:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
17340:                 $cenv{'internal.crosslistings'} .= $item.',';
17341:                 if ($addcheck eq 'ok') {
17342:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17343:                         push(@oklcsecs,$gp);
17344:                     }
17345:                 } else {
17346:                     push(@badclasses,$xl);
17347:                 }
17348:             }
17349:             $cenv{'internal.crosslistings'} =~ s/,$//;
17350:         }
17351:     }
17352:     if ($args->{'autoadds'}) {
17353:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
17354:     }
17355:     if ($args->{'autodrops'}) {
17356:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
17357:     }
17358: # check for notification of enrollment changes
17359:     my @notified = ();
17360:     if ($args->{'notify_owner'}) {
17361:         if ($args->{'ccuname'} ne '') {
17362:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
17363:         }
17364:     }
17365:     if ($args->{'notify_dc'}) {
17366:         if ($uname ne '') { 
17367:             push(@notified,$uname.':'.$udom);
17368:         }
17369:     }
17370:     if (@notified > 0) {
17371:         my $notifylist;
17372:         if (@notified > 1) {
17373:             $notifylist = join(',',@notified);
17374:         } else {
17375:             $notifylist = $notified[0];
17376:         }
17377:         $cenv{'internal.notifylist'} = $notifylist;
17378:     }
17379:     if (@badclasses > 0) {
17380:         my %lt=&Apache::lonlocal::texthash(
17381:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
17382:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
17383:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
17384:         );
17385:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
17386:                            &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'};
17387:         if ($context eq 'auto') {
17388:             $outcome .= $badclass_msg.$linefeed;
17389:         } else {
17390:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
17391:         }
17392:         foreach my $item (@badclasses) {
17393:             if ($context eq 'auto') {
17394:                 $outcome .= " - $item\n";
17395:             } else {
17396:                 $outcome .= "<li>$item</li>\n";
17397:             }
17398:         }
17399:         if ($context eq 'auto') {
17400:             $outcome .= $linefeed;
17401:         } else {
17402:             $outcome .= "</ul><br /><br /></div>\n";
17403:         } 
17404:     }
17405:     if ($args->{'no_end_date'}) {
17406:         $args->{'endaccess'} = 0;
17407:     }
17408: #  If an official course with institutional sections is created by cloning 
17409: #  an existing course, section-specific hiding of course totals in student's
17410: #  view of grades as copied from cloned course, will be checked for valid 
17411: #  sections.
17412:     if (($can_clone && $cloneid) &&
17413:         ($cenv{'internal.coursecode'} ne '') &&
17414:         ($cenv{'grading'} eq 'standard') &&
17415:         ($cenv{'hidetotals'} ne '') &&
17416:         ($cenv{'hidetotals'} ne 'all')) {
17417:         my @hidesecs;
17418:         my $deletehidetotals;
17419:         if (@oklcsecs) {
17420:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
17421:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
17422:                     push(@hidesecs,$sec);
17423:                 }
17424:             }
17425:             if (@hidesecs) {
17426:                 $cenv{'hidetotals'} = join(',',@hidesecs);
17427:             } else {
17428:                 $deletehidetotals = 1;
17429:             }
17430:         } else {
17431:             $deletehidetotals = 1;
17432:         }
17433:         if ($deletehidetotals) {
17434:             delete($cenv{'hidetotals'});
17435:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
17436:         }
17437:     }
17438:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
17439:     $cenv{'internal.autoend'}=$args->{'enrollend'};
17440:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
17441:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
17442:     if ($args->{'showphotos'}) {
17443:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
17444:     }
17445:     $cenv{'internal.authtype'} = $args->{'authtype'};
17446:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
17447:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
17448:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
17449:             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'); 
17450:             if ($context eq 'auto') {
17451:                 $outcome .= $krb_msg;
17452:             } else {
17453:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
17454:             }
17455:             $outcome .= $linefeed;
17456:         }
17457:     }
17458:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
17459:        if ($args->{'setpolicy'}) {
17460:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17461:        }
17462:        if ($args->{'setcontent'}) {
17463:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17464:        }
17465:        if ($args->{'setcomment'}) {
17466:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17467:        }
17468:     }
17469:     if ($args->{'reshome'}) {
17470: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
17471: 	$cenv{'reshome'}=~s/\/+$/\//;
17472:     }
17473: #
17474: # course has keyed access
17475: #
17476:     if ($args->{'setkeys'}) {
17477:        $cenv{'keyaccess'}='yes';
17478:     }
17479: # if specified, key authority is not course, but user
17480: # only active if keyaccess is yes
17481:     if ($args->{'keyauth'}) {
17482: 	my ($user,$domain) = split(':',$args->{'keyauth'});
17483: 	$user = &LONCAPA::clean_username($user);
17484: 	$domain = &LONCAPA::clean_username($domain);
17485: 	if ($user ne '' && $domain ne '') {
17486: 	    $cenv{'keyauth'}=$user.':'.$domain;
17487: 	}
17488:     }
17489: 
17490: #
17491: #  generate and store uniquecode (available to course requester), if course should have one.
17492: #
17493:     if ($args->{'uniquecode'}) {
17494:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
17495:         if ($code) {
17496:             $cenv{'internal.uniquecode'} = $code;
17497:             my %crsinfo =
17498:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
17499:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
17500:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
17501:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
17502:             } 
17503:             if (ref($coderef)) {
17504:                 $$coderef = $code;
17505:             }
17506:         }
17507:     }
17508: 
17509:     if ($args->{'disresdis'}) {
17510:         $cenv{'pch.roles.denied'}='st';
17511:     }
17512:     if ($args->{'disablechat'}) {
17513:         $cenv{'plc.roles.denied'}='st';
17514:     }
17515: 
17516:     # Record we've not yet viewed the Course Initialization Helper for this 
17517:     # course
17518:     $cenv{'course.helper.not.run'} = 1;
17519:     #
17520:     # Use new Randomseed
17521:     #
17522:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
17523:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
17524:     #
17525:     # The encryption code and receipt prefix for this course
17526:     #
17527:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
17528:     $cenv{'internal.encpref'}=100+int(9*rand(99));
17529:     #
17530:     # By default, use standard grading
17531:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
17532: 
17533:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
17534:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
17535: #
17536: # Open all assignments
17537: #
17538:     if ($args->{'openall'}) {
17539:        my $opendate = time;
17540:        if ($args->{'openallfrom'} =~ /^\d+$/) {
17541:            $opendate = $args->{'openallfrom'};
17542:        }
17543:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
17544:        my %storecontent = ($storeunder         => $opendate,
17545:                            $storeunder.'.type' => 'date_start');
17546:        $outcome .= &mt('All assignments open starting [_1]',
17547:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
17548:                    &Apache::lonnet::cput
17549:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
17550:    }
17551: #
17552: # Set first page
17553: #
17554:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
17555: 	    || ($cloneid)) {
17556: 	$outcome .= &mt('Setting first resource').': ';
17557: 
17558: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
17559:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
17560: 
17561:         $outcome .= ($fatal?$errtext:'read ok').' - ';
17562:         my $title; my $url;
17563:         if ($args->{'firstres'} eq 'syl') {
17564: 	    $title=&mt('Syllabus');
17565:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
17566:         } else {
17567:             $title=&mt('Table of Contents');
17568:             $url='/adm/navmaps';
17569:         }
17570: 
17571:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
17572: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
17573: 
17574: 	if ($errtext) { $fatal=2; }
17575:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
17576:     }
17577: 
17578: # 
17579: # Set params for Placement Tests
17580: #
17581:     if ($args->{'crstype'} eq 'Placement') {
17582:        my %storecontent; 
17583:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
17584:        my %defaults = (
17585:                         buttonshide   => { value => 'yes',
17586:                                            type => 'string_yesno',},
17587:                         type          => { value => 'randomizetry',
17588:                                            type  => 'string_questiontype',},
17589:                         maxtries      => { value => 1,
17590:                                            type => 'int_pos',},
17591:                         problemstatus => { value => 'no',
17592:                                            type  => 'string_problemstatus',},
17593:                       );
17594:        foreach my $key (keys(%defaults)) {
17595:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17596:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17597:        }
17598:        &Apache::lonnet::cput
17599:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
17600:     }
17601: 
17602:     return (1,$outcome,\@clonemsg);
17603: }
17604: 
17605: sub make_unique_code {
17606:     my ($cdom,$cnum) = @_;
17607:     # get lock on uniquecodes db
17608:     my $lockhash = {
17609:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
17610:                                                   ':'.$env{'user.domain'},
17611:                    };
17612:     my $tries = 0;
17613:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17614:     my ($code,$error);
17615:   
17616:     while (($gotlock ne 'ok') && ($tries<3)) {
17617:         $tries ++;
17618:         sleep 1;
17619:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17620:     }
17621:     if ($gotlock eq 'ok') {
17622:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17623:         my $gotcode;
17624:         my $attempts = 0;
17625:         while ((!$gotcode) && ($attempts < 100)) {
17626:             $code = &generate_code();
17627:             if (!exists($currcodes{$code})) {
17628:                 $gotcode = 1;
17629:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17630:                     $error = 'nostore';
17631:                 }
17632:             }
17633:             $attempts ++;
17634:         }
17635:         my @del_lock = ($cnum."\0".'uniquecodes');
17636:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17637:     } else {
17638:         $error = 'nolock';
17639:     }
17640:     return ($code,$error);
17641: }
17642: 
17643: sub generate_code {
17644:     my $code;
17645:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17646:     for (my $i=0; $i<6; $i++) {
17647:         my $lettnum = int (rand 2);
17648:         my $item = '';
17649:         if ($lettnum) {
17650:             $item = $letts[int( rand(18) )];
17651:         } else {
17652:             $item = 1+int( rand(8) );
17653:         }
17654:         $code .= $item;
17655:     }
17656:     return $code;
17657: }
17658: 
17659: ############################################################
17660: ############################################################
17661: 
17662: # Community, Course and Placement Test
17663: sub course_type {
17664:     my ($cid) = @_;
17665:     if (!defined($cid)) {
17666:         $cid = $env{'request.course.id'};
17667:     }
17668:     if (defined($env{'course.'.$cid.'.type'})) {
17669:         return $env{'course.'.$cid.'.type'};
17670:     } else {
17671:         return 'Course';
17672:     }
17673: }
17674: 
17675: sub group_term {
17676:     my $crstype = &course_type();
17677:     my %names = (
17678:                   'Course' => 'group',
17679:                   'Community' => 'group',
17680:                   'Placement' => 'group',
17681:                 );
17682:     return $names{$crstype};
17683: }
17684: 
17685: sub course_types {
17686:     my @types = ('official','unofficial','community','textbook','placement','lti');
17687:     my %typename = (
17688:                          official   => 'Official course',
17689:                          unofficial => 'Unofficial course',
17690:                          community  => 'Community',
17691:                          textbook   => 'Textbook course',
17692:                          placement  => 'Placement test',
17693:                          lti        => 'LTI provider',
17694:                    );
17695:     return (\@types,\%typename);
17696: }
17697: 
17698: sub icon {
17699:     my ($file)=@_;
17700:     my $curfext = lc((split(/\./,$file))[-1]);
17701:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17702:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17703:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17704: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17705: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17706: 	            $curfext.".gif") {
17707: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17708: 		$curfext.".gif";
17709: 	}
17710:     }
17711:     return &lonhttpdurl($iconname);
17712: } 
17713: 
17714: sub lonhttpdurl {
17715: #
17716: # Had been used for "small fry" static images on separate port 8080.
17717: # Modify here if lightweight http functionality desired again.
17718: # Currently eliminated due to increasing firewall issues.
17719: #
17720:     my ($url)=@_;
17721:     return $url;
17722: }
17723: 
17724: sub connection_aborted {
17725:     my ($r)=@_;
17726:     $r->print(" ");$r->rflush();
17727:     my $c = $r->connection;
17728:     return $c->aborted();
17729: }
17730: 
17731: #    Escapes strings that may have embedded 's that will be put into
17732: #    strings as 'strings'.
17733: sub escape_single {
17734:     my ($input) = @_;
17735:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
17736:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
17737:     return $input;
17738: }
17739: 
17740: #  Same as escape_single, but escape's "'s  This 
17741: #  can be used for  "strings"
17742: sub escape_double {
17743:     my ($input) = @_;
17744:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
17745:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
17746:     return $input;
17747: }
17748:  
17749: #   Escapes the last element of a full URL.
17750: sub escape_url {
17751:     my ($url)   = @_;
17752:     my @urlslices = split(/\//, $url,-1);
17753:     my $lastitem = &escape(pop(@urlslices));
17754:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17755: }
17756: 
17757: sub compare_arrays {
17758:     my ($arrayref1,$arrayref2) = @_;
17759:     my (@difference,%count);
17760:     @difference = ();
17761:     %count = ();
17762:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17763:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17764:         foreach my $element (keys(%count)) {
17765:             if ($count{$element} == 1) {
17766:                 push(@difference,$element);
17767:             }
17768:         }
17769:     }
17770:     return @difference;
17771: }
17772: 
17773: sub lon_status_items {
17774:     my %defaults = (
17775:                      E         => 100,
17776:                      W         => 4,
17777:                      N         => 1,
17778:                      U         => 5,
17779:                      threshold => 200,
17780:                      sysmail   => 2500,
17781:                    );
17782:     my %names = (
17783:                    E => 'Errors',
17784:                    W => 'Warnings',
17785:                    N => 'Notices',
17786:                    U => 'Unsent',
17787:                 );
17788:     return (\%defaults,\%names);
17789: }
17790: 
17791: # -------------------------------------------------------- Initialize user login
17792: sub init_user_environment {
17793:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
17794:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17795: 
17796:     my $public=($username eq 'public' && $domain eq 'public');
17797: 
17798:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
17799:         $coauthorenv);
17800:     my $now=time;
17801: 
17802:     if ($public) {
17803: 	my $max_public=100;
17804: 	my $oldest;
17805: 	my $oldest_time=0;
17806: 	for(my $next=1;$next<=$max_public;$next++) {
17807: 	    if (-e $lonids."/publicuser_$next.id") {
17808: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17809: 		if ($mtime<$oldest_time || !$oldest_time) {
17810: 		    $oldest_time=$mtime;
17811: 		    $oldest=$next;
17812: 		}
17813: 	    } else {
17814: 		$cookie="publicuser_$next";
17815: 		last;
17816: 	    }
17817: 	}
17818: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
17819:     } else {
17820: 	# See if old ID present, if so, remove if this isn't a robot,
17821: 	# killing any existing non-robot sessions
17822: 	if (!$args->{'robot'}) {
17823: 	    opendir(DIR,$lonids);
17824: 	    while ($filename=readdir(DIR)) {
17825: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17826:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17827:                             &GDBM_READER(),0640)) {
17828:                         my $linkedfile;
17829:                         if (exists($oldenv{'user.linkedenv'})) {
17830:                             $linkedfile = $oldenv{'user.linkedenv'};
17831:                         }
17832:                         untie(%oldenv);
17833:                         if (unlink("$lonids/$filename")) {
17834:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17835:                                 if (-l "$lonids/$linkedfile.id") {
17836:                                     unlink("$lonids/$linkedfile.id");
17837:                                 }
17838:                             }
17839:                         }
17840:                     } else {
17841:                         unlink($lonids.'/'.$filename);
17842:                     }
17843: 		}
17844: 	    }
17845: 	    closedir(DIR);
17846: # If there is a undeleted lockfile for the user's paste buffer remove it.
17847:             my $namespace = 'nohist_courseeditor';
17848:             my $lockingkey = 'paste'."\0".'locked_num';
17849:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17850:                                                 $domain,$username);
17851:             if (exists($lockhash{$lockingkey})) {
17852:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17853:                 unless ($delresult eq 'ok') {
17854:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17855:                 }
17856:             }
17857: 	}
17858: # Give them a new cookie
17859: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17860: 		                   : $now.$$.int(rand(10000)));
17861: 	$cookie="$username\_$id\_$domain\_$authhost";
17862:     
17863: # Initialize roles
17864: 
17865: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
17866:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
17867:     }
17868: # ------------------------------------ Check browser type and MathML capability
17869: 
17870:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17871:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17872: 
17873: # ------------------------------------------------------------- Get environment
17874: 
17875:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17876:     my ($tmp) = keys(%userenv);
17877:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17878: 	undef(%userenv);
17879:     }
17880:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
17881: 	$form->{'interface'}=$userenv{'interface'};
17882:     }
17883:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17884: 
17885: # --------------- Do not trust query string to be put directly into environment
17886:     foreach my $option ('interface','localpath','localres') {
17887:         $form->{$option}=~s/[\n\r\=]//gs;
17888:     }
17889: # --------------------------------------------------------- Write first profile
17890: 
17891:     {
17892:         my $ip = &Apache::lonnet::get_requestor_ip($r);
17893: 	my %initial_env = 
17894: 	    ("user.name"          => $username,
17895: 	     "user.domain"        => $domain,
17896: 	     "user.home"          => $authhost,
17897: 	     "browser.type"       => $clientbrowser,
17898: 	     "browser.version"    => $clientversion,
17899: 	     "browser.mathml"     => $clientmathml,
17900: 	     "browser.unicode"    => $clientunicode,
17901: 	     "browser.os"         => $clientos,
17902:              "browser.mobile"     => $clientmobile,
17903:              "browser.info"       => $clientinfo,
17904:              "browser.osversion"  => $clientosversion,
17905: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
17906: 	     "request.course.fn"  => '',
17907: 	     "request.course.uri" => '',
17908: 	     "request.course.sec" => '',
17909: 	     "request.role"       => 'cm',
17910: 	     "request.role.adv"   => $env{'user.adv'},
17911: 	     "request.host"       => $ip,);
17912: 
17913:         if ($form->{'localpath'}) {
17914: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
17915: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
17916:         }
17917: 	
17918: 	if ($form->{'interface'}) {
17919: 	    $form->{'interface'}=~s/\W//gs;
17920: 	    $initial_env{"browser.interface"} = $form->{'interface'};
17921: 	    $env{'browser.interface'}=$form->{'interface'};
17922: 	}
17923: 
17924:         if ($form->{'iptoken'}) {
17925:             my $lonhost = $r->dir_config('lonHostID');
17926:             $initial_env{"user.noloadbalance"} = $lonhost;
17927:             $env{'user.noloadbalance'} = $lonhost;
17928:         }
17929: 
17930:         if ($form->{'noloadbalance'}) {
17931:             my @hosts = &Apache::lonnet::current_machine_ids();
17932:             my $hosthere = $form->{'noloadbalance'};
17933:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
17934:                 $initial_env{"user.noloadbalance"} = $hosthere;
17935:                 $env{'user.noloadbalance'} = $hosthere;
17936:             }
17937:         }
17938: 
17939:         unless ($domain eq 'public') {
17940:             my %is_adv = ( is_adv => $env{'user.adv'} );
17941:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17942: 
17943:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
17944:                 $userenv{'availabletools.'.$tool} =
17945:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17946:                                                       undef,\%userenv,\%domdef,\%is_adv);
17947:             }
17948: 
17949:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17950:                 $userenv{'canrequest.'.$crstype} =
17951:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
17952:                                                       'reload','requestcourses',
17953:                                                       \%userenv,\%domdef,\%is_adv);
17954:             }
17955: 
17956:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
17957:                 (exists($userroles->{"user.role.au./$domain/"}))) {
17958:                 if ($userenv{'authoreditors'}) {
17959:                     $userenv{'editors'} = $userenv{'authoreditors'};
17960:                 } elsif ($domdef{'editors'} ne '') {
17961:                     $userenv{'editors'} = $domdef{'editors'};
17962:                 } else {
17963:                     $userenv{'editors'} = 'edit,xml';
17964:                 }
17965:             }
17966: 
17967:             $userenv{'canrequest.author'} =
17968:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17969:                                                   'reload','requestauthor',
17970:                                                   \%userenv,\%domdef,\%is_adv);
17971:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17972:                                                  $domain,$username);
17973:             my $reqstatus = $reqauthor{'author_status'};
17974:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
17975:                 if (ref($reqauthor{'author'}) eq 'HASH') {
17976:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
17977:                                                       $reqauthor{'author'}{'timestamp'};
17978:                 }
17979:             }
17980:             my ($types,$typename) = &course_types();
17981:             if (ref($types) eq 'ARRAY') {
17982:                 my @options = ('approval','validate','autolimit');
17983:                 my $optregex = join('|',@options);
17984:                 my (%willtrust,%trustchecked);
17985:                 foreach my $type (@{$types}) {
17986:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17987:                     if ($dom_str ne '') {
17988:                         my $updatedstr = '';
17989:                         my @possdomains = split(',',$dom_str);
17990:                         foreach my $entry (@possdomains) {
17991:                             my ($extdom,$extopt) = split(':',$entry);
17992:                             unless ($trustchecked{$extdom}) {
17993:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17994:                                 $trustchecked{$extdom} = 1;
17995:                             }
17996:                             if ($willtrust{$extdom}) {
17997:                                 $updatedstr .= $entry.',';
17998:                             }
17999:                         }
18000:                         $updatedstr =~ s/,$//;
18001:                         if ($updatedstr) {
18002:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
18003:                         } else {
18004:                             delete($userenv{'reqcrsotherdom.'.$type});
18005:                         }
18006:                     }
18007:                 }
18008:             }
18009:         }
18010: 	$env{'user.environment'} = "$lonids/$cookie.id";
18011: 
18012: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
18013: 		 &GDBM_WRCREAT(),0640)) {
18014: 	    &_add_to_env(\%disk_env,\%initial_env);
18015: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
18016: 	    &_add_to_env(\%disk_env,$userroles);
18017:             if (ref($firstaccenv) eq 'HASH') {
18018:                 &_add_to_env(\%disk_env,$firstaccenv);
18019:             }
18020:             if (ref($timerintenv) eq 'HASH') {
18021:                 &_add_to_env(\%disk_env,$timerintenv);
18022:             }
18023:             if (ref($coauthorenv) eq 'HASH') {
18024:                 if (keys(%{$coauthorenv})) {
18025:                     &_add_to_env(\%disk_env,$coauthorenv);
18026:                 }
18027:             }
18028: 	    if (ref($args->{'extra_env'})) {
18029: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
18030: 	    }
18031: 	    untie(%disk_env);
18032: 	} else {
18033: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
18034: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
18035: 	    return 'error: '.$!;
18036: 	}
18037:     }
18038:     $env{'request.role'}='cm';
18039:     $env{'request.role.adv'}=$env{'user.adv'};
18040:     $env{'browser.type'}=$clientbrowser;
18041: 
18042:     return $cookie;
18043: 
18044: }
18045: 
18046: sub _add_to_env {
18047:     my ($idf,$env_data,$prefix) = @_;
18048:     if (ref($env_data) eq 'HASH') {
18049:         while (my ($key,$value) = each(%$env_data)) {
18050: 	    $idf->{$prefix.$key} = $value;
18051: 	    $env{$prefix.$key}   = $value;
18052:         }
18053:     }
18054: }
18055: 
18056: # --- Get the symbolic name of a problem and the url
18057: sub get_symb {
18058:     my ($request,$silent) = @_;
18059:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
18060:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
18061:     if ($symb eq '') {
18062:         if (!$silent) {
18063:             if (ref($request)) { 
18064:                 $request->print("Unable to handle ambiguous references:$url:.");
18065:             }
18066:             return ();
18067:         }
18068:     }
18069:     &Apache::lonenc::check_decrypt(\$symb);
18070:     return ($symb);
18071: }
18072: 
18073: # --------------------------------------------------------------Get annotation
18074: 
18075: sub get_annotation {
18076:     my ($symb,$enc) = @_;
18077: 
18078:     my $key = $symb;
18079:     if (!$enc) {
18080:         $key =
18081:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
18082:     }
18083:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
18084:     return $annotation{$key};
18085: }
18086: 
18087: sub clean_symb {
18088:     my ($symb,$delete_enc) = @_;
18089: 
18090:     &Apache::lonenc::check_decrypt(\$symb);
18091:     my $enc = $env{'request.enc'};
18092:     if ($delete_enc) {
18093:         delete($env{'request.enc'});
18094:     }
18095: 
18096:     return ($symb,$enc);
18097: }
18098: 
18099: ############################################################
18100: ############################################################
18101: 
18102: =pod
18103: 
18104: =head1 Routines for building display used to search for courses
18105: 
18106: 
18107: =over 4
18108: 
18109: =item * &build_filters()
18110: 
18111: Create markup for a table used to set filters to use when selecting
18112: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
18113: and quotacheck.pl
18114: 
18115: 
18116: Inputs:
18117: 
18118: filterlist - anonymous array of fields to include as potential filters 
18119: 
18120: crstype - course type
18121: 
18122: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
18123:               to pop-open a course selector (will contain "extra element"). 
18124: 
18125: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
18126: 
18127: filter - anonymous hash of criteria and their values
18128: 
18129: action - form action
18130: 
18131: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
18132: 
18133: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
18134: 
18135: cloneruname - username of owner of new course who wants to clone
18136: 
18137: clonerudom - domain of owner of new course who wants to clone
18138: 
18139: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
18140: 
18141: codetitlesref - reference to array of titles of components in institutional codes (official courses)
18142: 
18143: codedom - domain
18144: 
18145: formname - value of form element named "form". 
18146: 
18147: fixeddom - domain, if fixed.
18148: 
18149: prevphase - value to assign to form element named "phase" when going back to the previous screen  
18150: 
18151: cnameelement - name of form element in form on opener page which will receive title of selected course 
18152: 
18153: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
18154: 
18155: cdomelement - name of form element in form on opener page which will receive domain of selected course
18156: 
18157: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
18158: 
18159: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
18160: 
18161: clonewarning - warning message about missing information for intended course owner when DC creates a course
18162: 
18163: 
18164: Returns: $output - HTML for display of search criteria, and hidden form elements.
18165: 
18166: 
18167: Side Effects: None
18168: 
18169: =cut
18170: 
18171: # ---------------------------------------------- search for courses based on last activity etc.
18172: 
18173: sub build_filters {
18174:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
18175:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
18176:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
18177:         $cnameelement,$cnumelement,$cdomelement,$setroles,
18178:         $clonetext,$clonewarning) = @_;
18179:     my ($list,$jscript);
18180:     my $onchange = 'javascript:updateFilters(this)';
18181:     my ($domainselectform,$sincefilterform,$createdfilterform,
18182:         $ownerdomselectform,$persondomselectform,$instcodeform,
18183:         $typeselectform,$instcodetitle);
18184:     if ($formname eq '') {
18185:         $formname = $caller;
18186:     }
18187:     foreach my $item (@{$filterlist}) {
18188:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
18189:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
18190:             if ($item eq 'domainfilter') {
18191:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
18192:             } elsif ($item eq 'coursefilter') {
18193:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
18194:             } elsif ($item eq 'ownerfilter') {
18195:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
18196:             } elsif ($item eq 'ownerdomfilter') {
18197:                 $filter->{'ownerdomfilter'} =
18198:                     &LONCAPA::clean_domain($filter->{$item});
18199:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
18200:                                                        'ownerdomfilter',1);
18201:             } elsif ($item eq 'personfilter') {
18202:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
18203:             } elsif ($item eq 'persondomfilter') {
18204:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
18205:                                                         'persondomfilter',1);
18206:             } else {
18207:                 $filter->{$item} =~ s/\W//g;
18208:             }
18209:             if (!$filter->{$item}) {
18210:                 $filter->{$item} = '';
18211:             }
18212:         }
18213:         if ($item eq 'domainfilter') {
18214:             my $allow_blank = 1;
18215:             if ($formname eq 'portform') {
18216:                 $allow_blank=0;
18217:             } elsif ($formname eq 'studentform') {
18218:                 $allow_blank=0;
18219:             }
18220:             if ($fixeddom) {
18221:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
18222:                                     ' value="'.$codedom.'" />'.
18223:                                     &Apache::lonnet::domain($codedom,'description');
18224:             } else {
18225:                 $domainselectform = &select_dom_form($filter->{$item},
18226:                                                      'domainfilter',
18227:                                                       $allow_blank,'',$onchange);
18228:             }
18229:         } else {
18230:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
18231:         }
18232:     }
18233: 
18234:     # last course activity filter and selection
18235:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
18236: 
18237:     # course created filter and selection
18238:     if (exists($filter->{'createdfilter'})) {
18239:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
18240:     }
18241: 
18242:     my $prefix = $crstype;
18243:     if ($crstype eq 'Placement') {
18244:         $prefix = 'Placement Test'
18245:     }
18246:     my %lt = &Apache::lonlocal::texthash(
18247:                 'cac' => "$prefix Activity",
18248:                 'ccr' => "$prefix Created",
18249:                 'cde' => "$prefix Title",
18250:                 'cdo' => "$prefix Domain",
18251:                 'ins' => 'Institutional Code',
18252:                 'inc' => 'Institutional Categorization',
18253:                 'cow' => "$prefix Owner/Co-owner",
18254:                 'cop' => "$prefix Personnel Includes",
18255:                 'cog' => 'Type',
18256:              );
18257: 
18258:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18259:         my $typeval = 'Course';
18260:         if ($crstype eq 'Community') {
18261:             $typeval = 'Community';
18262:         } elsif ($crstype eq 'Placement') {
18263:             $typeval = 'Placement';
18264:         }
18265:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
18266:     } else {
18267:         $typeselectform =  '<select name="type" size="1"';
18268:         if ($onchange) {
18269:             $typeselectform .= ' onchange="'.$onchange.'"';
18270:         }
18271:         $typeselectform .= '>'."\n";
18272:         foreach my $posstype ('Course','Community','Placement') {
18273:             my $shown;
18274:             if ($posstype eq 'Placement') {
18275:                 $shown = &mt('Placement Test');
18276:             } else {
18277:                 $shown = &mt($posstype);
18278:             }
18279:             $typeselectform.='<option value="'.$posstype.'"'.
18280:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
18281:         }
18282:         $typeselectform.="</select>";
18283:     }
18284: 
18285:     my ($cloneableonlyform,$cloneabletitle);
18286:     if (exists($filter->{'cloneableonly'})) {
18287:         my $cloneableon = '';
18288:         my $cloneableoff = ' checked="checked"';
18289:         if ($filter->{'cloneableonly'}) {
18290:             $cloneableon = $cloneableoff;
18291:             $cloneableoff = '';
18292:         }
18293:         $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>';
18294:         if ($formname eq 'ccrs') {
18295:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
18296:         } else {
18297:             $cloneabletitle = &mt('Cloneable by you');
18298:         }
18299:     }
18300:     my $officialjs;
18301:     if ($crstype eq 'Course') {
18302:         if (exists($filter->{'instcodefilter'})) {
18303: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
18304: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
18305:             if ($codedom) { 
18306:                 $officialjs = 1;
18307:                 ($instcodeform,$jscript,$$numtitlesref) =
18308:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
18309:                                                                   $officialjs,$codetitlesref);
18310:                 if ($jscript) {
18311:                     $jscript = '<script type="text/javascript">'."\n".
18312:                                '// <![CDATA['."\n".
18313:                                $jscript."\n".
18314:                                '// ]]>'."\n".
18315:                                '</script>'."\n";
18316:                 }
18317:             }
18318:             if ($instcodeform eq '') {
18319:                 $instcodeform =
18320:                     '<input type="text" name="instcodefilter" size="10" value="'.
18321:                     $list->{'instcodefilter'}.'" />';
18322:                 $instcodetitle = $lt{'ins'};
18323:             } else {
18324:                 $instcodetitle = $lt{'inc'};
18325:             }
18326:             if ($fixeddom) {
18327:                 $instcodetitle .= '<br />('.$codedom.')';
18328:             }
18329:         }
18330:     }
18331:     my $output = qq|
18332: <form method="post" name="filterpicker" action="$action">
18333: <input type="hidden" name="form" value="$formname" />
18334: |;
18335:     if ($formname eq 'modifycourse') {
18336:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
18337:                    '<input type="hidden" name="prevphase" value="'.
18338:                    $prevphase.'" />'."\n";
18339:     } elsif ($formname eq 'quotacheck') {
18340:         $output .= qq|
18341: <input type="hidden" name="sortby" value="" />
18342: <input type="hidden" name="sortorder" value="" />
18343: |;
18344:     } else {
18345:         my $name_input;
18346:         if ($cnameelement ne '') {
18347:             $name_input = '<input type="hidden" name="cnameelement" value="'.
18348:                           $cnameelement.'" />';
18349:         }
18350:         $output .= qq|
18351: <input type="hidden" name="cnumelement" value="$cnumelement" />
18352: <input type="hidden" name="cdomelement" value="$cdomelement" />
18353: $name_input
18354: $roleelement
18355: $multelement
18356: $typeelement
18357: |;
18358:         if ($formname eq 'portform') {
18359:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
18360:         }
18361:     }
18362:     if ($fixeddom) {
18363:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
18364:     }
18365:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
18366:     if ($sincefilterform) {
18367:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
18368:                   .$sincefilterform
18369:                   .&Apache::lonhtmlcommon::row_closure();
18370:     }
18371:     if ($createdfilterform) {
18372:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
18373:                   .$createdfilterform
18374:                   .&Apache::lonhtmlcommon::row_closure();
18375:     }
18376:     if ($domainselectform) {
18377:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
18378:                   .$domainselectform
18379:                   .&Apache::lonhtmlcommon::row_closure();
18380:     }
18381:     if ($typeselectform) {
18382:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18383:             $output .= $typeselectform;
18384:         } else {
18385:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
18386:                       .$typeselectform
18387:                       .&Apache::lonhtmlcommon::row_closure();
18388:         }
18389:     }
18390:     if ($instcodeform) {
18391:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
18392:                   .$instcodeform
18393:                   .&Apache::lonhtmlcommon::row_closure();
18394:     }
18395:     if (exists($filter->{'ownerfilter'})) {
18396:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
18397:                    '<table><tr><td>'.&mt('Username').'<br />'.
18398:                    '<input type="text" name="ownerfilter" size="20" value="'.
18399:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18400:                    $ownerdomselectform.'</td></tr></table>'.
18401:                    &Apache::lonhtmlcommon::row_closure();
18402:     }
18403:     if (exists($filter->{'personfilter'})) {
18404:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
18405:                    '<table><tr><td>'.&mt('Username').'<br />'.
18406:                    '<input type="text" name="personfilter" size="20" value="'.
18407:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18408:                    $persondomselectform.'</td></tr></table>'.
18409:                    &Apache::lonhtmlcommon::row_closure();
18410:     }
18411:     if (exists($filter->{'coursefilter'})) {
18412:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
18413:                   .'<input type="text" name="coursefilter" size="25" value="'
18414:                   .$list->{'coursefilter'}.'" />'
18415:                   .&Apache::lonhtmlcommon::row_closure();
18416:     }
18417:     if ($cloneableonlyform) {
18418:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
18419:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
18420:     }
18421:     if (exists($filter->{'descriptfilter'})) {
18422:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
18423:                   .'<input type="text" name="descriptfilter" size="40" value="'
18424:                   .$list->{'descriptfilter'}.'" />'
18425:                   .&Apache::lonhtmlcommon::row_closure(1);
18426:     }
18427:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
18428:                '<input type="hidden" name="updater" value="" />'."\n".
18429:                '<input type="submit" name="gosearch" value="'.
18430:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
18431:     return $jscript.$clonewarning.$output;
18432: }
18433: 
18434: =pod 
18435: 
18436: =item * &timebased_select_form()
18437: 
18438: Create markup for a dropdown list used to select a time-based
18439: filter e.g., Course Activity, Course Created, when searching for courses
18440: or communities
18441: 
18442: Inputs:
18443: 
18444: item - name of form element (sincefilter or createdfilter)
18445: 
18446: filter - anonymous hash of criteria and their values
18447: 
18448: Returns: HTML for a select box contained a blank, then six time selections,
18449:          with value set in incoming form variables currently selected. 
18450: 
18451: Side Effects: None
18452: 
18453: =cut
18454: 
18455: sub timebased_select_form {
18456:     my ($item,$filter) = @_;
18457:     if (ref($filter) eq 'HASH') {
18458:         $filter->{$item} =~ s/[^\d-]//g;
18459:         if (!$filter->{$item}) { $filter->{$item}=-1; }
18460:         return &select_form(
18461:                             $filter->{$item},
18462:                             $item,
18463:                             {      '-1' => '',
18464:                                 '86400' => &mt('today'),
18465:                                '604800' => &mt('last week'),
18466:                               '2592000' => &mt('last month'),
18467:                               '7776000' => &mt('last three months'),
18468:                              '15552000' => &mt('last six months'),
18469:                              '31104000' => &mt('last year'),
18470:                     'select_form_order' =>
18471:                            ['-1','86400','604800','2592000','7776000',
18472:                             '15552000','31104000']});
18473:     }
18474: }
18475: 
18476: =pod
18477: 
18478: =item * &js_changer()
18479: 
18480: Create script tag containing Javascript used to submit course search form
18481: when course type or domain is changed, and also to hide 'Searching ...' on
18482: page load completion for page showing search result.
18483: 
18484: Inputs: None
18485: 
18486: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
18487: 
18488: Side Effects: None
18489: 
18490: =cut
18491: 
18492: sub js_changer {
18493:     return <<ENDJS;
18494: <script type="text/javascript">
18495: // <![CDATA[
18496: function updateFilters(caller) {
18497:     if (typeof(caller) != "undefined") {
18498:         document.filterpicker.updater.value = caller.name;
18499:     }
18500:     document.filterpicker.submit();
18501: }
18502: 
18503: function hideSearching() {
18504:     if (document.getElementById('searching')) {
18505:         document.getElementById('searching').style.display = 'none';
18506:     }
18507:     return;
18508: }
18509: 
18510: // ]]>
18511: </script>
18512: 
18513: ENDJS
18514: }
18515: 
18516: =pod
18517: 
18518: =item * &search_courses()
18519: 
18520: Process selected filters form course search form and pass to lonnet::courseiddump
18521: to retrieve a hash for which keys are courseIDs which match the selected filters.
18522: 
18523: Inputs:
18524: 
18525: dom - domain being searched 
18526: 
18527: type - course type ('Course' or 'Community' or '.' if any).
18528: 
18529: filter - anonymous hash of criteria and their values
18530: 
18531: numtitles - for institutional codes - number of categories
18532: 
18533: cloneruname - optional username of new course owner
18534: 
18535: clonerudom - optional domain of new course owner
18536: 
18537: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
18538:             (used when DC is using course creation form)
18539: 
18540: codetitles - reference to array of titles of components in institutional codes (official courses).
18541: 
18542: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
18543:            (and so can clone automatically)
18544: 
18545: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
18546: 
18547: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
18548:               courses to clone 
18549: 
18550: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
18551: 
18552: 
18553: Side Effects: None
18554: 
18555: =cut
18556: 
18557: 
18558: sub search_courses {
18559:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
18560:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
18561:     my (%courses,%showcourses,$cloner);
18562:     if (($filter->{'ownerfilter'} ne '') ||
18563:         ($filter->{'ownerdomfilter'} ne '')) {
18564:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
18565:                                        $filter->{'ownerdomfilter'};
18566:     }
18567:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
18568:         if (!$filter->{$item}) {
18569:             $filter->{$item}='.';
18570:         }
18571:     }
18572:     my $now = time;
18573:     my $timefilter =
18574:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
18575:     my ($createdbefore,$createdafter);
18576:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
18577:         $createdbefore = $now;
18578:         $createdafter = $now-$filter->{'createdfilter'};
18579:     }
18580:     my ($instcodefilter,$regexpok);
18581:     if ($numtitles) {
18582:         if ($env{'form.official'} eq 'on') {
18583:             $instcodefilter =
18584:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18585:             $regexpok = 1;
18586:         } elsif ($env{'form.official'} eq 'off') {
18587:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18588:             unless ($instcodefilter eq '') {
18589:                 $regexpok = -1;
18590:             }
18591:         }
18592:     } else {
18593:         $instcodefilter = $filter->{'instcodefilter'};
18594:     }
18595:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
18596:     if ($type eq '') { $type = '.'; }
18597: 
18598:     if (($clonerudom ne '') && ($cloneruname ne '')) {
18599:         $cloner = $cloneruname.':'.$clonerudom;
18600:     }
18601:     %courses = &Apache::lonnet::courseiddump($dom,
18602:                                              $filter->{'descriptfilter'},
18603:                                              $timefilter,
18604:                                              $instcodefilter,
18605:                                              $filter->{'combownerfilter'},
18606:                                              $filter->{'coursefilter'},
18607:                                              undef,undef,$type,$regexpok,undef,undef,
18608:                                              undef,undef,$cloner,$cc_clone,
18609:                                              $filter->{'cloneableonly'},
18610:                                              $createdbefore,$createdafter,undef,
18611:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
18612:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18613:         my $ccrole;
18614:         if ($type eq 'Community') {
18615:             $ccrole = 'co';
18616:         } else {
18617:             $ccrole = 'cc';
18618:         }
18619:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18620:                                                      $filter->{'persondomfilter'},
18621:                                                      'userroles',undef,
18622:                                                      [$ccrole,'in','ad','ep','ta','cr'],
18623:                                                      $dom);
18624:         foreach my $role (keys(%rolehash)) {
18625:             my ($cnum,$cdom,$courserole) = split(':',$role);
18626:             my $cid = $cdom.'_'.$cnum;
18627:             if (exists($courses{$cid})) {
18628:                 if (ref($courses{$cid}) eq 'HASH') {
18629:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18630:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18631:                             push(@{$courses{$cid}{roles}},$courserole);
18632:                         }
18633:                     } else {
18634:                         $courses{$cid}{roles} = [$courserole];
18635:                     }
18636:                     $showcourses{$cid} = $courses{$cid};
18637:                 }
18638:             }
18639:         }
18640:         %courses = %showcourses;
18641:     }
18642:     return %courses;
18643: }
18644: 
18645: =pod
18646: 
18647: =back
18648: 
18649: =head1 Routines for version requirements for current course.
18650: 
18651: =over 4
18652: 
18653: =item * &check_release_required()
18654: 
18655: Compares required LON-CAPA version with version on server, and
18656: if required version is newer looks for a server with the required version.
18657: 
18658: Looks first at servers in user's owen domain; if none suitable, looks at
18659: servers in course's domain are permitted to host sessions for user's domain.
18660: 
18661: Inputs:
18662: 
18663: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18664: 
18665: $courseid - Course ID of current course
18666: 
18667: $rolecode - User's current role in course (for switchserver query string).
18668: 
18669: $required - LON-CAPA version needed by course (format: Major.Minor).
18670: 
18671: 
18672: Returns:
18673: 
18674: $switchserver - query string tp append to /adm/switchserver call (if 
18675:                 current server's LON-CAPA version is too old. 
18676: 
18677: $warning - Message is displayed if no suitable server could be found.
18678: 
18679: =cut
18680: 
18681: sub check_release_required {
18682:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
18683:     my ($switchserver,$warning);
18684:     if ($required ne '') {
18685:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18686:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18687:         if ($reqdmajor ne '' && $reqdminor ne '') {
18688:             my $otherserver;
18689:             if (($major eq '' && $minor eq '') ||
18690:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18691:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18692:                 my $switchlcrev =
18693:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18694:                                                            $userdomserver);
18695:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18696:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18697:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18698:                     my $cdom = $env{'course.'.$courseid.'.domain'};
18699:                     if ($cdom ne $env{'user.domain'}) {
18700:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18701:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18702:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18703:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18704:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18705:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18706:                         my $canhost =
18707:                             &Apache::lonnet::can_host_session($env{'user.domain'},
18708:                                                               $coursedomserver,
18709:                                                               $remoterev,
18710:                                                               $udomdefaults{'remotesessions'},
18711:                                                               $defdomdefaults{'hostedsessions'});
18712: 
18713:                         if ($canhost) {
18714:                             $otherserver = $coursedomserver;
18715:                         } else {
18716:                             $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.");
18717:                         }
18718:                     } else {
18719:                         $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).");
18720:                     }
18721:                 } else {
18722:                     $otherserver = $userdomserver;
18723:                 }
18724:             }
18725:             if ($otherserver ne '') {
18726:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
18727:             }
18728:         }
18729:     }
18730:     return ($switchserver,$warning);
18731: }
18732: 
18733: =pod
18734: 
18735: =item * &check_release_result()
18736: 
18737: Inputs:
18738: 
18739: $switchwarning - Warning message if no suitable server found to host session.
18740: 
18741: $switchserver - query string to append to /adm/switchserver containing lonHostID
18742:                 and current role.
18743: 
18744: Returns: HTML to display with information about requirement to switch server.
18745:          Either displaying warning with link to Roles/Courses screen or
18746:          display link to switchserver.
18747: 
18748: =cut
18749: 
18750: sub check_release_result {
18751:     my ($switchwarning,$switchserver) = @_;
18752:     my $output = &start_page('Selected course unavailable on this server').
18753:                  '<p class="LC_warning">';
18754:     if ($switchwarning) {
18755:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
18756:         if (&show_course()) {
18757:             $output .= &mt('Display courses');
18758:         } else {
18759:             $output .= &mt('Display roles');
18760:         }
18761:         $output .= '</a>';
18762:     } elsif ($switchserver) {
18763:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18764:                    '<br />'.
18765:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
18766:                    &mt('Switch Server').
18767:                    '</a>';
18768:     }
18769:     $output .= '</p>'.&end_page();
18770:     return $output;
18771: }
18772: 
18773: =pod
18774: 
18775: =item * &needs_coursereinit()
18776: 
18777: Determine if course contents stored for user's session needs to be
18778: refreshed, because content has changed since "Big Hash" last tied.
18779: 
18780: Check for change is made if time last checked is more than 10 minutes ago
18781: (by default).
18782: 
18783: Inputs:
18784: 
18785: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18786: 
18787: $interval (optional) - Time which may elapse (in s) between last check for content
18788:                        change in current course. (default: 600 s).  
18789: 
18790: Returns: an array; first element is:
18791: 
18792: =over 4
18793: 
18794: 'switch' - if content updates mean user's session
18795:            needs to be switched to a server running a newer LON-CAPA version
18796:  
18797: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18798:            on current server hosting user's session                
18799: 
18800: ''       - if no action required.
18801: 
18802: =back
18803: 
18804: If first item element is 'switch':
18805: 
18806: second item is $switchwarning - Warning message if no suitable server found to host session. 
18807: 
18808: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18809:                               and current role. 
18810: 
18811: otherwise: no other elements returned.
18812: 
18813: =back
18814: 
18815: =cut
18816: 
18817: sub needs_coursereinit {
18818:     my ($loncaparev,$interval) = @_;
18819:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18820:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18821:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18822:     my $now = time;
18823:     if ($interval eq '') {
18824:         $interval = 600;
18825:     }
18826:     if (($now-$env{'request.course.timechecked'})>$interval) {
18827:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18828:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18829:         if ($blocked) {
18830:             return ();
18831:         }
18832:         my $update;
18833:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18834:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
18835:         if ($lastmainchange > $env{'request.course.tied'}) {
18836:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18837:             if ($needswitch) {
18838:                 return ('switch',$switchwarning,$switchserver);
18839:             }
18840:             $update = 'main';
18841:         }
18842:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
18843:             if ($update) {
18844:                 $update = 'both';
18845:             } else {
18846:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18847:                 if ($needswitch) {
18848:                     return ('switch',$switchwarning,$switchserver);
18849:                 } else {
18850:                     $update = 'supp';
18851:                 }
18852:             }
18853:             return ($update);
18854:         }
18855:     }
18856:     return ();
18857: }
18858: 
18859: sub switch_for_update {
18860:     my ($loncaparev,$cdom,$cnum) = @_;
18861:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18862:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18863:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18864:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18865:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18866:                                     $curr_reqd_hash{'internal.releaserequired'}});
18867:             my ($switchserver,$switchwarning) =
18868:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18869:                                         $curr_reqd_hash{'internal.releaserequired'});
18870:             if ($switchwarning ne '' || $switchserver ne '') {
18871:                 return ('switch',$switchwarning,$switchserver);
18872:             }
18873:         }
18874:     }
18875:     return ();
18876: }
18877: 
18878: sub update_content_constraints {
18879:     my ($cdom,$cnum,$chome,$cid) = @_;
18880:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18881:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18882:     my (%checkresponsetypes,%checkcrsrestypes);
18883:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18884:         my ($item,$name,$value) = split(/:/,$key);
18885:         if ($item eq 'resourcetag') {
18886:             if ($name eq 'responsetype') {
18887:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18888:             }
18889:         } elsif ($item eq 'course') {
18890:             if ($name eq 'courserestype') {
18891:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
18892:             }
18893:         }
18894:     }
18895:     my $navmap = Apache::lonnavmaps::navmap->new();
18896:     if (defined($navmap)) {
18897:         my (%allresponses,%allcrsrestypes);
18898:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18899:             if ($res->is_tool()) {
18900:                 if ($allcrsrestypes{'exttool'}) {
18901:                     $allcrsrestypes{'exttool'} ++;
18902:                 } else {
18903:                     $allcrsrestypes{'exttool'} = 1;
18904:                 }
18905:                 next;
18906:             }
18907:             my %responses = $res->responseTypes();
18908:             foreach my $key (keys(%responses)) {
18909:                 next unless(exists($checkresponsetypes{$key}));
18910:                 $allresponses{$key} += $responses{$key};
18911:             }
18912:         }
18913:         foreach my $key (keys(%allresponses)) {
18914:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18915:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18916:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18917:             }
18918:         }
18919:         foreach my $key (keys(%allcrsrestypes)) {
18920:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18921:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18922:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18923:             }
18924:         }
18925:         undef($navmap);
18926:     }
18927:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
18928:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18929:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18930:             ($reqdmajor,$reqdminor) = ($major,$minor);
18931:         }
18932:     }
18933:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18934:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18935:     }
18936:     return;
18937: }
18938: 
18939: sub allmaps_incourse {
18940:     my ($cdom,$cnum,$chome,$cid) = @_;
18941:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18942:         $cid = $env{'request.course.id'};
18943:         $cdom = $env{'course.'.$cid.'.domain'};
18944:         $cnum = $env{'course.'.$cid.'.num'};
18945:         $chome = $env{'course.'.$cid.'.home'};
18946:     }
18947:     my %allmaps = ();
18948:     my $lastchange =
18949:         &Apache::lonnet::get_coursechange($cdom,$cnum);
18950:     if ($lastchange > $env{'request.course.tied'}) {
18951:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18952:         unless ($ferr) {
18953:             &update_content_constraints($cdom,$cnum,$chome,$cid);
18954:         }
18955:     }
18956:     my $navmap = Apache::lonnavmaps::navmap->new();
18957:     if (defined($navmap)) {
18958:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18959:             $allmaps{$res->src()} = 1;
18960:         }
18961:     }
18962:     return \%allmaps;
18963: }
18964: 
18965: sub parse_supplemental_title {
18966:     my ($title) = @_;
18967: 
18968:     my ($foldertitle,$renametitle);
18969:     if ($title =~ /&amp;&amp;&amp;/) {
18970:         $title = &HTML::Entites::decode($title);
18971:     }
18972:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18973:         $renametitle=$4;
18974:         my ($time,$uname,$udom) = ($1,$2,$3);
18975:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18976:         my $name =  &plainname($uname,$udom);
18977:         $name = &HTML::Entities::encode($name,'"<>&\'');
18978:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18979:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
18980:         if ($foldertitle ne '') {
18981:             $title .= ': <br />'.$foldertitle;
18982:         }
18983:     }
18984:     if (wantarray) {
18985:         return ($title,$foldertitle,$renametitle);
18986:     }
18987:     return $title;
18988: }
18989: 
18990: sub get_supplemental {
18991:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
18992:     my $hashid=$cnum.':'.$cdom;
18993:     my ($supplemental,$cached,$set_httprefs);
18994:     unless ($ignorecache) {
18995:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
18996:     }
18997:     unless (defined($cached)) {
18998:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
18999:         unless ($chome eq 'no_host') {
19000:             my @order = @LONCAPA::map::order;
19001:             my @resources = @LONCAPA::map::resources;
19002:             my @resparms = @LONCAPA::map::resparms;
19003:             my @zombies = @LONCAPA::map::zombies;
19004:             my ($errors,%ids,%hidden);
19005:             $errors =
19006:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
19007:                                       $errors,$possdel,\%ids,\%hidden);
19008:             @LONCAPA::map::order = @order;
19009:             @LONCAPA::map::resources = @resources;
19010:             @LONCAPA::map::resparms = @resparms;
19011:             @LONCAPA::map::zombies = @zombies;
19012:             $set_httprefs = 1;
19013:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
19014:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
19015:             }
19016:             $supplemental = {
19017:                                ids => \%ids,
19018:                                hidden => \%hidden,
19019:                             };
19020:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
19021:         }
19022:     }
19023:     return ($supplemental,$set_httprefs);
19024: }
19025: 
19026: sub recurse_supplemental {
19027:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
19028:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
19029:         my $mapnum;
19030:         if ($suppmap eq 'supplemental.sequence') {
19031:             $mapnum = 0;
19032:         } else {
19033:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
19034:         }
19035:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
19036:         if ($fatal) {
19037:             $errors ++;
19038:         } else {
19039:             my @order = @LONCAPA::map::order;
19040:             if (@order > 0) {
19041:                 my @resources = @LONCAPA::map::resources;
19042:                 my @resparms = @LONCAPA::map::resparms;
19043:                 foreach my $idx (@order) {
19044:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
19045:                     if (($src ne '') && ($status eq 'res')) {
19046:                         my $id = $mapnum.':'.$idx;
19047:                         push(@{$suppids->{$src}},$id);
19048:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
19049:                             $hiddensupp->{$id} = 1;
19050:                         }
19051:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
19052:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
19053:                                                             $hiddensupp,$hiddensupp->{$id});
19054:                         } else {
19055:                             my $allowed;
19056:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
19057:                                 $allowed = 1;
19058:                             } elsif ($possdel) {
19059:                                 foreach my $item (@{$suppids->{$src}}) {
19060:                                     next if ($item eq $id);
19061:                                     unless ($hiddensupp->{$item}) {
19062:                                        $allowed = 1;
19063:                                        last;
19064:                                     }
19065:                                 }
19066:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
19067:                                     &Apache::lonnet::delenv('httpref.'.$src);
19068:                                 }
19069:                             }
19070:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
19071:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
19072:                             }
19073:                         }
19074:                     }
19075:                 }
19076:             }
19077:         }
19078:     }
19079:     return $errors;
19080: }
19081: 
19082: sub set_supp_httprefs {
19083:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
19084:     if (ref($supplemental) eq 'HASH') {
19085:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
19086:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
19087:                 next if ($src =~ /\.sequence$/);
19088:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
19089:                     my $allowed;
19090:                     if ($env{'request.role.adv'}) {
19091:                         $allowed = 1;
19092:                     } else {
19093:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
19094:                             unless ($supplemental->{'hidden'}->{$id}) {
19095:                                 $allowed = 1;
19096:                                 last;
19097:                             }
19098:                         }
19099:                     }
19100:                     if (exists($env{'httpref.'.$src})) {
19101:                         if ($possdel) {
19102:                             unless ($allowed) {
19103:                                 &Apache::lonnet::delenv('httpref.'.$src);
19104:                             }
19105:                         }
19106:                     } elsif ($allowed) {
19107:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
19108:                     }
19109:                 }
19110:             }
19111:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
19112:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
19113:             }
19114:         }
19115:     }
19116: }
19117: 
19118: sub get_supp_parameter {
19119:     my ($resparm,$name)=@_;
19120:     return if ($resparm eq '');
19121:     my $value=undef;
19122:     my $ptype=undef;
19123:     foreach (split('&&&',$resparm)) {
19124:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
19125:         if ($thisname eq $name) {
19126:             $value=$thisvalue;
19127:             $ptype=$thistype;
19128:         }
19129:     }
19130:     return $value;
19131: }
19132: 
19133: sub symb_to_docspath {
19134:     my ($symb,$navmapref) = @_;
19135:     return unless ($symb && ref($navmapref));
19136:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
19137:     if ($resurl=~/\.(sequence|page)$/) {
19138:         $mapurl=$resurl;
19139:     } elsif ($resurl eq 'adm/navmaps') {
19140:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
19141:     }
19142:     my $mapresobj;
19143:     unless (ref($$navmapref)) {
19144:         $$navmapref = Apache::lonnavmaps::navmap->new();
19145:     }
19146:     if (ref($$navmapref)) {
19147:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
19148:     }
19149:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
19150:     my $type=$2;
19151:     my $path;
19152:     if (ref($mapresobj)) {
19153:         my $pcslist = $mapresobj->map_hierarchy();
19154:         if ($pcslist ne '') {
19155:             foreach my $pc (split(/,/,$pcslist)) {
19156:                 next if ($pc <= 1);
19157:                 my $res = $$navmapref->getByMapPc($pc);
19158:                 if (ref($res)) {
19159:                     my $thisurl = $res->src();
19160:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
19161:                     my $thistitle = $res->title();
19162:                     $path .= '&'.
19163:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
19164:                              &escape($thistitle).
19165:                              ':'.$res->randompick().
19166:                              ':'.$res->randomout().
19167:                              ':'.$res->encrypted().
19168:                              ':'.$res->randomorder().
19169:                              ':'.$res->is_page();
19170:                 }
19171:             }
19172:         }
19173:         $path =~ s/^\&//;
19174:         my $maptitle = $mapresobj->title();
19175:         if ($mapurl eq 'default') {
19176:             $maptitle = 'Main Content';
19177:         }
19178:         $path .= (($path ne '')? '&' : '').
19179:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
19180:                  &escape($maptitle).
19181:                  ':'.$mapresobj->randompick().
19182:                  ':'.$mapresobj->randomout().
19183:                  ':'.$mapresobj->encrypted().
19184:                  ':'.$mapresobj->randomorder().
19185:                  ':'.$mapresobj->is_page();
19186:     } else {
19187:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
19188:         my $ispage = (($type eq 'page')? 1 : '');
19189:         if ($mapurl eq 'default') {
19190:             $maptitle = 'Main Content';
19191:         }
19192:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
19193:                 &escape($maptitle).':::::'.$ispage;
19194:     }
19195:     unless ($mapurl eq 'default') {
19196:         $path = 'default&'.
19197:                 &escape('Main Content').
19198:                 ':::::&'.$path;
19199:     }
19200:     return $path;
19201: }
19202: 
19203: sub validate_folderpath {
19204:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
19205:     if ($env{'form.folderpath'} ne '') {
19206:         my @items = split(/\&/,$env{'form.folderpath'});
19207:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
19208:         for (my $i=0; $i<@items; $i++) {
19209:             my $odd = $i%2;
19210:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
19211:                 $badpath = 1;
19212:             } elsif ($odd && $supplementalflag) {
19213:                 my $idx = $i-1;
19214:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
19215:                     my $esc_name = $1;
19216:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
19217:                         $supppath .= '&'.$esc_name;
19218:                         $changed = 1;
19219:                     } else {
19220:                         $supppath .= '&'.$items[$i];
19221:                     }
19222:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
19223:                     $changed = 1;
19224:                     my $is_hidden;
19225:                     unless ($got_supp) {
19226:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
19227:                         if (ref($supplemental) eq 'HASH') {
19228:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
19229:                                 %supphidden = %{$supplemental->{'hidden'}};
19230:                             }
19231:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
19232:                                 %suppids = %{$supplemental->{'ids'}};
19233:                             }
19234:                         }
19235:                         $got_supp = 1;
19236:                     }
19237:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
19238:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
19239:                         if ($supphidden{$mapid}) {
19240:                             $is_hidden = 1;
19241:                         }
19242:                     }
19243:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
19244:                 } else {
19245:                     $supppath .= '&'.$items[$i];
19246:                 }
19247:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
19248:                 $badpath = 1;
19249:             } elsif ($supplementalflag) {
19250:                 $supppath .= '&'.$items[$i];
19251:             }
19252:             last if ($badpath);
19253:         }
19254:         if ($badpath) {
19255:             delete($env{'form.folderpath'});
19256:         } elsif ($changed && $supplementalflag) {
19257:             $supppath =~ s/^\&//;
19258:             $env{'form.folderpath'} = $supppath;
19259:         }
19260:     }
19261:     return;
19262: }
19263: 
19264: sub captcha_display {
19265:     my ($context,$lonhost,$defdom) = @_;
19266:     my ($output,$error);
19267:     my ($captcha,$pubkey,$privkey,$version) = 
19268:         &get_captcha_config($context,$lonhost,$defdom);
19269:     if ($captcha eq 'original') {
19270:         $output = &create_captcha();
19271:         unless ($output) {
19272:             $error = 'captcha';
19273:         }
19274:     } elsif ($captcha eq 'recaptcha') {
19275:         $output = &create_recaptcha($pubkey,$version);
19276:         unless ($output) {
19277:             $error = 'recaptcha';
19278:         }
19279:     }
19280:     return ($output,$error,$captcha,$version);
19281: }
19282: 
19283: sub captcha_response {
19284:     my ($context,$lonhost,$defdom) = @_;
19285:     my ($captcha_chk,$captcha_error);
19286:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
19287:     if ($captcha eq 'original') {
19288:         ($captcha_chk,$captcha_error) = &check_captcha();
19289:     } elsif ($captcha eq 'recaptcha') {
19290:         $captcha_chk = &check_recaptcha($privkey,$version);
19291:     } else {
19292:         $captcha_chk = 1;
19293:     }
19294:     return ($captcha_chk,$captcha_error);
19295: }
19296: 
19297: sub get_captcha_config {
19298:     my ($context,$lonhost,$dom_in_effect) = @_;
19299:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
19300:     my $hostname = &Apache::lonnet::hostname($lonhost);
19301:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
19302:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
19303:     if ($context eq 'usercreation') {
19304:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
19305:         if (ref($domconfig{$context}) eq 'HASH') {
19306:             $hashtocheck = $domconfig{$context}{'cancreate'};
19307:             if (ref($hashtocheck) eq 'HASH') {
19308:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
19309:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
19310:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
19311:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
19312:                     }
19313:                     if ($privkey && $pubkey) {
19314:                         $captcha = 'recaptcha';
19315:                         $version = $hashtocheck->{'recaptchaversion'};
19316:                         if ($version ne '2') {
19317:                             $version = 1;
19318:                         }
19319:                     } else {
19320:                         $captcha = 'original';
19321:                     }
19322:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
19323:                     $captcha = 'original';
19324:                 }
19325:             }
19326:         } else {
19327:             $captcha = 'captcha';
19328:         }
19329:     } elsif ($context eq 'login') {
19330:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
19331:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
19332:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
19333:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
19334:             if ($privkey && $pubkey) {
19335:                 $captcha = 'recaptcha';
19336:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
19337:                 if ($version ne '2') {
19338:                     $version = 1; 
19339:                 }
19340:             } else {
19341:                 $captcha = 'original';
19342:             }
19343:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
19344:             $captcha = 'original';
19345:         }
19346:     } elsif ($context eq 'passwords') {
19347:         if ($dom_in_effect) {
19348:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
19349:             if ($passwdconf{'captcha'} eq 'recaptcha') {
19350:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
19351:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
19352:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
19353:                 }
19354:                 if ($privkey && $pubkey) {
19355:                     $captcha = 'recaptcha';
19356:                     $version = $passwdconf{'recaptchaversion'};
19357:                     if ($version ne '2') {
19358:                         $version = 1;
19359:                     }
19360:                 } else {
19361:                     $captcha = 'original';
19362:                 }
19363:             } elsif ($passwdconf{'captcha'} ne 'notused') {
19364:                 $captcha = 'original';
19365:             }
19366:         }
19367:     } 
19368:     return ($captcha,$pubkey,$privkey,$version);
19369: }
19370: 
19371: sub create_captcha {
19372:     my %captcha_params = &captcha_settings();
19373:     my ($output,$maxtries,$tries) = ('',10,0);
19374:     while ($tries < $maxtries) {
19375:         $tries ++;
19376:         my $captcha = Authen::Captcha->new (
19377:                                            output_folder => $captcha_params{'output_dir'},
19378:                                            data_folder   => $captcha_params{'db_dir'},
19379:                                           );
19380:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
19381: 
19382:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
19383:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
19384:                       '<span class="LC_nobreak">'.
19385:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
19386:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
19387:                       '</span><br />'.
19388:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
19389:             last;
19390:         }
19391:     }
19392:     if ($output eq '') {
19393:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
19394:     }
19395:     return $output;
19396: }
19397: 
19398: sub captcha_settings {
19399:     my %captcha_params = (
19400:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
19401:                            www_output_dir => "/captchaspool",
19402:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
19403:                            numchars       => '5',
19404:                          );
19405:     return %captcha_params;
19406: }
19407: 
19408: sub check_captcha {
19409:     my ($captcha_chk,$captcha_error);
19410:     my $code = $env{'form.code'};
19411:     my $md5sum = $env{'form.crypt'};
19412:     my %captcha_params = &captcha_settings();
19413:     my $captcha = Authen::Captcha->new(
19414:                       output_folder => $captcha_params{'output_dir'},
19415:                       data_folder   => $captcha_params{'db_dir'},
19416:                   );
19417:     $captcha_chk = $captcha->check_code($code,$md5sum);
19418:     my %captcha_hash = (
19419:                         0       => 'Code not checked (file error)',
19420:                        -1      => 'Failed: code expired',
19421:                        -2      => 'Failed: invalid code (not in database)',
19422:                        -3      => 'Failed: invalid code (code does not match crypt)',
19423:     );
19424:     if ($captcha_chk != 1) {
19425:         $captcha_error = $captcha_hash{$captcha_chk}
19426:     }
19427:     return ($captcha_chk,$captcha_error);
19428: }
19429: 
19430: sub create_recaptcha {
19431:     my ($pubkey,$version) = @_;
19432:     if ($version >= 2) {
19433:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
19434:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
19435:     } else {
19436:         my $use_ssl;
19437:         if ($ENV{'SERVER_PORT'} == 443) {
19438:             $use_ssl = 1;
19439:         }
19440:         my $captcha = Captcha::reCAPTCHA->new;
19441:         return $captcha->get_options_setter({theme => 'white'})."\n".
19442:                $captcha->get_html($pubkey,undef,$use_ssl).
19443:                &mt('If the text is hard to read, [_1] will replace them.',
19444:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
19445:                '<br /><br />';
19446:     }
19447: }
19448: 
19449: sub check_recaptcha {
19450:     my ($privkey,$version) = @_;
19451:     my $captcha_chk;
19452:     my $ip = &Apache::lonnet::get_requestor_ip();
19453:     if ($version >= 2) {
19454:         my %info = (
19455:                      secret   => $privkey, 
19456:                      response => $env{'form.g-recaptcha-response'},
19457:                      remoteip => $ip,
19458:                    );
19459:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
19460:         $request->content(join('&',map {
19461:                          my $name = escape($_);
19462:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
19463:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
19464:                          : &escape($info{$_}) );
19465:         } keys(%info)));
19466:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
19467:         if ($response->is_success)  {
19468:             my $data = JSON::DWIW->from_json($response->decoded_content);
19469:             if (ref($data) eq 'HASH') {
19470:                 if ($data->{'success'}) {
19471:                     $captcha_chk = 1;
19472:                 }
19473:             }
19474:         }
19475:     } else {
19476:         my $captcha = Captcha::reCAPTCHA->new;
19477:         my $captcha_result =
19478:             $captcha->check_answer(
19479:                                     $privkey,
19480:                                     $ip,
19481:                                     $env{'form.recaptcha_challenge_field'},
19482:                                     $env{'form.recaptcha_response_field'},
19483:                                   );
19484:         if ($captcha_result->{is_valid}) {
19485:             $captcha_chk = 1;
19486:         }
19487:     }
19488:     return $captcha_chk;
19489: }
19490: 
19491: sub emailusername_info {
19492:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
19493:     my %titles = &Apache::lonlocal::texthash (
19494:                      lastname      => 'Last Name',
19495:                      firstname     => 'First Name',
19496:                      institution   => 'School/college/university',
19497:                      location      => "School's city, state/province, country",
19498:                      web           => "School's web address",
19499:                      officialemail => 'E-mail address at institution (if different)',
19500:                      id            => 'Student/Employee ID',
19501:                  );
19502:     return (\@fields,\%titles);
19503: }
19504: 
19505: sub cleanup_html {
19506:     my ($incoming) = @_;
19507:     my $outgoing;
19508:     if ($incoming ne '') {
19509:         $outgoing = $incoming;
19510:         $outgoing =~ s/;/&#059;/g;
19511:         $outgoing =~ s/\#/&#035;/g;
19512:         $outgoing =~ s/\&/&#038;/g;
19513:         $outgoing =~ s/</&#060;/g;
19514:         $outgoing =~ s/>/&#062;/g;
19515:         $outgoing =~ s/\(/&#040/g;
19516:         $outgoing =~ s/\)/&#041;/g;
19517:         $outgoing =~ s/"/&#034;/g;
19518:         $outgoing =~ s/'/&#039;/g;
19519:         $outgoing =~ s/\$/&#036;/g;
19520:         $outgoing =~ s{/}{&#047;}g;
19521:         $outgoing =~ s/=/&#061;/g;
19522:         $outgoing =~ s/\\/&#092;/g
19523:     }
19524:     return $outgoing;
19525: }
19526: 
19527: # Checks for critical messages and returns a redirect url if one exists.
19528: # $interval indicates how often to check for messages.
19529: # $context is the calling context -- roles, grades, contents, menu or flip. 
19530: sub critical_redirect {
19531:     my ($interval,$context) = @_;
19532:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
19533:         return ();
19534:     }
19535:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
19536:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
19537:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
19538:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
19539:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
19540:             if ($blocked) {
19541:                 my $checkrole = "cm./$cdom/$cnum";
19542:                 if ($env{'request.course.sec'} ne '') {
19543:                     $checkrole .= "/$env{'request.course.sec'}";
19544:                 }
19545:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
19546:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
19547:                     return;
19548:                 }
19549:             }
19550:         }
19551:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
19552:                                         $env{'user.name'});
19553:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
19554:         my $redirecturl;
19555:         if ($what[0]) {
19556: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
19557: 	        $redirecturl='/adm/email?critical=display';
19558: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
19559:                 return (1, $url);
19560:             }
19561:         }
19562:     } 
19563:     return ();
19564: }
19565: 
19566: # Use:
19567: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
19568: #
19569: ##################################################
19570: #          password associated functions         #
19571: ##################################################
19572: sub des_keys {
19573:     # Make a new key for DES encryption.
19574:     # Each key has two parts which are returned separately.
19575:     # Please note:  Each key must be passed through the &hex function
19576:     # before it is output to the web browser.  The hex versions cannot
19577:     # be used to decrypt.
19578:     my @hexstr=('0','1','2','3','4','5','6','7',
19579:                 '8','9','a','b','c','d','e','f');
19580:     my $lkey='';
19581:     for (0..7) {
19582:         $lkey.=$hexstr[rand(15)];
19583:     }
19584:     my $ukey='';
19585:     for (0..7) {
19586:         $ukey.=$hexstr[rand(15)];
19587:     }
19588:     return ($lkey,$ukey);
19589: }
19590: 
19591: sub des_decrypt {
19592:     my ($key,$cyphertext) = @_;
19593:     my $keybin=pack("H16",$key);
19594:     my $cypher;
19595:     if ($Crypt::DES::VERSION>=2.03) {
19596:         $cypher=new Crypt::DES $keybin;
19597:     } else {
19598:         $cypher=new DES $keybin;
19599:     }
19600:     my $plaintext='';
19601:     my $cypherlength = length($cyphertext);
19602:     my $numchunks = int($cypherlength/32);
19603:     for (my $j=0; $j<$numchunks; $j++) {
19604:         my $start = $j*32;
19605:         my $cypherblock = substr($cyphertext,$start,32);
19606:         my $chunk =
19607:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
19608:         $chunk .=
19609:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
19610:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
19611:         $plaintext .= $chunk;
19612:     }
19613:     return $plaintext;
19614: }
19615: 
19616: sub get_requested_shorturls {
19617:     my ($cdom,$cnum,$navmap) = @_;
19618:     return unless (ref($navmap));
19619:     my ($numnew,$errors);
19620:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
19621:     if (@toshorten) {
19622:         my (%maps,%resources,%titles);
19623:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
19624:                                                                'shorturls',$cdom,$cnum);
19625:         if (keys(%resources)) {
19626:             my %tocreate;
19627:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
19628:                 my $symb = $resources{$item};
19629:                 if ($symb) {
19630:                     $tocreate{$cnum.'&'.$symb} = 1;
19631:                 }
19632:             }
19633:             if (keys(%tocreate)) {
19634:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
19635:                                                       \%tocreate);
19636:             }
19637:         }
19638:     }
19639:     return ($numnew,$errors);
19640: }
19641: 
19642: sub make_short_symbs {
19643:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
19644:     my ($numnew,@errors);
19645:     if (ref($tocreateref) eq 'HASH') {
19646:         my %tocreate = %{$tocreateref};
19647:         if (keys(%tocreate)) {
19648:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
19649:             my $su = Short::URL->new(no_vowels => 1);
19650:             my $init = '';
19651:             my (%newunique,%addcourse,%courseonly,%failed);
19652:             # get lock on tiny db
19653:             my $now = time;
19654:             if ($lockuser eq '') {
19655:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
19656:             }
19657:             my $lockhash = {
19658:                                 "lock\0$now" => $lockuser,
19659:                             };
19660:             my $tries = 0;
19661:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19662:             my ($code,$error);
19663:             while (($gotlock ne 'ok') && ($tries<3)) {
19664:                 $tries ++;
19665:                 sleep 1;
19666:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19667:             }
19668:             if ($gotlock eq 'ok') {
19669:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
19670:                                        \%addcourse,\%courseonly,\%failed);
19671:                 if (keys(%failed)) {
19672:                     my $numfailed = scalar(keys(%failed));
19673:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
19674:                 }
19675:                 if (keys(%newunique)) {
19676:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
19677:                     if ($putres eq 'ok') {
19678:                         $numnew = scalar(keys(%newunique));
19679:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
19680:                         unless ($newputres eq 'ok') {
19681:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
19682:                         }
19683:                     } else {
19684:                         push(@errors,&mt('error: could not store unique six character URLs'));
19685:                     }
19686:                 }
19687:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
19688:                 unless ($dellockres eq 'ok') {
19689:                     push(@errors,&mt('error: could not release lockfile'));
19690:                 }
19691:             } else {
19692:                 push(@errors,&mt('error: could not obtain lockfile'));
19693:             }
19694:             if (keys(%courseonly)) {
19695:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
19696:                 if ($result ne 'ok') {
19697:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
19698:                 }
19699:             }
19700:         }
19701:     }
19702:     return ($numnew,\@errors);
19703: }
19704: 
19705: sub shorten_symbs {
19706:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
19707:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
19708:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
19709:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
19710:     my (%possibles,%collisions);
19711:     foreach my $key (keys(%{$tocreate})) {
19712:         my $num = String::CRC32::crc32($key);
19713:         my $tiny = $su->encode($num,$init);
19714:         if ($tiny) {
19715:             $possibles{$tiny} = $key;
19716:         }
19717:     }
19718:     if (!$init) {
19719:         $init = 1;
19720:     } else {
19721:         $init ++;
19722:     }
19723:     if (keys(%possibles)) {
19724:         my @posstiny = keys(%possibles);
19725:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
19726:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
19727:         if (keys(%currtiny)) {
19728:             foreach my $key (keys(%currtiny)) {
19729:                 next if ($currtiny{$key} eq '');
19730:                 if ($currtiny{$key} eq $possibles{$key}) {
19731:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
19732:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19733:                         $courseonly->{$tsymb} = $key;
19734:                     }
19735:                 } else {
19736:                     $collisions{$possibles{$key}} = 1;
19737:                 }
19738:                 delete($possibles{$key});
19739:             }
19740:         }
19741:         foreach my $key (keys(%possibles)) {
19742:             $newunique->{$key} = $possibles{$key};
19743:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
19744:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19745:                 $addcourse->{$tsymb} = $key;
19746:             }
19747:         }
19748:     }
19749:     if (keys(%collisions)) {
19750:         if ($init <5) {
19751:             if (!$init) {
19752:                 $init = 1;
19753:             } else {
19754:                 $init ++;
19755:             }
19756:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
19757:                                    $newunique,$addcourse,$courseonly,$failed);
19758:         } else {
19759:             foreach my $key (keys(%collisions)) {
19760:                 $failed->{$key} = 1;
19761:             }
19762:         }
19763:     }
19764:     return $init;
19765: }
19766: 
19767: sub is_nonframeable {
19768:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
19769:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
19770:     return if (($remprotocol eq '') || ($remhost eq ''));
19771: 
19772:     $remprotocol = lc($remprotocol);
19773:     $remhost = lc($remhost);
19774:     my $remport = 80;
19775:     if ($remprotocol eq 'https') {
19776:         $remport = 443;
19777:     }
19778:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19779:     if ($cached) {
19780:         unless ($nocache) {
19781:             if ($result) {
19782:                 return 1;
19783:             } else {
19784:                 return 0;
19785:             }
19786:         }
19787:     }
19788:     my $uselink;
19789:     my $request = new HTTP::Request('HEAD',$url);
19790:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19791:     if ($response->is_success()) {
19792:         my $secpolicy = lc($response->header('content-security-policy'));
19793:         my $xframeop = lc($response->header('x-frame-options'));
19794:         $secpolicy =~ s/^\s+|\s+$//g;
19795:         $xframeop =~ s/^\s+|\s+$//g;
19796:         if (($secpolicy ne '') || ($xframeop ne '')) {
19797:             my $remotehost = $remprotocol.'://'.$remhost;
19798:             my ($origin,$protocol,$port);
19799:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19800:                 $port = $ENV{'SERVER_PORT'};
19801:             } else {
19802:                 $port = 80;
19803:             }
19804:             if ($absolute eq '') {
19805:                 $protocol = 'http:';
19806:                 if ($port == 443) {
19807:                     $protocol = 'https:';
19808:                 }
19809:                 $origin = $protocol.'//'.lc($hostname);
19810:             } else {
19811:                 $origin = lc($absolute);
19812:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19813:             }
19814:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19815:                 my $framepolicy = $1;
19816:                 $framepolicy =~ s/^\s+|\s+$//g;
19817:                 my @policies = split(/\s+/,$framepolicy);
19818:                 if (@policies) {
19819:                     if (grep(/^\Q'none'\E$/,@policies)) {
19820:                         $uselink = 1;
19821:                     } else {
19822:                         $uselink = 1;
19823:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19824:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19825:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19826:                             undef($uselink);
19827:                         }
19828:                         if ($uselink) {
19829:                             if (grep(/^\Q'self'\E$/,@policies)) {
19830:                                 if (($origin ne '') && ($remotehost eq $origin)) {
19831:                                     undef($uselink);
19832:                                 }
19833:                             }
19834:                         }
19835:                         if ($uselink) {
19836:                             my @possok;
19837:                             if ($ip ne '') {
19838:                                 push(@possok,$ip);
19839:                             }
19840:                             my $hoststr = '';
19841:                             foreach my $part (reverse(split(/\./,$hostname))) {
19842:                                 if ($hoststr eq '') {
19843:                                     $hoststr = $part;
19844:                                 } else {
19845:                                     $hoststr = "$part.$hoststr";
19846:                                 }
19847:                                 if ($hoststr eq $hostname) {
19848:                                     push(@possok,$hostname);
19849:                                 } else {
19850:                                     push(@possok,"*.$hoststr");
19851:                                 }
19852:                             }
19853:                             if (@possok) {
19854:                                 foreach my $poss (@possok) {
19855:                                     last if (!$uselink);
19856:                                     foreach my $policy (@policies) {
19857:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19858:                                             undef($uselink);
19859:                                             last;
19860:                                         }
19861:                                     }
19862:                                 }
19863:                             }
19864:                         }
19865:                     }
19866:                 }
19867:             } elsif ($xframeop ne '') {
19868:                 $uselink = 1;
19869:                 my @policies = split(/\s*,\s*/,$xframeop);
19870:                 if (@policies) {
19871:                     unless (grep(/^deny$/,@policies)) {
19872:                         if ($origin ne '') {
19873:                             if (grep(/^sameorigin$/,@policies)) {
19874:                                 if ($remotehost eq $origin) {
19875:                                     undef($uselink);
19876:                                 }
19877:                             }
19878:                             if ($uselink) {
19879:                                 foreach my $policy (@policies) {
19880:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
19881:                                         my $allowfrom = $1;
19882:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19883:                                             undef($uselink);
19884:                                             last;
19885:                                         }
19886:                                     }
19887:                                 }
19888:                             }
19889:                         }
19890:                     }
19891:                 }
19892:             }
19893:         }
19894:     }
19895:     if ($nocache) {
19896:         if ($cached) {
19897:             my $devalidate;
19898:             if ($uselink && !$result) {
19899:                 $devalidate = 1;
19900:             } elsif (!$uselink && $result) {
19901:                 $devalidate = 1;
19902:             }
19903:             if ($devalidate) {
19904:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19905:             }
19906:         }
19907:     } else {
19908:         if ($uselink) {
19909:             $result = 1;
19910:         } else {
19911:             $result = 0;
19912:         }
19913:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19914:     }
19915:     return $uselink;
19916: }
19917: 
19918: sub page_menu {
19919:     my ($menucolls,$menunum) = @_;
19920:     my %menu;
19921:     foreach my $item (split(/;/,$menucolls)) {
19922:         my ($num,$value) = split(/\%/,$item);
19923:         if ($num eq $menunum) {
19924:             my @entries = split(/\&/,$value);
19925:             foreach my $entry (@entries) {
19926:                 my ($name,$fields) = split(/=/,$entry);
19927:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19928:                     $menu{$name} = $fields;
19929:                 } else {
19930:                     my @shown;
19931:                     if ($fields =~ /,/) {
19932:                         @shown = split(/,/,$fields);
19933:                     } else {
19934:                         @shown = ($fields);
19935:                     }
19936:                     if (@shown) {
19937:                         foreach my $field (@shown) {
19938:                             next if ($field eq '');
19939:                             $menu{$field} = 1;
19940:                         }
19941:                     }
19942:                 }
19943:             }
19944:         }
19945:     }
19946:     return %menu;
19947: }
19948: 
19949: 1;
19950: __END__;
19951: 

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