File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.161.2.20: download - view: text, annotated - select for diffs
Fri Oct 6 13:40:53 2023 UTC (7 months, 3 weeks ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  Include changes in  1.1412,  1.1413

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.161.2.20 2023/10/06 13:40:53 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::map();
   75: use HTTP::Request;
   76: use DateTime::TimeZone;
   77: use DateTime::Locale;
   78: use Encode();
   79: use Authen::Captcha;
   80: use Captcha::reCAPTCHA;
   81: use JSON::DWIW;
   82: use LWP::UserAgent;
   83: use Crypt::DES;
   84: use DynaLoader; # for Crypt::DES version
   85: use File::Copy();
   86: use File::Path();
   87: use String::CRC32();
   88: use Short::URL();
   89: 
   90: # ---------------------------------------------- Designs
   91: use vars qw(%defaultdesign);
   92: 
   93: my $readit;
   94: 
   95: 
   96: ##
   97: ## Global Variables
   98: ##
   99: 
  100: 
  101: # ----------------------------------------------- SSI with retries:
  102: #
  103: 
  104: =pod
  105: 
  106: =head1 Server Side include with retries:
  107: 
  108: =over 4
  109: 
  110: =item * &ssi_with_retries(resource,retries form)
  111: 
  112: Performs an ssi with some number of retries.  Retries continue either
  113: until the result is ok or until the retry count supplied by the
  114: caller is exhausted.  
  115: 
  116: Inputs:
  117: 
  118: =over 4
  119: 
  120: resource   - Identifies the resource to insert.
  121: 
  122: retries    - Count of the number of retries allowed.
  123: 
  124: form       - Hash that identifies the rendering options.
  125: 
  126: =back
  127: 
  128: Returns:
  129: 
  130: =over 4
  131: 
  132: content    - The content of the response.  If retries were exhausted this is empty.
  133: 
  134: response   - The response from the last attempt (which may or may not have been successful.
  135: 
  136: =back
  137: 
  138: =back
  139: 
  140: =cut
  141: 
  142: sub ssi_with_retries {
  143:     my ($resource, $retries, %form) = @_;
  144: 
  145: 
  146:     my $ok = 0;			# True if we got a good response.
  147:     my $content;
  148:     my $response;
  149: 
  150:     # Try to get the ssi done. within the retries count:
  151: 
  152:     do {
  153: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  154: 	$ok      = $response->is_success;
  155:         if (!$ok) {
  156:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  157:         }
  158: 	$retries--;
  159:     } while (!$ok && ($retries > 0));
  160: 
  161:     if (!$ok) {
  162: 	$content = '';		# On error return an empty content.
  163:     }
  164:     return ($content, $response);
  165: 
  166: }
  167: 
  168: 
  169: 
  170: # ----------------------------------------------- Filetypes/Languages/Copyright
  171: my %language;
  172: my %supported_language;
  173: my %latex_language;		# For choosing hyphenation in <transl..>
  174: my %latex_language_bykey;	# for choosing hyphenation from metadata
  175: my %cprtag;
  176: my %scprtag;
  177: my %fe; my %fd; my %fm;
  178: my %category_extensions;
  179: 
  180: # ---------------------------------------------- Thesaurus variables
  181: #
  182: # %Keywords:
  183: #      A hash used by &keyword to determine if a word is considered a keyword.
  184: # $thesaurus_db_file 
  185: #      Scalar containing the full path to the thesaurus database.
  186: 
  187: my %Keywords;
  188: my $thesaurus_db_file;
  189: 
  190: #
  191: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  192: # thesaurus.tab, and filecategories.tab.
  193: #
  194: BEGIN {
  195:     # Variable initialization
  196:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  197:     #
  198:     unless ($readit) {
  199: # ------------------------------------------------------------------- languages
  200:     {
  201:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  202:                                    '/language.tab';
  203:         if ( open(my $fh,'<',$langtabfile) ) {
  204:             while (my $line = <$fh>) {
  205:                 next if ($line=~/^\#/);
  206:                 chomp($line);
  207:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  208:                 $language{$key}=$val.' - '.$enc;
  209:                 if ($sup) {
  210:                     $supported_language{$key}=$sup;
  211:                 }
  212: 		if ($latex) {
  213: 		    $latex_language_bykey{$key} = $latex;
  214: 		    $latex_language{$two} = $latex;
  215: 		}
  216:             }
  217:             close($fh);
  218:         }
  219:     }
  220: # ------------------------------------------------------------------ copyrights
  221:     {
  222:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  223:                                   '/copyright.tab';
  224:         if ( open (my $fh,'<',$copyrightfile) ) {
  225:             while (my $line = <$fh>) {
  226:                 next if ($line=~/^\#/);
  227:                 chomp($line);
  228:                 my ($key,$val)=(split(/\s+/,$line,2));
  229:                 $cprtag{$key}=$val;
  230:             }
  231:             close($fh);
  232:         }
  233:     }
  234: # ----------------------------------------------------------- source copyrights
  235:     {
  236:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  237:                                   '/source_copyright.tab';
  238:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  239:             while (my $line = <$fh>) {
  240:                 next if ($line =~ /^\#/);
  241:                 chomp($line);
  242:                 my ($key,$val)=(split(/\s+/,$line,2));
  243:                 $scprtag{$key}=$val;
  244:             }
  245:             close($fh);
  246:         }
  247:     }
  248: 
  249: # -------------------------------------------------------------- default domain designs
  250:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  251:     my $designfile = $designdir.'/default.tab';
  252:     if ( open (my $fh,'<',$designfile) ) {
  253:         while (my $line = <$fh>) {
  254:             next if ($line =~ /^\#/);
  255:             chomp($line);
  256:             my ($key,$val)=(split(/\=/,$line));
  257:             if ($val) { $defaultdesign{$key}=$val; }
  258:         }
  259:         close($fh);
  260:     }
  261: 
  262: # ------------------------------------------------------------- file categories
  263:     {
  264:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  265:                                   '/filecategories.tab';
  266:         if ( open (my $fh,'<',$categoryfile) ) {
  267: 	    while (my $line = <$fh>) {
  268: 		next if ($line =~ /^\#/);
  269: 		chomp($line);
  270:                 my ($extension,$category)=(split(/\s+/,$line,2));
  271:                 push(@{$category_extensions{lc($category)}},$extension);
  272:             }
  273:             close($fh);
  274:         }
  275: 
  276:     }
  277: # ------------------------------------------------------------------ file types
  278:     {
  279:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  280:                '/filetypes.tab';
  281:         if ( open (my $fh,'<',$typesfile) ) {
  282:             while (my $line = <$fh>) {
  283: 		next if ($line =~ /^\#/);
  284: 		chomp($line);
  285:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  286:                 if ($descr ne '') {
  287:                     $fe{$ending}=lc($emb);
  288:                     $fd{$ending}=$descr;
  289:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  290:                 }
  291:             }
  292:             close($fh);
  293:         }
  294:     }
  295:     &Apache::lonnet::logthis(
  296:              "<span style='color:yellow;'>INFO: Read file types</span>");
  297:     $readit=1;
  298:     }  # end of unless($readit) 
  299:     
  300: }
  301: 
  302: ###############################################################
  303: ##           HTML and Javascript Helper Functions            ##
  304: ###############################################################
  305: 
  306: =pod 
  307: 
  308: =head1 HTML and Javascript Functions
  309: 
  310: =over 4
  311: 
  312: =item * &browser_and_searcher_javascript()
  313: 
  314: X<browsing, javascript>X<searching, javascript>Returns a string
  315: containing javascript with two functions, C<openbrowser> and
  316: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  317: tags.
  318: 
  319: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  320: 
  321: inputs: formname, elementname, only, omit
  322: 
  323: formname and elementname indicate the name of the html form and name of
  324: the element that the results of the browsing selection are to be placed in. 
  325: 
  326: Specifying 'only' will restrict the browser to displaying only files
  327: with the given extension.  Can be a comma separated list.
  328: 
  329: Specifying 'omit' will restrict the browser to NOT displaying files
  330: with the given extension.  Can be a comma separated list.
  331: 
  332: =item * &opensearcher(formname,elementname) [javascript]
  333: 
  334: Inputs: formname, elementname
  335: 
  336: formname and elementname specify the name of the html form and the name
  337: of the element the selection from the search results will be placed in.
  338: 
  339: =cut
  340: 
  341: sub browser_and_searcher_javascript {
  342:     my ($mode)=@_;
  343:     if (!defined($mode)) { $mode='edit'; }
  344:     my $resurl=&escape_single(&lastresurl());
  345:     return <<END;
  346: // <!-- BEGIN LON-CAPA Internal
  347:     var editbrowser = null;
  348:     function openbrowser(formname,elementname,only,omit,titleelement) {
  349:         var url = '$resurl/?';
  350:         if (editbrowser == null) {
  351:             url += 'launch=1&';
  352:         }
  353:         url += 'catalogmode=interactive&';
  354:         url += 'mode=$mode&';
  355:         url += 'inhibitmenu=yes&';
  356:         url += 'form=' + formname + '&';
  357:         if (only != null) {
  358:             url += 'only=' + only + '&';
  359:         } else {
  360:             url += 'only=&';
  361: 	}
  362:         if (omit != null) {
  363:             url += 'omit=' + omit + '&';
  364:         } else {
  365:             url += 'omit=&';
  366: 	}
  367:         if (titleelement != null) {
  368:             url += 'titleelement=' + titleelement + '&';
  369:         } else {
  370: 	    url += 'titleelement=&';
  371: 	}
  372:         url += 'element=' + elementname + '';
  373:         var title = 'Browser';
  374:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  375:         options += ',width=700,height=600';
  376:         editbrowser = open(url,title,options,'1');
  377:         editbrowser.focus();
  378:     }
  379:     var editsearcher;
  380:     function opensearcher(formname,elementname,titleelement) {
  381:         var url = '/adm/searchcat?';
  382:         if (editsearcher == null) {
  383:             url += 'launch=1&';
  384:         }
  385:         url += 'catalogmode=interactive&';
  386:         url += 'mode=$mode&';
  387:         url += 'form=' + formname + '&';
  388:         if (titleelement != null) {
  389:             url += 'titleelement=' + titleelement + '&';
  390:         } else {
  391: 	    url += 'titleelement=&';
  392: 	}
  393:         url += 'element=' + elementname + '';
  394:         var title = 'Search';
  395:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  396:         options += ',width=700,height=600';
  397:         editsearcher = open(url,title,options,'1');
  398:         editsearcher.focus();
  399:     }
  400: // END LON-CAPA Internal -->
  401: END
  402: }
  403: 
  404: sub lastresurl {
  405:     if ($env{'environment.lastresurl'}) {
  406: 	return $env{'environment.lastresurl'}
  407:     } else {
  408: 	return '/res';
  409:     }
  410: }
  411: 
  412: sub storeresurl {
  413:     my $resurl=&Apache::lonnet::clutter(shift);
  414:     unless ($resurl=~/^\/res/) { return 0; }
  415:     $resurl=~s/\/$//;
  416:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  417:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  418:     return 1;
  419: }
  420: 
  421: sub studentbrowser_javascript {
  422:    unless (
  423:             (($env{'request.course.id'}) && 
  424:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  425: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  426: 					  '/'.$env{'request.course.sec'})
  427: 	      ))
  428:          || ($env{'request.role'}=~/^(au|dc|su)/)
  429:           ) { return ''; }  
  430:    return (<<'ENDSTDBRW');
  431: <script type="text/javascript" language="Javascript">
  432: // <![CDATA[
  433:     var stdeditbrowser;
  434:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
  435:         var url = '/adm/pickstudent?';
  436:         var filter;
  437: 	if (!ignorefilter) {
  438: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  439: 	}
  440:         if (filter != null) {
  441:            if (filter != '') {
  442:                url += 'filter='+filter+'&';
  443: 	   }
  444:         }
  445:         url += 'form=' + formname + '&unameelement='+uname+
  446:                                     '&udomelement='+udom+
  447:                                     '&clicker='+clicker;
  448: 	if (roleflag) { url+="&roles=1"; }
  449:         if (courseadv == 'condition') {
  450:             if (document.getElementById('courseadv')) {
  451:                 courseadv = document.getElementById('courseadv').value;
  452:             }
  453:         }
  454:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  455:         if (uident !== '') { url+="&identelement="+uident; }
  456:         var title = 'Student_Browser';
  457:         var options = 'scrollbars=1,resizable=1,menubar=0';
  458:         options += ',width=700,height=600';
  459:         stdeditbrowser = open(url,title,options,'1');
  460:         stdeditbrowser.focus();
  461:     }
  462: // ]]>
  463: </script>
  464: ENDSTDBRW
  465: }
  466: 
  467: sub resourcebrowser_javascript {
  468:    unless ($env{'request.course.id'}) { return ''; }
  469:    return (<<'ENDRESBRW');
  470: <script type="text/javascript" language="Javascript">
  471: // <![CDATA[
  472:     var reseditbrowser;
  473:     function openresbrowser(formname,reslink) {
  474:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  475:         var title = 'Resource_Browser';
  476:         var options = 'scrollbars=1,resizable=1,menubar=0';
  477:         options += ',width=700,height=500';
  478:         reseditbrowser = open(url,title,options,'1');
  479:         reseditbrowser.focus();
  480:     }
  481: // ]]>
  482: </script>
  483: ENDRESBRW
  484: }
  485: 
  486: sub selectstudent_link {
  487:    my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
  488:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  489:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  490:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  491:    if ($env{'request.course.id'}) {  
  492:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  493: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  494: 					'/'.$env{'request.course.sec'})) {
  495: 	   return '';
  496:        }
  497:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  498:        if ($courseadv eq 'only') {
  499:            $callargs .= ",'',1,'$courseadv'";
  500:        } elsif ($courseadv eq 'none') {
  501:            $callargs .= ",'','','$courseadv'";
  502:        } elsif ($courseadv eq 'condition') {
  503:            $callargs .= ",'','','$courseadv'";
  504:        } elsif ($identelem ne '') {
  505:            $callargs .= ",'','',''";
  506:        }
  507:        if ($identelem ne '') {
  508:            $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
  509:        }
  510:        return '<span class="LC_nobreak">'.
  511:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  512:               &mt('Select User').'</a></span>';
  513:    }
  514:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  515:        $callargs .= ",'',1"; 
  516:        return '<span class="LC_nobreak">'.
  517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  518:               &mt('Select User').'</a></span>';
  519:    }
  520:    return '';
  521: }
  522: 
  523: sub selectresource_link {
  524:    my ($form,$reslink,$arg)=@_;
  525:    
  526:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  527:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  528:    unless ($env{'request.course.id'}) { return $arg; }
  529:    return '<span class="LC_nobreak">'.
  530:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  531:               $arg.'</a></span>';
  532: }
  533: 
  534: 
  535: 
  536: sub authorbrowser_javascript {
  537:     return <<"ENDAUTHORBRW";
  538: <script type="text/javascript" language="JavaScript">
  539: // <![CDATA[
  540: var stdeditbrowser;
  541: 
  542: function openauthorbrowser(formname,udom) {
  543:     var url = '/adm/pickauthor?';
  544:     url += 'form='+formname+'&roledom='+udom;
  545:     var title = 'Author_Browser';
  546:     var options = 'scrollbars=1,resizable=1,menubar=0';
  547:     options += ',width=700,height=600';
  548:     stdeditbrowser = open(url,title,options,'1');
  549:     stdeditbrowser.focus();
  550: }
  551: 
  552: // ]]>
  553: </script>
  554: ENDAUTHORBRW
  555: }
  556: 
  557: sub coursebrowser_javascript {
  558:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  559:         $credits_element,$instcode) = @_;
  560:     my $wintitle = 'Course_Browser';
  561:     if ($crstype eq 'Community') {
  562:         $wintitle = 'Community_Browser';
  563:     }
  564:     my $id_functions = &javascript_index_functions();
  565:     my $output = '
  566: <script type="text/javascript" language="JavaScript">
  567: // <![CDATA[
  568:     var stdeditbrowser;'."\n";
  569: 
  570:     $output .= <<"ENDSTDBRW";
  571:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  572:         var url = '/adm/pickcourse?';
  573:         var formid = getFormIdByName(formname);
  574:         var domainfilter = getDomainFromSelectbox(formname,udom);
  575:         if (domainfilter != null) {
  576:            if (domainfilter != '') {
  577:                url += 'domainfilter='+domainfilter+'&';
  578: 	   }
  579:         }
  580:         url += 'form=' + formname + '&cnumelement='+uname+
  581: 	                            '&cdomelement='+udom+
  582:                                     '&cnameelement='+desc;
  583:         if (extra_element !=null && extra_element != '') {
  584:             if (formname == 'rolechoice' || formname == 'studentform') {
  585:                 url += '&roleelement='+extra_element;
  586:                 if (domainfilter == null || domainfilter == '') {
  587:                     url += '&domainfilter='+extra_element;
  588:                 }
  589:             }
  590:             else {
  591:                 if (formname == 'portform') {
  592:                     url += '&setroles='+extra_element;
  593:                 } else {
  594:                     if (formname == 'rules') {
  595:                         url += '&fixeddom='+extra_element; 
  596:                     }
  597:                 }
  598:             }     
  599:         }
  600:         if (type != null && type != '') {
  601:             url += '&type='+type;
  602:         }
  603:         if (type_elem != null && type_elem != '') {
  604:             url += '&typeelement='+type_elem;
  605:         }
  606:         if (formname == 'ccrs') {
  607:             var ownername = document.forms[formid].ccuname.value;
  608:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  609:             url += '&cloner='+ownername+':'+ownerdom;
  610:             if (type == 'Course') {
  611:                 url += '&crscode='+document.forms[formid].crscode.value;
  612:             }
  613:         }
  614:         if (formname == 'requestcrs') {
  615:             url += '&crsdom=$domainfilter&crscode=$instcode';
  616:         }
  617:         if (multflag !=null && multflag != '') {
  618:             url += '&multiple='+multflag;
  619:         }
  620:         var title = '$wintitle';
  621:         var options = 'scrollbars=1,resizable=1,menubar=0';
  622:         options += ',width=700,height=600';
  623:         stdeditbrowser = open(url,title,options,'1');
  624:         stdeditbrowser.focus();
  625:     }
  626: $id_functions
  627: ENDSTDBRW
  628:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  629:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  630:                                       $credits_element);
  631:     }
  632:     $output .= '
  633: // ]]>
  634: </script>';
  635:     return $output;
  636: }
  637: 
  638: sub javascript_index_functions {
  639:     return <<"ENDJS";
  640: 
  641: function getFormIdByName(formname) {
  642:     for (var i=0;i<document.forms.length;i++) {
  643:         if (document.forms[i].name == formname) {
  644:             return i;
  645:         }
  646:     }
  647:     return -1;
  648: }
  649: 
  650: function getIndexByName(formid,item) {
  651:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  652:         if (document.forms[formid].elements[i].name == item) {
  653:             return i;
  654:         }
  655:     }
  656:     return -1;
  657: }
  658: 
  659: function getDomainFromSelectbox(formname,udom) {
  660:     var userdom;
  661:     var formid = getFormIdByName(formname);
  662:     if (formid > -1) {
  663:         var domid = getIndexByName(formid,udom);
  664:         if (domid > -1) {
  665:             if (document.forms[formid].elements[domid].type == 'select-one') {
  666:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  667:             }
  668:             if (document.forms[formid].elements[domid].type == 'hidden') {
  669:                 userdom=document.forms[formid].elements[domid].value;
  670:             }
  671:         }
  672:     }
  673:     return userdom;
  674: }
  675: 
  676: ENDJS
  677: 
  678: }
  679: 
  680: sub javascript_array_indexof {
  681:     return <<ENDJS;
  682: <script type="text/javascript" language="JavaScript">
  683: // <![CDATA[
  684: 
  685: if (!Array.prototype.indexOf) {
  686:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  687:         "use strict";
  688:         if (this === void 0 || this === null) {
  689:             throw new TypeError();
  690:         }
  691:         var t = Object(this);
  692:         var len = t.length >>> 0;
  693:         if (len === 0) {
  694:             return -1;
  695:         }
  696:         var n = 0;
  697:         if (arguments.length > 0) {
  698:             n = Number(arguments[1]);
  699:             if (n !== n) { // shortcut for verifying if it's NaN
  700:                 n = 0;
  701:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  702:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  703:             }
  704:         }
  705:         if (n >= len) {
  706:             return -1;
  707:         }
  708:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  709:         for (; k < len; k++) {
  710:             if (k in t && t[k] === searchElement) {
  711:                 return k;
  712:             }
  713:         }
  714:         return -1;
  715:     }
  716: }
  717: 
  718: // ]]>
  719: </script>
  720: 
  721: ENDJS
  722: 
  723: }
  724: 
  725: sub userbrowser_javascript {
  726:     my $id_functions = &javascript_index_functions();
  727:     return <<"ENDUSERBRW";
  728: 
  729: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  730:     var url = '/adm/pickuser?';
  731:     var userdom = getDomainFromSelectbox(formname,udom);
  732:     if (userdom != null) {
  733:        if (userdom != '') {
  734:            url += 'srchdom='+userdom+'&';
  735:        }
  736:     }
  737:     url += 'form=' + formname + '&unameelement='+uname+
  738:                                 '&udomelement='+udom+
  739:                                 '&ulastelement='+ulast+
  740:                                 '&ufirstelement='+ufirst+
  741:                                 '&uemailelement='+uemail+
  742:                                 '&hideudomelement='+hideudom+
  743:                                 '&coursedom='+crsdom;
  744:     if ((caller != null) && (caller != undefined)) {
  745:         url += '&caller='+caller;
  746:     }
  747:     var title = 'User_Browser';
  748:     var options = 'scrollbars=1,resizable=1,menubar=0';
  749:     options += ',width=700,height=600';
  750:     var stdeditbrowser = open(url,title,options,'1');
  751:     stdeditbrowser.focus();
  752: }
  753: 
  754: function fix_domain (formname,udom,origdom,uname) {
  755:     var formid = getFormIdByName(formname);
  756:     if (formid > -1) {
  757:         var unameid = getIndexByName(formid,uname);
  758:         var domid = getIndexByName(formid,udom);
  759:         var hidedomid = getIndexByName(formid,origdom);
  760:         if (hidedomid > -1) {
  761:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  762:             var unameval = document.forms[formid].elements[unameid].value;
  763:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  764:                 if (domid > -1) {
  765:                     var slct = document.forms[formid].elements[domid];
  766:                     if (slct.type == 'select-one') {
  767:                         var i;
  768:                         for (i=0;i<slct.length;i++) {
  769:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  770:                         }
  771:                     }
  772:                     if (slct.type == 'hidden') {
  773:                         slct.value = fixeddom;
  774:                     }
  775:                 }
  776:             }
  777:         }
  778:     }
  779:     return;
  780: }
  781: 
  782: $id_functions
  783: ENDUSERBRW
  784: }
  785: 
  786: sub setsec_javascript {
  787:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  788:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  789:         $communityrolestr);
  790:     if ($role_element ne '') {
  791:         my @allroles = ('st','ta','ep','in','ad');
  792:         foreach my $crstype ('Course','Community') {
  793:             if ($crstype eq 'Community') {
  794:                 foreach my $role (@allroles) {
  795:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  796:                 }
  797:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  798:             } else {
  799:                 foreach my $role (@allroles) {
  800:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  801:                 }
  802:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  803:             }
  804:         }
  805:         $rolestr = '"'.join('","',@allroles).'"';
  806:         $courserolestr = '"'.join('","',@courserolenames).'"';
  807:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  808:     }
  809:     my $setsections = qq|
  810: function setSect(sectionlist) {
  811:     var sectionsArray = new Array();
  812:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  813:         sectionsArray = sectionlist.split(",");
  814:     }
  815:     var numSections = sectionsArray.length;
  816:     document.$formname.$sec_element.length = 0;
  817:     if (numSections == 0) {
  818:         document.$formname.$sec_element.multiple=false;
  819:         document.$formname.$sec_element.size=1;
  820:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  821:     } else {
  822:         if (numSections == 1) {
  823:             document.$formname.$sec_element.multiple=false;
  824:             document.$formname.$sec_element.size=1;
  825:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  826:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  827:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  828:         } else {
  829:             for (var i=0; i<numSections; i++) {
  830:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  831:             }
  832:             document.$formname.$sec_element.multiple=true
  833:             if (numSections < 3) {
  834:                 document.$formname.$sec_element.size=numSections;
  835:             } else {
  836:                 document.$formname.$sec_element.size=3;
  837:             }
  838:             document.$formname.$sec_element.options[0].selected = false
  839:         }
  840:     }
  841: }
  842: 
  843: function setRole(crstype) {
  844: |;
  845:     if ($role_element eq '') {
  846:         $setsections .= '    return;
  847: }
  848: ';
  849:     } else {
  850:         $setsections .= qq|
  851:     var elementLength = document.$formname.$role_element.length;
  852:     var allroles = Array($rolestr);
  853:     var courserolenames = Array($courserolestr);
  854:     var communityrolenames = Array($communityrolestr);
  855:     if (elementLength != undefined) {
  856:         if (document.$formname.$role_element.options[5].value == 'cc') {
  857:             if (crstype == 'Course') {
  858:                 return;
  859:             } else {
  860:                 allroles[5] = 'co';
  861:                 for (var i=0; i<6; i++) {
  862:                     document.$formname.$role_element.options[i].value = allroles[i];
  863:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  864:                 }
  865:             }
  866:         } else {
  867:             if (crstype == 'Community') {
  868:                 return;
  869:             } else {
  870:                 allroles[5] = 'cc';
  871:                 for (var i=0; i<6; i++) {
  872:                     document.$formname.$role_element.options[i].value = allroles[i];
  873:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  874:                 }
  875:             }
  876:         }
  877:     }
  878:     return;
  879: }
  880: |;
  881:     }
  882:     if ($credits_element) {
  883:         $setsections .= qq|
  884: function setCredits(defaultcredits) {
  885:     document.$formname.$credits_element.value = defaultcredits;
  886:     return;
  887: }
  888: |;
  889:     }
  890:     return $setsections;
  891: }
  892: 
  893: sub selectcourse_link {
  894:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  895:        $typeelement) = @_;
  896:    my $type = $selecttype;
  897:    my $linktext = &mt('Select Course');
  898:    if ($selecttype eq 'Community') {
  899:        $linktext = &mt('Select Community');
  900:    } elsif ($selecttype eq 'Course/Community') {
  901:        $linktext = &mt('Select Course/Community');
  902:        $type = '';
  903:    } elsif ($selecttype eq 'Select') {
  904:        $linktext = &mt('Select');
  905:        $type = '';
  906:    }
  907:    return '<span class="LC_nobreak">'
  908:          ."<a href='"
  909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  912:          ."'>".$linktext.'</a>'
  913:          .'</span>';
  914: }
  915: 
  916: sub selectauthor_link {
  917:    my ($form,$udom)=@_;
  918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  919:           &mt('Select Author').'</a>';
  920: }
  921: 
  922: sub selectuser_link {
  923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  924:         $coursedom,$linktext,$caller) = @_;
  925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  927:            ');">'.$linktext.'</a>';
  928: }
  929: 
  930: sub check_uncheck_jscript {
  931:     my $jscript = <<"ENDSCRT";
  932: function checkAll(field) {
  933:     if (field.length > 0) {
  934:         for (i = 0; i < field.length; i++) {
  935:             if (!field[i].disabled) {
  936:                 field[i].checked = true;
  937:             }
  938:         }
  939:     } else {
  940:         if (!field.disabled) {
  941:             field.checked = true;
  942:         }
  943:     }
  944: }
  945:  
  946: function uncheckAll(field) {
  947:     if (field.length > 0) {
  948:         for (i = 0; i < field.length; i++) {
  949:             field[i].checked = false ;
  950:         }
  951:     } else {
  952:         field.checked = false ;
  953:     }
  954: }
  955: ENDSCRT
  956:     return $jscript;
  957: }
  958: 
  959: sub select_timezone {
  960:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
  961:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
  962:    if ($includeempty) {
  963:        $output .= '<option value=""';
  964:        if (($selected eq '') || ($selected eq 'local')) {
  965:            $output .= ' selected="selected" ';
  966:        }
  967:        $output .= '> </option>';
  968:    }
  969:    my @timezones = DateTime::TimeZone->all_names;
  970:    foreach my $tzone (@timezones) {
  971:        $output.= '<option value="'.$tzone.'"';
  972:        if ($tzone eq $selected) {
  973:            $output.=' selected="selected"';
  974:        }
  975:        $output.=">$tzone</option>\n";
  976:    }
  977:    $output.="</select>";
  978:    return $output;
  979: }
  980: 
  981: sub select_datelocale {
  982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  984:     if ($includeempty) {
  985:         $output .= '<option value=""';
  986:         if ($selected eq '') {
  987:             $output .= ' selected="selected" ';
  988:         }
  989:         $output .= '> </option>';
  990:     }
  991:     my @languages = &Apache::lonlocal::preferred_languages();
  992:     my (@possibles,%locale_names);
  993:     my @locales = DateTime::Locale->ids();
  994:     foreach my $id (@locales) {
  995:         if ($id ne '') {
  996:             my ($en_terr,$native_terr);
  997:             my $loc = DateTime::Locale->load($id);
  998:             if (ref($loc)) {
  999:                 $en_terr = $loc->name();
 1000:                 $native_terr = $loc->native_name();
 1001:                 if (grep(/^en$/,@languages) || !@languages) {
 1002:                     if ($en_terr ne '') {
 1003:                         $locale_names{$id} = '('.$en_terr.')';
 1004:                     } elsif ($native_terr ne '') {
 1005:                         $locale_names{$id} = $native_terr;
 1006:                     }
 1007:                 } else {
 1008:                     if ($native_terr ne '') {
 1009:                         $locale_names{$id} = $native_terr.' ';
 1010:                     } elsif ($en_terr ne '') {
 1011:                         $locale_names{$id} = '('.$en_terr.')';
 1012:                     }
 1013:                 }
 1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1015:                 push(@possibles,$id);
 1016:             }
 1017:         }
 1018:     }
 1019:     foreach my $item (sort(@possibles)) {
 1020:         $output.= '<option value="'.$item.'"';
 1021:         if ($item eq $selected) {
 1022:             $output.=' selected="selected"';
 1023:         }
 1024:         $output.=">$item";
 1025:         if ($locale_names{$item} ne '') {
 1026:             $output.='  '.$locale_names{$item};
 1027:         }
 1028:         $output.="</option>\n";
 1029:     }
 1030:     $output.="</select>";
 1031:     return $output;
 1032: }
 1033: 
 1034: sub select_language {
 1035:     my ($name,$selected,$includeempty,$noedit) = @_;
 1036:     my %langchoices;
 1037:     if ($includeempty) {
 1038:         %langchoices = ('' => 'No language preference');
 1039:     }
 1040:     foreach my $id (&languageids()) {
 1041:         my $code = &supportedlanguagecode($id);
 1042:         if ($code) {
 1043:             $langchoices{$code} = &plainlanguagedescription($id);
 1044:         }
 1045:     }
 1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1048: }
 1049: 
 1050: =pod
 1051: 
 1052: =item * &linked_select_forms(...)
 1053: 
 1054: linked_select_forms returns a string containing a <script></script> block
 1055: and html for two <select> menus.  The select menus will be linked in that
 1056: changing the value of the first menu will result in new values being placed
 1057: in the second menu.  The values in the select menu will appear in alphabetical
 1058: order unless a defined order is provided.
 1059: 
 1060: linked_select_forms takes the following ordered inputs:
 1061: 
 1062: =over 4
 1063: 
 1064: =item * $formname, the name of the <form> tag
 1065: 
 1066: =item * $middletext, the text which appears between the <select> tags
 1067: 
 1068: =item * $firstdefault, the default value for the first menu
 1069: 
 1070: =item * $firstselectname, the name of the first <select> tag
 1071: 
 1072: =item * $secondselectname, the name of the second <select> tag
 1073: 
 1074: =item * $hashref, a reference to a hash containing the data for the menus.
 1075: 
 1076: =item * $menuorder, the order of values in the first menu
 1077: 
 1078: =item * $onchangefirst, additional javascript call to execute for an onchange
 1079:         event for the first <select> tag
 1080: 
 1081: =item * $onchangesecond, additional javascript call to execute for an onchange
 1082:         event for the second <select> tag
 1083: 
 1084: =back 
 1085: 
 1086: Below is an example of such a hash.  Only the 'text', 'default', and 
 1087: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1088: values for the first select menu.  The text that coincides with the 
 1089: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1090: and text for the second menu are given in the hash pointed to by 
 1091: $menu{$choice1}->{'select2'}.  
 1092: 
 1093:  my %menu = ( A1 => { text =>"Choice A1" ,
 1094:                        default => "B3",
 1095:                        select2 => { 
 1096:                            B1 => "Choice B1",
 1097:                            B2 => "Choice B2",
 1098:                            B3 => "Choice B3",
 1099:                            B4 => "Choice B4"
 1100:                            },
 1101:                        order => ['B4','B3','B1','B2'],
 1102:                    },
 1103:                A2 => { text =>"Choice A2" ,
 1104:                        default => "C2",
 1105:                        select2 => { 
 1106:                            C1 => "Choice C1",
 1107:                            C2 => "Choice C2",
 1108:                            C3 => "Choice C3"
 1109:                            },
 1110:                        order => ['C2','C1','C3'],
 1111:                    },
 1112:                A3 => { text =>"Choice A3" ,
 1113:                        default => "D6",
 1114:                        select2 => { 
 1115:                            D1 => "Choice D1",
 1116:                            D2 => "Choice D2",
 1117:                            D3 => "Choice D3",
 1118:                            D4 => "Choice D4",
 1119:                            D5 => "Choice D5",
 1120:                            D6 => "Choice D6",
 1121:                            D7 => "Choice D7"
 1122:                            },
 1123:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1124:                    }
 1125:                );
 1126: 
 1127: =cut
 1128: 
 1129: sub linked_select_forms {
 1130:     my ($formname,
 1131:         $middletext,
 1132:         $firstdefault,
 1133:         $firstselectname,
 1134:         $secondselectname, 
 1135:         $hashref,
 1136:         $menuorder,
 1137:         $onchangefirst,
 1138:         $onchangesecond
 1139:         ) = @_;
 1140:     my $second = "document.$formname.$secondselectname";
 1141:     my $first = "document.$formname.$firstselectname";
 1142:     # output the javascript to do the changing
 1143:     my $result = '';
 1144:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1145:     $result.="// <![CDATA[\n";
 1146:     $result.="var select2data = new Object();\n";
 1147:     $" = '","';
 1148:     my $debug = '';
 1149:     foreach my $s1 (sort(keys(%$hashref))) {
 1150:         $result.="select2data.d_$s1 = new Object();\n";        
 1151:         $result.="select2data.d_$s1.def = new String('".
 1152:             $hashref->{$s1}->{'default'}."');\n";
 1153:         $result.="select2data.d_$s1.values = new Array(";
 1154:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1155:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1156:             @s2values = @{$hashref->{$s1}->{'order'}};
 1157:         }
 1158:         $result.="\"@s2values\");\n";
 1159:         $result.="select2data.d_$s1.texts = new Array(";        
 1160:         my @s2texts;
 1161:         foreach my $value (@s2values) {
 1162:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1163:         }
 1164:         $result.="\"@s2texts\");\n";
 1165:     }
 1166:     $"=' ';
 1167:     $result.= <<"END";
 1168: 
 1169: function select1_changed() {
 1170:     // Determine new choice
 1171:     var newvalue = "d_" + $first.value;
 1172:     // update select2
 1173:     var values     = select2data[newvalue].values;
 1174:     var texts      = select2data[newvalue].texts;
 1175:     var select2def = select2data[newvalue].def;
 1176:     var i;
 1177:     // out with the old
 1178:     for (i = 0; i < $second.options.length; i++) {
 1179:         $second.options[i] = null;
 1180:     }
 1181:     // in with the nuclear
 1182:     for (i=0;i<values.length; i++) {
 1183:         $second.options[i] = new Option(values[i]);
 1184:         $second.options[i].value = values[i];
 1185:         $second.options[i].text = texts[i];
 1186:         if (values[i] == select2def) {
 1187:             $second.options[i].selected = true;
 1188:         }
 1189:     }
 1190: }
 1191: // ]]>
 1192: </script>
 1193: END
 1194:     # output the initial values for the selection lists
 1195:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1196:     my @order = sort(keys(%{$hashref}));
 1197:     if (ref($menuorder) eq 'ARRAY') {
 1198:         @order = @{$menuorder};
 1199:     }
 1200:     foreach my $value (@order) {
 1201:         $result.="    <option value=\"$value\" ";
 1202:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1203:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1204:     }
 1205:     $result .= "</select>\n";
 1206:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1207:     $result .= $middletext;
 1208:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1209:     if ($onchangesecond) {
 1210:         $result .= ' onchange="'.$onchangesecond.'"';
 1211:     }
 1212:     $result .= ">\n";
 1213:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1214:     
 1215:     my @secondorder = sort(keys(%select2));
 1216:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1217:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1218:     }
 1219:     foreach my $value (@secondorder) {
 1220:         $result.="    <option value=\"$value\" ";        
 1221:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1222:         $result.=">".&mt($select2{$value})."</option>\n";
 1223:     }
 1224:     $result .= "</select>\n";
 1225:     #    return $debug;
 1226:     return $result;
 1227: }   #  end of sub linked_select_forms {
 1228: 
 1229: =pod
 1230: 
 1231: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
 1232: 
 1233: Returns a string corresponding to an HTML link to the given help
 1234: $topic, where $topic corresponds to the name of a .tex file in
 1235: /home/httpd/html/adm/help/tex, with underscores replaced by
 1236: spaces. 
 1237: 
 1238: $text will optionally be linked to the same topic, allowing you to
 1239: link text in addition to the graphic. If you do not want to link
 1240: text, but wish to specify one of the later parameters, pass an
 1241: empty string. 
 1242: 
 1243: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1244: the link will not open a new window. If false, the link will open
 1245: a new window using Javascript. (Default is false.) 
 1246: 
 1247: $width and $height are optional numerical parameters that will
 1248: override the width and height of the popped up window, which may
 1249: be useful for certain help topics with big pictures included.
 1250: 
 1251: $imgid is the id of the img tag used for the help icon. This may be
 1252: used in a javascript call to switch the image src.  See 
 1253: lonhtmlcommon::htmlareaselectactive() for an example.
 1254: 
 1255: $links_target will optionally be set to a target (_top, _parent or _self).
 1256: 
 1257: =cut
 1258: 
 1259: sub help_open_topic {
 1260:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
 1261:     $text = "" if (not defined $text);
 1262:     $stayOnPage = 0 if (not defined $stayOnPage);
 1263:     $width = 500 if (not defined $width);
 1264:     $height = 400 if (not defined $height);
 1265:     my $filename = $topic;
 1266:     $filename =~ s/ /_/g;
 1267: 
 1268:     my $template = "";
 1269:     my $link;
 1270:     
 1271:     $topic=~s/\W/\_/g;
 1272: 
 1273:     if (!$stayOnPage) {
 1274:         if ($env{'browser.mobile'}) {
 1275: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1276:         } else {
 1277:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1278:         }
 1279:     } elsif ($stayOnPage eq 'popup') {
 1280:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1281:     } else {
 1282: 	$link = "/adm/help/${filename}.hlp";
 1283:     }
 1284: 
 1285:     # Add the text
 1286:     my $target = ' target="_top"';
 1287:     if ($links_target) {
 1288:         $target = ' target="'.$links_target.'"';
 1289:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1290:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1291:         $target = '';
 1292:     }
 1293:     if ($text ne "") {	
 1294: 	$template.='<span class="LC_help_open_topic">'
 1295:                   .'<a'.$target.' href="'.$link.'">'
 1296:                   .$text.'</a>';
 1297:     }
 1298: 
 1299:     # (Always) Add the graphic
 1300:     my $title = &mt('Online Help');
 1301:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1302:     if ($imgid ne '') {
 1303:         $imgid = ' id="'.$imgid.'"';
 1304:     }
 1305:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1306:               .'<img src="'.$helpicon.'" border="0"'
 1307:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1308:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1309:               .' /></a>';
 1310:     if ($text ne "") {	
 1311:         $template.='</span>';
 1312:     }
 1313:     return $template;
 1314: 
 1315: }
 1316: 
 1317: # This is a quicky function for Latex cheatsheet editing, since it 
 1318: # appears in at least four places
 1319: sub helpLatexCheatsheet {
 1320:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1321:     my $out;
 1322:     my $addOther = '';
 1323:     if ($topic) {
 1324: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1325:     }
 1326:     $out = '<span>' # Start cheatsheet
 1327: 	  .$addOther
 1328:           .'<span>'
 1329: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1330: 	  .'</span> <span>'
 1331: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1332: 	  .'</span>';
 1333:     unless ($not_author) {
 1334:         $out .= ' <span>'
 1335: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1336: 	       .'</span> <span>'
 1337:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1338:                .'</span>';
 1339:     }
 1340:     $out .= '</span>'; # End cheatsheet
 1341:     return $out;
 1342: }
 1343: 
 1344: sub general_help {
 1345:     my $helptopic='Student_Intro';
 1346:     if ($env{'request.role'}=~/^(ca|au)/) {
 1347: 	$helptopic='Authoring_Intro';
 1348:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1349: 	$helptopic='Course_Coordination_Intro';
 1350:     } elsif ($env{'request.role'}=~/^dc/) {
 1351:         $helptopic='Domain_Coordination_Intro';
 1352:     }
 1353:     return $helptopic;
 1354: }
 1355: 
 1356: sub update_help_link {
 1357:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1358:     my $origurl = $ENV{'REQUEST_URI'};
 1359:     $origurl=~s|^/~|/priv/|;
 1360:     my $timestamp = time;
 1361:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1362:         $$datum = &escape($$datum);
 1363:     }
 1364: 
 1365:     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";
 1366:     my $output .= <<"ENDOUTPUT";
 1367: <script type="text/javascript">
 1368: // <![CDATA[
 1369: banner_link = '$banner_link';
 1370: // ]]>
 1371: </script>
 1372: ENDOUTPUT
 1373:     return $output;
 1374: }
 1375: 
 1376: # now just updates the help link and generates a blue icon
 1377: sub help_open_menu {
 1378:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
 1379: 	= @_;    
 1380:     $stayOnPage = 1;
 1381:     my $output;
 1382:     if ($component_help) {
 1383: 	if (!$text) {
 1384: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1385: 				       $width,$height,'',$links_target);
 1386: 	} else {
 1387: 	    my $help_text;
 1388: 	    $help_text=&unescape($topic);
 1389: 	    $output='<table><tr><td>'.
 1390: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1391: 				 $width,$height,'',$links_target).'</td></tr></table>';
 1392: 	}
 1393:     }
 1394:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1395:     return $output.$banner_link;
 1396: }
 1397: 
 1398: sub top_nav_help {
 1399:     my ($text,$linkattr) = @_;
 1400:     $text = &mt($text);
 1401:     my $stay_on_page;
 1402:     unless ($env{'environment.remote'} eq 'on') {
 1403:         $stay_on_page = 1;
 1404:     }
 1405:     my ($link,$banner_link);
 1406:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1407:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1408: 	                         : "javascript:helpMenu('open')";
 1409:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1410:     }
 1411:     my $title = &mt('Get help');
 1412:     if ($link) {
 1413:         return <<"END";
 1414: $banner_link
 1415: <a href="$link" title="$title" $linkattr>$text</a>
 1416: END
 1417:     } else {
 1418:         return '&nbsp;'.$text.'&nbsp;';
 1419:     }
 1420: }
 1421: 
 1422: sub help_menu_js {
 1423:     my ($httphost) = @_;
 1424:     my $stayOnPage = 1;
 1425:     my $width = 620;
 1426:     my $height = 600;
 1427:     my $helptopic=&general_help();
 1428:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1429:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1430:     my $start_page =
 1431:         &Apache::loncommon::start_page('Help Menu', undef,
 1432: 				       {'frameset'    => 1,
 1433: 					'js_ready'    => 1,
 1434:                                         'use_absolute' => $httphost,
 1435: 					'add_entries' => {
 1436: 					    'border' => '0',
 1437: 					    'rows'   => "110,*",},});
 1438:     my $end_page =
 1439:         &Apache::loncommon::end_page({'frameset' => 1,
 1440: 				      'js_ready' => 1,});
 1441: 
 1442:     my $template .= <<"ENDTEMPLATE";
 1443: <script type="text/javascript">
 1444: // <![CDATA[
 1445: // <!-- BEGIN LON-CAPA Internal
 1446: var banner_link = '';
 1447: function helpMenu(target) {
 1448:     var caller = this;
 1449:     if (target == 'open') {
 1450:         var newWindow = null;
 1451:         try {
 1452:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1453:         }
 1454:         catch(error) {
 1455:             writeHelp(caller);
 1456:             return;
 1457:         }
 1458:         if (newWindow) {
 1459:             caller = newWindow;
 1460:         }
 1461:     }
 1462:     writeHelp(caller);
 1463:     return;
 1464: }
 1465: function writeHelp(caller) {
 1466:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1467:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1468:     caller.document.close();
 1469:     caller.focus();
 1470: }
 1471: // END LON-CAPA Internal -->
 1472: // ]]>
 1473: </script>
 1474: ENDTEMPLATE
 1475:     return $template;
 1476: }
 1477: 
 1478: sub help_open_bug {
 1479:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1480:     unless ($env{'user.adv'}) { return ''; }
 1481:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1482:     $text = "" if (not defined $text);
 1483: 	$stayOnPage=1;
 1484:     $width = 600 if (not defined $width);
 1485:     $height = 600 if (not defined $height);
 1486: 
 1487:     $topic=~s/\W+/\+/g;
 1488:     my $link='';
 1489:     my $template='';
 1490:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1491: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1492:     if (!$stayOnPage)
 1493:     {
 1494: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1495:     }
 1496:     else
 1497:     {
 1498: 	$link = $url;
 1499:     }
 1500: 
 1501:     my $target = '_top';
 1502:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1503:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1504:         $target = '_blank';
 1505:     }
 1506: 
 1507:     # Add the text
 1508:     if ($text ne "")
 1509:     {
 1510: 	$template .= 
 1511:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1512:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1513:     }
 1514: 
 1515:     # Add the graphic
 1516:     my $title = &mt('Report a Bug');
 1517:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1518:     $template .= <<"ENDTEMPLATE";
 1519:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1520: ENDTEMPLATE
 1521:     if ($text ne '') { $template.='</td></tr></table>' };
 1522:     return $template;
 1523: 
 1524: }
 1525: 
 1526: sub help_open_faq {
 1527:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1528:     unless ($env{'user.adv'}) { return ''; }
 1529:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1530:     $text = "" if (not defined $text);
 1531: 	$stayOnPage=1;
 1532:     $width = 350 if (not defined $width);
 1533:     $height = 400 if (not defined $height);
 1534: 
 1535:     $topic=~s/\W+/\+/g;
 1536:     my $link='';
 1537:     my $template='';
 1538:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1539:     if (!$stayOnPage)
 1540:     {
 1541: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1542:     }
 1543:     else
 1544:     {
 1545: 	$link = $url;
 1546:     }
 1547: 
 1548:     # Add the text
 1549:     if ($text ne "")
 1550:     {
 1551: 	$template .= 
 1552:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1553:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1554:     }
 1555: 
 1556:     # Add the graphic
 1557:     my $title = &mt('View the FAQ');
 1558:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1559:     $template .= <<"ENDTEMPLATE";
 1560:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1561: ENDTEMPLATE
 1562:     if ($text ne '') { $template.='</td></tr></table>' };
 1563:     return $template;
 1564: 
 1565: }
 1566: 
 1567: ###############################################################
 1568: ###############################################################
 1569: 
 1570: =pod
 1571: 
 1572: =item * &change_content_javascript():
 1573: 
 1574: This and the next function allow you to create small sections of an
 1575: otherwise static HTML page that you can update on the fly with
 1576: Javascript, even in Netscape 4.
 1577: 
 1578: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1579: must be written to the HTML page once. It will prove the Javascript
 1580: function "change(name, content)". Calling the change function with the
 1581: name of the section 
 1582: you want to update, matching the name passed to C<changable_area>, and
 1583: the new content you want to put in there, will put the content into
 1584: that area.
 1585: 
 1586: B<Note>: Netscape 4 only reserves enough space for the changable area
 1587: to contain room for the original contents. You need to "make space"
 1588: for whatever changes you wish to make, and be B<sure> to check your
 1589: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1590: it's adequate for updating a one-line status display, but little more.
 1591: This script will set the space to 100% width, so you only need to
 1592: worry about height in Netscape 4.
 1593: 
 1594: Modern browsers are much less limiting, and if you can commit to the
 1595: user not using Netscape 4, this feature may be used freely with
 1596: pretty much any HTML.
 1597: 
 1598: =cut
 1599: 
 1600: sub change_content_javascript {
 1601:     # If we're on Netscape 4, we need to use Layer-based code
 1602:     if ($env{'browser.type'} eq 'netscape' &&
 1603: 	$env{'browser.version'} =~ /^4\./) {
 1604: 	return (<<NETSCAPE4);
 1605: 	function change(name, content) {
 1606: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1607: 	    doc.open();
 1608: 	    doc.write(content);
 1609: 	    doc.close();
 1610: 	}
 1611: NETSCAPE4
 1612:     } else {
 1613: 	# Otherwise, we need to use semi-standards-compliant code
 1614: 	# (technically, "innerHTML" isn't standard but the equivalent
 1615: 	# is really scary, and every useful browser supports it
 1616: 	return (<<DOMBASED);
 1617: 	function change(name, content) {
 1618: 	    element = document.getElementById(name);
 1619: 	    element.innerHTML = content;
 1620: 	}
 1621: DOMBASED
 1622:     }
 1623: }
 1624: 
 1625: =pod
 1626: 
 1627: =item * &changable_area($name,$origContent):
 1628: 
 1629: This provides a "changable area" that can be modified on the fly via
 1630: the Javascript code provided in C<change_content_javascript>. $name is
 1631: the name you will use to reference the area later; do not repeat the
 1632: same name on a given HTML page more then once. $origContent is what
 1633: the area will originally contain, which can be left blank.
 1634: 
 1635: =cut
 1636: 
 1637: sub changable_area {
 1638:     my ($name, $origContent) = @_;
 1639: 
 1640:     if ($env{'browser.type'} eq 'netscape' &&
 1641: 	$env{'browser.version'} =~ /^4\./) {
 1642: 	# If this is netscape 4, we need to use the Layer tag
 1643: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1644:     } else {
 1645: 	return "<span id='$name'>$origContent</span>";
 1646:     }
 1647: }
 1648: 
 1649: =pod
 1650: 
 1651: =item * &viewport_geometry_js 
 1652: 
 1653: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1654: 
 1655: =cut
 1656: 
 1657: 
 1658: sub viewport_geometry_js { 
 1659:     return <<"GEOMETRY";
 1660: var Geometry = {};
 1661: function init_geometry() {
 1662:     if (Geometry.init) { return };
 1663:     Geometry.init=1;
 1664:     if (window.innerHeight) {
 1665:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1666:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1667:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1668:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1669:     }
 1670:     else if (document.documentElement && document.documentElement.clientHeight) {
 1671:         Geometry.getViewportHeight =
 1672:             function() { return document.documentElement.clientHeight; };
 1673:         Geometry.getViewportWidth =
 1674:             function() { return document.documentElement.clientWidth; };
 1675: 
 1676:         Geometry.getHorizontalScroll =
 1677:             function() { return document.documentElement.scrollLeft; };
 1678:         Geometry.getVerticalScroll =
 1679:             function() { return document.documentElement.scrollTop; };
 1680:     }
 1681:     else if (document.body.clientHeight) {
 1682:         Geometry.getViewportHeight =
 1683:             function() { return document.body.clientHeight; };
 1684:         Geometry.getViewportWidth =
 1685:             function() { return document.body.clientWidth; };
 1686:         Geometry.getHorizontalScroll =
 1687:             function() { return document.body.scrollLeft; };
 1688:         Geometry.getVerticalScroll =
 1689:             function() { return document.body.scrollTop; };
 1690:     }
 1691: }
 1692: 
 1693: GEOMETRY
 1694: }
 1695: 
 1696: =pod
 1697: 
 1698: =item * &viewport_size_js()
 1699: 
 1700: 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. 
 1701: 
 1702: =cut
 1703: 
 1704: sub viewport_size_js {
 1705:     my $geometry = &viewport_geometry_js();
 1706:     return <<"DIMS";
 1707: 
 1708: $geometry
 1709: 
 1710: function getViewportDims(width,height) {
 1711:     init_geometry();
 1712:     width.value = Geometry.getViewportWidth();
 1713:     height.value = Geometry.getViewportHeight();
 1714:     return;
 1715: }
 1716: 
 1717: DIMS
 1718: }
 1719: 
 1720: =pod
 1721: 
 1722: =item * &resize_textarea_js()
 1723: 
 1724: emits the needed javascript to resize a textarea to be as big as possible
 1725: 
 1726: creates a function resize_textrea that takes two IDs first should be
 1727: the id of the element to resize, second should be the id of a div that
 1728: surrounds everything that comes after the textarea, this routine needs
 1729: to be attached to the <body> for the onload and onresize events.
 1730: 
 1731: =back
 1732: 
 1733: =cut
 1734: 
 1735: sub resize_textarea_js {
 1736:     my $geometry = &viewport_geometry_js();
 1737:     return <<"RESIZE";
 1738:     <script type="text/javascript">
 1739: // <![CDATA[
 1740: $geometry
 1741: 
 1742: function getX(element) {
 1743:     var x = 0;
 1744:     while (element) {
 1745: 	x += element.offsetLeft;
 1746: 	element = element.offsetParent;
 1747:     }
 1748:     return x;
 1749: }
 1750: function getY(element) {
 1751:     var y = 0;
 1752:     while (element) {
 1753: 	y += element.offsetTop;
 1754: 	element = element.offsetParent;
 1755:     }
 1756:     return y;
 1757: }
 1758: 
 1759: 
 1760: function resize_textarea(textarea_id,bottom_id) {
 1761:     init_geometry();
 1762:     var textarea        = document.getElementById(textarea_id);
 1763:     //alert(textarea);
 1764: 
 1765:     var textarea_top    = getY(textarea);
 1766:     var textarea_height = textarea.offsetHeight;
 1767:     var bottom          = document.getElementById(bottom_id);
 1768:     var bottom_top      = getY(bottom);
 1769:     var bottom_height   = bottom.offsetHeight;
 1770:     var window_height   = Geometry.getViewportHeight();
 1771:     var fudge           = 23;
 1772:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1773:     if (new_height < 300) {
 1774: 	new_height = 300;
 1775:     }
 1776:     textarea.style.height=new_height+'px';
 1777: }
 1778: // ]]>
 1779: </script>
 1780: RESIZE
 1781: 
 1782: }
 1783: 
 1784: sub colorfuleditor_js {
 1785:     return <<"COLORFULEDIT"
 1786: <script type="text/javascript">
 1787: // <![CDATA[>
 1788:     function fold_box(curDepth, lastresource){
 1789: 
 1790:     // we need a list because there can be several blocks you need to fold in one tag
 1791:         var block = document.getElementsByName('foldblock_'+curDepth);
 1792:     // but there is only one folding button per tag
 1793:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1794: 
 1795:         if(block.item(0).style.display == 'none'){
 1796: 
 1797:             foldbutton.value = '@{[&mt("Hide")]}';
 1798:             for (i = 0; i < block.length; i++){
 1799:                 block.item(i).style.display = '';
 1800:             }
 1801:         }else{
 1802: 
 1803:             foldbutton.value = '@{[&mt("Show")]}';
 1804:             for (i = 0; i < block.length; i++){
 1805:                 // block.item(i).style.visibility = 'collapse';
 1806:                 block.item(i).style.display = 'none';
 1807:             }
 1808:         };
 1809:         saveState(lastresource);
 1810:     }
 1811: 
 1812:     function saveState (lastresource) {
 1813: 
 1814:         var tag_list = getTagList();
 1815:         if(tag_list != null){
 1816:             var timestamp = new Date().getTime();
 1817:             var key = lastresource;
 1818: 
 1819:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1820:             // starting with timestamp
 1821:             var value = timestamp+';';
 1822: 
 1823:             // building the list of key-value pairs
 1824:             for(var i = 0; i < tag_list.length; i++){
 1825:                 value += tag_list[i]+',';
 1826:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1827:             }
 1828: 
 1829:             // only iterate whole storage if nothing to override
 1830:             if(localStorage.getItem(key) == null){
 1831: 
 1832:                 // prevent storage from growing large
 1833:                 if(localStorage.length > 50){
 1834:                     var regex_getTimestamp = /^(?:\d)+;/;
 1835:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1836:                     var oldest_key;
 1837: 
 1838:                     for(var i = 1; i < localStorage.length; i++){
 1839:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1840:                             oldest_key = localStorage.key(i);
 1841:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1842:                         }
 1843:                     }
 1844:                     localStorage.removeItem(oldest_key);
 1845:                 }
 1846:             }
 1847:             localStorage.setItem(key,value);
 1848:         }
 1849:     }
 1850: 
 1851:     // restore folding status of blocks (on page load)
 1852:     function restoreState (lastresource) {
 1853:         if(localStorage.getItem(lastresource) != null){
 1854:             var key = lastresource;
 1855:             var value = localStorage.getItem(key);
 1856:             var regex_delTimestamp = /^\d+;/;
 1857: 
 1858:             value.replace(regex_delTimestamp, '');
 1859: 
 1860:             var valueArr = value.split(';');
 1861:             var pairs;
 1862:             var elements;
 1863:             for (var i = 0; i < valueArr.length; i++){
 1864:                 pairs = valueArr[i].split(',');
 1865:                 elements = document.getElementsByName(pairs[0]);
 1866: 
 1867:                 for (var j = 0; j < elements.length; j++){
 1868:                     elements[j].style.display = pairs[1];
 1869:                     if (pairs[1] == "none"){
 1870:                         var regex_id = /([_\\d]+)\$/;
 1871:                         regex_id.exec(pairs[0]);
 1872:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1873:                     }
 1874:                 }
 1875:             }
 1876:         }
 1877:     }
 1878: 
 1879:     function getTagList () {
 1880: 
 1881:         var stringToSearch = document.lonhomework.innerHTML;
 1882: 
 1883:         var ret = new Array();
 1884:         var regex_findBlock = /(foldblock_.*?)"/g;
 1885:         var tag_list = stringToSearch.match(regex_findBlock);
 1886: 
 1887:         if(tag_list != null){
 1888:             for(var i = 0; i < tag_list.length; i++){
 1889:                 ret.push(tag_list[i].replace(/"/, ''));
 1890:             }
 1891:         }
 1892:         return ret;
 1893:     }
 1894: 
 1895:     function saveScrollPosition (resource) {
 1896:         var tag_list = getTagList();
 1897: 
 1898:         // we dont always want to jump to the first block
 1899:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1900:         if(\$(window).scrollTop() > 170){
 1901:             if(tag_list != null){
 1902:                 var result;
 1903:                 for(var i = 0; i < tag_list.length; i++){
 1904:                     if(isElementInViewport(tag_list[i])){
 1905:                         result += tag_list[i]+';';
 1906:                     }
 1907:                 }
 1908:                 sessionStorage.setItem('anchor_'+resource, result);
 1909:             }
 1910:         } else {
 1911:             // we dont need to save zero, just delete the item to leave everything tidy
 1912:             sessionStorage.removeItem('anchor_'+resource);
 1913:         }
 1914:     }
 1915: 
 1916:     function restoreScrollPosition(resource){
 1917: 
 1918:         var elem = sessionStorage.getItem('anchor_'+resource);
 1919:         if(elem != null){
 1920:             var tag_list = elem.split(';');
 1921:             var elem_list;
 1922: 
 1923:             for(var i = 0; i < tag_list.length; i++){
 1924:                 elem_list = document.getElementsByName(tag_list[i]);
 1925: 
 1926:                 if(elem_list.length > 0){
 1927:                     elem = elem_list[0];
 1928:                     break;
 1929:                 }
 1930:             }
 1931:             elem.scrollIntoView();
 1932:         }
 1933:     }
 1934: 
 1935:     function isElementInViewport(el) {
 1936: 
 1937:         // change to last element instead of first
 1938:         var elem = document.getElementsByName(el);
 1939:         var rect = elem[0].getBoundingClientRect();
 1940: 
 1941:         return (
 1942:             rect.top >= 0 &&
 1943:             rect.left >= 0 &&
 1944:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1945:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1946:         );
 1947:     }
 1948: 
 1949:     function autosize(depth){
 1950:         var cmInst = window['cm'+depth];
 1951:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1952: 
 1953:         // is fixed size, switching to dynamic
 1954:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1955:             cmInst.setSize("","auto");
 1956:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1957:             sessionStorage.setItem("autosized_"+depth, "yes");
 1958: 
 1959:         // is dynamic size, switching to fixed
 1960:         } else {
 1961:             cmInst.setSize("","300px");
 1962:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1963:             sessionStorage.removeItem("autosized_"+depth);
 1964:         }
 1965:     }
 1966: 
 1967: 
 1968: 
 1969: // ]]>
 1970: </script>
 1971: COLORFULEDIT
 1972: }
 1973: 
 1974: sub xmleditor_js {
 1975:     return <<XMLEDIT
 1976: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1977: <script type="text/javascript">
 1978: // <![CDATA[>
 1979: 
 1980:     function saveScrollPosition (resource) {
 1981: 
 1982:         var scrollPos = \$(window).scrollTop();
 1983:         sessionStorage.setItem(resource,scrollPos);
 1984:     }
 1985: 
 1986:     function restoreScrollPosition(resource){
 1987: 
 1988:         var scrollPos = sessionStorage.getItem(resource);
 1989:         \$(window).scrollTop(scrollPos);
 1990:     }
 1991: 
 1992:     // unless internet explorer
 1993:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1994: 
 1995:         \$(document).ready(function() {
 1996:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1997:         });
 1998:     }
 1999: 
 2000:     // inserts text at cursor position into codemirror (xml editor only)
 2001:     function insertText(text){
 2002:         cm.focus();
 2003:         var curPos = cm.getCursor();
 2004:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2005:     }
 2006: // ]]>
 2007: </script>
 2008: XMLEDIT
 2009: }
 2010: 
 2011: sub insert_folding_button {
 2012:     my $curDepth = $Apache::lonxml::curdepth;
 2013:     my $lastresource = $env{'request.ambiguous'};
 2014: 
 2015:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 2016:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2017: }
 2018: 
 2019: 
 2020: =pod
 2021: 
 2022: =head1 Excel and CSV file utility routines
 2023: 
 2024: =cut
 2025: 
 2026: ###############################################################
 2027: ###############################################################
 2028: 
 2029: =pod
 2030: 
 2031: =over 4
 2032: 
 2033: =item * &csv_translate($text) 
 2034: 
 2035: Translate $text to allow it to be output as a 'comma separated values' 
 2036: format.
 2037: 
 2038: =cut
 2039: 
 2040: ###############################################################
 2041: ###############################################################
 2042: sub csv_translate {
 2043:     my $text = shift;
 2044:     $text =~ s/\"/\"\"/g;
 2045:     $text =~ s/\n/ /g;
 2046:     return $text;
 2047: }
 2048: 
 2049: ###############################################################
 2050: ###############################################################
 2051: 
 2052: =pod
 2053: 
 2054: =item * &define_excel_formats()
 2055: 
 2056: Define some commonly used Excel cell formats.
 2057: 
 2058: Currently supported formats:
 2059: 
 2060: =over 4
 2061: 
 2062: =item header
 2063: 
 2064: =item bold
 2065: 
 2066: =item h1
 2067: 
 2068: =item h2
 2069: 
 2070: =item h3
 2071: 
 2072: =item h4
 2073: 
 2074: =item i
 2075: 
 2076: =item date
 2077: 
 2078: =back
 2079: 
 2080: Inputs: $workbook
 2081: 
 2082: Returns: $format, a hash reference.
 2083: 
 2084: 
 2085: =cut
 2086: 
 2087: ###############################################################
 2088: ###############################################################
 2089: sub define_excel_formats {
 2090:     my ($workbook) = @_;
 2091:     my $format;
 2092:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2093:                                                 bottom    => 1,
 2094:                                                 align     => 'center');
 2095:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2096:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2097:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2098:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2099:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2100:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2101:     $format->{'date'} = $workbook->add_format(num_format=>
 2102:                                             'mm/dd/yyyy hh:mm:ss');
 2103:     return $format;
 2104: }
 2105: 
 2106: ###############################################################
 2107: ###############################################################
 2108: 
 2109: =pod
 2110: 
 2111: =item * &create_workbook()
 2112: 
 2113: Create an Excel worksheet.  If it fails, output message on the
 2114: request object and return undefs.
 2115: 
 2116: Inputs: Apache request object
 2117: 
 2118: Returns (undef) on failure, 
 2119:     Excel worksheet object, scalar with filename, and formats 
 2120:     from &Apache::loncommon::define_excel_formats on success
 2121: 
 2122: =cut
 2123: 
 2124: ###############################################################
 2125: ###############################################################
 2126: sub create_workbook {
 2127:     my ($r) = @_;
 2128:         #
 2129:     # Create the excel spreadsheet
 2130:     my $filename = '/prtspool/'.
 2131:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2132:         time.'_'.rand(1000000000).'.xls';
 2133:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2134:     if (! defined($workbook)) {
 2135:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2136:         $r->print(
 2137:             '<p class="LC_error">'
 2138:            .&mt('Problems occurred in creating the new Excel file.')
 2139:            .' '.&mt('This error has been logged.')
 2140:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2141:            .'</p>'
 2142:         );
 2143:         return (undef);
 2144:     }
 2145:     #
 2146:     $workbook->set_tempdir(LONCAPA::tempdir());
 2147:     #
 2148:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2149:     return ($workbook,$filename,$format);
 2150: }
 2151: 
 2152: ###############################################################
 2153: ###############################################################
 2154: 
 2155: =pod
 2156: 
 2157: =item * &create_text_file()
 2158: 
 2159: Create a file to write to and eventually make available to the user.
 2160: If file creation fails, outputs an error message on the request object and 
 2161: return undefs.
 2162: 
 2163: Inputs: Apache request object, and file suffix
 2164: 
 2165: Returns (undef) on failure, 
 2166:     Filehandle and filename on success.
 2167: 
 2168: =cut
 2169: 
 2170: ###############################################################
 2171: ###############################################################
 2172: sub create_text_file {
 2173:     my ($r,$suffix) = @_;
 2174:     if (! defined($suffix)) { $suffix = 'txt'; };
 2175:     my $fh;
 2176:     my $filename = '/prtspool/'.
 2177:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2178:         time.'_'.rand(1000000000).'.'.$suffix;
 2179:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2180:     if (! defined($fh)) {
 2181:         $r->log_error("Couldn't open $filename for output $!");
 2182:         $r->print(
 2183:             '<p class="LC_error">'
 2184:            .&mt('Problems occurred in creating the output file.')
 2185:            .' '.&mt('This error has been logged.')
 2186:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2187:            .'</p>'
 2188:         );
 2189:     }
 2190:     return ($fh,$filename)
 2191: }
 2192: 
 2193: 
 2194: =pod 
 2195: 
 2196: =back
 2197: 
 2198: =cut
 2199: 
 2200: ###############################################################
 2201: ##        Home server <option> list generating code          ##
 2202: ###############################################################
 2203: 
 2204: # ------------------------------------------
 2205: 
 2206: sub domain_select {
 2207:     my ($name,$value,$multiple)=@_;
 2208:     my %domains=map { 
 2209: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2210:     } &Apache::lonnet::all_domains();
 2211:     if ($multiple) {
 2212: 	$domains{''}=&mt('Any domain');
 2213: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2214: 	return &multiple_select_form($name,$value,4,\%domains);
 2215:     } else {
 2216: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2217: 	return &select_form($name,$value,\%domains);
 2218:     }
 2219: }
 2220: 
 2221: #-------------------------------------------
 2222: 
 2223: =pod
 2224: 
 2225: =head1 Routines for form select boxes
 2226: 
 2227: =over 4
 2228: 
 2229: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2230: 
 2231: Returns a string containing a <select> element int multiple mode
 2232: 
 2233: 
 2234: Args:
 2235:   $name - name of the <select> element
 2236:   $value - scalar or array ref of values that should already be selected
 2237:   $size - number of rows long the select element is
 2238:   $hash - the elements should be 'option' => 'shown text'
 2239:           (shown text should already have been &mt())
 2240:   $order - (optional) array ref of the order to show the elements in
 2241: 
 2242: =cut
 2243: 
 2244: #-------------------------------------------
 2245: sub multiple_select_form {
 2246:     my ($name,$value,$size,$hash,$order)=@_;
 2247:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2248:     my $output='';
 2249:     if (! defined($size)) {
 2250:         $size = 4;
 2251:         if (scalar(keys(%$hash))<4) {
 2252:             $size = scalar(keys(%$hash));
 2253:         }
 2254:     }
 2255:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2256:     my @order;
 2257:     if (ref($order) eq 'ARRAY')  {
 2258:         @order = @{$order};
 2259:     } else {
 2260:         @order = sort(keys(%$hash));
 2261:     }
 2262:     if (exists($$hash{'select_form_order'})) {
 2263:         @order = @{$$hash{'select_form_order'}};
 2264:     }
 2265:         
 2266:     foreach my $key (@order) {
 2267:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2268:         $output.='selected="selected" ' if ($selected{$key});
 2269:         $output.='>'.$hash->{$key}."</option>\n";
 2270:     }
 2271:     $output.="</select>\n";
 2272:     return $output;
 2273: }
 2274: 
 2275: #-------------------------------------------
 2276: 
 2277: =pod
 2278: 
 2279: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2280: 
 2281: Returns a string containing a <select name='$name' size='1'> form to 
 2282: allow a user to select options from a ref to a hash containing:
 2283: option_name => displayed text. An optional $onchange can include
 2284: a javascript onchange item, e.g., onchange="this.form.submit();".
 2285: An optional arg -- $readonly -- if true will cause the select form
 2286: to be disabled, e.g., for the case where an instructor has a section-
 2287: specific role, and is viewing/modifying parameters.  
 2288: 
 2289: See lonrights.pm for an example invocation and use.
 2290: 
 2291: =cut
 2292: 
 2293: #-------------------------------------------
 2294: sub select_form {
 2295:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2296:     return unless (ref($hashref) eq 'HASH');
 2297:     if ($onchange) {
 2298:         $onchange = ' onchange="'.$onchange.'"';
 2299:     }
 2300:     my $disabled;
 2301:     if ($readonly) {
 2302:         $disabled = ' disabled="disabled"';
 2303:     }
 2304:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2305:     my @keys;
 2306:     if (exists($hashref->{'select_form_order'})) {
 2307: 	@keys=@{$hashref->{'select_form_order'}};
 2308:     } else {
 2309: 	@keys=sort(keys(%{$hashref}));
 2310:     }
 2311:     foreach my $key (@keys) {
 2312:         $selectform.=
 2313: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2314:             ($key eq $def ? 'selected="selected" ' : '').
 2315:                 ">".$hashref->{$key}."</option>\n";
 2316:     }
 2317:     $selectform.="</select>";
 2318:     return $selectform;
 2319: }
 2320: 
 2321: # For display filters
 2322: 
 2323: sub display_filter {
 2324:     my ($context) = @_;
 2325:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2326:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2327:     my $phraseinput = 'hidden';
 2328:     my $includeinput = 'hidden';
 2329:     my ($checked,$includetypestext);
 2330:     if ($env{'form.displayfilter'} eq 'containing') {
 2331:         $phraseinput = 'text'; 
 2332:         if ($context eq 'parmslog') {
 2333:             $includeinput = 'checkbox';
 2334:             if ($env{'form.includetypes'}) {
 2335:                 $checked = ' checked="checked"';
 2336:             }
 2337:             $includetypestext = &mt('Include parameter types');
 2338:         }
 2339:     } else {
 2340:         $includetypestext = '&nbsp;';
 2341:     }
 2342:     my ($additional,$secondid,$thirdid);
 2343:     if ($context eq 'parmslog') {
 2344:         $additional = 
 2345:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2346:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2347:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2348:             '</label>';
 2349:         $secondid = 'includetypes';
 2350:         $thirdid = 'includetypestext';
 2351:     }
 2352:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2353:                                                     '$secondid','$thirdid')";
 2354:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2355: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2356: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2357: 	   '</label></span> <span class="LC_nobreak">'.
 2358:            &mt('Filter: [_1]',
 2359: 	   &select_form($env{'form.displayfilter'},
 2360: 			'displayfilter',
 2361: 			{'currentfolder' => 'Current folder/page',
 2362: 			 'containing' => 'Containing phrase',
 2363: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2364: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2365:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2366:                          '" />'.$additional;
 2367: }
 2368: 
 2369: sub display_filter_js {
 2370:     my $includetext = &mt('Include parameter types');
 2371:     return <<"ENDJS";
 2372:   
 2373: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2374:     var firstType = 'hidden';
 2375:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2376:         firstType = 'text';
 2377:     }
 2378:     firstObject = document.getElementById(firstid);
 2379:     if (typeof(firstObject) == 'object') {
 2380:         if (firstObject.type != firstType) {
 2381:             changeInputType(firstObject,firstType);
 2382:         }
 2383:     }
 2384:     if (context == 'parmslog') {
 2385:         var secondType = 'hidden';
 2386:         if (firstType == 'text') {
 2387:             secondType = 'checkbox';
 2388:         }
 2389:         secondObject = document.getElementById(secondid);  
 2390:         if (typeof(secondObject) == 'object') {
 2391:             if (secondObject.type != secondType) {
 2392:                 changeInputType(secondObject,secondType);
 2393:             }
 2394:         }
 2395:         var textItem = document.getElementById(thirdid);
 2396:         var currtext = textItem.innerHTML;
 2397:         var newtext;
 2398:         if (firstType == 'text') {
 2399:             newtext = '$includetext';
 2400:         } else {
 2401:             newtext = '&nbsp;';
 2402:         }
 2403:         if (currtext != newtext) {
 2404:             textItem.innerHTML = newtext;
 2405:         }
 2406:     }
 2407:     return;
 2408: }
 2409: 
 2410: function changeInputType(oldObject,newType) {
 2411:     var newObject = document.createElement('input');
 2412:     newObject.type = newType;
 2413:     if (oldObject.size) {
 2414:         newObject.size = oldObject.size;
 2415:     }
 2416:     if (oldObject.value) {
 2417:         newObject.value = oldObject.value;
 2418:     }
 2419:     if (oldObject.name) {
 2420:         newObject.name = oldObject.name;
 2421:     }
 2422:     if (oldObject.id) {
 2423:         newObject.id = oldObject.id;
 2424:     }
 2425:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2426:     return;
 2427: }
 2428: 
 2429: ENDJS
 2430: }
 2431: 
 2432: sub gradeleveldescription {
 2433:     my $gradelevel=shift;
 2434:     my %gradelevels=(0 => 'Not specified',
 2435: 		     1 => 'Grade 1',
 2436: 		     2 => 'Grade 2',
 2437: 		     3 => 'Grade 3',
 2438: 		     4 => 'Grade 4',
 2439: 		     5 => 'Grade 5',
 2440: 		     6 => 'Grade 6',
 2441: 		     7 => 'Grade 7',
 2442: 		     8 => 'Grade 8',
 2443: 		     9 => 'Grade 9',
 2444: 		     10 => 'Grade 10',
 2445: 		     11 => 'Grade 11',
 2446: 		     12 => 'Grade 12',
 2447: 		     13 => 'Grade 13',
 2448: 		     14 => '100 Level',
 2449: 		     15 => '200 Level',
 2450: 		     16 => '300 Level',
 2451: 		     17 => '400 Level',
 2452: 		     18 => 'Graduate Level');
 2453:     return &mt($gradelevels{$gradelevel});
 2454: }
 2455: 
 2456: sub select_level_form {
 2457:     my ($deflevel,$name)=@_;
 2458:     unless ($deflevel) { $deflevel=0; }
 2459:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2460:     for (my $i=0; $i<=18; $i++) {
 2461:         $selectform.="<option value=\"$i\" ".
 2462:             ($i==$deflevel ? 'selected="selected" ' : '').
 2463:                 ">".&gradeleveldescription($i)."</option>\n";
 2464:     }
 2465:     $selectform.="</select>";
 2466:     return $selectform;
 2467: }
 2468: 
 2469: #-------------------------------------------
 2470: 
 2471: =pod
 2472: 
 2473: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2474: 
 2475: Returns a string containing a <select name='$name' size='1'> form to 
 2476: allow a user to select the domain to preform an operation in.  
 2477: See loncreateuser.pm for an example invocation and use.
 2478: 
 2479: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2480: selected");
 2481: 
 2482: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2483: 
 2484: 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.
 2485: 
 2486: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2487: 
 2488: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2489: 
 2490: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
 2491: 
 2492: =cut
 2493: 
 2494: #-------------------------------------------
 2495: sub select_dom_form {
 2496:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2497:     if ($onchange) {
 2498:         $onchange = ' onchange="'.$onchange.'"';
 2499:     }
 2500:     if ($disabled) {
 2501:         $disabled = ' disabled="disabled"';
 2502:     }
 2503:     my (@domains,%exclude);
 2504:     if (ref($incdoms) eq 'ARRAY') {
 2505:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2506:     } else {
 2507:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2508:     }
 2509:     if ($includeempty) { @domains=('',@domains); }
 2510:     if (ref($excdoms) eq 'ARRAY') {
 2511:         map { $exclude{$_} = 1; } @{$excdoms};
 2512:     }
 2513:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2514:     foreach my $dom (@domains) {
 2515:         next if ($exclude{$dom});
 2516:         $selectdomain.="<option value=\"$dom\" ".
 2517:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2518:         if ($showdomdesc) {
 2519:             if ($dom ne '') {
 2520:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2521:                 if ($domdesc ne '') {
 2522:                     $selectdomain .= ' ('.$domdesc.')';
 2523:                 }
 2524:             } 
 2525:         }
 2526:         $selectdomain .= "</option>\n";
 2527:     }
 2528:     $selectdomain.="</select>";
 2529:     return $selectdomain;
 2530: }
 2531: 
 2532: #-------------------------------------------
 2533: 
 2534: =pod
 2535: 
 2536: =item * &home_server_form_item($domain,$name,$defaultflag)
 2537: 
 2538: input: 4 arguments (two required, two optional) - 
 2539:     $domain - domain of new user
 2540:     $name - name of form element
 2541:     $default - Value of 'default' causes a default item to be first 
 2542:                             option, and selected by default. 
 2543:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2544:                             if 1 server found, or default, if 0 found.
 2545: output: returns 2 items: 
 2546: (a) form element which contains either:
 2547:    (i) <select name="$name">
 2548:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2549:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2550:        </select>
 2551:        form item if there are multiple library servers in $domain, or
 2552:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2553:        if there is only one library server in $domain.
 2554: 
 2555: (b) number of library servers found.
 2556: 
 2557: See loncreateuser.pm for example of use.
 2558: 
 2559: =cut
 2560: 
 2561: #-------------------------------------------
 2562: sub home_server_form_item {
 2563:     my ($domain,$name,$default,$hide) = @_;
 2564:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2565:     my $result;
 2566:     my $numlib = keys(%servers);
 2567:     if ($numlib > 1) {
 2568:         $result .= '<select name="'.$name.'" />'."\n";
 2569:         if ($default) {
 2570:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2571:                        '</option>'."\n";
 2572:         }
 2573:         foreach my $hostid (sort(keys(%servers))) {
 2574:             $result.= '<option value="'.$hostid.'">'.
 2575: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2576:         }
 2577:         $result .= '</select>'."\n";
 2578:     } elsif ($numlib == 1) {
 2579:         my $hostid;
 2580:         foreach my $item (keys(%servers)) {
 2581:             $hostid = $item;
 2582:         }
 2583:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2584:                    $hostid.'" />';
 2585:                    if (!$hide) {
 2586:                        $result .= $hostid.' '.$servers{$hostid};
 2587:                    }
 2588:                    $result .= "\n";
 2589:     } elsif ($default) {
 2590:         $result .= '<input type="hidden" name="'.$name.
 2591:                    '" value="default" />';
 2592:                    if (!$hide) {
 2593:                        $result .= &mt('default');
 2594:                    }
 2595:                    $result .= "\n";
 2596:     }
 2597:     return ($result,$numlib);
 2598: }
 2599: 
 2600: =pod
 2601: 
 2602: =back 
 2603: 
 2604: =cut
 2605: 
 2606: ###############################################################
 2607: ##                  Decoding User Agent                      ##
 2608: ###############################################################
 2609: 
 2610: =pod
 2611: 
 2612: =head1 Decoding the User Agent
 2613: 
 2614: =over 4
 2615: 
 2616: =item * &decode_user_agent()
 2617: 
 2618: Inputs: $r
 2619: 
 2620: Outputs:
 2621: 
 2622: =over 4
 2623: 
 2624: =item * $httpbrowser
 2625: 
 2626: =item * $clientbrowser
 2627: 
 2628: =item * $clientversion
 2629: 
 2630: =item * $clientmathml
 2631: 
 2632: =item * $clientunicode
 2633: 
 2634: =item * $clientos
 2635: 
 2636: =item * $clientmobile
 2637: 
 2638: =item * $clientinfo
 2639: 
 2640: =item * $clientosversion
 2641: 
 2642: =back
 2643: 
 2644: =back 
 2645: 
 2646: =cut
 2647: 
 2648: ###############################################################
 2649: ###############################################################
 2650: sub decode_user_agent {
 2651:     my ($r)=@_;
 2652:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2653:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2654:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2655:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2656:     my $clientbrowser='unknown';
 2657:     my $clientversion='0';
 2658:     my $clientmathml='';
 2659:     my $clientunicode='0';
 2660:     my $clientmobile=0;
 2661:     my $clientosversion='';
 2662:     for (my $i=0;$i<=$#browsertype;$i++) {
 2663:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2664: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2665: 	    $clientbrowser=$bname;
 2666:             $httpbrowser=~/$vreg/i;
 2667: 	    $clientversion=$1;
 2668:             $clientmathml=($clientversion>=$minv);
 2669:             $clientunicode=($clientversion>=$univ);
 2670: 	}
 2671:     }
 2672:     my $clientos='unknown';
 2673:     my $clientinfo;
 2674:     if (($httpbrowser=~/linux/i) ||
 2675:         ($httpbrowser=~/unix/i) ||
 2676:         ($httpbrowser=~/ux/i) ||
 2677:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2678:     if (($httpbrowser=~/vax/i) ||
 2679:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2680:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2681:     if (($httpbrowser=~/mac/i) ||
 2682:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2683:     if ($httpbrowser=~/win/i) {
 2684:         $clientos='win';
 2685:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2686:             $clientosversion = $1;
 2687:         }
 2688:     }
 2689:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2690:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2691:         $clientmobile=lc($1);
 2692:     }
 2693:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2694:         $clientinfo = 'firefox-'.$1;
 2695:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2696:         $clientinfo = 'chromeframe-'.$1;
 2697:     }
 2698:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2699:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2700:             $clientosversion);
 2701: }
 2702: 
 2703: ###############################################################
 2704: ##    Authentication changing form generation subroutines    ##
 2705: ###############################################################
 2706: ##
 2707: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2708: ## hash, and have reasonable default values.
 2709: ##
 2710: ##    formname = the name given in the <form> tag.
 2711: #-------------------------------------------
 2712: 
 2713: =pod
 2714: 
 2715: =head1 Authentication Routines
 2716: 
 2717: =over 4
 2718: 
 2719: =item * &authform_xxxxxx()
 2720: 
 2721: The authform_xxxxxx subroutines provide javascript and html forms which 
 2722: handle some of the conveniences required for authentication forms.  
 2723: This is not an optimal method, but it works.  
 2724: 
 2725: =over 4
 2726: 
 2727: =item * authform_header
 2728: 
 2729: =item * authform_authorwarning
 2730: 
 2731: =item * authform_nochange
 2732: 
 2733: =item * authform_kerberos
 2734: 
 2735: =item * authform_internal
 2736: 
 2737: =item * authform_filesystem
 2738: 
 2739: =item * authform_lti
 2740: 
 2741: =back
 2742: 
 2743: See loncreateuser.pm for invocation and use examples.
 2744: 
 2745: =cut
 2746: 
 2747: #-------------------------------------------
 2748: sub authform_header{  
 2749:     my %in = (
 2750:         formname => 'cu',
 2751:         kerb_def_dom => '',
 2752:         @_,
 2753:     );
 2754:     $in{'formname'} = 'document.' . $in{'formname'};
 2755:     my $result='';
 2756: 
 2757: #---------------------------------------------- Code for upper case translation
 2758:     my $Javascript_toUpperCase;
 2759:     unless ($in{kerb_def_dom}) {
 2760:         $Javascript_toUpperCase =<<"END";
 2761:         switch (choice) {
 2762:            case 'krb': currentform.elements[choicearg].value =
 2763:                currentform.elements[choicearg].value.toUpperCase();
 2764:                break;
 2765:            default:
 2766:         }
 2767: END
 2768:     } else {
 2769:         $Javascript_toUpperCase = "";
 2770:     }
 2771: 
 2772:     my $radioval = "'nochange'";
 2773:     if (defined($in{'curr_authtype'})) {
 2774:         if ($in{'curr_authtype'} ne '') {
 2775:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2776:         }
 2777:     }
 2778:     my $argfield = 'null';
 2779:     if (defined($in{'mode'})) {
 2780:         if ($in{'mode'} eq 'modifycourse')  {
 2781:             if (defined($in{'curr_autharg'})) {
 2782:                 if ($in{'curr_autharg'} ne '') {
 2783:                     $argfield = "'$in{'curr_autharg'}'";
 2784:                 }
 2785:             }
 2786:         }
 2787:     }
 2788: 
 2789:     $result.=<<"END";
 2790: var current = new Object();
 2791: current.radiovalue = $radioval;
 2792: current.argfield = $argfield;
 2793: 
 2794: function changed_radio(choice,currentform) {
 2795:     var choicearg = choice + 'arg';
 2796:     // If a radio button in changed, we need to change the argfield
 2797:     if (current.radiovalue != choice) {
 2798:         current.radiovalue = choice;
 2799:         if (current.argfield != null) {
 2800:             currentform.elements[current.argfield].value = '';
 2801:         }
 2802:         if (choice == 'nochange') {
 2803:             current.argfield = null;
 2804:         } else {
 2805:             current.argfield = choicearg;
 2806:             switch(choice) {
 2807:                 case 'krb': 
 2808:                     currentform.elements[current.argfield].value = 
 2809:                         "$in{'kerb_def_dom'}";
 2810:                 break;
 2811:               default:
 2812:                 break;
 2813:             }
 2814:         }
 2815:     }
 2816:     return;
 2817: }
 2818: 
 2819: function changed_text(choice,currentform) {
 2820:     var choicearg = choice + 'arg';
 2821:     if (currentform.elements[choicearg].value !='') {
 2822:         $Javascript_toUpperCase
 2823:         // clear old field
 2824:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2825:             currentform.elements[current.argfield].value = '';
 2826:         }
 2827:         current.argfield = choicearg;
 2828:     }
 2829:     set_auth_radio_buttons(choice,currentform);
 2830:     return;
 2831: }
 2832: 
 2833: function set_auth_radio_buttons(newvalue,currentform) {
 2834:     var numauthchoices = currentform.login.length;
 2835:     if (typeof numauthchoices  == "undefined") {
 2836:         return;
 2837:     } 
 2838:     var i=0;
 2839:     while (i < numauthchoices) {
 2840:         if (currentform.login[i].value == newvalue) { break; }
 2841:         i++;
 2842:     }
 2843:     if (i == numauthchoices) {
 2844:         return;
 2845:     }
 2846:     current.radiovalue = newvalue;
 2847:     currentform.login[i].checked = true;
 2848:     return;
 2849: }
 2850: END
 2851:     return $result;
 2852: }
 2853: 
 2854: sub authform_authorwarning {
 2855:     my $result='';
 2856:     $result='<i>'.
 2857:         &mt('As a general rule, only authors or co-authors should be '.
 2858:             'filesystem authenticated '.
 2859:             '(which allows access to the server filesystem).')."</i>\n";
 2860:     return $result;
 2861: }
 2862: 
 2863: sub authform_nochange {
 2864:     my %in = (
 2865:               formname => 'document.cu',
 2866:               kerb_def_dom => 'MSU.EDU',
 2867:               @_,
 2868:           );
 2869:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2870:     my $result;
 2871:     if (!$authnum) {
 2872:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2873:     } else {
 2874:         $result = '<label>'.&mt('[_1] Do not change login data',
 2875:                   '<input type="radio" name="login" value="nochange" '.
 2876:                   'checked="checked" onclick="'.
 2877:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2878: 	    '</label>';
 2879:     }
 2880:     return $result;
 2881: }
 2882: 
 2883: sub authform_kerberos {
 2884:     my %in = (
 2885:               formname => 'document.cu',
 2886:               kerb_def_dom => 'MSU.EDU',
 2887:               kerb_def_auth => 'krb4',
 2888:               @_,
 2889:               );
 2890:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2891:         $autharg,$jscall,$disabled);
 2892:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2893:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2894:        $check5 = ' checked="checked"';
 2895:     } else {
 2896:        $check4 = ' checked="checked"';
 2897:     }
 2898:     if ($in{'readonly'}) {
 2899:         $disabled = ' disabled="disabled"';
 2900:     }
 2901:     $krbarg = $in{'kerb_def_dom'};
 2902:     if (defined($in{'curr_authtype'})) {
 2903:         if ($in{'curr_authtype'} eq 'krb') {
 2904:             $krbcheck = ' checked="checked"';
 2905:             if (defined($in{'mode'})) {
 2906:                 if ($in{'mode'} eq 'modifyuser') {
 2907:                     $krbcheck = '';
 2908:                 }
 2909:             }
 2910:             if (defined($in{'curr_kerb_ver'})) {
 2911:                 if ($in{'curr_krb_ver'} eq '5') {
 2912:                     $check5 = ' checked="checked"';
 2913:                     $check4 = '';
 2914:                 } else {
 2915:                     $check4 = ' checked="checked"';
 2916:                     $check5 = '';
 2917:                 }
 2918:             }
 2919:             if (defined($in{'curr_autharg'})) {
 2920:                 $krbarg = $in{'curr_autharg'};
 2921:             }
 2922:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2923:                 if (defined($in{'curr_autharg'})) {
 2924:                     $result = 
 2925:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2926:         $in{'curr_autharg'},$krbver);
 2927:                 } else {
 2928:                     $result =
 2929:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2930:                 }
 2931:                 return $result; 
 2932:             }
 2933:         }
 2934:     } else {
 2935:         if ($authnum == 1) {
 2936:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2937:         }
 2938:     }
 2939:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2940:         return;
 2941:     } elsif ($authtype eq '') {
 2942:         if (defined($in{'mode'})) {
 2943:             if ($in{'mode'} eq 'modifycourse') {
 2944:                 if ($authnum == 1) {
 2945:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 2946:                 }
 2947:             }
 2948:         }
 2949:     }
 2950:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2951:     if ($authtype eq '') {
 2952:         $authtype = '<input type="radio" name="login" value="krb" '.
 2953:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2954:                     $krbcheck.$disabled.' />';
 2955:     }
 2956:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2957:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2958:          $in{'curr_authtype'} eq 'krb5') ||
 2959:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2960:          $in{'curr_authtype'} eq 'krb4')) {
 2961:         $result .= &mt
 2962:         ('[_1] Kerberos authenticated with domain [_2] '.
 2963:          '[_3] Version 4 [_4] Version 5 [_5]',
 2964:          '<label>'.$authtype,
 2965:          '</label><input type="text" size="10" name="krbarg" '.
 2966:              'value="'.$krbarg.'" '.
 2967:              'onchange="'.$jscall.'"'.$disabled.' />',
 2968:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 2969:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 2970: 	 '</label>');
 2971:     } elsif ($can_assign{'krb4'}) {
 2972:         $result .= &mt
 2973:         ('[_1] Kerberos authenticated with domain [_2] '.
 2974:          '[_3] Version 4 [_4]',
 2975:          '<label>'.$authtype,
 2976:          '</label><input type="text" size="10" name="krbarg" '.
 2977:              'value="'.$krbarg.'" '.
 2978:              'onchange="'.$jscall.'"'.$disabled.' />',
 2979:          '<label><input type="hidden" name="krbver" value="4" />',
 2980:          '</label>');
 2981:     } elsif ($can_assign{'krb5'}) {
 2982:         $result .= &mt
 2983:         ('[_1] Kerberos authenticated with domain [_2] '.
 2984:          '[_3] Version 5 [_4]',
 2985:          '<label>'.$authtype,
 2986:          '</label><input type="text" size="10" name="krbarg" '.
 2987:              'value="'.$krbarg.'" '.
 2988:              'onchange="'.$jscall.'"'.$disabled.' />',
 2989:          '<label><input type="hidden" name="krbver" value="5" />',
 2990:          '</label>');
 2991:     }
 2992:     return $result;
 2993: }
 2994: 
 2995: sub authform_internal {
 2996:     my %in = (
 2997:                 formname => 'document.cu',
 2998:                 kerb_def_dom => 'MSU.EDU',
 2999:                 @_,
 3000:                 );
 3001:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3002:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3003:     if ($in{'readonly'}) {
 3004:         $disabled = ' disabled="disabled"';
 3005:     }
 3006:     if (defined($in{'curr_authtype'})) {
 3007:         if ($in{'curr_authtype'} eq 'int') {
 3008:             if ($can_assign{'int'}) {
 3009:                 $intcheck = 'checked="checked" ';
 3010:                 if (defined($in{'mode'})) {
 3011:                     if ($in{'mode'} eq 'modifyuser') {
 3012:                         $intcheck = '';
 3013:                     }
 3014:                 }
 3015:                 if (defined($in{'curr_autharg'})) {
 3016:                     $intarg = $in{'curr_autharg'};
 3017:                 }
 3018:             } else {
 3019:                 $result = &mt('Currently internally authenticated.');
 3020:                 return $result;
 3021:             }
 3022:         }
 3023:     } else {
 3024:         if ($authnum == 1) {
 3025:             $authtype = '<input type="hidden" name="login" value="int" />';
 3026:         }
 3027:     }
 3028:     if (!$can_assign{'int'}) {
 3029:         return;
 3030:     } elsif ($authtype eq '') {
 3031:         if (defined($in{'mode'})) {
 3032:             if ($in{'mode'} eq 'modifycourse') {
 3033:                 if ($authnum == 1) {
 3034:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3035:                 }
 3036:             }
 3037:         }
 3038:     }
 3039:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3040:     if ($authtype eq '') {
 3041:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3042:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3043:     }
 3044:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3045:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3046:     $result = &mt
 3047:         ('[_1] Internally authenticated (with initial password [_2])',
 3048:          '<label>'.$authtype,'</label>'.$autharg);
 3049:     $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>';
 3050:     return $result;
 3051: }
 3052: 
 3053: sub authform_local {
 3054:     my %in = (
 3055:               formname => 'document.cu',
 3056:               kerb_def_dom => 'MSU.EDU',
 3057:               @_,
 3058:               );
 3059:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3060:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3061:     if ($in{'readonly'}) {
 3062:         $disabled = ' disabled="disabled"';
 3063:     }
 3064:     if (defined($in{'curr_authtype'})) {
 3065:         if ($in{'curr_authtype'} eq 'loc') {
 3066:             if ($can_assign{'loc'}) {
 3067:                 $loccheck = 'checked="checked" ';
 3068:                 if (defined($in{'mode'})) {
 3069:                     if ($in{'mode'} eq 'modifyuser') {
 3070:                         $loccheck = '';
 3071:                     }
 3072:                 }
 3073:                 if (defined($in{'curr_autharg'})) {
 3074:                     $locarg = $in{'curr_autharg'};
 3075:                 }
 3076:             } else {
 3077:                 $result = &mt('Currently using local (institutional) authentication.');
 3078:                 return $result;
 3079:             }
 3080:         }
 3081:     } else {
 3082:         if ($authnum == 1) {
 3083:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3084:         }
 3085:     }
 3086:     if (!$can_assign{'loc'}) {
 3087:         return;
 3088:     } elsif ($authtype eq '') {
 3089:         if (defined($in{'mode'})) {
 3090:             if ($in{'mode'} eq 'modifycourse') {
 3091:                 if ($authnum == 1) {
 3092:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3093:                 }
 3094:             }
 3095:         }
 3096:     }
 3097:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3098:     if ($authtype eq '') {
 3099:         $authtype = '<input type="radio" name="login" value="loc" '.
 3100:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3101:                     $jscall.'"'.$disabled.' />';
 3102:     }
 3103:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3104:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3105:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3106:                   '<label>'.$authtype,'</label>'.$autharg);
 3107:     return $result;
 3108: }
 3109: 
 3110: sub authform_filesystem {
 3111:     my %in = (
 3112:               formname => 'document.cu',
 3113:               kerb_def_dom => 'MSU.EDU',
 3114:               @_,
 3115:               );
 3116:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3117:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3118:     if ($in{'readonly'}) {
 3119:         $disabled = ' disabled="disabled"';
 3120:     }
 3121:     if (defined($in{'curr_authtype'})) {
 3122:         if ($in{'curr_authtype'} eq 'fsys') {
 3123:             if ($can_assign{'fsys'}) {
 3124:                 $fsyscheck = 'checked="checked" ';
 3125:                 if (defined($in{'mode'})) {
 3126:                     if ($in{'mode'} eq 'modifyuser') {
 3127:                         $fsyscheck = '';
 3128:                     }
 3129:                 }
 3130:             } else {
 3131:                 $result = &mt('Currently Filesystem Authenticated.');
 3132:                 return $result;
 3133:             }           
 3134:         }
 3135:     } else {
 3136:         if ($authnum == 1) {
 3137:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3138:         }
 3139:     }
 3140:     if (!$can_assign{'fsys'}) {
 3141:         return;
 3142:     } elsif ($authtype eq '') {
 3143:         if (defined($in{'mode'})) {
 3144:             if ($in{'mode'} eq 'modifycourse') {
 3145:                 if ($authnum == 1) {
 3146:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3147:                 }
 3148:             }
 3149:         }
 3150:     }
 3151:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3152:     if ($authtype eq '') {
 3153:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3154:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3155:                     $jscall.'"'.$disabled.' />';
 3156:     }
 3157:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3158:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3159:     $result = &mt
 3160:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3161:          '<label>'.$authtype,'</label>'.$autharg);
 3162:     return $result;
 3163: }
 3164: 
 3165: sub authform_lti {
 3166:     my %in = (
 3167:               formname => 'document.cu',
 3168:               kerb_def_dom => 'MSU.EDU',
 3169:               @_,
 3170:               );
 3171:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3172:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3173:     if ($in{'readonly'}) {
 3174:         $disabled = ' disabled="disabled"';
 3175:     }
 3176:     if (defined($in{'curr_authtype'})) {
 3177:         if ($in{'curr_authtype'} eq 'lti') {
 3178:             if ($can_assign{'lti'}) {
 3179:                 $lticheck = 'checked="checked" ';
 3180:                 if (defined($in{'mode'})) {
 3181:                     if ($in{'mode'} eq 'modifyuser') {
 3182:                         $lticheck = '';
 3183:                     }
 3184:                 }
 3185:             } else {
 3186:                 $result = &mt('Currently LTI Authenticated.');
 3187:                 return $result;
 3188:             }
 3189:         }
 3190:     } else {
 3191:         if ($authnum == 1) {
 3192:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3193:         }
 3194:     }
 3195:     if (!$can_assign{'lti'}) {
 3196:         return;
 3197:     } elsif ($authtype eq '') {
 3198:         if (defined($in{'mode'})) {
 3199:             if ($in{'mode'} eq 'modifycourse') {
 3200:                 if ($authnum == 1) {
 3201:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3202:                 }
 3203:             }
 3204:         }
 3205:     }
 3206:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3207:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3208:         $authtype = '<input type="radio" name="login" value="lti" '.
 3209:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3210:                     $jscall.'"'.$disabled.' />';
 3211:     }
 3212:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3213:     if ($authtype) {
 3214:         $result = &mt('[_1] LTI Authenticated',
 3215:                       '<label>'.$authtype.'</label>'.$autharg);
 3216:     } else {
 3217:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3218:                   $autharg;
 3219:     }
 3220:     return $result;
 3221: }
 3222: 
 3223: sub get_assignable_auth {
 3224:     my ($dom) = @_;
 3225:     if ($dom eq '') {
 3226:         $dom = $env{'request.role.domain'};
 3227:     }
 3228:     my %can_assign = (
 3229:                           krb4 => 1,
 3230:                           krb5 => 1,
 3231:                           int  => 1,
 3232:                           loc  => 1,
 3233:                      );
 3234:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3235:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3236:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3237:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3238:             my $context;
 3239:             if ($env{'request.role'} =~ /^au/) {
 3240:                 $context = 'author';
 3241:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3242:                 $context = 'domain';
 3243:             } elsif ($env{'request.course.id'}) {
 3244:                 $context = 'course';
 3245:             }
 3246:             if ($context) {
 3247:                 if (ref($authhash->{$context}) eq 'HASH') {
 3248:                    %can_assign = %{$authhash->{$context}}; 
 3249:                 }
 3250:             }
 3251:         }
 3252:     }
 3253:     my $authnum = 0;
 3254:     foreach my $key (keys(%can_assign)) {
 3255:         if ($can_assign{$key}) {
 3256:             $authnum ++;
 3257:         }
 3258:     }
 3259:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3260:         $authnum --;
 3261:     }
 3262:     return ($authnum,%can_assign);
 3263: }
 3264: 
 3265: sub check_passwd_rules {
 3266:     my ($domain,$plainpass) = @_;
 3267:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3268:     my ($min,$max,@chars,@brokerule,$warning);
 3269:     $min = $Apache::lonnet::passwdmin;
 3270:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3271:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3272:             if ($passwdconf{'min'} > $min) {
 3273:                 $min = $passwdconf{'min'};
 3274:             }
 3275:         }
 3276:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3277:             $max = $passwdconf{'max'};
 3278:         }
 3279:         @chars = @{$passwdconf{'chars'}};
 3280:     }
 3281:     if (($min) && (length($plainpass) < $min)) {
 3282:         push(@brokerule,'min');
 3283:     }
 3284:     if (($max) && (length($plainpass) > $max)) {
 3285:         push(@brokerule,'max');
 3286:     }
 3287:     if (@chars) {
 3288:         my %rules;
 3289:         map { $rules{$_} = 1; } @chars;
 3290:         if ($rules{'uc'}) {
 3291:             unless ($plainpass =~ /[A-Z]/) {
 3292:                 push(@brokerule,'uc');
 3293:             }
 3294:         }
 3295:         if ($rules{'lc'}) {
 3296:             unless ($plainpass =~ /[a-z]/) {
 3297:                 push(@brokerule,'lc');
 3298:             }
 3299:         }
 3300:         if ($rules{'num'}) {
 3301:             unless ($plainpass =~ /\d/) {
 3302:                 push(@brokerule,'num');
 3303:             }
 3304:         }
 3305:         if ($rules{'spec'}) {
 3306:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3307:                 push(@brokerule,'spec');
 3308:             }
 3309:         }
 3310:     }
 3311:     if (@brokerule) {
 3312:         my %rulenames = &Apache::lonlocal::texthash(
 3313:             uc   => 'At least one upper case letter',
 3314:             lc   => 'At least one lower case letter',
 3315:             num  => 'At least one number',
 3316:             spec => 'At least one non-alphanumeric',
 3317:         );
 3318:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3319:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3320:         $rulenames{'num'} .= ': 0123456789';
 3321:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3322:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3323:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3324:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3325:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3326:             if (grep(/^$rule$/,@brokerule)) {
 3327:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3328:             }
 3329:         }
 3330:         $warning .= '</ul>';
 3331:     }
 3332:     if (wantarray) {
 3333:         return @brokerule;
 3334:     }
 3335:     return $warning;
 3336: }
 3337: 
 3338: sub passwd_validation_js {
 3339:     my ($currpasswdval,$domain,$context,$id) = @_;
 3340:     my (%passwdconf,$alertmsg);
 3341:     if ($context eq 'linkprot') {
 3342:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3343:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3344:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3345:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3346:             }
 3347:         }
 3348:         if ($id eq 'add') {
 3349:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3350:         } elsif ($id =~ /^\d+$/) {
 3351:             my $pos = $id+1;
 3352:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3353:         } else {
 3354:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3355:         }
 3356:     } else {
 3357:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3358:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3359:     }
 3360:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3361:     $numrules = 0;
 3362:     $min = $Apache::lonnet::passwdmin;
 3363:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3364:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3365:             if ($passwdconf{'min'} > $min) {
 3366:                 $min = $passwdconf{'min'};
 3367:             }
 3368:         }
 3369:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3370:             $max = $passwdconf{'max'};
 3371:             $numrules ++;
 3372:         }
 3373:         @chars = @{$passwdconf{'chars'}};
 3374:         if (@chars) {
 3375:             $numrules ++;
 3376:         }
 3377:     }
 3378:     if ($min > 0) {
 3379:         $numrules ++;
 3380:     }
 3381:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3382:         if ($min) {
 3383:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3384:         }
 3385:         if ($max) {
 3386:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3387:         }
 3388:         my (@charalerts,@charrules);
 3389:         if (@chars) {
 3390:             if (grep(/^uc$/,@chars)) {
 3391:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3392:                 push(@charrules,'uc');
 3393:             }
 3394:             if (grep(/^lc$/,@chars)) {
 3395:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3396:                 push(@charrules,'lc');
 3397:             }
 3398:             if (grep(/^num$/,@chars)) {
 3399:                 push(@charalerts,&mt('contain at least one number'));
 3400:                 push(@charrules,'num');
 3401:             }
 3402:             if (grep(/^spec$/,@chars)) {
 3403:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 3404:                 push(@charrules,'spec');
 3405:             }
 3406:         }
 3407:         $intargjs = qq|            var rulesmsg = '';\n|.
 3408:                     qq|            var currpwval = $currpasswdval;\n|;
 3409:             if ($min) {
 3410:                 $intargjs .= qq|
 3411:             if (currpwval.length < $min) {
 3412:                 rulesmsg += ' - $alert{min}';
 3413:             }
 3414: |;
 3415:             }
 3416:             if ($max) {
 3417:                 $intargjs .= qq|
 3418:             if (currpwval.length > $max) {
 3419:                 rulesmsg += ' - $alert{max}';
 3420:             }
 3421: |;
 3422:             }
 3423:             if (@chars > 0) {
 3424:                 my $charrulestr = '"'.join('","',@charrules).'"';
 3425:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 3426:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 3427:                              qq|            var charrules = new Array($charrulestr);\n|.
 3428:                              qq|            var charalerts = new Array($charalertstr);\n|;
 3429:                 my %rules;
 3430:                 map { $rules{$_} = 1; } @chars;
 3431:                 if ($rules{'uc'}) {
 3432:                     $intargjs .= qq|
 3433:             var ucRegExp = /[A-Z]/;
 3434:             if (!ucRegExp.test(currpwval)) {
 3435:                 brokerules.push('uc');
 3436:             }
 3437: |;
 3438:                 }
 3439:                 if ($rules{'lc'}) {
 3440:                     $intargjs .= qq|
 3441:             var lcRegExp = /[a-z]/;
 3442:             if (!lcRegExp.test(currpwval)) {
 3443:                 brokerules.push('lc');
 3444:             }
 3445: |;
 3446:                 }
 3447:                 if ($rules{'num'}) {
 3448:                      $intargjs .= qq|
 3449:             var numRegExp = /[0-9]/;
 3450:             if (!numRegExp.test(currpwval)) {
 3451:                 brokerules.push('num');
 3452:             }
 3453: |;
 3454:                 }
 3455:                 if ($rules{'spec'}) {
 3456:                      $intargjs .= q|
 3457:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 3458:             if (!specRegExp.test(currpwval)) {
 3459:                 brokerules.push('spec');
 3460:             }
 3461: |;
 3462:                 }
 3463:                 $intargjs .= qq|
 3464:             if (brokerules.length > 0) {
 3465:                 for (var i=0; i<brokerules.length; i++) {
 3466:                     for (var j=0; j<charrules.length; j++) {
 3467:                         if (brokerules[i] == charrules[j]) {
 3468:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 3469:                             break;
 3470:                         }
 3471:                     }
 3472:                 }
 3473:             }
 3474: |;
 3475:             }
 3476:             $intargjs .= qq|
 3477:             if (rulesmsg != '') {
 3478:                 rulesmsg = '$alertmsg'+rulesmsg;
 3479:                 alert(rulesmsg);
 3480:                 return false;
 3481:             }
 3482: |;
 3483:     }
 3484:     return ($numrules,$intargjs);
 3485: }
 3486: 
 3487: ###############################################################
 3488: ##    Get Kerberos Defaults for Domain                 ##
 3489: ###############################################################
 3490: ##
 3491: ## Returns default kerberos version and an associated argument
 3492: ## as listed in file domain.tab. If not listed, provides
 3493: ## appropriate default domain and kerberos version.
 3494: ##
 3495: #-------------------------------------------
 3496: 
 3497: =pod
 3498: 
 3499: =item * &get_kerberos_defaults()
 3500: 
 3501: get_kerberos_defaults($target_domain) returns the default kerberos
 3502: version and domain. If not found, it defaults to version 4 and the 
 3503: domain of the server.
 3504: 
 3505: =over 4
 3506: 
 3507: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3508: 
 3509: =back
 3510: 
 3511: =back
 3512: 
 3513: =cut
 3514: 
 3515: #-------------------------------------------
 3516: sub get_kerberos_defaults {
 3517:     my $domain=shift;
 3518:     my ($krbdef,$krbdefdom);
 3519:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3520:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3521:         $krbdef = $domdefaults{'auth_def'};
 3522:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3523:     } else {
 3524:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3525:         my $krbdefdom=$1;
 3526:         $krbdefdom=~tr/a-z/A-Z/;
 3527:         $krbdef = "krb4";
 3528:     }
 3529:     return ($krbdef,$krbdefdom);
 3530: }
 3531: 
 3532: 
 3533: ###############################################################
 3534: ##                Thesaurus Functions                        ##
 3535: ###############################################################
 3536: 
 3537: =pod
 3538: 
 3539: =head1 Thesaurus Functions
 3540: 
 3541: =over 4
 3542: 
 3543: =item * &initialize_keywords()
 3544: 
 3545: Initializes the package variable %Keywords if it is empty.  Uses the
 3546: package variable $thesaurus_db_file.
 3547: 
 3548: =cut
 3549: 
 3550: ###################################################
 3551: 
 3552: sub initialize_keywords {
 3553:     return 1 if (scalar keys(%Keywords));
 3554:     # If we are here, %Keywords is empty, so fill it up
 3555:     #   Make sure the file we need exists...
 3556:     if (! -e $thesaurus_db_file) {
 3557:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3558:                                  " failed because it does not exist");
 3559:         return 0;
 3560:     }
 3561:     #   Set up the hash as a database
 3562:     my %thesaurus_db;
 3563:     if (! tie(%thesaurus_db,'GDBM_File',
 3564:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3565:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3566:                                  $thesaurus_db_file);
 3567:         return 0;
 3568:     } 
 3569:     #  Get the average number of appearances of a word.
 3570:     my $avecount = $thesaurus_db{'average.count'};
 3571:     #  Put keywords (those that appear > average) into %Keywords
 3572:     while (my ($word,$data)=each (%thesaurus_db)) {
 3573:         my ($count,undef) = split /:/,$data;
 3574:         $Keywords{$word}++ if ($count > $avecount);
 3575:     }
 3576:     untie %thesaurus_db;
 3577:     # Remove special values from %Keywords.
 3578:     foreach my $value ('total.count','average.count') {
 3579:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3580:   }
 3581:     return 1;
 3582: }
 3583: 
 3584: ###################################################
 3585: 
 3586: =pod
 3587: 
 3588: =item * &keyword($word)
 3589: 
 3590: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3591: than the average number of times in the thesaurus database.  Calls 
 3592: &initialize_keywords
 3593: 
 3594: =cut
 3595: 
 3596: ###################################################
 3597: 
 3598: sub keyword {
 3599:     return if (!&initialize_keywords());
 3600:     my $word=lc(shift());
 3601:     $word=~s/\W//g;
 3602:     return exists($Keywords{$word});
 3603: }
 3604: 
 3605: ###############################################################
 3606: 
 3607: =pod 
 3608: 
 3609: =item * &get_related_words()
 3610: 
 3611: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3612: an array of words.  If the keyword is not in the thesaurus, an empty array
 3613: will be returned.  The order of the words returned is determined by the
 3614: database which holds them.
 3615: 
 3616: Uses global $thesaurus_db_file.
 3617: 
 3618: 
 3619: =cut
 3620: 
 3621: ###############################################################
 3622: sub get_related_words {
 3623:     my $keyword = shift;
 3624:     my %thesaurus_db;
 3625:     if (! -e $thesaurus_db_file) {
 3626:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3627:                                  "failed because the file does not exist");
 3628:         return ();
 3629:     }
 3630:     if (! tie(%thesaurus_db,'GDBM_File',
 3631:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3632:         return ();
 3633:     } 
 3634:     my @Words=();
 3635:     my $count=0;
 3636:     if (exists($thesaurus_db{$keyword})) {
 3637: 	# The first element is the number of times
 3638: 	# the word appears.  We do not need it now.
 3639: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3640: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3641: 	my $threshold=$mostfrequentcount/10;
 3642:         foreach my $possibleword (@RelatedWords) {
 3643:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3644:             if ($wordcount>$threshold) {
 3645: 		push(@Words,$word);
 3646:                 $count++;
 3647:                 if ($count>10) { last; }
 3648: 	    }
 3649:         }
 3650:     }
 3651:     untie %thesaurus_db;
 3652:     return @Words;
 3653: }
 3654: 
 3655: =pod
 3656: 
 3657: =back
 3658: 
 3659: =cut
 3660: 
 3661: # -------------------------------------------------------------- Plaintext name
 3662: =pod
 3663: 
 3664: =head1 User Name Functions
 3665: 
 3666: =over 4
 3667: 
 3668: =item * &plainname($uname,$udom,$first)
 3669: 
 3670: Takes a users logon name and returns it as a string in
 3671: "first middle last generation" form 
 3672: if $first is set to 'lastname' then it returns it as
 3673: 'lastname generation, firstname middlename' if their is a lastname
 3674: 
 3675: =cut
 3676: 
 3677: 
 3678: ###############################################################
 3679: sub plainname {
 3680:     my ($uname,$udom,$first)=@_;
 3681:     return if (!defined($uname) || !defined($udom));
 3682:     my %names=&getnames($uname,$udom);
 3683:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3684: 					  $names{'middlename'},
 3685: 					  $names{'lastname'},
 3686: 					  $names{'generation'},$first);
 3687:     $name=~s/^\s+//;
 3688:     $name=~s/\s+$//;
 3689:     $name=~s/\s+/ /g;
 3690:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3691:     return $name;
 3692: }
 3693: 
 3694: # -------------------------------------------------------------------- Nickname
 3695: =pod
 3696: 
 3697: =item * &nickname($uname,$udom)
 3698: 
 3699: Gets a users name and returns it as a string as
 3700: 
 3701: "&quot;nickname&quot;"
 3702: 
 3703: if the user has a nickname or
 3704: 
 3705: "first middle last generation"
 3706: 
 3707: if the user does not
 3708: 
 3709: =cut
 3710: 
 3711: sub nickname {
 3712:     my ($uname,$udom)=@_;
 3713:     return if (!defined($uname) || !defined($udom));
 3714:     my %names=&getnames($uname,$udom);
 3715:     my $name=$names{'nickname'};
 3716:     if ($name) {
 3717:        $name='&quot;'.$name.'&quot;'; 
 3718:     } else {
 3719:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3720: 	     $names{'lastname'}.' '.$names{'generation'};
 3721:        $name=~s/\s+$//;
 3722:        $name=~s/\s+/ /g;
 3723:     }
 3724:     return $name;
 3725: }
 3726: 
 3727: sub getnames {
 3728:     my ($uname,$udom)=@_;
 3729:     return if (!defined($uname) || !defined($udom));
 3730:     if ($udom eq 'public' && $uname eq 'public') {
 3731: 	return ('lastname' => &mt('Public'));
 3732:     }
 3733:     my $id=$uname.':'.$udom;
 3734:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3735:     if ($cached) {
 3736: 	return %{$names};
 3737:     } else {
 3738: 	my %loadnames=&Apache::lonnet::get('environment',
 3739:                     ['firstname','middlename','lastname','generation','nickname'],
 3740: 					 $udom,$uname);
 3741: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3742: 	return %loadnames;
 3743:     }
 3744: }
 3745: 
 3746: # -------------------------------------------------------------------- getemails
 3747: 
 3748: =pod
 3749: 
 3750: =item * &getemails($uname,$udom)
 3751: 
 3752: Gets a user's email information and returns it as a hash with keys:
 3753: notification, critnotification, permanentemail
 3754: 
 3755: For notification and critnotification, values are comma-separated lists 
 3756: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3757:  
 3758: 
 3759: =cut
 3760: 
 3761: 
 3762: sub getemails {
 3763:     my ($uname,$udom)=@_;
 3764:     if ($udom eq 'public' && $uname eq 'public') {
 3765: 	return;
 3766:     }
 3767:     if (!$udom) { $udom=$env{'user.domain'}; }
 3768:     if (!$uname) { $uname=$env{'user.name'}; }
 3769:     my $id=$uname.':'.$udom;
 3770:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3771:     if ($cached) {
 3772: 	return %{$names};
 3773:     } else {
 3774: 	my %loadnames=&Apache::lonnet::get('environment',
 3775:                     			   ['notification','critnotification',
 3776: 					    'permanentemail'],
 3777: 					   $udom,$uname);
 3778: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3779: 	return %loadnames;
 3780:     }
 3781: }
 3782: 
 3783: sub flush_email_cache {
 3784:     my ($uname,$udom)=@_;
 3785:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3786:     if (!$uname) { $uname=$env{'user.name'};   }
 3787:     return if ($udom eq 'public' && $uname eq 'public');
 3788:     my $id=$uname.':'.$udom;
 3789:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3790: }
 3791: 
 3792: # -------------------------------------------------------------------- getlangs
 3793: 
 3794: =pod
 3795: 
 3796: =item * &getlangs($uname,$udom)
 3797: 
 3798: Gets a user's language preference and returns it as a hash with key:
 3799: language.
 3800: 
 3801: =cut
 3802: 
 3803: 
 3804: sub getlangs {
 3805:     my ($uname,$udom) = @_;
 3806:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3807:     if (!$uname) { $uname=$env{'user.name'};   }
 3808:     my $id=$uname.':'.$udom;
 3809:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3810:     if ($cached) {
 3811:         return %{$langs};
 3812:     } else {
 3813:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3814:                                            $udom,$uname);
 3815:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3816:         return %loadlangs;
 3817:     }
 3818: }
 3819: 
 3820: sub flush_langs_cache {
 3821:     my ($uname,$udom)=@_;
 3822:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3823:     if (!$uname) { $uname=$env{'user.name'};   }
 3824:     return if ($udom eq 'public' && $uname eq 'public');
 3825:     my $id=$uname.':'.$udom;
 3826:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3827: }
 3828: 
 3829: # ------------------------------------------------------------------ Screenname
 3830: 
 3831: =pod
 3832: 
 3833: =item * &screenname($uname,$udom)
 3834: 
 3835: Gets a users screenname and returns it as a string
 3836: 
 3837: =cut
 3838: 
 3839: sub screenname {
 3840:     my ($uname,$udom)=@_;
 3841:     if ($uname eq $env{'user.name'} &&
 3842: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3843:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3844:     return $names{'screenname'};
 3845: }
 3846: 
 3847: 
 3848: # ------------------------------------------------------------- Confirm Wrapper
 3849: =pod
 3850: 
 3851: =item * &confirmwrapper($message)
 3852: 
 3853: Wrap messages about completion of operation in box
 3854: 
 3855: =cut
 3856: 
 3857: sub confirmwrapper {
 3858:     my ($message)=@_;
 3859:     if ($message) {
 3860:         return "\n".'<div class="LC_confirm_box">'."\n"
 3861:                .$message."\n"
 3862:                .'</div>'."\n";
 3863:     } else {
 3864:         return $message;
 3865:     }
 3866: }
 3867: 
 3868: # ------------------------------------------------------------- Message Wrapper
 3869: 
 3870: sub messagewrapper {
 3871:     my ($link,$username,$domain,$subject,$text)=@_;
 3872:     return 
 3873:         '<a href="/adm/email?compose=individual&amp;'.
 3874:         'recname='.$username.'&amp;recdom='.$domain.
 3875: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3876:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3877: }
 3878: 
 3879: # --------------------------------------------------------------- Notes Wrapper
 3880: 
 3881: sub noteswrapper {
 3882:     my ($link,$un,$do)=@_;
 3883:     return 
 3884: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3885: }
 3886: 
 3887: # ------------------------------------------------------------- Aboutme Wrapper
 3888: 
 3889: sub aboutmewrapper {
 3890:     my ($link,$username,$domain,$target,$class)=@_;
 3891:     if (!defined($username)  && !defined($domain)) {
 3892:         return;
 3893:     }
 3894:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3895: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3896: }
 3897: 
 3898: # ------------------------------------------------------------ Syllabus Wrapper
 3899: 
 3900: sub syllabuswrapper {
 3901:     my ($linktext,$coursedir,$domain)=@_;
 3902:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3903: }
 3904: 
 3905: sub aboutme_on {
 3906:     my ($uname,$udom)=@_;
 3907:     unless ($uname) { $uname=$env{'user.name'}; }
 3908:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3909:     return if ($udom eq 'public' && $uname eq 'public');
 3910:     my $hashkey=$uname.':'.$udom;
 3911:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
 3912:     if ($cached) {
 3913:         return $aboutme;
 3914:     }
 3915:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
 3916:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
 3917:     return $aboutme;
 3918: }
 3919: 
 3920: sub devalidate_aboutme_cache {
 3921:     my ($uname,$udom)=@_;
 3922:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3923:     if (!$uname) { $uname=$env{'user.name'};   }
 3924:     return if ($udom eq 'public' && $uname eq 'public');
 3925:     my $id=$uname.':'.$udom;
 3926:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
 3927: }
 3928: 
 3929: # -----------------------------------------------------------------------------
 3930: 
 3931: sub track_student_link {
 3932:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3933:     my $link ="/adm/trackstudent?";
 3934:     my $title = 'View recent activity';
 3935:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3936:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3937:         $link .= "selected_student=$sname:$sdom";
 3938:         $title .= ' of this student';
 3939:     } 
 3940:     if (defined($target) && $target !~ /^\s*$/) {
 3941:         $target = qq{target="$target"};
 3942:     } else {
 3943:         $target = '';
 3944:     }
 3945:     if ($start) { $link.='&amp;start='.$start; }
 3946:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3947:     $title = &mt($title);
 3948:     $linktext = &mt($linktext);
 3949:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3950: 	&help_open_topic('View_recent_activity');
 3951: }
 3952: 
 3953: sub slot_reservations_link {
 3954:     my ($linktext,$sname,$sdom,$target) = @_;
 3955:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3956:     my $title = 'View slot reservation history';
 3957:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3958:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3959:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3960:         $title .= ' of this student';
 3961:     }
 3962:     if (defined($target) && $target !~ /^\s*$/) {
 3963:         $target = qq{target="$target"};
 3964:     } else {
 3965:         $target = '';
 3966:     }
 3967:     $title = &mt($title);
 3968:     $linktext = &mt($linktext);
 3969:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3970: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3971: 
 3972: }
 3973: 
 3974: # ===================================================== Display a student photo
 3975: 
 3976: 
 3977: sub student_image_tag {
 3978:     my ($domain,$user)=@_;
 3979:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3980:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3981: 	return '<img src="'.$imgsrc.'" align="right" />';
 3982:     } else {
 3983: 	return '';
 3984:     }
 3985: }
 3986: 
 3987: =pod
 3988: 
 3989: =back
 3990: 
 3991: =head1 Access .tab File Data
 3992: 
 3993: =over 4
 3994: 
 3995: =item * &languageids() 
 3996: 
 3997: returns list of all language ids
 3998: 
 3999: =cut
 4000: 
 4001: sub languageids {
 4002:     return sort(keys(%language));
 4003: }
 4004: 
 4005: =pod
 4006: 
 4007: =item * &languagedescription() 
 4008: 
 4009: returns description of a specified language id
 4010: 
 4011: =cut
 4012: 
 4013: sub languagedescription {
 4014:     my $code=shift;
 4015:     return  ($supported_language{$code}?'* ':'').
 4016:             $language{$code}.
 4017: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4018: }
 4019: 
 4020: =pod
 4021: 
 4022: =item * &plainlanguagedescription
 4023: 
 4024: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4025: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4026: 
 4027: =cut
 4028: 
 4029: sub plainlanguagedescription {
 4030:     my $code=shift;
 4031:     return $language{$code};
 4032: }
 4033: 
 4034: =pod
 4035: 
 4036: =item * &supportedlanguagecode
 4037: 
 4038: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4039: code.
 4040: 
 4041: =cut
 4042: 
 4043: sub supportedlanguagecode {
 4044:     my $code=shift;
 4045:     return $supported_language{$code};
 4046: }
 4047: 
 4048: =pod
 4049: 
 4050: =item * &latexlanguage()
 4051: 
 4052: Given a language key code returns the correspondnig language to use
 4053: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4054: is no supported hyphenation for the language code.
 4055: 
 4056: =cut
 4057: 
 4058: sub latexlanguage {
 4059:     my $code = shift;
 4060:     return $latex_language{$code};
 4061: }
 4062: 
 4063: =pod
 4064: 
 4065: =item * &latexhyphenation()
 4066: 
 4067: Same as above but what's supplied is the language as it might be stored
 4068: in the metadata.
 4069: 
 4070: =cut
 4071: 
 4072: sub latexhyphenation {
 4073:     my $key = shift;
 4074:     return $latex_language_bykey{$key};
 4075: }
 4076: 
 4077: =pod
 4078: 
 4079: =item * &copyrightids() 
 4080: 
 4081: returns list of all copyrights
 4082: 
 4083: =cut
 4084: 
 4085: sub copyrightids {
 4086:     return sort(keys(%cprtag));
 4087: }
 4088: 
 4089: =pod
 4090: 
 4091: =item * &copyrightdescription() 
 4092: 
 4093: returns description of a specified copyright id
 4094: 
 4095: =cut
 4096: 
 4097: sub copyrightdescription {
 4098:     return &mt($cprtag{shift(@_)});
 4099: }
 4100: 
 4101: =pod
 4102: 
 4103: =item * &source_copyrightids() 
 4104: 
 4105: returns list of all source copyrights
 4106: 
 4107: =cut
 4108: 
 4109: sub source_copyrightids {
 4110:     return sort(keys(%scprtag));
 4111: }
 4112: 
 4113: =pod
 4114: 
 4115: =item * &source_copyrightdescription() 
 4116: 
 4117: returns description of a specified source copyright id
 4118: 
 4119: =cut
 4120: 
 4121: sub source_copyrightdescription {
 4122:     return &mt($scprtag{shift(@_)});
 4123: }
 4124: 
 4125: =pod
 4126: 
 4127: =item * &filecategories() 
 4128: 
 4129: returns list of all file categories
 4130: 
 4131: =cut
 4132: 
 4133: sub filecategories {
 4134:     return sort(keys(%category_extensions));
 4135: }
 4136: 
 4137: =pod
 4138: 
 4139: =item * &filecategorytypes() 
 4140: 
 4141: returns list of file types belonging to a given file
 4142: category
 4143: 
 4144: =cut
 4145: 
 4146: sub filecategorytypes {
 4147:     my ($cat) = @_;
 4148:     return @{$category_extensions{lc($cat)}};
 4149: }
 4150: 
 4151: =pod
 4152: 
 4153: =item * &fileembstyle() 
 4154: 
 4155: returns embedding style for a specified file type
 4156: 
 4157: =cut
 4158: 
 4159: sub fileembstyle {
 4160:     return $fe{lc(shift(@_))};
 4161: }
 4162: 
 4163: sub filemimetype {
 4164:     return $fm{lc(shift(@_))};
 4165: }
 4166: 
 4167: 
 4168: sub filecategoryselect {
 4169:     my ($name,$value)=@_;
 4170:     return &select_form($value,$name,
 4171:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4172: }
 4173: 
 4174: =pod
 4175: 
 4176: =item * &filedescription() 
 4177: 
 4178: returns description for a specified file type
 4179: 
 4180: =cut
 4181: 
 4182: sub filedescription {
 4183:     my $file_description = $fd{lc(shift())};
 4184:     $file_description =~ s:([\[\]]):~$1:g;
 4185:     return &mt($file_description);
 4186: }
 4187: 
 4188: =pod
 4189: 
 4190: =item * &filedescriptionex() 
 4191: 
 4192: returns description for a specified file type with
 4193: extra formatting
 4194: 
 4195: =cut
 4196: 
 4197: sub filedescriptionex {
 4198:     my $ex=shift;
 4199:     my $file_description = $fd{lc($ex)};
 4200:     $file_description =~ s:([\[\]]):~$1:g;
 4201:     return '.'.$ex.' '.&mt($file_description);
 4202: }
 4203: 
 4204: # End of .tab access
 4205: =pod
 4206: 
 4207: =back
 4208: 
 4209: =cut
 4210: 
 4211: # ------------------------------------------------------------------ File Types
 4212: sub fileextensions {
 4213:     return sort(keys(%fe));
 4214: }
 4215: 
 4216: # ----------------------------------------------------------- Display Languages
 4217: # returns a hash with all desired display languages
 4218: #
 4219: 
 4220: sub display_languages {
 4221:     my %languages=();
 4222:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4223: 	$languages{$lang}=1;
 4224:     }
 4225:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4226:     if ($env{'form.displaylanguage'}) {
 4227: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4228: 	    $languages{$lang}=1;
 4229:         }
 4230:     }
 4231:     return %languages;
 4232: }
 4233: 
 4234: sub languages {
 4235:     my ($possible_langs) = @_;
 4236:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4237:     if (!ref($possible_langs)) {
 4238: 	if( wantarray ) {
 4239: 	    return @preferred_langs;
 4240: 	} else {
 4241: 	    return $preferred_langs[0];
 4242: 	}
 4243:     }
 4244:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4245:     my @preferred_possibilities;
 4246:     foreach my $preferred_lang (@preferred_langs) {
 4247: 	if (exists($possibilities{$preferred_lang})) {
 4248: 	    push(@preferred_possibilities, $preferred_lang);
 4249: 	}
 4250:     }
 4251:     if( wantarray ) {
 4252: 	return @preferred_possibilities;
 4253:     }
 4254:     return $preferred_possibilities[0];
 4255: }
 4256: 
 4257: sub user_lang {
 4258:     my ($touname,$toudom,$fromcid) = @_;
 4259:     my @userlangs;
 4260:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4261:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4262:                     $env{'course.'.$fromcid.'.languages'}));
 4263:     } else {
 4264:         my %langhash = &getlangs($touname,$toudom);
 4265:         if ($langhash{'languages'} ne '') {
 4266:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4267:         } else {
 4268:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4269:             if ($domdefs{'lang_def'} ne '') {
 4270:                 @userlangs = ($domdefs{'lang_def'});
 4271:             }
 4272:         }
 4273:     }
 4274:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4275:     my $user_lh = Apache::localize->get_handle(@languages);
 4276:     return $user_lh;
 4277: }
 4278: 
 4279: 
 4280: ###############################################################
 4281: ##               Student Answer Attempts                     ##
 4282: ###############################################################
 4283: 
 4284: =pod
 4285: 
 4286: =head1 Alternate Problem Views
 4287: 
 4288: =over 4
 4289: 
 4290: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4291:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4292: 
 4293: Return string with previous attempt on problem. Arguments:
 4294: 
 4295: =over 4
 4296: 
 4297: =item * $symb: Problem, including path
 4298: 
 4299: =item * $username: username of the desired student
 4300: 
 4301: =item * $domain: domain of the desired student
 4302: 
 4303: =item * $course: Course ID
 4304: 
 4305: =item * $getattempt: Leave blank for all attempts, otherwise put
 4306:     something
 4307: 
 4308: =item * $regexp: if string matches this regexp, the string will be
 4309:     sent to $gradesub
 4310: 
 4311: =item * $gradesub: routine that processes the string if it matches $regexp
 4312: 
 4313: =item * $usec: section of the desired student
 4314: 
 4315: =item * $identifier: counter for student (multiple students one problem) or
 4316:     problem (one student; whole sequence).
 4317: 
 4318: =back
 4319: 
 4320: The output string is a table containing all desired attempts, if any.
 4321: 
 4322: =cut
 4323: 
 4324: sub get_previous_attempt {
 4325:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4326:   my $prevattempts='';
 4327:   no strict 'refs';
 4328:   if ($symb) {
 4329:     my (%returnhash)=
 4330:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4331:     if ($returnhash{'version'}) {
 4332:       my %lasthash=();
 4333:       my $version;
 4334:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4335:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4336:             if ($key =~ /\.rawrndseed$/) {
 4337:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4338:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4339:             } else {
 4340:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4341:             }
 4342:         }
 4343:       }
 4344:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4345:       $prevattempts.='<th>'.&mt('History').'</th>';
 4346:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4347:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4348:       foreach my $key (sort(keys(%lasthash))) {
 4349: 	my ($ign,@parts) = split(/\./,$key);
 4350: 	if ($#parts > 0) {
 4351: 	  my $data=$parts[-1];
 4352:           next if ($data eq 'foilorder');
 4353: 	  pop(@parts);
 4354:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4355:           if ($data eq 'type') {
 4356:               unless ($showsurv) {
 4357:                   my $id = join(',',@parts);
 4358:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4359:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4360:                       $lasthidden{$ign.'.'.$id} = 1;
 4361:                   }
 4362:               }
 4363:               if ($identifier ne '') {
 4364:                   my $id = join(',',@parts);
 4365:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4366:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4367:                       $hidestatus{$ign.'.'.$id} = 1;
 4368:                   }
 4369:               }
 4370:           } elsif ($data eq 'regrader') {
 4371:               if (($identifier ne '') && (@parts)) {
 4372:                   my $id = join(',',@parts);
 4373:                   $regraded{$ign.'.'.$id} = 1;
 4374:               }
 4375:           } 
 4376: 	} else {
 4377: 	  if ($#parts == 0) {
 4378: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4379: 	  } else {
 4380: 	    $prevattempts.='<th>'.$ign.'</th>';
 4381: 	  }
 4382: 	}
 4383:       }
 4384:       $prevattempts.=&end_data_table_header_row();
 4385:       if ($getattempt eq '') {
 4386:         my (%solved,%resets,%probstatus);
 4387:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4388:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4389:                 foreach my $id (keys(%regraded)) {
 4390:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4391:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4392:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4393:                         push(@{$resets{$id}},$version);
 4394:                     }
 4395:                 }
 4396:             }
 4397:         }
 4398: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4399:             my (@hidden,@unsolved);
 4400:             if (%typeparts) {
 4401:                 foreach my $id (keys(%typeparts)) {
 4402:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4403:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4404:                         push(@hidden,$id);
 4405:                     } elsif ($identifier ne '') {
 4406:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4407:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4408:                                 ($hidestatus{$id})) {
 4409:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4410:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4411:                                 push(@{$solved{$id}},$version);
 4412:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4413:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4414:                                 my $skip;
 4415:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4416:                                     foreach my $reset (@{$resets{$id}}) {
 4417:                                         if ($reset > $solved{$id}[-1]) {
 4418:                                             $skip=1;
 4419:                                             last;
 4420:                                         }
 4421:                                     }
 4422:                                 }
 4423:                                 unless ($skip) {
 4424:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4425:                                     push(@unsolved,$partslist);
 4426:                                 }
 4427:                             }
 4428:                         }
 4429:                     }
 4430:                 }
 4431:             }
 4432:             $prevattempts.=&start_data_table_row().
 4433:                            '<td>'.&mt('Transaction [_1]',$version);
 4434:             if (@unsolved) {
 4435:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4436:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4437:                                  &mt('Hide').'</label></span>';
 4438:             }
 4439:             $prevattempts .= '</td>';
 4440:             if (@hidden) {
 4441:                 foreach my $key (sort(keys(%lasthash))) {
 4442:                     next if ($key =~ /\.foilorder$/);
 4443:                     my $hide;
 4444:                     foreach my $id (@hidden) {
 4445:                         if ($key =~ /^\Q$id\E/) {
 4446:                             $hide = 1;
 4447:                             last;
 4448:                         }
 4449:                     }
 4450:                     if ($hide) {
 4451:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4452:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4453:                             my $value = &format_previous_attempt_value($key,
 4454:                                              $returnhash{$version.':'.$key});
 4455:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4456:                         } else {
 4457:                             $prevattempts.='<td>&nbsp;</td>';
 4458:                         }
 4459:                     } else {
 4460:                         if ($key =~ /\./) {
 4461:                             my $value = $returnhash{$version.':'.$key};
 4462:                             if ($key =~ /\.rndseed$/) {
 4463:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4464:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4465:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4466:                                 }
 4467:                             }
 4468:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4469:                                            '&nbsp;</td>';
 4470:                         } else {
 4471:                             $prevattempts.='<td>&nbsp;</td>';
 4472:                         }
 4473:                     }
 4474:                 }
 4475:             } else {
 4476: 	        foreach my $key (sort(keys(%lasthash))) {
 4477:                     next if ($key =~ /\.foilorder$/);
 4478:                     my $value = $returnhash{$version.':'.$key};
 4479:                     if ($key =~ /\.rndseed$/) {
 4480:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4481:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4482:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4483:                         }
 4484:                     }
 4485:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4486:                                    '&nbsp;</td>';
 4487: 	        }
 4488:             }
 4489: 	    $prevattempts.=&end_data_table_row();
 4490: 	 }
 4491:       }
 4492:       my @currhidden = keys(%lasthidden);
 4493:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4494:       foreach my $key (sort(keys(%lasthash))) {
 4495:           next if ($key =~ /\.foilorder$/);
 4496:           if (%typeparts) {
 4497:               my $hidden;
 4498:               foreach my $id (@currhidden) {
 4499:                   if ($key =~ /^\Q$id\E/) {
 4500:                       $hidden = 1;
 4501:                       last;
 4502:                   }
 4503:               }
 4504:               if ($hidden) {
 4505:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4506:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4507:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4508:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4509:                           $value = &$gradesub($value);
 4510:                       }
 4511:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4512:                   } else {
 4513:                       $prevattempts.='<td>&nbsp;</td>';
 4514:                   }
 4515:               } else {
 4516:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4517:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4518:                       $value = &$gradesub($value);
 4519:                   }
 4520:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4521:               }
 4522:           } else {
 4523: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4524: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4525:                   $value = &$gradesub($value);
 4526:               }
 4527: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4528:           }
 4529:       }
 4530:       $prevattempts.= &end_data_table_row().&end_data_table();
 4531:     } else {
 4532:       my $msg;
 4533:       if ($symb =~ /ext\.tool$/) {
 4534:           $msg = &mt('No grade passed back.');
 4535:       } else {
 4536:           $msg = &mt('Nothing submitted - no attempts.');
 4537:       }
 4538:       $prevattempts=
 4539: 	  &start_data_table().&start_data_table_row().
 4540: 	  '<td>'.$msg.'</td>'.
 4541: 	  &end_data_table_row().&end_data_table();
 4542:     }
 4543:   } else {
 4544:     $prevattempts=
 4545: 	  &start_data_table().&start_data_table_row().
 4546: 	  '<td>'.&mt('No data.').'</td>'.
 4547: 	  &end_data_table_row().&end_data_table();
 4548:   }
 4549: }
 4550: 
 4551: sub format_previous_attempt_value {
 4552:     my ($key,$value) = @_;
 4553:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4554: 	$value = &Apache::lonlocal::locallocaltime($value);
 4555:     } elsif (ref($value) eq 'ARRAY') {
 4556: 	$value = '('.join(', ', @{ $value }).')';
 4557:     } elsif ($key =~ /answerstring$/) {
 4558:         my %answers = &Apache::lonnet::str2hash($value);
 4559:         my @anskeys = sort(keys(%answers));
 4560:         if (@anskeys == 1) {
 4561:             my $answer = $answers{$anskeys[0]};
 4562:             if ($answer =~ m{\0}) {
 4563:                 $answer =~ s{\0}{,}g;
 4564:             }
 4565:             my $tag_internal_answer_name = 'INTERNAL';
 4566:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4567:                 $value = $answer; 
 4568:             } else {
 4569:                 $value = $anskeys[0].'='.$answer;
 4570:             }
 4571:         } else {
 4572:             foreach my $ans (@anskeys) {
 4573:                 my $answer = $answers{$ans};
 4574:                 if ($answer =~ m{\0}) {
 4575:                     $answer =~ s{\0}{,}g;
 4576:                 }
 4577:                 $value .=  $ans.'='.$answer.'<br />';;
 4578:             } 
 4579:         }
 4580:     } else {
 4581: 	$value = &unescape($value);
 4582:     }
 4583:     return $value;
 4584: }
 4585: 
 4586: 
 4587: sub relative_to_absolute {
 4588:     my ($url,$output)=@_;
 4589:     my $parser=HTML::TokeParser->new(\$output);
 4590:     my $token;
 4591:     my $thisdir=$url;
 4592:     my @rlinks=();
 4593:     while ($token=$parser->get_token) {
 4594: 	if ($token->[0] eq 'S') {
 4595: 	    if ($token->[1] eq 'a') {
 4596: 		if ($token->[2]->{'href'}) {
 4597: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4598: 		}
 4599: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4600: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4601: 	    } elsif ($token->[1] eq 'base') {
 4602: 		$thisdir=$token->[2]->{'href'};
 4603: 	    }
 4604: 	}
 4605:     }
 4606:     $thisdir=~s-/[^/]*$--;
 4607:     foreach my $link (@rlinks) {
 4608: 	unless (($link=~/^https?\:\/\//i) ||
 4609: 		($link=~/^\//) ||
 4610: 		($link=~/^javascript:/i) ||
 4611: 		($link=~/^mailto:/i) ||
 4612: 		($link=~/^\#/)) {
 4613: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4614: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4615: 	}
 4616:     }
 4617: # -------------------------------------------------- Deal with Applet codebases
 4618:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4619:     return $output;
 4620: }
 4621: 
 4622: =pod
 4623: 
 4624: =item * &get_student_view()
 4625: 
 4626: show a snapshot of what student was looking at
 4627: 
 4628: =cut
 4629: 
 4630: sub get_student_view {
 4631:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4632:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4633:   my (%form);
 4634:   my @elements=('symb','courseid','domain','username');
 4635:   foreach my $element (@elements) {
 4636:       $form{'grade_'.$element}=eval '$'.$element #'
 4637:   }
 4638:   if (defined($moreenv)) {
 4639:       %form=(%form,%{$moreenv});
 4640:   }
 4641:   if (defined($target)) { $form{'grade_target'} = $target; }
 4642:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4643:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4644:   $userview=~s/\<body[^\>]*\>//gi;
 4645:   $userview=~s/\<\/body\>//gi;
 4646:   $userview=~s/\<html\>//gi;
 4647:   $userview=~s/\<\/html\>//gi;
 4648:   $userview=~s/\<head\>//gi;
 4649:   $userview=~s/\<\/head\>//gi;
 4650:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4651:   $userview=&relative_to_absolute($feedurl,$userview);
 4652:   if (wantarray) {
 4653:      return ($userview,$response);
 4654:   } else {
 4655:      return $userview;
 4656:   }
 4657: }
 4658: 
 4659: sub get_student_view_with_retries {
 4660:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4661: 
 4662:     my $ok = 0;                 # True if we got a good response.
 4663:     my $content;
 4664:     my $response;
 4665: 
 4666:     # Try to get the student_view done. within the retries count:
 4667:     
 4668:     do {
 4669:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4670:          $ok      = $response->is_success;
 4671:          if (!$ok) {
 4672:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4673:          }
 4674:          $retries--;
 4675:     } while (!$ok && ($retries > 0));
 4676:     
 4677:     if (!$ok) {
 4678:        $content = '';          # On error return an empty content.
 4679:     }
 4680:     if (wantarray) {
 4681:        return ($content, $response);
 4682:     } else {
 4683:        return $content;
 4684:     }
 4685: }
 4686: 
 4687: sub css_links {
 4688:     my ($currsymb,$level) = @_;
 4689:     my ($links,@symbs,%cssrefs,%httpref);
 4690:     if ($level eq 'map') {
 4691:         my $navmap = Apache::lonnavmaps::navmap->new();
 4692:         if (ref($navmap)) {
 4693:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 4694:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 4695:             foreach my $res (@resources) {
 4696:                 if (ref($res) && $res->symb()) {
 4697:                     push(@symbs,$res->symb());
 4698:                 }
 4699:             }
 4700:         }
 4701:     } else {
 4702:         @symbs = ($currsymb);
 4703:     }
 4704:     foreach my $symb (@symbs) {
 4705:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 4706:         if ($css_href =~ /\S/) {
 4707:             unless ($css_href =~ m{https?://}) {
 4708:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 4709:                 my $proburl =  &Apache::lonnet::clutter($url);
 4710:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 4711:                 unless ($css_href =~ m{^/}) {
 4712:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 4713:                 }
 4714:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 4715:                     unless (($httpref{'httpref.'.$css_href}) ||
 4716:                             (&Apache::lonnet::is_on_map($css_href))) {
 4717:                         my $thisurl = $proburl;
 4718:                         if ($env{'httpref.'.$proburl}) {
 4719:                             $thisurl = $env{'httpref.'.$proburl};
 4720:                         }
 4721:                         $httpref{'httpref.'.$css_href} = $thisurl;
 4722:                     }
 4723:                 }
 4724:             }
 4725:             $cssrefs{$css_href} = 1;
 4726:         }
 4727:     }
 4728:     if (keys(%httpref)) {
 4729:         &Apache::lonnet::appenv(\%httpref);
 4730:     }
 4731:     if (keys(%cssrefs)) {
 4732:         foreach my $css_href (keys(%cssrefs)) {
 4733:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 4734:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 4735:         }
 4736:     }
 4737:     return $links;
 4738: }
 4739: 
 4740: =pod
 4741: 
 4742: =item * &get_student_answers() 
 4743: 
 4744: show a snapshot of how student was answering problem
 4745: 
 4746: =cut
 4747: 
 4748: sub get_student_answers {
 4749:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4750:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4751:   my (%moreenv);
 4752:   my @elements=('symb','courseid','domain','username');
 4753:   foreach my $element (@elements) {
 4754:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4755:   }
 4756:   $moreenv{'grade_target'}='answer';
 4757:   %moreenv=(%form,%moreenv);
 4758:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4759:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4760:   return $userview;
 4761: }
 4762: 
 4763: =pod
 4764: 
 4765: =item * &submlink()
 4766: 
 4767: Inputs: $text $uname $udom $symb $target
 4768: 
 4769: Returns: A link to grades.pm such as to see the SUBM view of a student
 4770: 
 4771: =cut
 4772: 
 4773: ###############################################
 4774: sub submlink {
 4775:     my ($text,$uname,$udom,$symb,$target)=@_;
 4776:     if (!($uname && $udom)) {
 4777: 	(my $cursymb, my $courseid,$udom,$uname)=
 4778: 	    &Apache::lonnet::whichuser($symb);
 4779: 	if (!$symb) { $symb=$cursymb; }
 4780:     }
 4781:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4782:     $symb=&escape($symb);
 4783:     if ($target) { $target=" target=\"$target\""; }
 4784:     return
 4785:         '<a href="/adm/grades?command=submission'.
 4786:         '&amp;symb='.$symb.
 4787:         '&amp;student='.$uname.
 4788:         '&amp;userdom='.$udom.'"'.
 4789:         $target.'>'.$text.'</a>';
 4790: }
 4791: ##############################################
 4792: 
 4793: =pod
 4794: 
 4795: =item * &pgrdlink()
 4796: 
 4797: Inputs: $text $uname $udom $symb $target
 4798: 
 4799: Returns: A link to grades.pm such as to see the PGRD view of a student
 4800: 
 4801: =cut
 4802: 
 4803: ###############################################
 4804: sub pgrdlink {
 4805:     my $link=&submlink(@_);
 4806:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4807:     return $link;
 4808: }
 4809: ##############################################
 4810: 
 4811: =pod
 4812: 
 4813: =item * &pprmlink()
 4814: 
 4815: Inputs: $text $uname $udom $symb $target
 4816: 
 4817: Returns: A link to parmset.pm such as to see the PPRM view of a
 4818: student and a specific resource
 4819: 
 4820: =cut
 4821: 
 4822: ###############################################
 4823: sub pprmlink {
 4824:     my ($text,$uname,$udom,$symb,$target)=@_;
 4825:     if (!($uname && $udom)) {
 4826: 	(my $cursymb, my $courseid,$udom,$uname)=
 4827: 	    &Apache::lonnet::whichuser($symb);
 4828: 	if (!$symb) { $symb=$cursymb; }
 4829:     }
 4830:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4831:     $symb=&escape($symb);
 4832:     if ($target) { $target="target=\"$target\""; }
 4833:     return '<a href="/adm/parmset?command=set&amp;'.
 4834: 	'symb='.$symb.'&amp;uname='.$uname.
 4835: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4836: }
 4837: ##############################################
 4838: 
 4839: =pod
 4840: 
 4841: =back
 4842: 
 4843: =cut
 4844: 
 4845: ###############################################
 4846: 
 4847: 
 4848: sub timehash {
 4849:     my ($thistime) = @_;
 4850:     my $timezone = &Apache::lonlocal::gettimezone();
 4851:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4852:                      ->set_time_zone($timezone);
 4853:     my $wday = $dt->day_of_week();
 4854:     if ($wday == 7) { $wday = 0; }
 4855:     return ( 'second' => $dt->second(),
 4856:              'minute' => $dt->minute(),
 4857:              'hour'   => $dt->hour(),
 4858:              'day'     => $dt->day_of_month(),
 4859:              'month'   => $dt->month(),
 4860:              'year'    => $dt->year(),
 4861:              'weekday' => $wday,
 4862:              'dayyear' => $dt->day_of_year(),
 4863:              'dlsav'   => $dt->is_dst() );
 4864: }
 4865: 
 4866: sub utc_string {
 4867:     my ($date)=@_;
 4868:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4869: }
 4870: 
 4871: sub maketime {
 4872:     my %th=@_;
 4873:     my ($epoch_time,$timezone,$dt);
 4874:     $timezone = &Apache::lonlocal::gettimezone();
 4875:     eval {
 4876:         $dt = DateTime->new( year   => $th{'year'},
 4877:                              month  => $th{'month'},
 4878:                              day    => $th{'day'},
 4879:                              hour   => $th{'hour'},
 4880:                              minute => $th{'minute'},
 4881:                              second => $th{'second'},
 4882:                              time_zone => $timezone,
 4883:                          );
 4884:     };
 4885:     if (!$@) {
 4886:         $epoch_time = $dt->epoch;
 4887:         if ($epoch_time) {
 4888:             return $epoch_time;
 4889:         }
 4890:     }
 4891:     return POSIX::mktime(
 4892:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4893:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4894: }
 4895: 
 4896: #########################################
 4897: 
 4898: sub findallcourses {
 4899:     my ($roles,$uname,$udom) = @_;
 4900:     my %roles;
 4901:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4902:     my %courses;
 4903:     my $now=time;
 4904:     if (!defined($uname)) {
 4905:         $uname = $env{'user.name'};
 4906:     }
 4907:     if (!defined($udom)) {
 4908:         $udom = $env{'user.domain'};
 4909:     }
 4910:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4911:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4912:         if (!%roles) {
 4913:             %roles = (
 4914:                        cc => 1,
 4915:                        co => 1,
 4916:                        in => 1,
 4917:                        ep => 1,
 4918:                        ta => 1,
 4919:                        cr => 1,
 4920:                        st => 1,
 4921:              );
 4922:         }
 4923:         foreach my $entry (keys(%roleshash)) {
 4924:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4925:             if ($trole =~ /^cr/) { 
 4926:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4927:             } else {
 4928:                 next if (!exists($roles{$trole}));
 4929:             }
 4930:             if ($tend) {
 4931:                 next if ($tend < $now);
 4932:             }
 4933:             if ($tstart) {
 4934:                 next if ($tstart > $now);
 4935:             }
 4936:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4937:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4938:             my $value = $trole.'/'.$cdom.'/';
 4939:             if ($secpart eq '') {
 4940:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4941:                 $sec = 'none';
 4942:                 $value .= $cnum.'/';
 4943:             } else {
 4944:                 $cnum = $cnumpart;
 4945:                 ($sec,$role) = split(/_/,$secpart);
 4946:                 $value .= $cnum.'/'.$sec;
 4947:             }
 4948:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4949:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4950:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4951:                 }
 4952:             } else {
 4953:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4954:             }
 4955:         }
 4956:     } else {
 4957:         foreach my $key (keys(%env)) {
 4958: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4959:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4960: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4961: 	        next if ($role eq 'ca' || $role eq 'aa');
 4962: 	        next if (%roles && !exists($roles{$role}));
 4963: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4964:                 my $active=1;
 4965:                 if ($starttime) {
 4966: 		    if ($now<$starttime) { $active=0; }
 4967:                 }
 4968:                 if ($endtime) {
 4969:                     if ($now>$endtime) { $active=0; }
 4970:                 }
 4971:                 if ($active) {
 4972:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4973:                     if ($sec eq '') {
 4974:                         $sec = 'none';
 4975:                     } else {
 4976:                         $value .= $sec;
 4977:                     }
 4978:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4979:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4980:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4981:                         }
 4982:                     } else {
 4983:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4984:                     }
 4985:                 }
 4986:             }
 4987:         }
 4988:     }
 4989:     return %courses;
 4990: }
 4991: 
 4992: ###############################################
 4993: 
 4994: sub blockcheck {
 4995:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 4996: 
 4997:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 4998:         my ($has_evb,$check_ipaccess);
 4999:         my $dom = $env{'user.domain'};
 5000:         if ($env{'request.course.id'}) {
 5001:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5002:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5003:             my $checkrole = "cm./$cdom/$cnum";
 5004:             my $sec = $env{'request.course.sec'};
 5005:             if ($sec ne '') {
 5006:                 $checkrole .= "/$sec";
 5007:             }
 5008:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 5009:                 ($env{'request.role'} !~ /^st/)) {
 5010:                 $has_evb = 1;
 5011:             }
 5012:             unless ($has_evb) {
 5013:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 5014:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 5015:                     if ($udom eq $cdom) {
 5016:                         $check_ipaccess = 1;
 5017:                     }
 5018:                 }
 5019:             }
 5020:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 5021:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 5022:             my $checkrole;
 5023:             if ($env{'request.role.domain'} eq '') {
 5024:                 $checkrole = "cm./$env{'user.domain'}/";
 5025:             } else {
 5026:                 $checkrole = "cm./$env{'request.role.domain'}/";
 5027:             }
 5028:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 5029:                 $has_evb = 1;
 5030:             }
 5031:         }
 5032:         unless ($has_evb || $check_ipaccess) {
 5033:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 5034:             if (($dom eq 'public') && ($activity eq 'port')) {
 5035:                 $dom = $udom;
 5036:             }
 5037:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 5038:                 $check_ipaccess = 1;
 5039:             } else {
 5040:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 5041:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 5042:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 5043:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 5044:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 5045:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 5046:                         $check_ipaccess = 1;
 5047:                     }
 5048:                 }
 5049:             }
 5050:         }
 5051:         if ($check_ipaccess) {
 5052:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 5053:             unless (defined($cached)) {
 5054:                 my %domconfig =
 5055:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 5056:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 5057:             }
 5058:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 5059:                 foreach my $id (keys(%{$ipaccessref})) {
 5060:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 5061:                         my $range = $ipaccessref->{$id}->{'ip'};
 5062:                         if ($range) {
 5063:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 5064:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 5065:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 5066:                                         return ('','','',$id,$dom);
 5067:                                         last;
 5068:                                     }
 5069:                                 }
 5070:                             }
 5071:                         }
 5072:                     }
 5073:                 }
 5074:             }
 5075:         }
 5076:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5077:             return ();
 5078:         }
 5079:     }
 5080:     if (defined($udom) && defined($uname)) {
 5081:         # If uname and udom are for a course, check for blocks in the course.
 5082:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5083:             my ($startblock,$endblock,$triggerblock) =
 5084:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5085:             return ($startblock,$endblock,$triggerblock);
 5086:         }
 5087:     } else {
 5088:         $udom = $env{'user.domain'};
 5089:         $uname = $env{'user.name'};
 5090:     }
 5091: 
 5092:     my $startblock = 0;
 5093:     my $endblock = 0;
 5094:     my $triggerblock = '';
 5095:     my %live_courses;
 5096:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5097:         %live_courses = &findallcourses(undef,$uname,$udom);
 5098:     }
 5099: 
 5100:     # If uname is for a user, and activity is course-specific, i.e.,
 5101:     # boards, chat or groups, check for blocking in current course only.
 5102: 
 5103:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5104:          $activity eq 'groups' || $activity eq 'printout' ||
 5105:          $activity eq 'search' || $activity eq 'reinit' ||
 5106:          $activity eq 'alert') && ($env{'request.course.id'})) {
 5107:         foreach my $key (keys(%live_courses)) {
 5108:             if ($key ne $env{'request.course.id'}) {
 5109:                 delete($live_courses{$key});
 5110:             }
 5111:         }
 5112:     }
 5113: 
 5114:     my $otheruser = 0;
 5115:     my %own_courses;
 5116:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5117:         # Resource belongs to user other than current user.
 5118:         $otheruser = 1;
 5119:         # Gather courses for current user
 5120:         %own_courses = 
 5121:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5122:     }
 5123: 
 5124:     # Gather active course roles - course coordinator, instructor, 
 5125:     # exam proctor, ta, student, or custom role.
 5126: 
 5127:     foreach my $course (keys(%live_courses)) {
 5128:         my ($cdom,$cnum);
 5129:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5130:             $cdom = $env{'course.'.$course.'.domain'};
 5131:             $cnum = $env{'course.'.$course.'.num'};
 5132:         } else {
 5133:             ($cdom,$cnum) = split(/_/,$course); 
 5134:         }
 5135:         my $no_ownblock = 0;
 5136:         my $no_userblock = 0;
 5137:         if ($otheruser && $activity ne 'com') {
 5138:             # Check if current user has 'evb' priv for this
 5139:             if (defined($own_courses{$course})) {
 5140:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5141:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5142:                     if ($sec ne 'none') {
 5143:                         $checkrole .= '/'.$sec;
 5144:                     }
 5145:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5146:                         $no_ownblock = 1;
 5147:                         last;
 5148:                     }
 5149:                 }
 5150:             }
 5151:             # if they have 'evb' priv and are currently not playing student
 5152:             next if (($no_ownblock) &&
 5153:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5154:         }
 5155:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5156:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5157:             if ($sec ne 'none') {
 5158:                 $checkrole .= '/'.$sec;
 5159:             }
 5160:             if ($otheruser) {
 5161:                 # Resource belongs to user other than current user.
 5162:                 # Assemble privs for that user, and check for 'evb' priv.
 5163:                 my (%allroles,%userroles);
 5164:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5165:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5166:                         my ($trole,$tdom,$tnum,$tsec);
 5167:                         if ($entry =~ /^cr/) {
 5168:                             ($trole,$tdom,$tnum,$tsec) = 
 5169:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5170:                         } else {
 5171:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5172:                         }
 5173:                         my ($spec,$area,$trest);
 5174:                         $area = '/'.$tdom.'/'.$tnum;
 5175:                         $trest = $tnum;
 5176:                         if ($tsec ne '') {
 5177:                             $area .= '/'.$tsec;
 5178:                             $trest .= '/'.$tsec;
 5179:                         }
 5180:                         $spec = $trole.'.'.$area;
 5181:                         if ($trole =~ /^cr/) {
 5182:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5183:                                                               $tdom,$spec,$trest,$area);
 5184:                         } else {
 5185:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5186:                                                                 $tdom,$spec,$trest,$area);
 5187:                         }
 5188:                     }
 5189:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5190:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5191:                         if ($1) {
 5192:                             $no_userblock = 1;
 5193:                             last;
 5194:                         }
 5195:                     }
 5196:                 }
 5197:             } else {
 5198:                 # Resource belongs to current user
 5199:                 # Check for 'evb' priv via lonnet::allowed().
 5200:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5201:                     $no_ownblock = 1;
 5202:                     last;
 5203:                 }
 5204:             }
 5205:         }
 5206:         # if they have the evb priv and are currently not playing student
 5207:         next if (($no_ownblock) &&
 5208:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5209:         next if ($no_userblock);
 5210: 
 5211:         # Retrieve blocking times and identity of blocker for course
 5212:         # of specified user, unless user has 'evb' privilege.
 5213:         
 5214:         my ($start,$end,$trigger) = 
 5215:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5216:         if (($start != 0) && 
 5217:             (($startblock == 0) || ($startblock > $start))) {
 5218:             $startblock = $start;
 5219:             if ($trigger ne '') {
 5220:                 $triggerblock = $trigger;
 5221:             }
 5222:         }
 5223:         if (($end != 0)  &&
 5224:             (($endblock == 0) || ($endblock < $end))) {
 5225:             $endblock = $end;
 5226:             if ($trigger ne '') {
 5227:                 $triggerblock = $trigger;
 5228:             }
 5229:         }
 5230:     }
 5231:     return ($startblock,$endblock,$triggerblock);
 5232: }
 5233: 
 5234: sub get_blocks {
 5235:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5236:     my $startblock = 0;
 5237:     my $endblock = 0;
 5238:     my $triggerblock = '';
 5239:     my $course = $cdom.'_'.$cnum;
 5240:     $setters->{$course} = {};
 5241:     $setters->{$course}{'staff'} = [];
 5242:     $setters->{$course}{'times'} = [];
 5243:     $setters->{$course}{'triggers'} = [];
 5244:     my (@blockers,%triggered);
 5245:     my $now = time;
 5246:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5247:     if ($activity eq 'docs') {
 5248:         my ($blocked,$nosymbcache,$noenccheck);
 5249:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5250:             $blocked = 1;
 5251:             $nosymbcache = 1;
 5252:             $noenccheck = 1;
 5253:         }
 5254:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5255:         foreach my $block (@blockers) {
 5256:             if ($block =~ /^firstaccess____(.+)$/) {
 5257:                 my $item = $1;
 5258:                 my $type = 'map';
 5259:                 my $timersymb = $item;
 5260:                 if ($item eq 'course') {
 5261:                     $type = 'course';
 5262:                 } elsif ($item =~ /___\d+___/) {
 5263:                     $type = 'resource';
 5264:                 } else {
 5265:                     $timersymb = &Apache::lonnet::symbread($item);
 5266:                 }
 5267:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5268:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5269:                 $triggered{$block} = {
 5270:                                        start => $start,
 5271:                                        end   => $end,
 5272:                                        type  => $type,
 5273:                                      };
 5274:             }
 5275:         }
 5276:     } else {
 5277:         foreach my $block (keys(%commblocks)) {
 5278:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5279:                 my ($start,$end) = ($1,$2);
 5280:                 if ($start <= time && $end >= time) {
 5281:                     if (ref($commblocks{$block}) eq 'HASH') {
 5282:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5283:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5284:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5285:                                     push(@blockers,$block);
 5286:                                 }
 5287:                             }
 5288:                         }
 5289:                     }
 5290:                 }
 5291:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5292:                 my $item = $1;
 5293:                 my $timersymb = $item; 
 5294:                 my $type = 'map';
 5295:                 if ($item eq 'course') {
 5296:                     $type = 'course';
 5297:                 } elsif ($item =~ /___\d+___/) {
 5298:                     $type = 'resource';
 5299:                 } else {
 5300:                     $timersymb = &Apache::lonnet::symbread($item);
 5301:                 }
 5302:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5303:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5304:                 if ($start && $end) {
 5305:                     if (($start <= time) && ($end >= time)) {
 5306:                         if (ref($commblocks{$block}) eq 'HASH') {
 5307:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5308:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5309:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5310:                                         push(@blockers,$block);
 5311:                                         $triggered{$block} = {
 5312:                                                                start => $start,
 5313:                                                                end   => $end,
 5314:                                                                type  => $type,
 5315:                                                              };
 5316:                                     }
 5317:                                 }
 5318:                             }
 5319:                         }
 5320:                     }
 5321:                 }
 5322:             }
 5323:         }
 5324:     }
 5325:     foreach my $blocker (@blockers) {
 5326:         my ($staff_name,$staff_dom,$title,$blocks) =
 5327:             &parse_block_record($commblocks{$blocker});
 5328:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5329:         my ($start,$end,$triggertype);
 5330:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5331:             ($start,$end) = ($1,$2);
 5332:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5333:             $start = $triggered{$blocker}{'start'};
 5334:             $end = $triggered{$blocker}{'end'};
 5335:             $triggertype = $triggered{$blocker}{'type'};
 5336:         }
 5337:         if ($start) {
 5338:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5339:             if ($triggertype) {
 5340:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5341:             } else {
 5342:                 push(@{$$setters{$course}{'triggers'}},0);
 5343:             }
 5344:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5345:                 $startblock = $start;
 5346:                 if ($triggertype) {
 5347:                     $triggerblock = $blocker;
 5348:                 }
 5349:             }
 5350:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5351:                $endblock = $end;
 5352:                if ($triggertype) {
 5353:                    $triggerblock = $blocker;
 5354:                }
 5355:             }
 5356:         }
 5357:     }
 5358:     return ($startblock,$endblock,$triggerblock);
 5359: }
 5360: 
 5361: sub parse_block_record {
 5362:     my ($record) = @_;
 5363:     my ($setuname,$setudom,$title,$blocks);
 5364:     if (ref($record) eq 'HASH') {
 5365:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5366:         $title = &unescape($record->{'event'});
 5367:         $blocks = $record->{'blocks'};
 5368:     } else {
 5369:         my @data = split(/:/,$record,3);
 5370:         if (scalar(@data) eq 2) {
 5371:             $title = $data[1];
 5372:             ($setuname,$setudom) = split(/@/,$data[0]);
 5373:         } else {
 5374:             ($setuname,$setudom,$title) = @data;
 5375:         }
 5376:         $blocks = { 'com' => 'on' };
 5377:     }
 5378:     return ($setuname,$setudom,$title,$blocks);
 5379: }
 5380: 
 5381: sub blocking_status {
 5382:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5383:     my %setters;
 5384: 
 5385: # check for active blocking
 5386:     if ($clientip eq '') {
 5387:         $clientip = &Apache::lonnet::get_requestor_ip();
 5388:     }
 5389:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5390:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5391:     my $blocked = 0;
 5392:     if (($startblock && $endblock) || ($by_ip)) {
 5393:         $blocked = 1;
 5394:     }
 5395: 
 5396: # caller just wants to know whether a block is active
 5397:     if (!wantarray) { return $blocked; }
 5398: 
 5399: # build a link to a popup window containing the details
 5400:     my $querystring  = "?activity=$activity";
 5401: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5402:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5403:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 5404:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5405:     } elsif ($activity eq 'docs') {
 5406:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5407:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5408:         if ($symb) {
 5409:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5410:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5411:         }
 5412:     }
 5413: 
 5414:     my $output .= <<'END_MYBLOCK';
 5415: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5416:     var options = "width=" + w + ",height=" + h + ",";
 5417:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5418:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5419:     var newWin = window.open(url, wdwName, options);
 5420:     newWin.focus();
 5421: }
 5422: END_MYBLOCK
 5423: 
 5424:     $output = Apache::lonhtmlcommon::scripttag($output);
 5425:   
 5426:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5427:     my $text = &mt('Communication Blocked');
 5428:     my $class = 'LC_comblock';
 5429:     if ($activity eq 'docs') {
 5430:         $text = &mt('Content Access Blocked');
 5431:         $class = '';
 5432:     } elsif ($activity eq 'printout') {
 5433:         $text = &mt('Printing Blocked');
 5434:     } elsif ($activity eq 'passwd') {
 5435:         $text = &mt('Password Changing Blocked');
 5436:     } elsif ($activity eq 'grades') {
 5437:         $text = &mt('Gradebook Blocked');
 5438:     } elsif ($activity eq 'search') {
 5439:         $text = &mt('Search Blocked');
 5440:     } elsif ($activity eq 'alert') {
 5441:         $text = &mt('Checking Critical Messages Blocked');
 5442:     } elsif ($activity eq 'reinit') {
 5443:         $text = &mt('Checking Course Update Blocked');
 5444:     } elsif ($activity eq 'about') {
 5445:         $text = &mt('Access to User Information Pages Blocked');
 5446:     } elsif ($activity eq 'wishlist') {
 5447:         $text = &mt('Access to Stored Links Blocked');
 5448:     } elsif ($activity eq 'annotate') {
 5449:         $text = &mt('Access to Annotations Blocked');
 5450:     }
 5451:     $output .= <<"END_BLOCK";
 5452: <div class='$class'>
 5453:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5454:   title='$text'>
 5455:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5456:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5457:   title='$text'>$text</a>
 5458: </div>
 5459: 
 5460: END_BLOCK
 5461: 
 5462:     return ($blocked, $output);
 5463: }
 5464: 
 5465: ###############################################
 5466: 
 5467: sub check_ip_acc {
 5468:     my ($acc,$clientip)=@_;
 5469:     &Apache::lonxml::debug("acc is $acc");
 5470:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5471:         return 1;
 5472:     }
 5473:     my $allowed=0;
 5474:     my $ip;
 5475:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5476:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5477:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5478:     } else {
 5479:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5480:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5481:     }
 5482: 
 5483:     my $name;
 5484:     my %access = (
 5485:                      allowfrom => 1,
 5486:                      denyfrom  => 0,
 5487:                  );
 5488:     my @allows;
 5489:     my @denies;
 5490:     foreach my $item (split(',',$acc)) {
 5491:         $item =~ s/^\s*//;
 5492:         $item =~ s/\s*$//;
 5493:         if ($item =~ /^\!(.+)$/) {
 5494:             push(@denies,$1);
 5495:         } else {
 5496:             push(@allows,$item);
 5497:         }
 5498:     }
 5499:     my $numdenies = scalar(@denies);
 5500:     my $numallows = scalar(@allows);
 5501:     my $count = 0;
 5502:     foreach my $pattern (@denies,@allows) {
 5503:         $count ++;
 5504:         my $acctype = 'allowfrom';
 5505:         if ($count <= $numdenies) {
 5506:             $acctype = 'denyfrom';
 5507:         }
 5508:         if ($pattern =~ /\*$/) {
 5509:             #35.8.*
 5510:             $pattern=~s/\*//;
 5511:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5512:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5513:             #35.8.3.[34-56]
 5514:             my $low=$2;
 5515:             my $high=$3;
 5516:             $pattern=$1;
 5517:             if ($ip =~ /^\Q$pattern\E/) {
 5518:                 my $last=(split(/\./,$ip))[3];
 5519:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5520:             }
 5521:         } elsif ($pattern =~ /^\*/) {
 5522:             #*.msu.edu
 5523:             $pattern=~s/\*//;
 5524:             if (!defined($name)) {
 5525:                 use Socket;
 5526:                 my $netaddr=inet_aton($ip);
 5527:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5528:             }
 5529:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5530:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5531:             #127.0.0.1
 5532:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5533:         } else {
 5534:             #some.name.com
 5535:             if (!defined($name)) {
 5536:                 use Socket;
 5537:                 my $netaddr=inet_aton($ip);
 5538:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5539:             }
 5540:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5541:         }
 5542:         if ($allowed =~ /^(0|1)$/) { last; }
 5543:     }
 5544:     if ($allowed eq '') {
 5545:         if ($numdenies && !$numallows) {
 5546:             $allowed = 1;
 5547:         } else {
 5548:             $allowed = 0;
 5549:         }
 5550:     }
 5551:     return $allowed;
 5552: }
 5553: 
 5554: ###############################################
 5555: 
 5556: =pod
 5557: 
 5558: =head1 Domain Template Functions
 5559: 
 5560: =over 4
 5561: 
 5562: =item * &determinedomain()
 5563: 
 5564: Inputs: $domain (usually will be undef)
 5565: 
 5566: Returns: Determines which domain should be used for designs
 5567: 
 5568: =cut
 5569: 
 5570: ###############################################
 5571: sub determinedomain {
 5572:     my $domain=shift;
 5573:     if (! $domain) {
 5574:         # Determine domain if we have not been given one
 5575:         $domain = &Apache::lonnet::default_login_domain();
 5576:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5577:         if ($env{'request.role.domain'}) { 
 5578:             $domain=$env{'request.role.domain'}; 
 5579:         }
 5580:     }
 5581:     return $domain;
 5582: }
 5583: ###############################################
 5584: 
 5585: sub devalidate_domconfig_cache {
 5586:     my ($udom)=@_;
 5587:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5588: }
 5589: 
 5590: # ---------------------- Get domain configuration for a domain
 5591: sub get_domainconf {
 5592:     my ($udom) = @_;
 5593:     my $cachetime=1800;
 5594:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5595:     if (defined($cached)) { return %{$result}; }
 5596: 
 5597:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5598: 					     ['login','rolecolors','autoenroll'],$udom);
 5599:     my (%designhash,%legacy);
 5600:     if (keys(%domconfig) > 0) {
 5601:         if (ref($domconfig{'login'}) eq 'HASH') {
 5602:             if (keys(%{$domconfig{'login'}})) {
 5603:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5604:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5605:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5606:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5607:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5608:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5609:                                         if ($key eq 'loginvia') {
 5610:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5611:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5612:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5613:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5614:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5615:                                                 } else {
 5616:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5617:                                                 }
 5618:                                             }
 5619:                                         } elsif ($key eq 'headtag') {
 5620:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5621:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5622:                                             }
 5623:                                         }
 5624:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5625:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5626:                                         }
 5627:                                     }
 5628:                                 }
 5629:                             }
 5630:                         } elsif ($key eq 'saml') {
 5631:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5632:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 5633:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 5634:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 5635:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 5636:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 5637:                                         }
 5638:                                     }
 5639:                                 }
 5640:                             }
 5641:                         } else {
 5642:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5643:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5644:                                     $domconfig{'login'}{$key}{$img};
 5645:                             }
 5646:                         }
 5647:                     } else {
 5648:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5649:                     }
 5650:                 }
 5651:             } else {
 5652:                 $legacy{'login'} = 1;
 5653:             }
 5654:         } else {
 5655:             $legacy{'login'} = 1;
 5656:         }
 5657:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5658:             if (keys(%{$domconfig{'rolecolors'}})) {
 5659:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5660:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5661:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5662:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5663:                         }
 5664:                     }
 5665:                 }
 5666:             } else {
 5667:                 $legacy{'rolecolors'} = 1;
 5668:             }
 5669:         } else {
 5670:             $legacy{'rolecolors'} = 1;
 5671:         }
 5672:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5673:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5674:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5675:             }
 5676:         }
 5677:         if (keys(%legacy) > 0) {
 5678:             my %legacyhash = &get_legacy_domconf($udom);
 5679:             foreach my $item (keys(%legacyhash)) {
 5680:                 if ($item =~ /^\Q$udom\E\.login/) {
 5681:                     if ($legacy{'login'}) { 
 5682:                         $designhash{$item} = $legacyhash{$item};
 5683:                     }
 5684:                 } else {
 5685:                     if ($legacy{'rolecolors'}) {
 5686:                         $designhash{$item} = $legacyhash{$item};
 5687:                     }
 5688:                 }
 5689:             }
 5690:         }
 5691:     } else {
 5692:         %designhash = &get_legacy_domconf($udom); 
 5693:     }
 5694:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5695: 				  $cachetime);
 5696:     return %designhash;
 5697: }
 5698: 
 5699: sub get_legacy_domconf {
 5700:     my ($udom) = @_;
 5701:     my %legacyhash;
 5702:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5703:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5704:     if (-e $designfile) {
 5705:         if ( open (my $fh,'<',$designfile) ) {
 5706:             while (my $line = <$fh>) {
 5707:                 next if ($line =~ /^\#/);
 5708:                 chomp($line);
 5709:                 my ($key,$val)=(split(/\=/,$line));
 5710:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5711:             }
 5712:             close($fh);
 5713:         }
 5714:     }
 5715:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5716:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5717:     }
 5718:     return %legacyhash;
 5719: }
 5720: 
 5721: =pod
 5722: 
 5723: =item * &domainlogo()
 5724: 
 5725: Inputs: $domain (usually will be undef)
 5726: 
 5727: Returns: A link to a domain logo, if the domain logo exists.
 5728: If the domain logo does not exist, a description of the domain.
 5729: 
 5730: =cut
 5731: 
 5732: ###############################################
 5733: sub domainlogo {
 5734:     my $domain = &determinedomain(shift);
 5735:     my %designhash = &get_domainconf($domain);    
 5736:     # See if there is a logo
 5737:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5738:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5739:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5740: 	    if ($imgsrc =~ m{^/res/}) {
 5741: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5742: 		&Apache::lonnet::repcopy($local_name);
 5743: 	    }
 5744: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5745:         }
 5746:         my $alttext = $domain;
 5747:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 5748:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 5749:         }
 5750:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 5751:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5752:         return &Apache::lonnet::domain($domain,'description');
 5753:     } else {
 5754:         return '';
 5755:     }
 5756: }
 5757: ##############################################
 5758: 
 5759: =pod
 5760: 
 5761: =item * &designparm()
 5762: 
 5763: Inputs: $which parameter; $domain (usually will be undef)
 5764: 
 5765: Returns: value of designparamter $which
 5766: 
 5767: =cut
 5768: 
 5769: 
 5770: ##############################################
 5771: sub designparm {
 5772:     my ($which,$domain)=@_;
 5773:     if (exists($env{'environment.color.'.$which})) {
 5774:         return $env{'environment.color.'.$which};
 5775:     }
 5776:     $domain=&determinedomain($domain);
 5777:     my %domdesign;
 5778:     unless ($domain eq 'public') {
 5779:         %domdesign = &get_domainconf($domain);
 5780:     }
 5781:     my $output;
 5782:     if ($domdesign{$domain.'.'.$which} ne '') {
 5783:         $output = $domdesign{$domain.'.'.$which};
 5784:     } else {
 5785:         $output = $defaultdesign{$which};
 5786:     }
 5787:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5788:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5789:         if ($output =~ m{^/(adm|res)/}) {
 5790:             if ($output =~ m{^/res/}) {
 5791:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5792:                 &Apache::lonnet::repcopy($local_name);
 5793:             }
 5794:             $output = &lonhttpdurl($output);
 5795:         }
 5796:     }
 5797:     return $output;
 5798: }
 5799: 
 5800: ##############################################
 5801: =pod
 5802: 
 5803: =item * &authorspace()
 5804: 
 5805: Inputs: $url (usually will be undef).
 5806: 
 5807: Returns: Path to Authoring Space containing the resource or 
 5808:          directory being viewed (or for which action is being taken). 
 5809:          If $url is provided, and begins /priv/<domain>/<uname>
 5810:          the path will be that portion of the $context argument.
 5811:          Otherwise the path will be for the author space of the current
 5812:          user when the current role is author, or for that of the 
 5813:          co-author/assistant co-author space when the current role 
 5814:          is co-author or assistant co-author.
 5815: 
 5816: =cut
 5817: 
 5818: sub authorspace {
 5819:     my ($url) = @_;
 5820:     if ($url ne '') {
 5821:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5822:            return $1;
 5823:         }
 5824:     }
 5825:     my $caname = '';
 5826:     my $cadom = '';
 5827:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5828:         ($cadom,$caname) =
 5829:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5830:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5831:         $caname = $env{'user.name'};
 5832:         $cadom = $env{'user.domain'};
 5833:     }
 5834:     if (($caname ne '') && ($cadom ne '')) {
 5835:         return "/priv/$cadom/$caname/";
 5836:     }
 5837:     return;
 5838: }
 5839: 
 5840: ##############################################
 5841: =pod
 5842: 
 5843: =item * &head_subbox()
 5844: 
 5845: Inputs: $content (contains HTML code with page functions, etc.)
 5846: 
 5847: Returns: HTML div with $content
 5848:          To be included in page header
 5849: 
 5850: =cut
 5851: 
 5852: sub head_subbox {
 5853:     my ($content)=@_;
 5854:     my $output =
 5855:         '<div class="LC_head_subbox">'
 5856:        .$content
 5857:        .'</div>'
 5858: }
 5859: 
 5860: ##############################################
 5861: =pod
 5862: 
 5863: =item * &CSTR_pageheader()
 5864: 
 5865: Input: (optional) filename from which breadcrumb trail is built.
 5866:        In most cases no input as needed, as $env{'request.filename'}
 5867:        is appropriate for use in building the breadcrumb trail.
 5868:        frameset flag
 5869:        If page header is being requested for use in a frameset, then
 5870:        the second (option) argument -- frameset will be true, and
 5871:        the target attribute set for links should be target="_parent".
 5872: 
 5873: Returns: HTML div with CSTR path and recent box
 5874:          To be included on Authoring Space pages
 5875: 
 5876: =cut
 5877: 
 5878: sub CSTR_pageheader {
 5879:     my ($trailfile,$frameset) = @_;
 5880:     if ($trailfile eq '') {
 5881:         $trailfile = $env{'request.filename'};
 5882:     }
 5883: 
 5884: # this is for resources; directories have customtitle, and crumbs
 5885: # and select recent are created in lonpubdir.pm
 5886: 
 5887:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5888:     my ($udom,$uname,$thisdisfn)=
 5889:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5890:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5891:     $formaction =~ s{/+}{/}g;
 5892: 
 5893:     my $parentpath = '';
 5894:     my $lastitem = '';
 5895:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5896:         $parentpath = $1;
 5897:         $lastitem = $2;
 5898:     } else {
 5899:         $lastitem = $thisdisfn;
 5900:     }
 5901: 
 5902:     my ($target,$crumbtarget) = (' target="_top"','_top');
 5903:     if ($frameset) {
 5904:         $target = ' target="_parent"';
 5905:         $crumbtarget = '_parent';
 5906:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 5907:         $target = '';
 5908:         $crumbtarget = '';
 5909:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 5910:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 5911:         $crumbtarget = $env{'request.deeplink.target'};
 5912:     }
 5913: 
 5914:     my $output =
 5915:          '<div>'
 5916:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5917:         .'<b>'.&mt('Authoring Space:').'</b> '
 5918:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 5919:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 5920: 
 5921:     if ($lastitem) {
 5922:         $output .=
 5923:              '<span class="LC_filename">'
 5924:             .$lastitem
 5925:             .'</span>';
 5926:     }
 5927:     $output .=
 5928:          '<br />'
 5929:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 5930:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5931:         .'</form>'
 5932:         .&Apache::lonmenu::constspaceform($frameset)
 5933:         .'</div>';
 5934: 
 5935:     return $output;
 5936: }
 5937: 
 5938: ###############################################
 5939: ###############################################
 5940: 
 5941: =pod
 5942: 
 5943: =back
 5944: 
 5945: =head1 HTML Helpers
 5946: 
 5947: =over 4
 5948: 
 5949: =item * &bodytag()
 5950: 
 5951: Returns a uniform header for LON-CAPA web pages.
 5952: 
 5953: Inputs: 
 5954: 
 5955: =over 4
 5956: 
 5957: =item * $title, A title to be displayed on the page.
 5958: 
 5959: =item * $function, the current role (can be undef).
 5960: 
 5961: =item * $addentries, extra parameters for the <body> tag.
 5962: 
 5963: =item * $bodyonly, if defined, only return the <body> tag.
 5964: 
 5965: =item * $domain, if defined, force a given domain.
 5966: 
 5967: =item * $forcereg, if page should register as content page (relevant for 
 5968:             text interface only)
 5969: 
 5970: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5971:                      navigational links
 5972: 
 5973: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5974: 
 5975: =item * $no_inline_link, if true and in remote mode, don't show the
 5976:          'Switch To Inline Menu' link
 5977: 
 5978: =item * $args, optional argument valid values are
 5979:             no_auto_mt_title -> prevents &mt()ing the title arg
 5980:             use_absolute     -> for external resource or syllabus, this will
 5981:                                 contain https://<hostname> if server uses
 5982:                                 https (as per hosts.tab), but request is for http
 5983:             hostname         -> hostname, from $r->hostname().
 5984: 
 5985: =item * $advtoolsref, optional argument, ref to an array containing
 5986:             inlineremote items to be added in "Functions" menu below
 5987:             breadcrumbs.
 5988: 
 5989: =item * $ltiscope, optional argument, will be one of: resource, map or
 5990:             course, if LON-CAPA is in LTI Provider context. Value is
 5991:             the scope of use, i.e., launch was for access to a single, a map
 5992:             or the entire course.
 5993: 
 5994: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 5995:             context, this will contain the URL for the landing item in
 5996:             the course, after launch from an LTI Consumer
 5997: 
 5998: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 5999:             context, this will contain a reference to hash of items
 6000:             to be included in the page header and/or inline menu.
 6001: 
 6002: =item * $menucoll, optional argument, if specific menu collection is in
 6003:             effect, either set as the default for the course, or set for
 6004:             the deeplink paramater for $env{'request.deeplink.login'}
 6005:             then $menucoll will be the number of that collection.
 6006: 
 6007: =item * $menuref, optional argument, reference to a hash, containing the
 6008:             menu options included for the menu in effect, based on the
 6009:             configuration for the numbered menu collection in use.
 6010: 
 6011: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 6012:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 6013:             if so, $showncrumbsref is set there to 1, and will propagate back
 6014:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 6015:             being called a second time.
 6016: 
 6017: =back
 6018: 
 6019: Returns: A uniform header for LON-CAPA web pages.  
 6020: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6021: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6022: other decorations will be returned.
 6023: 
 6024: =cut
 6025: 
 6026: sub bodytag {
 6027:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6028:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
 6029:         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 6030: 
 6031:     my $public;
 6032:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6033:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6034:         $public = 1;
 6035:     }
 6036:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6037:     my $httphost = $args->{'use_absolute'};
 6038:     my $hostname = $args->{'hostname'};
 6039: 
 6040:     $function = &get_users_function() if (!$function);
 6041:     my $img =    &designparm($function.'.img',$domain);
 6042:     my $font =   &designparm($function.'.font',$domain);
 6043:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6044: 
 6045:     my %design = ( 'style'   => 'margin-top: 0',
 6046: 		   'bgcolor' => $pgbg,
 6047: 		   'text'    => $font,
 6048:                    'alink'   => &designparm($function.'.alink',$domain),
 6049: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6050: 		   'link'    => &designparm($function.'.link',$domain),);
 6051:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6052: 
 6053:  # role and realm
 6054:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6055:     if ($realm) {
 6056:         $realm = '/'.$realm;
 6057:     }
 6058:     if ($role eq 'ca') {
 6059:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6060:         $realm = &plainname($rname,$rdom);
 6061:     } 
 6062: # realm
 6063:     my ($cid,$sec);
 6064:     if ($env{'request.course.id'}) {
 6065:         $cid = $env{'request.course.id'};
 6066:         if ($env{'request.course.sec'}) {
 6067:             $sec = $env{'request.course.sec'};
 6068:         }
 6069:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 6070:         if (&Apache::lonnet::is_course($1,$2)) {
 6071:             $cid = $1.'_'.$2;
 6072:             $sec = $3;
 6073:         }
 6074:     }
 6075:     if ($cid) {
 6076:         if ($env{'request.role'} !~ /^cr/) {
 6077:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6078:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6079:             if ($env{'request.role.desc'}) {
 6080:                 $role = $env{'request.role.desc'};
 6081:             } else {
 6082:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6083:             }
 6084:         } else {
 6085:             $role = (split(/\//,$role,4))[-1];
 6086:         }
 6087:         if ($sec) {
 6088:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6089:         }   
 6090: 	$realm = $env{'course.'.$cid.'.description'};
 6091:     } else {
 6092:         $role = &Apache::lonnet::plaintext($role);
 6093:     }
 6094: 
 6095:     if (!$realm) { $realm='&nbsp;'; }
 6096: 
 6097:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6098: 
 6099: # construct main body tag
 6100:     my $bodytag = "<body $extra_body_attr>".
 6101: 	&Apache::lontexconvert::init_math_support();
 6102: 
 6103:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6104: 
 6105:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6106:         return $bodytag;
 6107:     }
 6108: 
 6109:     if ($public) {
 6110: 	undef($role);
 6111:     }
 6112: 
 6113:     my $showcrstitle = 1;
 6114:     if (($cid) && ($env{'request.lti.login'})) {
 6115:         if (ref($ltimenu) eq 'HASH') {
 6116:             unless ($ltimenu->{'role'}) {
 6117:                 undef($role);
 6118:             }
 6119:             unless ($ltimenu->{'coursetitle'}) {
 6120:                 $realm='&nbsp;';
 6121:                 $showcrstitle = 0;
 6122:             }
 6123:         }
 6124:     } elsif (($cid) && ($menucoll)) {
 6125:         if (ref($menuref) eq 'HASH') {
 6126:             unless ($menuref->{'role'}) {
 6127:                 undef($role);
 6128:             }
 6129:             unless ($menuref->{'crs'}) {
 6130:                 $realm='&nbsp;';
 6131:                 $showcrstitle = 0;
 6132:             }
 6133:         }
 6134:     }
 6135: 
 6136:     my $titleinfo = '<h1>'.$title.'</h1>';
 6137:     #
 6138:     # Extra info if you are the DC
 6139:     my $dc_info = '';
 6140:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6141:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6142:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6143:         $dc_info =~ s/\s+$//;
 6144:     }
 6145: 
 6146:     my $crstype;
 6147:     if ($cid) {
 6148:         $crstype = $env{'course.'.$cid.'.type'};
 6149:     } elsif ($args->{'crstype'}) {
 6150:         $crstype = $args->{'crstype'};
 6151:     }
 6152: 
 6153:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6154: 
 6155:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6156: 
 6157: 
 6158: 
 6159:     my $funclist;
 6160:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 6161:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 6162:                     Apache::lonmenu::serverform();
 6163:         my $forbodytag;
 6164:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6165:                                             $forcereg,$args->{'group'},
 6166:                                             $args->{'bread_crumbs'},
 6167:                                             $advtoolsref,'','',\$forbodytag);
 6168:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 6169:             $funclist = $forbodytag;
 6170:         }
 6171:     } else {
 6172: 
 6173:         #    if ($env{'request.state'} eq 'construct') {
 6174:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6175:         #    }
 6176: 
 6177:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6178:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6179: 
 6180:         unless ($args->{'no_primary_menu'}) {
 6181:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6182:                                                               $args->{'links_disabled'},
 6183:                                                               $args->{'links_target'});
 6184:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6185:                 if ($dc_info) {
 6186:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6187:                 }
 6188:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6189:                                <em>$realm</em> $dc_info</div>|;
 6190:                 return $bodytag;
 6191:             }
 6192: 
 6193:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6194:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6195:             }
 6196: 
 6197:             $bodytag .= $right;
 6198: 
 6199:             if ($dc_info) {
 6200:                 $dc_info = &dc_courseid_toggle($dc_info);
 6201:             }
 6202:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6203:         }
 6204: 
 6205:         #if directed to not display the secondary menu, don't.
 6206:         if ($args->{'no_secondary_menu'}) {
 6207:             return $bodytag;
 6208:         }
 6209:         #don't show menus for public users
 6210:         if (!$public){
 6211:             unless ($args->{'no_inline_menu'}) {
 6212:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6213:                                                             $args->{'no_primary_menu'},
 6214:                                                             $menucoll,$menuref,
 6215:                                                             $args->{'links_disabled'},
 6216:                                                             $args->{'links_target'});
 6217:             }
 6218:             $bodytag .= Apache::lonmenu::serverform();
 6219:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6220:             if ($env{'request.state'} eq 'construct') {
 6221:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6222:                                 $args->{'bread_crumbs'},'','',$hostname,
 6223:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6224:             } elsif ($forcereg) {
 6225:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6226:                                 $args->{'group'},$args->{'hide_buttons'},
 6227:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6228:             } else {
 6229:                 my $forbodytag;
 6230:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6231:                                                     $forcereg,$args->{'group'},
 6232:                                                     $args->{'bread_crumbs'},
 6233:                                                     $advtoolsref,'',$hostname,
 6234:                                                     \$forbodytag);
 6235:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 6236:                     $bodytag .= $forbodytag;
 6237:                 }
 6238:             }
 6239:         }else{
 6240:             # this is to seperate menu from content when there's no secondary
 6241:             # menu. Especially needed for public accessible ressources.
 6242:             $bodytag .= '<hr style="clear:both" />';
 6243:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6244:         }
 6245: 
 6246:         return $bodytag;
 6247:     }
 6248: 
 6249: #
 6250: # Top frame rendering, Remote is up
 6251: #
 6252: 
 6253:     my $imgsrc = $img;
 6254:     if ($img =~ /^\/adm/) {
 6255:         $imgsrc = &lonhttpdurl($img);
 6256:     }
 6257:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 6258: 
 6259:     my $help=($no_inline_link?''
 6260:               :&Apache::loncommon::top_nav_help('Help'));
 6261: 
 6262:     # Explicit link to get inline menu
 6263:     my $menu= ($no_inline_link?''
 6264:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 6265: 
 6266:     if ($dc_info) {
 6267:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 6268:     }
 6269: 
 6270:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 6271:     unless ($public) {
 6272:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 6273:                                 undef,'LC_menubuttons_link');
 6274:     }
 6275: 
 6276:     unless ($env{'form.inhibitmenu'}) {
 6277:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 6278:                        <ol class="LC_primary_menu LC_floatright LC_right">
 6279:                        <li>$help</li>
 6280:                        <li>$menu</li>
 6281:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 6282:     }
 6283:     if ($env{'request.state'} eq 'construct') {
 6284:         if (!$public){
 6285:             if ($env{'request.state'} eq 'construct') {
 6286:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 6287:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 6288:                             &Apache::lonhtmlcommon::scripttag('','end').
 6289:                             &Apache::lonmenu::innerregister($forcereg,
 6290:                                                             $args->{'bread_crumbs'});
 6291:             }
 6292:         }
 6293:     }
 6294:     return $bodytag."\n".$funclist;
 6295: }
 6296: 
 6297: sub dc_courseid_toggle {
 6298:     my ($dc_info) = @_;
 6299:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6300:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6301:            &mt('(More ...)').'</a></span>'.
 6302:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6303: }
 6304: 
 6305: sub make_attr_string {
 6306:     my ($register,$attr_ref) = @_;
 6307: 
 6308:     if ($attr_ref && !ref($attr_ref)) {
 6309: 	die("addentries Must be a hash ref ".
 6310: 	    join(':',caller(1))." ".
 6311: 	    join(':',caller(0))." ");
 6312:     }
 6313: 
 6314:     if ($register) {
 6315: 	my ($on_load,$on_unload);
 6316: 	foreach my $key (keys(%{$attr_ref})) {
 6317: 	    if      (lc($key) eq 'onload') {
 6318: 		$on_load.=$attr_ref->{$key}.';';
 6319: 		delete($attr_ref->{$key});
 6320: 
 6321: 	    } elsif (lc($key) eq 'onunload') {
 6322: 		$on_unload.=$attr_ref->{$key}.';';
 6323: 		delete($attr_ref->{$key});
 6324: 	    }
 6325: 	}
 6326:         if ($env{'environment.remote'} eq 'on') {
 6327:             $attr_ref->{'onload'}  =
 6328:                 &Apache::lonmenu::loadevents().  $on_load;
 6329:             $attr_ref->{'onunload'}=
 6330:                 &Apache::lonmenu::unloadevents().$on_unload;
 6331:         } else {  
 6332: 	    $attr_ref->{'onload'}  = $on_load;
 6333: 	    $attr_ref->{'onunload'}= $on_unload;
 6334:         }
 6335:     }
 6336: 
 6337:     my $attr_string;
 6338:     foreach my $attr (sort(keys(%$attr_ref))) {
 6339: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6340:     }
 6341:     return $attr_string;
 6342: }
 6343: 
 6344: 
 6345: ###############################################
 6346: ###############################################
 6347: 
 6348: =pod
 6349: 
 6350: =item * &endbodytag()
 6351: 
 6352: Returns a uniform footer for LON-CAPA web pages.
 6353: 
 6354: Inputs: 1 - optional reference to an args hash
 6355: If in the hash, key for noredirectlink has a value which evaluates to true,
 6356: a 'Continue' link is not displayed if the page contains an
 6357: internal redirect in the <head></head> section,
 6358: i.e., $env{'internal.head.redirect'} exists   
 6359: 
 6360: =cut
 6361: 
 6362: sub endbodytag {
 6363:     my ($args) = @_;
 6364:     my $endbodytag;
 6365:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6366:         $endbodytag='</body>';
 6367:     }
 6368:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6369:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6370:             my ($endbodyjs,$idattr);
 6371:             if ($env{'internal.head.to_opener'}) {
 6372:                 my $linkid = 'LC_continue_link';
 6373:                 $idattr = ' id="'.$linkid.'"';
 6374:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 6375:                 $endbodyjs=<<ENDJS;
 6376: <script type="text/javascript">
 6377: // <![CDATA[
 6378: function ebFunction(evt) {
 6379:     evt.preventDefault();
 6380:     var dest = '$redirect_for_js';
 6381:     if (window.opener != null && !window.opener.closed) {
 6382:         window.opener.location.href=dest;
 6383:         window.close();
 6384:     } else {
 6385:         window.location.href=dest;
 6386:     }
 6387:     return false;
 6388: }
 6389: 
 6390: \$(document).ready(function () {
 6391:   if (document.getElementById('$linkid')) {
 6392:     var clickelem = document.getElementById('$linkid');
 6393:     clickelem.addEventListener('click',ebFunction,false);
 6394:   }
 6395: });
 6396: // ]]>
 6397: </script>
 6398: ENDJS
 6399:             }
 6400: 	    $endbodytag=
 6401: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 6402: 	        &mt('Continue').'</a>'.
 6403: 	        $endbodytag;
 6404:         }
 6405:     }
 6406:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
 6407:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
 6408:     }
 6409:     return $endbodytag;
 6410: }
 6411: 
 6412: =pod
 6413: 
 6414: =item * &standard_css()
 6415: 
 6416: Returns a style sheet
 6417: 
 6418: Inputs: (all optional)
 6419:             domain         -> force to color decorate a page for a specific
 6420:                                domain
 6421:             function       -> force usage of a specific rolish color scheme
 6422:             bgcolor        -> override the default page bgcolor
 6423: 
 6424: =cut
 6425: 
 6426: sub standard_css {
 6427:     my ($function,$domain,$bgcolor) = @_;
 6428:     $function  = &get_users_function() if (!$function);
 6429:     my $img    = &designparm($function.'.img',   $domain);
 6430:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6431:     my $font   = &designparm($function.'.font',  $domain);
 6432:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6433: #second colour for later usage
 6434:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6435:     my $pgbg_or_bgcolor =
 6436: 	         $bgcolor ||
 6437: 	         &designparm($function.'.pgbg',  $domain);
 6438:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6439:     my $alink  = &designparm($function.'.alink', $domain);
 6440:     my $vlink  = &designparm($function.'.vlink', $domain);
 6441:     my $link   = &designparm($function.'.link',  $domain);
 6442: 
 6443:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6444:     my $mono                 = 'monospace';
 6445:     my $data_table_head      = $sidebg;
 6446:     my $data_table_light     = '#FAFAFA';
 6447:     my $data_table_dark      = '#E0E0E0';
 6448:     my $data_table_darker    = '#CCCCCC';
 6449:     my $data_table_highlight = '#FFFF00';
 6450:     my $mail_new             = '#FFBB77';
 6451:     my $mail_new_hover       = '#DD9955';
 6452:     my $mail_read            = '#BBBB77';
 6453:     my $mail_read_hover      = '#999944';
 6454:     my $mail_replied         = '#AAAA88';
 6455:     my $mail_replied_hover   = '#888855';
 6456:     my $mail_other           = '#99BBBB';
 6457:     my $mail_other_hover     = '#669999';
 6458:     my $table_header         = '#DDDDDD';
 6459:     my $feedback_link_bg     = '#BBBBBB';
 6460:     my $lg_border_color      = '#C8C8C8';
 6461:     my $button_hover         = '#BF2317';
 6462: 
 6463:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6464:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6465:                                              : '0 3px 0 4px';
 6466: 
 6467: 
 6468:     return <<END;
 6469: 
 6470: /* needed for iframe to allow 100% height in FF */
 6471: body, html { 
 6472:     margin: 0;
 6473:     padding: 0 0.5%;
 6474:     height: 99%; /* to avoid scrollbars */
 6475: }
 6476: 
 6477: body {
 6478:   font-family: $sans;
 6479:   line-height:130%;
 6480:   font-size:0.83em;
 6481:   color:$font;
 6482: }
 6483: 
 6484: a:focus,
 6485: a:focus img {
 6486:   color: red;
 6487: }
 6488: 
 6489: form, .inline {
 6490:   display: inline;
 6491: }
 6492: 
 6493: .LC_right {
 6494:   text-align:right;
 6495: }
 6496: 
 6497: .LC_middle {
 6498:   vertical-align:middle;
 6499: }
 6500: 
 6501: .LC_floatleft {
 6502:   float: left;
 6503: }
 6504: 
 6505: .LC_floatright {
 6506:   float: right;
 6507: }
 6508: 
 6509: .LC_400Box {
 6510:   width:400px;
 6511: }
 6512: 
 6513: .LC_iframecontainer {
 6514:     width: 98%;
 6515:     margin: 0;
 6516:     position: fixed;
 6517:     top: 8.5em;
 6518:     bottom: 0;
 6519: }
 6520: 
 6521: .LC_iframecontainer iframe{
 6522:     border: none;
 6523:     width: 100%;
 6524:     height: 100%;
 6525: }
 6526: 
 6527: .LC_filename {
 6528:   font-family: $mono;
 6529:   white-space:pre;
 6530:   font-size: 120%;
 6531: }
 6532: 
 6533: .LC_fileicon {
 6534:   border: none;
 6535:   height: 1.3em;
 6536:   vertical-align: text-bottom;
 6537:   margin-right: 0.3em;
 6538:   text-decoration:none;
 6539: }
 6540: 
 6541: .LC_setting {
 6542:   text-decoration:underline;
 6543: }
 6544: 
 6545: .LC_error {
 6546:   color: red;
 6547: }
 6548: 
 6549: .LC_warning {
 6550:   color: darkorange;
 6551: }
 6552: 
 6553: .LC_diff_removed {
 6554:   color: red;
 6555: }
 6556: 
 6557: .LC_info,
 6558: .LC_success,
 6559: .LC_diff_added {
 6560:   color: green;
 6561: }
 6562: 
 6563: div.LC_confirm_box {
 6564:   background-color: #FAFAFA;
 6565:   border: 1px solid $lg_border_color;
 6566:   margin-right: 0;
 6567:   padding: 5px;
 6568: }
 6569: 
 6570: div.LC_confirm_box .LC_error img,
 6571: div.LC_confirm_box .LC_success img {
 6572:   vertical-align: middle;
 6573: }
 6574: 
 6575: .LC_maxwidth {
 6576:   max-width: 100%;
 6577:   height: auto;
 6578: }
 6579: 
 6580: .LC_textsize_mobile {
 6581:   \@media only screen and (max-device-width: 480px) {
 6582:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6583:   }
 6584: }
 6585: 
 6586: .LC_icon {
 6587:   border: none;
 6588:   vertical-align: middle;
 6589: }
 6590: 
 6591: .LC_docs_spacer {
 6592:   width: 25px;
 6593:   height: 1px;
 6594:   border: none;
 6595: }
 6596: 
 6597: .LC_internal_info {
 6598:   color: #999999;
 6599: }
 6600: 
 6601: .LC_discussion {
 6602:   background: $data_table_dark;
 6603:   border: 1px solid black;
 6604:   margin: 2px;
 6605: }
 6606: 
 6607: .LC_disc_action_left {
 6608:   background: $sidebg;
 6609:   text-align: left;
 6610:   padding: 4px;
 6611:   margin: 2px;
 6612: }
 6613: 
 6614: .LC_disc_action_right {
 6615:   background: $sidebg;
 6616:   text-align: right;
 6617:   padding: 4px;
 6618:   margin: 2px;
 6619: }
 6620: 
 6621: .LC_disc_new_item {
 6622:   background: white;
 6623:   border: 2px solid red;
 6624:   margin: 4px;
 6625:   padding: 4px;
 6626: }
 6627: 
 6628: .LC_disc_old_item {
 6629:   background: white;
 6630:   margin: 4px;
 6631:   padding: 4px;
 6632: }
 6633: 
 6634: table.LC_pastsubmission {
 6635:   border: 1px solid black;
 6636:   margin: 2px;
 6637: }
 6638: 
 6639: table#LC_menubuttons {
 6640:   width: 100%;
 6641:   background: $pgbg;
 6642:   border: 2px;
 6643:   border-collapse: separate;
 6644:   padding: 0;
 6645: }
 6646: 
 6647: table#LC_title_bar a {
 6648:   color: $fontmenu;
 6649: }
 6650: 
 6651: table#LC_title_bar {
 6652:   clear: both;
 6653:   display: none;
 6654: }
 6655: 
 6656: table#LC_title_bar,
 6657: table.LC_breadcrumbs, /* obsolete? */
 6658: table#LC_title_bar.LC_with_remote {
 6659:   width: 100%;
 6660:   border-color: $pgbg;
 6661:   border-style: solid;
 6662:   border-width: $border;
 6663:   background: $pgbg;
 6664:   color: $fontmenu;
 6665:   border-collapse: collapse;
 6666:   padding: 0;
 6667:   margin: 0;
 6668: }
 6669: 
 6670: ul.LC_breadcrumb_tools_outerlist {
 6671:     margin: 0;
 6672:     padding: 0;
 6673:     position: relative;
 6674:     list-style: none;
 6675: }
 6676: ul.LC_breadcrumb_tools_outerlist li {
 6677:     display: inline;
 6678: }
 6679: 
 6680: .LC_breadcrumb_tools_navigation {
 6681:     padding: 0;
 6682:     margin: 0;
 6683:     float: left;
 6684: }
 6685: .LC_breadcrumb_tools_tools {
 6686:     padding: 0;
 6687:     margin: 0;
 6688:     float: right;
 6689: }
 6690: 
 6691: table#LC_title_bar td {
 6692:   background: $tabbg;
 6693: }
 6694: 
 6695: table#LC_menubuttons img {
 6696:   border: none;
 6697: }
 6698: 
 6699: .LC_breadcrumbs_component {
 6700:   float: right;
 6701:   margin: 0 1em;
 6702: }
 6703: .LC_breadcrumbs_component img {
 6704:   vertical-align: middle;
 6705: }
 6706: 
 6707: .LC_breadcrumbs_hoverable {
 6708:   background: $sidebg;
 6709: }
 6710: 
 6711: td.LC_table_cell_checkbox {
 6712:   text-align: center;
 6713: }
 6714: 
 6715: .LC_fontsize_small {
 6716:   font-size: 70%;
 6717: }
 6718: 
 6719: #LC_breadcrumbs {
 6720:   clear:both;
 6721:   background: $sidebg;
 6722:   border-bottom: 1px solid $lg_border_color;
 6723:   line-height: 2.5em;
 6724:   overflow: hidden;
 6725:   margin: 0;
 6726:   padding: 0;
 6727:   text-align: left;
 6728: }
 6729: 
 6730: .LC_head_subbox, .LC_actionbox {
 6731:   clear:both;
 6732:   background: #F8F8F8; /* $sidebg; */
 6733:   border: 1px solid $sidebg;
 6734:   margin: 0 0 10px 0;
 6735:   padding: 3px;
 6736:   text-align: left;
 6737: }
 6738: 
 6739: .LC_fontsize_medium {
 6740:   font-size: 85%;
 6741: }
 6742: 
 6743: .LC_fontsize_large {
 6744:   font-size: 120%;
 6745: }
 6746: 
 6747: .LC_menubuttons_inline_text {
 6748:   color: $font;
 6749:   font-size: 90%;
 6750:   padding-left:3px;
 6751: }
 6752: 
 6753: .LC_menubuttons_inline_text img{
 6754:   vertical-align: middle;
 6755: }
 6756: 
 6757: li.LC_menubuttons_inline_text img {
 6758:   cursor:pointer;
 6759:   text-decoration: none;
 6760: }
 6761: 
 6762: .LC_menubuttons_link {
 6763:   text-decoration: none;
 6764: }
 6765: 
 6766: .LC_menubuttons_category {
 6767:   color: $font;
 6768:   background: $pgbg;
 6769:   font-size: larger;
 6770:   font-weight: bold;
 6771: }
 6772: 
 6773: td.LC_menubuttons_text {
 6774:   color: $font;
 6775: }
 6776: 
 6777: .LC_current_location {
 6778:   background: $tabbg;
 6779: }
 6780: 
 6781: td.LC_zero_height {
 6782:   line-height: 0;
 6783:   cellpadding: 0;
 6784: }
 6785: 
 6786: table.LC_data_table {
 6787:   border: 1px solid #000000;
 6788:   border-collapse: separate;
 6789:   border-spacing: 1px;
 6790:   background: $pgbg;
 6791: }
 6792: 
 6793: .LC_data_table_dense {
 6794:   font-size: small;
 6795: }
 6796: 
 6797: table.LC_nested_outer {
 6798:   border: 1px solid #000000;
 6799:   border-collapse: collapse;
 6800:   border-spacing: 0;
 6801:   width: 100%;
 6802: }
 6803: 
 6804: table.LC_innerpickbox,
 6805: table.LC_nested {
 6806:   border: none;
 6807:   border-collapse: collapse;
 6808:   border-spacing: 0;
 6809:   width: 100%;
 6810: }
 6811: 
 6812: table.LC_data_table tr th,
 6813: table.LC_calendar tr th,
 6814: table.LC_prior_tries tr th,
 6815: table.LC_innerpickbox tr th {
 6816:   font-weight: bold;
 6817:   background-color: $data_table_head;
 6818:   color:$fontmenu;
 6819:   font-size:90%;
 6820: }
 6821: 
 6822: table.LC_innerpickbox tr th,
 6823: table.LC_innerpickbox tr td {
 6824:   vertical-align: top;
 6825: }
 6826: 
 6827: table.LC_data_table tr.LC_info_row > td {
 6828:   background-color: #CCCCCC;
 6829:   font-weight: bold;
 6830:   text-align: left;
 6831: }
 6832: 
 6833: table.LC_data_table tr.LC_odd_row > td {
 6834:   background-color: $data_table_light;
 6835:   padding: 2px;
 6836:   vertical-align: top;
 6837: }
 6838: 
 6839: table.LC_pick_box tr > td.LC_odd_row {
 6840:   background-color: $data_table_light;
 6841:   vertical-align: top;
 6842: }
 6843: 
 6844: table.LC_data_table tr.LC_even_row > td {
 6845:   background-color: $data_table_dark;
 6846:   padding: 2px;
 6847:   vertical-align: top;
 6848: }
 6849: 
 6850: table.LC_pick_box tr > td.LC_even_row {
 6851:   background-color: $data_table_dark;
 6852:   vertical-align: top;
 6853: }
 6854: 
 6855: table.LC_data_table tr.LC_data_table_highlight td {
 6856:   background-color: $data_table_darker;
 6857: }
 6858: 
 6859: table.LC_data_table tr td.LC_leftcol_header {
 6860:   background-color: $data_table_head;
 6861:   font-weight: bold;
 6862: }
 6863: 
 6864: table.LC_data_table tr.LC_empty_row td,
 6865: table.LC_nested tr.LC_empty_row td {
 6866:   font-weight: bold;
 6867:   font-style: italic;
 6868:   text-align: center;
 6869:   padding: 8px;
 6870: }
 6871: 
 6872: table.LC_data_table tr.LC_empty_row td,
 6873: table.LC_data_table tr.LC_footer_row td {
 6874:   background-color: $sidebg;
 6875: }
 6876: 
 6877: table.LC_nested tr.LC_empty_row td {
 6878:   background-color: #FFFFFF;
 6879: }
 6880: 
 6881: table.LC_caption {
 6882: }
 6883: 
 6884: table.LC_nested tr.LC_empty_row td {
 6885:   padding: 4ex
 6886: }
 6887: 
 6888: table.LC_nested_outer tr th {
 6889:   font-weight: bold;
 6890:   color:$fontmenu;
 6891:   background-color: $data_table_head;
 6892:   font-size: small;
 6893:   border-bottom: 1px solid #000000;
 6894: }
 6895: 
 6896: table.LC_nested_outer tr td.LC_subheader {
 6897:   background-color: $data_table_head;
 6898:   font-weight: bold;
 6899:   font-size: small;
 6900:   border-bottom: 1px solid #000000;
 6901:   text-align: right;
 6902: }
 6903: 
 6904: table.LC_nested tr.LC_info_row td {
 6905:   background-color: #CCCCCC;
 6906:   font-weight: bold;
 6907:   font-size: small;
 6908:   text-align: center;
 6909: }
 6910: 
 6911: table.LC_nested tr.LC_info_row td.LC_left_item,
 6912: table.LC_nested_outer tr th.LC_left_item {
 6913:   text-align: left;
 6914: }
 6915: 
 6916: table.LC_nested td {
 6917:   background-color: #FFFFFF;
 6918:   font-size: small;
 6919: }
 6920: 
 6921: table.LC_nested_outer tr th.LC_right_item,
 6922: table.LC_nested tr.LC_info_row td.LC_right_item,
 6923: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6924: table.LC_nested tr td.LC_right_item {
 6925:   text-align: right;
 6926: }
 6927: 
 6928: table.LC_nested tr.LC_odd_row td {
 6929:   background-color: #EEEEEE;
 6930: }
 6931: 
 6932: table.LC_createuser {
 6933: }
 6934: 
 6935: table.LC_createuser tr.LC_section_row td {
 6936:   font-size: small;
 6937: }
 6938: 
 6939: table.LC_createuser tr.LC_info_row td  {
 6940:   background-color: #CCCCCC;
 6941:   font-weight: bold;
 6942:   text-align: center;
 6943: }
 6944: 
 6945: table.LC_calendar {
 6946:   border: 1px solid #000000;
 6947:   border-collapse: collapse;
 6948:   width: 98%;
 6949: }
 6950: 
 6951: table.LC_calendar_pickdate {
 6952:   font-size: xx-small;
 6953: }
 6954: 
 6955: table.LC_calendar tr td {
 6956:   border: 1px solid #000000;
 6957:   vertical-align: top;
 6958:   width: 14%;
 6959: }
 6960: 
 6961: table.LC_calendar tr td.LC_calendar_day_empty {
 6962:   background-color: $data_table_dark;
 6963: }
 6964: 
 6965: table.LC_calendar tr td.LC_calendar_day_current {
 6966:   background-color: $data_table_highlight;
 6967: }
 6968: 
 6969: table.LC_data_table tr td.LC_mail_new {
 6970:   background-color: $mail_new;
 6971: }
 6972: 
 6973: table.LC_data_table tr.LC_mail_new:hover {
 6974:   background-color: $mail_new_hover;
 6975: }
 6976: 
 6977: table.LC_data_table tr td.LC_mail_read {
 6978:   background-color: $mail_read;
 6979: }
 6980: 
 6981: /*
 6982: table.LC_data_table tr.LC_mail_read:hover {
 6983:   background-color: $mail_read_hover;
 6984: }
 6985: */
 6986: 
 6987: table.LC_data_table tr td.LC_mail_replied {
 6988:   background-color: $mail_replied;
 6989: }
 6990: 
 6991: /*
 6992: table.LC_data_table tr.LC_mail_replied:hover {
 6993:   background-color: $mail_replied_hover;
 6994: }
 6995: */
 6996: 
 6997: table.LC_data_table tr td.LC_mail_other {
 6998:   background-color: $mail_other;
 6999: }
 7000: 
 7001: /*
 7002: table.LC_data_table tr.LC_mail_other:hover {
 7003:   background-color: $mail_other_hover;
 7004: }
 7005: */
 7006: 
 7007: table.LC_data_table tr > td.LC_browser_file,
 7008: table.LC_data_table tr > td.LC_browser_file_published {
 7009:   background: #AAEE77;
 7010: }
 7011: 
 7012: table.LC_data_table tr > td.LC_browser_file_locked,
 7013: table.LC_data_table tr > td.LC_browser_file_unpublished {
 7014:   background: #FFAA99;
 7015: }
 7016: 
 7017: table.LC_data_table tr > td.LC_browser_file_obsolete {
 7018:   background: #888888;
 7019: }
 7020: 
 7021: table.LC_data_table tr > td.LC_browser_file_modified,
 7022: table.LC_data_table tr > td.LC_browser_file_metamodified {
 7023:   background: #F8F866;
 7024: }
 7025: 
 7026: table.LC_data_table tr.LC_browser_folder > td {
 7027:   background: #E0E8FF;
 7028: }
 7029: 
 7030: table.LC_data_table tr > td.LC_roles_is {
 7031:   /* background: #77FF77; */
 7032: }
 7033: 
 7034: table.LC_data_table tr > td.LC_roles_future {
 7035:   border-right: 8px solid #FFFF77;
 7036: }
 7037: 
 7038: table.LC_data_table tr > td.LC_roles_will {
 7039:   border-right: 8px solid #FFAA77;
 7040: }
 7041: 
 7042: table.LC_data_table tr > td.LC_roles_expired {
 7043:   border-right: 8px solid #FF7777;
 7044: }
 7045: 
 7046: table.LC_data_table tr > td.LC_roles_will_not {
 7047:   border-right: 8px solid #AAFF77;
 7048: }
 7049: 
 7050: table.LC_data_table tr > td.LC_roles_selected {
 7051:   border-right: 8px solid #11CC55;
 7052: }
 7053: 
 7054: span.LC_current_location {
 7055:   font-size:larger;
 7056:   background: $pgbg;
 7057: }
 7058: 
 7059: span.LC_current_nav_location {
 7060:   font-weight:bold;
 7061:   background: $sidebg;
 7062: }
 7063: 
 7064: span.LC_parm_menu_item {
 7065:   font-size: larger;
 7066: }
 7067: 
 7068: span.LC_parm_scope_all {
 7069:   color: red;
 7070: }
 7071: 
 7072: span.LC_parm_scope_folder {
 7073:   color: green;
 7074: }
 7075: 
 7076: span.LC_parm_scope_resource {
 7077:   color: orange;
 7078: }
 7079: 
 7080: span.LC_parm_part {
 7081:   color: blue;
 7082: }
 7083: 
 7084: span.LC_parm_folder,
 7085: span.LC_parm_symb {
 7086:   font-size: x-small;
 7087:   font-family: $mono;
 7088:   color: #AAAAAA;
 7089: }
 7090: 
 7091: ul.LC_parm_parmlist li {
 7092:   display: inline-block;
 7093:   padding: 0.3em 0.8em;
 7094:   vertical-align: top;
 7095:   width: 150px;
 7096:   border-top:1px solid $lg_border_color;
 7097: }
 7098: 
 7099: td.LC_parm_overview_level_menu,
 7100: td.LC_parm_overview_map_menu,
 7101: td.LC_parm_overview_parm_selectors,
 7102: td.LC_parm_overview_restrictions  {
 7103:   border: 1px solid black;
 7104:   border-collapse: collapse;
 7105: }
 7106: 
 7107: table.LC_parm_overview_restrictions td {
 7108:   border-width: 1px 4px 1px 4px;
 7109:   border-style: solid;
 7110:   border-color: $pgbg;
 7111:   text-align: center;
 7112: }
 7113: 
 7114: table.LC_parm_overview_restrictions th {
 7115:   background: $tabbg;
 7116:   border-width: 1px 4px 1px 4px;
 7117:   border-style: solid;
 7118:   border-color: $pgbg;
 7119: }
 7120: 
 7121: table#LC_helpmenu {
 7122:   border: none;
 7123:   height: 55px;
 7124:   border-spacing: 0;
 7125: }
 7126: 
 7127: table#LC_helpmenu fieldset legend {
 7128:   font-size: larger;
 7129: }
 7130: 
 7131: table#LC_helpmenu_links {
 7132:   width: 100%;
 7133:   border: 1px solid black;
 7134:   background: $pgbg;
 7135:   padding: 0;
 7136:   border-spacing: 1px;
 7137: }
 7138: 
 7139: table#LC_helpmenu_links tr td {
 7140:   padding: 1px;
 7141:   background: $tabbg;
 7142:   text-align: center;
 7143:   font-weight: bold;
 7144: }
 7145: 
 7146: table#LC_helpmenu_links a:link,
 7147: table#LC_helpmenu_links a:visited,
 7148: table#LC_helpmenu_links a:active {
 7149:   text-decoration: none;
 7150:   color: $font;
 7151: }
 7152: 
 7153: table#LC_helpmenu_links a:hover {
 7154:   text-decoration: underline;
 7155:   color: $vlink;
 7156: }
 7157: 
 7158: .LC_chrt_popup_exists {
 7159:   border: 1px solid #339933;
 7160:   margin: -1px;
 7161: }
 7162: 
 7163: .LC_chrt_popup_up {
 7164:   border: 1px solid yellow;
 7165:   margin: -1px;
 7166: }
 7167: 
 7168: .LC_chrt_popup {
 7169:   border: 1px solid #8888FF;
 7170:   background: #CCCCFF;
 7171: }
 7172: 
 7173: table.LC_pick_box {
 7174:   border-collapse: separate;
 7175:   background: white;
 7176:   border: 1px solid black;
 7177:   border-spacing: 1px;
 7178: }
 7179: 
 7180: table.LC_pick_box td.LC_pick_box_title {
 7181:   background: $sidebg;
 7182:   font-weight: bold;
 7183:   text-align: left;
 7184:   vertical-align: top;
 7185:   width: 184px;
 7186:   padding: 8px;
 7187: }
 7188: 
 7189: table.LC_pick_box td.LC_pick_box_value {
 7190:   text-align: left;
 7191:   padding: 8px;
 7192: }
 7193: 
 7194: table.LC_pick_box td.LC_pick_box_select {
 7195:   text-align: left;
 7196:   padding: 8px;
 7197: }
 7198: 
 7199: table.LC_pick_box td.LC_pick_box_separator {
 7200:   padding: 0;
 7201:   height: 1px;
 7202:   background: black;
 7203: }
 7204: 
 7205: table.LC_pick_box td.LC_pick_box_submit {
 7206:   text-align: right;
 7207: }
 7208: 
 7209: table.LC_pick_box td.LC_evenrow_value {
 7210:   text-align: left;
 7211:   padding: 8px;
 7212:   background-color: $data_table_light;
 7213: }
 7214: 
 7215: table.LC_pick_box td.LC_oddrow_value {
 7216:   text-align: left;
 7217:   padding: 8px;
 7218:   background-color: $data_table_light;
 7219: }
 7220: 
 7221: span.LC_helpform_receipt_cat {
 7222:   font-weight: bold;
 7223: }
 7224: 
 7225: table.LC_group_priv_box {
 7226:   background: white;
 7227:   border: 1px solid black;
 7228:   border-spacing: 1px;
 7229: }
 7230: 
 7231: table.LC_group_priv_box td.LC_pick_box_title {
 7232:   background: $tabbg;
 7233:   font-weight: bold;
 7234:   text-align: right;
 7235:   width: 184px;
 7236: }
 7237: 
 7238: table.LC_group_priv_box td.LC_groups_fixed {
 7239:   background: $data_table_light;
 7240:   text-align: center;
 7241: }
 7242: 
 7243: table.LC_group_priv_box td.LC_groups_optional {
 7244:   background: $data_table_dark;
 7245:   text-align: center;
 7246: }
 7247: 
 7248: table.LC_group_priv_box td.LC_groups_functionality {
 7249:   background: $data_table_darker;
 7250:   text-align: center;
 7251:   font-weight: bold;
 7252: }
 7253: 
 7254: table.LC_group_priv td {
 7255:   text-align: left;
 7256:   padding: 0;
 7257: }
 7258: 
 7259: .LC_navbuttons {
 7260:   margin: 2ex 0ex 2ex 0ex;
 7261: }
 7262: 
 7263: .LC_topic_bar {
 7264:   font-weight: bold;
 7265:   background: $tabbg;
 7266:   margin: 1em 0em 1em 2em;
 7267:   padding: 3px;
 7268:   font-size: 1.2em;
 7269: }
 7270: 
 7271: .LC_topic_bar span {
 7272:   left: 0.5em;
 7273:   position: absolute;
 7274:   vertical-align: middle;
 7275:   font-size: 1.2em;
 7276: }
 7277: 
 7278: table.LC_course_group_status {
 7279:   margin: 20px;
 7280: }
 7281: 
 7282: table.LC_status_selector td {
 7283:   vertical-align: top;
 7284:   text-align: center;
 7285:   padding: 4px;
 7286: }
 7287: 
 7288: div.LC_feedback_link {
 7289:   clear: both;
 7290:   background: $sidebg;
 7291:   width: 100%;
 7292:   padding-bottom: 10px;
 7293:   border: 1px $tabbg solid;
 7294:   height: 22px;
 7295:   line-height: 22px;
 7296:   padding-top: 5px;
 7297: }
 7298: 
 7299: div.LC_feedback_link img {
 7300:   height: 22px;
 7301:   vertical-align:middle;
 7302: }
 7303: 
 7304: div.LC_feedback_link a {
 7305:   text-decoration: none;
 7306: }
 7307: 
 7308: div.LC_comblock {
 7309:   display:inline;
 7310:   color:$font;
 7311:   font-size:90%;
 7312: }
 7313: 
 7314: div.LC_feedback_link div.LC_comblock {
 7315:   padding-left:5px;
 7316: }
 7317: 
 7318: div.LC_feedback_link div.LC_comblock a {
 7319:   color:$font;
 7320: }
 7321: 
 7322: span.LC_feedback_link {
 7323:   /* background: $feedback_link_bg; */
 7324:   font-size: larger;
 7325: }
 7326: 
 7327: span.LC_message_link {
 7328:   /* background: $feedback_link_bg; */
 7329:   font-size: larger;
 7330:   position: absolute;
 7331:   right: 1em;
 7332: }
 7333: 
 7334: table.LC_prior_tries {
 7335:   border: 1px solid #000000;
 7336:   border-collapse: separate;
 7337:   border-spacing: 1px;
 7338: }
 7339: 
 7340: table.LC_prior_tries td {
 7341:   padding: 2px;
 7342: }
 7343: 
 7344: .LC_answer_correct {
 7345:   background: lightgreen;
 7346:   color: darkgreen;
 7347:   padding: 6px;
 7348: }
 7349: 
 7350: .LC_answer_charged_try {
 7351:   background: #FFAAAA;
 7352:   color: darkred;
 7353:   padding: 6px;
 7354: }
 7355: 
 7356: .LC_answer_not_charged_try,
 7357: .LC_answer_no_grade,
 7358: .LC_answer_late {
 7359:   background: lightyellow;
 7360:   color: black;
 7361:   padding: 6px;
 7362: }
 7363: 
 7364: .LC_answer_previous {
 7365:   background: lightblue;
 7366:   color: darkblue;
 7367:   padding: 6px;
 7368: }
 7369: 
 7370: .LC_answer_no_message {
 7371:   background: #FFFFFF;
 7372:   color: black;
 7373:   padding: 6px;
 7374: }
 7375: 
 7376: .LC_answer_unknown,
 7377: .LC_answer_warning {
 7378:   background: orange;
 7379:   color: black;
 7380:   padding: 6px;
 7381: }
 7382: 
 7383: span.LC_prior_numerical,
 7384: span.LC_prior_string,
 7385: span.LC_prior_custom,
 7386: span.LC_prior_reaction,
 7387: span.LC_prior_math {
 7388:   font-family: $mono;
 7389:   white-space: pre;
 7390: }
 7391: 
 7392: span.LC_prior_string {
 7393:   font-family: $mono;
 7394:   white-space: pre;
 7395: }
 7396: 
 7397: table.LC_prior_option {
 7398:   width: 100%;
 7399:   border-collapse: collapse;
 7400: }
 7401: 
 7402: table.LC_prior_rank,
 7403: table.LC_prior_match {
 7404:   border-collapse: collapse;
 7405: }
 7406: 
 7407: table.LC_prior_option tr td,
 7408: table.LC_prior_rank tr td,
 7409: table.LC_prior_match tr td {
 7410:   border: 1px solid #000000;
 7411: }
 7412: 
 7413: .LC_nobreak {
 7414:   white-space: nowrap;
 7415: }
 7416: 
 7417: span.LC_cusr_emph {
 7418:   font-style: italic;
 7419: }
 7420: 
 7421: span.LC_cusr_subheading {
 7422:   font-weight: normal;
 7423:   font-size: 85%;
 7424: }
 7425: 
 7426: div.LC_docs_entry_move {
 7427:   border: 1px solid #BBBBBB;
 7428:   background: #DDDDDD;
 7429:   width: 22px;
 7430:   padding: 1px;
 7431:   margin: 0;
 7432: }
 7433: 
 7434: table.LC_data_table tr > td.LC_docs_entry_commands,
 7435: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7436:   font-size: x-small;
 7437: }
 7438: 
 7439: .LC_docs_entry_parameter {
 7440:   white-space: nowrap;
 7441: }
 7442: 
 7443: .LC_docs_copy {
 7444:   color: #000099;
 7445: }
 7446: 
 7447: .LC_docs_cut {
 7448:   color: #550044;
 7449: }
 7450: 
 7451: .LC_docs_rename {
 7452:   color: #009900;
 7453: }
 7454: 
 7455: .LC_docs_remove {
 7456:   color: #990000;
 7457: }
 7458: 
 7459: .LC_domprefs_email,
 7460: .LC_docs_reinit_warn,
 7461: .LC_docs_ext_edit {
 7462:   font-size: x-small;
 7463: }
 7464: 
 7465: table.LC_docs_adddocs td,
 7466: table.LC_docs_adddocs th {
 7467:   border: 1px solid #BBBBBB;
 7468:   padding: 4px;
 7469:   background: #DDDDDD;
 7470: }
 7471: 
 7472: table.LC_sty_begin {
 7473:   background: #BBFFBB;
 7474: }
 7475: 
 7476: table.LC_sty_end {
 7477:   background: #FFBBBB;
 7478: }
 7479: 
 7480: table.LC_double_column {
 7481:   border-width: 0;
 7482:   border-collapse: collapse;
 7483:   width: 100%;
 7484:   padding: 2px;
 7485: }
 7486: 
 7487: table.LC_double_column tr td.LC_left_col {
 7488:   top: 2px;
 7489:   left: 2px;
 7490:   width: 47%;
 7491:   vertical-align: top;
 7492: }
 7493: 
 7494: table.LC_double_column tr td.LC_right_col {
 7495:   top: 2px;
 7496:   right: 2px;
 7497:   width: 47%;
 7498:   vertical-align: top;
 7499: }
 7500: 
 7501: div.LC_left_float {
 7502:   float: left;
 7503:   padding-right: 5%;
 7504:   padding-bottom: 4px;
 7505: }
 7506: 
 7507: div.LC_clear_float_header {
 7508:   padding-bottom: 2px;
 7509: }
 7510: 
 7511: div.LC_clear_float_footer {
 7512:   padding-top: 10px;
 7513:   clear: both;
 7514: }
 7515: 
 7516: div.LC_grade_show_user {
 7517: /*  border-left: 5px solid $sidebg; */
 7518:   border-top: 5px solid #000000;
 7519:   margin: 50px 0 0 0;
 7520:   padding: 15px 0 5px 10px;
 7521: }
 7522: 
 7523: div.LC_grade_show_user_odd_row {
 7524: /*  border-left: 5px solid #000000; */
 7525: }
 7526: 
 7527: div.LC_grade_show_user div.LC_Box {
 7528:   margin-right: 50px;
 7529: }
 7530: 
 7531: div.LC_grade_submissions,
 7532: div.LC_grade_message_center,
 7533: div.LC_grade_info_links {
 7534:   margin: 5px;
 7535:   width: 99%;
 7536:   background: #FFFFFF;
 7537: }
 7538: 
 7539: div.LC_grade_submissions_header,
 7540: div.LC_grade_message_center_header {
 7541:   font-weight: bold;
 7542:   font-size: large;
 7543: }
 7544: 
 7545: div.LC_grade_submissions_body,
 7546: div.LC_grade_message_center_body {
 7547:   border: 1px solid black;
 7548:   width: 99%;
 7549:   background: #FFFFFF;
 7550: }
 7551: 
 7552: table.LC_scantron_action {
 7553:   width: 100%;
 7554: }
 7555: 
 7556: table.LC_scantron_action tr th {
 7557:   font-weight:bold;
 7558:   font-style:normal;
 7559: }
 7560: 
 7561: .LC_edit_problem_header,
 7562: div.LC_edit_problem_footer {
 7563:   font-weight: normal;
 7564:   font-size:  medium;
 7565:   margin: 2px;
 7566:   background-color: $sidebg;
 7567: }
 7568: 
 7569: div.LC_edit_problem_header,
 7570: div.LC_edit_problem_header div,
 7571: div.LC_edit_problem_footer,
 7572: div.LC_edit_problem_footer div,
 7573: div.LC_edit_problem_editxml_header,
 7574: div.LC_edit_problem_editxml_header div {
 7575:   z-index: 100;
 7576: }
 7577: 
 7578: div.LC_edit_problem_header_title {
 7579:   font-weight: bold;
 7580:   font-size: larger;
 7581:   background: $tabbg;
 7582:   padding: 3px;
 7583:   margin: 0 0 5px 0;
 7584: }
 7585: 
 7586: table.LC_edit_problem_header_title {
 7587:   width: 100%;
 7588:   background: $tabbg;
 7589: }
 7590: 
 7591: div.LC_edit_actionbar {
 7592:     background-color: $sidebg;
 7593:     margin: 0;
 7594:     padding: 0;
 7595:     line-height: 200%;
 7596: }
 7597: 
 7598: div.LC_edit_actionbar div{
 7599:     padding: 0;
 7600:     margin: 0;
 7601:     display: inline-block;
 7602: }
 7603: 
 7604: .LC_edit_opt {
 7605:   padding-left: 1em;
 7606:   white-space: nowrap;
 7607: }
 7608: 
 7609: .LC_edit_problem_latexhelper{
 7610:     text-align: right;
 7611: }
 7612: 
 7613: #LC_edit_problem_colorful div{
 7614:     margin-left: 40px;
 7615: }
 7616: 
 7617: #LC_edit_problem_codemirror div{
 7618:     margin-left: 0px;
 7619: }
 7620: 
 7621: img.stift {
 7622:   border-width: 0;
 7623:   vertical-align: middle;
 7624: }
 7625: 
 7626: table td.LC_mainmenu_col_fieldset {
 7627:   vertical-align: top;
 7628: }
 7629: 
 7630: div.LC_createcourse {
 7631:   margin: 10px 10px 10px 10px;
 7632: }
 7633: 
 7634: .LC_dccid {
 7635:   float: right;
 7636:   margin: 0.2em 0 0 0;
 7637:   padding: 0;
 7638:   font-size: 90%;
 7639:   display:none;
 7640: }
 7641: 
 7642: ol.LC_primary_menu a:hover,
 7643: ol#LC_MenuBreadcrumbs a:hover,
 7644: ol#LC_PathBreadcrumbs a:hover,
 7645: ul#LC_secondary_menu a:hover,
 7646: .LC_FormSectionClearButton input:hover
 7647: ul.LC_TabContent   li:hover a {
 7648:   color:$button_hover;
 7649:   text-decoration:none;
 7650: }
 7651: 
 7652: h1 {
 7653:   padding: 0;
 7654:   line-height:130%;
 7655: }
 7656: 
 7657: h2,
 7658: h3,
 7659: h4,
 7660: h5,
 7661: h6 {
 7662:   margin: 5px 0 5px 0;
 7663:   padding: 0;
 7664:   line-height:130%;
 7665: }
 7666: 
 7667: .LC_hcell {
 7668:   padding:3px 15px 3px 15px;
 7669:   margin: 0;
 7670:   background-color:$tabbg;
 7671:   color:$fontmenu;
 7672:   border-bottom:solid 1px $lg_border_color;
 7673: }
 7674: 
 7675: .LC_Box > .LC_hcell {
 7676:   margin: 0 -10px 10px -10px;
 7677: }
 7678: 
 7679: .LC_noBorder {
 7680:   border: 0;
 7681: }
 7682: 
 7683: .LC_FormSectionClearButton input {
 7684:   background-color:transparent;
 7685:   border: none;
 7686:   cursor:pointer;
 7687:   text-decoration:underline;
 7688: }
 7689: 
 7690: .LC_help_open_topic {
 7691:   color: #FFFFFF;
 7692:   background-color: #EEEEFF;
 7693:   margin: 1px;
 7694:   padding: 4px;
 7695:   border: 1px solid #000033;
 7696:   white-space: nowrap;
 7697:   /* vertical-align: middle; */
 7698: }
 7699: 
 7700: dl,
 7701: ul,
 7702: div,
 7703: fieldset {
 7704:   margin: 10px 10px 10px 0;
 7705:   /* overflow: hidden; */
 7706: }
 7707: 
 7708: fieldset#LC_selectuser {
 7709:     margin: 0;
 7710:     padding: 0;
 7711: }
 7712: 
 7713: article.geogebraweb div {
 7714:     margin: 0;
 7715: }
 7716: 
 7717: fieldset > legend {
 7718:   font-weight: bold;
 7719:   padding: 0 5px 0 5px;
 7720: }
 7721: 
 7722: #LC_nav_bar {
 7723:   float: left;
 7724:   background-color: $pgbg_or_bgcolor;
 7725:   margin: 0 0 2px 0;
 7726: }
 7727: 
 7728: #LC_realm {
 7729:   margin: 0.2em 0 0 0;
 7730:   padding: 0;
 7731:   font-weight: bold;
 7732:   text-align: center;
 7733:   background-color: $pgbg_or_bgcolor;
 7734: }
 7735: 
 7736: #LC_nav_bar em {
 7737:   font-weight: bold;
 7738:   font-style: normal;
 7739: }
 7740: 
 7741: ol.LC_primary_menu {
 7742:   margin: 0;
 7743:   padding: 0;
 7744: }
 7745: 
 7746: ol#LC_PathBreadcrumbs {
 7747:   margin: 0;
 7748: }
 7749: 
 7750: ol.LC_primary_menu li {
 7751:   color: RGB(80, 80, 80);
 7752:   vertical-align: middle;
 7753:   text-align: left;
 7754:   list-style: none;
 7755:   position: relative;
 7756:   float: left;
 7757:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7758:   line-height: 1.5em;
 7759: }
 7760: 
 7761: ol.LC_primary_menu li a, 
 7762: ol.LC_primary_menu li p {
 7763:   display: block;
 7764:   margin: 0;
 7765:   padding: 0 5px 0 10px;
 7766:   text-decoration: none;
 7767: }
 7768: 
 7769: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7770:   display: inline-block;
 7771:   width: 95%;
 7772:   text-align: left;
 7773: }
 7774: 
 7775: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7776:   display: inline-block;
 7777:   width: 5%;
 7778:   float: right;
 7779:   text-align: right;
 7780:   font-size: 70%;
 7781: }
 7782: 
 7783: ol.LC_primary_menu ul {
 7784:   display: none;
 7785:   width: 15em;
 7786:   background-color: $data_table_light;
 7787:   position: absolute;
 7788:   top: 100%;
 7789: }
 7790: 
 7791: ol.LC_primary_menu ul ul {
 7792:   left: 100%;
 7793:   top: 0;
 7794: }
 7795: 
 7796: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7797:   display: block;
 7798:   position: absolute;
 7799:   margin: 0;
 7800:   padding: 0;
 7801:   z-index: 2;
 7802: }
 7803: 
 7804: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7805: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7806:   font-size: 90%;
 7807:   vertical-align: top;
 7808:   float: none;
 7809:   border-left: 1px solid black;
 7810:   border-right: 1px solid black;
 7811: /* A dark bottom border to visualize different menu options;
 7812: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7813:   border-bottom: 1px solid $data_table_dark;
 7814: }
 7815: 
 7816: ol.LC_primary_menu li li p:hover {
 7817:   color:$button_hover;
 7818:   text-decoration:none;
 7819:   background-color:$data_table_dark;
 7820: }
 7821: 
 7822: ol.LC_primary_menu li li a:hover {
 7823:    color:$button_hover;
 7824:    background-color:$data_table_dark;
 7825: }
 7826: 
 7827: /* Font-size equal to the size of the predecessors*/
 7828: ol.LC_primary_menu li:hover li li {
 7829:   font-size: 100%;
 7830: }
 7831: 
 7832: ol.LC_primary_menu li img {
 7833:   vertical-align: bottom;
 7834:   height: 1.1em;
 7835:   margin: 0.2em 0 0 0;
 7836: }
 7837: 
 7838: ol.LC_primary_menu a {
 7839:   color: RGB(80, 80, 80);
 7840:   text-decoration: none;
 7841: }
 7842: 
 7843: ol.LC_primary_menu a.LC_new_message {
 7844:   font-weight:bold;
 7845:   color: darkred;
 7846: }
 7847: 
 7848: ol.LC_docs_parameters {
 7849:   margin-left: 0;
 7850:   padding: 0;
 7851:   list-style: none;
 7852: }
 7853: 
 7854: ol.LC_docs_parameters li {
 7855:   margin: 0;
 7856:   padding-right: 20px;
 7857:   display: inline;
 7858: }
 7859: 
 7860: ol.LC_docs_parameters li:before {
 7861:   content: "\\002022 \\0020";
 7862: }
 7863: 
 7864: li.LC_docs_parameters_title {
 7865:   font-weight: bold;
 7866: }
 7867: 
 7868: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7869:   content: "";
 7870: }
 7871: 
 7872: ul#LC_secondary_menu {
 7873:   clear: right;
 7874:   color: $fontmenu;
 7875:   background: $tabbg;
 7876:   list-style: none;
 7877:   padding: 0;
 7878:   margin: 0;
 7879:   width: 100%;
 7880:   text-align: left;
 7881:   float: left;
 7882: }
 7883: 
 7884: ul#LC_secondary_menu li {
 7885:   font-weight: bold;
 7886:   line-height: 1.8em;
 7887:   border-right: 1px solid black;
 7888:   float: left;
 7889: }
 7890: 
 7891: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7892:   background-color: $data_table_light;
 7893: }
 7894: 
 7895: ul#LC_secondary_menu li a {
 7896:   padding: 0 0.8em;
 7897: }
 7898: 
 7899: ul#LC_secondary_menu li ul {
 7900:   display: none;
 7901: }
 7902: 
 7903: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7904:   display: block;
 7905:   position: absolute;
 7906:   margin: 0;
 7907:   padding: 0;
 7908:   list-style:none;
 7909:   float: none;
 7910:   background-color: $data_table_light;
 7911:   z-index: 2;
 7912:   margin-left: -1px;
 7913: }
 7914: 
 7915: ul#LC_secondary_menu li ul li {
 7916:   font-size: 90%;
 7917:   vertical-align: top;
 7918:   border-left: 1px solid black;
 7919:   border-right: 1px solid black;
 7920:   background-color: $data_table_light;
 7921:   list-style:none;
 7922:   float: none;
 7923: }
 7924: 
 7925: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7926:   background-color: $data_table_dark;
 7927: }
 7928: 
 7929: ul.LC_TabContent {
 7930:   display:block;
 7931:   background: $sidebg;
 7932:   border-bottom: solid 1px $lg_border_color;
 7933:   list-style:none;
 7934:   margin: -1px -10px 0 -10px;
 7935:   padding: 0;
 7936: }
 7937: 
 7938: ul.LC_TabContent li,
 7939: ul.LC_TabContentBigger li {
 7940:   float:left;
 7941: }
 7942: 
 7943: ul#LC_secondary_menu li a {
 7944:   color: $fontmenu;
 7945:   text-decoration: none;
 7946: }
 7947: 
 7948: ul.LC_TabContent {
 7949:   min-height:20px;
 7950: }
 7951: 
 7952: ul.LC_TabContent li {
 7953:   vertical-align:middle;
 7954:   padding: 0 16px 0 10px;
 7955:   background-color:$tabbg;
 7956:   border-bottom:solid 1px $lg_border_color;
 7957:   border-left: solid 1px $font;
 7958: }
 7959: 
 7960: ul.LC_TabContent .right {
 7961:   float:right;
 7962: }
 7963: 
 7964: ul.LC_TabContent li a,
 7965: ul.LC_TabContent li {
 7966:   color:rgb(47,47,47);
 7967:   text-decoration:none;
 7968:   font-size:95%;
 7969:   font-weight:bold;
 7970:   min-height:20px;
 7971: }
 7972: 
 7973: ul.LC_TabContent li a:hover,
 7974: ul.LC_TabContent li a:focus {
 7975:   color: $button_hover;
 7976:   background:none;
 7977:   outline:none;
 7978: }
 7979: 
 7980: ul.LC_TabContent li:hover {
 7981:   color: $button_hover;
 7982:   cursor:pointer;
 7983: }
 7984: 
 7985: ul.LC_TabContent li.active {
 7986:   color: $font;
 7987:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7988:   border-bottom:solid 1px #FFFFFF;
 7989:   cursor: default;
 7990: }
 7991: 
 7992: ul.LC_TabContent li.active a {
 7993:   color:$font;
 7994:   background:#FFFFFF;
 7995:   outline: none;
 7996: }
 7997: 
 7998: ul.LC_TabContent li.goback {
 7999:   float: left;
 8000:   border-left: none;
 8001: }
 8002: 
 8003: #maincoursedoc {
 8004:   clear:both;
 8005: }
 8006: 
 8007: ul.LC_TabContentBigger {
 8008:   display:block;
 8009:   list-style:none;
 8010:   padding: 0;
 8011: }
 8012: 
 8013: ul.LC_TabContentBigger li {
 8014:   vertical-align:bottom;
 8015:   height: 30px;
 8016:   font-size:110%;
 8017:   font-weight:bold;
 8018:   color: #737373;
 8019: }
 8020: 
 8021: ul.LC_TabContentBigger li.active {
 8022:   position: relative;
 8023:   top: 1px;
 8024: }
 8025: 
 8026: ul.LC_TabContentBigger li a {
 8027:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 8028:   height: 30px;
 8029:   line-height: 30px;
 8030:   text-align: center;
 8031:   display: block;
 8032:   text-decoration: none;
 8033:   outline: none;  
 8034: }
 8035: 
 8036: ul.LC_TabContentBigger li.active a {
 8037:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8038:   color:$font;
 8039: }
 8040: 
 8041: ul.LC_TabContentBigger li b {
 8042:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8043:   display: block;
 8044:   float: left;
 8045:   padding: 0 30px;
 8046:   border-bottom: 1px solid $lg_border_color;
 8047: }
 8048: 
 8049: ul.LC_TabContentBigger li:hover b {
 8050:   color:$button_hover;
 8051: }
 8052: 
 8053: ul.LC_TabContentBigger li.active b {
 8054:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8055:   color:$font;
 8056:   border: 0;
 8057: }
 8058: 
 8059: 
 8060: ul.LC_CourseBreadcrumbs {
 8061:   background: $sidebg;
 8062:   height: 2em;
 8063:   padding-left: 10px;
 8064:   margin: 0;
 8065:   list-style-position: inside;
 8066: }
 8067: 
 8068: ol#LC_MenuBreadcrumbs,
 8069: ol#LC_PathBreadcrumbs {
 8070:   padding-left: 10px;
 8071:   margin: 0;
 8072:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8073: }
 8074: 
 8075: ol#LC_MenuBreadcrumbs li,
 8076: ol#LC_PathBreadcrumbs li,
 8077: ul.LC_CourseBreadcrumbs li {
 8078:   display: inline;
 8079:   white-space: normal;  
 8080: }
 8081: 
 8082: ol#LC_MenuBreadcrumbs li a,
 8083: ul.LC_CourseBreadcrumbs li a {
 8084:   text-decoration: none;
 8085:   font-size:90%;
 8086: }
 8087: 
 8088: ol#LC_MenuBreadcrumbs h1 {
 8089:   display: inline;
 8090:   font-size: 90%;
 8091:   line-height: 2.5em;
 8092:   margin: 0;
 8093:   padding: 0;
 8094: }
 8095: 
 8096: ol#LC_PathBreadcrumbs li a {
 8097:   text-decoration:none;
 8098:   font-size:100%;
 8099:   font-weight:bold;
 8100: }
 8101: 
 8102: .LC_Box {
 8103:   border: solid 1px $lg_border_color;
 8104:   padding: 0 10px 10px 10px;
 8105: }
 8106: 
 8107: .LC_DocsBox {
 8108:   border: solid 1px $lg_border_color;
 8109:   padding: 0 0 10px 10px;
 8110: }
 8111: 
 8112: .LC_AboutMe_Image {
 8113:   float:left;
 8114:   margin-right:10px;
 8115: }
 8116: 
 8117: .LC_Clear_AboutMe_Image {
 8118:   clear:left;
 8119: }
 8120: 
 8121: dl.LC_ListStyleClean dt {
 8122:   padding-right: 5px;
 8123:   display: table-header-group;
 8124: }
 8125: 
 8126: dl.LC_ListStyleClean dd {
 8127:   display: table-row;
 8128: }
 8129: 
 8130: .LC_ListStyleClean,
 8131: .LC_ListStyleSimple,
 8132: .LC_ListStyleNormal,
 8133: .LC_ListStyleSpecial {
 8134:   /* display:block; */
 8135:   list-style-position: inside;
 8136:   list-style-type: none;
 8137:   overflow: hidden;
 8138:   padding: 0;
 8139: }
 8140: 
 8141: .LC_ListStyleSimple li,
 8142: .LC_ListStyleSimple dd,
 8143: .LC_ListStyleNormal li,
 8144: .LC_ListStyleNormal dd,
 8145: .LC_ListStyleSpecial li,
 8146: .LC_ListStyleSpecial dd {
 8147:   margin: 0;
 8148:   padding: 5px 5px 5px 10px;
 8149:   clear: both;
 8150: }
 8151: 
 8152: .LC_ListStyleClean li,
 8153: .LC_ListStyleClean dd {
 8154:   padding-top: 0;
 8155:   padding-bottom: 0;
 8156: }
 8157: 
 8158: .LC_ListStyleSimple dd,
 8159: .LC_ListStyleSimple li {
 8160:   border-bottom: solid 1px $lg_border_color;
 8161: }
 8162: 
 8163: .LC_ListStyleSpecial li,
 8164: .LC_ListStyleSpecial dd {
 8165:   list-style-type: none;
 8166:   background-color: RGB(220, 220, 220);
 8167:   margin-bottom: 4px;
 8168: }
 8169: 
 8170: table.LC_SimpleTable {
 8171:   margin:5px;
 8172:   border:solid 1px $lg_border_color;
 8173: }
 8174: 
 8175: table.LC_SimpleTable tr {
 8176:   padding: 0;
 8177:   border:solid 1px $lg_border_color;
 8178: }
 8179: 
 8180: table.LC_SimpleTable thead {
 8181:   background:rgb(220,220,220);
 8182: }
 8183: 
 8184: div.LC_columnSection {
 8185:   display: block;
 8186:   clear: both;
 8187:   overflow: hidden;
 8188:   margin: 0;
 8189: }
 8190: 
 8191: div.LC_columnSection>* {
 8192:   float: left;
 8193:   margin: 10px 20px 10px 0;
 8194:   overflow:hidden;
 8195: }
 8196: 
 8197: table em {
 8198:   font-weight: bold;
 8199:   font-style: normal;
 8200: }
 8201: 
 8202: table.LC_tableBrowseRes,
 8203: table.LC_tableOfContent {
 8204:   border:none;
 8205:   border-spacing: 1px;
 8206:   padding: 3px;
 8207:   background-color: #FFFFFF;
 8208:   font-size: 90%;
 8209: }
 8210: 
 8211: table.LC_tableOfContent {
 8212:   border-collapse: collapse;
 8213: }
 8214: 
 8215: table.LC_tableBrowseRes a,
 8216: table.LC_tableOfContent a {
 8217:   background-color: transparent;
 8218:   text-decoration: none;
 8219: }
 8220: 
 8221: table.LC_tableOfContent img {
 8222:   border: none;
 8223:   height: 1.3em;
 8224:   vertical-align: text-bottom;
 8225:   margin-right: 0.3em;
 8226: }
 8227: 
 8228: a#LC_content_toolbar_firsthomework {
 8229:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8230: }
 8231: 
 8232: a#LC_content_toolbar_everything {
 8233:   background-image:url(/res/adm/pages/show-all.gif);
 8234: }
 8235: 
 8236: a#LC_content_toolbar_uncompleted {
 8237:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8238: }
 8239: 
 8240: #LC_content_toolbar_clearbubbles {
 8241:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8242: }
 8243: 
 8244: a#LC_content_toolbar_changefolder {
 8245:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8246: }
 8247: 
 8248: a#LC_content_toolbar_changefolder_toggled {
 8249:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8250: }
 8251: 
 8252: a#LC_content_toolbar_edittoplevel {
 8253:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8254: }
 8255: 
 8256: a#LC_content_toolbar_printout {
 8257:   background-image:url(/res/adm/pages/printout.gif);
 8258: }
 8259: 
 8260: ul#LC_toolbar li a:hover {
 8261:   background-position: bottom center;
 8262: }
 8263: 
 8264: ul#LC_toolbar {
 8265:   padding: 0;
 8266:   margin: 2px;
 8267:   list-style:none;
 8268:   position:relative;
 8269:   background-color:white;
 8270:   overflow: auto;
 8271: }
 8272: 
 8273: ul#LC_toolbar li {
 8274:   border:1px solid white;
 8275:   padding: 0;
 8276:   margin: 0;
 8277:   float: left;
 8278:   display:inline;
 8279:   vertical-align:middle;
 8280:   white-space: nowrap;
 8281: }
 8282: 
 8283: 
 8284: a.LC_toolbarItem {
 8285:   display:block;
 8286:   padding: 0;
 8287:   margin: 0;
 8288:   height: 32px;
 8289:   width: 32px;
 8290:   color:white;
 8291:   border: none;
 8292:   background-repeat:no-repeat;
 8293:   background-color:transparent;
 8294: }
 8295: 
 8296: ul.LC_funclist {
 8297:     margin: 0;
 8298:     padding: 0.5em 1em 0.5em 0;
 8299: }
 8300: 
 8301: ul.LC_funclist > li:first-child {
 8302:     font-weight:bold; 
 8303:     margin-left:0.8em;
 8304: }
 8305: 
 8306: ul.LC_funclist + ul.LC_funclist {
 8307:     /* 
 8308:        left border as a seperator if we have more than
 8309:        one list 
 8310:     */
 8311:     border-left: 1px solid $sidebg;
 8312:     /* 
 8313:        this hides the left border behind the border of the 
 8314:        outer box if element is wrapped to the next 'line' 
 8315:     */
 8316:     margin-left: -1px;
 8317: }
 8318: 
 8319: ul.LC_funclist li {
 8320:   display: inline;
 8321:   white-space: nowrap;
 8322:   margin: 0 0 0 25px;
 8323:   line-height: 150%;
 8324: }
 8325: 
 8326: .LC_hidden {
 8327:   display: none;
 8328: }
 8329: 
 8330: .LCmodal-overlay {
 8331: 		position:fixed;
 8332: 		top:0;
 8333: 		right:0;
 8334: 		bottom:0;
 8335: 		left:0;
 8336: 		height:100%;
 8337: 		width:100%;
 8338: 		margin:0;
 8339: 		padding:0;
 8340: 		background:#999;
 8341: 		opacity:.75;
 8342: 		filter: alpha(opacity=75);
 8343: 		-moz-opacity: 0.75;
 8344: 		z-index:101;
 8345: }
 8346: 
 8347: * html .LCmodal-overlay {   
 8348: 		position: absolute;
 8349: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8350: }
 8351: 
 8352: .LCmodal-window {
 8353: 		position:fixed;
 8354: 		top:50%;
 8355: 		left:50%;
 8356: 		margin:0;
 8357: 		padding:0;
 8358: 		z-index:102;
 8359: 	}
 8360: 
 8361: * html .LCmodal-window {
 8362: 		position:absolute;
 8363: }
 8364: 
 8365: .LCclose-window {
 8366: 		position:absolute;
 8367: 		width:32px;
 8368: 		height:32px;
 8369: 		right:8px;
 8370: 		top:8px;
 8371: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8372: 		text-indent:-99999px;
 8373: 		overflow:hidden;
 8374: 		cursor:pointer;
 8375: }
 8376: 
 8377: .LCisDisabled {
 8378:   cursor: not-allowed;
 8379:   opacity: 0.5;
 8380: }
 8381: 
 8382: a[aria-disabled="true"] {
 8383:   color: currentColor;
 8384:   display: inline-block;  /* For IE11/ MS Edge bug */
 8385:   pointer-events: none;
 8386:   text-decoration: none;
 8387: }
 8388: 
 8389: pre.LC_wordwrap {
 8390:   white-space: pre-wrap;
 8391:   white-space: -moz-pre-wrap;
 8392:   white-space: -pre-wrap;
 8393:   white-space: -o-pre-wrap;
 8394:   word-wrap: break-word;
 8395: }
 8396: 
 8397: /*
 8398:   styles used by TTH when "Default set of options to pass to tth/m
 8399:   when converting TeX" in course settings has been set
 8400: 
 8401:   option passed: -t
 8402: 
 8403: */
 8404: 
 8405: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8406: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8407: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8408: td div.norm {line-height:normal;}
 8409: 
 8410: /*
 8411:   option passed -y3
 8412: */
 8413: 
 8414: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8415: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8416: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8417: 
 8418: #LC_minitab_header {
 8419:   float:left;
 8420:   width:100%;
 8421:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8422:   font-size:93%;
 8423:   line-height:normal;
 8424:   margin: 0.5em 0 0.5em 0;
 8425: }
 8426: #LC_minitab_header ul {
 8427:   margin:0;
 8428:   padding:10px 10px 0;
 8429:   list-style:none;
 8430: }
 8431: #LC_minitab_header li {
 8432:   float:left;
 8433:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8434:   margin:0;
 8435:   padding:0 0 0 9px;
 8436: }
 8437: #LC_minitab_header a {
 8438:   display:block;
 8439:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8440:   padding:5px 15px 4px 6px;
 8441: }
 8442: #LC_minitab_header #LC_current_minitab {
 8443:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8444: }
 8445: #LC_minitab_header #LC_current_minitab a {
 8446:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8447:   padding-bottom:5px;
 8448: }
 8449: 
 8450: 
 8451: END
 8452: }
 8453: 
 8454: =pod
 8455: 
 8456: =item * &headtag()
 8457: 
 8458: Returns a uniform footer for LON-CAPA web pages.
 8459: 
 8460: Inputs: $title - optional title for the head
 8461:         $head_extra - optional extra HTML to put inside the <head>
 8462:         $args - optional arguments
 8463:             force_register - if is true call registerurl so the remote is 
 8464:                              informed
 8465:             redirect       -> array ref of
 8466:                                    1- seconds before redirect occurs
 8467:                                    2- url to redirect to
 8468:                                    3- whether the side effect should occur
 8469:                            (side effect of setting 
 8470:                                $env{'internal.head.redirect'} to the url 
 8471:                                redirected to)
 8472:                                    4- whether the redirect target should be
 8473:                                       the opener of the current (pop-up)
 8474:                                       window (side effect of setting
 8475:                                       $env{'internal.head.to_opener'} to
 8476:                                       1, if true.
 8477:                                    5- whether encrypt check should be skipped
 8478:             domain         -> force to color decorate a page for a specific
 8479:                                domain
 8480:             function       -> force usage of a specific rolish color scheme
 8481:             bgcolor        -> override the default page bgcolor
 8482:             no_auto_mt_title
 8483:                            -> prevent &mt()ing the title arg
 8484: 
 8485: =cut
 8486: 
 8487: sub headtag {
 8488:     my ($title,$head_extra,$args) = @_;
 8489:     
 8490:     my $function = $args->{'function'} || &get_users_function();
 8491:     my $domain   = $args->{'domain'}   || &determinedomain();
 8492:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8493:     my $httphost = $args->{'use_absolute'};
 8494:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8495: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8496: 		   #time(),
 8497: 		   $env{'environment.color.timestamp'},
 8498: 		   $function,$domain,$bgcolor);
 8499: 
 8500:     $url = '/adm/css/'.&escape($url).'.css';
 8501: 
 8502:     my $result =
 8503: 	'<head>'.
 8504: 	&font_settings($args);
 8505: 
 8506:     my $inhibitprint;
 8507:     if ($args->{'print_suppress'}) {
 8508:         $inhibitprint = &print_suppression();
 8509:     }
 8510: 
 8511:     if (!$args->{'frameset'}) {
 8512: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8513:     }
 8514:     if ($args->{'force_register'}) {
 8515:         $result .= &Apache::lonmenu::registerurl(1);
 8516:     }
 8517:     if (!$args->{'no_nav_bar'} 
 8518: 	&& !$args->{'only_body'}
 8519: 	&& !$args->{'frameset'}) {
 8520: 	$result .= &help_menu_js($httphost);
 8521:         $result.=&modal_window();
 8522:         $result.=&togglebox_script();
 8523:         $result.=&wishlist_window();
 8524:         $result.=&LCprogressbarUpdate_script();
 8525:     } else {
 8526:         if ($args->{'add_modal'}) {
 8527:            $result.=&modal_window();
 8528:         }
 8529:         if ($args->{'add_wishlist'}) {
 8530:            $result.=&wishlist_window();
 8531:         }
 8532:         if ($args->{'add_togglebox'}) {
 8533:            $result.=&togglebox_script();
 8534:         }
 8535:         if ($args->{'add_progressbar'}) {
 8536:            $result.=&LCprogressbarUpdate_script();
 8537:         }
 8538:     }
 8539:     if (ref($args->{'redirect'})) {
 8540: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 8541:         if (!$skip_enc_check) {
 8542: 	    $url = &Apache::lonenc::check_encrypt($url);
 8543:         }
 8544: 	if (!$inhibit_continue) {
 8545: 	    $env{'internal.head.redirect'} = $url;
 8546: 	}
 8547:         $result.=<<"ADDMETA";
 8548: <meta http-equiv="pragma" content="no-cache" />
 8549: ADDMETA
 8550:         if ($to_opener) {
 8551:             $env{'internal.head.to_opener'} = 1;
 8552:             my $dest = &js_escape($url);
 8553:             my $timeout = int($time * 1000);
 8554:             $result .=<<"ENDJS";
 8555: <script type="text/javascript">
 8556: // <![CDATA[
 8557: function LC_To_Opener() {
 8558:     var dest = '$dest';
 8559:     if (dest != '') {
 8560:         if (window.opener != null && !window.opener.closed) {
 8561:             window.opener.location.href=dest;
 8562:             window.close();
 8563:         } else {
 8564:             window.location.href=dest;
 8565:         }
 8566:     }
 8567: }
 8568: \$(document).ready(function () {
 8569:     setTimeout('LC_To_Opener()',$timeout);
 8570: });
 8571: // ]]>
 8572: </script>
 8573: ENDJS
 8574:         } else {
 8575:             $result.=<<"ADDMETA";
 8576: <meta http-equiv="Refresh" content="$time; url=$url" />
 8577: ADDMETA
 8578:         }
 8579:     } else {
 8580:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8581:             my $requrl = $env{'request.uri'};
 8582:             if ($requrl eq '') {
 8583:                 $requrl = $ENV{'REQUEST_URI'};
 8584:                 $requrl =~ s/\?.+$//;
 8585:             }
 8586:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8587:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8588:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8589:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8590:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8591:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8592:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8593:                     my ($offload,$offloadoth);
 8594:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8595:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8596:                             $offload = 1;
 8597:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8598:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8599:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8600:                                     $offloadoth = 1;
 8601:                                     $dom_in_use = $env{'user.domain'};
 8602:                                 }
 8603:                             }
 8604:                         }
 8605:                     }
 8606:                     unless ($offload) {
 8607:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 8608:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 8609:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8610:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8611:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8612:                                         $offload = 1;
 8613:                                         $offloadoth = 1;
 8614:                                         $dom_in_use = $env{'user.domain'};
 8615:                                     }
 8616:                                 }
 8617:                             }
 8618:                         }
 8619:                     }
 8620:                     if ($offload) {
 8621:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 8622:                         if (($newserver eq '') && ($offloadoth)) {
 8623:                             my @domains = &Apache::lonnet::current_machine_domains();
 8624:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
 8625:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 8626:                             }
 8627:                         }
 8628:                         if (($newserver) && ($newserver ne $lonhost)) {
 8629:                             my $numsec = 5;
 8630:                             my $timeout = $numsec * 1000;
 8631:                             my ($newurl,$locknum,%locks,$msg);
 8632:                             if ($env{'request.role.adv'}) {
 8633:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 8634:                             }
 8635:                             my $disable_submit = 0;
 8636:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 8637:                                 $disable_submit = 1;
 8638:                             }
 8639:                             if ($locknum) {
 8640:                                 my @lockinfo = sort(values(%locks));
 8641:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 8642:                                        join(", ",sort(values(%locks)))."\n";
 8643:                                 if (&show_course()) {
 8644:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 8645:                                 } else {
 8646:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 8647:                                 }
 8648:                             } else {
 8649:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8650:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 8651:                                 }
 8652:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8653:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 8654:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8655:                                     $newurl .= '&role='.$env{'request.role'};
 8656:                                 }
 8657:                                 if ($env{'request.symb'}) {
 8658:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 8659:                                     if ($shownsymb =~ m{^/enc/}) {
 8660:                                         my $reqdmajor = 2;
 8661:                                         my $reqdminor = 11;
 8662:                                         my $reqdsubminor = 3;
 8663:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 8664:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 8665:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 8666:                                         if (($major eq '' && $minor eq '') ||
 8667:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 8668:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 8669:                                              ($reqdsubminor > $subminor))))) {
 8670:                                             undef($shownsymb);
 8671:                                         }
 8672:                                     }
 8673:                                     if ($shownsymb) {
 8674:                                         &js_escape(\$shownsymb);
 8675:                                         $newurl .= '&symb='.$shownsymb;
 8676:                                     }
 8677:                                 } else {
 8678:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 8679:                                     &js_escape(\$shownurl);
 8680:                                     $newurl .= '&origurl='.$shownurl;
 8681:                                 }
 8682:                             }
 8683:                             &js_escape(\$msg);
 8684:                             $result.=<<OFFLOAD
 8685: <meta http-equiv="pragma" content="no-cache" />
 8686: <script type="text/javascript">
 8687: // <![CDATA[
 8688: function LC_Offload_Now() {
 8689:     var dest = "$newurl";
 8690:     if (dest != '') {
 8691:         window.location.href="$newurl";
 8692:     }
 8693: }
 8694: \$(document).ready(function () {
 8695:     window.alert('$msg');
 8696:     if ($disable_submit) {
 8697:         \$(".LC_hwk_submit").prop("disabled", true);
 8698:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8699:     }
 8700:     setTimeout('LC_Offload_Now()', $timeout);
 8701: });
 8702: // ]]>
 8703: </script>
 8704: OFFLOAD
 8705:                         }
 8706:                     }
 8707:                 }
 8708:             }
 8709:         }
 8710:     }
 8711:     if (!defined($title)) {
 8712: 	$title = 'The LearningOnline Network with CAPA';
 8713:     }
 8714:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8715:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8716: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8717:     if (!$args->{'frameset'}) {
 8718:         $result .= ' /';
 8719:     }
 8720:     $result .= '>'
 8721:         .$inhibitprint
 8722: 	.$head_extra;
 8723:     my $clientmobile;
 8724:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8725:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8726:     } else {
 8727:         $clientmobile = $env{'browser.mobile'};
 8728:     }
 8729:     if ($clientmobile) {
 8730:         $result .= '
 8731: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8732: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8733:     }
 8734:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8735:     return $result.'</head>';
 8736: }
 8737: 
 8738: =pod
 8739: 
 8740: =item * &font_settings()
 8741: 
 8742: Returns neccessary <meta> to set the proper encoding
 8743: 
 8744: Inputs: optional reference to HASH -- $args passed to &headtag()
 8745: 
 8746: =cut
 8747: 
 8748: sub font_settings {
 8749:     my ($args) = @_;
 8750:     my $headerstring='';
 8751:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8752:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8753: 	$headerstring.=
 8754: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8755:         if (!$args->{'frameset'}) {
 8756:             $headerstring.= ' /';
 8757:         }
 8758:         $headerstring .= '>'."\n";
 8759:     }
 8760:     return $headerstring;
 8761: }
 8762: 
 8763: =pod
 8764: 
 8765: =item * &print_suppression()
 8766: 
 8767: In course context returns css which causes the body to be blank when media="print",
 8768: if printout generation is unavailable for the current resource.
 8769: 
 8770: This could be because:
 8771: 
 8772: (a) printstartdate is in the future
 8773: 
 8774: (b) printenddate is in the past
 8775: 
 8776: (c) there is an active exam block with "printout"
 8777: functionality blocked
 8778: 
 8779: Users with pav, pfo or evb privileges are exempt.
 8780: 
 8781: Inputs: none
 8782: 
 8783: =cut
 8784: 
 8785: 
 8786: sub print_suppression {
 8787:     my $noprint;
 8788:     if ($env{'request.course.id'}) {
 8789:         my $scope = $env{'request.course.id'};
 8790:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8791:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8792:             return;
 8793:         }
 8794:         if ($env{'request.course.sec'} ne '') {
 8795:             $scope .= "/$env{'request.course.sec'}";
 8796:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8797:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8798:                 return;
 8799:             }
 8800:         }
 8801:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8802:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8803:         my $clientip = &Apache::lonnet::get_requestor_ip();
 8804:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 8805:         if ($blocked) {
 8806:             my $checkrole = "cm./$cdom/$cnum";
 8807:             if ($env{'request.course.sec'} ne '') {
 8808:                 $checkrole .= "/$env{'request.course.sec'}";
 8809:             }
 8810:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8811:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8812:                 $noprint = 1;
 8813:             }
 8814:         }
 8815:         unless ($noprint) {
 8816:             my $symb = &Apache::lonnet::symbread();
 8817:             if ($symb ne '') {
 8818:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8819:                 if (ref($navmap)) {
 8820:                     my $res = $navmap->getBySymb($symb);
 8821:                     if (ref($res)) {
 8822:                         if (!$res->resprintable()) {
 8823:                             $noprint = 1;
 8824:                         }
 8825:                     }
 8826:                 }
 8827:             }
 8828:         }
 8829:         if ($noprint) {
 8830:             return <<"ENDSTYLE";
 8831: <style type="text/css" media="print">
 8832:     body { display:none }
 8833: </style>
 8834: ENDSTYLE
 8835:         }
 8836:     }
 8837:     return;
 8838: }
 8839: 
 8840: =pod
 8841: 
 8842: =item * &xml_begin()
 8843: 
 8844: Returns the needed doctype and <html>
 8845: 
 8846: Inputs: none
 8847: 
 8848: =cut
 8849: 
 8850: sub xml_begin {
 8851:     my ($is_frameset) = @_;
 8852:     my $output='';
 8853: 
 8854:     if ($env{'browser.mathml'}) {
 8855: 	$output='<?xml version="1.0"?>'
 8856:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8857: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8858:             
 8859: #	    .'<!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">] >'
 8860: 	    .'<!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">'
 8861:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8862: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8863:     } elsif ($is_frameset) {
 8864:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8865:                 '<html>'."\n";
 8866:     } else {
 8867: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8868:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8869:     }
 8870:     return $output;
 8871: }
 8872: 
 8873: =pod
 8874: 
 8875: =item * &start_page()
 8876: 
 8877: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8878: 
 8879: Inputs:
 8880: 
 8881: =over 4
 8882: 
 8883: $title - optional title for the page
 8884: 
 8885: $head_extra - optional extra HTML to incude inside the <head>
 8886: 
 8887: $args - additional optional args supported are:
 8888: 
 8889: =over 8
 8890: 
 8891:              only_body      -> is true will set &bodytag() onlybodytag
 8892:                                     arg on
 8893:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8894:              add_entries    -> additional attributes to add to the  <body>
 8895:              domain         -> force to color decorate a page for a 
 8896:                                     specific domain
 8897:              function       -> force usage of a specific rolish color
 8898:                                     scheme
 8899:              redirect       -> see &headtag()
 8900:              bgcolor        -> override the default page bg color
 8901:              js_ready       -> return a string ready for being used in 
 8902:                                     a javascript writeln
 8903:              html_encode    -> return a string ready for being used in 
 8904:                                     a html attribute
 8905:              force_register -> if is true will turn on the &bodytag()
 8906:                                     $forcereg arg
 8907:              frameset       -> if true will start with a <frameset>
 8908:                                     rather than <body>
 8909:              skip_phases    -> hash ref of 
 8910:                                     head -> skip the <html><head> generation
 8911:                                     body -> skip all <body> generation
 8912:              no_inline_link -> if true and in remote mode, don't show the
 8913:                                     'Switch To Inline Menu' link
 8914:              no_auto_mt_title -> prevent &mt()ing the title arg
 8915:              bread_crumbs ->             Array containing breadcrumbs
 8916:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8917:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8918:                                     to lonhtmlcommon::breadcrumbs
 8919:              group          -> includes the current group, if page is for a
 8920:                                specific group
 8921:              use_absolute   -> for request for external resource or syllabus, this
 8922:                                will contain https://<hostname> if server uses
 8923:                                https (as per hosts.tab), but request is for http
 8924:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8925:              links_disabled -> Links in primary and secondary menus are disabled
 8926:                                (Can enable them once page has loaded - see lonroles.pm
 8927:                                for an example).
 8928:              links_target   -> Target for links, e.g., _parent (optional).
 8929: 
 8930: =back
 8931: 
 8932: =back
 8933: 
 8934: =cut
 8935: 
 8936: sub start_page {
 8937:     my ($title,$head_extra,$args) = @_;
 8938:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8939: 
 8940:     $env{'internal.start_page'}++;
 8941:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 8942: 
 8943:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8944:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8945:     }
 8946: 
 8947:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 8948:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 8949:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 8950:                 $args->{'no_primary_menu'} = 1;
 8951:             }
 8952:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 8953:                 $args->{'no_inline_menu'} = 1;
 8954:             }
 8955:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 8956:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 8957:             }
 8958:         } else {
 8959:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8960:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 8961:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 8962:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 8963:                     $args->{'no_primary_menu'} = 1;
 8964:                 }
 8965:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 8966:                     $args->{'no_inline_menu'} = 1;
 8967:                 }
 8968:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 8969:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 8970:                 }
 8971:             }
 8972:         }
 8973:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 8974:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 8975:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 8976:     } elsif ($env{'request.course.id'}) {
 8977:         my $expiretime=600;
 8978:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 8979:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 8980:         }
 8981:         my ($deeplinkmenu,$menuref);
 8982:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 8983:         if ($menucoll) {
 8984:             if (ref($menuref) eq 'HASH') {
 8985:                 %menu = %{$menuref};
 8986:             }
 8987:             if ($menu{'top'} eq 'n') {
 8988:                 $args->{'no_primary_menu'} = 1;
 8989:             }
 8990:             if ($menu{'inline'} eq 'n') {
 8991:                 unless (&Apache::lonnet::allowed('opa')) {
 8992:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8993:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8994:                     my $crstype = &course_type();
 8995:                     my $now = time;
 8996:                     my $ccrole;
 8997:                     if ($crstype eq 'Community') {
 8998:                         $ccrole = 'co';
 8999:                     } else {
 9000:                         $ccrole = 'cc';
 9001:                     }
 9002:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 9003:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 9004:                         if ((($start) && ($start<0)) ||
 9005:                             (($end) && ($end<$now))  ||
 9006:                             (($start) && ($now<$start))) {
 9007:                             $args->{'no_inline_menu'} = 1;
 9008:                         }
 9009:                     } else {
 9010:                         $args->{'no_inline_menu'} = 1;
 9011:                     }
 9012:                 }
 9013:             }
 9014:         }
 9015:     }
 9016: 
 9017:     my $showncrumbs;
 9018:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 9019: 	if ($args->{'frameset'}) {
 9020: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 9021: 						$args->{'add_entries'});
 9022: 	    $result .= "\n<frameset $attr_string>\n";
 9023:         } else {
 9024:             $result .=
 9025:                 &bodytag($title, 
 9026:                          $args->{'function'},       $args->{'add_entries'},
 9027:                          $args->{'only_body'},      $args->{'domain'},
 9028:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 9029:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 9030:                          $args,                     \@advtools,
 9031:                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
 9032:         }
 9033:     }
 9034: 
 9035:     if ($args->{'js_ready'}) {
 9036: 		$result = &js_ready($result);
 9037:     }
 9038:     if ($args->{'html_encode'}) {
 9039: 		$result = &html_encode($result);
 9040:     }
 9041: 
 9042:     # Preparation for new and consistent functionlist at top of screen
 9043:     # if ($args->{'functionlist'}) {
 9044:     #            $result .= &build_functionlist();
 9045:     #}
 9046: 
 9047:     # Don't add anything more if only_body wanted or in const space
 9048:     return $result if    $args->{'only_body'} 
 9049:                       || $env{'request.state'} eq 'construct';
 9050: 
 9051:     #Breadcrumbs
 9052:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 9053:         unless ($showncrumbs) {
 9054: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 9055: 		#if any br links exists, add them to the breadcrumbs
 9056: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9057: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9058: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9059: 			}
 9060: 		}
 9061:                 # if @advtools array contains items add then to the breadcrumbs
 9062:                 if (@advtools > 0) {
 9063:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9064:                 }
 9065:                 my $menulink;
 9066:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9067:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9068:                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
 9069:                     $menulink = 0;
 9070:                 } else {
 9071:                     undef($menulink);
 9072:                 }
 9073:                 my $linkprotout;
 9074:                 if ($env{'request.deeplink.login'}) {
 9075:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 9076:                     if ($linkprotout) {
 9077:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 9078:                     }
 9079:                 }
 9080: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9081: 		if(exists($args->{'bread_crumbs_component'})){
 9082: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9083: 		} else {
 9084: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9085: 		}
 9086:         }
 9087:     } elsif (($env{'environment.remote'} eq 'on') &&
 9088:              ($env{'form.inhibitmenu'} ne 'yes') &&
 9089:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 9090:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 9091:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 9092:     }
 9093:     return $result;
 9094: }
 9095: 
 9096: sub end_page {
 9097:     my ($args) = @_;
 9098:     $env{'internal.end_page'}++;
 9099:     my $result;
 9100:     if ($args->{'discussion'}) {
 9101: 	my ($target,$parser);
 9102: 	if (ref($args->{'discussion'})) {
 9103: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9104: 				$args->{'discussion'}{'parser'});
 9105: 	}
 9106: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9107:     }
 9108:     if ($args->{'frameset'}) {
 9109: 	$result .= '</frameset>';
 9110:     } else {
 9111: 	$result .= &endbodytag($args);
 9112:     }
 9113:     unless ($args->{'notbody'}) {
 9114:         $result .= "\n</html>";
 9115:     }
 9116: 
 9117:     if ($args->{'js_ready'}) {
 9118: 	$result = &js_ready($result);
 9119:     }
 9120: 
 9121:     if ($args->{'html_encode'}) {
 9122: 	$result = &html_encode($result);
 9123:     }
 9124: 
 9125:     return $result;
 9126: }
 9127: 
 9128: sub menucoll_in_effect {
 9129:     my ($menucoll,$deeplinkmenu,%menu);
 9130:     if ($env{'request.course.id'}) {
 9131:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9132:         if ($env{'request.deeplink.login'}) {
 9133:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9134:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9135:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9136:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9137:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9138:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9139:                     if (ref($navmap)) {
 9140:                         $deeplink = $navmap->get_mapparam(undef,
 9141:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9142:                                                           '0.deeplink');
 9143:                     } else {
 9144:                         $check_login_symb = 1;
 9145:                     }
 9146:                 } else {
 9147:                     my $symb=&Apache::lonnet::symbread();
 9148:                     if ($symb) {
 9149:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9150:                     } else {
 9151:                         $check_login_symb = 1;
 9152:                     }
 9153:                 }
 9154:             } else {
 9155:                 $check_login_symb = 1;
 9156:             }
 9157:             if ($check_login_symb) {
 9158:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9159:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9160:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9161:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9162:                     if (ref($navmap)) {
 9163:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9164:                     }
 9165:                 } else {
 9166:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9167:                 }
 9168:             }
 9169:             if ($deeplink ne '') {
 9170:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9171:                 if ($display =~ /^\d+$/) {
 9172:                     $deeplinkmenu = 1;
 9173:                     $menucoll = $display;
 9174:                 }
 9175:             }
 9176:         }
 9177:         if ($menucoll) {
 9178:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9179:         }
 9180:     }
 9181:     return ($menucoll,$deeplinkmenu,\%menu);
 9182: }
 9183: 
 9184: sub deeplink_login_symb {
 9185:     my ($cnum,$cdom) = @_;
 9186:     my $login_symb;
 9187:     if ($env{'request.deeplink.login'}) {
 9188:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9189:     }
 9190:     return $login_symb;
 9191: }
 9192: 
 9193: sub symb_from_tinyurl {
 9194:     my ($url,$cnum,$cdom) = @_;
 9195:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9196:         my $key = $1;
 9197:         my ($tinyurl,$login);
 9198:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9199:         if (defined($cached)) {
 9200:             $tinyurl = $result;
 9201:         } else {
 9202:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9203:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9204:             if ($currtiny{$key} ne '') {
 9205:                 $tinyurl = $currtiny{$key};
 9206:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9207:             }
 9208:         }
 9209:         if ($tinyurl ne '') {
 9210:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9211:             if (wantarray) {
 9212:                 return ($cnumreq,$symb);
 9213:             } elsif ($cnumreq eq $cnum) {
 9214:                 return $symb;
 9215:             }
 9216:         }
 9217:     }
 9218:     if (wantarray) {
 9219:         return ();
 9220:     } else {
 9221:         return;
 9222:     }
 9223: }
 9224: 
 9225: sub usable_exttools {
 9226:     my %tooltypes;
 9227:     if ($env{'request.course.id'}) {
 9228:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
 9229:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
 9230:                %tooltypes = (
 9231:                              crs => 1,
 9232:                              dom => 1,
 9233:                             );
 9234:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
 9235:                $tooltypes{'crs'} = 1;
 9236:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
 9237:                $tooltypes{'dom'} = 1;
 9238:            }
 9239:         } else {
 9240:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9241:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9242:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9243:             if ($crstype eq '') {
 9244:                 $crstype = 'course';
 9245:             }
 9246:             if ($crstype eq 'course') {
 9247:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
 9248:                     $crstype = 'official';
 9249:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
 9250:                     $crstype = 'textbook';
 9251:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
 9252:                     $crstype = 'lti';
 9253:                 } else {
 9254:                     $crstype = 'unofficial';
 9255:                 }
 9256:             }
 9257:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 9258:             if ($domdefaults{$crstype.'domexttool'}) {
 9259:                 $tooltypes{'dom'} = 1;
 9260:             }
 9261:             if ($domdefaults{$crstype.'exttool'}) {
 9262:                 $tooltypes{'crs'} = 1;
 9263:             }
 9264:         }
 9265:     }
 9266:     return %tooltypes;
 9267: }
 9268: 
 9269: sub wishlist_window {
 9270:     return(<<'ENDWISHLIST');
 9271: <script type="text/javascript">
 9272: // <![CDATA[
 9273: // <!-- BEGIN LON-CAPA Internal
 9274: function set_wishlistlink(title, path) {
 9275:     if (!title) {
 9276:         title = document.title;
 9277:         title = title.replace(/^LON-CAPA /,'');
 9278:     }
 9279:     title = encodeURIComponent(title);
 9280:     title = title.replace("'","\\\'");
 9281:     if (!path) {
 9282:         path = location.pathname;
 9283:     }
 9284:     path = encodeURIComponent(path);
 9285:     path = path.replace("'","\\\'");
 9286:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9287:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9288: }
 9289: // END LON-CAPA Internal -->
 9290: // ]]>
 9291: </script>
 9292: ENDWISHLIST
 9293: }
 9294: 
 9295: sub modal_window {
 9296:     return(<<'ENDMODAL');
 9297: <script type="text/javascript">
 9298: // <![CDATA[
 9299: // <!-- BEGIN LON-CAPA Internal
 9300: var modalWindow = {
 9301: 	parent:"body",
 9302: 	windowId:null,
 9303: 	content:null,
 9304: 	width:null,
 9305: 	height:null,
 9306: 	close:function()
 9307: 	{
 9308: 	        $(".LCmodal-window").remove();
 9309: 	        $(".LCmodal-overlay").remove();
 9310: 	},
 9311: 	open:function()
 9312: 	{
 9313: 		var modal = "";
 9314: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9315: 		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;\">";
 9316: 		modal += this.content;
 9317: 		modal += "</div>";	
 9318: 
 9319: 		$(this.parent).append(modal);
 9320: 
 9321: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9322: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9323: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9324: 	}
 9325: };
 9326: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9327: 	{
 9328:                 source = source.replace(/'/g,"&#39;");
 9329: 		modalWindow.windowId = "myModal";
 9330: 		modalWindow.width = width;
 9331: 		modalWindow.height = height;
 9332: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9333: 		modalWindow.open();
 9334: 	};
 9335: // END LON-CAPA Internal -->
 9336: // ]]>
 9337: </script>
 9338: ENDMODAL
 9339: }
 9340: 
 9341: sub modal_link {
 9342:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9343:     unless ($width) { $width=480; }
 9344:     unless ($height) { $height=400; }
 9345:     unless ($scrolling) { $scrolling='yes'; }
 9346:     unless ($transparency) { $transparency='true'; }
 9347: 
 9348:     my $target_attr;
 9349:     if (defined($target)) {
 9350:         $target_attr = 'target="'.$target.'"';
 9351:     }
 9352:     return <<"ENDLINK";
 9353: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9354: ENDLINK
 9355: }
 9356: 
 9357: sub modal_adhoc_script {
 9358:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9359:     my $mathjax;
 9360:     if ($possmathjax) {
 9361:         $mathjax = <<'ENDJAX';
 9362:                if (typeof MathJax == 'object') {
 9363:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 9364:                }
 9365: ENDJAX
 9366:     }
 9367:     return (<<ENDADHOC);
 9368: <script type="text/javascript">
 9369: // <![CDATA[
 9370:         var $funcname = function()
 9371:         {
 9372:                 modalWindow.windowId = "myModal";
 9373:                 modalWindow.width = $width;
 9374:                 modalWindow.height = $height;
 9375:                 modalWindow.content = '$content';
 9376:                 modalWindow.open();
 9377:                 $mathjax
 9378:         };  
 9379: // ]]>
 9380: </script>
 9381: ENDADHOC
 9382: }
 9383: 
 9384: sub modal_adhoc_inner {
 9385:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9386:     my $innerwidth=$width-20;
 9387:     $content=&js_ready(
 9388:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9389:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9390:                  $content.
 9391:                  &end_scrollbox().
 9392:                  &end_page()
 9393:              );
 9394:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 9395: }
 9396: 
 9397: sub modal_adhoc_window {
 9398:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 9399:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 9400:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9401: }
 9402: 
 9403: sub modal_adhoc_launch {
 9404:     my ($funcname,$width,$height,$content)=@_;
 9405:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9406: <script type="text/javascript">
 9407: // <![CDATA[
 9408: $funcname();
 9409: // ]]>
 9410: </script>
 9411: ENDLAUNCH
 9412: }
 9413: 
 9414: sub modal_adhoc_close {
 9415:     return (<<ENDCLOSE);
 9416: <script type="text/javascript">
 9417: // <![CDATA[
 9418: modalWindow.close();
 9419: // ]]>
 9420: </script>
 9421: ENDCLOSE
 9422: }
 9423: 
 9424: sub togglebox_script {
 9425:    return(<<ENDTOGGLE);
 9426: <script type="text/javascript"> 
 9427: // <![CDATA[
 9428: function LCtoggleDisplay(id,hidetext,showtext) {
 9429:    link = document.getElementById(id + "link").childNodes[0];
 9430:    with (document.getElementById(id).style) {
 9431:       if (display == "none" ) {
 9432:           display = "inline";
 9433:           link.nodeValue = hidetext;
 9434:         } else {
 9435:           display = "none";
 9436:           link.nodeValue = showtext;
 9437:        }
 9438:    }
 9439: }
 9440: // ]]>
 9441: </script>
 9442: ENDTOGGLE
 9443: }
 9444: 
 9445: sub start_togglebox {
 9446:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9447:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9448:     unless ($showtext) { $showtext=&mt('show'); }
 9449:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9450:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9451:     return &start_data_table().
 9452:            &start_data_table_header_row().
 9453:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9454:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9455:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9456:            &end_data_table_header_row().
 9457:            '<tr id="'.$id.'" style="display:none""><td>';
 9458: }
 9459: 
 9460: sub end_togglebox {
 9461:     return '</td></tr>'.&end_data_table();
 9462: }
 9463: 
 9464: sub LCprogressbar_script {
 9465:    my ($id,$number_to_do)=@_;
 9466:    if ($number_to_do) {
 9467:        return(<<ENDPROGRESS);
 9468: <script type="text/javascript">
 9469: // <![CDATA[
 9470: \$('#progressbar$id').progressbar({
 9471:   value: 0,
 9472:   change: function(event, ui) {
 9473:     var newVal = \$(this).progressbar('option', 'value');
 9474:     \$('.pblabel', this).text(LCprogressTxt);
 9475:   }
 9476: });
 9477: // ]]>
 9478: </script>
 9479: ENDPROGRESS
 9480:    } else {
 9481:        return(<<ENDPROGRESS);
 9482: <script type="text/javascript">
 9483: // <![CDATA[
 9484: \$('#progressbar$id').progressbar({
 9485:   value: false,
 9486:   create: function(event, ui) {
 9487:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9488:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9489:   }
 9490: });
 9491: // ]]>
 9492: </script>
 9493: ENDPROGRESS
 9494:    }
 9495: }
 9496: 
 9497: sub LCprogressbarUpdate_script {
 9498:    return(<<ENDPROGRESSUPDATE);
 9499: <style type="text/css">
 9500: .ui-progressbar { position:relative; }
 9501: .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%; }
 9502: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9503: </style>
 9504: <script type="text/javascript">
 9505: // <![CDATA[
 9506: var LCprogressTxt='---';
 9507: 
 9508: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9509:    LCprogressTxt=progresstext;
 9510:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9511:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9512:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9513:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9514:    } else {
 9515:        \$('#progressbar'+id).progressbar('value',percent);
 9516:    }
 9517: }
 9518: // ]]>
 9519: </script>
 9520: ENDPROGRESSUPDATE
 9521: }
 9522: 
 9523: my $LClastpercent;
 9524: my $LCidcnt;
 9525: my $LCcurrentid;
 9526: 
 9527: sub LCprogressbar {
 9528:     my ($r,$number_to_do,$preamble)=@_;
 9529:     $LClastpercent=0;
 9530:     $LCidcnt++;
 9531:     $LCcurrentid=$$.'_'.$LCidcnt;
 9532:     my ($starting,$content);
 9533:     if ($number_to_do) {
 9534:         $starting=&mt('Starting');
 9535:         $content=(<<ENDPROGBAR);
 9536: $preamble
 9537:   <div id="progressbar$LCcurrentid">
 9538:     <span class="pblabel">$starting</span>
 9539:   </div>
 9540: ENDPROGBAR
 9541:     } else {
 9542:         $starting=&mt('Loading...');
 9543:         $LClastpercent='false';
 9544:         $content=(<<ENDPROGBAR);
 9545: $preamble
 9546:   <div id="progressbar$LCcurrentid">
 9547:       <div class="progress-label">$starting</div>
 9548:   </div>
 9549: ENDPROGBAR
 9550:     }
 9551:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9552: }
 9553: 
 9554: sub LCprogressbarUpdate {
 9555:     my ($r,$val,$text,$number_to_do)=@_;
 9556:     if ($number_to_do) {
 9557:         unless ($val) { 
 9558:             if ($LClastpercent) {
 9559:                 $val=$LClastpercent;
 9560:             } else {
 9561:                 $val=0;
 9562:             }
 9563:         }
 9564:         if ($val<0) { $val=0; }
 9565:         if ($val>100) { $val=0; }
 9566:         $LClastpercent=$val;
 9567:         unless ($text) { $text=$val.'%'; }
 9568:     } else {
 9569:         $val = 'false';
 9570:     }
 9571:     $text=&js_ready($text);
 9572:     &r_print($r,<<ENDUPDATE);
 9573: <script type="text/javascript">
 9574: // <![CDATA[
 9575: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9576: // ]]>
 9577: </script>
 9578: ENDUPDATE
 9579: }
 9580: 
 9581: sub LCprogressbarClose {
 9582:     my ($r)=@_;
 9583:     $LClastpercent=0;
 9584:     &r_print($r,<<ENDCLOSE);
 9585: <script type="text/javascript">
 9586: // <![CDATA[
 9587: \$("#progressbar$LCcurrentid").hide('slow'); 
 9588: // ]]>
 9589: </script>
 9590: ENDCLOSE
 9591: }
 9592: 
 9593: sub r_print {
 9594:     my ($r,$to_print)=@_;
 9595:     if ($r) {
 9596:       $r->print($to_print);
 9597:       $r->rflush();
 9598:     } else {
 9599:       print($to_print);
 9600:     }
 9601: }
 9602: 
 9603: sub html_encode {
 9604:     my ($result) = @_;
 9605: 
 9606:     $result = &HTML::Entities::encode($result,'<>&"');
 9607:     
 9608:     return $result;
 9609: }
 9610: 
 9611: sub js_ready {
 9612:     my ($result) = @_;
 9613: 
 9614:     $result =~ s/[\n\r]/ /xmsg;
 9615:     $result =~ s/\\/\\\\/xmsg;
 9616:     $result =~ s/'/\\'/xmsg;
 9617:     $result =~ s{</}{<\\/}xmsg;
 9618:     
 9619:     return $result;
 9620: }
 9621: 
 9622: sub validate_page {
 9623:     if (  exists($env{'internal.start_page'})
 9624: 	  &&     $env{'internal.start_page'} > 1) {
 9625: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9626: 				 $env{'internal.start_page'}.' '.
 9627: 				 $ENV{'request.filename'});
 9628:     }
 9629:     if (  exists($env{'internal.end_page'})
 9630: 	  &&     $env{'internal.end_page'} > 1) {
 9631: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9632: 				 $env{'internal.end_page'}.' '.
 9633: 				 $env{'request.filename'});
 9634:     }
 9635:     if (     exists($env{'internal.start_page'})
 9636: 	&& ! exists($env{'internal.end_page'})) {
 9637: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9638: 				 $env{'request.filename'});
 9639:     }
 9640:     if (   ! exists($env{'internal.start_page'})
 9641: 	&&   exists($env{'internal.end_page'})) {
 9642: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9643: 				 $env{'request.filename'});
 9644:     }
 9645: }
 9646: 
 9647: 
 9648: sub start_scrollbox {
 9649:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9650:     unless ($outerwidth) { $outerwidth='520px'; }
 9651:     unless ($width) { $width='500px'; }
 9652:     unless ($height) { $height='200px'; }
 9653:     my ($table_id,$div_id,$tdcol);
 9654:     if ($id ne '') {
 9655:         $table_id = ' id="table_'.$id.'"';
 9656:         $div_id = ' id="div_'.$id.'"';
 9657:     }
 9658:     if ($bgcolor ne '') {
 9659:         $tdcol = "background-color: $bgcolor;";
 9660:     }
 9661:     my $nicescroll_js;
 9662:     if ($env{'browser.mobile'}) {
 9663:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9664:     }
 9665:     return <<"END";
 9666: $nicescroll_js
 9667: 
 9668: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9669: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9670: END
 9671: }
 9672: 
 9673: sub end_scrollbox {
 9674:     return '</div></td></tr></table>';
 9675: }
 9676: 
 9677: sub nicescroll_javascript {
 9678:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9679:     my %options;
 9680:     if (ref($cursor) eq 'HASH') {
 9681:         %options = %{$cursor};
 9682:     }
 9683:     unless ($options{'railalign'} =~ /^left|right$/) {
 9684:         $options{'railalign'} = 'left';
 9685:     }
 9686:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9687:         my $function  = &get_users_function();
 9688:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9689:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9690:             $options{'cursorcolor'} = '#00F';
 9691:         }
 9692:     }
 9693:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9694:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9695:             $options{'cursoropacity'}='1.0';
 9696:         }
 9697:     } else {
 9698:         $options{'cursoropacity'}='1.0';
 9699:     }
 9700:     if ($options{'cursorfixedheight'} eq 'none') {
 9701:         delete($options{'cursorfixedheight'});
 9702:     } else {
 9703:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9704:     }
 9705:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9706:         delete($options{'railoffset'});
 9707:     }
 9708:     my @niceoptions;
 9709:     while (my($key,$value) = each(%options)) {
 9710:         if ($value =~ /^\{.+\}$/) {
 9711:             push(@niceoptions,$key.':'.$value);
 9712:         } else {
 9713:             push(@niceoptions,$key.':"'.$value.'"');
 9714:         }
 9715:     }
 9716:     my $nicescroll_js = '
 9717: $(document).ready(
 9718:       function() {
 9719:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9720:       }
 9721: );
 9722: ';
 9723:     if ($framecheck) {
 9724:         $nicescroll_js .= '
 9725: function expand_div(caller) {
 9726:     if (top === self) {
 9727:         document.getElementById("'.$id.'").style.width = "auto";
 9728:         document.getElementById("'.$id.'").style.height = "auto";
 9729:     } else {
 9730:         try {
 9731:             if (parent.frames) {
 9732:                 if (parent.frames.length > 1) {
 9733:                     var framesrc = parent.frames[1].location.href;
 9734:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9735:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9736:                         document.getElementById("'.$id.'").style.width = "auto";
 9737:                         document.getElementById("'.$id.'").style.height = "auto";
 9738:                     }
 9739:                 }
 9740:             }
 9741:         } catch (e) {
 9742:             return;
 9743:         }
 9744:     }
 9745:     return;
 9746: }
 9747: ';
 9748:     }
 9749:     if ($needjsready) {
 9750:         $nicescroll_js = '
 9751: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9752:     } else {
 9753:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9754:     }
 9755:     return $nicescroll_js;
 9756: }
 9757: 
 9758: sub simple_error_page {
 9759:     my ($r,$title,$msg,$args) = @_;
 9760:     my %displayargs;
 9761:     if (ref($args) eq 'HASH') {
 9762:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9763:         if ($args->{'only_body'}) {
 9764:             $displayargs{'only_body'} = 1;
 9765:         }
 9766:         if ($args->{'no_nav_bar'}) {
 9767:             $displayargs{'no_nav_bar'} = 1;
 9768:         }
 9769:     } else {
 9770:         $msg = &mt($msg);
 9771:     }
 9772: 
 9773:     my $page =
 9774: 	&Apache::loncommon::start_page($title,'',\%displayargs).
 9775: 	'<p class="LC_error">'.$msg.'</p>'.
 9776: 	&Apache::loncommon::end_page();
 9777:     if (ref($r)) {
 9778: 	$r->print($page);
 9779: 	return;
 9780:     }
 9781:     return $page;
 9782: }
 9783: 
 9784: {
 9785:     my @row_count;
 9786: 
 9787:     sub start_data_table_count {
 9788:         unshift(@row_count, 0);
 9789:         return;
 9790:     }
 9791: 
 9792:     sub end_data_table_count {
 9793:         shift(@row_count);
 9794:         return;
 9795:     }
 9796: 
 9797:     sub start_data_table {
 9798: 	my ($add_class,$id) = @_;
 9799: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9800:         my $table_id;
 9801:         if (defined($id)) {
 9802:             $table_id = ' id="'.$id.'"';
 9803:         }
 9804: 	&start_data_table_count();
 9805: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9806:     }
 9807: 
 9808:     sub end_data_table {
 9809: 	&end_data_table_count();
 9810: 	return '</table>'."\n";;
 9811:     }
 9812: 
 9813:     sub start_data_table_row {
 9814: 	my ($add_class, $id) = @_;
 9815: 	$row_count[0]++;
 9816: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9817: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9818:         $id = (' id="'.$id.'"') unless ($id eq '');
 9819:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9820:     }
 9821:     
 9822:     sub continue_data_table_row {
 9823: 	my ($add_class, $id) = @_;
 9824: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9825: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9826:         $id = (' id="'.$id.'"') unless ($id eq '');
 9827:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9828:     }
 9829: 
 9830:     sub end_data_table_row {
 9831: 	return '</tr>'."\n";;
 9832:     }
 9833: 
 9834:     sub start_data_table_empty_row {
 9835: #	$row_count[0]++;
 9836: 	return  '<tr class="LC_empty_row" >'."\n";;
 9837:     }
 9838: 
 9839:     sub end_data_table_empty_row {
 9840: 	return '</tr>'."\n";;
 9841:     }
 9842: 
 9843:     sub start_data_table_header_row {
 9844: 	return  '<tr class="LC_header_row">'."\n";;
 9845:     }
 9846: 
 9847:     sub end_data_table_header_row {
 9848: 	return '</tr>'."\n";;
 9849:     }
 9850: 
 9851:     sub data_table_caption {
 9852:         my $caption = shift;
 9853:         return "<caption class=\"LC_caption\">$caption</caption>";
 9854:     }
 9855: }
 9856: 
 9857: =pod
 9858: 
 9859: =item * &inhibit_menu_check($arg)
 9860: 
 9861: Checks for a inhibitmenu state and generates output to preserve it
 9862: 
 9863: Inputs:         $arg - can be any of
 9864:                      - undef - in which case the return value is a string 
 9865:                                to add  into arguments list of a uri
 9866:                      - 'input' - in which case the return value is a HTML
 9867:                                  <form> <input> field of type hidden to
 9868:                                  preserve the value
 9869:                      - a url - in which case the return value is the url with
 9870:                                the neccesary cgi args added to preserve the
 9871:                                inhibitmenu state
 9872:                      - a ref to a url - no return value, but the string is
 9873:                                         updated to include the neccessary cgi
 9874:                                         args to preserve the inhibitmenu state
 9875: 
 9876: =cut
 9877: 
 9878: sub inhibit_menu_check {
 9879:     my ($arg) = @_;
 9880:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9881:     if ($arg eq 'input') {
 9882: 	if ($env{'form.inhibitmenu'}) {
 9883: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9884: 	} else {
 9885: 	    return
 9886: 	}
 9887:     }
 9888:     if ($env{'form.inhibitmenu'}) {
 9889: 	if (ref($arg)) {
 9890: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9891: 	} elsif ($arg eq '') {
 9892: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9893: 	} else {
 9894: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9895: 	}
 9896:     }
 9897:     if (!ref($arg)) {
 9898: 	return $arg;
 9899:     }
 9900: }
 9901: 
 9902: ###############################################
 9903: 
 9904: =pod
 9905: 
 9906: =back
 9907: 
 9908: =head1 User Information Routines
 9909: 
 9910: =over 4
 9911: 
 9912: =item * &get_users_function()
 9913: 
 9914: Used by &bodytag to determine the current users primary role.
 9915: Returns either 'student','coordinator','admin', or 'author'.
 9916: 
 9917: =cut
 9918: 
 9919: ###############################################
 9920: sub get_users_function {
 9921:     my $function = 'norole';
 9922:     if ($env{'request.role'}=~/^(st)/) {
 9923:         $function='student';
 9924:     }
 9925:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9926:         $function='coordinator';
 9927:     }
 9928:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9929:         $function='admin';
 9930:     }
 9931:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9932:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9933:         $function='author';
 9934:     }
 9935:     return $function;
 9936: }
 9937: 
 9938: ###############################################
 9939: 
 9940: =pod
 9941: 
 9942: =item * &show_course()
 9943: 
 9944: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9945: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9946: 
 9947: Inputs:
 9948: None
 9949: 
 9950: Outputs:
 9951: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9952: 
 9953: =cut
 9954: 
 9955: ###############################################
 9956: sub show_course {
 9957:     my $course = !$env{'user.adv'};
 9958:     if (!$env{'user.adv'}) {
 9959:         foreach my $env (keys(%env)) {
 9960:             next if ($env !~ m/^user\.priv\./);
 9961:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9962:                 $course = 0;
 9963:                 last;
 9964:             }
 9965:         }
 9966:     }
 9967:     return $course;
 9968: }
 9969: 
 9970: ###############################################
 9971: 
 9972: =pod
 9973: 
 9974: =item * &check_user_status()
 9975: 
 9976: Determines current status of supplied role for a
 9977: specific user. Roles can be active, previous or future.
 9978: 
 9979: Inputs: 
 9980: user's domain, user's username, course's domain,
 9981: course's number, optional section ID.
 9982: 
 9983: Outputs:
 9984: role status: active, previous or future. 
 9985: 
 9986: =cut
 9987: 
 9988: sub check_user_status {
 9989:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9990:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9991:     my @uroles = keys(%userinfo);
 9992:     my $srchstr;
 9993:     my $active_chk = 'none';
 9994:     my $now = time;
 9995:     if (@uroles > 0) {
 9996:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9997:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9998:         } else {
 9999:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10000:         }
10001:         if (grep/^\Q$srchstr\E$/,@uroles) {
10002:             my $role_end = 0;
10003:             my $role_start = 0;
10004:             $active_chk = 'active';
10005:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10006:                 $role_end = $1;
10007:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10008:                     $role_start = $1;
10009:                 }
10010:             }
10011:             if ($role_start > 0) {
10012:                 if ($now < $role_start) {
10013:                     $active_chk = 'future';
10014:                 }
10015:             }
10016:             if ($role_end > 0) {
10017:                 if ($now > $role_end) {
10018:                     $active_chk = 'previous';
10019:                 }
10020:             }
10021:         }
10022:     }
10023:     return $active_chk;
10024: }
10025: 
10026: ###############################################
10027: 
10028: =pod
10029: 
10030: =item * &get_sections()
10031: 
10032: Determines all the sections for a course including
10033: sections with students and sections containing other roles.
10034: Incoming parameters: 
10035: 
10036: 1. domain
10037: 2. course number 
10038: 3. reference to array containing roles for which sections should 
10039: be gathered (optional).
10040: 4. reference to array containing status types for which sections 
10041: should be gathered (optional).
10042: 
10043: If the third argument is undefined, sections are gathered for any role. 
10044: If the fourth argument is undefined, sections are gathered for any status.
10045: Permissible values are 'active' or 'future' or 'previous'.
10046:  
10047: Returns section hash (keys are section IDs, values are
10048: number of users in each section), subject to the
10049: optional roles filter, optional status filter 
10050: 
10051: =cut
10052: 
10053: ###############################################
10054: sub get_sections {
10055:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10056:     if (!defined($cdom) || !defined($cnum)) {
10057:         my $cid =  $env{'request.course.id'};
10058: 
10059: 	return if (!defined($cid));
10060: 
10061:         $cdom = $env{'course.'.$cid.'.domain'};
10062:         $cnum = $env{'course.'.$cid.'.num'};
10063:     }
10064: 
10065:     my %sectioncount;
10066:     my $now = time;
10067: 
10068:     my $check_students = 1;
10069:     my $only_students = 0;
10070:     if (ref($possible_roles) eq 'ARRAY') {
10071:         if (grep(/^st$/,@{$possible_roles})) {
10072:             if (@{$possible_roles} == 1) {
10073:                 $only_students = 1;
10074:             }
10075:         } else {
10076:             $check_students = 0;
10077:         }
10078:     }
10079: 
10080:     if ($check_students) {
10081: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10082: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
10083: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
10084:         my $start_index = &Apache::loncoursedata::CL_START();
10085:         my $end_index = &Apache::loncoursedata::CL_END();
10086:         my $status;
10087: 	while (my ($student,$data) = each(%$classlist)) {
10088: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10089: 				                     $data->[$status_index],
10090:                                                      $data->[$start_index],
10091:                                                      $data->[$end_index]);
10092:             if ($stu_status eq 'Active') {
10093:                 $status = 'active';
10094:             } elsif ($end < $now) {
10095:                 $status = 'previous';
10096:             } elsif ($start > $now) {
10097:                 $status = 'future';
10098:             } 
10099: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
10100:                 if ((!defined($possible_status)) || (($status ne '') && 
10101:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
10102: 		    $sectioncount{$section}++;
10103:                 }
10104: 	    }
10105: 	}
10106:     }
10107:     if ($only_students) {
10108:         return %sectioncount;
10109:     }
10110:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10111:     foreach my $user (sort(keys(%courseroles))) {
10112: 	if ($user !~ /^(\w{2})/) { next; }
10113: 	my ($role) = ($user =~ /^(\w{2})/);
10114: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10115: 	my ($section,$status);
10116: 	if ($role eq 'cr' &&
10117: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10118: 	    $section=$1;
10119: 	}
10120: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10121: 	if (!defined($section) || $section eq '-1') { next; }
10122:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10123:         if ($end == -1 && $start == -1) {
10124:             next; #deleted role
10125:         }
10126:         if (!defined($possible_status)) { 
10127:             $sectioncount{$section}++;
10128:         } else {
10129:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10130:                 $status = 'active';
10131:             } elsif ($end < $now) {
10132:                 $status = 'future';
10133:             } elsif ($start > $now) {
10134:                 $status = 'previous';
10135:             }
10136:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10137:                 $sectioncount{$section}++;
10138:             }
10139:         }
10140:     }
10141:     return %sectioncount;
10142: }
10143: 
10144: ###############################################
10145: 
10146: =pod
10147: 
10148: =item * &get_course_users()
10149: 
10150: Retrieves usernames:domains for users in the specified course
10151: with specific role(s), and access status. 
10152: 
10153: Incoming parameters:
10154: 1. course domain
10155: 2. course number
10156: 3. access status: users must have - either active, 
10157: previous, future, or all.
10158: 4. reference to array of permissible roles
10159: 5. reference to array of section restrictions (optional)
10160: 6. reference to results object (hash of hashes).
10161: 7. reference to optional userdata hash
10162: 8. reference to optional statushash
10163: 9. flag if privileged users (except those set to unhide in
10164:    course settings) should be excluded    
10165: Keys of top level results hash are roles.
10166: Keys of inner hashes are username:domain, with 
10167: values set to access type.
10168: Optional userdata hash returns an array with arguments in the 
10169: same order as loncoursedata::get_classlist() for student data.
10170: 
10171: Optional statushash returns
10172: 
10173: Entries for end, start, section and status are blank because
10174: of the possibility of multiple values for non-student roles.
10175: 
10176: =cut
10177: 
10178: ###############################################
10179: 
10180: sub get_course_users {
10181:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10182:     my %idx = ();
10183:     my %seclists;
10184: 
10185:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10186:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10187:     $idx{end} = &Apache::loncoursedata::CL_END();
10188:     $idx{start} = &Apache::loncoursedata::CL_START();
10189:     $idx{id} = &Apache::loncoursedata::CL_ID();
10190:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10191:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10192:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10193: 
10194:     if (grep(/^st$/,@{$roles})) {
10195:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10196:         my $now = time;
10197:         foreach my $student (keys(%{$classlist})) {
10198:             my $match = 0;
10199:             my $secmatch = 0;
10200:             my $section = $$classlist{$student}[$idx{section}];
10201:             my $status = $$classlist{$student}[$idx{status}];
10202:             if ($section eq '') {
10203:                 $section = 'none';
10204:             }
10205:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10206:                 if (grep(/^all$/,@{$sections})) {
10207:                     $secmatch = 1;
10208:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
10209:                     if (grep(/^none$/,@{$sections})) {
10210:                         $secmatch = 1;
10211:                     }
10212:                 } else {  
10213: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
10214: 		        $secmatch = 1;
10215:                     }
10216: 		}
10217:                 if (!$secmatch) {
10218:                     next;
10219:                 }
10220:             }
10221:             if (defined($$types{'active'})) {
10222:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10223:                     push(@{$$users{st}{$student}},'active');
10224:                     $match = 1;
10225:                 }
10226:             }
10227:             if (defined($$types{'previous'})) {
10228:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10229:                     push(@{$$users{st}{$student}},'previous');
10230:                     $match = 1;
10231:                 }
10232:             }
10233:             if (defined($$types{'future'})) {
10234:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10235:                     push(@{$$users{st}{$student}},'future');
10236:                     $match = 1;
10237:                 }
10238:             }
10239:             if ($match) {
10240:                 push(@{$seclists{$student}},$section);
10241:                 if (ref($userdata) eq 'HASH') {
10242:                     $$userdata{$student} = $$classlist{$student};
10243:                 }
10244:                 if (ref($statushash) eq 'HASH') {
10245:                     $statushash->{$student}{'st'}{$section} = $status;
10246:                 }
10247:             }
10248:         }
10249:     }
10250:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10251:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10252:         my $now = time;
10253:         my %displaystatus = ( previous => 'Expired',
10254:                               active   => 'Active',
10255:                               future   => 'Future',
10256:                             );
10257:         my (%nothide,@possdoms);
10258:         if ($hidepriv) {
10259:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10260:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10261:                 if ($user !~ /:/) {
10262:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10263:                 } else {
10264:                     $nothide{$user} = 1;
10265:                 }
10266:             }
10267:             my @possdoms = ($cdom);
10268:             if ($coursehash{'checkforpriv'}) {
10269:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10270:             }
10271:         }
10272:         foreach my $person (sort(keys(%coursepersonnel))) {
10273:             my $match = 0;
10274:             my $secmatch = 0;
10275:             my $status;
10276:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10277:             $user =~ s/:$//;
10278:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10279:             if ($end == -1 || $start == -1) {
10280:                 next;
10281:             }
10282:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10283:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10284:                 my ($uname,$udom) = split(/:/,$user);
10285:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10286:                     if (grep(/^all$/,@{$sections})) {
10287:                         $secmatch = 1;
10288:                     } elsif ($usec eq '') {
10289:                         if (grep(/^none$/,@{$sections})) {
10290:                             $secmatch = 1;
10291:                         }
10292:                     } else {
10293:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10294:                             $secmatch = 1;
10295:                         }
10296:                     }
10297:                     if (!$secmatch) {
10298:                         next;
10299:                     }
10300:                 }
10301:                 if ($usec eq '') {
10302:                     $usec = 'none';
10303:                 }
10304:                 if ($uname ne '' && $udom ne '') {
10305:                     if ($hidepriv) {
10306:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10307:                             (!$nothide{$uname.':'.$udom})) {
10308:                             next;
10309:                         }
10310:                     }
10311:                     if ($end > 0 && $end < $now) {
10312:                         $status = 'previous';
10313:                     } elsif ($start > $now) {
10314:                         $status = 'future';
10315:                     } else {
10316:                         $status = 'active';
10317:                     }
10318:                     foreach my $type (keys(%{$types})) { 
10319:                         if ($status eq $type) {
10320:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10321:                                 push(@{$$users{$role}{$user}},$type);
10322:                             }
10323:                             $match = 1;
10324:                         }
10325:                     }
10326:                     if (($match) && (ref($userdata) eq 'HASH')) {
10327:                         if (!exists($$userdata{$uname.':'.$udom})) {
10328: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10329:                         }
10330:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10331:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10332:                         }
10333:                         if (ref($statushash) eq 'HASH') {
10334:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10335:                         }
10336:                     }
10337:                 }
10338:             }
10339:         }
10340:         if (grep(/^ow$/,@{$roles})) {
10341:             if ((defined($cdom)) && (defined($cnum))) {
10342:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10343:                 if ( defined($csettings{'internal.courseowner'}) ) {
10344:                     my $owner = $csettings{'internal.courseowner'};
10345:                     next if ($owner eq '');
10346:                     my ($ownername,$ownerdom);
10347:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10348:                         $ownername = $1;
10349:                         $ownerdom = $2;
10350:                     } else {
10351:                         $ownername = $owner;
10352:                         $ownerdom = $cdom;
10353:                         $owner = $ownername.':'.$ownerdom;
10354:                     }
10355:                     @{$$users{'ow'}{$owner}} = 'any';
10356:                     if (defined($userdata) && 
10357: 			!exists($$userdata{$owner})) {
10358: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10359:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10360:                             push(@{$seclists{$owner}},'none');
10361:                         }
10362:                         if (ref($statushash) eq 'HASH') {
10363:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10364:                         }
10365: 		    }
10366:                 }
10367:             }
10368:         }
10369:         foreach my $user (keys(%seclists)) {
10370:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10371:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10372:         }
10373:     }
10374:     return;
10375: }
10376: 
10377: sub get_user_info {
10378:     my ($udom,$uname,$idx,$userdata) = @_;
10379:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10380: 	&plainname($uname,$udom,'lastname');
10381:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10382:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10383:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10384:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10385:     return;
10386: }
10387: 
10388: ###############################################
10389: 
10390: =pod
10391: 
10392: =item * &get_user_quota()
10393: 
10394: Retrieves quota assigned for storage of user files.
10395: Default is to report quota for portfolio files.
10396: 
10397: Incoming parameters:
10398: 1. user's username
10399: 2. user's domain
10400: 3. quota name - portfolio, author, or course
10401:    (if no quota name provided, defaults to portfolio).
10402: 4. crstype - official, unofficial, textbook or community, if quota name is
10403:    course
10404: 
10405: Returns:
10406: 1. Disk quota (in MB) assigned to student.
10407: 2. (Optional) Type of setting: custom or default
10408:    (individually assigned or default for user's 
10409:    institutional status).
10410: 3. (Optional) - User's institutional status (e.g., faculty, staff
10411:    or student - types as defined in localenroll::inst_usertypes 
10412:    for user's domain, which determines default quota for user.
10413: 4. (Optional) - Default quota which would apply to the user.
10414: 
10415: If a value has been stored in the user's environment, 
10416: it will return that, otherwise it returns the maximal default
10417: defined for the user's institutional status(es) in the domain.
10418: 
10419: =cut
10420: 
10421: ###############################################
10422: 
10423: 
10424: sub get_user_quota {
10425:     my ($uname,$udom,$quotaname,$crstype) = @_;
10426:     my ($quota,$quotatype,$settingstatus,$defquota);
10427:     if (!defined($udom)) {
10428:         $udom = $env{'user.domain'};
10429:     }
10430:     if (!defined($uname)) {
10431:         $uname = $env{'user.name'};
10432:     }
10433:     if (($udom eq '' || $uname eq '') ||
10434:         ($udom eq 'public') && ($uname eq 'public')) {
10435:         $quota = 0;
10436:         $quotatype = 'default';
10437:         $defquota = 0; 
10438:     } else {
10439:         my $inststatus;
10440:         if ($quotaname eq 'course') {
10441:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10442:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10443:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10444:             } else {
10445:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10446:                 $quota = $cenv{'internal.uploadquota'};
10447:             }
10448:         } else {
10449:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10450:                 if ($quotaname eq 'author') {
10451:                     $quota = $env{'environment.authorquota'};
10452:                 } else {
10453:                     $quota = $env{'environment.portfolioquota'};
10454:                 }
10455:                 $inststatus = $env{'environment.inststatus'};
10456:             } else {
10457:                 my %userenv = 
10458:                     &Apache::lonnet::get('environment',['portfolioquota',
10459:                                          'authorquota','inststatus'],$udom,$uname);
10460:                 my ($tmp) = keys(%userenv);
10461:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10462:                     if ($quotaname eq 'author') {
10463:                         $quota = $userenv{'authorquota'};
10464:                     } else {
10465:                         $quota = $userenv{'portfolioquota'};
10466:                     }
10467:                     $inststatus = $userenv{'inststatus'};
10468:                 } else {
10469:                     undef(%userenv);
10470:                 }
10471:             }
10472:         }
10473:         if ($quota eq '' || wantarray) {
10474:             if ($quotaname eq 'course') {
10475:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10476:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
10477:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
10478:                     $defquota = $domdefs{$crstype.'quota'};
10479:                 }
10480:                 if ($defquota eq '') {
10481:                     $defquota = 500;
10482:                 }
10483:             } else {
10484:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10485:             }
10486:             if ($quota eq '') {
10487:                 $quota = $defquota;
10488:                 $quotatype = 'default';
10489:             } else {
10490:                 $quotatype = 'custom';
10491:             }
10492:         }
10493:     }
10494:     if (wantarray) {
10495:         return ($quota,$quotatype,$settingstatus,$defquota);
10496:     } else {
10497:         return $quota;
10498:     }
10499: }
10500: 
10501: ###############################################
10502: 
10503: =pod
10504: 
10505: =item * &default_quota()
10506: 
10507: Retrieves default quota assigned for storage of user portfolio files,
10508: given an (optional) user's institutional status.
10509: 
10510: Incoming parameters:
10511: 
10512: 1. domain
10513: 2. (Optional) institutional status(es).  This is a : separated list of 
10514:    status types (e.g., faculty, staff, student etc.)
10515:    which apply to the user for whom the default is being retrieved.
10516:    If the institutional status string in undefined, the domain
10517:    default quota will be returned.
10518: 3.  quota name - portfolio, author, or course
10519:    (if no quota name provided, defaults to portfolio).
10520: 
10521: Returns:
10522: 
10523: 1. Default disk quota (in MB) for user portfolios in the domain.
10524: 2. (Optional) institutional type which determined the value of the
10525:    default quota.
10526: 
10527: If a value has been stored in the domain's configuration db,
10528: it will return that, otherwise it returns 20 (for backwards 
10529: compatibility with domains which have not set up a configuration
10530: db file; the original statically defined portfolio quota was 20 MB). 
10531: 
10532: If the user's status includes multiple types (e.g., staff and student),
10533: the largest default quota which applies to the user determines the
10534: default quota returned.
10535: 
10536: =cut
10537: 
10538: ###############################################
10539: 
10540: 
10541: sub default_quota {
10542:     my ($udom,$inststatus,$quotaname) = @_;
10543:     my ($defquota,$settingstatus);
10544:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10545:                                             ['quotas'],$udom);
10546:     my $key = 'defaultquota';
10547:     if ($quotaname eq 'author') {
10548:         $key = 'authorquota';
10549:     }
10550:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10551:         if ($inststatus ne '') {
10552:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10553:             foreach my $item (@statuses) {
10554:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10555:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10556:                         if ($defquota eq '') {
10557:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10558:                             $settingstatus = $item;
10559:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10560:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10561:                             $settingstatus = $item;
10562:                         }
10563:                     }
10564:                 } elsif ($key eq 'defaultquota') {
10565:                     if ($quotahash{'quotas'}{$item} ne '') {
10566:                         if ($defquota eq '') {
10567:                             $defquota = $quotahash{'quotas'}{$item};
10568:                             $settingstatus = $item;
10569:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10570:                             $defquota = $quotahash{'quotas'}{$item};
10571:                             $settingstatus = $item;
10572:                         }
10573:                     }
10574:                 }
10575:             }
10576:         }
10577:         if ($defquota eq '') {
10578:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10579:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10580:             } elsif ($key eq 'defaultquota') {
10581:                 $defquota = $quotahash{'quotas'}{'default'};
10582:             }
10583:             $settingstatus = 'default';
10584:             if ($defquota eq '') {
10585:                 if ($quotaname eq 'author') {
10586:                     $defquota = 500;
10587:                 }
10588:             }
10589:         }
10590:     } else {
10591:         $settingstatus = 'default';
10592:         if ($quotaname eq 'author') {
10593:             $defquota = 500;
10594:         } else {
10595:             $defquota = 20;
10596:         }
10597:     }
10598:     if (wantarray) {
10599:         return ($defquota,$settingstatus);
10600:     } else {
10601:         return $defquota;
10602:     }
10603: }
10604: 
10605: ###############################################
10606: 
10607: =pod
10608: 
10609: =item * &excess_filesize_warning()
10610: 
10611: Returns warning message if upload of file to authoring space, or copying
10612: of existing file within authoring space will cause quota for the authoring
10613: space to be exceeded.
10614: 
10615: Same, if upload of a file directly to a course/community via Course Editor
10616: will cause quota for uploaded content for the course to be exceeded.
10617: 
10618: Inputs: 7 
10619: 1. username or coursenum
10620: 2. domain
10621: 3. context ('author' or 'course')
10622: 4. filename of file for which action is being requested
10623: 5. filesize (kB) of file
10624: 6. action being taken: copy or upload.
10625: 7. quotatype (in course context -- official, unofficial, community or textbook).
10626: 
10627: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10628:          otherwise return null.
10629: 
10630: =back
10631: 
10632: =cut
10633: 
10634: sub excess_filesize_warning {
10635:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10636:     my $current_disk_usage = 0;
10637:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10638:     if ($context eq 'author') {
10639:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10640:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10641:     } else {
10642:         foreach my $subdir ('docs','supplemental') {
10643:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10644:         }
10645:     }
10646:     $disk_quota = int($disk_quota * 1000);
10647:     if (($current_disk_usage + $filesize) > $disk_quota) {
10648:         return '<p class="LC_warning">'.
10649:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10650:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10651:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10652:                             $disk_quota,$current_disk_usage).
10653:                '</p>';
10654:     }
10655:     return;
10656: }
10657: 
10658: ###############################################
10659: 
10660: 
10661: sub get_secgrprole_info {
10662:     my ($cdom,$cnum,$needroles,$type)  = @_;
10663:     my %sections_count = &get_sections($cdom,$cnum);
10664:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10665:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10666:     my @groups = sort(keys(%curr_groups));
10667:     my $allroles = [];
10668:     my $rolehash;
10669:     my $accesshash = {
10670:                      active => 'Currently has access',
10671:                      future => 'Will have future access',
10672:                      previous => 'Previously had access',
10673:                   };
10674:     if ($needroles) {
10675:         $rolehash = {'all' => 'all'};
10676:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10677: 	if (&Apache::lonnet::error(%user_roles)) {
10678: 	    undef(%user_roles);
10679: 	}
10680:         foreach my $item (keys(%user_roles)) {
10681:             my ($role)=split(/\:/,$item,2);
10682:             if ($role eq 'cr') { next; }
10683:             if ($role =~ /^cr/) {
10684:                 $$rolehash{$role} = (split('/',$role))[3];
10685:             } else {
10686:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10687:             }
10688:         }
10689:         foreach my $key (sort(keys(%{$rolehash}))) {
10690:             push(@{$allroles},$key);
10691:         }
10692:         push (@{$allroles},'st');
10693:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10694:     }
10695:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10696: }
10697: 
10698: sub user_picker {
10699:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10700:     my $currdom = $dom;
10701:     my @alldoms = &Apache::lonnet::all_domains();
10702:     if (@alldoms == 1) {
10703:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10704:                                                ['directorysrch'],$alldoms[0]);
10705:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10706:         my $showdom = $domdesc;
10707:         if ($showdom eq '') {
10708:             $showdom = $dom;
10709:         }
10710:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10711:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10712:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10713:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10714:             }
10715:         }
10716:     }
10717:     my %curr_selected = (
10718:                         srchin => 'dom',
10719:                         srchby => 'lastname',
10720:                       );
10721:     my $srchterm;
10722:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10723:         if ($srch->{'srchby'} ne '') {
10724:             $curr_selected{'srchby'} = $srch->{'srchby'};
10725:         }
10726:         if ($srch->{'srchin'} ne '') {
10727:             $curr_selected{'srchin'} = $srch->{'srchin'};
10728:         }
10729:         if ($srch->{'srchtype'} ne '') {
10730:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10731:         }
10732:         if ($srch->{'srchdomain'} ne '') {
10733:             $currdom = $srch->{'srchdomain'};
10734:         }
10735:         $srchterm = $srch->{'srchterm'};
10736:     }
10737:     my %html_lt=&Apache::lonlocal::texthash(
10738:                     'usr'       => 'Search criteria',
10739:                     'doma'      => 'Domain/institution to search',
10740:                     'uname'     => 'username',
10741:                     'lastname'  => 'last name',
10742:                     'lastfirst' => 'last name, first name',
10743:                     'crs'       => 'in this course',
10744:                     'dom'       => 'in selected LON-CAPA domain', 
10745:                     'alc'       => 'all LON-CAPA',
10746:                     'instd'     => 'in institutional directory for selected domain',
10747:                     'exact'     => 'is',
10748:                     'contains'  => 'contains',
10749:                     'begins'    => 'begins with',
10750:                                        );
10751:     my %js_lt=&Apache::lonlocal::texthash(
10752:                     'youm'      => "You must include some text to search for.",
10753:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10754:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10755:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10756:                     'ymcd'      => "You must choose a domain when using a domain search.",
10757:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10758:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10759:                      'thfo'     => "The following need to be corrected before the search can be run:",
10760:                                        );
10761:     &html_escape(\%html_lt);
10762:     &js_escape(\%js_lt);
10763:     my $domform;
10764:     my $allow_blank = 1;
10765:     if ($fixeddom) {
10766:         $allow_blank = 0;
10767:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10768:     } else {
10769:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
10770:     }
10771:     my $srchinsel = ' <select name="srchin">';
10772: 
10773:     my @srchins = ('crs','dom','alc','instd');
10774: 
10775:     foreach my $option (@srchins) {
10776:         # FIXME 'alc' option unavailable until 
10777:         #       loncreateuser::print_user_query_page()
10778:         #       has been completed.
10779:         next if ($option eq 'alc');
10780:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10781:         next if ($option eq 'crs' && !$env{'request.course.id'});
10782:         next if (($option eq 'instd') && ($noinstd));
10783:         if ($curr_selected{'srchin'} eq $option) {
10784:             $srchinsel .= ' 
10785:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10786:         } else {
10787:             $srchinsel .= '
10788:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10789:         }
10790:     }
10791:     $srchinsel .= "\n  </select>\n";
10792: 
10793:     my $srchbysel =  ' <select name="srchby">';
10794:     foreach my $option ('lastname','lastfirst','uname') {
10795:         if ($curr_selected{'srchby'} eq $option) {
10796:             $srchbysel .= '
10797:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10798:         } else {
10799:             $srchbysel .= '
10800:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10801:          }
10802:     }
10803:     $srchbysel .= "\n  </select>\n";
10804: 
10805:     my $srchtypesel = ' <select name="srchtype">';
10806:     foreach my $option ('begins','contains','exact') {
10807:         if ($curr_selected{'srchtype'} eq $option) {
10808:             $srchtypesel .= '
10809:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10810:         } else {
10811:             $srchtypesel .= '
10812:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10813:         }
10814:     }
10815:     $srchtypesel .= "\n  </select>\n";
10816: 
10817:     my ($newuserscript,$new_user_create);
10818:     my $context_dom = $env{'request.role.domain'};
10819:     if ($context eq 'requestcrs') {
10820:         if ($env{'form.coursedom'} ne '') { 
10821:             $context_dom = $env{'form.coursedom'};
10822:         }
10823:     }
10824:     if ($forcenewuser) {
10825:         if (ref($srch) eq 'HASH') {
10826:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10827:                 if ($cancreate) {
10828:                     $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>';
10829:                 } else {
10830:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10831:                     my %usertypetext = (
10832:                         official   => 'institutional',
10833:                         unofficial => 'non-institutional',
10834:                     );
10835:                     $new_user_create = '<p class="LC_warning">'
10836:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10837:                                       .' '
10838:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10839:                                           ,'<a href="'.$helplink.'">','</a>')
10840:                                       .'</p><br />';
10841:                 }
10842:             }
10843:         }
10844: 
10845:         $newuserscript = <<"ENDSCRIPT";
10846: 
10847: function setSearch(createnew,callingForm) {
10848:     if (createnew == 1) {
10849:         for (var i=0; i<callingForm.srchby.length; i++) {
10850:             if (callingForm.srchby.options[i].value == 'uname') {
10851:                 callingForm.srchby.selectedIndex = i;
10852:             }
10853:         }
10854:         for (var i=0; i<callingForm.srchin.length; i++) {
10855:             if ( callingForm.srchin.options[i].value == 'dom') {
10856: 		callingForm.srchin.selectedIndex = i;
10857:             }
10858:         }
10859:         for (var i=0; i<callingForm.srchtype.length; i++) {
10860:             if (callingForm.srchtype.options[i].value == 'exact') {
10861:                 callingForm.srchtype.selectedIndex = i;
10862:             }
10863:         }
10864:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10865:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10866:                 callingForm.srchdomain.selectedIndex = i;
10867:             }
10868:         }
10869:     }
10870: }
10871: ENDSCRIPT
10872: 
10873:     }
10874: 
10875:     my $output = <<"END_BLOCK";
10876: <script type="text/javascript">
10877: // <![CDATA[
10878: function validateEntry(callingForm) {
10879: 
10880:     var checkok = 1;
10881:     var srchin;
10882:     for (var i=0; i<callingForm.srchin.length; i++) {
10883: 	if ( callingForm.srchin[i].checked ) {
10884: 	    srchin = callingForm.srchin[i].value;
10885: 	}
10886:     }
10887: 
10888:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10889:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10890:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10891:     var srchterm =  callingForm.srchterm.value;
10892:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10893:     var msg = "";
10894: 
10895:     if (srchterm == "") {
10896:         checkok = 0;
10897:         msg += "$js_lt{'youm'}\\n";
10898:     }
10899: 
10900:     if (srchtype== 'begins') {
10901:         if (srchterm.length < 2) {
10902:             checkok = 0;
10903:             msg += "$js_lt{'thte'}\\n";
10904:         }
10905:     }
10906: 
10907:     if (srchtype== 'contains') {
10908:         if (srchterm.length < 3) {
10909:             checkok = 0;
10910:             msg += "$js_lt{'thet'}\\n";
10911:         }
10912:     }
10913:     if (srchin == 'instd') {
10914:         if (srchdomain == '') {
10915:             checkok = 0;
10916:             msg += "$js_lt{'yomc'}\\n";
10917:         }
10918:     }
10919:     if (srchin == 'dom') {
10920:         if (srchdomain == '') {
10921:             checkok = 0;
10922:             msg += "$js_lt{'ymcd'}\\n";
10923:         }
10924:     }
10925:     if (srchby == 'lastfirst') {
10926:         if (srchterm.indexOf(",") == -1) {
10927:             checkok = 0;
10928:             msg += "$js_lt{'whus'}\\n";
10929:         }
10930:         if (srchterm.indexOf(",") == srchterm.length -1) {
10931:             checkok = 0;
10932:             msg += "$js_lt{'whse'}\\n";
10933:         }
10934:     }
10935:     if (checkok == 0) {
10936:         alert("$js_lt{'thfo'}\\n"+msg);
10937:         return;
10938:     }
10939:     if (checkok == 1) {
10940:         callingForm.submit();
10941:     }
10942: }
10943: 
10944: $newuserscript
10945: 
10946: // ]]>
10947: </script>
10948: 
10949: $new_user_create
10950: 
10951: END_BLOCK
10952: 
10953:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10954:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10955:                $domform.
10956:                &Apache::lonhtmlcommon::row_closure().
10957:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10958:                $srchbysel.
10959:                $srchtypesel. 
10960:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10961:                $srchinsel.
10962:                &Apache::lonhtmlcommon::row_closure(1). 
10963:                &Apache::lonhtmlcommon::end_pick_box().
10964:                '<br />';
10965:     return ($output,1);
10966: }
10967: 
10968: sub user_rule_check {
10969:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10970:     my ($response,%inst_response);
10971:     if (ref($usershash) eq 'HASH') {
10972:         if (keys(%{$usershash}) > 1) {
10973:             my (%by_username,%by_id,%userdoms);
10974:             my $checkid;
10975:             if (ref($checks) eq 'HASH') {
10976:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10977:                     $checkid = 1;
10978:                 }
10979:             }
10980:             foreach my $user (keys(%{$usershash})) {
10981:                 my ($uname,$udom) = split(/:/,$user);
10982:                 if ($checkid) {
10983:                     if (ref($usershash->{$user}) eq 'HASH') {
10984:                         if ($usershash->{$user}->{'id'} ne '') {
10985:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10986:                             $userdoms{$udom} = 1;
10987:                             if (ref($inst_results) eq 'HASH') {
10988:                                 $inst_results->{$uname.':'.$udom} = {};
10989:                             }
10990:                         }
10991:                     }
10992:                 } else {
10993:                     $by_username{$udom}{$uname} = 1;
10994:                     $userdoms{$udom} = 1;
10995:                     if (ref($inst_results) eq 'HASH') {
10996:                         $inst_results->{$uname.':'.$udom} = {};
10997:                     }
10998:                 }
10999:             }
11000:             foreach my $udom (keys(%userdoms)) {
11001:                 if (!$got_rules->{$udom}) {
11002:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
11003:                                                              ['usercreation'],$udom);
11004:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11005:                         foreach my $item ('username','id') {
11006:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11007:                                 $$curr_rules{$udom}{$item} =
11008:                                     $domconfig{'usercreation'}{$item.'_rule'};
11009:                             }
11010:                         }
11011:                     }
11012:                     $got_rules->{$udom} = 1;
11013:                 }
11014:             }
11015:             if ($checkid) {
11016:                 foreach my $udom (keys(%by_id)) {
11017:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11018:                     if ($outcome eq 'ok') {
11019:                         foreach my $id (keys(%{$by_id{$udom}})) {
11020:                             my $uname = $by_id{$udom}{$id};
11021:                             $inst_response{$uname.':'.$udom} = $outcome;
11022:                         }
11023:                         if (ref($results) eq 'HASH') {
11024:                             foreach my $uname (keys(%{$results})) {
11025:                                 if (exists($inst_response{$uname.':'.$udom})) {
11026:                                     $inst_response{$uname.':'.$udom} = $outcome;
11027:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
11028:                                 }
11029:                             }
11030:                         }
11031:                     }
11032:                 }
11033:             } else {
11034:                 foreach my $udom (keys(%by_username)) {
11035:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11036:                     if ($outcome eq 'ok') {
11037:                         foreach my $uname (keys(%{$by_username{$udom}})) {
11038:                             $inst_response{$uname.':'.$udom} = $outcome;
11039:                         }
11040:                         if (ref($results) eq 'HASH') {
11041:                             foreach my $uname (keys(%{$results})) {
11042:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
11043:                             }
11044:                         }
11045:                     }
11046:                 }
11047:             }
11048:         } elsif (keys(%{$usershash}) == 1) {
11049:             my $user = (keys(%{$usershash}))[0];
11050:             my ($uname,$udom) = split(/:/,$user);
11051:             if (($udom ne '') && ($uname ne '')) {
11052:                 if (ref($usershash->{$user}) eq 'HASH') {
11053:                     if (ref($checks) eq 'HASH') {
11054:                         if (defined($checks->{'username'})) {
11055:                             ($inst_response{$user},%{$inst_results->{$user}}) =
11056:                                 &Apache::lonnet::get_instuser($udom,$uname);
11057:                         } elsif (defined($checks->{'id'})) {
11058:                             if ($usershash->{$user}->{'id'} ne '') {
11059:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11060:                                     &Apache::lonnet::get_instuser($udom,undef,
11061:                                                                   $usershash->{$user}->{'id'});
11062:                             } else {
11063:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11064:                                     &Apache::lonnet::get_instuser($udom,$uname);
11065:                             }
11066:                         }
11067:                     } else {
11068:                        ($inst_response{$user},%{$inst_results->{$user}}) =
11069:                             &Apache::lonnet::get_instuser($udom,$uname);
11070:                        return;
11071:                     }
11072:                     if (!$got_rules->{$udom}) {
11073:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
11074:                                                                  ['usercreation'],$udom);
11075:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
11076:                             foreach my $item ('username','id') {
11077:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11078:                                    $$curr_rules{$udom}{$item} =
11079:                                        $domconfig{'usercreation'}{$item.'_rule'};
11080:                                 }
11081:                             }
11082:                         }
11083:                         $got_rules->{$udom} = 1;
11084:                     }
11085:                 }
11086:             } else {
11087:                 return;
11088:             }
11089:         } else {
11090:             return;
11091:         }
11092:         foreach my $user (keys(%{$usershash})) {
11093:             my ($uname,$udom) = split(/:/,$user);
11094:             next if (($udom eq '') || ($uname eq ''));
11095:             my $id;
11096:             if (ref($inst_results) eq 'HASH') {
11097:                 if (ref($inst_results->{$user}) eq 'HASH') {
11098:                     $id = $inst_results->{$user}->{'id'};
11099:                 }
11100:             }
11101:             if ($id eq '') {
11102:                 if (ref($usershash->{$user})) {
11103:                     $id = $usershash->{$user}->{'id'};
11104:                 }
11105:             }
11106:             foreach my $item (keys(%{$checks})) {
11107:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
11108:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11109:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
11110:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11111:                                                                              $$curr_rules{$udom}{$item});
11112:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11113:                                 if ($rule_check{$rule}) {
11114:                                     $$rulematch{$user}{$item} = $rule;
11115:                                     if ($inst_response{$user} eq 'ok') {
11116:                                         if (ref($inst_results) eq 'HASH') {
11117:                                             if (ref($inst_results->{$user}) eq 'HASH') {
11118:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
11119:                                                     $$alerts{$item}{$udom}{$uname} = 1;
11120:                                                 } elsif ($item eq 'id') {
11121:                                                     if ($inst_results->{$user}->{'id'} eq '') {
11122:                                                         $$alerts{$item}{$udom}{$uname} = 1;
11123:                                                     }
11124:                                                 }
11125:                                             }
11126:                                         }
11127:                                     }
11128:                                     last;
11129:                                 }
11130:                             }
11131:                         }
11132:                     }
11133:                 }
11134:             }
11135:         }
11136:     }
11137:     return;
11138: }
11139: 
11140: sub user_rule_formats {
11141:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11142:     my %text = ( 
11143:                  'username' => 'Usernames',
11144:                  'id'       => 'IDs',
11145:                );
11146:     my $output;
11147:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11148:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11149:         if (@{$ruleorder} > 0) {
11150:             $output = '<br />'.
11151:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11152:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11153:                       ' <ul>';
11154:             foreach my $rule (@{$ruleorder}) {
11155:                 if (ref($curr_rules) eq 'ARRAY') {
11156:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11157:                         if (ref($rules->{$rule}) eq 'HASH') {
11158:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11159:                                         $rules->{$rule}{'desc'}.'</li>';
11160:                         }
11161:                     }
11162:                 }
11163:             }
11164:             $output .= '</ul>';
11165:         }
11166:     }
11167:     return $output;
11168: }
11169: 
11170: sub instrule_disallow_msg {
11171:     my ($checkitem,$domdesc,$count,$mode) = @_;
11172:     my $response;
11173:     my %text = (
11174:                   item   => 'username',
11175:                   items  => 'usernames',
11176:                   match  => 'matches',
11177:                   do     => 'does',
11178:                   action => 'a username',
11179:                   one    => 'one',
11180:                );
11181:     if ($count > 1) {
11182:         $text{'item'} = 'usernames';
11183:         $text{'match'} ='match';
11184:         $text{'do'} = 'do';
11185:         $text{'action'} = 'usernames',
11186:         $text{'one'} = 'ones';
11187:     }
11188:     if ($checkitem eq 'id') {
11189:         $text{'items'} = 'IDs';
11190:         $text{'item'} = 'ID';
11191:         $text{'action'} = 'an ID';
11192:         if ($count > 1) {
11193:             $text{'item'} = 'IDs';
11194:             $text{'action'} = 'IDs';
11195:         }
11196:     }
11197:     $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 />';
11198:     if ($mode eq 'upload') {
11199:         if ($checkitem eq 'username') {
11200:             $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'}.");
11201:         } elsif ($checkitem eq 'id') {
11202:             $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.");
11203:         }
11204:     } elsif ($mode eq 'selfcreate') {
11205:         if ($checkitem eq 'id') {
11206:             $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.");
11207:         }
11208:     } else {
11209:         if ($checkitem eq 'username') {
11210:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11211:         } elsif ($checkitem eq 'id') {
11212:             $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.");
11213:         }
11214:     }
11215:     return $response;
11216: }
11217: 
11218: sub personal_data_fieldtitles {
11219:     my %fieldtitles = &Apache::lonlocal::texthash (
11220:                         id => 'Student/Employee ID',
11221:                         permanentemail => 'E-mail address',
11222:                         lastname => 'Last Name',
11223:                         firstname => 'First Name',
11224:                         middlename => 'Middle Name',
11225:                         generation => 'Generation',
11226:                         gen => 'Generation',
11227:                         inststatus => 'Affiliation',
11228:                    );
11229:     return %fieldtitles;
11230: }
11231: 
11232: sub sorted_inst_types {
11233:     my ($dom) = @_;
11234:     my ($usertypes,$order);
11235:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11236:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11237:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11238:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11239:     } else {
11240:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11241:     }
11242:     my $othertitle = &mt('All users');
11243:     if ($env{'request.course.id'}) {
11244:         $othertitle  = &mt('Any users');
11245:     }
11246:     my @types;
11247:     if (ref($order) eq 'ARRAY') {
11248:         @types = @{$order};
11249:     }
11250:     if (@types == 0) {
11251:         if (ref($usertypes) eq 'HASH') {
11252:             @types = sort(keys(%{$usertypes}));
11253:         }
11254:     }
11255:     if (keys(%{$usertypes}) > 0) {
11256:         $othertitle = &mt('Other users');
11257:     }
11258:     return ($othertitle,$usertypes,\@types);
11259: }
11260: 
11261: sub get_institutional_codes {
11262:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11263: # Get complete list of course sections to update
11264:     my @currsections = ();
11265:     my @currxlists = ();
11266:     my (%unclutteredsec,%unclutteredlcsec);
11267:     my $coursecode = $$settings{'internal.coursecode'};
11268:     my $crskey = $crs.':'.$coursecode;
11269:     @{$unclutteredsec{$crskey}} = ();
11270:     @{$unclutteredlcsec{$crskey}} = ();
11271: 
11272:     if ($$settings{'internal.sectionnums'} ne '') {
11273:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11274:     }
11275: 
11276:     if ($$settings{'internal.crosslistings'} ne '') {
11277:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11278:     }
11279: 
11280:     if (@currxlists > 0) {
11281:         foreach my $xl (@currxlists) {
11282:             if ($xl =~ /^([^:]+):(\w*)$/) {
11283:                 unless (grep/^$1$/,@{$allcourses}) {
11284:                     push(@{$allcourses},$1);
11285:                     $$LC_code{$1} = $2;
11286:                 }
11287:             }
11288:         }
11289:     }
11290: 
11291:     if (@currsections > 0) {
11292:         foreach my $sec (@currsections) {
11293:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
11294:                 my $instsec = $1;
11295:                 my $lc_sec = $2;
11296:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11297:                     push(@{$unclutteredsec{$crskey}},$instsec);
11298:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11299:                 }
11300:             }
11301:         }
11302:     }
11303: 
11304:     if (@{$unclutteredsec{$crskey}} > 0) {
11305:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11306:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11307:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11308:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
11309:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11310:                     push(@{$allcourses},$sec);
11311:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11312:                 }
11313:             }
11314:         }
11315:     }
11316:     return;
11317: }
11318: 
11319: sub get_standard_codeitems {
11320:     return ('Year','Semester','Department','Number','Section');
11321: }
11322: 
11323: =pod
11324: 
11325: =head1 Slot Helpers
11326: 
11327: =over 4
11328: 
11329: =item * sorted_slots()
11330: 
11331: Sorts an array of slot names in order of an optional sort key,
11332: default sort is by slot start time (earliest first). 
11333: 
11334: Inputs:
11335: 
11336: =over 4
11337: 
11338: slotsarr  - Reference to array of unsorted slot names.
11339: 
11340: slots     - Reference to hash of hash, where outer hash keys are slot names.
11341: 
11342: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11343: 
11344: =back
11345: 
11346: Returns:
11347: 
11348: =over 4
11349: 
11350: sorted   - An array of slot names sorted by a specified sort key 
11351:            (default sort key is start time of the slot).
11352: 
11353: =back
11354: 
11355: =cut
11356: 
11357: 
11358: sub sorted_slots {
11359:     my ($slotsarr,$slots,$sortkey) = @_;
11360:     if ($sortkey eq '') {
11361:         $sortkey = 'starttime';
11362:     }
11363:     my @sorted;
11364:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11365:         @sorted =
11366:             sort {
11367:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11368:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11369:                      }
11370:                      if (ref($slots->{$a})) { return -1;}
11371:                      if (ref($slots->{$b})) { return 1;}
11372:                      return 0;
11373:                  } @{$slotsarr};
11374:     }
11375:     return @sorted;
11376: }
11377: 
11378: =pod
11379: 
11380: =item * get_future_slots()
11381: 
11382: Inputs:
11383: 
11384: =over 4
11385: 
11386: cnum - course number
11387: 
11388: cdom - course domain
11389: 
11390: now - current UNIX time
11391: 
11392: symb - optional symb
11393: 
11394: =back
11395: 
11396: Returns:
11397: 
11398: =over 4
11399: 
11400: sorted_reservable - ref to array of student_schedulable slots currently 
11401:                     reservable, ordered by end date of reservation period.
11402: 
11403: reservable_now - ref to hash of student_schedulable slots currently
11404:                  reservable.
11405: 
11406:     Keys in inner hash are:
11407:     (a) symb: either blank or symb to which slot use is restricted.
11408:     (b) endreserve: end date of reservation period.
11409:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11410:         selected.
11411: 
11412: sorted_future - ref to array of student_schedulable slots reservable in
11413:                 the future, ordered by start date of reservation period.
11414: 
11415: future_reservable - ref to hash of student_schedulable slots reservable
11416:                     in the future.
11417: 
11418:     Keys in inner hash are:
11419:     (a) symb: either blank or symb to which slot use is restricted.
11420:     (b) startreserve:  start date of reservation period.
11421:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11422:         selected.
11423: 
11424: =back
11425: 
11426: =cut
11427: 
11428: sub get_future_slots {
11429:     my ($cnum,$cdom,$now,$symb) = @_;
11430:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11431:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11432:     foreach my $slot (keys(%slots)) {
11433:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11434:         if ($symb) {
11435:             next if (($slots{$slot}->{'symb'} ne '') && 
11436:                      ($slots{$slot}->{'symb'} ne $symb));
11437:         }
11438:         if (($slots{$slot}->{'starttime'} > $now) &&
11439:             ($slots{$slot}->{'endtime'} > $now)) {
11440:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11441:                 my $userallowed = 0;
11442:                 if ($slots{$slot}->{'allowedsections'}) {
11443:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11444:                     if (!defined($env{'request.role.sec'})
11445:                         && grep(/^No section assigned$/,@allowed_sec)) {
11446:                         $userallowed=1;
11447:                     } else {
11448:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11449:                             $userallowed=1;
11450:                         }
11451:                     }
11452:                     unless ($userallowed) {
11453:                         if (defined($env{'request.course.groups'})) {
11454:                             my @groups = split(/:/,$env{'request.course.groups'});
11455:                             foreach my $group (@groups) {
11456:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11457:                                     $userallowed=1;
11458:                                     last;
11459:                                 }
11460:                             }
11461:                         }
11462:                     }
11463:                 }
11464:                 if ($slots{$slot}->{'allowedusers'}) {
11465:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11466:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11467:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11468:                         $userallowed = 1;
11469:                     }
11470:                 }
11471:                 next unless($userallowed);
11472:             }
11473:             my $startreserve = $slots{$slot}->{'startreserve'};
11474:             my $endreserve = $slots{$slot}->{'endreserve'};
11475:             my $symb = $slots{$slot}->{'symb'};
11476:             my $uniqueperiod;
11477:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11478:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11479:             }
11480:             if (($startreserve < $now) &&
11481:                 (!$endreserve || $endreserve > $now)) {
11482:                 my $lastres = $endreserve;
11483:                 if (!$lastres) {
11484:                     $lastres = $slots{$slot}->{'starttime'};
11485:                 }
11486:                 $reservable_now{$slot} = {
11487:                                            symb       => $symb,
11488:                                            endreserve => $lastres,
11489:                                            uniqueperiod => $uniqueperiod,   
11490:                                          };
11491:             } elsif (($startreserve > $now) &&
11492:                      (!$endreserve || $endreserve > $startreserve)) {
11493:                 $future_reservable{$slot} = {
11494:                                               symb         => $symb,
11495:                                               startreserve => $startreserve,
11496:                                               uniqueperiod => $uniqueperiod,
11497:                                             };
11498:             }
11499:         }
11500:     }
11501:     my @unsorted_reservable = keys(%reservable_now);
11502:     if (@unsorted_reservable > 0) {
11503:         @sorted_reservable = 
11504:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11505:     }
11506:     my @unsorted_future = keys(%future_reservable);
11507:     if (@unsorted_future > 0) {
11508:         @sorted_future =
11509:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11510:     }
11511:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11512: }
11513: 
11514: =pod
11515: 
11516: =back
11517: 
11518: =head1 HTTP Helpers
11519: 
11520: =over 4
11521: 
11522: =item * &get_unprocessed_cgi($query,$possible_names)
11523: 
11524: Modify the %env hash to contain unprocessed CGI form parameters held in
11525: $query.  The parameters listed in $possible_names (an array reference),
11526: will be set in $env{'form.name'} if they do not already exist.
11527: 
11528: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11529: $possible_names is an ref to an array of form element names.  As an example:
11530: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11531: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11532: 
11533: =cut
11534: 
11535: sub get_unprocessed_cgi {
11536:   my ($query,$possible_names)= @_;
11537:   # $Apache::lonxml::debug=1;
11538:   foreach my $pair (split(/&/,$query)) {
11539:     my ($name, $value) = split(/=/,$pair);
11540:     $name = &unescape($name);
11541:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11542:       $value =~ tr/+/ /;
11543:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11544:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11545:     }
11546:   }
11547: }
11548: 
11549: =pod
11550: 
11551: =item * &cacheheader() 
11552: 
11553: returns cache-controlling header code
11554: 
11555: =cut
11556: 
11557: sub cacheheader {
11558:     unless ($env{'request.method'} eq 'GET') { return ''; }
11559:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11560:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11561:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11562:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11563:     return $output;
11564: }
11565: 
11566: =pod
11567: 
11568: =item * &no_cache($r) 
11569: 
11570: specifies header code to not have cache
11571: 
11572: =cut
11573: 
11574: sub no_cache {
11575:     my ($r) = @_;
11576:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11577: 	$env{'request.method'} ne 'GET') { return ''; }
11578:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11579:     $r->no_cache(1);
11580:     $r->header_out("Expires" => $date);
11581:     $r->header_out("Pragma" => "no-cache");
11582: }
11583: 
11584: sub content_type {
11585:     my ($r,$type,$charset) = @_;
11586:     if ($r) {
11587: 	#  Note that printout.pl calls this with undef for $r.
11588: 	&no_cache($r);
11589:     }
11590:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11591:     unless ($charset) {
11592: 	$charset=&Apache::lonlocal::current_encoding;
11593:     }
11594:     if ($charset) { $type.='; charset='.$charset; }
11595:     if ($r) {
11596: 	$r->content_type($type);
11597:     } else {
11598: 	print("Content-type: $type\n\n");
11599:     }
11600: }
11601: 
11602: =pod
11603: 
11604: =item * &add_to_env($name,$value) 
11605: 
11606: adds $name to the %env hash with value
11607: $value, if $name already exists, the entry is converted to an array
11608: reference and $value is added to the array.
11609: 
11610: =cut
11611: 
11612: sub add_to_env {
11613:   my ($name,$value)=@_;
11614:   if (defined($env{$name})) {
11615:     if (ref($env{$name})) {
11616:       #already have multiple values
11617:       push(@{ $env{$name} },$value);
11618:     } else {
11619:       #first time seeing multiple values, convert hash entry to an arrayref
11620:       my $first=$env{$name};
11621:       undef($env{$name});
11622:       push(@{ $env{$name} },$first,$value);
11623:     }
11624:   } else {
11625:     $env{$name}=$value;
11626:   }
11627: }
11628: 
11629: =pod
11630: 
11631: =item * &get_env_multiple($name) 
11632: 
11633: gets $name from the %env hash, it seemlessly handles the cases where multiple
11634: values may be defined and end up as an array ref.
11635: 
11636: returns an array of values
11637: 
11638: =cut
11639: 
11640: sub get_env_multiple {
11641:     my ($name) = @_;
11642:     my @values;
11643:     if (defined($env{$name})) {
11644:         # exists is it an array
11645:         if (ref($env{$name})) {
11646:             @values=@{ $env{$name} };
11647:         } else {
11648:             $values[0]=$env{$name};
11649:         }
11650:     }
11651:     return(@values);
11652: }
11653: 
11654: sub ask_for_embedded_content {
11655:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11656:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11657:         %currsubfile,%unused,$rem);
11658:     my $counter = 0;
11659:     my $numnew = 0;
11660:     my $numremref = 0;
11661:     my $numinvalid = 0;
11662:     my $numpathchg = 0;
11663:     my $numexisting = 0;
11664:     my $numunused = 0;
11665:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11666:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11667:     my $heading = &mt('Upload embedded files');
11668:     my $buttontext = &mt('Upload');
11669: 
11670:     if ($env{'request.course.id'}) {
11671:         if ($actionurl eq '/adm/dependencies') {
11672:             $navmap = Apache::lonnavmaps::navmap->new();
11673:         }
11674:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11675:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11676:     }
11677:     if (($actionurl eq '/adm/portfolio') ||
11678:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11679:         my $current_path='/';
11680:         if ($env{'form.currentpath'}) {
11681:             $current_path = $env{'form.currentpath'};
11682:         }
11683:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11684:             $udom = $cdom;
11685:             $uname = $cnum;
11686:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11687:         } else {
11688:             $udom = $env{'user.domain'};
11689:             $uname = $env{'user.name'};
11690:             $url = '/userfiles/portfolio';
11691:         }
11692:         $toplevel = $url.'/';
11693:         $url .= $current_path;
11694:         $getpropath = 1;
11695:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11696:              ($actionurl eq '/adm/imsimport')) { 
11697:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11698:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11699:         $toplevel = $url;
11700:         if ($rest ne '') {
11701:             $url .= $rest;
11702:         }
11703:     } elsif ($actionurl eq '/adm/coursedocs') {
11704:         if (ref($args) eq 'HASH') {
11705:             $url = $args->{'docs_url'};
11706:             $toplevel = $url;
11707:             if ($args->{'context'} eq 'paste') {
11708:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11709:                 ($path) =
11710:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11711:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11712:                 $fileloc =~ s{^/}{};
11713:             }
11714:         }
11715:     } elsif ($actionurl eq '/adm/dependencies') {
11716:         if ($env{'request.course.id'} ne '') {
11717:             if (ref($args) eq 'HASH') {
11718:                 $url = $args->{'docs_url'};
11719:                 $title = $args->{'docs_title'};
11720:                 $toplevel = $url;
11721:                 unless ($toplevel =~ m{^/}) {
11722:                     $toplevel = "/$url";
11723:                 }
11724:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11725:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11726:                     $path = $1;
11727:                 } else {
11728:                     ($path) =
11729:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11730:                 }
11731:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11732:                     $fileloc = $toplevel;
11733:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11734:                     my ($udom,$uname,$fname) =
11735:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11736:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11737:                 } else {
11738:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11739:                 }
11740:                 $fileloc =~ s{^/}{};
11741:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11742:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11743:             }
11744:         }
11745:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11746:         $udom = $cdom;
11747:         $uname = $cnum;
11748:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11749:         $toplevel = $url;
11750:         $path = $url;
11751:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11752:         $fileloc =~ s{^/}{};
11753:     }
11754:     foreach my $file (keys(%{$allfiles})) {
11755:         my $embed_file;
11756:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11757:             $embed_file = $1;
11758:         } else {
11759:             $embed_file = $file;
11760:         }
11761:         my ($absolutepath,$cleaned_file);
11762:         if ($embed_file =~ m{^\w+://}) {
11763:             $cleaned_file = $embed_file;
11764:             $newfiles{$cleaned_file} = 1;
11765:             $mapping{$cleaned_file} = $embed_file;
11766:         } else {
11767:             $cleaned_file = &clean_path($embed_file);
11768:             if ($embed_file =~ m{^/}) {
11769:                 $absolutepath = $embed_file;
11770:             }
11771:             if ($cleaned_file =~ m{/}) {
11772:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11773:                 $path = &check_for_traversal($path,$url,$toplevel);
11774:                 my $item = $fname;
11775:                 if ($path ne '') {
11776:                     $item = $path.'/'.$fname;
11777:                     $subdependencies{$path}{$fname} = 1;
11778:                 } else {
11779:                     $dependencies{$item} = 1;
11780:                 }
11781:                 if ($absolutepath) {
11782:                     $mapping{$item} = $absolutepath;
11783:                 } else {
11784:                     $mapping{$item} = $embed_file;
11785:                 }
11786:             } else {
11787:                 $dependencies{$embed_file} = 1;
11788:                 if ($absolutepath) {
11789:                     $mapping{$cleaned_file} = $absolutepath;
11790:                 } else {
11791:                     $mapping{$cleaned_file} = $embed_file;
11792:                 }
11793:             }
11794:         }
11795:     }
11796:     my $dirptr = 16384;
11797:     foreach my $path (keys(%subdependencies)) {
11798:         $currsubfile{$path} = {};
11799:         if (($actionurl eq '/adm/portfolio') ||
11800:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
11801:             my ($sublistref,$listerror) =
11802:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11803:             if (ref($sublistref) eq 'ARRAY') {
11804:                 foreach my $line (@{$sublistref}) {
11805:                     my ($file_name,$rest) = split(/\&/,$line,2);
11806:                     $currsubfile{$path}{$file_name} = 1;
11807:                 }
11808:             }
11809:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11810:             if (opendir(my $dir,$url.'/'.$path)) {
11811:                 my @subdir_list = grep(!/^\./,readdir($dir));
11812:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11813:             }
11814:         } elsif (($actionurl eq '/adm/dependencies') ||
11815:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11816:                   ($args->{'context'} eq 'paste')) ||
11817:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11818:             if ($env{'request.course.id'} ne '') {
11819:                 my $dir;
11820:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11821:                     $dir = $fileloc;
11822:                 } else {
11823:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11824:                 }
11825:                 if ($dir ne '') {
11826:                     my ($sublistref,$listerror) =
11827:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11828:                     if (ref($sublistref) eq 'ARRAY') {
11829:                         foreach my $line (@{$sublistref}) {
11830:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11831:                                 undef,$mtime)=split(/\&/,$line,12);
11832:                             unless (($testdir&$dirptr) ||
11833:                                     ($file_name =~ /^\.\.?$/)) {
11834:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11835:                             }
11836:                         }
11837:                     }
11838:                 }
11839:             }
11840:         }
11841:         foreach my $file (keys(%{$subdependencies{$path}})) {
11842:             if (exists($currsubfile{$path}{$file})) {
11843:                 my $item = $path.'/'.$file;
11844:                 unless ($mapping{$item} eq $item) {
11845:                     $pathchanges{$item} = 1;
11846:                 }
11847:                 $existing{$item} = 1;
11848:                 $numexisting ++;
11849:             } else {
11850:                 $newfiles{$path.'/'.$file} = 1;
11851:             }
11852:         }
11853:         if ($actionurl eq '/adm/dependencies') {
11854:             foreach my $path (keys(%currsubfile)) {
11855:                 if (ref($currsubfile{$path}) eq 'HASH') {
11856:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11857:                          unless ($subdependencies{$path}{$file}) {
11858:                              next if (($rem ne '') &&
11859:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11860:                                        (ref($navmap) &&
11861:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11862:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11863:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11864:                              $unused{$path.'/'.$file} = 1; 
11865:                          }
11866:                     }
11867:                 }
11868:             }
11869:         }
11870:     }
11871:     my %currfile;
11872:     if (($actionurl eq '/adm/portfolio') ||
11873:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11874:         my ($dirlistref,$listerror) =
11875:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11876:         if (ref($dirlistref) eq 'ARRAY') {
11877:             foreach my $line (@{$dirlistref}) {
11878:                 my ($file_name,$rest) = split(/\&/,$line,2);
11879:                 $currfile{$file_name} = 1;
11880:             }
11881:         }
11882:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11883:         if (opendir(my $dir,$url)) {
11884:             my @dir_list = grep(!/^\./,readdir($dir));
11885:             map {$currfile{$_} = 1;} @dir_list;
11886:         }
11887:     } elsif (($actionurl eq '/adm/dependencies') ||
11888:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11889:               ($args->{'context'} eq 'paste')) ||
11890:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11891:         if ($env{'request.course.id'} ne '') {
11892:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11893:             if ($dir ne '') {
11894:                 my ($dirlistref,$listerror) =
11895:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11896:                 if (ref($dirlistref) eq 'ARRAY') {
11897:                     foreach my $line (@{$dirlistref}) {
11898:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11899:                             $size,undef,$mtime)=split(/\&/,$line,12);
11900:                         unless (($testdir&$dirptr) ||
11901:                                 ($file_name =~ /^\.\.?$/)) {
11902:                             $currfile{$file_name} = [$size,$mtime];
11903:                         }
11904:                     }
11905:                 }
11906:             }
11907:         }
11908:     }
11909:     foreach my $file (keys(%dependencies)) {
11910:         if (exists($currfile{$file})) {
11911:             unless ($mapping{$file} eq $file) {
11912:                 $pathchanges{$file} = 1;
11913:             }
11914:             $existing{$file} = 1;
11915:             $numexisting ++;
11916:         } else {
11917:             $newfiles{$file} = 1;
11918:         }
11919:     }
11920:     foreach my $file (keys(%currfile)) {
11921:         unless (($file eq $filename) ||
11922:                 ($file eq $filename.'.bak') ||
11923:                 ($dependencies{$file})) {
11924:             if ($actionurl eq '/adm/dependencies') {
11925:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11926:                     next if (($rem ne '') &&
11927:                              (($env{"httpref.$rem".$file} ne '') ||
11928:                               (ref($navmap) &&
11929:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11930:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11931:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11932:                 }
11933:             }
11934:             $unused{$file} = 1;
11935:         }
11936:     }
11937:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11938:         ($args->{'context'} eq 'paste')) {
11939:         $counter = scalar(keys(%existing));
11940:         $numpathchg = scalar(keys(%pathchanges));
11941:         return ($output,$counter,$numpathchg,\%existing);
11942:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
11943:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11944:         $counter = scalar(keys(%existing));
11945:         $numpathchg = scalar(keys(%pathchanges));
11946:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11947:     }
11948:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11949:         if ($actionurl eq '/adm/dependencies') {
11950:             next if ($embed_file =~ m{^\w+://});
11951:         }
11952:         $upload_output .= &start_data_table_row().
11953:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11954:                           '<span class="LC_filename">'.$embed_file.'</span>';
11955:         unless ($mapping{$embed_file} eq $embed_file) {
11956:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11957:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11958:         }
11959:         $upload_output .= '</td>';
11960:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11961:             $upload_output.='<td align="right">'.
11962:                             '<span class="LC_info LC_fontsize_medium">'.
11963:                             &mt("URL points to web address").'</span>';
11964:             $numremref++;
11965:         } elsif ($args->{'error_on_invalid_names'}
11966:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11967:             $upload_output.='<td align="right"><span class="LC_warning">'.
11968:                             &mt('Invalid characters').'</span>';
11969:             $numinvalid++;
11970:         } else {
11971:             $upload_output .= '<td>'.
11972:                               &embedded_file_element('upload_embedded',$counter,
11973:                                                      $embed_file,\%mapping,
11974:                                                      $allfiles,$codebase,'upload');
11975:             $counter ++;
11976:             $numnew ++;
11977:         }
11978:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11979:     }
11980:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11981:         if ($actionurl eq '/adm/dependencies') {
11982:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11983:             $modify_output .= &start_data_table_row().
11984:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11985:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11986:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11987:                               '<td>'.$size.'</td>'.
11988:                               '<td>'.$mtime.'</td>'.
11989:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11990:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11991:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11992:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11993:                               &embedded_file_element('upload_embedded',$counter,
11994:                                                      $embed_file,\%mapping,
11995:                                                      $allfiles,$codebase,'modify').
11996:                               '</div></td>'.
11997:                               &end_data_table_row()."\n";
11998:             $counter ++;
11999:         } else {
12000:             $upload_output .= &start_data_table_row().
12001:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12002:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
12003:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12004:                               &Apache::loncommon::end_data_table_row()."\n";
12005:         }
12006:     }
12007:     my $delidx = $counter;
12008:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12009:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12010:         $delete_output .= &start_data_table_row().
12011:                           '<td><img src="'.&icon($oldfile).'" />'.
12012:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
12013:                           '<td>'.$size.'</td>'.
12014:                           '<td>'.$mtime.'</td>'.
12015:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
12016:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12017:                           &embedded_file_element('upload_embedded',$delidx,
12018:                                                  $oldfile,\%mapping,$allfiles,
12019:                                                  $codebase,'delete').'</td>'.
12020:                           &end_data_table_row()."\n"; 
12021:         $numunused ++;
12022:         $delidx ++;
12023:     }
12024:     if ($upload_output) {
12025:         $upload_output = &start_data_table().
12026:                          $upload_output.
12027:                          &end_data_table()."\n";
12028:     }
12029:     if ($modify_output) {
12030:         $modify_output = &start_data_table().
12031:                          &start_data_table_header_row().
12032:                          '<th>'.&mt('File').'</th>'.
12033:                          '<th>'.&mt('Size (KB)').'</th>'.
12034:                          '<th>'.&mt('Modified').'</th>'.
12035:                          '<th>'.&mt('Upload replacement?').'</th>'.
12036:                          &end_data_table_header_row().
12037:                          $modify_output.
12038:                          &end_data_table()."\n";
12039:     }
12040:     if ($delete_output) {
12041:         $delete_output = &start_data_table().
12042:                          &start_data_table_header_row().
12043:                          '<th>'.&mt('File').'</th>'.
12044:                          '<th>'.&mt('Size (KB)').'</th>'.
12045:                          '<th>'.&mt('Modified').'</th>'.
12046:                          '<th>'.&mt('Delete?').'</th>'.
12047:                          &end_data_table_header_row().
12048:                          $delete_output.
12049:                          &end_data_table()."\n";
12050:     }
12051:     my $applies = 0;
12052:     if ($numremref) {
12053:         $applies ++;
12054:     }
12055:     if ($numinvalid) {
12056:         $applies ++;
12057:     }
12058:     if ($numexisting) {
12059:         $applies ++;
12060:     }
12061:     if ($counter || $numunused) {
12062:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12063:                   ' method="post" enctype="multipart/form-data">'."\n".
12064:                   $state.'<h3>'.$heading.'</h3>'; 
12065:         if ($actionurl eq '/adm/dependencies') {
12066:             if ($numnew) {
12067:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12068:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12069:                            $upload_output.'<br />'."\n";
12070:             }
12071:             if ($numexisting) {
12072:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12073:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12074:                            $modify_output.'<br />'."\n";
12075:                            $buttontext = &mt('Save changes');
12076:             }
12077:             if ($numunused) {
12078:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
12079:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12080:                            $delete_output.'<br />'."\n";
12081:                            $buttontext = &mt('Save changes');
12082:             }
12083:         } else {
12084:             $output .= $upload_output.'<br />'."\n";
12085:         }
12086:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12087:                    $counter.'" />'."\n";
12088:         if ($actionurl eq '/adm/dependencies') { 
12089:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12090:                        $numnew.'" />'."\n";
12091:         } elsif ($actionurl eq '') {
12092:             $output .=  '<input type="hidden" name="phase" value="three" />';
12093:         }
12094:     } elsif ($applies) {
12095:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12096:         if ($applies > 1) {
12097:             $output .=  
12098:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12099:             if ($numremref) {
12100:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12101:             }
12102:             if ($numinvalid) {
12103:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12104:             }
12105:             if ($numexisting) {
12106:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12107:             }
12108:             $output .= '</ul><br />';
12109:         } elsif ($numremref) {
12110:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12111:         } elsif ($numinvalid) {
12112:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12113:         } elsif ($numexisting) {
12114:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12115:         }
12116:         $output .= $upload_output.'<br />';
12117:     }
12118:     my ($pathchange_output,$chgcount);
12119:     $chgcount = $counter;
12120:     if (keys(%pathchanges) > 0) {
12121:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12122:             if ($counter) {
12123:                 $output .= &embedded_file_element('pathchange',$chgcount,
12124:                                                   $embed_file,\%mapping,
12125:                                                   $allfiles,$codebase,'change');
12126:             } else {
12127:                 $pathchange_output .= 
12128:                     &start_data_table_row().
12129:                     '<td><input type ="checkbox" name="namechange" value="'.
12130:                     $chgcount.'" checked="checked" /></td>'.
12131:                     '<td>'.$mapping{$embed_file}.'</td>'.
12132:                     '<td>'.$embed_file.
12133:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
12134:                                            \%mapping,$allfiles,$codebase,'change').
12135:                     '</td>'.&end_data_table_row();
12136:             }
12137:             $numpathchg ++;
12138:             $chgcount ++;
12139:         }
12140:     }
12141:     if (($counter) || ($numunused)) {
12142:         if ($numpathchg) {
12143:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12144:                        $numpathchg.'" />'."\n";
12145:         }
12146:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
12147:             ($actionurl eq '/adm/imsimport')) {
12148:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12149:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12150:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12151:         } elsif ($actionurl eq '/adm/dependencies') {
12152:             $output .= '<input type="hidden" name="action" value="process_changes" />';
12153:         }
12154:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12155:     } elsif ($numpathchg) {
12156:         my %pathchange = ();
12157:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12158:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12159:             $output .= '<p>'.&mt('or').'</p>'; 
12160:         }
12161:     }
12162:     return ($output,$counter,$numpathchg);
12163: }
12164: 
12165: =pod
12166: 
12167: =item * clean_path($name)
12168: 
12169: Performs clean-up of directories, subdirectories and filename in an
12170: embedded object, referenced in an HTML file which is being uploaded
12171: to a course or portfolio, where
12172: "Upload embedded images/multimedia files if HTML file" checkbox was
12173: checked.
12174: 
12175: Clean-up is similar to replacements in lonnet::clean_filename()
12176: except each / between sub-directory and next level is preserved.
12177: 
12178: =cut
12179: 
12180: sub clean_path {
12181:     my ($embed_file) = @_;
12182:     $embed_file =~s{^/+}{};
12183:     my @contents;
12184:     if ($embed_file =~ m{/}) {
12185:         @contents = split(/\//,$embed_file);
12186:     } else {
12187:         @contents = ($embed_file);
12188:     }
12189:     my $lastidx = scalar(@contents)-1;
12190:     for (my $i=0; $i<=$lastidx; $i++) {
12191:         $contents[$i]=~s{\\}{/}g;
12192:         $contents[$i]=~s/\s+/\_/g;
12193:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12194:         if ($i == $lastidx) {
12195:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12196:         }
12197:     }
12198:     if ($lastidx > 0) {
12199:         return join('/',@contents);
12200:     } else {
12201:         return $contents[0];
12202:     }
12203: }
12204: 
12205: sub embedded_file_element {
12206:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12207:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12208:                    (ref($codebase) eq 'HASH'));
12209:     my $output;
12210:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12211:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12212:     }
12213:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12214:                &escape($embed_file).'" />';
12215:     unless (($context eq 'upload_embedded') && 
12216:             ($mapping->{$embed_file} eq $embed_file)) {
12217:         $output .='
12218:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12219:     }
12220:     my $attrib;
12221:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12222:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12223:     }
12224:     $output .=
12225:         "\n\t\t".
12226:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12227:         $attrib.'" />';
12228:     if (exists($codebase->{$mapping->{$embed_file}})) {
12229:         $output .=
12230:             "\n\t\t".
12231:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12232:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12233:     }
12234:     return $output;
12235: }
12236: 
12237: sub get_dependency_details {
12238:     my ($currfile,$currsubfile,$embed_file) = @_;
12239:     my ($size,$mtime,$showsize,$showmtime);
12240:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12241:         if ($embed_file =~ m{/}) {
12242:             my ($path,$fname) = split(/\//,$embed_file);
12243:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12244:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12245:             }
12246:         } else {
12247:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12248:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12249:             }
12250:         }
12251:         $showsize = $size/1024.0;
12252:         $showsize = sprintf("%.1f",$showsize);
12253:         if ($mtime > 0) {
12254:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12255:         }
12256:     }
12257:     return ($showsize,$showmtime);
12258: }
12259: 
12260: sub ask_embedded_js {
12261:     return <<"END";
12262: <script type="text/javascript"">
12263: // <![CDATA[
12264: function toggleBrowse(counter) {
12265:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12266:     var fileid = document.getElementById('embedded_item_'+counter);
12267:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12268:     if (chkboxid.checked == true) {
12269:         uploaddivid.style.display='block';
12270:     } else {
12271:         uploaddivid.style.display='none';
12272:         fileid.value = '';
12273:     }
12274: }
12275: // ]]>
12276: </script>
12277: 
12278: END
12279: }
12280: 
12281: sub upload_embedded {
12282:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12283:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12284:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12285:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12286:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12287:         my $orig_uploaded_filename =
12288:             $env{'form.embedded_item_'.$i.'.filename'};
12289:         foreach my $type ('orig','ref','attrib','codebase') {
12290:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12291:                 $env{'form.embedded_'.$type.'_'.$i} =
12292:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12293:             }
12294:         }
12295:         my ($path,$fname) =
12296:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12297:         # no path, whole string is fname
12298:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12299:         $fname = &Apache::lonnet::clean_filename($fname);
12300:         # See if there is anything left
12301:         next if ($fname eq '');
12302: 
12303:         # Check if file already exists as a file or directory.
12304:         my ($state,$msg);
12305:         if ($context eq 'portfolio') {
12306:             my $port_path = $dirpath;
12307:             if ($group ne '') {
12308:                 $port_path = "groups/$group/$port_path";
12309:             }
12310:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12311:                                               $fname,$group,'embedded_item_'.$i,
12312:                                               $dir_root,$port_path,$disk_quota,
12313:                                               $current_disk_usage,$uname,$udom);
12314:             if ($state eq 'will_exceed_quota'
12315:                 || $state eq 'file_locked') {
12316:                 $output .= $msg;
12317:                 next;
12318:             }
12319:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12320:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12321:             if ($state eq 'exists') {
12322:                 $output .= $msg;
12323:                 next;
12324:             }
12325:         }
12326:         # Check if extension is valid
12327:         if (($fname =~ /\.(\w+)$/) &&
12328:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12329:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12330:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12331:             next;
12332:         } elsif (($fname =~ /\.(\w+)$/) &&
12333:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12334:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12335:             next;
12336:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12337:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12338:             next;
12339:         }
12340:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12341:         my $subdir = $path;
12342:         $subdir =~ s{/+$}{};
12343:         if ($context eq 'portfolio') {
12344:             my $result;
12345:             if ($state eq 'existingfile') {
12346:                 $result=
12347:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12348:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12349:             } else {
12350:                 $result=
12351:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12352:                                                     $dirpath.
12353:                                                     $env{'form.currentpath'}.$subdir);
12354:                 if ($result !~ m|^/uploaded/|) {
12355:                     $output .= '<span class="LC_error">'
12356:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12357:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12358:                                .'</span><br />';
12359:                     next;
12360:                 } else {
12361:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12362:                                $path.$fname.'</span>').'<br />';     
12363:                 }
12364:             }
12365:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12366:             my $extendedsubdir = $dirpath.'/'.$subdir;
12367:             $extendedsubdir =~ s{/+$}{};
12368:             my $result =
12369:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12370:             if ($result !~ m|^/uploaded/|) {
12371:                 $output .= '<span class="LC_error">'
12372:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12373:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12374:                            .'</span><br />';
12375:                     next;
12376:             } else {
12377:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12378:                            $path.$fname.'</span>').'<br />';
12379:                 if ($context eq 'syllabus') {
12380:                     &Apache::lonnet::make_public_indefinitely($result);
12381:                 }
12382:             }
12383:         } else {
12384: # Save the file
12385:             my $target = $env{'form.embedded_item_'.$i};
12386:             my $fullpath = $dir_root.$dirpath.'/'.$path;
12387:             my $dest = $fullpath.$fname;
12388:             my $url = $url_root.$dirpath.'/'.$path.$fname;
12389:             my @parts=split(/\//,"$dirpath/$path");
12390:             my $count;
12391:             my $filepath = $dir_root;
12392:             foreach my $subdir (@parts) {
12393:                 $filepath .= "/$subdir";
12394:                 if (!-e $filepath) {
12395:                     mkdir($filepath,0770);
12396:                 }
12397:             }
12398:             my $fh;
12399:             if (!open($fh,'>'.$dest)) {
12400:                 &Apache::lonnet::logthis('Failed to create '.$dest);
12401:                 $output .= '<span class="LC_error">'.
12402:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12403:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12404:                            '</span><br />';
12405:             } else {
12406:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
12407:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
12408:                     $output .= '<span class="LC_error">'.
12409:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12410:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12411:                               '</span><br />';
12412:                 } else {
12413:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12414:                                $url.'</span>').'<br />';
12415:                     unless ($context eq 'testbank') {
12416:                         $footer .= &mt('View embedded file: [_1]',
12417:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12418:                     }
12419:                 }
12420:                 close($fh);
12421:             }
12422:         }
12423:         if ($env{'form.embedded_ref_'.$i}) {
12424:             $pathchange{$i} = 1;
12425:         }
12426:     }
12427:     if ($output) {
12428:         $output = '<p>'.$output.'</p>';
12429:     }
12430:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12431:     $returnflag = 'ok';
12432:     my $numpathchgs = scalar(keys(%pathchange));
12433:     if ($numpathchgs > 0) {
12434:         if ($context eq 'portfolio') {
12435:             $output .= '<p>'.&mt('or').'</p>';
12436:         } elsif ($context eq 'testbank') {
12437:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12438:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12439:             $returnflag = 'modify_orightml';
12440:         }
12441:     }
12442:     return ($output.$footer,$returnflag,$numpathchgs);
12443: }
12444: 
12445: sub modify_html_form {
12446:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12447:     my $end = 0;
12448:     my $modifyform;
12449:     if ($context eq 'upload_embedded') {
12450:         return unless (ref($pathchange) eq 'HASH');
12451:         if ($env{'form.number_embedded_items'}) {
12452:             $end += $env{'form.number_embedded_items'};
12453:         }
12454:         if ($env{'form.number_pathchange_items'}) {
12455:             $end += $env{'form.number_pathchange_items'};
12456:         }
12457:         if ($end) {
12458:             for (my $i=0; $i<$end; $i++) {
12459:                 if ($i < $env{'form.number_embedded_items'}) {
12460:                     next unless($pathchange->{$i});
12461:                 }
12462:                 $modifyform .=
12463:                     &start_data_table_row().
12464:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12465:                     'checked="checked" /></td>'.
12466:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12467:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12468:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12469:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12470:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12471:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12472:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12473:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12474:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12475:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12476:                     &end_data_table_row();
12477:             }
12478:         }
12479:     } else {
12480:         $modifyform = $pathchgtable;
12481:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12482:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12483:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12484:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12485:         }
12486:     }
12487:     if ($modifyform) {
12488:         if ($actionurl eq '/adm/dependencies') {
12489:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12490:         }
12491:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12492:                '<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".
12493:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12494:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12495:                '</ol></p>'."\n".'<p>'.
12496:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12497:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12498:                &start_data_table()."\n".
12499:                &start_data_table_header_row().
12500:                '<th>'.&mt('Change?').'</th>'.
12501:                '<th>'.&mt('Current reference').'</th>'.
12502:                '<th>'.&mt('Required reference').'</th>'.
12503:                &end_data_table_header_row()."\n".
12504:                $modifyform.
12505:                &end_data_table().'<br />'."\n".$hiddenstate.
12506:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12507:                '</form>'."\n";
12508:     }
12509:     return;
12510: }
12511: 
12512: sub modify_html_refs {
12513:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12514:     my $container;
12515:     if ($context eq 'portfolio') {
12516:         $container = $env{'form.container'};
12517:     } elsif ($context eq 'coursedoc') {
12518:         $container = $env{'form.primaryurl'};
12519:     } elsif ($context eq 'manage_dependencies') {
12520:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12521:         $container = "/$container";
12522:     } elsif ($context eq 'syllabus') {
12523:         $container = $url;
12524:     } else {
12525:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12526:     }
12527:     my (%allfiles,%codebase,$output,$content);
12528:     my @changes = &get_env_multiple('form.namechange');
12529:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
12530:         if (wantarray) {
12531:             return ('',0,0); 
12532:         } else {
12533:             return;
12534:         }
12535:     }
12536:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12537:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12538:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12539:             if (wantarray) {
12540:                 return ('',0,0);
12541:             } else {
12542:                 return;
12543:             }
12544:         } 
12545:         $content = &Apache::lonnet::getfile($container);
12546:         if ($content eq '-1') {
12547:             if (wantarray) {
12548:                 return ('',0,0);
12549:             } else {
12550:                 return;
12551:             }
12552:         }
12553:     } else {
12554:         unless ($container =~ /^\Q$dir_root\E/) {
12555:             if (wantarray) {
12556:                 return ('',0,0);
12557:             } else {
12558:                 return;
12559:             }
12560:         } 
12561:         if (open(my $fh,'<',$container)) {
12562:             $content = join('', <$fh>);
12563:             close($fh);
12564:         } else {
12565:             if (wantarray) {
12566:                 return ('',0,0);
12567:             } else {
12568:                 return;
12569:             }
12570:         }
12571:     }
12572:     my ($count,$codebasecount) = (0,0);
12573:     my $mm = new File::MMagic;
12574:     my $mime_type = $mm->checktype_contents($content);
12575:     if ($mime_type eq 'text/html') {
12576:         my $parse_result = 
12577:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12578:                                                     \%codebase,\$content);
12579:         if ($parse_result eq 'ok') {
12580:             foreach my $i (@changes) {
12581:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12582:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12583:                 if ($allfiles{$ref}) {
12584:                     my $newname =  $orig;
12585:                     my ($attrib_regexp,$codebase);
12586:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12587:                     if ($attrib_regexp =~ /:/) {
12588:                         $attrib_regexp =~ s/\:/|/g;
12589:                     }
12590:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12591:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12592:                         $count += $numchg;
12593:                         $allfiles{$newname} = $allfiles{$ref};
12594:                         delete($allfiles{$ref});
12595:                     }
12596:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12597:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12598:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12599:                         $codebasecount ++;
12600:                     }
12601:                 }
12602:             }
12603:             my $skiprewrites;
12604:             if ($count || $codebasecount) {
12605:                 my $saveresult;
12606:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12607:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12608:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12609:                     if ($url eq $container) {
12610:                         my ($fname) = ($container =~ m{/([^/]+)$});
12611:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12612:                                             $count,'<span class="LC_filename">'.
12613:                                             $fname.'</span>').'</p>';
12614:                     } else {
12615:                          $output = '<p class="LC_error">'.
12616:                                    &mt('Error: update failed for: [_1].',
12617:                                    '<span class="LC_filename">'.
12618:                                    $container.'</span>').'</p>';
12619:                     }
12620:                     if ($context eq 'syllabus') {
12621:                         unless ($saveresult eq 'ok') {
12622:                             $skiprewrites = 1;
12623:                         }
12624:                     }
12625:                 } else {
12626:                     if (open(my $fh,'>',$container)) {
12627:                         print $fh $content;
12628:                         close($fh);
12629:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12630:                                   $count,'<span class="LC_filename">'.
12631:                                   $container.'</span>').'</p>';
12632:                     } else {
12633:                          $output = '<p class="LC_error">'.
12634:                                    &mt('Error: could not update [_1].',
12635:                                    '<span class="LC_filename">'.
12636:                                    $container.'</span>').'</p>';
12637:                     }
12638:                 }
12639:             }
12640:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12641:                 my ($actionurl,$state);
12642:                 $actionurl = "/public/$udom/$uname/syllabus";
12643:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12644:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12645:                                               \%codebase,
12646:                                               {'context' => 'rewrites',
12647:                                                'ignore_remote_references' => 1,});
12648:                 if (ref($mapping) eq 'HASH') {
12649:                     my $rewrites = 0;
12650:                     foreach my $key (keys(%{$mapping})) {
12651:                         next if ($key =~ m{^https?://});
12652:                         my $ref = $mapping->{$key};
12653:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12654:                         my $attrib;
12655:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12656:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12657:                         }
12658:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12659:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12660:                             $rewrites += $numchg;
12661:                         }
12662:                     }
12663:                     if ($rewrites) {
12664:                         my $saveresult;
12665:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12666:                         if ($url eq $container) {
12667:                             my ($fname) = ($container =~ m{/([^/]+)$});
12668:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12669:                                             $count,'<span class="LC_filename">'.
12670:                                             $fname.'</span>').'</p>';
12671:                         } else {
12672:                             $output .= '<p class="LC_error">'.
12673:                                        &mt('Error: could not update links in [_1].',
12674:                                        '<span class="LC_filename">'.
12675:                                        $container.'</span>').'</p>';
12676: 
12677:                         }
12678:                     }
12679:                 }
12680:             }
12681:         } else {
12682:             &logthis('Failed to parse '.$container.
12683:                      ' to modify references: '.$parse_result);
12684:         }
12685:     }
12686:     if (wantarray) {
12687:         return ($output,$count,$codebasecount);
12688:     } else {
12689:         return $output;
12690:     }
12691: }
12692: 
12693: sub check_for_existing {
12694:     my ($path,$fname,$element) = @_;
12695:     my ($state,$msg);
12696:     if (-d $path.'/'.$fname) {
12697:         $state = 'exists';
12698:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12699:     } elsif (-e $path.'/'.$fname) {
12700:         $state = 'exists';
12701:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12702:     }
12703:     if ($state eq 'exists') {
12704:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12705:     }
12706:     return ($state,$msg);
12707: }
12708: 
12709: sub check_for_upload {
12710:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12711:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12712:     my $filesize = length($env{'form.'.$element});
12713:     if (!$filesize) {
12714:         my $msg = '<span class="LC_error">'.
12715:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12716:                       '<span class="LC_filename">'.$fname.'</span>',
12717:                       $filesize).'<br />'.
12718:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12719:                   '</span>';
12720:         return ('zero_bytes',$msg);
12721:     }
12722:     $filesize =  $filesize/1000; #express in k (1024?)
12723:     my $getpropath = 1;
12724:     my ($dirlistref,$listerror) =
12725:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12726:     my $found_file = 0;
12727:     my $locked_file = 0;
12728:     my @lockers;
12729:     my $navmap;
12730:     if ($env{'request.course.id'}) {
12731:         $navmap = Apache::lonnavmaps::navmap->new();
12732:     }
12733:     if (ref($dirlistref) eq 'ARRAY') {
12734:         foreach my $line (@{$dirlistref}) {
12735:             my ($file_name,$rest)=split(/\&/,$line,2);
12736:             if ($file_name eq $fname){
12737:                 $file_name = $path.$file_name;
12738:                 if ($group ne '') {
12739:                     $file_name = $group.$file_name;
12740:                 }
12741:                 $found_file = 1;
12742:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12743:                     foreach my $lock (@lockers) {
12744:                         if (ref($lock) eq 'ARRAY') {
12745:                             my ($symb,$crsid) = @{$lock};
12746:                             if ($crsid eq $env{'request.course.id'}) {
12747:                                 if (ref($navmap)) {
12748:                                     my $res = $navmap->getBySymb($symb);
12749:                                     foreach my $part (@{$res->parts()}) { 
12750:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12751:                                         unless (($slot_status == $res->RESERVED) ||
12752:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12753:                                             $locked_file = 1;
12754:                                         }
12755:                                     }
12756:                                 } else {
12757:                                     $locked_file = 1;
12758:                                 }
12759:                             } else {
12760:                                 $locked_file = 1;
12761:                             }
12762:                         }
12763:                    }
12764:                 } else {
12765:                     my @info = split(/\&/,$rest);
12766:                     my $currsize = $info[6]/1000;
12767:                     if ($currsize < $filesize) {
12768:                         my $extra = $filesize - $currsize;
12769:                         if (($current_disk_usage + $extra) > $disk_quota) {
12770:                             my $msg = '<p class="LC_warning">'.
12771:                                       &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.',
12772:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12773:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12774:                                                    $disk_quota,$current_disk_usage).'</p>';
12775:                             return ('will_exceed_quota',$msg);
12776:                         }
12777:                     }
12778:                 }
12779:             }
12780:         }
12781:     }
12782:     if (($current_disk_usage + $filesize) > $disk_quota){
12783:         my $msg = '<p class="LC_warning">'.
12784:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12785:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12786:         return ('will_exceed_quota',$msg);
12787:     } elsif ($found_file) {
12788:         if ($locked_file) {
12789:             my $msg = '<p class="LC_warning">';
12790:             $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>');
12791:             $msg .= '</p>';
12792:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12793:             return ('file_locked',$msg);
12794:         } else {
12795:             my $msg = '<p class="LC_error">';
12796:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12797:             $msg .= '</p>';
12798:             return ('existingfile',$msg);
12799:         }
12800:     }
12801: }
12802: 
12803: sub check_for_traversal {
12804:     my ($path,$url,$toplevel) = @_;
12805:     my @parts=split(/\//,$path);
12806:     my $cleanpath;
12807:     my $fullpath = $url;
12808:     for (my $i=0;$i<@parts;$i++) {
12809:         next if ($parts[$i] eq '.');
12810:         if ($parts[$i] eq '..') {
12811:             $fullpath =~ s{([^/]+/)$}{};
12812:         } else {
12813:             $fullpath .= $parts[$i].'/';
12814:         }
12815:     }
12816:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12817:         $cleanpath = $1;
12818:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12819:         my $curr_toprel = $1;
12820:         my @parts = split(/\//,$curr_toprel);
12821:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12822:         my @urlparts = split(/\//,$url_toprel);
12823:         my $doubledots;
12824:         my $startdiff = -1;
12825:         for (my $i=0; $i<@urlparts; $i++) {
12826:             if ($startdiff == -1) {
12827:                 unless ($urlparts[$i] eq $parts[$i]) {
12828:                     $startdiff = $i;
12829:                     $doubledots .= '../';
12830:                 }
12831:             } else {
12832:                 $doubledots .= '../';
12833:             }
12834:         }
12835:         if ($startdiff > -1) {
12836:             $cleanpath = $doubledots;
12837:             for (my $i=$startdiff; $i<@parts; $i++) {
12838:                 $cleanpath .= $parts[$i].'/';
12839:             }
12840:         }
12841:     }
12842:     $cleanpath =~ s{(/)$}{};
12843:     return $cleanpath;
12844: }
12845: 
12846: sub is_archive_file {
12847:     my ($mimetype) = @_;
12848:     if (($mimetype eq 'application/octet-stream') ||
12849:         ($mimetype eq 'application/x-stuffit') ||
12850:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12851:         return 1;
12852:     }
12853:     return;
12854: }
12855: 
12856: sub decompress_form {
12857:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12858:     my %lt = &Apache::lonlocal::texthash (
12859:         this => 'This file is an archive file.',
12860:         camt => 'This file is a Camtasia archive file.',
12861:         itsc => 'Its contents are as follows:',
12862:         youm => 'You may wish to extract its contents.',
12863:         extr => 'Extract contents',
12864:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12865:         proa => 'Process automatically?',
12866:         yes  => 'Yes',
12867:         no   => 'No',
12868:         fold => 'Title for folder containing movie',
12869:         movi => 'Title for page containing embedded movie', 
12870:     );
12871:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12872:     my ($is_camtasia,$topdir,%toplevel,@paths);
12873:     my $info = &list_archive_contents($fileloc,\@paths);
12874:     if (@paths) {
12875:         foreach my $path (@paths) {
12876:             $path =~ s{^/}{};
12877:             if ($path =~ m{^([^/]+)/$}) {
12878:                 $topdir = $1;
12879:             }
12880:             if ($path =~ m{^([^/]+)/}) {
12881:                 $toplevel{$1} = $path;
12882:             } else {
12883:                 $toplevel{$path} = $path;
12884:             }
12885:         }
12886:     }
12887:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12888:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12889:                         "$topdir/media/",
12890:                         "$topdir/media/$topdir.mp4",
12891:                         "$topdir/media/FirstFrame.png",
12892:                         "$topdir/media/player.swf",
12893:                         "$topdir/media/swfobject.js",
12894:                         "$topdir/media/expressInstall.swf");
12895:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12896:                          "$topdir/$topdir.mp4",
12897:                          "$topdir/$topdir\_config.xml",
12898:                          "$topdir/$topdir\_controller.swf",
12899:                          "$topdir/$topdir\_embed.css",
12900:                          "$topdir/$topdir\_First_Frame.png",
12901:                          "$topdir/$topdir\_player.html",
12902:                          "$topdir/$topdir\_Thumbnails.png",
12903:                          "$topdir/playerProductInstall.swf",
12904:                          "$topdir/scripts/",
12905:                          "$topdir/scripts/config_xml.js",
12906:                          "$topdir/scripts/handlebars.js",
12907:                          "$topdir/scripts/jquery-1.7.1.min.js",
12908:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12909:                          "$topdir/scripts/modernizr.js",
12910:                          "$topdir/scripts/player-min.js",
12911:                          "$topdir/scripts/swfobject.js",
12912:                          "$topdir/skins/",
12913:                          "$topdir/skins/configuration_express.xml",
12914:                          "$topdir/skins/express_show/",
12915:                          "$topdir/skins/express_show/player-min.css",
12916:                          "$topdir/skins/express_show/spritesheet.png");
12917:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12918:                          "$topdir/$topdir.mp4",
12919:                          "$topdir/$topdir\_config.xml",
12920:                          "$topdir/$topdir\_controller.swf",
12921:                          "$topdir/$topdir\_embed.css",
12922:                          "$topdir/$topdir\_First_Frame.png",
12923:                          "$topdir/$topdir\_player.html",
12924:                          "$topdir/$topdir\_Thumbnails.png",
12925:                          "$topdir/playerProductInstall.swf",
12926:                          "$topdir/scripts/",
12927:                          "$topdir/scripts/config_xml.js",
12928:                          "$topdir/scripts/techsmith-smart-player.min.js",
12929:                          "$topdir/skins/",
12930:                          "$topdir/skins/configuration_express.xml",
12931:                          "$topdir/skins/express_show/",
12932:                          "$topdir/skins/express_show/spritesheet.min.css",
12933:                          "$topdir/skins/express_show/spritesheet.png",
12934:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12935:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12936:         if (@diffs == 0) {
12937:             $is_camtasia = 6;
12938:         } else {
12939:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12940:             if (@diffs == 0) {
12941:                 $is_camtasia = 8;
12942:             } else {
12943:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12944:                 if (@diffs == 0) {
12945:                     $is_camtasia = 8;
12946:                 }
12947:             }
12948:         }
12949:     }
12950:     my $output;
12951:     if ($is_camtasia) {
12952:         $output = <<"ENDCAM";
12953: <script type="text/javascript" language="Javascript">
12954: // <![CDATA[
12955: 
12956: function camtasiaToggle() {
12957:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12958:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12959:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12960:                 document.getElementById('camtasia_titles').style.display='block';
12961:             } else {
12962:                 document.getElementById('camtasia_titles').style.display='none';
12963:             }
12964:         }
12965:     }
12966:     return;
12967: }
12968: 
12969: // ]]>
12970: </script>
12971: <p>$lt{'camt'}</p>
12972: ENDCAM
12973:     } else {
12974:         $output = '<p>'.$lt{'this'};
12975:         if ($info eq '') {
12976:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12977:         } else {
12978:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12979:                        '<div><pre>'.$info.'</pre></div>';
12980:         }
12981:     }
12982:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12983:     my $duplicates;
12984:     my $num = 0;
12985:     if (ref($dirlist) eq 'ARRAY') {
12986:         foreach my $item (@{$dirlist}) {
12987:             if (ref($item) eq 'ARRAY') {
12988:                 if (exists($toplevel{$item->[0]})) {
12989:                     $duplicates .= 
12990:                         &start_data_table_row().
12991:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12992:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12993:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12994:                         'value="1" />'.&mt('Yes').'</label>'.
12995:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12996:                         '<td>'.$item->[0].'</td>';
12997:                     if ($item->[2]) {
12998:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12999:                     } else {
13000:                         $duplicates .= '<td>'.&mt('File').'</td>';
13001:                     }
13002:                     $duplicates .= '<td>'.$item->[3].'</td>'.
13003:                                    '<td>'.
13004:                                    &Apache::lonlocal::locallocaltime($item->[4]).
13005:                                    '</td>'.
13006:                                    &end_data_table_row();
13007:                     $num ++;
13008:                 }
13009:             }
13010:         }
13011:     }
13012:     my $itemcount;
13013:     if (@paths > 0) {
13014:         $itemcount = scalar(@paths);
13015:     } else {
13016:         $itemcount = 1;
13017:     }
13018:     if ($is_camtasia) {
13019:         $output .= $lt{'auto'}.'<br />'.
13020:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13021:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13022:                    $lt{'yes'}.'</label>&nbsp;<label>'.
13023:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13024:                    $lt{'no'}.'</label></span><br />'.
13025:                    '<div id="camtasia_titles" style="display:block">'.
13026:                    &Apache::lonhtmlcommon::start_pick_box().
13027:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13028:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13029:                    &Apache::lonhtmlcommon::row_closure().
13030:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13031:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13032:                    &Apache::lonhtmlcommon::row_closure(1).
13033:                    &Apache::lonhtmlcommon::end_pick_box().
13034:                    '</div>';
13035:     }
13036:     $output .= 
13037:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13038:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13039:         "\n";
13040:     if ($duplicates ne '') {
13041:         $output .= '<p><span class="LC_warning">'.
13042:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
13043:                    &start_data_table().
13044:                    &start_data_table_header_row().
13045:                    '<th>'.&mt('Overwrite?').'</th>'.
13046:                    '<th>'.&mt('Name').'</th>'.
13047:                    '<th>'.&mt('Type').'</th>'.
13048:                    '<th>'.&mt('Size').'</th>'.
13049:                    '<th>'.&mt('Last modified').'</th>'.
13050:                    &end_data_table_header_row().
13051:                    $duplicates.
13052:                    &end_data_table().
13053:                    '</p>';
13054:     }
13055:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13056:     if (ref($hiddenelements) eq 'HASH') {
13057:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13058:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13059:         }
13060:     }
13061:     $output .= <<"END";
13062: <br />
13063: <input type="submit" name="decompress" value="$lt{'extr'}" />
13064: </form>
13065: $noextract
13066: END
13067:     return $output;
13068: }
13069: 
13070: sub decompression_utility {
13071:     my ($program) = @_;
13072:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
13073:     my $location;
13074:     if (grep(/^\Q$program\E$/,@utilities)) { 
13075:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13076:                          '/usr/sbin/') {
13077:             if (-x $dir.$program) {
13078:                 $location = $dir.$program;
13079:                 last;
13080:             }
13081:         }
13082:     }
13083:     return $location;
13084: }
13085: 
13086: sub list_archive_contents {
13087:     my ($file,$pathsref) = @_;
13088:     my (@cmd,$output);
13089:     my $needsregexp;
13090:     if ($file =~ /\.zip$/) {
13091:         @cmd = (&decompression_utility('unzip'),"-l");
13092:         $needsregexp = 1;
13093:     } elsif (($file =~ m/\.tar\.gz$/) ||
13094:              ($file =~ /\.tgz$/)) {
13095:         @cmd = (&decompression_utility('tar'),"-ztf");
13096:     } elsif ($file =~ /\.tar\.bz2$/) {
13097:         @cmd = (&decompression_utility('tar'),"-jtf");
13098:     } elsif ($file =~ m|\.tar$|) {
13099:         @cmd = (&decompression_utility('tar'),"-tf");
13100:     }
13101:     if (@cmd) {
13102:         undef($!);
13103:         undef($@);
13104:         if (open(my $fh,"-|", @cmd, $file)) {
13105:             while (my $line = <$fh>) {
13106:                 $output .= $line;
13107:                 chomp($line);
13108:                 my $item;
13109:                 if ($needsregexp) {
13110:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
13111:                 } else {
13112:                     $item = $line;
13113:                 }
13114:                 if ($item ne '') {
13115:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13116:                         push(@{$pathsref},$item);
13117:                     } 
13118:                 }
13119:             }
13120:             close($fh);
13121:         }
13122:     }
13123:     return $output;
13124: }
13125: 
13126: sub decompress_uploaded_file {
13127:     my ($file,$dir) = @_;
13128:     &Apache::lonnet::appenv({'cgi.file' => $file});
13129:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
13130:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13131:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13132:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13133:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13134:     my $decompressed = $env{'cgi.decompressed'};
13135:     &Apache::lonnet::delenv('cgi.file');
13136:     &Apache::lonnet::delenv('cgi.dir');
13137:     &Apache::lonnet::delenv('cgi.decompressed');
13138:     return ($decompressed,$result);
13139: }
13140: 
13141: sub process_decompression {
13142:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13143:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13144:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13145:                &mt('Unexpected file path.').'</p>'."\n";
13146:     }
13147:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13148:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13149:                &mt('Unexpected course context.').'</p>'."\n";
13150:     }
13151:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
13152:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13153:                &mt('Filename contained unexpected characters.').'</p>'."\n";
13154:     }
13155:     my ($dir,$error,$warning,$output);
13156:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13157:         $error = &mt('Filename not a supported archive file type.').
13158:                  '<br />'.&mt('Filename should end with one of: [_1].',
13159:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13160:     } else {
13161:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13162:         if ($docuhome eq 'no_host') {
13163:             $error = &mt('Could not determine home server for course.');
13164:         } else {
13165:             my @ids=&Apache::lonnet::current_machine_ids();
13166:             my $currdir = "$dir_root/$destination";
13167:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13168:                 $dir = &LONCAPA::propath($docudom,$docuname).
13169:                        "$dir_root/$destination";
13170:             } else {
13171:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13172:                        "$dir_root/$docudom/$docuname/$destination";
13173:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13174:                     $error = &mt('Archive file not found.');
13175:                 }
13176:             }
13177:             my (@to_overwrite,@to_skip);
13178:             if ($env{'form.archive_overwrite_total'} > 0) {
13179:                 my $total = $env{'form.archive_overwrite_total'};
13180:                 for (my $i=0; $i<$total; $i++) {
13181:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13182:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13183:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13184:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13185:                     }
13186:                 }
13187:             }
13188:             my $numskip = scalar(@to_skip);
13189:             my $numoverwrite = scalar(@to_overwrite);
13190:             if (($numskip) && (!$numoverwrite)) {
13191:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13192:             } elsif ($dir eq '') {
13193:                 $error = &mt('Directory containing archive file unavailable.');
13194:             } elsif (!$error) {
13195:                 my ($decompressed,$display);
13196:                 if (($numskip) || ($numoverwrite)) {
13197:                     my $tempdir = time.'_'.$$.int(rand(10000));
13198:                     mkdir("$dir/$tempdir",0755);
13199:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13200:                         ($decompressed,$display) =
13201:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13202:                         foreach my $item (@to_skip) {
13203:                             if (($item ne '') && ($item !~ /\.\./)) {
13204:                                 if (-f "$dir/$tempdir/$item") {
13205:                                     unlink("$dir/$tempdir/$item");
13206:                                 } elsif (-d "$dir/$tempdir/$item") {
13207:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13208:                                 }
13209:                             }
13210:                         }
13211:                         foreach my $item (@to_overwrite) {
13212:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13213:                                 if (($item ne '') && ($item !~ /\.\./)) {
13214:                                     if (-f "$dir/$item") {
13215:                                         unlink("$dir/$item");
13216:                                     } elsif (-d "$dir/$item") {
13217:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13218:                                     }
13219:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13220:                                 }
13221:                             }
13222:                         }
13223:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13224:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13225:                         }
13226:                     }
13227:                 } else {
13228:                     ($decompressed,$display) = 
13229:                         &decompress_uploaded_file($file,$dir);
13230:                 }
13231:                 if ($decompressed eq 'ok') {
13232:                     $output = '<p class="LC_info">'.
13233:                               &mt('Files extracted successfully from archive.').
13234:                               '</p>'."\n";
13235:                     my ($warning,$result,@contents);
13236:                     my ($newdirlistref,$newlisterror) =
13237:                         &Apache::lonnet::dirlist($currdir,$docudom,
13238:                                                  $docuname,1);
13239:                     my (%is_dir,%changes,@newitems);
13240:                     my $dirptr = 16384;
13241:                     if (ref($newdirlistref) eq 'ARRAY') {
13242:                         foreach my $dir_line (@{$newdirlistref}) {
13243:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13244:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
13245:                                 push(@newitems,$item);
13246:                                 if ($dirptr&$testdir) {
13247:                                     $is_dir{$item} = 1;
13248:                                 }
13249:                                 $changes{$item} = 1;
13250:                             }
13251:                         }
13252:                     }
13253:                     if (keys(%changes) > 0) {
13254:                         foreach my $item (sort(@newitems)) {
13255:                             if ($changes{$item}) {
13256:                                 push(@contents,$item);
13257:                             }
13258:                         }
13259:                     }
13260:                     if (@contents > 0) {
13261:                         my $wantform;
13262:                         unless ($env{'form.autoextract_camtasia'}) {
13263:                             $wantform = 1;
13264:                         }
13265:                         my (%children,%parent,%dirorder,%titles);
13266:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13267:                                                                 $currdir,\%is_dir,
13268:                                                                 \%children,\%parent,
13269:                                                                 \@contents,\%dirorder,
13270:                                                                 \%titles,$wantform);
13271:                         if ($datatable ne '') {
13272:                             $output .= &archive_options_form('decompressed',$datatable,
13273:                                                              $count,$hiddenelem);
13274:                             my $startcount = 6;
13275:                             $output .= &archive_javascript($startcount,$count,
13276:                                                            \%titles,\%children);
13277:                         }
13278:                         if ($env{'form.autoextract_camtasia'}) {
13279:                             my $version = $env{'form.autoextract_camtasia'};
13280:                             my %displayed;
13281:                             my $total = 1;
13282:                             $env{'form.archive_directory'} = [];
13283:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13284:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13285:                                 $path =~ s{/$}{};
13286:                                 my $item;
13287:                                 if ($path ne '') {
13288:                                     $item = "$path/$titles{$i}";
13289:                                 } else {
13290:                                     $item = $titles{$i};
13291:                                 }
13292:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13293:                                 if ($item eq $contents[0]) {
13294:                                     push(@{$env{'form.archive_directory'}},$i);
13295:                                     $env{'form.archive_'.$i} = 'display';
13296:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13297:                                     $displayed{'folder'} = $i;
13298:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13299:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
13300:                                     $env{'form.archive_'.$i} = 'display';
13301:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13302:                                     $displayed{'web'} = $i;
13303:                                 } else {
13304:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13305:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13306:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13307:                                         push(@{$env{'form.archive_directory'}},$i);
13308:                                     }
13309:                                     $env{'form.archive_'.$i} = 'dependency';
13310:                                 }
13311:                                 $total ++;
13312:                             }
13313:                             for (my $i=1; $i<$total; $i++) {
13314:                                 next if ($i == $displayed{'web'});
13315:                                 next if ($i == $displayed{'folder'});
13316:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13317:                             }
13318:                             $env{'form.phase'} = 'decompress_cleanup';
13319:                             $env{'form.archivedelete'} = 1;
13320:                             $env{'form.archive_count'} = $total-1;
13321:                             $output .=
13322:                                 &process_extracted_files('coursedocs',$docudom,
13323:                                                          $docuname,$destination,
13324:                                                          $dir_root,$hiddenelem);
13325:                         }
13326:                     } else {
13327:                         $warning = &mt('No new items extracted from archive file.');
13328:                     }
13329:                 } else {
13330:                     $output = $display;
13331:                     $error = &mt('An error occurred during extraction from the archive file.');
13332:                 }
13333:             }
13334:         }
13335:     }
13336:     if ($error) {
13337:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13338:                    $error.'</p>'."\n";
13339:     }
13340:     if ($warning) {
13341:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13342:     }
13343:     return $output;
13344: }
13345: 
13346: sub get_extracted {
13347:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13348:         $titles,$wantform) = @_;
13349:     my $count = 0;
13350:     my $depth = 0;
13351:     my $datatable;
13352:     my @hierarchy;
13353:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13354:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13355:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13356:     foreach my $item (@{$contents}) {
13357:         $count ++;
13358:         @{$dirorder->{$count}} = @hierarchy;
13359:         $titles->{$count} = $item;
13360:         &archive_hierarchy($depth,$count,$parent,$children);
13361:         if ($wantform) {
13362:             $datatable .= &archive_row($is_dir->{$item},$item,
13363:                                        $currdir,$depth,$count);
13364:         }
13365:         if ($is_dir->{$item}) {
13366:             $depth ++;
13367:             push(@hierarchy,$count);
13368:             $parent->{$depth} = $count;
13369:             $datatable .=
13370:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13371:                                            \$depth,\$count,\@hierarchy,$dirorder,
13372:                                            $children,$parent,$titles,$wantform);
13373:             $depth --;
13374:             pop(@hierarchy);
13375:         }
13376:     }
13377:     return ($count,$datatable);
13378: }
13379: 
13380: sub recurse_extracted_archive {
13381:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13382:         $children,$parent,$titles,$wantform) = @_;
13383:     my $result='';
13384:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13385:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13386:             (ref($dirorder) eq 'HASH')) {
13387:         return $result;
13388:     }
13389:     my $dirptr = 16384;
13390:     my ($newdirlistref,$newlisterror) =
13391:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13392:     if (ref($newdirlistref) eq 'ARRAY') {
13393:         foreach my $dir_line (@{$newdirlistref}) {
13394:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13395:             unless ($item =~ /^\.+$/) {
13396:                 $$count ++;
13397:                 @{$dirorder->{$$count}} = @{$hierarchy};
13398:                 $titles->{$$count} = $item;
13399:                 &archive_hierarchy($$depth,$$count,$parent,$children);
13400: 
13401:                 my $is_dir;
13402:                 if ($dirptr&$testdir) {
13403:                     $is_dir = 1;
13404:                 }
13405:                 if ($wantform) {
13406:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13407:                 }
13408:                 if ($is_dir) {
13409:                     $$depth ++;
13410:                     push(@{$hierarchy},$$count);
13411:                     $parent->{$$depth} = $$count;
13412:                     $result .=
13413:                         &recurse_extracted_archive("$currdir/$item",$docudom,
13414:                                                    $docuname,$depth,$count,
13415:                                                    $hierarchy,$dirorder,$children,
13416:                                                    $parent,$titles,$wantform);
13417:                     $$depth --;
13418:                     pop(@{$hierarchy});
13419:                 }
13420:             }
13421:         }
13422:     }
13423:     return $result;
13424: }
13425: 
13426: sub archive_hierarchy {
13427:     my ($depth,$count,$parent,$children) =@_;
13428:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13429:         if (exists($parent->{$depth})) {
13430:              $children->{$parent->{$depth}} .= $count.':';
13431:         }
13432:     }
13433:     return;
13434: }
13435: 
13436: sub archive_row {
13437:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13438:     my ($name) = ($item =~ m{([^/]+)$});
13439:     my %choices = &Apache::lonlocal::texthash (
13440:                                        'display'    => 'Add as file',
13441:                                        'dependency' => 'Include as dependency',
13442:                                        'discard'    => 'Discard',
13443:                                       );
13444:     if ($is_dir) {
13445:         $choices{'display'} = &mt('Add as folder'); 
13446:     }
13447:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13448:     my $offset = 0;
13449:     foreach my $action ('display','dependency','discard') {
13450:         $offset ++;
13451:         if ($action ne 'display') {
13452:             $offset ++;
13453:         }  
13454:         $output .= '<td><span class="LC_nobreak">'.
13455:                    '<label><input type="radio" name="archive_'.$count.
13456:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13457:         my $text = $choices{$action};
13458:         if ($is_dir) {
13459:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13460:             if ($action eq 'display') {
13461:                 $text = &mt('Add as folder');
13462:             }
13463:         } else {
13464:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13465: 
13466:         }
13467:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13468:         if ($action eq 'dependency') {
13469:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13470:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13471:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13472:                        '<option value=""></option>'."\n".
13473:                        '</select>'."\n".
13474:                        '</div>';
13475:         } elsif ($action eq 'display') {
13476:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13477:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13478:                        '</div>';
13479:         }
13480:         $output .= '</td>';
13481:     }
13482:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13483:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13484:     for (my $i=0; $i<$depth; $i++) {
13485:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13486:     }
13487:     if ($is_dir) {
13488:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13489:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13490:     } else {
13491:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13492:     }
13493:     $output .= '&nbsp;'.$name.'</td>'."\n".
13494:                &end_data_table_row();
13495:     return $output;
13496: }
13497: 
13498: sub archive_options_form {
13499:     my ($form,$display,$count,$hiddenelem) = @_;
13500:     my %lt = &Apache::lonlocal::texthash(
13501:                perm => 'Permanently remove archive file?',
13502:                hows => 'How should each extracted item be incorporated in the course?',
13503:                cont => 'Content actions for all',
13504:                addf => 'Add as folder/file',
13505:                incd => 'Include as dependency for a displayed file',
13506:                disc => 'Discard',
13507:                no   => 'No',
13508:                yes  => 'Yes',
13509:                save => 'Save',
13510:     );
13511:     my $output = <<"END";
13512: <form name="$form" method="post" action="">
13513: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13514: <label>
13515:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13516: </label>
13517: &nbsp;
13518: <label>
13519:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13520: </span>
13521: </p>
13522: <input type="hidden" name="phase" value="decompress_cleanup" />
13523: <br />$lt{'hows'}
13524: <div class="LC_columnSection">
13525:   <fieldset>
13526:     <legend>$lt{'cont'}</legend>
13527:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
13528:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13529:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13530:   </fieldset>
13531: </div>
13532: END
13533:     return $output.
13534:            &start_data_table()."\n".
13535:            $display."\n".
13536:            &end_data_table()."\n".
13537:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13538:            $hiddenelem.
13539:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13540:            '</form>';
13541: }
13542: 
13543: sub archive_javascript {
13544:     my ($startcount,$numitems,$titles,$children) = @_;
13545:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13546:     my $maintitle = $env{'form.comment'};
13547:     my $scripttag = <<START;
13548: <script type="text/javascript">
13549: // <![CDATA[
13550: 
13551: function checkAll(form,prefix) {
13552:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
13553:     for (var i=0; i < form.elements.length; i++) {
13554:         var id = form.elements[i].id;
13555:         if ((id != '') && (id != undefined)) {
13556:             if (idstr.test(id)) {
13557:                 if (form.elements[i].type == 'radio') {
13558:                     form.elements[i].checked = true;
13559:                     var nostart = i-$startcount;
13560:                     var offset = nostart%7;
13561:                     var count = (nostart-offset)/7;    
13562:                     dependencyCheck(form,count,offset);
13563:                 }
13564:             }
13565:         }
13566:     }
13567: }
13568: 
13569: function propagateCheck(form,count) {
13570:     if (count > 0) {
13571:         var startelement = $startcount + ((count-1) * 7);
13572:         for (var j=1; j<6; j++) {
13573:             if ((j != 2) && (j != 4)) {
13574:                 var item = startelement + j; 
13575:                 if (form.elements[item].type == 'radio') {
13576:                     if (form.elements[item].checked) {
13577:                         containerCheck(form,count,j);
13578:                         break;
13579:                     }
13580:                 }
13581:             }
13582:         }
13583:     }
13584: }
13585: 
13586: numitems = $numitems
13587: var titles = new Array(numitems);
13588: var parents = new Array(numitems);
13589: for (var i=0; i<numitems; i++) {
13590:     parents[i] = new Array;
13591: }
13592: var maintitle = '$maintitle';
13593: 
13594: START
13595: 
13596:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13597:         my @contents = split(/:/,$children->{$container});
13598:         for (my $i=0; $i<@contents; $i ++) {
13599:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13600:         }
13601:     }
13602: 
13603:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13604:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13605:     }
13606: 
13607:     $scripttag .= <<END;
13608: 
13609: function containerCheck(form,count,offset) {
13610:     if (count > 0) {
13611:         dependencyCheck(form,count,offset);
13612:         var item = (offset+$startcount)+7*(count-1);
13613:         form.elements[item].checked = true;
13614:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13615:             if (parents[count].length > 0) {
13616:                 for (var j=0; j<parents[count].length; j++) {
13617:                     containerCheck(form,parents[count][j],offset);
13618:                 }
13619:             }
13620:         }
13621:     }
13622: }
13623: 
13624: function dependencyCheck(form,count,offset) {
13625:     if (count > 0) {
13626:         var chosen = (offset+$startcount)+7*(count-1);
13627:         var depitem = $startcount + ((count-1) * 7) + 4;
13628:         var currtype = form.elements[depitem].type;
13629:         if (form.elements[chosen].value == 'dependency') {
13630:             document.getElementById('arc_depon_'+count).style.display='block'; 
13631:             form.elements[depitem].options.length = 0;
13632:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13633:             for (var i=1; i<=numitems; i++) {
13634:                 if (i == count) {
13635:                     continue;
13636:                 }
13637:                 var startelement = $startcount + (i-1) * 7;
13638:                 for (var j=1; j<6; j++) {
13639:                     if ((j != 2) && (j!= 4)) {
13640:                         var item = startelement + j;
13641:                         if (form.elements[item].type == 'radio') {
13642:                             if (form.elements[item].checked) {
13643:                                 if (form.elements[item].value == 'display') {
13644:                                     var n = form.elements[depitem].options.length;
13645:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13646:                                 }
13647:                             }
13648:                         }
13649:                     }
13650:                 }
13651:             }
13652:         } else {
13653:             document.getElementById('arc_depon_'+count).style.display='none';
13654:             form.elements[depitem].options.length = 0;
13655:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13656:         }
13657:         titleCheck(form,count,offset);
13658:     }
13659: }
13660: 
13661: function propagateSelect(form,count,offset) {
13662:     if (count > 0) {
13663:         var item = (1+offset+$startcount)+7*(count-1);
13664:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13665:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13666:             if (parents[count].length > 0) {
13667:                 for (var j=0; j<parents[count].length; j++) {
13668:                     containerSelect(form,parents[count][j],offset,picked);
13669:                 }
13670:             }
13671:         }
13672:     }
13673: }
13674: 
13675: function containerSelect(form,count,offset,picked) {
13676:     if (count > 0) {
13677:         var item = (offset+$startcount)+7*(count-1);
13678:         if (form.elements[item].type == 'radio') {
13679:             if (form.elements[item].value == 'dependency') {
13680:                 if (form.elements[item+1].type == 'select-one') {
13681:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13682:                         if (form.elements[item+1].options[i].value == picked) {
13683:                             form.elements[item+1].selectedIndex = i;
13684:                             break;
13685:                         }
13686:                     }
13687:                 }
13688:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13689:                     if (parents[count].length > 0) {
13690:                         for (var j=0; j<parents[count].length; j++) {
13691:                             containerSelect(form,parents[count][j],offset,picked);
13692:                         }
13693:                     }
13694:                 }
13695:             }
13696:         }
13697:     }
13698: }
13699: 
13700: function titleCheck(form,count,offset) {
13701:     if (count > 0) {
13702:         var chosen = (offset+$startcount)+7*(count-1);
13703:         var depitem = $startcount + ((count-1) * 7) + 2;
13704:         var currtype = form.elements[depitem].type;
13705:         if (form.elements[chosen].value == 'display') {
13706:             document.getElementById('arc_title_'+count).style.display='block';
13707:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13708:                 document.getElementById('archive_title_'+count).value=maintitle;
13709:             }
13710:         } else {
13711:             document.getElementById('arc_title_'+count).style.display='none';
13712:             if (currtype == 'text') { 
13713:                 document.getElementById('archive_title_'+count).value='';
13714:             }
13715:         }
13716:     }
13717:     return;
13718: }
13719: 
13720: // ]]>
13721: </script>
13722: END
13723:     return $scripttag;
13724: }
13725: 
13726: sub process_extracted_files {
13727:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13728:     my $numitems = $env{'form.archive_count'};
13729:     return if ((!$numitems) || ($numitems =~ /\D/));
13730:     my @ids=&Apache::lonnet::current_machine_ids();
13731:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13732:         %folders,%containers,%mapinner,%prompttofetch);
13733:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13734:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13735:         $prefix = &LONCAPA::propath($docudom,$docuname);
13736:         $pathtocheck = "$dir_root/$destination";
13737:         $dir = $dir_root;
13738:         $ishome = 1;
13739:     } else {
13740:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13741:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13742:         $dir = "$dir_root/$docudom/$docuname";
13743:     }
13744:     my $currdir = "$dir_root/$destination";
13745:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13746:     if ($env{'form.folderpath'}) {
13747:         my @items = split('&',$env{'form.folderpath'});
13748:         $folders{'0'} = $items[-2];
13749:         if ($env{'form.folderpath'} =~ /\:1$/) {
13750:             $containers{'0'}='page';
13751:         } else {
13752:             $containers{'0'}='sequence';
13753:         }
13754:     }
13755:     my @archdirs = &get_env_multiple('form.archive_directory');
13756:     if ($numitems) {
13757:         for (my $i=1; $i<=$numitems; $i++) {
13758:             my $path = $env{'form.archive_content_'.$i};
13759:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13760:                 my $item = $1;
13761:                 $toplevelitems{$item} = $i;
13762:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13763:                     $is_dir{$item} = 1;
13764:                 }
13765:             }
13766:         }
13767:     }
13768:     my ($output,%children,%parent,%titles,%dirorder,$result);
13769:     if (keys(%toplevelitems) > 0) {
13770:         my @contents = sort(keys(%toplevelitems));
13771:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13772:                                            \%parent,\@contents,\%dirorder,\%titles);
13773:     }
13774:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13775:     if ($numitems) {
13776:         for (my $i=1; $i<=$numitems; $i++) {
13777:             next if ($env{'form.archive_'.$i} eq 'dependency');
13778:             my $path = $env{'form.archive_content_'.$i};
13779:             if ($path =~ /^\Q$pathtocheck\E/) {
13780:                 if ($env{'form.archive_'.$i} eq 'discard') {
13781:                     if ($prefix ne '' && $path ne '') {
13782:                         if (-e $prefix.$path) {
13783:                             if ((@archdirs > 0) && 
13784:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13785:                                 $todeletedir{$prefix.$path} = 1;
13786:                             } else {
13787:                                 $todelete{$prefix.$path} = 1;
13788:                             }
13789:                         }
13790:                     }
13791:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13792:                     my ($docstitle,$title,$url,$outer);
13793:                     ($title) = ($path =~ m{/([^/]+)$});
13794:                     $docstitle = $env{'form.archive_title_'.$i};
13795:                     if ($docstitle eq '') {
13796:                         $docstitle = $title;
13797:                     }
13798:                     $outer = 0;
13799:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13800:                         if (@{$dirorder{$i}} > 0) {
13801:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13802:                                 if ($env{'form.archive_'.$item} eq 'display') {
13803:                                     $outer = $item;
13804:                                     last;
13805:                                 }
13806:                             }
13807:                         }
13808:                     }
13809:                     my ($errtext,$fatal) = 
13810:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13811:                                                '/'.$folders{$outer}.'.'.
13812:                                                $containers{$outer});
13813:                     next if ($fatal);
13814:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13815:                         if ($context eq 'coursedocs') {
13816:                             $mapinner{$i} = time;
13817:                             $folders{$i} = 'default_'.$mapinner{$i};
13818:                             $containers{$i} = 'sequence';
13819:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13820:                                       $folders{$i}.'.'.$containers{$i};
13821:                             my $newidx = &LONCAPA::map::getresidx();
13822:                             $LONCAPA::map::resources[$newidx]=
13823:                                 $docstitle.':'.$url.':false:normal:res';
13824:                             push(@LONCAPA::map::order,$newidx);
13825:                             my ($outtext,$errtext) =
13826:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13827:                                                         $docuname.'/'.$folders{$outer}.
13828:                                                         '.'.$containers{$outer},1,1);
13829:                             $newseqid{$i} = $newidx;
13830:                             unless ($errtext) {
13831:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13832:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
13833:                                             '</li>'."\n";
13834:                             }
13835:                         }
13836:                     } else {
13837:                         if ($context eq 'coursedocs') {
13838:                             my $newidx=&LONCAPA::map::getresidx();
13839:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13840:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13841:                                       $title;
13842:                             if (($outer !~ /\D/) &&
13843:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
13844:                                 ($newidx !~ /\D/)) {
13845:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13846:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13847:                                 }
13848:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13849:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13850:                                 }
13851:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13852:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13853:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13854:                                         unless ($ishome) {
13855:                                             my $fetch = "$newdest{$i}/$title";
13856:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13857:                                             $prompttofetch{$fetch} = 1;
13858:                                         }
13859:                                    }
13860:                                 }
13861:                                 $LONCAPA::map::resources[$newidx]=
13862:                                     $docstitle.':'.$url.':false:normal:res';
13863:                                 push(@LONCAPA::map::order, $newidx);
13864:                                 my ($outtext,$errtext)=
13865:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13866:                                                             $docuname.'/'.$folders{$outer}.
13867:                                                             '.'.$containers{$outer},1,1);
13868:                                 unless ($errtext) {
13869:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13870:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13871:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13872:                                                    '</li>'."\n";
13873:                                     }
13874:                                 }
13875:                             } else {
13876:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13877:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13878:                             }
13879:                         }
13880:                     }
13881:                 }
13882:             } else {
13883:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13884:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13885:             }
13886:         }
13887:         for (my $i=1; $i<=$numitems; $i++) {
13888:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13889:             my $path = $env{'form.archive_content_'.$i};
13890:             if ($path =~ /^\Q$pathtocheck\E/) {
13891:                 my ($title) = ($path =~ m{/([^/]+)$});
13892:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13893:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13894:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13895:                         my ($itemidx,$fullpath,$relpath);
13896:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13897:                             my $container = $dirorder{$referrer{$i}}->[-1];
13898:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13899:                                 if ($dirorder{$i}->[$j] eq $container) {
13900:                                     $itemidx = $j;
13901:                                 }
13902:                             }
13903:                         }
13904:                         if ($itemidx eq '') {
13905:                             $itemidx =  0;
13906:                         }
13907:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13908:                             if ($mapinner{$referrer{$i}}) {
13909:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13910:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13911:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13912:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13913:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13914:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13915:                                             if (!-e $fullpath) {
13916:                                                 mkdir($fullpath,0755);
13917:                                             }
13918:                                         }
13919:                                     } else {
13920:                                         last;
13921:                                     }
13922:                                 }
13923:                             }
13924:                         } elsif ($newdest{$referrer{$i}}) {
13925:                             $fullpath = $newdest{$referrer{$i}};
13926:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13927:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13928:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13929:                                     last;
13930:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13931:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13932:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13933:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13934:                                         if (!-e $fullpath) {
13935:                                             mkdir($fullpath,0755);
13936:                                         }
13937:                                     }
13938:                                 } else {
13939:                                     last;
13940:                                 }
13941:                             }
13942:                         }
13943:                         if ($fullpath ne '') {
13944:                             if (-e "$prefix$path") {
13945:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13946:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13947:                                 }
13948:                             }
13949:                             if (-e "$fullpath/$title") {
13950:                                 my $showpath;
13951:                                 if ($relpath ne '') {
13952:                                     $showpath = "$relpath/$title";
13953:                                 } else {
13954:                                     $showpath = "/$title";
13955:                                 }
13956:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13957:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13958:                                            '</li>'."\n";
13959:                                 unless ($ishome) {
13960:                                     my $fetch = "$fullpath/$title";
13961:                                     $fetch =~ s/^\Q$prefix$dir\E//;
13962:                                     $prompttofetch{$fetch} = 1;
13963:                                 }
13964:                             }
13965:                         }
13966:                     }
13967:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13968:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13969:                                     &HTML::Entities::encode($path,'<>&"'),
13970:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13971:                                 '<br />';
13972:                 }
13973:             } else {
13974:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13975:                                 &HTML::Entities::encode($path)).'<br />';
13976:             }
13977:         }
13978:         if (keys(%todelete)) {
13979:             foreach my $key (keys(%todelete)) {
13980:                 unlink($key);
13981:             }
13982:         }
13983:         if (keys(%todeletedir)) {
13984:             foreach my $key (keys(%todeletedir)) {
13985:                 rmdir($key);
13986:             }
13987:         }
13988:         foreach my $dir (sort(keys(%is_dir))) {
13989:             if (($pathtocheck ne '') && ($dir ne ''))  {
13990:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13991:             }
13992:         }
13993:         if ($result ne '') {
13994:             $output .= '<ul>'."\n".
13995:                        $result."\n".
13996:                        '</ul>';
13997:         }
13998:         unless ($ishome) {
13999:             my $replicationfail;
14000:             foreach my $item (keys(%prompttofetch)) {
14001:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14002:                 unless ($fetchresult eq 'ok') {
14003:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
14004:                 }
14005:             }
14006:             if ($replicationfail) {
14007:                 $output .= '<p class="LC_error">'.
14008:                            &mt('Course home server failed to retrieve:').'<ul>'.
14009:                            $replicationfail.
14010:                            '</ul></p>';
14011:             }
14012:         }
14013:     } else {
14014:         $warning = &mt('No items found in archive.');
14015:     }
14016:     if ($error) {
14017:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14018:                    $error.'</p>'."\n";
14019:     }
14020:     if ($warning) {
14021:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14022:     }
14023:     return $output;
14024: }
14025: 
14026: sub cleanup_empty_dirs {
14027:     my ($path) = @_;
14028:     if (($path ne '') && (-d $path)) {
14029:         if (opendir(my $dirh,$path)) {
14030:             my @dircontents = grep(!/^\./,readdir($dirh));
14031:             my $numitems = 0;
14032:             foreach my $item (@dircontents) {
14033:                 if (-d "$path/$item") {
14034:                     &cleanup_empty_dirs("$path/$item");
14035:                     if (-e "$path/$item") {
14036:                         $numitems ++;
14037:                     }
14038:                 } else {
14039:                     $numitems ++;
14040:                 }
14041:             }
14042:             if ($numitems == 0) {
14043:                 rmdir($path);
14044:             }
14045:             closedir($dirh);
14046:         }
14047:     }
14048:     return;
14049: }
14050: 
14051: =pod
14052: 
14053: =item * &get_folder_hierarchy()
14054: 
14055: Provides hierarchy of names of folders/sub-folders containing the current
14056: item,
14057: 
14058: Inputs: 3
14059:      - $navmap - navmaps object
14060: 
14061:      - $map - url for map (either the trigger itself, or map containing
14062:                            the resource, which is the trigger).
14063: 
14064:      - $showitem - 1 => show title for map itself; 0 => do not show.
14065: 
14066: Outputs: 1 @pathitems - array of folder/subfolder names.
14067: 
14068: =cut
14069: 
14070: sub get_folder_hierarchy {
14071:     my ($navmap,$map,$showitem) = @_;
14072:     my @pathitems;
14073:     if (ref($navmap)) {
14074:         my $mapres = $navmap->getResourceByUrl($map);
14075:         if (ref($mapres)) {
14076:             my $pcslist = $mapres->map_hierarchy();
14077:             if ($pcslist ne '') {
14078:                 my @pcs = split(/,/,$pcslist);
14079:                 foreach my $pc (@pcs) {
14080:                     if ($pc == 1) {
14081:                         push(@pathitems,&mt('Main Content'));
14082:                     } else {
14083:                         my $res = $navmap->getByMapPc($pc);
14084:                         if (ref($res)) {
14085:                             my $title = $res->compTitle();
14086:                             $title =~ s/\W+/_/g;
14087:                             if ($title ne '') {
14088:                                 push(@pathitems,$title);
14089:                             }
14090:                         }
14091:                     }
14092:                 }
14093:             }
14094:             if ($showitem) {
14095:                 if ($mapres->{ID} eq '0.0') {
14096:                     push(@pathitems,&mt('Main Content'));
14097:                 } else {
14098:                     my $maptitle = $mapres->compTitle();
14099:                     $maptitle =~ s/\W+/_/g;
14100:                     if ($maptitle ne '') {
14101:                         push(@pathitems,$maptitle);
14102:                     }
14103:                 }
14104:             }
14105:         }
14106:     }
14107:     return @pathitems;
14108: }
14109: 
14110: =pod
14111: 
14112: =item * &get_turnedin_filepath()
14113: 
14114: Determines path in a user's portfolio file for storage of files uploaded
14115: to a specific essayresponse or dropbox item.
14116: 
14117: Inputs: 3 required + 1 optional.
14118: $symb is symb for resource, $uname and $udom are for current user (required).
14119: $caller is optional (can be "submission", if routine is called when storing
14120: an upoaded file when "Submit Answer" button was pressed).
14121: 
14122: Returns array containing $path and $multiresp. 
14123: $path is path in portfolio.  $multiresp is 1 if this resource contains more
14124: than one file upload item.  Callers of routine should append partid as a 
14125: subdirectory to $path in cases where $multiresp is 1.
14126: 
14127: Called by: homework/essayresponse.pm and homework/structuretags.pm
14128: 
14129: =cut
14130: 
14131: sub get_turnedin_filepath {
14132:     my ($symb,$uname,$udom,$caller) = @_;
14133:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14134:     my $turnindir;
14135:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14136:     $turnindir = $userhash{'turnindir'};
14137:     my ($path,$multiresp);
14138:     if ($turnindir eq '') {
14139:         if ($caller eq 'submission') {
14140:             $turnindir = &mt('turned in');
14141:             $turnindir =~ s/\W+/_/g;
14142:             my %newhash = (
14143:                             'turnindir' => $turnindir,
14144:                           );
14145:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14146:         }
14147:     }
14148:     if ($turnindir ne '') {
14149:         $path = '/'.$turnindir.'/';
14150:         my ($multipart,$turnin,@pathitems);
14151:         my $navmap = Apache::lonnavmaps::navmap->new();
14152:         if (defined($navmap)) {
14153:             my $mapres = $navmap->getResourceByUrl($map);
14154:             if (ref($mapres)) {
14155:                 my $pcslist = $mapres->map_hierarchy();
14156:                 if ($pcslist ne '') {
14157:                     foreach my $pc (split(/,/,$pcslist)) {
14158:                         my $res = $navmap->getByMapPc($pc);
14159:                         if (ref($res)) {
14160:                             my $title = $res->compTitle();
14161:                             $title =~ s/\W+/_/g;
14162:                             if ($title ne '') {
14163:                                 if (($pc > 1) && (length($title) > 12)) {
14164:                                     $title = substr($title,0,12);
14165:                                 }
14166:                                 push(@pathitems,$title);
14167:                             }
14168:                         }
14169:                     }
14170:                 }
14171:                 my $maptitle = $mapres->compTitle();
14172:                 $maptitle =~ s/\W+/_/g;
14173:                 if ($maptitle ne '') {
14174:                     if (length($maptitle) > 12) {
14175:                         $maptitle = substr($maptitle,0,12);
14176:                     }
14177:                     push(@pathitems,$maptitle);
14178:                 }
14179:                 unless ($env{'request.state'} eq 'construct') {
14180:                     my $res = $navmap->getBySymb($symb);
14181:                     if (ref($res)) {
14182:                         my $partlist = $res->parts();
14183:                         my $totaluploads = 0;
14184:                         if (ref($partlist) eq 'ARRAY') {
14185:                             foreach my $part (@{$partlist}) {
14186:                                 my @types = $res->responseType($part);
14187:                                 my @ids = $res->responseIds($part);
14188:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14189:                                     if ($types[$i] eq 'essay') {
14190:                                         my $partid = $part.'_'.$ids[$i];
14191:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14192:                                             $totaluploads ++;
14193:                                         }
14194:                                     }
14195:                                 }
14196:                             }
14197:                             if ($totaluploads > 1) {
14198:                                 $multiresp = 1;
14199:                             }
14200:                         }
14201:                     }
14202:                 }
14203:             } else {
14204:                 return;
14205:             }
14206:         } else {
14207:             return;
14208:         }
14209:         my $restitle=&Apache::lonnet::gettitle($symb);
14210:         $restitle =~ s/\W+/_/g;
14211:         if ($restitle eq '') {
14212:             $restitle = ($resurl =~ m{/[^/]+$});
14213:             if ($restitle eq '') {
14214:                 $restitle = time;
14215:             }
14216:         }
14217:         if (length($restitle) > 12) {
14218:             $restitle = substr($restitle,0,12);
14219:         }
14220:         push(@pathitems,$restitle);
14221:         $path .= join('/',@pathitems);
14222:     }
14223:     return ($path,$multiresp);
14224: }
14225: 
14226: =pod
14227: 
14228: =back
14229: 
14230: =head1 CSV Upload/Handling functions
14231: 
14232: =over 4
14233: 
14234: =item * &upfile_store($r)
14235: 
14236: Store uploaded file, $r should be the HTTP Request object,
14237: needs $env{'form.upfile'}
14238: returns $datatoken to be put into hidden field
14239: 
14240: =cut
14241: 
14242: sub upfile_store {
14243:     my $r=shift;
14244:     $env{'form.upfile'}=~s/\r/\n/gs;
14245:     $env{'form.upfile'}=~s/\f/\n/gs;
14246:     $env{'form.upfile'}=~s/\n+/\n/gs;
14247:     $env{'form.upfile'}=~s/\n+$//gs;
14248: 
14249:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14250:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14251:                                      time.'_'.$$);
14252:     return if ($datatoken eq '');
14253: 
14254:     {
14255:         my $datafile = $r->dir_config('lonDaemons').
14256:                            '/tmp/'.$datatoken.'.tmp';
14257:         if ( open(my $fh,'>',$datafile) ) {
14258:             print $fh $env{'form.upfile'};
14259:             close($fh);
14260:         }
14261:     }
14262:     return $datatoken;
14263: }
14264: 
14265: =pod
14266: 
14267: =item * &load_tmp_file($r,$datatoken)
14268: 
14269: Load uploaded file from tmp, $r should be the HTTP Request object,
14270: $datatoken is the name to assign to the temporary file.
14271: sets $env{'form.upfile'} to the contents of the file
14272: 
14273: =cut
14274: 
14275: sub load_tmp_file {
14276:     my ($r,$datatoken) = @_;
14277:     return if ($datatoken eq '');
14278:     my @studentdata=();
14279:     {
14280:         my $studentfile = $r->dir_config('lonDaemons').
14281:                               '/tmp/'.$datatoken.'.tmp';
14282:         if ( open(my $fh,'<',$studentfile) ) {
14283:             @studentdata=<$fh>;
14284:             close($fh);
14285:         }
14286:     }
14287:     $env{'form.upfile'}=join('',@studentdata);
14288: }
14289: 
14290: sub valid_datatoken {
14291:     my ($datatoken) = @_;
14292:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14293:         return $datatoken;
14294:     }
14295:     return;
14296: }
14297: 
14298: =pod
14299: 
14300: =item * &upfile_record_sep()
14301: 
14302: Separate uploaded file into records
14303: returns array of records,
14304: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14305: 
14306: =cut
14307: 
14308: sub upfile_record_sep {
14309:     if ($env{'form.upfiletype'} eq 'xml') {
14310:     } else {
14311: 	my @records;
14312: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14313: 	    if ($line=~/^\s*$/) { next; }
14314: 	    push(@records,$line);
14315: 	}
14316: 	return @records;
14317:     }
14318: }
14319: 
14320: =pod
14321: 
14322: =item * &record_sep($record)
14323: 
14324: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14325: 
14326: =cut
14327: 
14328: sub takeleft {
14329:     my $index=shift;
14330:     return substr('0000'.$index,-4,4);
14331: }
14332: 
14333: sub record_sep {
14334:     my $record=shift;
14335:     my %components=();
14336:     if ($env{'form.upfiletype'} eq 'xml') {
14337:     } elsif ($env{'form.upfiletype'} eq 'space') {
14338:         my $i=0;
14339:         foreach my $field (split(/\s+/,$record)) {
14340:             $field=~s/^(\"|\')//;
14341:             $field=~s/(\"|\')$//;
14342:             $components{&takeleft($i)}=$field;
14343:             $i++;
14344:         }
14345:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14346:         my $i=0;
14347:         foreach my $field (split(/\t/,$record)) {
14348:             $field=~s/^(\"|\')//;
14349:             $field=~s/(\"|\')$//;
14350:             $components{&takeleft($i)}=$field;
14351:             $i++;
14352:         }
14353:     } else {
14354:         my $separator=',';
14355:         if ($env{'form.upfiletype'} eq 'semisv') {
14356:             $separator=';';
14357:         }
14358:         my $i=0;
14359: # the character we are looking for to indicate the end of a quote or a record 
14360:         my $looking_for=$separator;
14361: # do not add the characters to the fields
14362:         my $ignore=0;
14363: # we just encountered a separator (or the beginning of the record)
14364:         my $just_found_separator=1;
14365: # store the field we are working on here
14366:         my $field='';
14367: # work our way through all characters in record
14368:         foreach my $character ($record=~/(.)/g) {
14369:             if ($character eq $looking_for) {
14370:                if ($character ne $separator) {
14371: # Found the end of a quote, again looking for separator
14372:                   $looking_for=$separator;
14373:                   $ignore=1;
14374:                } else {
14375: # Found a separator, store away what we got
14376:                   $components{&takeleft($i)}=$field;
14377: 	          $i++;
14378:                   $just_found_separator=1;
14379:                   $ignore=0;
14380:                   $field='';
14381:                }
14382:                next;
14383:             }
14384: # single or double quotation marks after a separator indicate beginning of a quote
14385: # we are now looking for the end of the quote and need to ignore separators
14386:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
14387:                $looking_for=$character;
14388:                next;
14389:             }
14390: # ignore would be true after we reached the end of a quote
14391:             if ($ignore) { next; }
14392:             if (($just_found_separator) && ($character=~/\s/)) { next; }
14393:             $field.=$character;
14394:             $just_found_separator=0; 
14395:         }
14396: # catch the very last entry, since we never encountered the separator
14397:         $components{&takeleft($i)}=$field;
14398:     }
14399:     return %components;
14400: }
14401: 
14402: ######################################################
14403: ######################################################
14404: 
14405: =pod
14406: 
14407: =item * &upfile_select_html()
14408: 
14409: Return HTML code to select a file from the users machine and specify 
14410: the file type.
14411: 
14412: =cut
14413: 
14414: ######################################################
14415: ######################################################
14416: sub upfile_select_html {
14417:     my %Types = (
14418:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
14419:                  semisv => &mt('Semicolon separated values'),
14420:                  space => &mt('Space separated'),
14421:                  tab   => &mt('Tabulator separated'),
14422: #                 xml   => &mt('HTML/XML'),
14423:                  );
14424:     my $Str = '<input type="file" name="upfile" size="50" />'.
14425:         '<br />'.&mt('Type').': <select name="upfiletype">';
14426:     foreach my $type (sort(keys(%Types))) {
14427:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14428:     }
14429:     $Str .= "</select>\n";
14430:     return $Str;
14431: }
14432: 
14433: sub get_samples {
14434:     my ($records,$toget) = @_;
14435:     my @samples=({});
14436:     my $got=0;
14437:     foreach my $rec (@$records) {
14438: 	my %temp = &record_sep($rec);
14439: 	if (! grep(/\S/, values(%temp))) { next; }
14440: 	if (%temp) {
14441: 	    $samples[$got]=\%temp;
14442: 	    $got++;
14443: 	    if ($got == $toget) { last; }
14444: 	}
14445:     }
14446:     return \@samples;
14447: }
14448: 
14449: ######################################################
14450: ######################################################
14451: 
14452: =pod
14453: 
14454: =item * &csv_print_samples($r,$records)
14455: 
14456: Prints a table of sample values from each column uploaded $r is an
14457: Apache Request ref, $records is an arrayref from
14458: &Apache::loncommon::upfile_record_sep
14459: 
14460: =cut
14461: 
14462: ######################################################
14463: ######################################################
14464: sub csv_print_samples {
14465:     my ($r,$records) = @_;
14466:     my $samples = &get_samples($records,5);
14467: 
14468:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14469:               &start_data_table_header_row());
14470:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14471:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14472:     $r->print(&end_data_table_header_row());
14473:     foreach my $hash (@$samples) {
14474: 	$r->print(&start_data_table_row());
14475: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14476: 	    $r->print('<td>');
14477: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14478: 	    $r->print('</td>');
14479: 	}
14480: 	$r->print(&end_data_table_row());
14481:     }
14482:     $r->print(&end_data_table().'<br />'."\n");
14483: }
14484: 
14485: ######################################################
14486: ######################################################
14487: 
14488: =pod
14489: 
14490: =item * &csv_print_select_table($r,$records,$d)
14491: 
14492: Prints a table to create associations between values and table columns.
14493: 
14494: $r is an Apache Request ref,
14495: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14496: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14497: 
14498: =cut
14499: 
14500: ######################################################
14501: ######################################################
14502: sub csv_print_select_table {
14503:     my ($r,$records,$d) = @_;
14504:     my $i=0;
14505:     my $samples = &get_samples($records,1);
14506:     $r->print(&mt('Associate columns with student attributes.')."\n".
14507: 	      &start_data_table().&start_data_table_header_row().
14508:               '<th>'.&mt('Attribute').'</th>'.
14509:               '<th>'.&mt('Column').'</th>'.
14510:               &end_data_table_header_row()."\n");
14511:     foreach my $array_ref (@$d) {
14512: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14513: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14514: 
14515: 	$r->print('<td><select name="f'.$i.'"'.
14516: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14517: 	$r->print('<option value="none"></option>');
14518: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14519: 	    $r->print('<option value="'.$sample.'"'.
14520:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14521:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14522: 	}
14523: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14524: 	$i++;
14525:     }
14526:     $r->print(&end_data_table());
14527:     $i--;
14528:     return $i;
14529: }
14530: 
14531: ######################################################
14532: ######################################################
14533: 
14534: =pod
14535: 
14536: =item * &csv_samples_select_table($r,$records,$d)
14537: 
14538: Prints a table of sample values from the upload and can make associate samples to internal names.
14539: 
14540: $r is an Apache Request ref,
14541: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14542: $d is an array of 2 element arrays (internal name, displayed name)
14543: 
14544: =cut
14545: 
14546: ######################################################
14547: ######################################################
14548: sub csv_samples_select_table {
14549:     my ($r,$records,$d) = @_;
14550:     my $i=0;
14551:     #
14552:     my $max_samples = 5;
14553:     my $samples = &get_samples($records,$max_samples);
14554:     $r->print(&start_data_table().
14555:               &start_data_table_header_row().'<th>'.
14556:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14557:               &end_data_table_header_row());
14558: 
14559:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
14560: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14561: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14562: 	foreach my $option (@$d) {
14563: 	    my ($value,$display,$defaultcol)=@{ $option };
14564: 	    $r->print('<option value="'.$value.'"'.
14565:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14566:                       $display.'</option>');
14567: 	}
14568: 	$r->print('</select></td><td>');
14569: 	foreach my $line (0..($max_samples-1)) {
14570: 	    if (defined($samples->[$line]{$key})) { 
14571: 		$r->print($samples->[$line]{$key}."<br />\n"); 
14572: 	    }
14573: 	}
14574: 	$r->print('</td>'.&end_data_table_row());
14575: 	$i++;
14576:     }
14577:     $r->print(&end_data_table());
14578:     $i--;
14579:     return($i);
14580: }
14581: 
14582: ######################################################
14583: ######################################################
14584: 
14585: =pod
14586: 
14587: =item * &clean_excel_name($name)
14588: 
14589: Returns a replacement for $name which does not contain any illegal characters.
14590: 
14591: =cut
14592: 
14593: ######################################################
14594: ######################################################
14595: sub clean_excel_name {
14596:     my ($name) = @_;
14597:     $name =~ s/[:\*\?\/\\]//g;
14598:     if (length($name) > 31) {
14599:         $name = substr($name,0,31);
14600:     }
14601:     return $name;
14602: }
14603: 
14604: =pod
14605: 
14606: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14607: 
14608: Returns either 1 or undef
14609: 
14610: 1 if the part is to be hidden, undef if it is to be shown
14611: 
14612: Arguments are:
14613: 
14614: $id the id of the part to be checked
14615: $symb, optional the symb of the resource to check
14616: $udom, optional the domain of the user to check for
14617: $uname, optional the username of the user to check for
14618: 
14619: =cut
14620: 
14621: sub check_if_partid_hidden {
14622:     my ($id,$symb,$udom,$uname) = @_;
14623:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14624: 					 $symb,$udom,$uname);
14625:     my $truth=1;
14626:     #if the string starts with !, then the list is the list to show not hide
14627:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14628:     my @hiddenlist=split(/,/,$hiddenparts);
14629:     foreach my $checkid (@hiddenlist) {
14630: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14631:     }
14632:     return !$truth;
14633: }
14634: 
14635: 
14636: ############################################################
14637: ############################################################
14638: 
14639: =pod
14640: 
14641: =back 
14642: 
14643: =head1 cgi-bin script and graphing routines
14644: 
14645: =over 4
14646: 
14647: =item * &get_cgi_id()
14648: 
14649: Inputs: none
14650: 
14651: Returns an id which can be used to pass environment variables
14652: to various cgi-bin scripts.  These environment variables will
14653: be removed from the users environment after a given time by
14654: the routine &Apache::lonnet::transfer_profile_to_env.
14655: 
14656: =cut
14657: 
14658: ############################################################
14659: ############################################################
14660: my $uniq=0;
14661: sub get_cgi_id {
14662:     $uniq=($uniq+1)%100000;
14663:     return (time.'_'.$$.'_'.$uniq);
14664: }
14665: 
14666: ############################################################
14667: ############################################################
14668: 
14669: =pod
14670: 
14671: =item * &DrawBarGraph()
14672: 
14673: Facilitates the plotting of data in a (stacked) bar graph.
14674: Puts plot definition data into the users environment in order for 
14675: graph.png to plot it.  Returns an <img> tag for the plot.
14676: The bars on the plot are labeled '1','2',...,'n'.
14677: 
14678: Inputs:
14679: 
14680: =over 4
14681: 
14682: =item $Title: string, the title of the plot
14683: 
14684: =item $xlabel: string, text describing the X-axis of the plot
14685: 
14686: =item $ylabel: string, text describing the Y-axis of the plot
14687: 
14688: =item $Max: scalar, the maximum Y value to use in the plot
14689: If $Max is < any data point, the graph will not be rendered.
14690: 
14691: =item $colors: array ref holding the colors to be used for the data sets when
14692: they are plotted.  If undefined, default values will be used.
14693: 
14694: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14695: 
14696: =item @Values: An array of array references.  Each array reference holds data
14697: to be plotted in a stacked bar chart.
14698: 
14699: =item If the final element of @Values is a hash reference the key/value
14700: pairs will be added to the graph definition.
14701: 
14702: =back
14703: 
14704: Returns:
14705: 
14706: An <img> tag which references graph.png and the appropriate identifying
14707: information for the plot.
14708: 
14709: =cut
14710: 
14711: ############################################################
14712: ############################################################
14713: sub DrawBarGraph {
14714:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14715:     #
14716:     if (! defined($colors)) {
14717:         $colors = ['#33ff00', 
14718:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14719:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14720:                   ]; 
14721:     }
14722:     my $extra_settings = {};
14723:     if (ref($Values[-1]) eq 'HASH') {
14724:         $extra_settings = pop(@Values);
14725:     }
14726:     #
14727:     my $identifier = &get_cgi_id();
14728:     my $id = 'cgi.'.$identifier;        
14729:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14730:         return '';
14731:     }
14732:     #
14733:     my @Labels;
14734:     if (defined($labels)) {
14735:         @Labels = @$labels;
14736:     } else {
14737:         for (my $i=0;$i<@{$Values[0]};$i++) {
14738:             push(@Labels,$i+1);
14739:         }
14740:     }
14741:     #
14742:     my $NumBars = scalar(@{$Values[0]});
14743:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14744:     my %ValuesHash;
14745:     my $NumSets=1;
14746:     foreach my $array (@Values) {
14747:         next if (! ref($array));
14748:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14749:             join(',',@$array);
14750:     }
14751:     #
14752:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14753:     if ($NumBars < 3) {
14754:         $width = 120+$NumBars*32;
14755:         $xskip = 1;
14756:         $bar_width = 30;
14757:     } elsif ($NumBars < 5) {
14758:         $width = 120+$NumBars*20;
14759:         $xskip = 1;
14760:         $bar_width = 20;
14761:     } elsif ($NumBars < 10) {
14762:         $width = 120+$NumBars*15;
14763:         $xskip = 1;
14764:         $bar_width = 15;
14765:     } elsif ($NumBars <= 25) {
14766:         $width = 120+$NumBars*11;
14767:         $xskip = 5;
14768:         $bar_width = 8;
14769:     } elsif ($NumBars <= 50) {
14770:         $width = 120+$NumBars*8;
14771:         $xskip = 5;
14772:         $bar_width = 4;
14773:     } else {
14774:         $width = 120+$NumBars*8;
14775:         $xskip = 5;
14776:         $bar_width = 4;
14777:     }
14778:     #
14779:     $Max = 1 if ($Max < 1);
14780:     if ( int($Max) < $Max ) {
14781:         $Max++;
14782:         $Max = int($Max);
14783:     }
14784:     $Title  = '' if (! defined($Title));
14785:     $xlabel = '' if (! defined($xlabel));
14786:     $ylabel = '' if (! defined($ylabel));
14787:     $ValuesHash{$id.'.title'}    = &escape($Title);
14788:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14789:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14790:     $ValuesHash{$id.'.y_max_value'} = $Max;
14791:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14792:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14793:     $ValuesHash{$id.'.PlotType'} = 'bar';
14794:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14795:     $ValuesHash{$id.'.height'}   = $height;
14796:     $ValuesHash{$id.'.width'}    = $width;
14797:     $ValuesHash{$id.'.xskip'}    = $xskip;
14798:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14799:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14800:     #
14801:     # Deal with other parameters
14802:     while (my ($key,$value) = each(%$extra_settings)) {
14803:         $ValuesHash{$id.'.'.$key} = $value;
14804:     }
14805:     #
14806:     &Apache::lonnet::appenv(\%ValuesHash);
14807:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14808: }
14809: 
14810: ############################################################
14811: ############################################################
14812: 
14813: =pod
14814: 
14815: =item * &DrawXYGraph()
14816: 
14817: Facilitates the plotting of data in an XY graph.
14818: Puts plot definition data into the users environment in order for 
14819: graph.png to plot it.  Returns an <img> tag for the plot.
14820: 
14821: Inputs:
14822: 
14823: =over 4
14824: 
14825: =item $Title: string, the title of the plot
14826: 
14827: =item $xlabel: string, text describing the X-axis of the plot
14828: 
14829: =item $ylabel: string, text describing the Y-axis of the plot
14830: 
14831: =item $Max: scalar, the maximum Y value to use in the plot
14832: If $Max is < any data point, the graph will not be rendered.
14833: 
14834: =item $colors: Array ref containing the hex color codes for the data to be 
14835: plotted in.  If undefined, default values will be used.
14836: 
14837: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14838: 
14839: =item $Ydata: Array ref containing Array refs.  
14840: Each of the contained arrays will be plotted as a separate curve.
14841: 
14842: =item %Values: hash indicating or overriding any default values which are 
14843: passed to graph.png.  
14844: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14845: 
14846: =back
14847: 
14848: Returns:
14849: 
14850: An <img> tag which references graph.png and the appropriate identifying
14851: information for the plot.
14852: 
14853: =cut
14854: 
14855: ############################################################
14856: ############################################################
14857: sub DrawXYGraph {
14858:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14859:     #
14860:     # Create the identifier for the graph
14861:     my $identifier = &get_cgi_id();
14862:     my $id = 'cgi.'.$identifier;
14863:     #
14864:     $Title  = '' if (! defined($Title));
14865:     $xlabel = '' if (! defined($xlabel));
14866:     $ylabel = '' if (! defined($ylabel));
14867:     my %ValuesHash = 
14868:         (
14869:          $id.'.title'  => &escape($Title),
14870:          $id.'.xlabel' => &escape($xlabel),
14871:          $id.'.ylabel' => &escape($ylabel),
14872:          $id.'.y_max_value'=> $Max,
14873:          $id.'.labels'     => join(',',@$Xlabels),
14874:          $id.'.PlotType'   => 'XY',
14875:          );
14876:     #
14877:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14878:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14879:     }
14880:     #
14881:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14882:         return '';
14883:     }
14884:     my $NumSets=1;
14885:     foreach my $array (@{$Ydata}){
14886:         next if (! ref($array));
14887:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14888:     }
14889:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14890:     #
14891:     # Deal with other parameters
14892:     while (my ($key,$value) = each(%Values)) {
14893:         $ValuesHash{$id.'.'.$key} = $value;
14894:     }
14895:     #
14896:     &Apache::lonnet::appenv(\%ValuesHash);
14897:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14898: }
14899: 
14900: ############################################################
14901: ############################################################
14902: 
14903: =pod
14904: 
14905: =item * &DrawXYYGraph()
14906: 
14907: Facilitates the plotting of data in an XY graph with two Y axes.
14908: Puts plot definition data into the users environment in order for 
14909: graph.png to plot it.  Returns an <img> tag for the plot.
14910: 
14911: Inputs:
14912: 
14913: =over 4
14914: 
14915: =item $Title: string, the title of the plot
14916: 
14917: =item $xlabel: string, text describing the X-axis of the plot
14918: 
14919: =item $ylabel: string, text describing the Y-axis of the plot
14920: 
14921: =item $colors: Array ref containing the hex color codes for the data to be 
14922: plotted in.  If undefined, default values will be used.
14923: 
14924: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14925: 
14926: =item $Ydata1: The first data set
14927: 
14928: =item $Min1: The minimum value of the left Y-axis
14929: 
14930: =item $Max1: The maximum value of the left Y-axis
14931: 
14932: =item $Ydata2: The second data set
14933: 
14934: =item $Min2: The minimum value of the right Y-axis
14935: 
14936: =item $Max2: The maximum value of the left Y-axis
14937: 
14938: =item %Values: hash indicating or overriding any default values which are 
14939: passed to graph.png.  
14940: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14941: 
14942: =back
14943: 
14944: Returns:
14945: 
14946: An <img> tag which references graph.png and the appropriate identifying
14947: information for the plot.
14948: 
14949: =cut
14950: 
14951: ############################################################
14952: ############################################################
14953: sub DrawXYYGraph {
14954:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14955:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14956:     #
14957:     # Create the identifier for the graph
14958:     my $identifier = &get_cgi_id();
14959:     my $id = 'cgi.'.$identifier;
14960:     #
14961:     $Title  = '' if (! defined($Title));
14962:     $xlabel = '' if (! defined($xlabel));
14963:     $ylabel = '' if (! defined($ylabel));
14964:     my %ValuesHash = 
14965:         (
14966:          $id.'.title'  => &escape($Title),
14967:          $id.'.xlabel' => &escape($xlabel),
14968:          $id.'.ylabel' => &escape($ylabel),
14969:          $id.'.labels' => join(',',@$Xlabels),
14970:          $id.'.PlotType' => 'XY',
14971:          $id.'.NumSets' => 2,
14972:          $id.'.two_axes' => 1,
14973:          $id.'.y1_max_value' => $Max1,
14974:          $id.'.y1_min_value' => $Min1,
14975:          $id.'.y2_max_value' => $Max2,
14976:          $id.'.y2_min_value' => $Min2,
14977:          );
14978:     #
14979:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14980:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14981:     }
14982:     #
14983:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14984:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14985:         return '';
14986:     }
14987:     my $NumSets=1;
14988:     foreach my $array ($Ydata1,$Ydata2){
14989:         next if (! ref($array));
14990:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14991:     }
14992:     #
14993:     # Deal with other parameters
14994:     while (my ($key,$value) = each(%Values)) {
14995:         $ValuesHash{$id.'.'.$key} = $value;
14996:     }
14997:     #
14998:     &Apache::lonnet::appenv(\%ValuesHash);
14999:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15000: }
15001: 
15002: ############################################################
15003: ############################################################
15004: 
15005: =pod
15006: 
15007: =back 
15008: 
15009: =head1 Statistics helper routines?  
15010: 
15011: Bad place for them but what the hell.
15012: 
15013: =over 4
15014: 
15015: =item * &chartlink()
15016: 
15017: Returns a link to the chart for a specific student.  
15018: 
15019: Inputs:
15020: 
15021: =over 4
15022: 
15023: =item $linktext: The text of the link
15024: 
15025: =item $sname: The students username
15026: 
15027: =item $sdomain: The students domain
15028: 
15029: =back
15030: 
15031: =back
15032: 
15033: =cut
15034: 
15035: ############################################################
15036: ############################################################
15037: sub chartlink {
15038:     my ($linktext, $sname, $sdomain) = @_;
15039:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15040:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
15041:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
15042:        '">'.$linktext.'</a>';
15043: }
15044: 
15045: #######################################################
15046: #######################################################
15047: 
15048: =pod
15049: 
15050: =head1 Course Environment Routines
15051: 
15052: =over 4
15053: 
15054: =item * &restore_course_settings()
15055: 
15056: =item * &store_course_settings()
15057: 
15058: Restores/Store indicated form parameters from the course environment.
15059: Will not overwrite existing values of the form parameters.
15060: 
15061: Inputs: 
15062: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15063: 
15064: a hash ref describing the data to be stored.  For example:
15065:    
15066: %Save_Parameters = ('Status' => 'scalar',
15067:     'chartoutputmode' => 'scalar',
15068:     'chartoutputdata' => 'scalar',
15069:     'Section' => 'array',
15070:     'Group' => 'array',
15071:     'StudentData' => 'array',
15072:     'Maps' => 'array');
15073: 
15074: Returns: both routines return nothing
15075: 
15076: =back
15077: 
15078: =cut
15079: 
15080: #######################################################
15081: #######################################################
15082: sub store_course_settings {
15083:     return &store_settings($env{'request.course.id'},@_);
15084: }
15085: 
15086: sub store_settings {
15087:     # save to the environment
15088:     # appenv the same items, just to be safe
15089:     my $udom  = $env{'user.domain'};
15090:     my $uname = $env{'user.name'};
15091:     my ($context,$prefix,$Settings) = @_;
15092:     my %SaveHash;
15093:     my %AppHash;
15094:     while (my ($setting,$type) = each(%$Settings)) {
15095:         my $basename = join('.','internal',$context,$prefix,$setting);
15096:         my $envname = 'environment.'.$basename;
15097:         if (exists($env{'form.'.$setting})) {
15098:             # Save this value away
15099:             if ($type eq 'scalar' &&
15100:                 (! exists($env{$envname}) || 
15101:                  $env{$envname} ne $env{'form.'.$setting})) {
15102:                 $SaveHash{$basename} = $env{'form.'.$setting};
15103:                 $AppHash{$envname}   = $env{'form.'.$setting};
15104:             } elsif ($type eq 'array') {
15105:                 my $stored_form;
15106:                 if (ref($env{'form.'.$setting})) {
15107:                     $stored_form = join(',',
15108:                                         map {
15109:                                             &escape($_);
15110:                                         } sort(@{$env{'form.'.$setting}}));
15111:                 } else {
15112:                     $stored_form = 
15113:                         &escape($env{'form.'.$setting});
15114:                 }
15115:                 # Determine if the array contents are the same.
15116:                 if ($stored_form ne $env{$envname}) {
15117:                     $SaveHash{$basename} = $stored_form;
15118:                     $AppHash{$envname}   = $stored_form;
15119:                 }
15120:             }
15121:         }
15122:     }
15123:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15124:                                           $udom,$uname);
15125:     if ($put_result !~ /^(ok|delayed)/) {
15126:         &Apache::lonnet::logthis('unable to save form parameters, '.
15127:                                  'got error:'.$put_result);
15128:     }
15129:     # Make sure these settings stick around in this session, too
15130:     &Apache::lonnet::appenv(\%AppHash);
15131:     return;
15132: }
15133: 
15134: sub restore_course_settings {
15135:     return &restore_settings($env{'request.course.id'},@_);
15136: }
15137: 
15138: sub restore_settings {
15139:     my ($context,$prefix,$Settings) = @_;
15140:     while (my ($setting,$type) = each(%$Settings)) {
15141:         next if (exists($env{'form.'.$setting}));
15142:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
15143:             '.'.$setting;
15144:         if (exists($env{$envname})) {
15145:             if ($type eq 'scalar') {
15146:                 $env{'form.'.$setting} = $env{$envname};
15147:             } elsif ($type eq 'array') {
15148:                 $env{'form.'.$setting} = [ 
15149:                                            map { 
15150:                                                &unescape($_); 
15151:                                            } split(',',$env{$envname})
15152:                                            ];
15153:             }
15154:         }
15155:     }
15156: }
15157: 
15158: #######################################################
15159: #######################################################
15160: 
15161: =pod
15162: 
15163: =head1 Domain E-mail Routines  
15164: 
15165: =over 4
15166: 
15167: =item * &build_recipient_list()
15168: 
15169: Build recipient lists for following types of e-mail:
15170: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15171: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15172: module change checking, student/employee ID conflict checks, as
15173: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15174: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15175: 
15176: Inputs:
15177: defmail (scalar - email address of default recipient),
15178: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15179: requestsmail, updatesmail, or idconflictsmail).
15180: 
15181: defdom (domain for which to retrieve configuration settings),
15182: 
15183: origmail (scalar - email address of recipient from loncapa.conf,
15184: i.e., predates configuration by DC via domainprefs.pm
15185: 
15186: $requname username of requester (if mailing type is helpdeskmail)
15187: 
15188: $requdom domain of requester (if mailing type is helpdeskmail)
15189: 
15190: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15191: 
15192: Returns: comma separated list of addresses to which to send e-mail.
15193: 
15194: =back
15195: 
15196: =cut
15197: 
15198: ############################################################
15199: ############################################################
15200: sub build_recipient_list {
15201:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15202:     my @recipients;
15203:     my ($otheremails,$lastresort,$allbcc,$addtext);
15204:     my %domconfig =
15205:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15206:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15207:         if (exists($domconfig{'contacts'}{$mailing})) {
15208:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15209:                 my @contacts = ('adminemail','supportemail');
15210:                 foreach my $item (@contacts) {
15211:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15212:                         my $addr = $domconfig{'contacts'}{$item}; 
15213:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15214:                             push(@recipients,$addr);
15215:                         }
15216:                     }
15217:                 }
15218:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15219:                 if ($mailing eq 'helpdeskmail') {
15220:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15221:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15222:                         my @ok_bccs;
15223:                         foreach my $bcc (@bccs) {
15224:                             $bcc =~ s/^\s+//g;
15225:                             $bcc =~ s/\s+$//g;
15226:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15227:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15228:                                     push(@ok_bccs,$bcc);
15229:                                 }
15230:                             }
15231:                         }
15232:                         if (@ok_bccs > 0) {
15233:                             $allbcc = join(', ',@ok_bccs);
15234:                         }
15235:                     }
15236:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15237:                 }
15238:             }
15239:         } elsif ($origmail ne '') {
15240:             $lastresort = $origmail;
15241:         }
15242:         if ($mailing eq 'helpdeskmail') {
15243:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15244:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15245:                 my ($inststatus,$inststatus_checked);
15246:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15247:                     ($env{'user.domain'} ne 'public')) {
15248:                     $inststatus_checked = 1;
15249:                     $inststatus = $env{'environment.inststatus'};
15250:                 }
15251:                 unless ($inststatus_checked) {
15252:                     if (($requname ne '') && ($requdom ne '')) {
15253:                         if (($requname =~ /^$match_username$/) &&
15254:                             ($requdom =~ /^$match_domain$/) &&
15255:                             (&Apache::lonnet::domain($requdom))) {
15256:                             my $requhome = &Apache::lonnet::homeserver($requname,
15257:                                                                       $requdom);
15258:                             unless ($requhome eq 'no_host') {
15259:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15260:                                 $inststatus = $userenv{'inststatus'};
15261:                                 $inststatus_checked = 1;
15262:                             }
15263:                         }
15264:                     }
15265:                 }
15266:                 unless ($inststatus_checked) {
15267:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15268:                         my %srch = (srchby     => 'email',
15269:                                     srchdomain => $defdom,
15270:                                     srchterm   => $reqemail,
15271:                                     srchtype   => 'exact');
15272:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15273:                         foreach my $uname (keys(%srch_results)) {
15274:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15275:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15276:                                 $inststatus_checked = 1;
15277:                                 last;
15278:                             }
15279:                         }
15280:                         unless ($inststatus_checked) {
15281:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15282:                             if ($dirsrchres eq 'ok') {
15283:                                 foreach my $uname (keys(%srch_results)) {
15284:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15285:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15286:                                         $inststatus_checked = 1;
15287:                                         last;
15288:                                     }
15289:                                 }
15290:                             }
15291:                         }
15292:                     }
15293:                 }
15294:                 if ($inststatus ne '') {
15295:                     foreach my $status (split(/\:/,$inststatus)) {
15296:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15297:                             my @contacts = ('adminemail','supportemail');
15298:                             foreach my $item (@contacts) {
15299:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15300:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15301:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15302:                                         push(@recipients,$addr);
15303:                                     }
15304:                                 }
15305:                             }
15306:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15307:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15308:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15309:                                 my @ok_bccs;
15310:                                 foreach my $bcc (@bccs) {
15311:                                     $bcc =~ s/^\s+//g;
15312:                                     $bcc =~ s/\s+$//g;
15313:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15314:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15315:                                             push(@ok_bccs,$bcc);
15316:                                         }
15317:                                     }
15318:                                 }
15319:                                 if (@ok_bccs > 0) {
15320:                                     $allbcc = join(', ',@ok_bccs);
15321:                                 }
15322:                             }
15323:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15324:                             last;
15325:                         }
15326:                     }
15327:                 }
15328:             }
15329:         }
15330:     } elsif ($origmail ne '') {
15331:         $lastresort = $origmail;
15332:     }
15333:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15334:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15335:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15336:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15337:             my %what = (
15338:                           perlvar => 1,
15339:                        );
15340:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15341:             if ($primary) {
15342:                 my $gotaddr;
15343:                 my ($result,$returnhash) =
15344:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15345:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15346:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15347:                         $lastresort = $returnhash->{'lonSupportEMail'};
15348:                         $gotaddr = 1;
15349:                     }
15350:                 }
15351:                 unless ($gotaddr) {
15352:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15353:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
15354:                     unless ($uintdom eq $intdom) {
15355:                         my %domconfig =
15356:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15357:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
15358:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15359:                                 my @contacts = ('adminemail','supportemail');
15360:                                 foreach my $item (@contacts) {
15361:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15362:                                         my $addr = $domconfig{'contacts'}{$item};
15363:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15364:                                             push(@recipients,$addr);
15365:                                         }
15366:                                     }
15367:                                 }
15368:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15369:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15370:                                 }
15371:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15372:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15373:                                     my @ok_bccs;
15374:                                     foreach my $bcc (@bccs) {
15375:                                         $bcc =~ s/^\s+//g;
15376:                                         $bcc =~ s/\s+$//g;
15377:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15378:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15379:                                                 push(@ok_bccs,$bcc);
15380:                                             }
15381:                                         }
15382:                                     }
15383:                                     if (@ok_bccs > 0) {
15384:                                         $allbcc = join(', ',@ok_bccs);
15385:                                     }
15386:                                 }
15387:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15388:                             }
15389:                         }
15390:                     }
15391:                 }
15392:             }
15393:         }
15394:     }
15395:     if (defined($defmail)) {
15396:         if ($defmail ne '') {
15397:             push(@recipients,$defmail);
15398:         }
15399:     }
15400:     if ($otheremails) {
15401:         my @others;
15402:         if ($otheremails =~ /,/) {
15403:             @others = split(/,/,$otheremails);
15404:         } else {
15405:             push(@others,$otheremails);
15406:         }
15407:         foreach my $addr (@others) {
15408:             if (!grep(/^\Q$addr\E$/,@recipients)) {
15409:                 push(@recipients,$addr);
15410:             }
15411:         }
15412:     }
15413:     if ($mailing eq 'helpdeskmail') {
15414:         if ((!@recipients) && ($lastresort ne '')) {
15415:             push(@recipients,$lastresort);
15416:         }
15417:     } elsif ($lastresort ne '') {
15418:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15419:             push(@recipients,$lastresort);
15420:         }
15421:     }
15422:     my $recipientlist = join(',',@recipients);
15423:     if (wantarray) {
15424:         return ($recipientlist,$allbcc,$addtext);
15425:     } else {
15426:         return $recipientlist;
15427:     }
15428: }
15429: 
15430: ############################################################
15431: ############################################################
15432: 
15433: =pod
15434: 
15435: =head1 Course Catalog Routines
15436: 
15437: =over 4
15438: 
15439: =item * &gather_categories()
15440: 
15441: Converts category definitions - keys of categories hash stored in  
15442: coursecategories in configuration.db on the primary library server in a 
15443: domain - to an array.  Also generates javascript and idx hash used to 
15444: generate Domain Coordinator interface for editing Course Categories.
15445: 
15446: Inputs:
15447: 
15448: categories (reference to hash of category definitions).
15449: 
15450: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15451:       categories and subcategories).
15452: 
15453: idx (reference to hash of counters used in Domain Coordinator interface for 
15454:       editing Course Categories).
15455: 
15456: jsarray (reference to array of categories used to create Javascript arrays for
15457:          Domain Coordinator interface for editing Course Categories).
15458: 
15459: Returns: nothing
15460: 
15461: Side effects: populates cats, idx and jsarray. 
15462: 
15463: =cut
15464: 
15465: sub gather_categories {
15466:     my ($categories,$cats,$idx,$jsarray) = @_;
15467:     my %counters;
15468:     my $num = 0;
15469:     foreach my $item (keys(%{$categories})) {
15470:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15471:         if ($container eq '' && $depth == 0) {
15472:             $cats->[$depth][$categories->{$item}] = $cat;
15473:         } else {
15474:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15475:         }
15476:         my ($escitem,$tail) = split(/:/,$item,2);
15477:         if ($counters{$tail} eq '') {
15478:             $counters{$tail} = $num;
15479:             $num ++;
15480:         }
15481:         if (ref($idx) eq 'HASH') {
15482:             $idx->{$item} = $counters{$tail};
15483:         }
15484:         if (ref($jsarray) eq 'ARRAY') {
15485:             push(@{$jsarray->[$counters{$tail}]},$item);
15486:         }
15487:     }
15488:     return;
15489: }
15490: 
15491: =pod
15492: 
15493: =item * &extract_categories()
15494: 
15495: Used to generate breadcrumb trails for course categories.
15496: 
15497: Inputs:
15498: 
15499: categories (reference to hash of category definitions).
15500: 
15501: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15502:       categories and subcategories).
15503: 
15504: trails (reference to array of breacrumb trails for each category).
15505: 
15506: allitems (reference to hash - key is category key 
15507:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15508: 
15509: idx (reference to hash of counters used in Domain Coordinator interface for
15510:       editing Course Categories).
15511: 
15512: jsarray (reference to array of categories used to create Javascript arrays for
15513:          Domain Coordinator interface for editing Course Categories).
15514: 
15515: subcats (reference to hash of arrays containing all subcategories within each 
15516:          category, -recursive)
15517: 
15518: maxd (reference to hash used to hold max depth for all top-level categories).
15519: 
15520: Returns: nothing
15521: 
15522: Side effects: populates trails and allitems hash references.
15523: 
15524: =cut
15525: 
15526: sub extract_categories {
15527:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15528:     if (ref($categories) eq 'HASH') {
15529:         &gather_categories($categories,$cats,$idx,$jsarray);
15530:         if (ref($cats->[0]) eq 'ARRAY') {
15531:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
15532:                 my $name = $cats->[0][$i];
15533:                 my $item = &escape($name).'::0';
15534:                 my $trailstr;
15535:                 if ($name eq 'instcode') {
15536:                     $trailstr = &mt('Official courses (with institutional codes)');
15537:                 } elsif ($name eq 'communities') {
15538:                     $trailstr = &mt('Communities');
15539:                 } else {
15540:                     $trailstr = $name;
15541:                 }
15542:                 if ($allitems->{$item} eq '') {
15543:                     push(@{$trails},$trailstr);
15544:                     $allitems->{$item} = scalar(@{$trails})-1;
15545:                 }
15546:                 my @parents = ($name);
15547:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
15548:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15549:                         my $category = $cats->[1]{$name}[$j];
15550:                         if (ref($subcats) eq 'HASH') {
15551:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15552:                         }
15553:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15554:                     }
15555:                 } else {
15556:                     if (ref($subcats) eq 'HASH') {
15557:                         $subcats->{$item} = [];
15558:                     }
15559:                     if (ref($maxd) eq 'HASH') {
15560:                         $maxd->{$name} = 1;
15561:                     }
15562:                 }
15563:             }
15564:         }
15565:     }
15566:     return;
15567: }
15568: 
15569: =pod
15570: 
15571: =item * &recurse_categories()
15572: 
15573: Recursively used to generate breadcrumb trails for course categories.
15574: 
15575: Inputs:
15576: 
15577: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15578:       categories and subcategories).
15579: 
15580: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15581: 
15582: category (current course category, for which breadcrumb trail is being generated).
15583: 
15584: trails (reference to array of breadcrumb trails for each category).
15585: 
15586: allitems (reference to hash - key is category key
15587:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15588: 
15589: parents (array containing containers directories for current category, 
15590:          back to top level). 
15591: 
15592: Returns: nothing
15593: 
15594: Side effects: populates trails and allitems hash references
15595: 
15596: =cut
15597: 
15598: sub recurse_categories {
15599:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
15600:     my $shallower = $depth - 1;
15601:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15602:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15603:             my $name = $cats->[$depth]{$category}[$k];
15604:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15605:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
15606:             if ($allitems->{$item} eq '') {
15607:                 push(@{$trails},$trailstr);
15608:                 $allitems->{$item} = scalar(@{$trails})-1;
15609:             }
15610:             my $deeper = $depth+1;
15611:             push(@{$parents},$category);
15612:             if (ref($subcats) eq 'HASH') {
15613:                 my $subcat = &escape($name).':'.$category.':'.$depth;
15614:                 for (my $j=@{$parents}; $j>=0; $j--) {
15615:                     my $higher;
15616:                     if ($j > 0) {
15617:                         $higher = &escape($parents->[$j]).':'.
15618:                                   &escape($parents->[$j-1]).':'.$j;
15619:                     } else {
15620:                         $higher = &escape($parents->[$j]).'::'.$j;
15621:                     }
15622:                     push(@{$subcats->{$higher}},$subcat);
15623:                 }
15624:             }
15625:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15626:                                 $subcats,$maxd);
15627:             pop(@{$parents});
15628:         }
15629:     } else {
15630:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15631:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
15632:         if ($allitems->{$item} eq '') {
15633:             push(@{$trails},$trailstr);
15634:             $allitems->{$item} = scalar(@{$trails})-1;
15635:         }
15636:         if (ref($maxd) eq 'HASH') {
15637:             if ($depth > $maxd->{$parents->[0]}) {
15638:                 $maxd->{$parents->[0]} = $depth;
15639:             }
15640:         }
15641:     }
15642:     return;
15643: }
15644: 
15645: =pod
15646: 
15647: =item * &assign_categories_table()
15648: 
15649: Create a datatable for display of hierarchical categories in a domain,
15650: with checkboxes to allow a course to be categorized. 
15651: 
15652: Inputs:
15653: 
15654: cathash - reference to hash of categories defined for the domain (from
15655:           configuration.db)
15656: 
15657: currcat - scalar with an & separated list of categories assigned to a course. 
15658: 
15659: type    - scalar contains course type (Course or Community).
15660: 
15661: disabled - scalar (optional) contains disabled="disabled" if input elements are
15662:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15663: 
15664: Returns: $output (markup to be displayed) 
15665: 
15666: =cut
15667: 
15668: sub assign_categories_table {
15669:     my ($cathash,$currcat,$type,$disabled) = @_;
15670:     my $output;
15671:     if (ref($cathash) eq 'HASH') {
15672:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
15673:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
15674:         $maxdepth = scalar(@cats);
15675:         if (@cats > 0) {
15676:             my $itemcount = 0;
15677:             if (ref($cats[0]) eq 'ARRAY') {
15678:                 my @currcategories;
15679:                 if ($currcat ne '') {
15680:                     @currcategories = split('&',$currcat);
15681:                 }
15682:                 my $table;
15683:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15684:                     my $parent = $cats[0][$i];
15685:                     next if ($parent eq 'instcode');
15686:                     if ($type eq 'Community') {
15687:                         next unless ($parent eq 'communities');
15688:                     } else {
15689:                         next if ($parent eq 'communities');
15690:                     }
15691:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15692:                     my $item = &escape($parent).'::0';
15693:                     my $checked = '';
15694:                     if (@currcategories > 0) {
15695:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15696:                             $checked = ' checked="checked"';
15697:                         }
15698:                     }
15699:                     my $parent_title = $parent;
15700:                     if ($parent eq 'communities') {
15701:                         $parent_title = &mt('Communities');
15702:                     }
15703:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15704:                               '<input type="checkbox" name="usecategory" value="'.
15705:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15706:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15707:                     my $depth = 1;
15708:                     push(@path,$parent);
15709:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15710:                     pop(@path);
15711:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15712:                     $itemcount ++;
15713:                 }
15714:                 if ($itemcount) {
15715:                     $output = &Apache::loncommon::start_data_table().
15716:                               $table.
15717:                               &Apache::loncommon::end_data_table();
15718:                 }
15719:             }
15720:         }
15721:     }
15722:     return $output;
15723: }
15724: 
15725: =pod
15726: 
15727: =item * &assign_category_rows()
15728: 
15729: Create a datatable row for display of nested categories in a domain,
15730: with checkboxes to allow a course to be categorized,called recursively.
15731: 
15732: Inputs:
15733: 
15734: itemcount - track row number for alternating colors
15735: 
15736: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15737:       categories and subcategories.
15738: 
15739: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15740: 
15741: parent - parent of current category item
15742: 
15743: path - Array containing all categories back up through the hierarchy from the
15744:        current category to the top level.
15745: 
15746: currcategories - reference to array of current categories assigned to the course
15747: 
15748: disabled - scalar (optional) contains disabled="disabled" if input elements are
15749:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15750: 
15751: Returns: $output (markup to be displayed).
15752: 
15753: =cut
15754: 
15755: sub assign_category_rows {
15756:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15757:     my ($text,$name,$item,$chgstr);
15758:     if (ref($cats) eq 'ARRAY') {
15759:         my $maxdepth = scalar(@{$cats});
15760:         if (ref($cats->[$depth]) eq 'HASH') {
15761:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15762:                 my $numchildren = @{$cats->[$depth]{$parent}};
15763:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15764:                 $text .= '<td><table class="LC_data_table">';
15765:                 for (my $j=0; $j<$numchildren; $j++) {
15766:                     $name = $cats->[$depth]{$parent}[$j];
15767:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15768:                     my $deeper = $depth+1;
15769:                     my $checked = '';
15770:                     if (ref($currcategories) eq 'ARRAY') {
15771:                         if (@{$currcategories} > 0) {
15772:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15773:                                 $checked = ' checked="checked"';
15774:                             }
15775:                         }
15776:                     }
15777:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15778:                              '<input type="checkbox" name="usecategory" value="'.
15779:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15780:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15781:                              '</td><td>';
15782:                     if (ref($path) eq 'ARRAY') {
15783:                         push(@{$path},$name);
15784:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15785:                         pop(@{$path});
15786:                     }
15787:                     $text .= '</td></tr>';
15788:                 }
15789:                 $text .= '</table></td>';
15790:             }
15791:         }
15792:     }
15793:     return $text;
15794: }
15795: 
15796: =pod
15797: 
15798: =back
15799: 
15800: =cut
15801: 
15802: ############################################################
15803: ############################################################
15804: 
15805: 
15806: sub commit_customrole {
15807:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15808:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15809:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15810:                          ($end?', ending '.localtime($end):'').': <b>'.
15811:               &Apache::lonnet::assigncustomrole(
15812:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15813:                  '</b><br />';
15814:     return $output;
15815: }
15816: 
15817: sub commit_standardrole {
15818:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15819:     my ($output,$logmsg,$linefeed);
15820:     if ($context eq 'auto') {
15821:         $linefeed = "\n";
15822:     } else {
15823:         $linefeed = "<br />\n";
15824:     }  
15825:     if ($three eq 'st') {
15826:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15827:                                          $one,$two,$sec,$context,$credits);
15828:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15829:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15830:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15831:         } else {
15832:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15833:                ($start?', '.&mt('starting').' '.localtime($start):'').
15834:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15835:             if ($context eq 'auto') {
15836:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15837:             } else {
15838:                $output .= '<b>'.$result.'</b>'.$linefeed.
15839:                &mt('Add to classlist').': <b>ok</b>';
15840:             }
15841:             $output .= $linefeed;
15842:         }
15843:     } else {
15844:         $output = &mt('Assigning').' '.$three.' in '.$url.
15845:                ($start?', '.&mt('starting').' '.localtime($start):'').
15846:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15847:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15848:         if ($context eq 'auto') {
15849:             $output .= $result.$linefeed;
15850:         } else {
15851:             $output .= '<b>'.$result.'</b>'.$linefeed;
15852:         }
15853:     }
15854:     return $output;
15855: }
15856: 
15857: sub commit_studentrole {
15858:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15859:         $credits) = @_;
15860:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15861:     if ($context eq 'auto') {
15862:         $linefeed = "\n";
15863:     } else {
15864:         $linefeed = '<br />'."\n";
15865:     }
15866:     if (defined($one) && defined($two)) {
15867:         my $cid=$one.'_'.$two;
15868:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15869:         my $secchange = 0;
15870:         my $expire_role_result;
15871:         my $modify_section_result;
15872:         if ($oldsec ne '-1') { 
15873:             if ($oldsec ne $sec) {
15874:                 $secchange = 1;
15875:                 my $now = time;
15876:                 my $uurl='/'.$cid;
15877:                 $uurl=~s/\_/\//g;
15878:                 if ($oldsec) {
15879:                     $uurl.='/'.$oldsec;
15880:                 }
15881:                 $oldsecurl = $uurl;
15882:                 $expire_role_result = 
15883:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','','',$context);
15884:                 if ($env{'request.course.sec'} ne '') { 
15885:                     if ($expire_role_result eq 'refused') {
15886:                         my @roles = ('st');
15887:                         my @statuses = ('previous');
15888:                         my @roledoms = ($one);
15889:                         my $withsec = 1;
15890:                         my %roleshash = 
15891:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15892:                                               \@statuses,\@roles,\@roledoms,$withsec);
15893:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15894:                             my ($oldstart,$oldend) = 
15895:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15896:                             if ($oldend > 0 && $oldend <= $now) {
15897:                                 $expire_role_result = 'ok';
15898:                             }
15899:                         }
15900:                     }
15901:                 }
15902:                 $result = $expire_role_result;
15903:             }
15904:         }
15905:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15906:             $modify_section_result = 
15907:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15908:                                                            undef,undef,undef,$sec,
15909:                                                            $end,$start,'','',$cid,
15910:                                                            '',$context,$credits);
15911:             if ($modify_section_result =~ /^ok/) {
15912:                 if ($secchange == 1) {
15913:                     if ($sec eq '') {
15914:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15915:                     } else {
15916:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15917:                     }
15918:                 } elsif ($oldsec eq '-1') {
15919:                     if ($sec eq '') {
15920:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15921:                     } else {
15922:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15923:                     }
15924:                 } else {
15925:                     if ($sec eq '') {
15926:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15927:                     } else {
15928:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15929:                     }
15930:                 }
15931:             } else {
15932:                 if ($secchange) {       
15933:                     $$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;
15934:                 } else {
15935:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15936:                 }
15937:             }
15938:             $result = $modify_section_result;
15939:         } elsif ($secchange == 1) {
15940:             if ($oldsec eq '') {
15941:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15942:             } else {
15943:                 $$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;
15944:             }
15945:             if ($expire_role_result eq 'refused') {
15946:                 my $newsecurl = '/'.$cid;
15947:                 $newsecurl =~ s/\_/\//g;
15948:                 if ($sec ne '') {
15949:                     $newsecurl.='/'.$sec;
15950:                 }
15951:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15952:                     if ($sec eq '') {
15953:                         $$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;
15954:                     } else {
15955:                         $$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;
15956:                     }
15957:                 }
15958:             }
15959:         }
15960:     } else {
15961:         $$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;
15962:         $result = "error: incomplete course id\n";
15963:     }
15964:     return $result;
15965: }
15966: 
15967: sub show_role_extent {
15968:     my ($scope,$context,$role) = @_;
15969:     $scope =~ s{^/}{};
15970:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15971:     push(@courseroles,'co');
15972:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15973:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15974:         $scope =~ s{/}{_};
15975:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15976:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15977:         my ($audom,$auname) = split(/\//,$scope);
15978:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15979:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15980:     } else {
15981:         $scope =~ s{/$}{};
15982:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15983:                    &Apache::lonnet::domain($scope,'description').'</span>');
15984:     }
15985: }
15986: 
15987: ############################################################
15988: ############################################################
15989: 
15990: sub check_clone {
15991:     my ($args,$linefeed) = @_;
15992:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15993:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15994:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15995:     my $clonetitle;
15996:     my @clonemsg;
15997:     my $can_clone = 0;
15998:     my $lctype = lc($args->{'crstype'});
15999:     if ($lctype ne 'community') {
16000:         $lctype = 'course';
16001:     }
16002:     if ($clonehome eq 'no_host') {
16003:         if ($args->{'crstype'} eq 'Community') {
16004:             push(@clonemsg,({
16005:                               mt => 'No new community created.',
16006:                               args => [],
16007:                             },
16008:                             {
16009:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16010:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16011:                             }));
16012:         } else {
16013:             push(@clonemsg,({
16014:                               mt => 'No new course created.',
16015:                               args => [],
16016:                             },
16017:                             {
16018:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16019:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16020:                             }));
16021:         }
16022:     } else {
16023: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16024:         $clonetitle = $clonedesc{'description'};
16025:         if ($args->{'crstype'} eq 'Community') {
16026:             if ($clonedesc{'type'} ne 'Community') {
16027:                 push(@clonemsg,({
16028:                                   mt => 'No new community created.',
16029:                                   args => [],
16030:                                 },
16031:                                 {
16032:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16033:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16034:                                 }));
16035:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16036:             }
16037:         }
16038: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16039:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16040: 	    $can_clone = 1;
16041: 	} else {
16042: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16043: 						 $args->{'clonedomain'},$args->{'clonecourse'});
16044:             if ($clonehash{'cloners'} eq '') {
16045:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16046:                 if ($domdefs{'canclone'}) {
16047:                     unless ($domdefs{'canclone'} eq 'none') {
16048:                         if ($domdefs{'canclone'} eq 'domain') {
16049:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16050:                                 $can_clone = 1;
16051:                             }
16052:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
16053:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16054:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16055:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16056:                                 $can_clone = 1;
16057:                             }
16058:                         }
16059:                     }
16060:                 }
16061:             } else {
16062: 	        my @cloners = split(/,/,$clonehash{'cloners'});
16063:                 if (grep(/^\*$/,@cloners)) {
16064:                     $can_clone = 1;
16065:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16066:                     $can_clone = 1;
16067:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16068:                     $can_clone = 1;
16069:                 }
16070:                 unless ($can_clone) {
16071:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
16072:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16073:                         my (%gotdomdefaults,%gotcodedefaults);
16074:                         foreach my $cloner (@cloners) {
16075:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16076:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16077:                                 my (%codedefaults,@code_order);
16078:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16079:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16080:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16081:                                     }
16082:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16083:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16084:                                     }
16085:                                 } else {
16086:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16087:                                                                             \%codedefaults,
16088:                                                                             \@code_order);
16089:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16090:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16091:                                 }
16092:                                 if (@code_order > 0) {
16093:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16094:                                                                                 $cloner,$clonehash{'internal.coursecode'},
16095:                                                                                 $args->{'crscode'})) {
16096:                                         $can_clone = 1;
16097:                                         last;
16098:                                     }
16099:                                 }
16100:                             }
16101:                         }
16102:                     }
16103:                 }
16104:             }
16105:             unless ($can_clone) {
16106:                 my $ccrole = 'cc';
16107:                 if ($args->{'crstype'} eq 'Community') {
16108:                     $ccrole = 'co';
16109:                 }
16110:                 my %roleshash =
16111:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
16112:                                                   $args->{'ccdomain'},
16113:                                                   'userroles',['active'],[$ccrole],
16114:                                                   [$args->{'clonedomain'}]);
16115:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16116:                     $can_clone = 1;
16117:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16118:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
16119:                     $can_clone = 1;
16120:                 }
16121:             }
16122:             unless ($can_clone) {
16123:                 if ($args->{'crstype'} eq 'Community') {
16124:                     push(@clonemsg,({
16125:                                       mt => 'No new community created.',
16126:                                       args => [],
16127:                                     },
16128:                                     {
16129:                                       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]).',
16130:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16131:                                     }));
16132:                 } else {
16133:                     push(@clonemsg,({
16134:                                       mt => 'No new course created.',
16135:                                       args => [],
16136:                                     },
16137:                                     {
16138:                                       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]).',
16139:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16140:                                     }));
16141: 	        }
16142: 	    }
16143:         }
16144:     }
16145:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16146: }
16147: 
16148: sub construct_course {
16149:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16150:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16151:     my ($outcome,$msgref,$clonemsgref);
16152:     my $linefeed =  '<br />'."\n";
16153:     if ($context eq 'auto') {
16154:         $linefeed = "\n";
16155:     }
16156: 
16157: #
16158: # Are we cloning?
16159: #
16160:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16161:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16162: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16163:         if (!$can_clone) {
16164: 	    return (0,$outcome,$clonemsgref);
16165: 	}
16166:     }
16167: 
16168: #
16169: # Open course
16170: #
16171:     my $crstype = lc($args->{'crstype'});
16172:     my %cenv=();
16173:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16174:                                              $args->{'cdescr'},
16175:                                              $args->{'curl'},
16176:                                              $args->{'course_home'},
16177:                                              $args->{'nonstandard'},
16178:                                              $args->{'crscode'},
16179:                                              $args->{'ccuname'}.':'.
16180:                                              $args->{'ccdomain'},
16181:                                              $args->{'crstype'},
16182:                                              $cnum,$context,$category,
16183:                                              $callercontext);
16184: 
16185:     # Note: The testing routines depend on this being output; see 
16186:     # Utils::Course. This needs to at least be output as a comment
16187:     # if anyone ever decides to not show this, and Utils::Course::new
16188:     # will need to be suitably modified.
16189:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16190:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
16191:     } else {
16192:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
16193:     }
16194:     if ($$courseid =~ /^error:/) {
16195:         return (0,$outcome,$clonemsgref);
16196:     }
16197: 
16198: #
16199: # Check if created correctly
16200: #
16201:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16202:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16203:     if ($crsuhome eq 'no_host') {
16204:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16205:             $outcome .= &mt_user($user_lh,
16206:                             'Course creation failed, unrecognized course home server.');
16207:         } else {
16208:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16209:         }
16210:         $outcome .= $linefeed;
16211:         return (0,$outcome,$clonemsgref);
16212:     }
16213:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16214: 
16215: #
16216: # Do the cloning
16217: #
16218:     my @clonemsg;
16219:     if ($can_clone && $cloneid) {
16220:         push(@clonemsg,
16221:                       {
16222:                           mt => 'Created [_1] by cloning from [_2]',
16223:                           args => [$crstype,$clonetitle],
16224:                       });
16225: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16226: # Copy all files
16227:         my @info =
16228:             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16229:                                                      $args->{'dateshift'},$args->{'crscode'},
16230:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16231:                                                      $args->{'tinyurls'});
16232:         if (@info) {
16233:             push(@clonemsg,@info);
16234:         }
16235: # Restore URL
16236: 	$cenv{'url'}=$oldcenv{'url'};
16237: # Restore title
16238: 	$cenv{'description'}=$oldcenv{'description'};
16239: # Restore creation date, creator and creation context.
16240:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16241:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16242:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16243: # Mark as cloned
16244: 	$cenv{'clonedfrom'}=$cloneid;
16245: # Need to clone grading mode
16246:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16247:         $cenv{'grading'}=$newenv{'grading'};
16248: # Do not clone these environment entries
16249:         &Apache::lonnet::del('environment',
16250:                   ['default_enrollment_start_date',
16251:                    'default_enrollment_end_date',
16252:                    'question.email',
16253:                    'policy.email',
16254:                    'comment.email',
16255:                    'pch.users.denied',
16256:                    'plc.users.denied',
16257:                    'hidefromcat',
16258:                    'checkforpriv',
16259:                    'categories'],
16260:                    $$crsudom,$$crsunum);
16261:         if ($args->{'textbook'}) {
16262:             $cenv{'internal.textbook'} = $args->{'textbook'};
16263:         }
16264:     }
16265: 
16266: #
16267: # Set environment (will override cloned, if existing)
16268: #
16269:     my @sections = ();
16270:     my @xlists = ();
16271:     if ($args->{'crstype'}) {
16272:         $cenv{'type'}=$args->{'crstype'};
16273:     }
16274:     if ($args->{'lti'}) {
16275:         $cenv{'internal.lti'}=$args->{'lti'};
16276:     }
16277:     if ($args->{'crsid'}) {
16278:         $cenv{'courseid'}=$args->{'crsid'};
16279:     }
16280:     if ($args->{'crscode'}) {
16281:         $cenv{'internal.coursecode'}=$args->{'crscode'};
16282:     }
16283:     if ($args->{'crsquota'} ne '') {
16284:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
16285:     } else {
16286:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16287:     }
16288:     if ($args->{'ccuname'}) {
16289:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16290:                                         ':'.$args->{'ccdomain'};
16291:     } else {
16292:         $cenv{'internal.courseowner'} = $args->{'curruser'};
16293:     }
16294:     if ($args->{'defaultcredits'}) {
16295:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16296:     }
16297:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16298:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
16299:     if ($args->{'crssections'}) {
16300:         $cenv{'internal.sectionnums'} = '';
16301:         if ($args->{'crssections'} =~ m/,/) {
16302:             @sections = split/,/,$args->{'crssections'};
16303:         } else {
16304:             $sections[0] = $args->{'crssections'};
16305:         }
16306:         if (@sections > 0) {
16307:             foreach my $item (@sections) {
16308:                 my ($sec,$gp) = split/:/,$item;
16309:                 my $class = $args->{'crscode'}.$sec;
16310:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16311:                 $cenv{'internal.sectionnums'} .= $item.',';
16312:                 if ($addcheck eq 'ok') {
16313:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
16314:                         push(@oklcsecs,$gp);
16315:                     }
16316:                 } else {
16317:                     push(@badclasses,$class);
16318:                 }
16319:             }
16320:             $cenv{'internal.sectionnums'} =~ s/,$//;
16321:         }
16322:     }
16323: # do not hide course coordinator from staff listing, 
16324: # even if privileged
16325:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16326: # add course coordinator's domain to domains to check for privileged users
16327: # if different to course domain
16328:     if ($$crsudom ne $args->{'ccdomain'}) {
16329:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
16330:     }
16331: # add crosslistings
16332:     if ($args->{'crsxlist'}) {
16333:         $cenv{'internal.crosslistings'}='';
16334:         if ($args->{'crsxlist'} =~ m/,/) {
16335:             @xlists = split/,/,$args->{'crsxlist'};
16336:         } else {
16337:             $xlists[0] = $args->{'crsxlist'};
16338:         }
16339:         if (@xlists > 0) {
16340:             foreach my $item (@xlists) {
16341:                 my ($xl,$gp) = split/:/,$item;
16342:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16343:                 $cenv{'internal.crosslistings'} .= $item.',';
16344:                 if ($addcheck eq 'ok') {
16345:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
16346:                         push(@oklcsecs,$gp);
16347:                     }
16348:                 } else {
16349:                     push(@badclasses,$xl);
16350:                 }
16351:             }
16352:             $cenv{'internal.crosslistings'} =~ s/,$//;
16353:         }
16354:     }
16355:     if ($args->{'autoadds'}) {
16356:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
16357:     }
16358:     if ($args->{'autodrops'}) {
16359:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
16360:     }
16361: # check for notification of enrollment changes
16362:     my @notified = ();
16363:     if ($args->{'notify_owner'}) {
16364:         if ($args->{'ccuname'} ne '') {
16365:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16366:         }
16367:     }
16368:     if ($args->{'notify_dc'}) {
16369:         if ($uname ne '') { 
16370:             push(@notified,$uname.':'.$udom);
16371:         }
16372:     }
16373:     if (@notified > 0) {
16374:         my $notifylist;
16375:         if (@notified > 1) {
16376:             $notifylist = join(',',@notified);
16377:         } else {
16378:             $notifylist = $notified[0];
16379:         }
16380:         $cenv{'internal.notifylist'} = $notifylist;
16381:     }
16382:     if (@badclasses > 0) {
16383:         my %lt=&Apache::lonlocal::texthash(
16384:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16385:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16386:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16387:         );
16388:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16389:                            &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'};
16390:         if ($context eq 'auto') {
16391:             $outcome .= $badclass_msg.$linefeed;
16392:         } else {
16393:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16394:         }
16395:         foreach my $item (@badclasses) {
16396:             if ($context eq 'auto') {
16397:                 $outcome .= " - $item\n";
16398:             } else {
16399:                 $outcome .= "<li>$item</li>\n";
16400:             }
16401:         }
16402:         if ($context eq 'auto') {
16403:             $outcome .= $linefeed;
16404:         } else {
16405:             $outcome .= "</ul><br /><br /></div>\n";
16406:         }
16407:     }
16408:     if ($args->{'no_end_date'}) {
16409:         $args->{'endaccess'} = 0;
16410:     }
16411: #  If an official course with institutional sections is created by cloning
16412: #  an existing course, section-specific hiding of course totals in student's
16413: #  view of grades as copied from cloned course, will be checked for valid
16414: #  sections.
16415:     if (($can_clone && $cloneid) &&
16416:         ($cenv{'internal.coursecode'} ne '') &&
16417:         ($cenv{'grading'} eq 'standard') &&
16418:         ($cenv{'hidetotals'} ne '') &&
16419:         ($cenv{'hidetotals'} ne 'all')) {
16420:         my @hidesecs;
16421:         my $deletehidetotals;
16422:         if (@oklcsecs) {
16423:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
16424:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
16425:                     push(@hidesecs,$sec);
16426:                 }
16427:             }
16428:             if (@hidesecs) {
16429:                 $cenv{'hidetotals'} = join(',',@hidesecs);
16430:             } else {
16431:                 $deletehidetotals = 1;
16432:             }
16433:         } else {
16434:             $deletehidetotals = 1;
16435:         }
16436:         if ($deletehidetotals) {
16437:             delete($cenv{'hidetotals'});
16438:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
16439:         }
16440:     }
16441:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
16442:     $cenv{'internal.autoend'}=$args->{'enrollend'};
16443:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16444:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16445:     if ($args->{'showphotos'}) {
16446:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
16447:     }
16448:     $cenv{'internal.authtype'} = $args->{'authtype'};
16449:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
16450:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16451:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
16452:             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'); 
16453:             if ($context eq 'auto') {
16454:                 $outcome .= $krb_msg;
16455:             } else {
16456:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16457:             }
16458:             $outcome .= $linefeed;
16459:         }
16460:     }
16461:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16462:        if ($args->{'setpolicy'}) {
16463:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16464:        }
16465:        if ($args->{'setcontent'}) {
16466:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16467:        }
16468:        if ($args->{'setcomment'}) {
16469:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16470:        }
16471:     }
16472:     if ($args->{'reshome'}) {
16473: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
16474: 	$cenv{'reshome'}=~s/\/+$/\//;
16475:     }
16476: #
16477: # course has keyed access
16478: #
16479:     if ($args->{'setkeys'}) {
16480:        $cenv{'keyaccess'}='yes';
16481:     }
16482: # if specified, key authority is not course, but user
16483: # only active if keyaccess is yes
16484:     if ($args->{'keyauth'}) {
16485: 	my ($user,$domain) = split(':',$args->{'keyauth'});
16486: 	$user = &LONCAPA::clean_username($user);
16487: 	$domain = &LONCAPA::clean_username($domain);
16488: 	if ($user ne '' && $domain ne '') {
16489: 	    $cenv{'keyauth'}=$user.':'.$domain;
16490: 	}
16491:     }
16492: 
16493: #
16494: #  generate and store uniquecode (available to course requester), if course should have one.
16495: #
16496:     if ($args->{'uniquecode'}) {
16497:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16498:         if ($code) {
16499:             $cenv{'internal.uniquecode'} = $code;
16500:             my %crsinfo =
16501:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16502:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16503:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16504:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16505:             }
16506:             if (ref($coderef)) {
16507:                 $$coderef = $code;
16508:             }
16509:         }
16510:     }
16511: 
16512:     if ($args->{'disresdis'}) {
16513:         $cenv{'pch.roles.denied'}='st';
16514:     }
16515:     if ($args->{'disablechat'}) {
16516:         $cenv{'plc.roles.denied'}='st';
16517:     }
16518: 
16519:     # Record we've not yet viewed the Course Initialization Helper for this 
16520:     # course
16521:     $cenv{'course.helper.not.run'} = 1;
16522:     #
16523:     # Use new Randomseed
16524:     #
16525:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16526:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16527:     #
16528:     # The encryption code and receipt prefix for this course
16529:     #
16530:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16531:     $cenv{'internal.encpref'}=100+int(9*rand(99));
16532:     #
16533:     # By default, use standard grading
16534:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16535: 
16536:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
16537:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16538: #
16539: # Open all assignments
16540: #
16541:     if ($args->{'openall'}) {
16542:        my $opendate = time;
16543:        if ($args->{'openallfrom'} =~ /^\d+$/) {
16544:            $opendate = $args->{'openallfrom'};
16545:        }
16546:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16547:        my %storecontent = ($storeunder         => $opendate,
16548:                            $storeunder.'.type' => 'date_start');
16549:        $outcome .= &mt('All assignments open starting [_1]',
16550:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
16551:                    &Apache::lonnet::cput
16552:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16553:    }
16554: #
16555: # Set first page
16556: #
16557:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16558: 	    || ($cloneid)) {
16559: 	$outcome .= &mt('Setting first resource').': ';
16560: 
16561: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16562:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16563: 
16564:         $outcome .= ($fatal?$errtext:'read ok').' - ';
16565:         my $title; my $url;
16566:         if ($args->{'firstres'} eq 'syl') {
16567: 	    $title=&mt('Syllabus');
16568:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16569:         } else {
16570:             $title=&mt('Table of Contents');
16571:             $url='/adm/navmaps';
16572:         }
16573: 
16574:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16575: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16576: 
16577: 	if ($errtext) { $fatal=2; }
16578:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16579:     }
16580: 
16581:     return (1,$outcome,\@clonemsg);
16582: }
16583: 
16584: sub make_unique_code {
16585:     my ($cdom,$cnum) = @_;
16586:     # get lock on uniquecodes db
16587:     my $lockhash = {
16588:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
16589:                                                   ':'.$env{'user.domain'},
16590:                    };
16591:     my $tries = 0;
16592:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16593:     my ($code,$error);
16594: 
16595:     while (($gotlock ne 'ok') && ($tries<3)) {
16596:         $tries ++;
16597:         sleep 1;
16598:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16599:     }
16600:     if ($gotlock eq 'ok') {
16601:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16602:         my $gotcode;
16603:         my $attempts = 0;
16604:         while ((!$gotcode) && ($attempts < 100)) {
16605:             $code = &generate_code();
16606:             if (!exists($currcodes{$code})) {
16607:                 $gotcode = 1;
16608:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16609:                     $error = 'nostore';
16610:                 }
16611:             }
16612:             $attempts ++;
16613:         }
16614:         my @del_lock = ($cnum."\0".'uniquecodes');
16615:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16616:     } else {
16617:         $error = 'nolock';
16618:     }
16619:     return ($code,$error);
16620: }
16621: 
16622: sub generate_code {
16623:     my $code;
16624:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16625:     for (my $i=0; $i<6; $i++) {
16626:         my $lettnum = int (rand 2);
16627:         my $item = '';
16628:         if ($lettnum) {
16629:             $item = $letts[int( rand(18) )];
16630:         } else {
16631:             $item = 1+int( rand(8) );
16632:         }
16633:         $code .= $item;
16634:     }
16635:     return $code;
16636: }
16637: 
16638: ############################################################
16639: ############################################################
16640: 
16641: #SD
16642: # only Community and Course, or anything else?
16643: sub course_type {
16644:     my ($cid) = @_;
16645:     if (!defined($cid)) {
16646:         $cid = $env{'request.course.id'};
16647:     }
16648:     if (defined($env{'course.'.$cid.'.type'})) {
16649:         return $env{'course.'.$cid.'.type'};
16650:     } else {
16651:         return 'Course';
16652:     }
16653: }
16654: 
16655: sub group_term {
16656:     my $crstype = &course_type();
16657:     my %names = (
16658:                   'Course' => 'group',
16659:                   'Community' => 'group',
16660:                 );
16661:     return $names{$crstype};
16662: }
16663: 
16664: sub course_types {
16665:     my @types = ('official','unofficial','community','textbook','lti');
16666:     my %typename = (
16667:                          official   => 'Official course',
16668:                          unofficial => 'Unofficial course',
16669:                          community  => 'Community',
16670:                          textbook   => 'Textbook course',
16671:                          lti        => 'LTI provider',
16672:                    );
16673:     return (\@types,\%typename);
16674: }
16675: 
16676: sub icon {
16677:     my ($file)=@_;
16678:     my $curfext = lc((split(/\./,$file))[-1]);
16679:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16680:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16681:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16682: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16683: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16684: 	            $curfext.".gif") {
16685: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16686: 		$curfext.".gif";
16687: 	}
16688:     }
16689:     return &lonhttpdurl($iconname);
16690: } 
16691: 
16692: sub lonhttpdurl {
16693: #
16694: # Had been used for "small fry" static images on separate port 8080.
16695: # Modify here if lightweight http functionality desired again.
16696: # Currently eliminated due to increasing firewall issues.
16697: #
16698:     my ($url)=@_;
16699:     return $url;
16700: }
16701: 
16702: sub connection_aborted {
16703:     my ($r)=@_;
16704:     $r->print(" ");$r->rflush();
16705:     my $c = $r->connection;
16706:     return $c->aborted();
16707: }
16708: 
16709: #    Escapes strings that may have embedded 's that will be put into
16710: #    strings as 'strings'.
16711: sub escape_single {
16712:     my ($input) = @_;
16713:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16714:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16715:     return $input;
16716: }
16717: 
16718: #  Same as escape_single, but escape's "'s  This 
16719: #  can be used for  "strings"
16720: sub escape_double {
16721:     my ($input) = @_;
16722:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16723:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16724:     return $input;
16725: }
16726:  
16727: #   Escapes the last element of a full URL.
16728: sub escape_url {
16729:     my ($url)   = @_;
16730:     my @urlslices = split(/\//, $url,-1);
16731:     my $lastitem = &escape(pop(@urlslices));
16732:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16733: }
16734: 
16735: sub compare_arrays {
16736:     my ($arrayref1,$arrayref2) = @_;
16737:     my (@difference,%count);
16738:     @difference = ();
16739:     %count = ();
16740:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16741:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16742:         foreach my $element (keys(%count)) {
16743:             if ($count{$element} == 1) {
16744:                 push(@difference,$element);
16745:             }
16746:         }
16747:     }
16748:     return @difference;
16749: }
16750: 
16751: sub lon_status_items {
16752:     my %defaults = (
16753:                      E         => 100,
16754:                      W         => 4,
16755:                      N         => 1,
16756:                      U         => 5,
16757:                      threshold => 200,
16758:                      sysmail   => 2500,
16759:                    );
16760:     my %names = (
16761:                    E => 'Errors',
16762:                    W => 'Warnings',
16763:                    N => 'Notices',
16764:                    U => 'Unsent',
16765:                 );
16766:     return (\%defaults,\%names);
16767: }
16768: 
16769: # -------------------------------------------------------- Initialize user login
16770: sub init_user_environment {
16771:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16772:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16773: 
16774:     my $public=($username eq 'public' && $domain eq 'public');
16775: 
16776: # See if old ID present, if so, remove
16777: 
16778:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16779:     my $now=time;
16780: 
16781:     if ($public) {
16782: 	my $max_public=100;
16783: 	my $oldest;
16784: 	my $oldest_time=0;
16785: 	for(my $next=1;$next<=$max_public;$next++) {
16786: 	    if (-e $lonids."/publicuser_$next.id") {
16787: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16788: 		if ($mtime<$oldest_time || !$oldest_time) {
16789: 		    $oldest_time=$mtime;
16790: 		    $oldest=$next;
16791: 		}
16792: 	    } else {
16793: 		$cookie="publicuser_$next";
16794: 		last;
16795: 	    }
16796: 	}
16797: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16798:     } else {
16799: 	# if this isn't a robot, kill any existing non-robot sessions
16800: 	if (!$args->{'robot'}) {
16801: 	    opendir(DIR,$lonids);
16802: 	    while ($filename=readdir(DIR)) {
16803: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16804:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
16805:                             &GDBM_READER(),0640)) {
16806:                         my $linkedfile;
16807:                         if (exists($oldenv{'user.linkedenv'})) {
16808:                             $linkedfile = $oldenv{'user.linkedenv'};
16809:                         }
16810:                         untie(%oldenv);
16811:                         if (unlink("$lonids/$filename")) {
16812:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16813:                                 if (-l "$lonids/$linkedfile.id") {
16814:                                     unlink("$lonids/$linkedfile.id");
16815:                                 }
16816:                             }
16817:                         }
16818:                     } else {
16819:                         unlink($lonids.'/'.$filename);
16820:                     }
16821: 		}
16822: 	    }
16823: 	    closedir(DIR);
16824: # If there is a undeleted lockfile for the user's paste buffer remove it.
16825:             my $namespace = 'nohist_courseeditor';
16826:             my $lockingkey = 'paste'."\0".'locked_num';
16827:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16828:                                                 $domain,$username);
16829:             if (exists($lockhash{$lockingkey})) {
16830:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16831:                 unless ($delresult eq 'ok') {
16832:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16833:                 }
16834:             }
16835: 	}
16836: # Give them a new cookie
16837: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16838: 		                   : $now.$$.int(rand(10000)));
16839: 	$cookie="$username\_$id\_$domain\_$authhost";
16840:     
16841: # Initialize roles
16842: 
16843: 	($userroles,$firstaccenv,$timerintenv) = 
16844:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16845:     }
16846: # ------------------------------------ Check browser type and MathML capability
16847: 
16848:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16849:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16850: 
16851: # ------------------------------------------------------------- Get environment
16852: 
16853:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16854:     my ($tmp) = keys(%userenv);
16855:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
16856:     } else {
16857: 	undef(%userenv);
16858:     }
16859:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16860: 	$form->{'interface'}=$userenv{'interface'};
16861:     }
16862:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16863: 
16864: # --------------- Do not trust query string to be put directly into environment
16865:     foreach my $option ('interface','localpath','localres') {
16866:         $form->{$option}=~s/[\n\r\=]//gs;
16867:     }
16868: # --------------------------------------------------------- Write first profile
16869: 
16870:     {
16871:         my $ip = &Apache::lonnet::get_requestor_ip();
16872: 	my %initial_env = 
16873: 	    ("user.name"          => $username,
16874: 	     "user.domain"        => $domain,
16875: 	     "user.home"          => $authhost,
16876: 	     "browser.type"       => $clientbrowser,
16877: 	     "browser.version"    => $clientversion,
16878: 	     "browser.mathml"     => $clientmathml,
16879: 	     "browser.unicode"    => $clientunicode,
16880: 	     "browser.os"         => $clientos,
16881:              "browser.mobile"     => $clientmobile,
16882:              "browser.info"       => $clientinfo,
16883:              "browser.osversion"  => $clientosversion,
16884: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16885: 	     "request.course.fn"  => '',
16886: 	     "request.course.uri" => '',
16887: 	     "request.course.sec" => '',
16888: 	     "request.role"       => 'cm',
16889: 	     "request.role.adv"   => $env{'user.adv'},
16890: 	     "request.host"       => $ip,);
16891: 
16892:         if ($form->{'localpath'}) {
16893: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16894: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16895:         }
16896: 	
16897: 	if ($form->{'interface'}) {
16898: 	    $form->{'interface'}=~s/\W//gs;
16899: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16900: 	    $env{'browser.interface'}=$form->{'interface'};
16901: 	}
16902: 
16903:         if ($form->{'iptoken'}) {
16904:             my $lonhost = $r->dir_config('lonHostID');
16905:             $initial_env{"user.noloadbalance"} = $lonhost;
16906:             $env{'user.noloadbalance'} = $lonhost;
16907:         }
16908: 
16909:         if ($form->{'noloadbalance'}) {
16910:             my @hosts = &Apache::lonnet::current_machine_ids();
16911:             my $hosthere = $form->{'noloadbalance'};
16912:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16913:                 $initial_env{"user.noloadbalance"} = $hosthere;
16914:                 $env{'user.noloadbalance'} = $hosthere;
16915:             }
16916:         }
16917: 
16918:         unless ($domain eq 'public') {
16919:             my %is_adv = ( is_adv => $env{'user.adv'} );
16920:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16921: 
16922:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
16923:                 $userenv{'availabletools.'.$tool} = 
16924:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16925:                                                       undef,\%userenv,\%domdef,\%is_adv);
16926:             }
16927: 
16928:             foreach my $crstype ('official','unofficial','community','textbook','lti') {
16929:                 $userenv{'canrequest.'.$crstype} =
16930:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16931:                                                       'reload','requestcourses',
16932:                                                       \%userenv,\%domdef,\%is_adv);
16933:             }
16934: 
16935:             $userenv{'canrequest.author'} =
16936:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16937:                                                   'reload','requestauthor',
16938:                                                   \%userenv,\%domdef,\%is_adv);
16939:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16940:                                                  $domain,$username);
16941:             my $reqstatus = $reqauthor{'author_status'};
16942:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
16943:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16944:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16945:                                                       $reqauthor{'author'}{'timestamp'};
16946:                 }
16947:             }
16948:         }
16949: 
16950: 	$env{'user.environment'} = "$lonids/$cookie.id";
16951: 
16952: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16953: 		 &GDBM_WRCREAT(),0640)) {
16954: 	    &_add_to_env(\%disk_env,\%initial_env);
16955: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16956: 	    &_add_to_env(\%disk_env,$userroles);
16957:             if (ref($firstaccenv) eq 'HASH') {
16958:                 &_add_to_env(\%disk_env,$firstaccenv);
16959:             }
16960:             if (ref($timerintenv) eq 'HASH') {
16961:                 &_add_to_env(\%disk_env,$timerintenv);
16962:             }
16963: 	    if (ref($args->{'extra_env'})) {
16964: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16965: 	    }
16966: 	    untie(%disk_env);
16967: 	} else {
16968: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16969: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16970: 	    return 'error: '.$!;
16971: 	}
16972:     }
16973:     $env{'request.role'}='cm';
16974:     $env{'request.role.adv'}=$env{'user.adv'};
16975:     $env{'browser.type'}=$clientbrowser;
16976: 
16977:     return $cookie;
16978: 
16979: }
16980: 
16981: sub _add_to_env {
16982:     my ($idf,$env_data,$prefix) = @_;
16983:     if (ref($env_data) eq 'HASH') {
16984:         while (my ($key,$value) = each(%$env_data)) {
16985: 	    $idf->{$prefix.$key} = $value;
16986: 	    $env{$prefix.$key}   = $value;
16987:         }
16988:     }
16989: }
16990: 
16991: # --- Get the symbolic name of a problem and the url
16992: sub get_symb {
16993:     my ($request,$silent) = @_;
16994:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16995:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16996:     if ($symb eq '') {
16997:         if (!$silent) {
16998:             if (ref($request)) { 
16999:                 $request->print("Unable to handle ambiguous references:$url:.");
17000:             }
17001:             return ();
17002:         }
17003:     }
17004:     &Apache::lonenc::check_decrypt(\$symb);
17005:     return ($symb);
17006: }
17007: 
17008: # --------------------------------------------------------------Get annotation
17009: 
17010: sub get_annotation {
17011:     my ($symb,$enc) = @_;
17012: 
17013:     my $key = $symb;
17014:     if (!$enc) {
17015:         $key =
17016:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17017:     }
17018:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17019:     return $annotation{$key};
17020: }
17021: 
17022: sub clean_symb {
17023:     my ($symb,$delete_enc) = @_;
17024: 
17025:     &Apache::lonenc::check_decrypt(\$symb);
17026:     my $enc = $env{'request.enc'};
17027:     if ($delete_enc) {
17028:         delete($env{'request.enc'});
17029:     }
17030: 
17031:     return ($symb,$enc);
17032: }
17033: 
17034: ############################################################
17035: ############################################################
17036: 
17037: =pod
17038: 
17039: =head1 Routines for building display used to search for courses
17040: 
17041: 
17042: =over 4
17043: 
17044: =item * &build_filters()
17045: 
17046: Create markup for a table used to set filters to use when selecting
17047: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
17048: and quotacheck.pl
17049: 
17050: 
17051: Inputs:
17052: 
17053: filterlist - anonymous array of fields to include as potential filters
17054: 
17055: crstype - course type
17056: 
17057: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17058:               to pop-open a course selector (will contain "extra element").
17059: 
17060: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17061: 
17062: filter - anonymous hash of criteria and their values
17063: 
17064: action - form action
17065: 
17066: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17067: 
17068: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17069: 
17070: cloneruname - username of owner of new course who wants to clone
17071: 
17072: clonerudom - domain of owner of new course who wants to clone
17073: 
17074: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
17075: 
17076: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17077: 
17078: codedom - domain
17079: 
17080: formname - value of form element named "form".
17081: 
17082: fixeddom - domain, if fixed.
17083: 
17084: prevphase - value to assign to form element named "phase" when going back to the previous screen
17085: 
17086: cnameelement - name of form element in form on opener page which will receive title of selected course
17087: 
17088: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
17089: 
17090: cdomelement - name of form element in form on opener page which will receive domain of selected course
17091: 
17092: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17093: 
17094: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17095: 
17096: clonewarning - warning message about missing information for intended course owner when DC creates a course
17097: 
17098: 
17099: Returns: $output - HTML for display of search criteria, and hidden form elements.
17100: 
17101: 
17102: Side Effects: None
17103: 
17104: =cut
17105: 
17106: # ---------------------------------------------- search for courses based on last activity etc.
17107: 
17108: sub build_filters {
17109:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17110:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17111:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17112:         $cnameelement,$cnumelement,$cdomelement,$setroles,
17113:         $clonetext,$clonewarning) = @_;
17114:     my ($list,$jscript);
17115:     my $onchange = 'javascript:updateFilters(this)';
17116:     my ($domainselectform,$sincefilterform,$createdfilterform,
17117:         $ownerdomselectform,$persondomselectform,$instcodeform,
17118:         $typeselectform,$instcodetitle);
17119:     if ($formname eq '') {
17120:         $formname = $caller;
17121:     }
17122:     foreach my $item (@{$filterlist}) {
17123:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17124:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17125:             if ($item eq 'domainfilter') {
17126:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17127:             } elsif ($item eq 'coursefilter') {
17128:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17129:             } elsif ($item eq 'ownerfilter') {
17130:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17131:             } elsif ($item eq 'ownerdomfilter') {
17132:                 $filter->{'ownerdomfilter'} =
17133:                     &LONCAPA::clean_domain($filter->{$item});
17134:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17135:                                                        'ownerdomfilter',1);
17136:             } elsif ($item eq 'personfilter') {
17137:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17138:             } elsif ($item eq 'persondomfilter') {
17139:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17140:                                                         'persondomfilter',1);
17141:             } else {
17142:                 $filter->{$item} =~ s/\W//g;
17143:             }
17144:             if (!$filter->{$item}) {
17145:                 $filter->{$item} = '';
17146:             }
17147:         }
17148:         if ($item eq 'domainfilter') {
17149:             my $allow_blank = 1;
17150:             if ($formname eq 'portform') {
17151:                 $allow_blank=0;
17152:             } elsif ($formname eq 'studentform') {
17153:                 $allow_blank=0;
17154:             }
17155:             if ($fixeddom) {
17156:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
17157:                                     ' value="'.$codedom.'" />'.
17158:                                     &Apache::lonnet::domain($codedom,'description');
17159:             } else {
17160:                 $domainselectform = &select_dom_form($filter->{$item},
17161:                                                      'domainfilter',
17162:                                                       $allow_blank,'',$onchange);
17163:             }
17164:         } else {
17165:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17166:         }
17167:     }
17168: 
17169:     # last course activity filter and selection
17170:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
17171: 
17172:     # course created filter and selection
17173:     if (exists($filter->{'createdfilter'})) {
17174:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
17175:     }
17176: 
17177:     my %lt = &Apache::lonlocal::texthash(
17178:                 'cac' => "$crstype Activity",
17179:                 'ccr' => "$crstype Created",
17180:                 'cde' => "$crstype Title",
17181:                 'cdo' => "$crstype Domain",
17182:                 'ins' => 'Institutional Code',
17183:                 'inc' => 'Institutional Categorization',
17184:                 'cow' => "$crstype Owner/Co-owner",
17185:                 'cop' => "$crstype Personnel Includes",
17186:                 'cog' => 'Type',
17187:              );
17188: 
17189:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17190:         my $typeval = 'Course';
17191:         if ($crstype eq 'Community') {
17192:             $typeval = 'Community';
17193:         }
17194:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17195:     } else {
17196:         $typeselectform =  '<select name="type" size="1"';
17197:         if ($onchange) {
17198:             $typeselectform .= ' onchange="'.$onchange.'"';
17199:         }
17200:         $typeselectform .= '>'."\n";
17201:         foreach my $posstype ('Course','Community') {
17202:             $typeselectform.='<option value="'.$posstype.'"'.
17203:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
17204:         }
17205:         $typeselectform.="</select>";
17206:     }
17207: 
17208:     my ($cloneableonlyform,$cloneabletitle);
17209:     if (exists($filter->{'cloneableonly'})) {
17210:         my $cloneableon = '';
17211:         my $cloneableoff = ' checked="checked"';
17212:         if ($filter->{'cloneableonly'}) {
17213:             $cloneableon = $cloneableoff;
17214:             $cloneableoff = '';
17215:         }
17216:         $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>';
17217:         if ($formname eq 'ccrs') {
17218:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17219:         } else {
17220:             $cloneabletitle = &mt('Cloneable by you');
17221:         }
17222:     }
17223:     my $officialjs;
17224:     if ($crstype eq 'Course') {
17225:         if (exists($filter->{'instcodefilter'})) {
17226: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
17227: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17228:             if ($codedom) {
17229:                 $officialjs = 1;
17230:                 ($instcodeform,$jscript,$$numtitlesref) =
17231:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17232:                                                                   $officialjs,$codetitlesref);
17233:                 if ($jscript) {
17234:                     $jscript = '<script type="text/javascript">'."\n".
17235:                                '// <![CDATA['."\n".
17236:                                $jscript."\n".
17237:                                '// ]]>'."\n".
17238:                                '</script>'."\n";
17239:                 }
17240:             }
17241:             if ($instcodeform eq '') {
17242:                 $instcodeform =
17243:                     '<input type="text" name="instcodefilter" size="10" value="'.
17244:                     $list->{'instcodefilter'}.'" />';
17245:                 $instcodetitle = $lt{'ins'};
17246:             } else {
17247:                 $instcodetitle = $lt{'inc'};
17248:             }
17249:             if ($fixeddom) {
17250:                 $instcodetitle .= '<br />('.$codedom.')';
17251:             }
17252:         }
17253:     }
17254:     my $output = qq|
17255: <form method="post" name="filterpicker" action="$action">
17256: <input type="hidden" name="form" value="$formname" />
17257: |;
17258:     if ($formname eq 'modifycourse') {
17259:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17260:                    '<input type="hidden" name="prevphase" value="'.
17261:                    $prevphase.'" />'."\n";
17262:     } elsif ($formname eq 'quotacheck') {
17263:         $output .= qq|
17264: <input type="hidden" name="sortby" value="" />
17265: <input type="hidden" name="sortorder" value="" />
17266: |;
17267:     } else {
17268:         my $name_input;
17269:         if ($cnameelement ne '') {
17270:             $name_input = '<input type="hidden" name="cnameelement" value="'.
17271:                           $cnameelement.'" />';
17272:         }
17273:         $output .= qq|
17274: <input type="hidden" name="cnumelement" value="$cnumelement" />
17275: <input type="hidden" name="cdomelement" value="$cdomelement" />
17276: $name_input
17277: $roleelement
17278: $multelement
17279: $typeelement
17280: |;
17281:         if ($formname eq 'portform') {
17282:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17283:         }
17284:     }
17285:     if ($fixeddom) {
17286:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17287:     }
17288:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17289:     if ($sincefilterform) {
17290:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17291:                   .$sincefilterform
17292:                   .&Apache::lonhtmlcommon::row_closure();
17293:     }
17294:     if ($createdfilterform) {
17295:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17296:                   .$createdfilterform
17297:                   .&Apache::lonhtmlcommon::row_closure();
17298:     }
17299:     if ($domainselectform) {
17300:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17301:                   .$domainselectform
17302:                   .&Apache::lonhtmlcommon::row_closure();
17303:     }
17304:     if ($typeselectform) {
17305:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17306:             $output .= $typeselectform;
17307:         } else {
17308:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17309:                       .$typeselectform
17310:                       .&Apache::lonhtmlcommon::row_closure();
17311:         }
17312:     }
17313:     if ($instcodeform) {
17314:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17315:                   .$instcodeform
17316:                   .&Apache::lonhtmlcommon::row_closure();
17317:     }
17318:     if (exists($filter->{'ownerfilter'})) {
17319:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17320:                    '<table><tr><td>'.&mt('Username').'<br />'.
17321:                    '<input type="text" name="ownerfilter" size="20" value="'.
17322:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17323:                    $ownerdomselectform.'</td></tr></table>'.
17324:                    &Apache::lonhtmlcommon::row_closure();
17325:     }
17326:     if (exists($filter->{'personfilter'})) {
17327:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17328:                    '<table><tr><td>'.&mt('Username').'<br />'.
17329:                    '<input type="text" name="personfilter" size="20" value="'.
17330:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17331:                    $persondomselectform.'</td></tr></table>'.
17332:                    &Apache::lonhtmlcommon::row_closure();
17333:     }
17334:     if (exists($filter->{'coursefilter'})) {
17335:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17336:                   .'<input type="text" name="coursefilter" size="25" value="'
17337:                   .$list->{'coursefilter'}.'" />'
17338:                   .&Apache::lonhtmlcommon::row_closure();
17339:     }
17340:     if ($cloneableonlyform) {
17341:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17342:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17343:     }
17344:     if (exists($filter->{'descriptfilter'})) {
17345:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17346:                   .'<input type="text" name="descriptfilter" size="40" value="'
17347:                   .$list->{'descriptfilter'}.'" />'
17348:                   .&Apache::lonhtmlcommon::row_closure(1);
17349:     }
17350:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17351:                '<input type="hidden" name="updater" value="" />'."\n".
17352:                '<input type="submit" name="gosearch" value="'.
17353:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17354:     return $jscript.$clonewarning.$output;
17355: }
17356: 
17357: =pod
17358: 
17359: =item * &timebased_select_form()
17360: 
17361: Create markup for a dropdown list used to select a time-based
17362: filter e.g., Course Activity, Course Created, when searching for courses
17363: or communities
17364: 
17365: Inputs:
17366: 
17367: item - name of form element (sincefilter or createdfilter)
17368: 
17369: filter - anonymous hash of criteria and their values
17370: 
17371: Returns: HTML for a select box contained a blank, then six time selections,
17372:          with value set in incoming form variables currently selected.
17373: 
17374: Side Effects: None
17375: 
17376: =cut
17377: 
17378: sub timebased_select_form {
17379:     my ($item,$filter) = @_;
17380:     if (ref($filter) eq 'HASH') {
17381:         $filter->{$item} =~ s/[^\d-]//g;
17382:         if (!$filter->{$item}) { $filter->{$item}=-1; }
17383:         return &select_form(
17384:                             $filter->{$item},
17385:                             $item,
17386:                             {      '-1' => '',
17387:                                 '86400' => &mt('today'),
17388:                                '604800' => &mt('last week'),
17389:                               '2592000' => &mt('last month'),
17390:                               '7776000' => &mt('last three months'),
17391:                              '15552000' => &mt('last six months'),
17392:                              '31104000' => &mt('last year'),
17393:                     'select_form_order' =>
17394:                            ['-1','86400','604800','2592000','7776000',
17395:                             '15552000','31104000']});
17396:     }
17397: }
17398: 
17399: =pod
17400: 
17401: =item * &js_changer()
17402: 
17403: Create script tag containing Javascript used to submit course search form
17404: when course type or domain is changed, and also to hide 'Searching ...' on
17405: page load completion for page showing search result.
17406: 
17407: Inputs: None
17408: 
17409: Returns: markup containing updateFilters() and hideSearching() javascript functions.
17410: 
17411: Side Effects: None
17412: 
17413: =cut
17414: 
17415: sub js_changer {
17416:     return <<ENDJS;
17417: <script type="text/javascript">
17418: // <![CDATA[
17419: function updateFilters(caller) {
17420:     if (typeof(caller) != "undefined") {
17421:         document.filterpicker.updater.value = caller.name;
17422:     }
17423:     document.filterpicker.submit();
17424: }
17425: 
17426: function hideSearching() {
17427:     if (document.getElementById('searching')) {
17428:         document.getElementById('searching').style.display = 'none';
17429:     }
17430:     return;
17431: }
17432: 
17433: // ]]>
17434: </script>
17435: 
17436: ENDJS
17437: }
17438: 
17439: =pod
17440: 
17441: =item * &search_courses()
17442: 
17443: Process selected filters form course search form and pass to lonnet::courseiddump
17444: to retrieve a hash for which keys are courseIDs which match the selected filters.
17445: 
17446: Inputs:
17447: 
17448: dom - domain being searched
17449: 
17450: type - course type ('Course' or 'Community' or '.' if any).
17451: 
17452: filter - anonymous hash of criteria and their values
17453: 
17454: numtitles - for institutional codes - number of categories
17455: 
17456: cloneruname - optional username of new course owner
17457: 
17458: clonerudom - optional domain of new course owner
17459: 
17460: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
17461:             (used when DC is using course creation form)
17462: 
17463: codetitles - reference to array of titles of components in institutional codes (official courses).
17464: 
17465: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17466:            (and so can clone automatically)
17467: 
17468: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17469: 
17470: reqinstcode - institutional code of new course, where search_courses is used to identify potential
17471:               courses to clone
17472: 
17473: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17474: 
17475: 
17476: Side Effects: None
17477: 
17478: =cut
17479: 
17480: 
17481: sub search_courses {
17482:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17483:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17484:     my (%courses,%showcourses,$cloner);
17485:     if (($filter->{'ownerfilter'} ne '') ||
17486:         ($filter->{'ownerdomfilter'} ne '')) {
17487:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17488:                                        $filter->{'ownerdomfilter'};
17489:     }
17490:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17491:         if (!$filter->{$item}) {
17492:             $filter->{$item}='.';
17493:         }
17494:     }
17495:     my $now = time;
17496:     my $timefilter =
17497:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17498:     my ($createdbefore,$createdafter);
17499:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17500:         $createdbefore = $now;
17501:         $createdafter = $now-$filter->{'createdfilter'};
17502:     }
17503:     my ($instcodefilter,$regexpok);
17504:     if ($numtitles) {
17505:         if ($env{'form.official'} eq 'on') {
17506:             $instcodefilter =
17507:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17508:             $regexpok = 1;
17509:         } elsif ($env{'form.official'} eq 'off') {
17510:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17511:             unless ($instcodefilter eq '') {
17512:                 $regexpok = -1;
17513:             }
17514:         }
17515:     } else {
17516:         $instcodefilter = $filter->{'instcodefilter'};
17517:     }
17518:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
17519:     if ($type eq '') { $type = '.'; }
17520: 
17521:     if (($clonerudom ne '') && ($cloneruname ne '')) {
17522:         $cloner = $cloneruname.':'.$clonerudom;
17523:     }
17524:     %courses = &Apache::lonnet::courseiddump($dom,
17525:                                              $filter->{'descriptfilter'},
17526:                                              $timefilter,
17527:                                              $instcodefilter,
17528:                                              $filter->{'combownerfilter'},
17529:                                              $filter->{'coursefilter'},
17530:                                              undef,undef,$type,$regexpok,undef,undef,
17531:                                              undef,undef,$cloner,$cc_clone,
17532:                                              $filter->{'cloneableonly'},
17533:                                              $createdbefore,$createdafter,undef,
17534:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
17535:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17536:         my $ccrole;
17537:         if ($type eq 'Community') {
17538:             $ccrole = 'co';
17539:         } else {
17540:             $ccrole = 'cc';
17541:         }
17542:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17543:                                                      $filter->{'persondomfilter'},
17544:                                                      'userroles',undef,
17545:                                                      [$ccrole,'in','ad','ep','ta','cr'],
17546:                                                      $dom);
17547:         foreach my $role (keys(%rolehash)) {
17548:             my ($cnum,$cdom,$courserole) = split(':',$role);
17549:             my $cid = $cdom.'_'.$cnum;
17550:             if (exists($courses{$cid})) {
17551:                 if (ref($courses{$cid}) eq 'HASH') {
17552:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17553:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17554:                             push(@{$courses{$cid}{roles}},$courserole);
17555:                         }
17556:                     } else {
17557:                         $courses{$cid}{roles} = [$courserole];
17558:                     }
17559:                     $showcourses{$cid} = $courses{$cid};
17560:                 }
17561:             }
17562:         }
17563:         %courses = %showcourses;
17564:     }
17565:     return %courses;
17566: }
17567: 
17568: =pod
17569: 
17570: =back
17571: 
17572: =head1 Routines for version requirements for current course.
17573: 
17574: =over 4
17575: 
17576: =item * &check_release_required()
17577: 
17578: Compares required LON-CAPA version with version on server, and
17579: if required version is newer looks for a server with the required version.
17580: 
17581: Looks first at servers in user's owen domain; if none suitable, looks at
17582: servers in course's domain are permitted to host sessions for user's domain.
17583: 
17584: Inputs:
17585: 
17586: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17587: 
17588: $courseid - Course ID of current course
17589: 
17590: $rolecode - User's current role in course (for switchserver query string).
17591: 
17592: $required - LON-CAPA version needed by course (format: Major.Minor).
17593: 
17594: 
17595: Returns:
17596: 
17597: $switchserver - query string tp append to /adm/switchserver call (if
17598:                 current server's LON-CAPA version is too old.
17599: 
17600: $warning - Message is displayed if no suitable server could be found.
17601: 
17602: =cut
17603: 
17604: sub check_release_required {
17605:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
17606:     my ($switchserver,$warning);
17607:     if ($required ne '') {
17608:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17609:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17610:         if ($reqdmajor ne '' && $reqdminor ne '') {
17611:             my $otherserver;
17612:             if (($major eq '' && $minor eq '') ||
17613:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17614:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17615:                 my $switchlcrev =
17616:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17617:                                                            $userdomserver);
17618:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17619:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17620:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17621:                     my $cdom = $env{'course.'.$courseid.'.domain'};
17622:                     if ($cdom ne $env{'user.domain'}) {
17623:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17624:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17625:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17626:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17627:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17628:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17629:                         my $canhost =
17630:                             &Apache::lonnet::can_host_session($env{'user.domain'},
17631:                                                               $coursedomserver,
17632:                                                               $remoterev,
17633:                                                               $udomdefaults{'remotesessions'},
17634:                                                               $defdomdefaults{'hostedsessions'});
17635: 
17636:                         if ($canhost) {
17637:                             $otherserver = $coursedomserver;
17638:                         } else {
17639:                             $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.");
17640:                         }
17641:                     } else {
17642:                         $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).");
17643:                     }
17644:                 } else {
17645:                     $otherserver = $userdomserver;
17646:                 }
17647:             }
17648:             if ($otherserver ne '') {
17649:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
17650:             }
17651:         }
17652:     }
17653:     return ($switchserver,$warning);
17654: }
17655: 
17656: =pod
17657: 
17658: =item * &check_release_result()
17659: 
17660: Inputs:
17661: 
17662: $switchwarning - Warning message if no suitable server found to host session.
17663: 
17664: $switchserver - query string to append to /adm/switchserver containing lonHostID
17665:                 and current role.
17666: 
17667: Returns: HTML to display with information about requirement to switch server.
17668:          Either displaying warning with link to Roles/Courses screen or
17669:          display link to switchserver.
17670: 
17671: =cut
17672: 
17673: sub check_release_result {
17674:     my ($switchwarning,$switchserver) = @_;
17675:     my $output = &start_page('Selected course unavailable on this server').
17676:                  '<p class="LC_warning">';
17677:     if ($switchwarning) {
17678:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
17679:         if (&show_course()) {
17680:             $output .= &mt('Display courses');
17681:         } else {
17682:             $output .= &mt('Display roles');
17683:         }
17684:         $output .= '</a>';
17685:     } elsif ($switchserver) {
17686:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17687:                    '<br />'.
17688:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
17689:                    &mt('Switch Server').
17690:                    '</a>';
17691:     }
17692:     $output .= '</p>'.&end_page();
17693:     return $output;
17694: }
17695: 
17696: =pod
17697: 
17698: =item * &needs_coursereinit()
17699: 
17700: Determine if course contents stored for user's session needs to be
17701: refreshed, because content has changed since "Big Hash" last tied.
17702: 
17703: Check for change is made if time last checked is more than 10 minutes ago
17704: (by default).
17705: 
17706: Inputs:
17707: 
17708: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17709: 
17710: $interval (optional) - Time which may elapse (in s) between last check for content
17711:                        change in current course. (default: 600 s).
17712: 
17713: Returns: an array; first element is:
17714: 
17715: =over 4
17716: 
17717: 'switch' - if content updates mean user's session
17718:            needs to be switched to a server running a newer LON-CAPA version
17719: 
17720: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17721:            on current server hosting user's session
17722: 
17723: ''       - if no action required.
17724: 
17725: =back
17726: 
17727: If first item element is 'switch':
17728: 
17729: second item is $switchwarning - Warning message if no suitable server found to host session.
17730: 
17731: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17732:                               and current role.
17733: 
17734: otherwise: no other elements returned.
17735: 
17736: =back
17737: 
17738: =cut
17739: 
17740: sub needs_coursereinit {
17741:     my ($loncaparev,$interval) = @_;
17742:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17743:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17744:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17745:     my $now = time;
17746:     if ($interval eq '') {
17747:         $interval = 600;
17748:     }
17749:     if (($now-$env{'request.course.timechecked'})>$interval) {
17750:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17751:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
17752:         if ($blocked) {
17753:             return ();
17754:         }
17755:         my $update;
17756:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17757:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
17758:         if ($lastmainchange > $env{'request.course.tied'}) {
17759:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
17760:             if ($needswitch) {
17761:                 return ('switch',$switchwarning,$switchserver);
17762:             }
17763:             $update = 'main';
17764:         }
17765:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
17766:             if ($update) {
17767:                 $update = 'both';
17768:             } else {
17769:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
17770:                 if ($needswitch) {
17771:                     return ('switch',$switchwarning,$switchserver);
17772:                 } else {
17773:                     $update = 'supp';
17774:                 }
17775:             }
17776:             return ($update);
17777:         }
17778:     }
17779:     return ();
17780: }
17781: 
17782: sub switch_for_update {
17783:     my ($loncaparev,$cdom,$cnum) = @_;
17784:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17785:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17786:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17787:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17788:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17789:                                     $curr_reqd_hash{'internal.releaserequired'}});
17790:             my ($switchserver,$switchwarning) =
17791:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17792:                                         $curr_reqd_hash{'internal.releaserequired'});
17793:             if ($switchwarning ne '' || $switchserver ne '') {
17794:                 return ('switch',$switchwarning,$switchserver);
17795:             }
17796:         }
17797:     }
17798:     return ();
17799: }
17800: 
17801: sub update_content_constraints {
17802:     my ($cdom,$cnum,$chome,$cid) = @_;
17803:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17804:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17805:     my %checkresponsetypes;
17806:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17807:         my ($item,$name,$value) = split(/:/,$key);
17808:         if ($item eq 'resourcetag') {
17809:             if ($name eq 'responsetype') {
17810:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17811:             }
17812:         }
17813:     }
17814:     my $navmap = Apache::lonnavmaps::navmap->new();
17815:     if (defined($navmap)) {
17816:         my %allresponses;
17817:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
17818:             my %responses = $res->responseTypes();
17819:             foreach my $key (keys(%responses)) {
17820:                 next unless(exists($checkresponsetypes{$key}));
17821:                 $allresponses{$key} += $responses{$key};
17822:             }
17823:         }
17824:         foreach my $key (keys(%allresponses)) {
17825:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17826:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17827:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17828:             }
17829:         }
17830:         undef($navmap);
17831:     }
17832:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17833:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17834:     }
17835:     return;
17836: }
17837: 
17838: sub allmaps_incourse {
17839:     my ($cdom,$cnum,$chome,$cid) = @_;
17840:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17841:         $cid = $env{'request.course.id'};
17842:         $cdom = $env{'course.'.$cid.'.domain'};
17843:         $cnum = $env{'course.'.$cid.'.num'};
17844:         $chome = $env{'course.'.$cid.'.home'};
17845:     }
17846:     my %allmaps = ();
17847:     my $lastchange =
17848:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17849:     if ($lastchange > $env{'request.course.tied'}) {
17850:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17851:         unless ($ferr) {
17852:             &update_content_constraints($cdom,$cnum,$chome,$cid);
17853:         }
17854:     }
17855:     my $navmap = Apache::lonnavmaps::navmap->new();
17856:     if (defined($navmap)) {
17857:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17858:             $allmaps{$res->src()} = 1;
17859:         }
17860:     }
17861:     return \%allmaps;
17862: }
17863: 
17864: sub parse_supplemental_title {
17865:     my ($title) = @_;
17866: 
17867:     my ($foldertitle,$renametitle);
17868:     if ($title =~ /&amp;&amp;&amp;/) {
17869:         $title = &HTML::Entites::decode($title);
17870:     }
17871:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17872:         $renametitle=$4;
17873:         my ($time,$uname,$udom) = ($1,$2,$3);
17874:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17875:         my $name =  &plainname($uname,$udom);
17876:         $name = &HTML::Entities::encode($name,'"<>&\'');
17877:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17878:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
17879:         if ($foldertitle ne '') {
17880:             $title .= ': <br />'.$foldertitle;
17881:         }
17882:     }
17883:     if (wantarray) {
17884:         return ($title,$foldertitle,$renametitle);
17885:     }
17886:     return $title;
17887: }
17888: 
17889: sub get_supplemental {
17890:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
17891:     my $hashid=$cnum.':'.$cdom;
17892:     my ($supplemental,$cached,$set_httprefs);
17893:     unless ($ignorecache) {
17894:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
17895:     }
17896:     unless (defined($cached)) {
17897:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
17898:         unless ($chome eq 'no_host') {
17899:             my @order = @LONCAPA::map::order;
17900:             my @resources = @LONCAPA::map::resources;
17901:             my @resparms = @LONCAPA::map::resparms;
17902:             my @zombies = @LONCAPA::map::zombies;
17903:             my ($errors,%ids,%hidden);
17904:             $errors =
17905:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
17906:                                       $errors,$possdel,\%ids,\%hidden);
17907:             @LONCAPA::map::order = @order;
17908:             @LONCAPA::map::resources = @resources;
17909:             @LONCAPA::map::resparms = @resparms;
17910:             @LONCAPA::map::zombies = @zombies;
17911:             $set_httprefs = 1;
17912:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
17913:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
17914:             }
17915:             $supplemental = {
17916:                                ids => \%ids,
17917:                                hidden => \%hidden,
17918:                             };
17919:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
17920:         }
17921:     }
17922:     return ($supplemental,$set_httprefs);
17923: }
17924: 
17925: sub recurse_supplemental {
17926:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
17927:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
17928:         my $mapnum;
17929:         if ($suppmap eq 'supplemental.sequence') {
17930:             $mapnum = 0;
17931:         } else {
17932:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
17933:         }
17934:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17935:         if ($fatal) {
17936:             $errors ++;
17937:         } else {
17938:             my @order = @LONCAPA::map::order;
17939:             if (@order > 0) {
17940:                 my @resources = @LONCAPA::map::resources;
17941:                 my @resparms = @LONCAPA::map::resparms;
17942:                 foreach my $idx (@order) {
17943:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
17944:                     if (($src ne '') && ($status eq 'res')) {
17945:                         my $id = $mapnum.':'.$idx;
17946:                         push(@{$suppids->{$src}},$id);
17947:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
17948:                             $hiddensupp->{$id} = 1;
17949:                         }
17950:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17951:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
17952:                                                             $hiddensupp,$hiddensupp->{$id});
17953:                         } else {
17954:                             my $allowed;
17955:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
17956:                                 $allowed = 1;
17957:                             } elsif ($possdel) {
17958:                                 foreach my $item (@{$suppids->{$src}}) {
17959:                                     next if ($item eq $id);
17960:                                     unless ($hiddensupp->{$item}) {
17961:                                        $allowed = 1;
17962:                                        last;
17963:                                     }
17964:                                 }
17965:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
17966:                                     &Apache::lonnet::delenv('httpref.'.$src);
17967:                                 }
17968:                             }
17969:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
17970:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
17971:                             }
17972:                         }
17973:                     }
17974:                 }
17975:             }
17976:         }
17977:     }
17978:     return $errors;
17979: }
17980: 
17981: sub set_supp_httprefs {
17982:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
17983:     if (ref($supplemental) eq 'HASH') {
17984:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
17985:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
17986:                 next if ($src =~ /\.sequence$/);
17987:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
17988:                     my $allowed;
17989:                     if ($env{'request.role.adv'}) {
17990:                         $allowed = 1;
17991:                     } else {
17992:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
17993:                             unless ($supplemental->{'hidden'}->{$id}) {
17994:                                 $allowed = 1;
17995:                                 last;
17996:                             }
17997:                         }
17998:                     }
17999:                     if (exists($env{'httpref.'.$src})) {
18000:                         if ($possdel) {
18001:                             unless ($allowed) {
18002:                                 &Apache::lonnet::delenv('httpref.'.$src);
18003:                             }
18004:                         }
18005:                     } elsif ($allowed) {
18006:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18007:                     }
18008:                 }
18009:             }
18010:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18011:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18012:             }
18013:         }
18014:     }
18015: }
18016: 
18017: sub get_supp_parameter {
18018:     my ($resparm,$name)=@_;
18019:     return if ($resparm eq '');
18020:     my $value=undef;
18021:     my $ptype=undef;
18022:     foreach (split('&&&',$resparm)) {
18023:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
18024:         if ($thisname eq $name) {
18025:             $value=$thisvalue;
18026:             $ptype=$thistype;
18027:         }
18028:     }
18029:     return $value;
18030: }
18031: 
18032: sub symb_to_docspath {
18033:     my ($symb,$navmapref) = @_;
18034:     return unless ($symb && ref($navmapref));
18035:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18036:     if ($resurl=~/\.(sequence|page)$/) {
18037:         $mapurl=$resurl;
18038:     } elsif ($resurl eq 'adm/navmaps') {
18039:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18040:     }
18041:     my $mapresobj;
18042:     unless (ref($$navmapref)) {
18043:         $$navmapref = Apache::lonnavmaps::navmap->new();
18044:     }
18045:     if (ref($$navmapref)) {
18046:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18047:     }
18048:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18049:     my $type=$2;
18050:     my $path;
18051:     if (ref($mapresobj)) {
18052:         my $pcslist = $mapresobj->map_hierarchy();
18053:         if ($pcslist ne '') {
18054:             foreach my $pc (split(/,/,$pcslist)) {
18055:                 next if ($pc <= 1);
18056:                 my $res = $$navmapref->getByMapPc($pc);
18057:                 if (ref($res)) {
18058:                     my $thisurl = $res->src();
18059:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18060:                     my $thistitle = $res->title();
18061:                     $path .= '&'.
18062:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18063:                              &escape($thistitle).
18064:                              ':'.$res->randompick().
18065:                              ':'.$res->randomout().
18066:                              ':'.$res->encrypted().
18067:                              ':'.$res->randomorder().
18068:                              ':'.$res->is_page();
18069:                 }
18070:             }
18071:         }
18072:         $path =~ s/^\&//;
18073:         my $maptitle = $mapresobj->title();
18074:         if ($mapurl eq 'default') {
18075:             $maptitle = 'Main Content';
18076:         }
18077:         $path .= (($path ne '')? '&' : '').
18078:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18079:                  &escape($maptitle).
18080:                  ':'.$mapresobj->randompick().
18081:                  ':'.$mapresobj->randomout().
18082:                  ':'.$mapresobj->encrypted().
18083:                  ':'.$mapresobj->randomorder().
18084:                  ':'.$mapresobj->is_page();
18085:     } else {
18086:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
18087:         my $ispage = (($type eq 'page')? 1 : '');
18088:         if ($mapurl eq 'default') {
18089:             $maptitle = 'Main Content';
18090:         }
18091:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18092:                 &escape($maptitle).':::::'.$ispage;
18093:     }
18094:     unless ($mapurl eq 'default') {
18095:         $path = 'default&'.
18096:                 &escape('Main Content').
18097:                 ':::::&'.$path;
18098:     }
18099:     return $path;
18100: }
18101: 
18102: sub validate_folderpath {
18103:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
18104:     if ($env{'form.folderpath'} ne '') {
18105:         my @items = split(/\&/,$env{'form.folderpath'});
18106:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
18107:         for (my $i=0; $i<@items; $i++) {
18108:             my $odd = $i%2;
18109:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
18110:                 $badpath = 1;
18111:             } elsif ($odd && $supplementalflag) {
18112:                 my $idx = $i-1;
18113:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
18114:                     my $esc_name = $1;
18115:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
18116:                         $supppath .= '&'.$esc_name;
18117:                         $changed = 1;
18118:                     } else {
18119:                         $supppath .= '&'.$items[$i];
18120:                     }
18121:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
18122:                     $changed = 1;
18123:                     my $is_hidden;
18124:                     unless ($got_supp) {
18125:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
18126:                         if (ref($supplemental) eq 'HASH') {
18127:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
18128:                                 %supphidden = %{$supplemental->{'hidden'}};
18129:                             }
18130:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
18131:                                 %suppids = %{$supplemental->{'ids'}};
18132:                             }
18133:                         }
18134:                         $got_supp = 1;
18135:                     }
18136:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
18137:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
18138:                         if ($supphidden{$mapid}) {
18139:                             $is_hidden = 1;
18140:                         }
18141:                     }
18142:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
18143:                 } else {
18144:                     $supppath .= '&'.$items[$i];
18145:                 }
18146:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
18147:                 $badpath = 1;
18148:             } elsif ($supplementalflag) {
18149:                 $supppath .= '&'.$items[$i];
18150:             }
18151:             last if ($badpath);
18152:         }
18153:         if ($badpath) {
18154:             delete($env{'form.folderpath'});
18155:         } elsif ($changed && $supplementalflag) {
18156:             $supppath =~ s/^\&//;
18157:             $env{'form.folderpath'} = $supppath;
18158:         }
18159:     }
18160:     return;
18161: }
18162: 
18163: sub captcha_display {
18164:     my ($context,$lonhost,$defdom) = @_;
18165:     my ($output,$error);
18166:     my ($captcha,$pubkey,$privkey,$version) =
18167:         &get_captcha_config($context,$lonhost,$defdom);
18168:     if ($captcha eq 'original') {
18169:         $output = &create_captcha();
18170:         unless ($output) {
18171:             $error = 'captcha';
18172:         }
18173:     } elsif ($captcha eq 'recaptcha') {
18174:         $output = &create_recaptcha($pubkey,$version);
18175:         unless ($output) {
18176:             $error = 'recaptcha';
18177:         }
18178:     }
18179:     return ($output,$error,$captcha,$version);
18180: }
18181: 
18182: sub captcha_response {
18183:     my ($context,$lonhost,$defdom) = @_;
18184:     my ($captcha_chk,$captcha_error);
18185:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
18186:     if ($captcha eq 'original') {
18187:         ($captcha_chk,$captcha_error) = &check_captcha();
18188:     } elsif ($captcha eq 'recaptcha') {
18189:         $captcha_chk = &check_recaptcha($privkey,$version);
18190:     } else {
18191:         $captcha_chk = 1;
18192:     }
18193:     return ($captcha_chk,$captcha_error);
18194: }
18195: 
18196: sub get_captcha_config {
18197:     my ($context,$lonhost,$dom_in_effect) = @_;
18198:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
18199:     my $hostname = &Apache::lonnet::hostname($lonhost);
18200:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
18201:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18202:     if ($context eq 'usercreation') {
18203:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
18204:         if (ref($domconfig{$context}) eq 'HASH') {
18205:             $hashtocheck = $domconfig{$context}{'cancreate'};
18206:             if (ref($hashtocheck) eq 'HASH') {
18207:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
18208:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
18209:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
18210:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
18211:                     }
18212:                     if ($privkey && $pubkey) {
18213:                         $captcha = 'recaptcha';
18214:                         $version = $hashtocheck->{'recaptchaversion'};
18215:                         if ($version ne '2') {
18216:                             $version = 1;
18217:                         }
18218:                     } else {
18219:                         $captcha = 'original';
18220:                     }
18221:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
18222:                     $captcha = 'original';
18223:                 }
18224:             }
18225:         } else {
18226:             $captcha = 'captcha';
18227:         }
18228:     } elsif ($context eq 'login') {
18229:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
18230:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
18231:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
18232:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
18233:             if ($privkey && $pubkey) {
18234:                 $captcha = 'recaptcha';
18235:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
18236:                 if ($version ne '2') {
18237:                     $version = 1;
18238:                 }
18239:             } else {
18240:                 $captcha = 'original';
18241:             }
18242:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
18243:             $captcha = 'original';
18244:         }
18245:     } elsif ($context eq 'passwords') {
18246:         if ($dom_in_effect) {
18247:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
18248:             if ($passwdconf{'captcha'} eq 'recaptcha') {
18249:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
18250:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
18251:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
18252:                 }
18253:                 if ($privkey && $pubkey) {
18254:                     $captcha = 'recaptcha';
18255:                     $version = $passwdconf{'recaptchaversion'};
18256:                     if ($version ne '2') {
18257:                         $version = 1;
18258:                     }
18259:                 } else {
18260:                     $captcha = 'original';
18261:                 }
18262:             } elsif ($passwdconf{'captcha'} ne 'notused') {
18263:                 $captcha = 'original';
18264:             }
18265:         }
18266:     }
18267:     return ($captcha,$pubkey,$privkey,$version);
18268: }
18269: 
18270: sub create_captcha {
18271:     my %captcha_params = &captcha_settings();
18272:     my ($output,$maxtries,$tries) = ('',10,0);
18273:     while ($tries < $maxtries) {
18274:         $tries ++;
18275:         my $captcha = Authen::Captcha->new (
18276:                                            output_folder => $captcha_params{'output_dir'},
18277:                                            data_folder   => $captcha_params{'db_dir'},
18278:                                           );
18279:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
18280: 
18281:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
18282:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
18283:                       '<span class="LC_nobreak">'.
18284:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
18285:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
18286:                       '</span><br />'.
18287:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
18288:             last;
18289:         }
18290:     }
18291:     if ($output eq '') {
18292:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
18293:     }
18294:     return $output;
18295: }
18296: 
18297: sub captcha_settings {
18298:     my %captcha_params = (
18299:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
18300:                            www_output_dir => "/captchaspool",
18301:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
18302:                            numchars       => '5',
18303:                          );
18304:     return %captcha_params;
18305: }
18306: 
18307: sub check_captcha {
18308:     my ($captcha_chk,$captcha_error);
18309:     my $code = $env{'form.code'};
18310:     my $md5sum = $env{'form.crypt'};
18311:     my %captcha_params = &captcha_settings();
18312:     my $captcha = Authen::Captcha->new(
18313:                       output_folder => $captcha_params{'output_dir'},
18314:                       data_folder   => $captcha_params{'db_dir'},
18315:                   );
18316:     $captcha_chk = $captcha->check_code($code,$md5sum);
18317:     my %captcha_hash = (
18318:                         0       => 'Code not checked (file error)',
18319:                        -1      => 'Failed: code expired',
18320:                        -2      => 'Failed: invalid code (not in database)',
18321:                        -3      => 'Failed: invalid code (code does not match crypt)',
18322:     );
18323:     if ($captcha_chk != 1) {
18324:         $captcha_error = $captcha_hash{$captcha_chk}
18325:     }
18326:     return ($captcha_chk,$captcha_error);
18327: }
18328: 
18329: sub create_recaptcha {
18330:     my ($pubkey,$version) = @_;
18331:     if ($version >= 2) {
18332:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
18333:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
18334:     } else {
18335:         my $use_ssl;
18336:         if ($ENV{'SERVER_PORT'} == 443) {
18337:             $use_ssl = 1;
18338:         }
18339:         my $captcha = Captcha::reCAPTCHA->new;
18340:         return $captcha->get_options_setter({theme => 'white'})."\n".
18341:                $captcha->get_html($pubkey,undef,$use_ssl).
18342:                &mt('If the text is hard to read, [_1] will replace them.',
18343:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
18344:                '<br /><br />';
18345:      }
18346: }
18347: 
18348: sub check_recaptcha {
18349:     my ($privkey,$version) = @_;
18350:     my $captcha_chk;
18351:     my $ip = &Apache::lonnet::get_requestor_ip(); 
18352:     if ($version >= 2) {
18353:         my $ua = LWP::UserAgent->new;
18354:         $ua->timeout(10);
18355:         my %info = (
18356:                      secret   => $privkey,
18357:                      response => $env{'form.g-recaptcha-response'},
18358:                      remoteip => $ip,
18359:                    );
18360:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
18361:         if ($response->is_success)  {
18362:             my $data = JSON::DWIW->from_json($response->decoded_content);
18363:             if (ref($data) eq 'HASH') {
18364:                 if ($data->{'success'}) {
18365:                     $captcha_chk = 1;
18366:                 }
18367:             }
18368:         }
18369:     } else {
18370:         my $captcha = Captcha::reCAPTCHA->new;
18371:         my $captcha_result =
18372:             $captcha->check_answer(
18373:                                     $privkey,
18374:                                     $ip,
18375:                                     $env{'form.recaptcha_challenge_field'},
18376:                                     $env{'form.recaptcha_response_field'},
18377:                                   );
18378:         if ($captcha_result->{is_valid}) {
18379:             $captcha_chk = 1;
18380:         }
18381:     }
18382:     return $captcha_chk;
18383: }
18384: 
18385: sub emailusername_info {
18386:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
18387:     my %titles = &Apache::lonlocal::texthash (
18388:                      lastname      => 'Last Name',
18389:                      firstname     => 'First Name',
18390:                      institution   => 'School/college/university',
18391:                      location      => "School's city, state/province, country",
18392:                      web           => "School's web address",
18393:                      officialemail => 'E-mail address at institution (if different)',
18394:                      id            => 'Student/Employee ID',
18395:                  );
18396:     return (\@fields,\%titles);
18397: }
18398: 
18399: sub cleanup_html {
18400:     my ($incoming) = @_;
18401:     my $outgoing;
18402:     if ($incoming ne '') {
18403:         $outgoing = $incoming;
18404:         $outgoing =~ s/;/&#059;/g;
18405:         $outgoing =~ s/\#/&#035;/g;
18406:         $outgoing =~ s/\&/&#038;/g;
18407:         $outgoing =~ s/</&#060;/g;
18408:         $outgoing =~ s/>/&#062;/g;
18409:         $outgoing =~ s/\(/&#040/g;
18410:         $outgoing =~ s/\)/&#041;/g;
18411:         $outgoing =~ s/"/&#034;/g;
18412:         $outgoing =~ s/'/&#039;/g;
18413:         $outgoing =~ s/\$/&#036;/g;
18414:         $outgoing =~ s{/}{&#047;}g;
18415:         $outgoing =~ s/=/&#061;/g;
18416:         $outgoing =~ s/\\/&#092;/g
18417:     }
18418:     return $outgoing;
18419: }
18420: 
18421: # Checks for critical messages and returns a redirect url if one exists.
18422: # $interval indicates how often to check for messages.
18423: # $context is the calling context -- roles, grades, contents, menu or flip.
18424: sub critical_redirect {
18425:     my ($interval,$context) = @_;
18426:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
18427:         return ();
18428:     }
18429:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
18430:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18431:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18432:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18433:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
18434:             if ($blocked) {
18435:                 my $checkrole = "cm./$cdom/$cnum";
18436:                 if ($env{'request.course.sec'} ne '') {
18437:                     $checkrole .= "/$env{'request.course.sec'}";
18438:                 }
18439:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18440:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18441:                     return;
18442:                 }
18443:             }
18444:         }
18445:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
18446:                                         $env{'user.name'});
18447:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18448:         my $redirecturl;
18449:         if ($what[0]) {
18450:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
18451:                 $redirecturl='/adm/email?critical=display';
18452:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
18453:                 return (1, $url);
18454:             }
18455:         }
18456:     }
18457:     return ();
18458: }
18459: 
18460: # Use:
18461: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18462: #
18463: ##################################################
18464: #          password associated functions         #
18465: ##################################################
18466: sub des_keys {
18467:     # Make a new key for DES encryption.
18468:     # Each key has two parts which are returned separately.
18469:     # Please note:  Each key must be passed through the &hex function
18470:     # before it is output to the web browser.  The hex versions cannot
18471:     # be used to decrypt.
18472:     my @hexstr=('0','1','2','3','4','5','6','7',
18473:                 '8','9','a','b','c','d','e','f');
18474:     my $lkey='';
18475:     for (0..7) {
18476:         $lkey.=$hexstr[rand(15)];
18477:     }
18478:     my $ukey='';
18479:     for (0..7) {
18480:         $ukey.=$hexstr[rand(15)];
18481:     }
18482:     return ($lkey,$ukey);
18483: }
18484: 
18485: sub des_decrypt {
18486:     my ($key,$cyphertext) = @_;
18487:     my $keybin=pack("H16",$key);
18488:     my $cypher;
18489:     if ($Crypt::DES::VERSION>=2.03) {
18490:         $cypher=new Crypt::DES $keybin;
18491:     } else {
18492:         $cypher=new DES $keybin;
18493:     }
18494:     my $plaintext='';
18495:     my $cypherlength = length($cyphertext);
18496:     my $numchunks = int($cypherlength/32);
18497:     for (my $j=0; $j<$numchunks; $j++) {
18498:         my $start = $j*32;
18499:         my $cypherblock = substr($cyphertext,$start,32);
18500:         my $chunk =
18501:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18502:         $chunk .=
18503:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18504:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18505:         $plaintext .= $chunk;
18506:     }
18507:     return $plaintext;
18508: }
18509: 
18510: sub get_requested_shorturls {
18511:     my ($cdom,$cnum,$navmap) = @_;
18512:     return unless (ref($navmap));
18513:     my ($numnew,$errors);
18514:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18515:     if (@toshorten) {
18516:         my (%maps,%resources,%titles);
18517:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18518:                                                                'shorturls',$cdom,$cnum);
18519:         if (keys(%resources)) {
18520:             my %tocreate;
18521:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
18522:                 my $symb = $resources{$item};
18523:                 if ($symb) {
18524:                     $tocreate{$cnum.'&'.$symb} = 1;
18525:                 }
18526:             }
18527:             if (keys(%tocreate)) {
18528:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
18529:                                                       \%tocreate);
18530:             }
18531:         }
18532:     }
18533:     return ($numnew,$errors);
18534: }
18535: 
18536: sub make_short_symbs {
18537:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
18538:     my ($numnew,@errors);
18539:     if (ref($tocreateref) eq 'HASH') {
18540:         my %tocreate = %{$tocreateref};
18541:         if (keys(%tocreate)) {
18542:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18543:             my $su = Short::URL->new(no_vowels => 1);
18544:             my $init = '';
18545:             my (%newunique,%addcourse,%courseonly,%failed);
18546:             # get lock on tiny db
18547:             my $now = time;
18548:             if ($lockuser eq '') {
18549:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
18550:             }
18551:             my $lockhash = {
18552:                                 "lock\0$now" => $lockuser,
18553:                             };
18554:             my $tries = 0;
18555:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18556:             my ($code,$error);
18557:             while (($gotlock ne 'ok') && ($tries<3)) {
18558:                 $tries ++;
18559:                 sleep 1;
18560:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18561:             }
18562:             if ($gotlock eq 'ok') {
18563:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18564:                                        \%addcourse,\%courseonly,\%failed);
18565:                 if (keys(%failed)) {
18566:                     my $numfailed = scalar(keys(%failed));
18567:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18568:                 }
18569:                 if (keys(%newunique)) {
18570:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18571:                     if ($putres eq 'ok') {
18572:                         $numnew = scalar(keys(%newunique));
18573:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18574:                         unless ($newputres eq 'ok') {
18575:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
18576:                         }
18577:                     } else {
18578:                         push(@errors,&mt('error: could not store unique six character URLs'));
18579:                     }
18580:                 }
18581:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18582:                 unless ($dellockres eq 'ok') {
18583:                     push(@errors,&mt('error: could not release lockfile'));
18584:                 }
18585:             } else {
18586:                 push(@errors,&mt('error: could not obtain lockfile'));
18587:             }
18588:             if (keys(%courseonly)) {
18589:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
18590:                 if ($result ne 'ok') {
18591:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
18592:                 }
18593:             }
18594:         }
18595:     }
18596:     return ($numnew,\@errors);
18597: }
18598: 
18599: sub shorten_symbs {
18600:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18601:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18602:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18603:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18604:     my (%possibles,%collisions);
18605:     foreach my $key (keys(%{$tocreate})) {
18606:         my $num = String::CRC32::crc32($key);
18607:         my $tiny = $su->encode($num,$init);
18608:         if ($tiny) {
18609:             $possibles{$tiny} = $key;
18610:         }
18611:     }
18612:     if (!$init) {
18613:         $init = 1;
18614:     } else {
18615:         $init ++;
18616:     }
18617:     if (keys(%possibles)) {
18618:         my @posstiny = keys(%possibles);
18619:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18620:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18621:         if (keys(%currtiny)) {
18622:             foreach my $key (keys(%currtiny)) {
18623:                 next if ($currtiny{$key} eq '');
18624:                 if ($currtiny{$key} eq $possibles{$key}) {
18625:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18626:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18627:                         $courseonly->{$tsymb} = $key;
18628:                     }
18629:                 } else {
18630:                     $collisions{$possibles{$key}} = 1;
18631:                 }
18632:                 delete($possibles{$key});
18633:             }
18634:         }
18635:         foreach my $key (keys(%possibles)) {
18636:             $newunique->{$key} = $possibles{$key};
18637:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18638:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18639:                 $addcourse->{$tsymb} = $key;
18640:             }
18641:         }
18642:     }
18643:     if (keys(%collisions)) {
18644:         if ($init <5) {
18645:             if (!$init) {
18646:                 $init = 1;
18647:             } else {
18648:                 $init ++;
18649:             }
18650:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18651:                                    $newunique,$addcourse,$courseonly,$failed);
18652:         } else {
18653:             foreach my $key (keys(%collisions)) {
18654:                 $failed->{$key} = 1;
18655:                 $failed->{$key} = 1;
18656:             }
18657:         }
18658:     }
18659:     return $init;
18660: }
18661: 
18662: sub is_nonframeable {
18663:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
18664:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
18665:     return if (($remprotocol eq '') || ($remhost eq ''));
18666: 
18667:     $remprotocol = lc($remprotocol);
18668:     $remhost = lc($remhost);
18669:     my $remport = 80;
18670:     if ($remprotocol eq 'https') {
18671:         $remport = 443;
18672:     }
18673:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
18674:     if ($cached) {
18675:         unless ($nocache) {
18676:             if ($result) {
18677:                 return 1;
18678:             } else {
18679:                 return 0;
18680:             }
18681:         }
18682:     }
18683:     my $uselink;
18684:     my $request = new HTTP::Request('HEAD',$url);
18685:     my $ua = LWP::UserAgent->new;
18686:     $ua->timeout(5);
18687:     my $response=$ua->request($request);
18688:     if ($response->is_success()) {
18689:         my $secpolicy = lc($response->header('content-security-policy'));
18690:         my $xframeop = lc($response->header('x-frame-options'));
18691:         $secpolicy =~ s/^\s+|\s+$//g;
18692:         $xframeop =~ s/^\s+|\s+$//g;
18693:         if (($secpolicy ne '') || ($xframeop ne '')) {
18694:             my $remotehost = $remprotocol.'://'.$remhost;
18695:             my ($origin,$protocol,$port);
18696:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
18697:                 $port = $ENV{'SERVER_PORT'};
18698:             } else {
18699:                 $port = 80;
18700:             }
18701:             if ($absolute eq '') {
18702:                 $protocol = 'http:';
18703:                 if ($port == 443) {
18704:                     $protocol = 'https:';
18705:                 }
18706:                 $origin = $protocol.'//'.lc($hostname);
18707:             } else {
18708:                 $origin = lc($absolute);
18709:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
18710:             }
18711:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
18712:                 my $framepolicy = $1;
18713:                 $framepolicy =~ s/^\s+|\s+$//g;
18714:                 my @policies = split(/\s+/,$framepolicy);
18715:                 if (@policies) {
18716:                     if (grep(/^\Q'none'\E$/,@policies)) {
18717:                         $uselink = 1;
18718:                     } else {
18719:                         $uselink = 1;
18720:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
18721:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
18722:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
18723:                             undef($uselink);
18724:                         }
18725:                         if ($uselink) {
18726:                             if (grep(/^\Q'self'\E$/,@policies)) {
18727:                                 if (($origin ne '') && ($remotehost eq $origin)) {
18728:                                     undef($uselink);
18729:                                 }
18730:                             }
18731:                         }
18732:                         if ($uselink) {
18733:                             my @possok;
18734:                             if ($ip ne '') {
18735:                                 push(@possok,$ip);
18736:                             }
18737:                             my $hoststr = '';
18738:                             foreach my $part (reverse(split(/\./,$hostname))) {
18739:                                 if ($hoststr eq '') {
18740:                                     $hoststr = $part;
18741:                                 } else {
18742:                                     $hoststr = "$part.$hoststr";
18743:                                 }
18744:                                 if ($hoststr eq $hostname) {
18745:                                     push(@possok,$hostname);
18746:                                 } else {
18747:                                     push(@possok,"*.$hoststr");
18748:                                 }
18749:                             }
18750:                             if (@possok) {
18751:                                 foreach my $poss (@possok) {
18752:                                     last if (!$uselink);
18753:                                     foreach my $policy (@policies) {
18754:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
18755:                                             undef($uselink);
18756:                                             last;
18757:                                         }
18758:                                     }
18759:                                 }
18760:                             }
18761:                         }
18762:                     }
18763:                 }
18764:             } elsif ($xframeop ne '') {
18765:                 $uselink = 1;
18766:                 my @policies = split(/\s*,\s*/,$xframeop);
18767:                 if (@policies) {
18768:                     unless (grep(/^deny$/,@policies)) {
18769:                         if ($origin ne '') {
18770:                             if (grep(/^sameorigin$/,@policies)) {
18771:                                 if ($remotehost eq $origin) {
18772:                                     undef($uselink);
18773:                                 }
18774:                             }
18775:                             if ($uselink) {
18776:                                 foreach my $policy (@policies) {
18777:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
18778:                                         my $allowfrom = $1;
18779:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
18780:                                             undef($uselink);
18781:                                             last;
18782:                                         }
18783:                                     }
18784:                                 }
18785:                             }
18786:                         }
18787:                     }
18788:                 }
18789:             }
18790:         }
18791:     }
18792:     if ($nocache) {
18793:         if ($cached) {
18794:             my $devalidate;
18795:             if ($uselink && !$result) {
18796:                 $devalidate = 1;
18797:             } elsif (!$uselink && $result) {
18798:                 $devalidate = 1;
18799:             }
18800:             if ($devalidate) {
18801:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
18802:             }
18803:         }
18804:     } else {
18805:         if ($uselink) {
18806:             $result = 1;
18807:         } else {
18808:             $result = 0;
18809:         }
18810:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
18811:     }
18812:     return $uselink;
18813: }
18814: 
18815: sub page_menu {
18816:     my ($menucolls,$menunum) = @_;
18817:     my %menu;
18818:     foreach my $item (split(/;/,$menucolls)) {
18819:         my ($num,$value) = split(/\%/,$item);
18820:         if ($num eq $menunum) {
18821:             my @entries = split(/\&/,$value);
18822:             foreach my $entry (@entries) {
18823:                 my ($name,$fields) = split(/=/,$entry);
18824:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
18825:                     $menu{$name} = $fields;
18826:                 } else {
18827:                     my @shown;
18828:                     if ($fields =~ /,/) {
18829:                         @shown = split(/,/,$fields);
18830:                     } else {
18831:                         @shown = ($fields);
18832:                     }
18833:                     if (@shown) {
18834:                         foreach my $field (@shown) {
18835:                             next if ($field eq '');
18836:                             $menu{$field} = 1;
18837:                         }
18838:                     }
18839:                 }
18840:             }
18841:         }
18842:     }
18843:     return %menu;
18844: }
18845: 
18846: 1;
18847: __END__;
18848: 

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