File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1412: download - view: text, annotated - select for diffs
Mon Sep 25 22:36:29 2023 UTC (9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 2689

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1412 2023/09/25 22:36:29 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnavmaps();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use LONCAPA::ltiutils;
   75: use LONCAPA::LWPReq;
   76: use LONCAPA::map();
   77: use HTTP::Request;
   78: use DateTime::TimeZone;
   79: use DateTime::Locale;
   80: use Encode();
   81: use Text::Aspell;
   82: use Authen::Captcha;
   83: use Captcha::reCAPTCHA;
   84: use JSON::DWIW;
   85: use Crypt::DES;
   86: use DynaLoader; # for Crypt::DES version
   87: use MIME::Lite;
   88: use MIME::Types;
   89: use File::Copy();
   90: use File::Path();
   91: use String::CRC32();
   92: use Short::URL();
   93: 
   94: # ---------------------------------------------- Designs
   95: use vars qw(%defaultdesign);
   96: 
   97: my $readit;
   98: 
   99: 
  100: ##
  101: ## Global Variables
  102: ##
  103: 
  104: 
  105: # ----------------------------------------------- SSI with retries:
  106: #
  107: 
  108: =pod
  109: 
  110: =head1 Server Side include with retries:
  111: 
  112: =over 4
  113: 
  114: =item * &ssi_with_retries(resource,retries form)
  115: 
  116: Performs an ssi with some number of retries.  Retries continue either
  117: until the result is ok or until the retry count supplied by the
  118: caller is exhausted.  
  119: 
  120: Inputs:
  121: 
  122: =over 4
  123: 
  124: resource   - Identifies the resource to insert.
  125: 
  126: retries    - Count of the number of retries allowed.
  127: 
  128: form       - Hash that identifies the rendering options.
  129: 
  130: =back
  131: 
  132: Returns:
  133: 
  134: =over 4
  135: 
  136: content    - The content of the response.  If retries were exhausted this is empty.
  137: 
  138: response   - The response from the last attempt (which may or may not have been successful.
  139: 
  140: =back
  141: 
  142: =back
  143: 
  144: =cut
  145: 
  146: sub ssi_with_retries {
  147:     my ($resource, $retries, %form) = @_;
  148: 
  149: 
  150:     my $ok = 0;			# True if we got a good response.
  151:     my $content;
  152:     my $response;
  153: 
  154:     # Try to get the ssi done. within the retries count:
  155: 
  156:     do {
  157: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  158: 	$ok      = $response->is_success;
  159:         if (!$ok) {
  160:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  161:         }
  162: 	$retries--;
  163:     } while (!$ok && ($retries > 0));
  164: 
  165:     if (!$ok) {
  166: 	$content = '';		# On error return an empty content.
  167:     }
  168:     return ($content, $response);
  169: 
  170: }
  171: 
  172: 
  173: 
  174: # ----------------------------------------------- Filetypes/Languages/Copyright
  175: my %language;
  176: my %supported_language;
  177: my %supported_codes;
  178: my %latex_language;		# For choosing hyphenation in <transl..>
  179: my %latex_language_bykey;	# for choosing hyphenation from metadata
  180: my %cprtag;
  181: my %scprtag;
  182: my %fe; my %fd; my %fm;
  183: my %category_extensions;
  184: 
  185: # ---------------------------------------------- Thesaurus variables
  186: #
  187: # %Keywords:
  188: #      A hash used by &keyword to determine if a word is considered a keyword.
  189: # $thesaurus_db_file 
  190: #      Scalar containing the full path to the thesaurus database.
  191: 
  192: my %Keywords;
  193: my $thesaurus_db_file;
  194: 
  195: #
  196: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  197: # thesaurus.tab, and filecategories.tab.
  198: #
  199: BEGIN {
  200:     # Variable initialization
  201:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  202:     #
  203:     unless ($readit) {
  204: # ------------------------------------------------------------------- languages
  205:     {
  206:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  207:                                    '/language.tab';
  208:         if ( open(my $fh,'<',$langtabfile) ) {
  209:             while (my $line = <$fh>) {
  210:                 next if ($line=~/^\#/);
  211:                 chomp($line);
  212:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  213:                 $language{$key}=$val.' - '.$enc;
  214:                 if ($sup) {
  215:                     $supported_language{$key}=$sup;
  216: 		    $supported_codes{$key}   = $code;
  217:                 }
  218: 		if ($latex) {
  219: 		    $latex_language_bykey{$key} = $latex;
  220: 		    $latex_language{$code} = $latex;
  221: 		}
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: # ------------------------------------------------------------------ copyrights
  227:     {
  228:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  229:                                   '/copyright.tab';
  230:         if ( open (my $fh,'<',$copyrightfile) ) {
  231:             while (my $line = <$fh>) {
  232:                 next if ($line=~/^\#/);
  233:                 chomp($line);
  234:                 my ($key,$val)=(split(/\s+/,$line,2));
  235:                 $cprtag{$key}=$val;
  236:             }
  237:             close($fh);
  238:         }
  239:     }
  240: # ----------------------------------------------------------- source copyrights
  241:     {
  242:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  243:                                   '/source_copyright.tab';
  244:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  245:             while (my $line = <$fh>) {
  246:                 next if ($line =~ /^\#/);
  247:                 chomp($line);
  248:                 my ($key,$val)=(split(/\s+/,$line,2));
  249:                 $scprtag{$key}=$val;
  250:             }
  251:             close($fh);
  252:         }
  253:     }
  254: 
  255: # -------------------------------------------------------------- default domain designs
  256:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  257:     my $designfile = $designdir.'/default.tab';
  258:     if ( open (my $fh,'<',$designfile) ) {
  259:         while (my $line = <$fh>) {
  260:             next if ($line =~ /^\#/);
  261:             chomp($line);
  262:             my ($key,$val)=(split(/\=/,$line));
  263:             if ($val) { $defaultdesign{$key}=$val; }
  264:         }
  265:         close($fh);
  266:     }
  267: 
  268: # ------------------------------------------------------------- file categories
  269:     {
  270:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  271:                                   '/filecategories.tab';
  272:         if ( open (my $fh,'<',$categoryfile) ) {
  273: 	    while (my $line = <$fh>) {
  274: 		next if ($line =~ /^\#/);
  275: 		chomp($line);
  276:                 my ($extension,$category)=(split(/\s+/,$line,2));
  277:                 push(@{$category_extensions{lc($category)}},$extension);
  278:             }
  279:             close($fh);
  280:         }
  281: 
  282:     }
  283: # ------------------------------------------------------------------ file types
  284:     {
  285:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  286:                '/filetypes.tab';
  287:         if ( open (my $fh,'<',$typesfile) ) {
  288:             while (my $line = <$fh>) {
  289: 		next if ($line =~ /^\#/);
  290: 		chomp($line);
  291:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  292:                 if ($descr ne '') {
  293:                     $fe{$ending}=lc($emb);
  294:                     $fd{$ending}=$descr;
  295:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  296:                 }
  297:             }
  298:             close($fh);
  299:         }
  300:     }
  301:     &Apache::lonnet::logthis(
  302:              "<span style='color:yellow;'>INFO: Read file types</span>");
  303:     $readit=1;
  304:     }  # end of unless($readit) 
  305:     
  306: }
  307: 
  308: ###############################################################
  309: ##           HTML and Javascript Helper Functions            ##
  310: ###############################################################
  311: 
  312: =pod 
  313: 
  314: =head1 HTML and Javascript Functions
  315: 
  316: =over 4
  317: 
  318: =item * &browser_and_searcher_javascript()
  319: 
  320: X<browsing, javascript>X<searching, javascript>Returns a string
  321: containing javascript with two functions, C<openbrowser> and
  322: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  323: tags.
  324: 
  325: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  326: 
  327: inputs: formname, elementname, only, omit
  328: 
  329: formname and elementname indicate the name of the html form and name of
  330: the element that the results of the browsing selection are to be placed in. 
  331: 
  332: Specifying 'only' will restrict the browser to displaying only files
  333: with the given extension.  Can be a comma separated list.
  334: 
  335: Specifying 'omit' will restrict the browser to NOT displaying files
  336: with the given extension.  Can be a comma separated list.
  337: 
  338: =item * &opensearcher(formname,elementname) [javascript]
  339: 
  340: Inputs: formname, elementname
  341: 
  342: formname and elementname specify the name of the html form and the name
  343: of the element the selection from the search results will be placed in.
  344: 
  345: =cut
  346: 
  347: sub browser_and_searcher_javascript {
  348:     my ($mode)=@_;
  349:     if (!defined($mode)) { $mode='edit'; }
  350:     my $resurl=&escape_single(&lastresurl());
  351:     return <<END;
  352: // <!-- BEGIN LON-CAPA Internal
  353:     var editbrowser = null;
  354:     function openbrowser(formname,elementname,only,omit,titleelement) {
  355:         var url = '$resurl/?';
  356:         if (editbrowser == null) {
  357:             url += 'launch=1&';
  358:         }
  359:         url += 'catalogmode=interactive&';
  360:         url += 'mode=$mode&';
  361:         url += 'inhibitmenu=yes&';
  362:         url += 'form=' + formname + '&';
  363:         if (only != null) {
  364:             url += 'only=' + only + '&';
  365:         } else {
  366:             url += 'only=&';
  367: 	}
  368:         if (omit != null) {
  369:             url += 'omit=' + omit + '&';
  370:         } else {
  371:             url += 'omit=&';
  372: 	}
  373:         if (titleelement != null) {
  374:             url += 'titleelement=' + titleelement + '&';
  375:         } else {
  376: 	    url += 'titleelement=&';
  377: 	}
  378:         url += 'element=' + elementname + '';
  379:         var title = 'Browser';
  380:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  381:         options += ',width=700,height=600';
  382:         editbrowser = open(url,title,options,'1');
  383:         editbrowser.focus();
  384:     }
  385:     var editsearcher;
  386:     function opensearcher(formname,elementname,titleelement) {
  387:         var url = '/adm/searchcat?';
  388:         if (editsearcher == null) {
  389:             url += 'launch=1&';
  390:         }
  391:         url += 'catalogmode=interactive&';
  392:         url += 'mode=$mode&';
  393:         url += 'form=' + formname + '&';
  394:         if (titleelement != null) {
  395:             url += 'titleelement=' + titleelement + '&';
  396:         } else {
  397: 	    url += 'titleelement=&';
  398: 	}
  399:         url += 'element=' + elementname + '';
  400:         var title = 'Search';
  401:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  402:         options += ',width=700,height=600';
  403:         editsearcher = open(url,title,options,'1');
  404:         editsearcher.focus();
  405:     }
  406: // END LON-CAPA Internal -->
  407: END
  408: }
  409: 
  410: sub lastresurl {
  411:     if ($env{'environment.lastresurl'}) {
  412: 	return $env{'environment.lastresurl'}
  413:     } else {
  414: 	return '/res';
  415:     }
  416: }
  417: 
  418: sub storeresurl {
  419:     my $resurl=&Apache::lonnet::clutter(shift);
  420:     unless ($resurl=~/^\/res/) { return 0; }
  421:     $resurl=~s/\/$//;
  422:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  423:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  424:     return 1;
  425: }
  426: 
  427: sub studentbrowser_javascript {
  428:    unless (
  429:             (($env{'request.course.id'}) && 
  430:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  431: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  432: 					  '/'.$env{'request.course.sec'})
  433: 	      ))
  434:          || ($env{'request.role'}=~/^(au|dc|su)/)
  435:           ) { return ''; }  
  436:    return (<<'ENDSTDBRW');
  437: <script type="text/javascript" language="Javascript">
  438: // <![CDATA[
  439:     var stdeditbrowser;
  440:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  441:         var url = '/adm/pickstudent?';
  442:         var filter;
  443: 	if (!ignorefilter) {
  444: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  445: 	}
  446:         if (filter != null) {
  447:            if (filter != '') {
  448:                url += 'filter='+filter+'&';
  449: 	   }
  450:         }
  451:         url += 'form=' + formname + '&unameelement='+uname+
  452:                                     '&udomelement='+udom+
  453:                                     '&clicker='+clicker;
  454: 	if (roleflag) { url+="&roles=1"; }
  455:         if (courseadv == 'condition') {
  456:             if (document.getElementById('courseadv')) {
  457:                 courseadv = document.getElementById('courseadv').value;
  458:             }
  459:         }
  460:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  461:         var title = 'Student_Browser';
  462:         var options = 'scrollbars=1,resizable=1,menubar=0';
  463:         options += ',width=700,height=600';
  464:         stdeditbrowser = open(url,title,options,'1');
  465:         stdeditbrowser.focus();
  466:     }
  467: // ]]>
  468: </script>
  469: ENDSTDBRW
  470: }
  471: 
  472: sub resourcebrowser_javascript {
  473:    unless ($env{'request.course.id'}) { return ''; }
  474:    return (<<'ENDRESBRW');
  475: <script type="text/javascript" language="Javascript">
  476: // <![CDATA[
  477:     var reseditbrowser;
  478:     function openresbrowser(formname,reslink) {
  479:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  480:         var title = 'Resource_Browser';
  481:         var options = 'scrollbars=1,resizable=1,menubar=0';
  482:         options += ',width=700,height=500';
  483:         reseditbrowser = open(url,title,options,'1');
  484:         reseditbrowser.focus();
  485:     }
  486: // ]]>
  487: </script>
  488: ENDRESBRW
  489: }
  490: 
  491: sub selectstudent_link {
  492:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  493:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  494:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  495:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  496:    if ($env{'request.course.id'}) {  
  497:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  498: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  499: 					'/'.$env{'request.course.sec'})) {
  500: 	   return '';
  501:        }
  502:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  503:        if ($courseadv eq 'only') {
  504:            $callargs .= ",'',1,'$courseadv'";
  505:        } elsif ($courseadv eq 'none') {
  506:            $callargs .= ",'','','$courseadv'";
  507:        } elsif ($courseadv eq 'condition') {
  508:            $callargs .= ",'','','$courseadv'";
  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 is 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 'Placement') {
  901:        $linktext = &mt('Select Placement Test'); 
  902:    } elsif ($selecttype eq 'Course/Community') {
  903:        $linktext = &mt('Select Course/Community');
  904:        $type = '';
  905:    } elsif ($selecttype eq 'Select') {
  906:        $linktext = &mt('Select');
  907:        $type = '';
  908:    }
  909:    return '<span class="LC_nobreak">'
  910:          ."<a href='"
  911:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  912:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  913:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  914:          ."'>".$linktext.'</a>'
  915:          .'</span>';
  916: }
  917: 
  918: sub selectauthor_link {
  919:    my ($form,$udom)=@_;
  920:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  921:           &mt('Select Author').'</a>';
  922: }
  923: 
  924: sub selectuser_link {
  925:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  926:         $coursedom,$linktext,$caller) = @_;
  927:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  928:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  929:            ');">'.$linktext.'</a>';
  930: }
  931: 
  932: sub check_uncheck_jscript {
  933:     my $jscript = <<"ENDSCRT";
  934: function checkAll(field) {
  935:     if (field.length > 0) {
  936:         for (i = 0; i < field.length; i++) {
  937:             if (!field[i].disabled) { 
  938:                 field[i].checked = true;
  939:             }
  940:         }
  941:     } else {
  942:         if (!field.disabled) { 
  943:             field.checked = true;
  944:         }
  945:     }
  946: }
  947:  
  948: function uncheckAll(field) {
  949:     if (field.length > 0) {
  950:         for (i = 0; i < field.length; i++) {
  951:             field[i].checked = false ;
  952:         }
  953:     } else {
  954:         field.checked = false ;
  955:     }
  956: }
  957: ENDSCRT
  958:     return $jscript;
  959: }
  960: 
  961: sub select_timezone {
  962:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
  963:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
  964:    if ($includeempty) {
  965:        $output .= '<option value=""';
  966:        if (($selected eq '') || ($selected eq 'local')) {
  967:            $output .= ' selected="selected" ';
  968:        }
  969:        $output .= '> </option>';
  970:    }
  971:    my @timezones = DateTime::TimeZone->all_names;
  972:    foreach my $tzone (@timezones) {
  973:        $output.= '<option value="'.$tzone.'"';
  974:        if ($tzone eq $selected) {
  975:            $output.=' selected="selected"';
  976:        }
  977:        $output.=">$tzone</option>\n";
  978:    }
  979:    $output.="</select>";
  980:    return $output;
  981: }
  982: 
  983: sub select_datelocale {
  984:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  985:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  986:     if ($includeempty) {
  987:         $output .= '<option value=""';
  988:         if ($selected eq '') {
  989:             $output .= ' selected="selected" ';
  990:         }
  991:         $output .= '> </option>';
  992:     }
  993:     my @languages = &Apache::lonlocal::preferred_languages();
  994:     my (@possibles,%locale_names);
  995:     my @locales = DateTime::Locale->ids();
  996:     foreach my $id (@locales) {
  997:         if ($id ne '') {
  998:             my ($en_terr,$native_terr);
  999:             my $loc = DateTime::Locale->load($id);
 1000:             if (ref($loc)) {
 1001:                 $en_terr = $loc->name();
 1002:                 $native_terr = $loc->native_name();
 1003:                 if (grep(/^en$/,@languages) || !@languages) {
 1004:                     if ($en_terr ne '') {
 1005:                         $locale_names{$id} = '('.$en_terr.')';
 1006:                     } elsif ($native_terr ne '') {
 1007:                         $locale_names{$id} = $native_terr;
 1008:                     }
 1009:                 } else {
 1010:                     if ($native_terr ne '') {
 1011:                         $locale_names{$id} = $native_terr.' ';
 1012:                     } elsif ($en_terr ne '') {
 1013:                         $locale_names{$id} = '('.$en_terr.')';
 1014:                     }
 1015:                 }
 1016:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1017:                 push(@possibles,$id);
 1018:             } 
 1019:         }
 1020:     }
 1021:     foreach my $item (sort(@possibles)) {
 1022:         $output.= '<option value="'.$item.'"';
 1023:         if ($item eq $selected) {
 1024:             $output.=' selected="selected"';
 1025:         }
 1026:         $output.=">$item";
 1027:         if ($locale_names{$item} ne '') {
 1028:             $output.='  '.$locale_names{$item};
 1029:         }
 1030:         $output.="</option>\n";
 1031:     }
 1032:     $output.="</select>";
 1033:     return $output;
 1034: }
 1035: 
 1036: sub select_language {
 1037:     my ($name,$selected,$includeempty,$noedit) = @_;
 1038:     my %langchoices;
 1039:     if ($includeempty) {
 1040:         %langchoices = ('' => 'No language preference');
 1041:     }
 1042:     foreach my $id (&languageids()) {
 1043:         my $code = &supportedlanguagecode($id);
 1044:         if ($code) {
 1045:             $langchoices{$code} = &plainlanguagedescription($id);
 1046:         }
 1047:     }
 1048:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1049:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1050: }
 1051: 
 1052: =pod
 1053: 
 1054: 
 1055: =item * &list_languages()
 1056: 
 1057: Returns an array reference that is suitable for use in language prompters.
 1058: Each array element is itself a two element array.  The first element
 1059: is the language code.  The second element a descsriptiuon of the 
 1060: language itself.  This is suitable for use in e.g.
 1061: &Apache::edit::select_arg (once dereferenced that is).
 1062: 
 1063: =cut 
 1064: 
 1065: sub list_languages {
 1066:     my @lang_choices;
 1067: 
 1068:     foreach my $id (&languageids()) {
 1069: 	my $code = &supportedlanguagecode($id);
 1070: 	if ($code) {
 1071: 	    my $selector    = $supported_codes{$id};
 1072: 	    my $description = &plainlanguagedescription($id);
 1073: 	    push(@lang_choices, [$selector, $description]);
 1074: 	}
 1075:     }
 1076:     return \@lang_choices;
 1077: }
 1078: 
 1079: =pod
 1080: 
 1081: =item * &linked_select_forms(...)
 1082: 
 1083: linked_select_forms returns a string containing a <script></script> block
 1084: and html for two <select> menus.  The select menus will be linked in that
 1085: changing the value of the first menu will result in new values being placed
 1086: in the second menu.  The values in the select menu will appear in alphabetical
 1087: order unless a defined order is provided.
 1088: 
 1089: linked_select_forms takes the following ordered inputs:
 1090: 
 1091: =over 4
 1092: 
 1093: =item * $formname, the name of the <form> tag
 1094: 
 1095: =item * $middletext, the text which appears between the <select> tags
 1096: 
 1097: =item * $firstdefault, the default value for the first menu
 1098: 
 1099: =item * $firstselectname, the name of the first <select> tag
 1100: 
 1101: =item * $secondselectname, the name of the second <select> tag
 1102: 
 1103: =item * $hashref, a reference to a hash containing the data for the menus.
 1104: 
 1105: =item * $menuorder, the order of values in the first menu
 1106: 
 1107: =item * $onchangefirst, additional javascript call to execute for an onchange
 1108:         event for the first <select> tag
 1109: 
 1110: =item * $onchangesecond, additional javascript call to execute for an onchange
 1111:         event for the second <select> tag
 1112: 
 1113: =item * $suffix, to differentiate separate uses of select2data javascript
 1114:         objects in a page.
 1115: 
 1116: =back 
 1117: 
 1118: Below is an example of such a hash.  Only the 'text', 'default', and 
 1119: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1120: values for the first select menu.  The text that coincides with the 
 1121: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1122: and text for the second menu are given in the hash pointed to by 
 1123: $menu{$choice1}->{'select2'}.  
 1124: 
 1125:  my %menu = ( A1 => { text =>"Choice A1" ,
 1126:                        default => "B3",
 1127:                        select2 => { 
 1128:                            B1 => "Choice B1",
 1129:                            B2 => "Choice B2",
 1130:                            B3 => "Choice B3",
 1131:                            B4 => "Choice B4"
 1132:                            },
 1133:                        order => ['B4','B3','B1','B2'],
 1134:                    },
 1135:                A2 => { text =>"Choice A2" ,
 1136:                        default => "C2",
 1137:                        select2 => { 
 1138:                            C1 => "Choice C1",
 1139:                            C2 => "Choice C2",
 1140:                            C3 => "Choice C3"
 1141:                            },
 1142:                        order => ['C2','C1','C3'],
 1143:                    },
 1144:                A3 => { text =>"Choice A3" ,
 1145:                        default => "D6",
 1146:                        select2 => { 
 1147:                            D1 => "Choice D1",
 1148:                            D2 => "Choice D2",
 1149:                            D3 => "Choice D3",
 1150:                            D4 => "Choice D4",
 1151:                            D5 => "Choice D5",
 1152:                            D6 => "Choice D6",
 1153:                            D7 => "Choice D7"
 1154:                            },
 1155:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1156:                    }
 1157:                );
 1158: 
 1159: =cut
 1160: 
 1161: sub linked_select_forms {
 1162:     my ($formname,
 1163:         $middletext,
 1164:         $firstdefault,
 1165:         $firstselectname,
 1166:         $secondselectname, 
 1167:         $hashref,
 1168:         $menuorder,
 1169:         $onchangefirst,
 1170:         $onchangesecond,
 1171:         $suffix
 1172:         ) = @_;
 1173:     my $second = "document.$formname.$secondselectname";
 1174:     my $first = "document.$formname.$firstselectname";
 1175:     # output the javascript to do the changing
 1176:     my $result = '';
 1177:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1178:     $result.="// <![CDATA[\n";
 1179:     $result.="var select2data${suffix} = new Object();\n";
 1180:     $" = '","';
 1181:     my $debug = '';
 1182:     foreach my $s1 (sort(keys(%$hashref))) {
 1183:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1184:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1185:             $hashref->{$s1}->{'default'}."');\n";
 1186:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1187:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1188:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1189:             @s2values = @{$hashref->{$s1}->{'order'}};
 1190:         }
 1191:         $result.="\"@s2values\");\n";
 1192:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1193:         my @s2texts;
 1194:         foreach my $value (@s2values) {
 1195:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1196:         }
 1197:         $result.="\"@s2texts\");\n";
 1198:     }
 1199:     $"=' ';
 1200:     $result.= <<"END";
 1201: 
 1202: function select1${suffix}_changed() {
 1203:     // Determine new choice
 1204:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1205:     // update select2
 1206:     var values     = select2data${suffix}[newvalue].values;
 1207:     var texts      = select2data${suffix}[newvalue].texts;
 1208:     var select2def = select2data${suffix}[newvalue].def;
 1209:     var i;
 1210:     // out with the old
 1211:     $second.options.length = 0;
 1212:     // in with the new
 1213:     for (i=0;i<values.length; i++) {
 1214:         $second.options[i] = new Option(values[i]);
 1215:         $second.options[i].value = values[i];
 1216:         $second.options[i].text = texts[i];
 1217:         if (values[i] == select2def) {
 1218:             $second.options[i].selected = true;
 1219:         }
 1220:     }
 1221: }
 1222: // ]]>
 1223: </script>
 1224: END
 1225:     # output the initial values for the selection lists
 1226:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1227:     my @order = sort(keys(%{$hashref}));
 1228:     if (ref($menuorder) eq 'ARRAY') {
 1229:         @order = @{$menuorder};
 1230:     }
 1231:     foreach my $value (@order) {
 1232:         $result.="    <option value=\"$value\" ";
 1233:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1234:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1235:     }
 1236:     $result .= "</select>\n";
 1237:     my %select2;
 1238:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
 1239:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
 1240:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1241:         }
 1242:     }
 1243:     $result .= $middletext;
 1244:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1245:     if ($onchangesecond) {
 1246:         $result .= ' onchange="'.$onchangesecond.'"';
 1247:     }
 1248:     $result .= ">\n";
 1249:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1250:     
 1251:     my @secondorder = sort(keys(%select2));
 1252:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1253:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1254:     }
 1255:     foreach my $value (@secondorder) {
 1256:         $result.="    <option value=\"$value\" ";        
 1257:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1258:         $result.=">".&mt($select2{$value})."</option>\n";
 1259:     }
 1260:     $result .= "</select>\n";
 1261:     #    return $debug;
 1262:     return $result;
 1263: }   #  end of sub linked_select_forms {
 1264: 
 1265: =pod
 1266: 
 1267: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
 1268: 
 1269: Returns a string corresponding to an HTML link to the given help
 1270: $topic, where $topic corresponds to the name of a .tex file in
 1271: /home/httpd/html/adm/help/tex, with underscores replaced by
 1272: spaces. 
 1273: 
 1274: $text will optionally be linked to the same topic, allowing you to
 1275: link text in addition to the graphic. If you do not want to link
 1276: text, but wish to specify one of the later parameters, pass an
 1277: empty string. 
 1278: 
 1279: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1280: the link will not open a new window. If false, the link will open
 1281: a new window using Javascript. (Default is false.) 
 1282: 
 1283: $width and $height are optional numerical parameters that will
 1284: override the width and height of the popped up window, which may
 1285: be useful for certain help topics with big pictures included.
 1286: 
 1287: $imgid is the id of the img tag used for the help icon. This may be
 1288: used in a javascript call to switch the image src.  See 
 1289: lonhtmlcommon::htmlareaselectactive() for an example.
 1290: 
 1291: $links_target will optionally be set to a target (_top, _parent or _self).
 1292: 
 1293: =cut
 1294: 
 1295: sub help_open_topic {
 1296:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
 1297:     $text = "" if (not defined $text);
 1298:     $stayOnPage = 0 if (not defined $stayOnPage);
 1299:     $width = 500 if (not defined $width);
 1300:     $height = 400 if (not defined $height);
 1301:     my $filename = $topic;
 1302:     $filename =~ s/ /_/g;
 1303: 
 1304:     my $template = "";
 1305:     my $link;
 1306:     
 1307:     $topic=~s/\W/\_/g;
 1308: 
 1309:     if (!$stayOnPage) {
 1310: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1311:     } elsif ($stayOnPage eq 'popup') {
 1312:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1313:     } else {
 1314: 	$link = "/adm/help/${filename}.hlp";
 1315:     }
 1316: 
 1317:     # Add the text
 1318:     my $target = ' target="_top"';
 1319:     if ($links_target) {
 1320:         $target = ' target="'.$links_target.'"';
 1321:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1322:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1323:         $target = '';
 1324:     }
 1325:     if ($text ne "") {
 1326: 	$template.='<span class="LC_help_open_topic">'
 1327:                   .'<a'.$target.' href="'.$link.'">'
 1328:                   .$text.'</a>';
 1329:     }
 1330: 
 1331:     # (Always) Add the graphic
 1332:     my $title = &mt('Online Help');
 1333:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1334:     if ($imgid ne '') {
 1335:         $imgid = ' id="'.$imgid.'"';
 1336:     }
 1337:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1338:               .'<img src="'.$helpicon.'" border="0"'
 1339:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1340:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1341:               .' /></a>';
 1342:     if ($text ne "") {	
 1343:         $template.='</span>';
 1344:     }
 1345:     return $template;
 1346: 
 1347: }
 1348: 
 1349: # This is a quicky function for Latex cheatsheet editing, since it 
 1350: # appears in at least four places
 1351: sub helpLatexCheatsheet {
 1352:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1353:     my $out;
 1354:     my $addOther = '';
 1355:     if ($topic) {
 1356: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1357:     }
 1358:     $out = '<span>' # Start cheatsheet
 1359: 	  .$addOther
 1360:           .'<span>'
 1361: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1362: 	  .'</span> <span>'
 1363: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1364: 	  .'</span>';
 1365:     unless ($not_author) {
 1366:         $out .= '<span>'
 1367:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1368:                .'</span> <span>'
 1369:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1370: 	       .'</span>';
 1371:     }
 1372:     $out .= '</span>'; # End cheatsheet
 1373:     return $out;
 1374: }
 1375: 
 1376: sub general_help {
 1377:     my $helptopic='Student_Intro';
 1378:     if ($env{'request.role'}=~/^(ca|au)/) {
 1379: 	$helptopic='Authoring_Intro';
 1380:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1381: 	$helptopic='Course_Coordination_Intro';
 1382:     } elsif ($env{'request.role'}=~/^dc/) {
 1383:         $helptopic='Domain_Coordination_Intro';
 1384:     }
 1385:     return $helptopic;
 1386: }
 1387: 
 1388: sub update_help_link {
 1389:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1390:     my $origurl = $ENV{'REQUEST_URI'};
 1391:     $origurl=~s|^/~|/priv/|;
 1392:     my $timestamp = time;
 1393:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1394:         $$datum = &escape($$datum);
 1395:     }
 1396: 
 1397:     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";
 1398:     my $output .= <<"ENDOUTPUT";
 1399: <script type="text/javascript">
 1400: // <![CDATA[
 1401: banner_link = '$banner_link';
 1402: // ]]>
 1403: </script>
 1404: ENDOUTPUT
 1405:     return $output;
 1406: }
 1407: 
 1408: # now just updates the help link and generates a blue icon
 1409: sub help_open_menu {
 1410:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
 1411: 	= @_;    
 1412:     $stayOnPage = 1;
 1413:     my $output;
 1414:     if ($component_help) {
 1415: 	if (!$text) {
 1416: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1417: 				       $width,$height,'',$links_target);
 1418: 	} else {
 1419: 	    my $help_text;
 1420: 	    $help_text=&unescape($topic);
 1421: 	    $output='<table><tr><td>'.
 1422: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1423: 				 $width,$height,'',$links_target).'</td></tr></table>';
 1424: 	}
 1425:     }
 1426:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1427:     return $output.$banner_link;
 1428: }
 1429: 
 1430: sub top_nav_help {
 1431:     my ($text,$linkattr) = @_;
 1432:     $text = &mt($text);
 1433:     my $stay_on_page = 1;
 1434: 
 1435:     my ($link,$banner_link);
 1436:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1437:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1438: 	                         : "javascript:helpMenu('open')";
 1439:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1440:     }
 1441:     my $title = &mt('Get help');
 1442:     if ($link) {
 1443:         return <<"END";
 1444: $banner_link
 1445: <a href="$link" title="$title" $linkattr>$text</a>
 1446: END
 1447:     } else {
 1448:         return '&nbsp;'.$text.'&nbsp;';
 1449:     }
 1450: }
 1451: 
 1452: sub help_menu_js {
 1453:     my ($httphost) = @_;
 1454:     my $stayOnPage = 1;
 1455:     my $width = 620;
 1456:     my $height = 600;
 1457:     my $helptopic=&general_help();
 1458:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1459:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1460:     my $start_page =
 1461:         &Apache::loncommon::start_page('Help Menu', undef,
 1462: 				       {'frameset'    => 1,
 1463: 					'js_ready'    => 1,
 1464:                                         'use_absolute' => $httphost,
 1465: 					'add_entries' => {
 1466: 					    'border' => '0', 
 1467: 					    'rows'   => "110,*",},});
 1468:     my $end_page =
 1469:         &Apache::loncommon::end_page({'frameset' => 1,
 1470: 				      'js_ready' => 1,});
 1471: 
 1472:     my $template .= <<"ENDTEMPLATE";
 1473: <script type="text/javascript">
 1474: // <![CDATA[
 1475: // <!-- BEGIN LON-CAPA Internal
 1476: var banner_link = '';
 1477: function helpMenu(target) {
 1478:     var caller = this;
 1479:     if (target == 'open') {
 1480:         var newWindow = null;
 1481:         try {
 1482:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1483:         }
 1484:         catch(error) {
 1485:             writeHelp(caller);
 1486:             return;
 1487:         }
 1488:         if (newWindow) {
 1489:             caller = newWindow;
 1490:         }
 1491:     }
 1492:     writeHelp(caller);
 1493:     return;
 1494: }
 1495: function writeHelp(caller) {
 1496:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1497:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1498:     caller.document.close();
 1499:     caller.focus();
 1500: }
 1501: // END LON-CAPA Internal -->
 1502: // ]]>
 1503: </script>
 1504: ENDTEMPLATE
 1505:     return $template;
 1506: }
 1507: 
 1508: sub help_open_bug {
 1509:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1510:     unless ($env{'user.adv'}) { return ''; }
 1511:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1512:     $text = "" if (not defined $text);
 1513: 	$stayOnPage=1;
 1514:     $width = 600 if (not defined $width);
 1515:     $height = 600 if (not defined $height);
 1516: 
 1517:     $topic=~s/\W+/\+/g;
 1518:     my $link='';
 1519:     my $template='';
 1520:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1521: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1522:     if (!$stayOnPage)
 1523:     {
 1524: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1525:     }
 1526:     else
 1527:     {
 1528: 	$link = $url;
 1529:     }
 1530: 
 1531:     my $target = '_top';
 1532:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1533:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1534:         $target = '_blank';
 1535:     }
 1536: 
 1537:     # Add the text
 1538:     if ($text ne "")
 1539:     {
 1540: 	$template .= 
 1541:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1542:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1543:     }
 1544: 
 1545:     # Add the graphic
 1546:     my $title = &mt('Report a Bug');
 1547:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1548:     $template .= <<"ENDTEMPLATE";
 1549:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1550: ENDTEMPLATE
 1551:     if ($text ne '') { $template.='</td></tr></table>' };
 1552:     return $template;
 1553: 
 1554: }
 1555: 
 1556: sub help_open_faq {
 1557:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1558:     unless ($env{'user.adv'}) { return ''; }
 1559:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1560:     $text = "" if (not defined $text);
 1561: 	$stayOnPage=1;
 1562:     $width = 350 if (not defined $width);
 1563:     $height = 400 if (not defined $height);
 1564: 
 1565:     $topic=~s/\W+/\+/g;
 1566:     my $link='';
 1567:     my $template='';
 1568:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1569:     if (!$stayOnPage)
 1570:     {
 1571: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1572:     }
 1573:     else
 1574:     {
 1575: 	$link = $url;
 1576:     }
 1577: 
 1578:     # Add the text
 1579:     if ($text ne "")
 1580:     {
 1581: 	$template .= 
 1582:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1583:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1584:     }
 1585: 
 1586:     # Add the graphic
 1587:     my $title = &mt('View the FAQ');
 1588:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1589:     $template .= <<"ENDTEMPLATE";
 1590:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1591: ENDTEMPLATE
 1592:     if ($text ne '') { $template.='</td></tr></table>' };
 1593:     return $template;
 1594: 
 1595: }
 1596: 
 1597: ###############################################################
 1598: ###############################################################
 1599: 
 1600: =pod
 1601: 
 1602: =item * &change_content_javascript():
 1603: 
 1604: This and the next function allow you to create small sections of an
 1605: otherwise static HTML page that you can update on the fly with
 1606: Javascript, even in Netscape 4.
 1607: 
 1608: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1609: must be written to the HTML page once. It will prove the Javascript
 1610: function "change(name, content)". Calling the change function with the
 1611: name of the section 
 1612: you want to update, matching the name passed to C<changable_area>, and
 1613: the new content you want to put in there, will put the content into
 1614: that area.
 1615: 
 1616: B<Note>: Netscape 4 only reserves enough space for the changable area
 1617: to contain room for the original contents. You need to "make space"
 1618: for whatever changes you wish to make, and be B<sure> to check your
 1619: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1620: it's adequate for updating a one-line status display, but little more.
 1621: This script will set the space to 100% width, so you only need to
 1622: worry about height in Netscape 4.
 1623: 
 1624: Modern browsers are much less limiting, and if you can commit to the
 1625: user not using Netscape 4, this feature may be used freely with
 1626: pretty much any HTML.
 1627: 
 1628: =cut
 1629: 
 1630: sub change_content_javascript {
 1631:     # If we're on Netscape 4, we need to use Layer-based code
 1632:     if ($env{'browser.type'} eq 'netscape' &&
 1633: 	$env{'browser.version'} =~ /^4\./) {
 1634: 	return (<<NETSCAPE4);
 1635: 	function change(name, content) {
 1636: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1637: 	    doc.open();
 1638: 	    doc.write(content);
 1639: 	    doc.close();
 1640: 	}
 1641: NETSCAPE4
 1642:     } else {
 1643: 	# Otherwise, we need to use semi-standards-compliant code
 1644: 	# (technically, "innerHTML" isn't standard but the equivalent
 1645: 	# is really scary, and every useful browser supports it
 1646: 	return (<<DOMBASED);
 1647: 	function change(name, content) {
 1648: 	    element = document.getElementById(name);
 1649: 	    element.innerHTML = content;
 1650: 	}
 1651: DOMBASED
 1652:     }
 1653: }
 1654: 
 1655: =pod
 1656: 
 1657: =item * &changable_area($name,$origContent):
 1658: 
 1659: This provides a "changable area" that can be modified on the fly via
 1660: the Javascript code provided in C<change_content_javascript>. $name is
 1661: the name you will use to reference the area later; do not repeat the
 1662: same name on a given HTML page more then once. $origContent is what
 1663: the area will originally contain, which can be left blank.
 1664: 
 1665: =cut
 1666: 
 1667: sub changable_area {
 1668:     my ($name, $origContent) = @_;
 1669: 
 1670:     if ($env{'browser.type'} eq 'netscape' &&
 1671: 	$env{'browser.version'} =~ /^4\./) {
 1672: 	# If this is netscape 4, we need to use the Layer tag
 1673: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1674:     } else {
 1675: 	return "<span id='$name'>$origContent</span>";
 1676:     }
 1677: }
 1678: 
 1679: =pod
 1680: 
 1681: =item * &viewport_geometry_js 
 1682: 
 1683: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1684: 
 1685: =cut
 1686: 
 1687: 
 1688: sub viewport_geometry_js { 
 1689:     return <<"GEOMETRY";
 1690: var Geometry = {};
 1691: function init_geometry() {
 1692:     if (Geometry.init) { return };
 1693:     Geometry.init=1;
 1694:     if (window.innerHeight) {
 1695:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1696:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1697:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1698:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1699:     }
 1700:     else if (document.documentElement && document.documentElement.clientHeight) {
 1701:         Geometry.getViewportHeight =
 1702:             function() { return document.documentElement.clientHeight; };
 1703:         Geometry.getViewportWidth =
 1704:             function() { return document.documentElement.clientWidth; };
 1705: 
 1706:         Geometry.getHorizontalScroll =
 1707:             function() { return document.documentElement.scrollLeft; };
 1708:         Geometry.getVerticalScroll =
 1709:             function() { return document.documentElement.scrollTop; };
 1710:     }
 1711:     else if (document.body.clientHeight) {
 1712:         Geometry.getViewportHeight =
 1713:             function() { return document.body.clientHeight; };
 1714:         Geometry.getViewportWidth =
 1715:             function() { return document.body.clientWidth; };
 1716:         Geometry.getHorizontalScroll =
 1717:             function() { return document.body.scrollLeft; };
 1718:         Geometry.getVerticalScroll =
 1719:             function() { return document.body.scrollTop; };
 1720:     }
 1721: }
 1722: 
 1723: GEOMETRY
 1724: }
 1725: 
 1726: =pod
 1727: 
 1728: =item * &viewport_size_js()
 1729: 
 1730: 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. 
 1731: 
 1732: =cut
 1733: 
 1734: sub viewport_size_js {
 1735:     my $geometry = &viewport_geometry_js();
 1736:     return <<"DIMS";
 1737: 
 1738: $geometry
 1739: 
 1740: function getViewportDims(width,height) {
 1741:     init_geometry();
 1742:     width.value = Geometry.getViewportWidth();
 1743:     height.value = Geometry.getViewportHeight();
 1744:     return;
 1745: }
 1746: 
 1747: DIMS
 1748: }
 1749: 
 1750: =pod
 1751: 
 1752: =item * &resize_textarea_js()
 1753: 
 1754: emits the needed javascript to resize a textarea to be as big as possible
 1755: 
 1756: creates a function resize_textrea that takes two IDs first should be
 1757: the id of the element to resize, second should be the id of a div that
 1758: surrounds everything that comes after the textarea, this routine needs
 1759: to be attached to the <body> for the onload and onresize events.
 1760: 
 1761: =back
 1762: 
 1763: =cut
 1764: 
 1765: sub resize_textarea_js {
 1766:     my $geometry = &viewport_geometry_js();
 1767:     return <<"RESIZE";
 1768:     <script type="text/javascript">
 1769: // <![CDATA[
 1770: $geometry
 1771: 
 1772: function getX(element) {
 1773:     var x = 0;
 1774:     while (element) {
 1775: 	x += element.offsetLeft;
 1776: 	element = element.offsetParent;
 1777:     }
 1778:     return x;
 1779: }
 1780: function getY(element) {
 1781:     var y = 0;
 1782:     while (element) {
 1783: 	y += element.offsetTop;
 1784: 	element = element.offsetParent;
 1785:     }
 1786:     return y;
 1787: }
 1788: 
 1789: 
 1790: function resize_textarea(textarea_id,bottom_id) {
 1791:     init_geometry();
 1792:     var textarea        = document.getElementById(textarea_id);
 1793:     //alert(textarea);
 1794: 
 1795:     var textarea_top    = getY(textarea);
 1796:     var textarea_height = textarea.offsetHeight;
 1797:     var bottom          = document.getElementById(bottom_id);
 1798:     var bottom_top      = getY(bottom);
 1799:     var bottom_height   = bottom.offsetHeight;
 1800:     var window_height   = Geometry.getViewportHeight();
 1801:     var fudge           = 23;
 1802:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1803:     if (new_height < 300) {
 1804: 	new_height = 300;
 1805:     }
 1806:     textarea.style.height=new_height+'px';
 1807: }
 1808: // ]]>
 1809: </script>
 1810: RESIZE
 1811: 
 1812: }
 1813: 
 1814: sub colorfuleditor_js {
 1815:     my $browse_or_search;
 1816:     my $respath;
 1817:     my ($cnum,$cdom) = &crsauthor_url();
 1818:     if ($cnum) {
 1819:         $respath = "/res/$cdom/$cnum/";
 1820:         my %js_lt = &Apache::lonlocal::texthash(
 1821:             sunm => 'Sub-directory name',
 1822:             save => 'Save page to make this permanent',
 1823:         );
 1824:         &js_escape(\%js_lt);
 1825:         my $showfile_js = &show_crsfiles_js();
 1826:         $browse_or_search = <<"END";
 1827: 
 1828:     $showfile_js
 1829: 
 1830:     function toggleChooser(form,element,titleid,only,search) {
 1831:         var disp = 'none';
 1832:         if (document.getElementById('chooser_'+element)) {
 1833:             var curr = document.getElementById('chooser_'+element).style.display;
 1834:             if (curr == 'none') {
 1835:                 disp='inline';
 1836:                 if (form.elements['chooser_'+element].length) {
 1837:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1838:                         form.elements['chooser_'+element][i].checked = false;
 1839:                     }
 1840:                 }
 1841:                 toggleResImport(form,element);
 1842:             }
 1843:             document.getElementById('chooser_'+element).style.display = disp;
 1844:             var dirsel = '';
 1845:             var filesel = '';
 1846:             if (document.getElementById('chooser_'+element+'_crsres')) {
 1847:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
 1848:                 if (currcrsres == 'none') {
 1849:                     dirsel = 'coursepath_'+element;
 1850:                     var filesel = 'coursefile_'+element;
 1851:                     var include;
 1852:                     if (document.getElementById('crsres_include_'+element)) {
 1853:                         include = document.getElementById('crsres_include_'+element).value;
 1854:                     }
 1855:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
 1856:                 }
 1857:             }
 1858:             if (document.getElementById('chooser_'+element+'_upload')) {
 1859:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
 1860:                 if (currcrsupload == 'none') {
 1861:                     dirsel = 'crsauthorpath_'+element;
 1862:                     filesel = '';
 1863:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
 1864:                 }
 1865:             }
 1866:         }
 1867:     }
 1868: 
 1869:     function toggleCrsFile(form,element) {
 1870:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1871:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1872:             if (curr == 'none') {
 1873:                 if (document.getElementById('coursepath_'+element)) {
 1874:                     var numdirs;
 1875:                     if (document.getElementById('coursepath_'+element).length) {
 1876:                         numdirs = document.getElementById('coursepath_'+element).length;
 1877:                     }
 1878:                     if ((document.getElementById('hascrsres_'+element)) &&
 1879:                         (document.getElementById('nocrsres_'+element))) {
 1880:                         if (numdirs) {
 1881:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
 1882:                             document.getElementById('nocrsres_'+element).style.display='none';
 1883:                         } else {
 1884:                             document.getElementById('hascrsres_'+element).style.display='none';
 1885:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
 1886:                         }
 1887:                     }
 1888:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1889:                     if (numdirs > 1) {
 1890:                         var selelem = form.elements['coursefile_'+element];
 1891:                         var i, len = selelem.options.length -1;
 1892:                         if (len >=0) {
 1893:                             for (i = len; i >= 0; i--) {
 1894:                                 selelem.remove(i);
 1895:                             }
 1896:                             selelem.options[0] = new Option('','');
 1897:                         }
 1898:                     }
 1899:                 }
 1900:             }
 1901:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1902:         }
 1903:         if (document.getElementById('chooser_'+element+'_upload')) {
 1904:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1905:             if (document.getElementById('uploadcrsres_'+element)) {
 1906:                 document.getElementById('uploadcrsres_'+element).value = '';
 1907:             }
 1908:         }
 1909:         return;
 1910:     }
 1911: 
 1912:     function toggleCrsUpload(form,element) {
 1913:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1914:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1915:         }
 1916:         if (document.getElementById('chooser_'+element+'_upload')) {
 1917:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1918:             if (curr == 'none') {
 1919:                 form.elements['newsubdir_'+element][0].checked = true;
 1920:                 toggleNewsubdir(form,element);
 1921:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1922:                 if (document.getElementById('uploadcrsres_'+element)) {
 1923:                     document.getElementById('uploadcrsres_'+element).value = '';
 1924:                 }
 1925:             }
 1926:         }
 1927:         return;
 1928:     }
 1929: 
 1930:     function toggleResImport(form,element) {
 1931:         var choices = new Array('crsres','upload');
 1932:         for (var i=0; i<choices.length; i++) {
 1933:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1934:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1935:             }
 1936:         }
 1937:     }
 1938: 
 1939:     function toggleNewsubdir(form,element) {
 1940:         var newsub = form.elements['newsubdir_'+element];
 1941:         if (newsub) {
 1942:             if (newsub.length) {
 1943:                 for (var j=0; j<newsub.length; j++) {
 1944:                     if (newsub[j].checked) {
 1945:                         if (document.getElementById('newsubdirname_'+element)) {
 1946:                             if (newsub[j].value == '1') {
 1947:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1948:                                 if (document.getElementById('newsubdir_'+element)) {
 1949:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1950:                                 }
 1951:                             } else {
 1952:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1953:                                 document.getElementById('newsubdirname_'+element).value = "";
 1954:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1955:                             }
 1956:                         }
 1957:                         break; 
 1958:                     }
 1959:                 }
 1960:             }
 1961:         }
 1962:     }
 1963: 
 1964:     function updateCrsFile(form,element) {
 1965:         var directory = form.elements['coursepath_'+element];
 1966:         var filename = form.elements['coursefile_'+element];
 1967:         var path = directory.options[directory.selectedIndex].value;
 1968:         var file = filename.options[filename.selectedIndex].value;
 1969:         if (file != '') {
 1970:             form.elements[element].value = '$respath';
 1971:             if (path == '/') {
 1972:                 form.elements[element].value += file;
 1973:             } else {
 1974:                 form.elements[element].value += path+'/'+file;
 1975:             }
 1976:             unClean();
 1977:             if (document.getElementById('previewimg_'+element)) {
 1978:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1979:                 var newsrc = document.getElementById('previewimg_'+element).src; 
 1980:             }
 1981:             if (document.getElementById('showimg_'+element)) {
 1982:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1983:             }
 1984:         }
 1985:         toggleChooser(form,element);
 1986:         return;
 1987:     }
 1988: 
 1989:     function uploadDone(suffix,name) {
 1990:         if (name) {
 1991: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1992:             unClean();
 1993:             toggleChooser(document.forms["lonhomework"],suffix);
 1994:         }
 1995:     }
 1996: 
 1997: \$(document).ready(function(){
 1998: 
 1999:     \$(document).delegate('form :submit', 'click', function( event ) {
 2000:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 2001:             var buttonId = this.id;
 2002:             var suffix = buttonId.toString();
 2003:             suffix = suffix.replace(/^crsupload_/,'');
 2004:             event.preventDefault();
 2005:             document.lonhomework.target = 'crsupload_target_'+suffix;
 2006:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 2007:             \$(this.form).submit();
 2008:             document.lonhomework.target = '';
 2009:             if (document.getElementById('crsuploadto_'+suffix)) {
 2010:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 2011:             }
 2012:             return false;
 2013:         }
 2014:     });
 2015: });
 2016: END
 2017:     }
 2018:     return <<"COLORFULEDIT"
 2019: <script type="text/javascript">
 2020: // <![CDATA[>
 2021:     function fold_box(curDepth, lastresource){
 2022: 
 2023:     // we need a list because there can be several blocks you need to fold in one tag
 2024:         var block = document.getElementsByName('foldblock_'+curDepth);
 2025:     // but there is only one folding button per tag
 2026:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 2027: 
 2028:         if(block.item(0).style.display == 'none'){
 2029: 
 2030:             foldbutton.value = '@{[&mt("Hide")]}';
 2031:             for (i = 0; i < block.length; i++){
 2032:                 block.item(i).style.display = '';
 2033:             }
 2034:         }else{
 2035: 
 2036:             foldbutton.value = '@{[&mt("Show")]}';
 2037:             for (i = 0; i < block.length; i++){
 2038:                 // block.item(i).style.visibility = 'collapse';
 2039:                 block.item(i).style.display = 'none';
 2040:             }
 2041:         };
 2042:         saveState(lastresource);
 2043:     }
 2044: 
 2045:     function saveState (lastresource) {
 2046: 
 2047:         var tag_list = getTagList();
 2048:         if(tag_list != null){
 2049:             var timestamp = new Date().getTime();
 2050:             var key = lastresource;
 2051: 
 2052:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 2053:             // starting with timestamp
 2054:             var value = timestamp+';';
 2055: 
 2056:             // building the list of key-value pairs
 2057:             for(var i = 0; i < tag_list.length; i++){
 2058:                 value += tag_list[i]+',';
 2059:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 2060:             }
 2061: 
 2062:             // only iterate whole storage if nothing to override
 2063:             if(localStorage.getItem(key) == null){        
 2064: 
 2065:                 // prevent storage from growing large
 2066:                 if(localStorage.length > 50){
 2067:                     var regex_getTimestamp = /^(?:\d)+;/;
 2068:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2069:                     var oldest_key;
 2070:                     
 2071:                     for(var i = 1; i < localStorage.length; i++){
 2072:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2073:                             oldest_key = localStorage.key(i);
 2074:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2075:                         }
 2076:                     }
 2077:                     localStorage.removeItem(oldest_key);
 2078:                 }
 2079:             }
 2080:             localStorage.setItem(key,value);
 2081:         }
 2082:     }
 2083: 
 2084:     // restore folding status of blocks (on page load)
 2085:     function restoreState (lastresource) {
 2086:         if(localStorage.getItem(lastresource) != null){
 2087:             var key = lastresource;
 2088:             var value = localStorage.getItem(key);
 2089:             var regex_delTimestamp = /^\d+;/;
 2090: 
 2091:             value.replace(regex_delTimestamp, '');
 2092: 
 2093:             var valueArr = value.split(';');
 2094:             var pairs;
 2095:             var elements;
 2096:             for (var i = 0; i < valueArr.length; i++){
 2097:                 pairs = valueArr[i].split(',');
 2098:                 elements = document.getElementsByName(pairs[0]);
 2099: 
 2100:                 for (var j = 0; j < elements.length; j++){  
 2101:                     elements[j].style.display = pairs[1];
 2102:                     if (pairs[1] == "none"){
 2103:                         var regex_id = /([_\\d]+)\$/;
 2104:                         regex_id.exec(pairs[0]);
 2105:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2106:                     }
 2107:                 }
 2108:             }
 2109:         }
 2110:     }
 2111: 
 2112:     function getTagList () {
 2113:         
 2114:         var stringToSearch = document.lonhomework.innerHTML;
 2115: 
 2116:         var ret = new Array();
 2117:         var regex_findBlock = /(foldblock_.*?)"/g;
 2118:         var tag_list = stringToSearch.match(regex_findBlock);
 2119: 
 2120:         if(tag_list != null){
 2121:             for(var i = 0; i < tag_list.length; i++){            
 2122:                 ret.push(tag_list[i].replace(/"/, ''));
 2123:             }
 2124:         }
 2125:         return ret;
 2126:     }
 2127: 
 2128:     function saveScrollPosition (resource) {
 2129:         var tag_list = getTagList();
 2130: 
 2131:         // we dont always want to jump to the first block
 2132:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2133:         if(\$(window).scrollTop() > 170){
 2134:             if(tag_list != null){
 2135:                 var result;
 2136:                 for(var i = 0; i < tag_list.length; i++){
 2137:                     if(isElementInViewport(tag_list[i])){
 2138:                         result += tag_list[i]+';';
 2139:                     }
 2140:                 }
 2141:                 sessionStorage.setItem('anchor_'+resource, result);
 2142:             }
 2143:         } else {
 2144:             // we dont need to save zero, just delete the item to leave everything tidy
 2145:             sessionStorage.removeItem('anchor_'+resource);
 2146:         }
 2147:     }
 2148: 
 2149:     function restoreScrollPosition(resource){
 2150: 
 2151:         var elem = sessionStorage.getItem('anchor_'+resource);
 2152:         if(elem != null){
 2153:             var tag_list = elem.split(';');
 2154:             var elem_list;
 2155: 
 2156:             for(var i = 0; i < tag_list.length; i++){
 2157:                 elem_list = document.getElementsByName(tag_list[i]);
 2158:                 
 2159:                 if(elem_list.length > 0){
 2160:                     elem = elem_list[0];
 2161:                     break;
 2162:                 }
 2163:             }
 2164:             elem.scrollIntoView();
 2165:         }
 2166:     }
 2167: 
 2168:     function isElementInViewport(el) {
 2169: 
 2170:         // change to last element instead of first
 2171:         var elem = document.getElementsByName(el);
 2172:         var rect = elem[0].getBoundingClientRect();
 2173: 
 2174:         return (
 2175:             rect.top >= 0 &&
 2176:             rect.left >= 0 &&
 2177:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2178:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2179:         );
 2180:     }
 2181:     
 2182:     function autosize(depth){
 2183:         var cmInst = window['cm'+depth];
 2184:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2185: 
 2186:         // is fixed size, switching to dynamic
 2187:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2188:             cmInst.setSize("","auto");
 2189:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2190:             sessionStorage.setItem("autosized_"+depth, "yes");
 2191: 
 2192:         // is dynamic size, switching to fixed
 2193:         } else {
 2194:             cmInst.setSize("","300px");
 2195:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2196:             sessionStorage.removeItem("autosized_"+depth);
 2197:         }
 2198:     }
 2199: 
 2200: $browse_or_search
 2201: 
 2202: // ]]>
 2203: </script>
 2204: COLORFULEDIT
 2205: }
 2206: 
 2207: sub xmleditor_js {
 2208:     return <<XMLEDIT
 2209: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2210: <script type="text/javascript">
 2211: // <![CDATA[>
 2212: 
 2213:     function saveScrollPosition (resource) {
 2214: 
 2215:         var scrollPos = \$(window).scrollTop();
 2216:         sessionStorage.setItem(resource,scrollPos);
 2217:     }
 2218: 
 2219:     function restoreScrollPosition(resource){
 2220: 
 2221:         var scrollPos = sessionStorage.getItem(resource);
 2222:         \$(window).scrollTop(scrollPos);
 2223:     }
 2224: 
 2225:     // unless internet explorer
 2226:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2227: 
 2228:         \$(document).ready(function() {
 2229:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2230:         });
 2231:     }
 2232: 
 2233:     // inserts text at cursor position into codemirror (xml editor only)
 2234:     function insertText(text){
 2235:         cm.focus();
 2236:         var curPos = cm.getCursor();
 2237:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2238:     }
 2239: // ]]>
 2240: </script>
 2241: XMLEDIT
 2242: }
 2243: 
 2244: sub insert_folding_button {
 2245:     my $curDepth = $Apache::lonxml::curdepth;
 2246:     my $lastresource = $env{'request.ambiguous'};
 2247: 
 2248:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2249:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2250: }
 2251: 
 2252: sub crsauthor_url {
 2253:     my ($url) = @_;
 2254:     if ($url eq '') {
 2255:         $url = $ENV{'REQUEST_URI'};
 2256:     }
 2257:     my ($cnum,$cdom);
 2258:     if ($env{'request.course.id'}) {
 2259:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2260:         if ($audom ne '' && $auname ne '') {
 2261:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2262:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2263:                 $cnum = $auname;
 2264:                 $cdom = $audom;
 2265:             }
 2266:         }
 2267:     }
 2268:     return ($cnum,$cdom);
 2269: }
 2270: 
 2271: sub import_crsauthor_form {
 2272:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2273:     return (0) unless ($env{'request.course.id'});
 2274:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2275:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2276:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2277:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2278:     my @ids=&Apache::lonnet::current_machine_ids();
 2279:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
 2280: 
 2281:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2282:         $is_home = 1;
 2283:     }
 2284:     $toppath = "/priv/$cdom/$cnum";
 2285:     my $nonemptydir = 1;
 2286:     my $js_only;
 2287:     if ($only) {
 2288:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
 2289:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
 2290:     }
 2291:     $exclude = &Apache::lonnet::priv_exclude();
 2292:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
 2293:     my $numdirs = scalar(keys(%files));
 2294:     my %lt = &Apache::lonlocal::texthash (
 2295:         fnam => 'Filename',
 2296:         dire => 'Directory',
 2297:         se   => 'Select',
 2298:     );
 2299:     $output = $lt{'dire'}.':&nbsp;'.
 2300:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
 2301:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
 2302:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
 2303:     if ($files{'/'}) {
 2304:         $output .= '<option value="/">/</option>'."\n";
 2305:     }
 2306:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2307:         next if ($key eq '/');
 2308:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
 2309:     }
 2310:     $output .= '</select><br />'."\n".
 2311:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
 2312:                '<option value="" selected="selected"></option>'."\n".
 2313:                '</select>'."\n".
 2314:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
 2315:     return ($numdirs,$output);
 2316: }
 2317: 
 2318: sub show_crsfiles_js {
 2319:     my $excluderef = &Apache::lonnet::priv_exclude();
 2320:     my $se = &js_escape(&mt('Select'));
 2321:     my $exclude;
 2322:     if (ref($excluderef) eq 'HASH') {
 2323:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
 2324:     }
 2325:     my $js = <<"END";
 2326: 
 2327: 
 2328:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
 2329:         var relpath = '';
 2330:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2331:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
 2332:             if (currdir == '') {
 2333:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2334:                     selelem = form.elements[filesel];
 2335:                     var j, numfiles = selelem.options.length -1;
 2336:                     if (numfiles >=0) {
 2337:                         for (j = numfiles; j >= 0; j--) {
 2338:                             selelem.remove(j);
 2339:                         }
 2340:                     }
 2341:                     if (selelem.options.length == 0) {
 2342:                         selelem.options[selelem.options.length] = new Option('','');
 2343:                         selelem.selectedIndex = 0;
 2344:                     }
 2345:                 }
 2346:                 return;
 2347:             } else {
 2348:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
 2349:             }
 2350:         }
 2351:         var http = new XMLHttpRequest();
 2352:         var url = "/adm/courseauthor";
 2353:         var crsrole = "$env{'request.role'}";
 2354:         var exclude = '';
 2355:         if (exc) {
 2356:             exclude = '$exclude';
 2357:         }
 2358:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
 2359:         http.open("POST", url, true);
 2360:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 2361:         http.onreadystatechange = function() {
 2362:             if (http.readyState == 4 && http.status == 200) {
 2363:                 var data = JSON.parse(http.responseText);
 2364:                 var selelem;
 2365:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2366:                     if (Array.isArray(data.dirs)) {
 2367:                         selelem = form.elements[dirsel];
 2368:                         var i, numdirs = selelem.options.length -1;
 2369:                         if (numdirs >=0) {
 2370:                             for (i = numdirs; i >= 0; i--) {
 2371:                                 selelem.remove(i);
 2372:                             }
 2373:                         }
 2374:                         var len = data.dirs.length;
 2375:                         if (len) {
 2376:                             selelem.options[selelem.options.length] = new Option('$se','');
 2377:                             var j;
 2378:                             for (j = 0; j < len; j++) {
 2379:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
 2380:                             }
 2381:                             selelem.selectedIndex = 0;
 2382:                         }
 2383:                         if (!setfile) {
 2384:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2385:                                 selelem = form.elements[filesel];
 2386:                                 var j, numfiles = selelem.options.length -1;
 2387:                                 if (numfiles >=0) {
 2388:                                     for (j = numfiles; j >= 0; j--) {
 2389:                                         selelem.remove(j);
 2390:                                     }
 2391:                                 }
 2392:                                 if (selelem.options.length == 0) {
 2393:                                     selelem.options[selelem.options.length] = new Option('','');
 2394:                                     selelem.selectedIndex = 0;
 2395:                                 }
 2396:                             }
 2397:                         }
 2398:                     }
 2399:                 }
 2400:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2401:                     selelem = form.elements[filesel];
 2402:                     var i, numfiles = selelem.options.length -1;
 2403:                     if (numfiles >=0) {
 2404:                         for (i = numfiles; i >= 0; i--) {
 2405:                             selelem.remove(i);
 2406:                         }
 2407:                     }
 2408:                     var x;
 2409:                     for (x in data.files) {
 2410:                         if (Array.isArray(data.files[x])) {
 2411:                             if (data.files[x].length > 1) {
 2412:                                 selelem.options[selelem.options.length] = new Option('$se','');
 2413:                             }
 2414:                             var len = data.files[x].length;
 2415:                             if (len) {
 2416:                                 var k;
 2417:                                 for (k = 0; k < len; k++) {
 2418:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
 2419:                                 }
 2420:                                 selelem.selectedIndex = 0;
 2421:                             }
 2422:                         }
 2423:                     }
 2424:                     if (selelem.options.length == 0) {
 2425:                         selelem.options[selelem.options.length] = new Option('','');
 2426:                         selelem.selectedIndex = 0;
 2427:                     }
 2428:                 }
 2429:             }
 2430:         }
 2431:         http.send(params);
 2432:     }
 2433: END
 2434: }
 2435: 
 2436: =pod
 2437: 
 2438: =head1 Excel and CSV file utility routines
 2439: 
 2440: =cut
 2441: 
 2442: ###############################################################
 2443: ###############################################################
 2444: 
 2445: =pod
 2446: 
 2447: =over 4
 2448: 
 2449: =item * &csv_translate($text) 
 2450: 
 2451: Translate $text to allow it to be output as a 'comma separated values' 
 2452: format.
 2453: 
 2454: =cut
 2455: 
 2456: ###############################################################
 2457: ###############################################################
 2458: sub csv_translate {
 2459:     my $text = shift;
 2460:     $text =~ s/\"/\"\"/g;
 2461:     $text =~ s/\n/ /g;
 2462:     return $text;
 2463: }
 2464: 
 2465: ###############################################################
 2466: ###############################################################
 2467: 
 2468: =pod
 2469: 
 2470: =item * &define_excel_formats()
 2471: 
 2472: Define some commonly used Excel cell formats.
 2473: 
 2474: Currently supported formats:
 2475: 
 2476: =over 4
 2477: 
 2478: =item header
 2479: 
 2480: =item bold
 2481: 
 2482: =item h1
 2483: 
 2484: =item h2
 2485: 
 2486: =item h3
 2487: 
 2488: =item h4
 2489: 
 2490: =item i
 2491: 
 2492: =item date
 2493: 
 2494: =back
 2495: 
 2496: Inputs: $workbook
 2497: 
 2498: Returns: $format, a hash reference.
 2499: 
 2500: 
 2501: =cut
 2502: 
 2503: ###############################################################
 2504: ###############################################################
 2505: sub define_excel_formats {
 2506:     my ($workbook) = @_;
 2507:     my $format;
 2508:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2509:                                                 bottom    => 1,
 2510:                                                 align     => 'center');
 2511:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2512:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2513:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2514:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2515:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2516:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2517:     $format->{'date'} = $workbook->add_format(num_format=>
 2518:                                             'mm/dd/yyyy hh:mm:ss');
 2519:     return $format;
 2520: }
 2521: 
 2522: ###############################################################
 2523: ###############################################################
 2524: 
 2525: =pod
 2526: 
 2527: =item * &create_workbook()
 2528: 
 2529: Create an Excel worksheet.  If it fails, output message on the
 2530: request object and return undefs.
 2531: 
 2532: Inputs: Apache request object
 2533: 
 2534: Returns (undef) on failure, 
 2535:     Excel worksheet object, scalar with filename, and formats 
 2536:     from &Apache::loncommon::define_excel_formats on success
 2537: 
 2538: =cut
 2539: 
 2540: ###############################################################
 2541: ###############################################################
 2542: sub create_workbook {
 2543:     my ($r) = @_;
 2544:         #
 2545:     # Create the excel spreadsheet
 2546:     my $filename = '/prtspool/'.
 2547:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2548:         time.'_'.rand(1000000000).'.xls';
 2549:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2550:     if (! defined($workbook)) {
 2551:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2552:         $r->print(
 2553:             '<p class="LC_error">'
 2554:            .&mt('Problems occurred in creating the new Excel file.')
 2555:            .' '.&mt('This error has been logged.')
 2556:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2557:            .'</p>'
 2558:         );
 2559:         return (undef);
 2560:     }
 2561:     #
 2562:     $workbook->set_tempdir(LONCAPA::tempdir());
 2563:     #
 2564:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2565:     return ($workbook,$filename,$format);
 2566: }
 2567: 
 2568: ###############################################################
 2569: ###############################################################
 2570: 
 2571: =pod
 2572: 
 2573: =item * &create_text_file()
 2574: 
 2575: Create a file to write to and eventually make available to the user.
 2576: If file creation fails, outputs an error message on the request object and 
 2577: return undefs.
 2578: 
 2579: Inputs: Apache request object, and file suffix
 2580: 
 2581: Returns (undef) on failure, 
 2582:     Filehandle and filename on success.
 2583: 
 2584: =cut
 2585: 
 2586: ###############################################################
 2587: ###############################################################
 2588: sub create_text_file {
 2589:     my ($r,$suffix) = @_;
 2590:     if (! defined($suffix)) { $suffix = 'txt'; };
 2591:     my $fh;
 2592:     my $filename = '/prtspool/'.
 2593:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2594:         time.'_'.rand(1000000000).'.'.$suffix;
 2595:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2596:     if (! defined($fh)) {
 2597:         $r->log_error("Couldn't open $filename for output $!");
 2598:         $r->print(
 2599:             '<p class="LC_error">'
 2600:            .&mt('Problems occurred in creating the output file.')
 2601:            .' '.&mt('This error has been logged.')
 2602:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2603:            .'</p>'
 2604:         );
 2605:     }
 2606:     return ($fh,$filename)
 2607: }
 2608: 
 2609: 
 2610: =pod 
 2611: 
 2612: =back
 2613: 
 2614: =cut
 2615: 
 2616: ###############################################################
 2617: ##        Home server <option> list generating code          ##
 2618: ###############################################################
 2619: 
 2620: # ------------------------------------------
 2621: 
 2622: sub domain_select {
 2623:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2624:     my @possdoms;
 2625:     if (ref($incdoms) eq 'ARRAY') {
 2626:         @possdoms = @{$incdoms};
 2627:     } else {
 2628:         @possdoms = &Apache::lonnet::all_domains();
 2629:     }
 2630: 
 2631:     my %domains=map { 
 2632: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2633:     } @possdoms;
 2634: 
 2635:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2636:         foreach my $dom (@{$excdoms}) {
 2637:             delete($domains{$dom});
 2638:         }
 2639:     }
 2640: 
 2641:     if ($multiple) {
 2642: 	$domains{''}=&mt('Any domain');
 2643: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2644: 	return &multiple_select_form($name,$value,4,\%domains);
 2645:     } else {
 2646: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2647: 	return &select_form($name,$value,\%domains);
 2648:     }
 2649: }
 2650: 
 2651: #-------------------------------------------
 2652: 
 2653: =pod
 2654: 
 2655: =head1 Routines for form select boxes
 2656: 
 2657: =over 4
 2658: 
 2659: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2660: 
 2661: Returns a string containing a <select> element int multiple mode
 2662: 
 2663: 
 2664: Args:
 2665:   $name - name of the <select> element
 2666:   $value - scalar or array ref of values that should already be selected
 2667:   $size - number of rows long the select element is
 2668:   $hash - the elements should be 'option' => 'shown text'
 2669:           (shown text should already have been &mt())
 2670:   $order - (optional) array ref of the order to show the elements in
 2671: 
 2672: =cut
 2673: 
 2674: #-------------------------------------------
 2675: sub multiple_select_form {
 2676:     my ($name,$value,$size,$hash,$order)=@_;
 2677:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2678:     my $output='';
 2679:     if (! defined($size)) {
 2680:         $size = 4;
 2681:         if (scalar(keys(%$hash))<4) {
 2682:             $size = scalar(keys(%$hash));
 2683:         }
 2684:     }
 2685:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2686:     my @order;
 2687:     if (ref($order) eq 'ARRAY')  {
 2688:         @order = @{$order};
 2689:     } else {
 2690:         @order = sort(keys(%$hash));
 2691:     }
 2692:     if (exists($$hash{'select_form_order'})) {
 2693:         @order = @{$$hash{'select_form_order'}};
 2694:     }
 2695:         
 2696:     foreach my $key (@order) {
 2697:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2698:         $output.='selected="selected" ' if ($selected{$key});
 2699:         $output.='>'.$hash->{$key}."</option>\n";
 2700:     }
 2701:     $output.="</select>\n";
 2702:     return $output;
 2703: }
 2704: 
 2705: #-------------------------------------------
 2706: 
 2707: =pod
 2708: 
 2709: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2710: 
 2711: Returns a string containing a <select name='$name' size='1'> form to 
 2712: allow a user to select options from a ref to a hash containing:
 2713: option_name => displayed text. An optional $onchange can include
 2714: a javascript onchange item, e.g., onchange="this.form.submit();".
 2715: An optional arg -- $readonly -- if true will cause the select form
 2716: to be disabled, e.g., for the case where an instructor has a section-
 2717: specific role, and is viewing/modifying parameters. 
 2718: 
 2719: See lonrights.pm for an example invocation and use.
 2720: 
 2721: =cut
 2722: 
 2723: #-------------------------------------------
 2724: sub select_form {
 2725:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2726:     return unless (ref($hashref) eq 'HASH');
 2727:     if ($onchange) {
 2728:         $onchange = ' onchange="'.$onchange.'"';
 2729:     }
 2730:     my $disabled;
 2731:     if ($readonly) {
 2732:         $disabled = ' disabled="disabled"';
 2733:     }
 2734:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2735:     my @keys;
 2736:     if (exists($hashref->{'select_form_order'})) {
 2737: 	@keys=@{$hashref->{'select_form_order'}};
 2738:     } else {
 2739: 	@keys=sort(keys(%{$hashref}));
 2740:     }
 2741:     foreach my $key (@keys) {
 2742:         $selectform.=
 2743: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2744:             ($key eq $def ? 'selected="selected" ' : '').
 2745:                 ">".$hashref->{$key}."</option>\n";
 2746:     }
 2747:     $selectform.="</select>";
 2748:     return $selectform;
 2749: }
 2750: 
 2751: # For display filters
 2752: 
 2753: sub display_filter {
 2754:     my ($context) = @_;
 2755:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2756:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2757:     my $phraseinput = 'hidden';
 2758:     my $includeinput = 'hidden';
 2759:     my ($checked,$includetypestext);
 2760:     if ($env{'form.displayfilter'} eq 'containing') {
 2761:         $phraseinput = 'text'; 
 2762:         if ($context eq 'parmslog') {
 2763:             $includeinput = 'checkbox';
 2764:             if ($env{'form.includetypes'}) {
 2765:                 $checked = ' checked="checked"';
 2766:             }
 2767:             $includetypestext = &mt('Include parameter types');
 2768:         }
 2769:     } else {
 2770:         $includetypestext = '&nbsp;';
 2771:     }
 2772:     my ($additional,$secondid,$thirdid);
 2773:     if ($context eq 'parmslog') {
 2774:         $additional = 
 2775:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2776:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2777:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2778:             '</label>';
 2779:         $secondid = 'includetypes';
 2780:         $thirdid = 'includetypestext';
 2781:     }
 2782:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2783:                                                     '$secondid','$thirdid')";
 2784:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2785: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
 2786: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2787: 	   '</label></span> <span class="LC_nobreak">'.
 2788:            &mt('Filter: [_1]',
 2789: 	   &select_form($env{'form.displayfilter'},
 2790: 			'displayfilter',
 2791: 			{'currentfolder' => 'Current folder/page',
 2792: 			 'containing' => 'Containing phrase',
 2793: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2794: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2795:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2796:                          '" />'.$additional;
 2797: }
 2798: 
 2799: sub display_filter_js {
 2800:     my $includetext = &mt('Include parameter types');
 2801:     return <<"ENDJS";
 2802:   
 2803: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2804:     var firstType = 'hidden';
 2805:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2806:         firstType = 'text';
 2807:     }
 2808:     firstObject = document.getElementById(firstid);
 2809:     if (typeof(firstObject) == 'object') {
 2810:         if (firstObject.type != firstType) {
 2811:             changeInputType(firstObject,firstType);
 2812:         }
 2813:     }
 2814:     if (context == 'parmslog') {
 2815:         var secondType = 'hidden';
 2816:         if (firstType == 'text') {
 2817:             secondType = 'checkbox';
 2818:         }
 2819:         secondObject = document.getElementById(secondid);  
 2820:         if (typeof(secondObject) == 'object') {
 2821:             if (secondObject.type != secondType) {
 2822:                 changeInputType(secondObject,secondType);
 2823:             }
 2824:         }
 2825:         var textItem = document.getElementById(thirdid);
 2826:         var currtext = textItem.innerHTML;
 2827:         var newtext;
 2828:         if (firstType == 'text') {
 2829:             newtext = '$includetext';
 2830:         } else {
 2831:             newtext = '&nbsp;';
 2832:         }
 2833:         if (currtext != newtext) {
 2834:             textItem.innerHTML = newtext;
 2835:         }
 2836:     }
 2837:     return;
 2838: }
 2839: 
 2840: function changeInputType(oldObject,newType) {
 2841:     var newObject = document.createElement('input');
 2842:     newObject.type = newType;
 2843:     if (oldObject.size) {
 2844:         newObject.size = oldObject.size;
 2845:     }
 2846:     if (oldObject.value) {
 2847:         newObject.value = oldObject.value;
 2848:     }
 2849:     if (oldObject.name) {
 2850:         newObject.name = oldObject.name;
 2851:     }
 2852:     if (oldObject.id) {
 2853:         newObject.id = oldObject.id;
 2854:     }
 2855:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2856:     return;
 2857: }
 2858: 
 2859: ENDJS
 2860: }
 2861: 
 2862: sub gradeleveldescription {
 2863:     my $gradelevel=shift;
 2864:     my %gradelevels=(0 => 'Not specified',
 2865: 		     1 => 'Grade 1',
 2866: 		     2 => 'Grade 2',
 2867: 		     3 => 'Grade 3',
 2868: 		     4 => 'Grade 4',
 2869: 		     5 => 'Grade 5',
 2870: 		     6 => 'Grade 6',
 2871: 		     7 => 'Grade 7',
 2872: 		     8 => 'Grade 8',
 2873: 		     9 => 'Grade 9',
 2874: 		     10 => 'Grade 10',
 2875: 		     11 => 'Grade 11',
 2876: 		     12 => 'Grade 12',
 2877: 		     13 => 'Grade 13',
 2878: 		     14 => '100 Level',
 2879: 		     15 => '200 Level',
 2880: 		     16 => '300 Level',
 2881: 		     17 => '400 Level',
 2882: 		     18 => 'Graduate Level');
 2883:     return &mt($gradelevels{$gradelevel});
 2884: }
 2885: 
 2886: sub select_level_form {
 2887:     my ($deflevel,$name)=@_;
 2888:     unless ($deflevel) { $deflevel=0; }
 2889:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2890:     for (my $i=0; $i<=18; $i++) {
 2891:         $selectform.="<option value=\"$i\" ".
 2892:             ($i==$deflevel ? 'selected="selected" ' : '').
 2893:                 ">".&gradeleveldescription($i)."</option>\n";
 2894:     }
 2895:     $selectform.="</select>";
 2896:     return $selectform;
 2897: }
 2898: 
 2899: #-------------------------------------------
 2900: 
 2901: =pod
 2902: 
 2903: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2904: 
 2905: Returns a string containing a <select name='$name' size='1'> form to 
 2906: allow a user to select the domain to preform an operation in.  
 2907: See loncreateuser.pm for an example invocation and use.
 2908: 
 2909: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2910: selected");
 2911: 
 2912: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2913: 
 2914: 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.
 2915: 
 2916: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2917: 
 2918: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2919: 
 2920: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2921: 
 2922: =cut
 2923: 
 2924: #-------------------------------------------
 2925: sub select_dom_form {
 2926:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2927:     if ($onchange) {
 2928:         $onchange = ' onchange="'.$onchange.'"';
 2929:     }
 2930:     if ($disabled) {
 2931:         $disabled = ' disabled="disabled"';
 2932:     }
 2933:     my (@domains,%exclude);
 2934:     if (ref($incdoms) eq 'ARRAY') {
 2935:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2936:     } else {
 2937:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2938:     }
 2939:     if ($includeempty) { @domains=('',@domains); }
 2940:     if (ref($excdoms) eq 'ARRAY') {
 2941:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2942:     }
 2943:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2944:     foreach my $dom (@domains) {
 2945:         next if ($exclude{$dom});
 2946:         $selectdomain.="<option value=\"$dom\" ".
 2947:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2948:         if ($showdomdesc) {
 2949:             if ($dom ne '') {
 2950:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2951:                 if ($domdesc ne '') {
 2952:                     $selectdomain .= ' ('.$domdesc.')';
 2953:                 }
 2954:             } 
 2955:         }
 2956:         $selectdomain .= "</option>\n";
 2957:     }
 2958:     $selectdomain.="</select>";
 2959:     return $selectdomain;
 2960: }
 2961: 
 2962: #-------------------------------------------
 2963: 
 2964: =pod
 2965: 
 2966: =item * &home_server_form_item($domain,$name,$defaultflag)
 2967: 
 2968: input: 4 arguments (two required, two optional) - 
 2969:     $domain - domain of new user
 2970:     $name - name of form element
 2971:     $default - Value of 'default' causes a default item to be first 
 2972:                             option, and selected by default. 
 2973:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2974:                             if 1 server found, or default, if 0 found.
 2975: output: returns 2 items: 
 2976: (a) form element which contains either:
 2977:    (i) <select name="$name">
 2978:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2979:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2980:        </select>
 2981:        form item if there are multiple library servers in $domain, or
 2982:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2983:        if there is only one library server in $domain.
 2984: 
 2985: (b) number of library servers found.
 2986: 
 2987: See loncreateuser.pm for example of use.
 2988: 
 2989: =cut
 2990: 
 2991: #-------------------------------------------
 2992: sub home_server_form_item {
 2993:     my ($domain,$name,$default,$hide) = @_;
 2994:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2995:     my $result;
 2996:     my $numlib = keys(%servers);
 2997:     if ($numlib > 1) {
 2998:         $result .= '<select name="'.$name.'" />'."\n";
 2999:         if ($default) {
 3000:             $result .= '<option value="default" selected="selected">'.&mt('default').
 3001:                        '</option>'."\n";
 3002:         }
 3003:         foreach my $hostid (sort(keys(%servers))) {
 3004:             $result.= '<option value="'.$hostid.'">'.
 3005: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 3006:         }
 3007:         $result .= '</select>'."\n";
 3008:     } elsif ($numlib == 1) {
 3009:         my $hostid;
 3010:         foreach my $item (keys(%servers)) {
 3011:             $hostid = $item;
 3012:         }
 3013:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 3014:                    $hostid.'" />';
 3015:                    if (!$hide) {
 3016:                        $result .= $hostid.' '.$servers{$hostid};
 3017:                    }
 3018:                    $result .= "\n";
 3019:     } elsif ($default) {
 3020:         $result .= '<input type="hidden" name="'.$name.
 3021:                    '" value="default" />';
 3022:                    if (!$hide) {
 3023:                        $result .= &mt('default');
 3024:                    }
 3025:                    $result .= "\n";
 3026:     }
 3027:     return ($result,$numlib);
 3028: }
 3029: 
 3030: =pod
 3031: 
 3032: =back 
 3033: 
 3034: =cut
 3035: 
 3036: ###############################################################
 3037: ##                  Decoding User Agent                      ##
 3038: ###############################################################
 3039: 
 3040: =pod
 3041: 
 3042: =head1 Decoding the User Agent
 3043: 
 3044: =over 4
 3045: 
 3046: =item * &decode_user_agent()
 3047: 
 3048: Inputs: $r
 3049: 
 3050: Outputs:
 3051: 
 3052: =over 4
 3053: 
 3054: =item * $httpbrowser
 3055: 
 3056: =item * $clientbrowser
 3057: 
 3058: =item * $clientversion
 3059: 
 3060: =item * $clientmathml
 3061: 
 3062: =item * $clientunicode
 3063: 
 3064: =item * $clientos
 3065: 
 3066: =item * $clientmobile
 3067: 
 3068: =item * $clientinfo
 3069: 
 3070: =item * $clientosversion
 3071: 
 3072: =back
 3073: 
 3074: =back 
 3075: 
 3076: =cut
 3077: 
 3078: ###############################################################
 3079: ###############################################################
 3080: sub decode_user_agent {
 3081:     my ($r)=@_;
 3082:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 3083:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 3084:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 3085:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 3086:     my $clientbrowser='unknown';
 3087:     my $clientversion='0';
 3088:     my $clientmathml='';
 3089:     my $clientunicode='0';
 3090:     my $clientmobile=0;
 3091:     my $clientosversion='';
 3092:     for (my $i=0;$i<=$#browsertype;$i++) {
 3093:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 3094: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 3095: 	    $clientbrowser=$bname;
 3096:             $httpbrowser=~/$vreg/i;
 3097: 	    $clientversion=$1;
 3098:             $clientmathml=($clientversion>=$minv);
 3099:             $clientunicode=($clientversion>=$univ);
 3100: 	}
 3101:     }
 3102:     my $clientos='unknown';
 3103:     my $clientinfo;
 3104:     if (($httpbrowser=~/linux/i) ||
 3105:         ($httpbrowser=~/unix/i) ||
 3106:         ($httpbrowser=~/ux/i) ||
 3107:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 3108:     if (($httpbrowser=~/vax/i) ||
 3109:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 3110:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 3111:     if (($httpbrowser=~/mac/i) ||
 3112:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 3113:     if ($httpbrowser=~/win/i) {
 3114:         $clientos='win';
 3115:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 3116:             $clientosversion = $1;
 3117:         }
 3118:     }
 3119:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3120:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3121:         $clientmobile=lc($1);
 3122:     }
 3123:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3124:         $clientinfo = 'firefox-'.$1;
 3125:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3126:         $clientinfo = 'chromeframe-'.$1;
 3127:     }
 3128:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3129:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3130:             $clientosversion);
 3131: }
 3132: 
 3133: ###############################################################
 3134: ##    Authentication changing form generation subroutines    ##
 3135: ###############################################################
 3136: ##
 3137: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3138: ## hash, and have reasonable default values.
 3139: ##
 3140: ##    formname = the name given in the <form> tag.
 3141: #-------------------------------------------
 3142: 
 3143: =pod
 3144: 
 3145: =head1 Authentication Routines
 3146: 
 3147: =over 4
 3148: 
 3149: =item * &authform_xxxxxx()
 3150: 
 3151: The authform_xxxxxx subroutines provide javascript and html forms which 
 3152: handle some of the conveniences required for authentication forms.  
 3153: This is not an optimal method, but it works.  
 3154: 
 3155: =over 4
 3156: 
 3157: =item * authform_header
 3158: 
 3159: =item * authform_authorwarning
 3160: 
 3161: =item * authform_nochange
 3162: 
 3163: =item * authform_kerberos
 3164: 
 3165: =item * authform_internal
 3166: 
 3167: =item * authform_filesystem
 3168: 
 3169: =item * authform_lti
 3170: 
 3171: =back
 3172: 
 3173: See loncreateuser.pm for invocation and use examples.
 3174: 
 3175: =cut
 3176: 
 3177: #-------------------------------------------
 3178: sub authform_header{  
 3179:     my %in = (
 3180:         formname => 'cu',
 3181:         kerb_def_dom => '',
 3182:         @_,
 3183:     );
 3184:     $in{'formname'} = 'document.' . $in{'formname'};
 3185:     my $result='';
 3186: 
 3187: #---------------------------------------------- Code for upper case translation
 3188:     my $Javascript_toUpperCase;
 3189:     unless ($in{kerb_def_dom}) {
 3190:         $Javascript_toUpperCase =<<"END";
 3191:         switch (choice) {
 3192:            case 'krb': currentform.elements[choicearg].value =
 3193:                currentform.elements[choicearg].value.toUpperCase();
 3194:                break;
 3195:            default:
 3196:         }
 3197: END
 3198:     } else {
 3199:         $Javascript_toUpperCase = "";
 3200:     }
 3201: 
 3202:     my $radioval = "'nochange'";
 3203:     if (defined($in{'curr_authtype'})) {
 3204:         if ($in{'curr_authtype'} ne '') {
 3205:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3206:         }
 3207:     }
 3208:     my $argfield = 'null';
 3209:     if (defined($in{'mode'})) {
 3210:         if ($in{'mode'} eq 'modifycourse')  {
 3211:             if (defined($in{'curr_autharg'})) {
 3212:                 if ($in{'curr_autharg'} ne '') {
 3213:                     $argfield = "'$in{'curr_autharg'}'";
 3214:                 }
 3215:             }
 3216:         }
 3217:     }
 3218: 
 3219:     $result.=<<"END";
 3220: var current = new Object();
 3221: current.radiovalue = $radioval;
 3222: current.argfield = $argfield;
 3223: 
 3224: function changed_radio(choice,currentform) {
 3225:     var choicearg = choice + 'arg';
 3226:     // If a radio button in changed, we need to change the argfield
 3227:     if (current.radiovalue != choice) {
 3228:         current.radiovalue = choice;
 3229:         if (current.argfield != null) {
 3230:             currentform.elements[current.argfield].value = '';
 3231:         }
 3232:         if (choice == 'nochange') {
 3233:             current.argfield = null;
 3234:         } else {
 3235:             current.argfield = choicearg;
 3236:             switch(choice) {
 3237:                 case 'krb': 
 3238:                     currentform.elements[current.argfield].value = 
 3239:                         "$in{'kerb_def_dom'}";
 3240:                 break;
 3241:               default:
 3242:                 break;
 3243:             }
 3244:         }
 3245:     }
 3246:     return;
 3247: }
 3248: 
 3249: function changed_text(choice,currentform) {
 3250:     var choicearg = choice + 'arg';
 3251:     if (currentform.elements[choicearg].value !='') {
 3252:         $Javascript_toUpperCase
 3253:         // clear old field
 3254:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3255:             currentform.elements[current.argfield].value = '';
 3256:         }
 3257:         current.argfield = choicearg;
 3258:     }
 3259:     set_auth_radio_buttons(choice,currentform);
 3260:     return;
 3261: }
 3262: 
 3263: function set_auth_radio_buttons(newvalue,currentform) {
 3264:     var numauthchoices = currentform.login.length;
 3265:     if (typeof numauthchoices  == "undefined") {
 3266:         return;
 3267:     } 
 3268:     var i=0;
 3269:     while (i < numauthchoices) {
 3270:         if (currentform.login[i].value == newvalue) { break; }
 3271:         i++;
 3272:     }
 3273:     if (i == numauthchoices) {
 3274:         return;
 3275:     }
 3276:     current.radiovalue = newvalue;
 3277:     currentform.login[i].checked = true;
 3278:     return;
 3279: }
 3280: END
 3281:     return $result;
 3282: }
 3283: 
 3284: sub authform_authorwarning {
 3285:     my $result='';
 3286:     $result='<i>'.
 3287:         &mt('As a general rule, only authors or co-authors should be '.
 3288:             'filesystem authenticated '.
 3289:             '(which allows access to the server filesystem).')."</i>\n";
 3290:     return $result;
 3291: }
 3292: 
 3293: sub authform_nochange {
 3294:     my %in = (
 3295:               formname => 'document.cu',
 3296:               kerb_def_dom => 'MSU.EDU',
 3297:               @_,
 3298:           );
 3299:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3300:     my $result;
 3301:     if (!$authnum) {
 3302:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3303:     } else {
 3304:         $result = '<label>'.&mt('[_1] Do not change login data',
 3305:                   '<input type="radio" name="login" value="nochange" '.
 3306:                   'checked="checked" onclick="'.
 3307:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3308: 	    '</label>';
 3309:     }
 3310:     return $result;
 3311: }
 3312: 
 3313: sub authform_kerberos {
 3314:     my %in = (
 3315:               formname => 'document.cu',
 3316:               kerb_def_dom => 'MSU.EDU',
 3317:               kerb_def_auth => 'krb4',
 3318:               @_,
 3319:               );
 3320:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3321:         $autharg,$jscall,$disabled);
 3322:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3323:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3324:        $check5 = ' checked="checked"';
 3325:     } else {
 3326:        $check4 = ' checked="checked"';
 3327:     }
 3328:     if ($in{'readonly'}) {
 3329:         $disabled = ' disabled="disabled"';
 3330:     }
 3331:     $krbarg = $in{'kerb_def_dom'};
 3332:     if (defined($in{'curr_authtype'})) {
 3333:         if ($in{'curr_authtype'} eq 'krb') {
 3334:             $krbcheck = ' checked="checked"';
 3335:             if (defined($in{'mode'})) {
 3336:                 if ($in{'mode'} eq 'modifyuser') {
 3337:                     $krbcheck = '';
 3338:                 }
 3339:             }
 3340:             if (defined($in{'curr_kerb_ver'})) {
 3341:                 if ($in{'curr_krb_ver'} eq '5') {
 3342:                     $check5 = ' checked="checked"';
 3343:                     $check4 = '';
 3344:                 } else {
 3345:                     $check4 = ' checked="checked"';
 3346:                     $check5 = '';
 3347:                 }
 3348:             }
 3349:             if (defined($in{'curr_autharg'})) {
 3350:                 $krbarg = $in{'curr_autharg'};
 3351:             }
 3352:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3353:                 if (defined($in{'curr_autharg'})) {
 3354:                     $result = 
 3355:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3356:         $in{'curr_autharg'},$krbver);
 3357:                 } else {
 3358:                     $result =
 3359:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3360:                 }
 3361:                 return $result; 
 3362:             }
 3363:         }
 3364:     } else {
 3365:         if ($authnum == 1) {
 3366:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3367:         }
 3368:     }
 3369:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3370:         return;
 3371:     } elsif ($authtype eq '') {
 3372:         if (defined($in{'mode'})) {
 3373:             if ($in{'mode'} eq 'modifycourse') {
 3374:                 if ($authnum == 1) {
 3375:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3376:                 }
 3377:             }
 3378:         }
 3379:     }
 3380:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3381:     if ($authtype eq '') {
 3382:         $authtype = '<input type="radio" name="login" value="krb" '.
 3383:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3384:                     $krbcheck.$disabled.' />';
 3385:     }
 3386:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3387:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3388:          $in{'curr_authtype'} eq 'krb5') ||
 3389:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3390:          $in{'curr_authtype'} eq 'krb4')) {
 3391:         $result .= &mt
 3392:         ('[_1] Kerberos authenticated with domain [_2] '.
 3393:          '[_3] Version 4 [_4] Version 5 [_5]',
 3394:          '<label>'.$authtype,
 3395:          '</label><input type="text" size="10" name="krbarg" '.
 3396:              'value="'.$krbarg.'" '.
 3397:              'onchange="'.$jscall.'"'.$disabled.' />',
 3398:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3399:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3400: 	 '</label>');
 3401:     } elsif ($can_assign{'krb4'}) {
 3402:         $result .= &mt
 3403:         ('[_1] Kerberos authenticated with domain [_2] '.
 3404:          '[_3] Version 4 [_4]',
 3405:          '<label>'.$authtype,
 3406:          '</label><input type="text" size="10" name="krbarg" '.
 3407:              'value="'.$krbarg.'" '.
 3408:              'onchange="'.$jscall.'"'.$disabled.' />',
 3409:          '<label><input type="hidden" name="krbver" value="4" />',
 3410:          '</label>');
 3411:     } elsif ($can_assign{'krb5'}) {
 3412:         $result .= &mt
 3413:         ('[_1] Kerberos authenticated with domain [_2] '.
 3414:          '[_3] Version 5 [_4]',
 3415:          '<label>'.$authtype,
 3416:          '</label><input type="text" size="10" name="krbarg" '.
 3417:              'value="'.$krbarg.'" '.
 3418:              'onchange="'.$jscall.'"'.$disabled.' />',
 3419:          '<label><input type="hidden" name="krbver" value="5" />',
 3420:          '</label>');
 3421:     }
 3422:     return $result;
 3423: }
 3424: 
 3425: sub authform_internal {
 3426:     my %in = (
 3427:                 formname => 'document.cu',
 3428:                 kerb_def_dom => 'MSU.EDU',
 3429:                 @_,
 3430:                 );
 3431:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3432:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3433:     if ($in{'readonly'}) {
 3434:         $disabled = ' disabled="disabled"';
 3435:     }
 3436:     if (defined($in{'curr_authtype'})) {
 3437:         if ($in{'curr_authtype'} eq 'int') {
 3438:             if ($can_assign{'int'}) {
 3439:                 $intcheck = 'checked="checked" ';
 3440:                 if (defined($in{'mode'})) {
 3441:                     if ($in{'mode'} eq 'modifyuser') {
 3442:                         $intcheck = '';
 3443:                     }
 3444:                 }
 3445:                 if (defined($in{'curr_autharg'})) {
 3446:                     $intarg = $in{'curr_autharg'};
 3447:                 }
 3448:             } else {
 3449:                 $result = &mt('Currently internally authenticated.');
 3450:                 return $result;
 3451:             }
 3452:         }
 3453:     } else {
 3454:         if ($authnum == 1) {
 3455:             $authtype = '<input type="hidden" name="login" value="int" />';
 3456:         }
 3457:     }
 3458:     if (!$can_assign{'int'}) {
 3459:         return;
 3460:     } elsif ($authtype eq '') {
 3461:         if (defined($in{'mode'})) {
 3462:             if ($in{'mode'} eq 'modifycourse') {
 3463:                 if ($authnum == 1) {
 3464:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3465:                 }
 3466:             }
 3467:         }
 3468:     }
 3469:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3470:     if ($authtype eq '') {
 3471:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3472:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3473:     }
 3474:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3475:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3476:     $result = &mt
 3477:         ('[_1] Internally authenticated (with initial password [_2])',
 3478:          '<label>'.$authtype,'</label>'.$autharg);
 3479:     $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>';
 3480:     return $result;
 3481: }
 3482: 
 3483: sub authform_local {
 3484:     my %in = (
 3485:               formname => 'document.cu',
 3486:               kerb_def_dom => 'MSU.EDU',
 3487:               @_,
 3488:               );
 3489:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3490:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3491:     if ($in{'readonly'}) {
 3492:         $disabled = ' disabled="disabled"';
 3493:     } 
 3494:     if (defined($in{'curr_authtype'})) {
 3495:         if ($in{'curr_authtype'} eq 'loc') {
 3496:             if ($can_assign{'loc'}) {
 3497:                 $loccheck = 'checked="checked" ';
 3498:                 if (defined($in{'mode'})) {
 3499:                     if ($in{'mode'} eq 'modifyuser') {
 3500:                         $loccheck = '';
 3501:                     }
 3502:                 }
 3503:                 if (defined($in{'curr_autharg'})) {
 3504:                     $locarg = $in{'curr_autharg'};
 3505:                 }
 3506:             } else {
 3507:                 $result = &mt('Currently using local (institutional) authentication.');
 3508:                 return $result;
 3509:             }
 3510:         }
 3511:     } else {
 3512:         if ($authnum == 1) {
 3513:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3514:         }
 3515:     }
 3516:     if (!$can_assign{'loc'}) {
 3517:         return;
 3518:     } elsif ($authtype eq '') {
 3519:         if (defined($in{'mode'})) {
 3520:             if ($in{'mode'} eq 'modifycourse') {
 3521:                 if ($authnum == 1) {
 3522:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3523:                 }
 3524:             }
 3525:         }
 3526:     }
 3527:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3528:     if ($authtype eq '') {
 3529:         $authtype = '<input type="radio" name="login" value="loc" '.
 3530:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3531:                     $jscall.'"'.$disabled.' />';
 3532:     }
 3533:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3534:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3535:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3536:                   '<label>'.$authtype,'</label>'.$autharg);
 3537:     return $result;
 3538: }
 3539: 
 3540: sub authform_filesystem {
 3541:     my %in = (
 3542:               formname => 'document.cu',
 3543:               kerb_def_dom => 'MSU.EDU',
 3544:               @_,
 3545:               );
 3546:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3547:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3548:     if ($in{'readonly'}) {
 3549:         $disabled = ' disabled="disabled"';
 3550:     }
 3551:     if (defined($in{'curr_authtype'})) {
 3552:         if ($in{'curr_authtype'} eq 'fsys') {
 3553:             if ($can_assign{'fsys'}) {
 3554:                 $fsyscheck = 'checked="checked" ';
 3555:                 if (defined($in{'mode'})) {
 3556:                     if ($in{'mode'} eq 'modifyuser') {
 3557:                         $fsyscheck = '';
 3558:                     }
 3559:                 }
 3560:             } else {
 3561:                 $result = &mt('Currently Filesystem Authenticated.');
 3562:                 return $result;
 3563:             }
 3564:         }
 3565:     } else {
 3566:         if ($authnum == 1) {
 3567:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3568:         }
 3569:     }
 3570:     if (!$can_assign{'fsys'}) {
 3571:         return;
 3572:     } elsif ($authtype eq '') {
 3573:         if (defined($in{'mode'})) {
 3574:             if ($in{'mode'} eq 'modifycourse') {
 3575:                 if ($authnum == 1) {
 3576:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3577:                 }
 3578:             }
 3579:         }
 3580:     }
 3581:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3582:     if ($authtype eq '') {
 3583:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3584:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3585:                     $jscall.'"'.$disabled.' />';
 3586:     }
 3587:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3588:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3589:     $result = &mt
 3590:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3591:          '<label>'.$authtype,'</label>'.$autharg);
 3592:     return $result;
 3593: }
 3594: 
 3595: sub authform_lti {
 3596:     my %in = (
 3597:               formname => 'document.cu',
 3598:               kerb_def_dom => 'MSU.EDU',
 3599:               @_,
 3600:               );
 3601:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3602:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3603:     if ($in{'readonly'}) {
 3604:         $disabled = ' disabled="disabled"';
 3605:     }
 3606:     if (defined($in{'curr_authtype'})) {
 3607:         if ($in{'curr_authtype'} eq 'lti') {
 3608:             if ($can_assign{'lti'}) {
 3609:                 $lticheck = 'checked="checked" ';
 3610:                 if (defined($in{'mode'})) {
 3611:                     if ($in{'mode'} eq 'modifyuser') {
 3612:                         $lticheck = '';
 3613:                     }
 3614:                 }
 3615:             } else {
 3616:                 $result = &mt('Currently LTI Authenticated.');
 3617:                 return $result;
 3618:             }
 3619:         }
 3620:     } else {
 3621:         if ($authnum == 1) {
 3622:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3623:         }
 3624:     }
 3625:     if (!$can_assign{'lti'}) {
 3626:         return;
 3627:     } elsif ($authtype eq '') {
 3628:         if (defined($in{'mode'})) {
 3629:             if ($in{'mode'} eq 'modifycourse') {
 3630:                 if ($authnum == 1) {
 3631:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3632:                 }
 3633:             }
 3634:         }
 3635:     }
 3636:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3637:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3638:         $authtype = '<input type="radio" name="login" value="lti" '.
 3639:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3640:                     $jscall.'"'.$disabled.' />';
 3641:     }
 3642:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3643:     if ($authtype) {
 3644:         $result = &mt('[_1] LTI Authenticated',
 3645:                       '<label>'.$authtype.'</label>'.$autharg);
 3646:     } else {
 3647:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3648:                   $autharg;
 3649:     }
 3650:     return $result;
 3651: }
 3652: 
 3653: sub get_assignable_auth {
 3654:     my ($dom) = @_;
 3655:     if ($dom eq '') {
 3656:         $dom = $env{'request.role.domain'};
 3657:     }
 3658:     my %can_assign = (
 3659:                           krb4 => 1,
 3660:                           krb5 => 1,
 3661:                           int  => 1,
 3662:                           loc  => 1,
 3663:                           lti  => 1,
 3664:                      );
 3665:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3666:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3667:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3668:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3669:             my $context;
 3670:             if ($env{'request.role'} =~ /^au/) {
 3671:                 $context = 'author';
 3672:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3673:                 $context = 'domain';
 3674:             } elsif ($env{'request.course.id'}) {
 3675:                 $context = 'course';
 3676:             }
 3677:             if ($context) {
 3678:                 if (ref($authhash->{$context}) eq 'HASH') {
 3679:                    %can_assign = %{$authhash->{$context}}; 
 3680:                 }
 3681:             }
 3682:         }
 3683:     }
 3684:     my $authnum = 0;
 3685:     foreach my $key (keys(%can_assign)) {
 3686:         if ($can_assign{$key}) {
 3687:             $authnum ++;
 3688:         }
 3689:     }
 3690:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3691:         $authnum --;
 3692:     }
 3693:     return ($authnum,%can_assign);
 3694: }
 3695: 
 3696: sub check_passwd_rules {
 3697:     my ($domain,$plainpass) = @_;
 3698:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3699:     my ($min,$max,@chars,@brokerule,$warning);
 3700:     $min = $Apache::lonnet::passwdmin;
 3701:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3702:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3703:             if ($passwdconf{'min'} > $min) {
 3704:                 $min = $passwdconf{'min'};
 3705:             }
 3706:         }
 3707:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3708:             $max = $passwdconf{'max'};
 3709:         }
 3710:         @chars = @{$passwdconf{'chars'}};
 3711:     }
 3712:     if (($min) && (length($plainpass) < $min)) {
 3713:         push(@brokerule,'min');
 3714:     }
 3715:     if (($max) && (length($plainpass) > $max)) {
 3716:         push(@brokerule,'max');
 3717:     }
 3718:     if (@chars) {
 3719:         my %rules;
 3720:         map { $rules{$_} = 1; } @chars;
 3721:         if ($rules{'uc'}) {
 3722:             unless ($plainpass =~ /[A-Z]/) {
 3723:                 push(@brokerule,'uc');
 3724:             }
 3725:         }
 3726:         if ($rules{'lc'}) {
 3727:             unless ($plainpass =~ /[a-z]/) {
 3728:                 push(@brokerule,'lc');
 3729:             }
 3730:         }
 3731:         if ($rules{'num'}) {
 3732:             unless ($plainpass =~ /\d/) {
 3733:                 push(@brokerule,'num');
 3734:             }
 3735:         }
 3736:         if ($rules{'spec'}) {
 3737:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3738:                 push(@brokerule,'spec');
 3739:             }
 3740:         }
 3741:     }
 3742:     if (@brokerule) {
 3743:         my %rulenames = &Apache::lonlocal::texthash(
 3744:             uc   => 'At least one upper case letter',
 3745:             lc   => 'At least one lower case letter',
 3746:             num  => 'At least one number',
 3747:             spec => 'At least one non-alphanumeric',
 3748:         );
 3749:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3750:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3751:         $rulenames{'num'} .= ': 0123456789';
 3752:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3753:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3754:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3755:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3756:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3757:             if (grep(/^$rule$/,@brokerule)) {
 3758:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3759:             }
 3760:         }
 3761:         $warning .= '</ul>';
 3762:     }
 3763:     if (wantarray) {
 3764:         return @brokerule;
 3765:     }
 3766:     return $warning;
 3767: }
 3768: 
 3769: sub passwd_validation_js {
 3770:     my ($currpasswdval,$domain,$context,$id) = @_;
 3771:     my (%passwdconf,$alertmsg);
 3772:     if ($context eq 'linkprot') {
 3773:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3774:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3775:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3776:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3777:             }
 3778:         }
 3779:         if ($id eq 'add') {
 3780:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3781:         } elsif ($id =~ /^\d+$/) {
 3782:             my $pos = $id+1;
 3783:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3784:         } else {
 3785:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3786:         }
 3787:     } else {
 3788:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3789:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3790:     }
 3791:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3792:     $numrules = 0;
 3793:     $min = $Apache::lonnet::passwdmin;
 3794:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3795:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3796:             if ($passwdconf{'min'} > $min) {
 3797:                 $min = $passwdconf{'min'};
 3798:             }
 3799:         }
 3800:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3801:             $max = $passwdconf{'max'};
 3802:             $numrules ++;
 3803:         }
 3804:         @chars = @{$passwdconf{'chars'}};
 3805:         if (@chars) {
 3806:             $numrules ++;
 3807:         }
 3808:     }
 3809:     if ($min > 0) {
 3810:         $numrules ++;
 3811:     }
 3812:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3813:         if ($min) {
 3814:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3815:         }
 3816:         if ($max) {
 3817:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3818:         }
 3819:         my (@charalerts,@charrules);
 3820:         if (@chars) {
 3821:             if (grep(/^uc$/,@chars)) {
 3822:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3823:                 push(@charrules,'uc');
 3824:             }
 3825:             if (grep(/^lc$/,@chars)) {
 3826:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3827:                 push(@charrules,'lc');
 3828:             }
 3829:             if (grep(/^num$/,@chars)) {
 3830:                 push(@charalerts,&mt('contain at least one number'));
 3831:                 push(@charrules,'num');
 3832:             }
 3833:             if (grep(/^spec$/,@chars)) {
 3834:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 3835:                 push(@charrules,'spec');
 3836:             }
 3837:         }
 3838:         $intargjs = qq|            var rulesmsg = '';\n|.
 3839:                     qq|            var currpwval = $currpasswdval;\n|;
 3840:             if ($min) {
 3841:                 $intargjs .= qq|
 3842:             if (currpwval.length < $min) {
 3843:                 rulesmsg += ' - $alert{min}';
 3844:             }
 3845: |;
 3846:             }
 3847:             if ($max) {
 3848:                 $intargjs .= qq|
 3849:             if (currpwval.length > $max) {
 3850:                 rulesmsg += ' - $alert{max}';
 3851:             }
 3852: |;
 3853:             }
 3854:             if (@chars > 0) {
 3855:                 my $charrulestr = '"'.join('","',@charrules).'"';
 3856:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 3857:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 3858:                              qq|            var charrules = new Array($charrulestr);\n|.
 3859:                              qq|            var charalerts = new Array($charalertstr);\n|;
 3860:                 my %rules;
 3861:                 map { $rules{$_} = 1; } @chars;
 3862:                 if ($rules{'uc'}) {
 3863:                     $intargjs .= qq|
 3864:             var ucRegExp = /[A-Z]/;
 3865:             if (!ucRegExp.test(currpwval)) {
 3866:                 brokerules.push('uc');
 3867:             }
 3868: |;
 3869:                 }
 3870:                 if ($rules{'lc'}) {
 3871:                     $intargjs .= qq|
 3872:             var lcRegExp = /[a-z]/;
 3873:             if (!lcRegExp.test(currpwval)) {
 3874:                 brokerules.push('lc');
 3875:             }
 3876: |;
 3877:                 }
 3878:                 if ($rules{'num'}) {
 3879:                      $intargjs .= qq|
 3880:             var numRegExp = /[0-9]/;
 3881:             if (!numRegExp.test(currpwval)) {
 3882:                 brokerules.push('num');
 3883:             }
 3884: |;
 3885:                 }
 3886:                 if ($rules{'spec'}) {
 3887:                      $intargjs .= q|
 3888:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 3889:             if (!specRegExp.test(currpwval)) {
 3890:                 brokerules.push('spec');
 3891:             }
 3892: |;
 3893:                 }
 3894:                 $intargjs .= qq|
 3895:             if (brokerules.length > 0) {
 3896:                 for (var i=0; i<brokerules.length; i++) {
 3897:                     for (var j=0; j<charrules.length; j++) {
 3898:                         if (brokerules[i] == charrules[j]) {
 3899:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 3900:                             break;
 3901:                         }
 3902:                     }
 3903:                 }
 3904:             }
 3905: |;
 3906:             }
 3907:             $intargjs .= qq|
 3908:             if (rulesmsg != '') {
 3909:                 rulesmsg = '$alertmsg'+rulesmsg;
 3910:                 alert(rulesmsg);
 3911:                 return false;
 3912:             }
 3913: |;
 3914:     }
 3915:     return ($numrules,$intargjs);
 3916: }
 3917: 
 3918: ###############################################################
 3919: ##    Get Kerberos Defaults for Domain                 ##
 3920: ###############################################################
 3921: ##
 3922: ## Returns default kerberos version and an associated argument
 3923: ## as listed in file domain.tab. If not listed, provides
 3924: ## appropriate default domain and kerberos version.
 3925: ##
 3926: #-------------------------------------------
 3927: 
 3928: =pod
 3929: 
 3930: =item * &get_kerberos_defaults()
 3931: 
 3932: get_kerberos_defaults($target_domain) returns the default kerberos
 3933: version and domain. If not found, it defaults to version 4 and the 
 3934: domain of the server.
 3935: 
 3936: =over 4
 3937: 
 3938: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3939: 
 3940: =back
 3941: 
 3942: =back
 3943: 
 3944: =cut
 3945: 
 3946: #-------------------------------------------
 3947: sub get_kerberos_defaults {
 3948:     my $domain=shift;
 3949:     my ($krbdef,$krbdefdom);
 3950:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3951:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3952:         $krbdef = $domdefaults{'auth_def'};
 3953:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3954:     } else {
 3955:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3956:         my $krbdefdom=$1;
 3957:         $krbdefdom=~tr/a-z/A-Z/;
 3958:         $krbdef = "krb4";
 3959:     }
 3960:     return ($krbdef,$krbdefdom);
 3961: }
 3962: 
 3963: 
 3964: ###############################################################
 3965: ##                Thesaurus Functions                        ##
 3966: ###############################################################
 3967: 
 3968: =pod
 3969: 
 3970: =head1 Thesaurus Functions
 3971: 
 3972: =over 4
 3973: 
 3974: =item * &initialize_keywords()
 3975: 
 3976: Initializes the package variable %Keywords if it is empty.  Uses the
 3977: package variable $thesaurus_db_file.
 3978: 
 3979: =cut
 3980: 
 3981: ###################################################
 3982: 
 3983: sub initialize_keywords {
 3984:     return 1 if (scalar keys(%Keywords));
 3985:     # If we are here, %Keywords is empty, so fill it up
 3986:     #   Make sure the file we need exists...
 3987:     if (! -e $thesaurus_db_file) {
 3988:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3989:                                  " failed because it does not exist");
 3990:         return 0;
 3991:     }
 3992:     #   Set up the hash as a database
 3993:     my %thesaurus_db;
 3994:     if (! tie(%thesaurus_db,'GDBM_File',
 3995:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3996:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3997:                                  $thesaurus_db_file);
 3998:         return 0;
 3999:     } 
 4000:     #  Get the average number of appearances of a word.
 4001:     my $avecount = $thesaurus_db{'average.count'};
 4002:     #  Put keywords (those that appear > average) into %Keywords
 4003:     while (my ($word,$data)=each (%thesaurus_db)) {
 4004:         my ($count,undef) = split /:/,$data;
 4005:         $Keywords{$word}++ if ($count > $avecount);
 4006:     }
 4007:     untie %thesaurus_db;
 4008:     # Remove special values from %Keywords.
 4009:     foreach my $value ('total.count','average.count') {
 4010:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 4011:   }
 4012:     return 1;
 4013: }
 4014: 
 4015: ###################################################
 4016: 
 4017: =pod
 4018: 
 4019: =item * &keyword($word)
 4020: 
 4021: Returns true if $word is a keyword.  A keyword is a word that appears more 
 4022: than the average number of times in the thesaurus database.  Calls 
 4023: &initialize_keywords
 4024: 
 4025: =cut
 4026: 
 4027: ###################################################
 4028: 
 4029: sub keyword {
 4030:     return if (!&initialize_keywords());
 4031:     my $word=lc(shift());
 4032:     $word=~s/\W//g;
 4033:     return exists($Keywords{$word});
 4034: }
 4035: 
 4036: ###############################################################
 4037: 
 4038: =pod 
 4039: 
 4040: =item * &get_related_words()
 4041: 
 4042: Look up a word in the thesaurus.  Takes a scalar argument and returns
 4043: an array of words.  If the keyword is not in the thesaurus, an empty array
 4044: will be returned.  The order of the words returned is determined by the
 4045: database which holds them.
 4046: 
 4047: Uses global $thesaurus_db_file.
 4048: 
 4049: 
 4050: =cut
 4051: 
 4052: ###############################################################
 4053: sub get_related_words {
 4054:     my $keyword = shift;
 4055:     my %thesaurus_db;
 4056:     if (! -e $thesaurus_db_file) {
 4057:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 4058:                                  "failed because the file does not exist");
 4059:         return ();
 4060:     }
 4061:     if (! tie(%thesaurus_db,'GDBM_File',
 4062:               $thesaurus_db_file,&GDBM_READER(),0640)){
 4063:         return ();
 4064:     } 
 4065:     my @Words=();
 4066:     my $count=0;
 4067:     if (exists($thesaurus_db{$keyword})) {
 4068: 	# The first element is the number of times
 4069: 	# the word appears.  We do not need it now.
 4070: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 4071: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 4072: 	my $threshold=$mostfrequentcount/10;
 4073:         foreach my $possibleword (@RelatedWords) {
 4074:             my ($word,$wordcount)=split(/\,/,$possibleword);
 4075:             if ($wordcount>$threshold) {
 4076: 		push(@Words,$word);
 4077:                 $count++;
 4078:                 if ($count>10) { last; }
 4079: 	    }
 4080:         }
 4081:     }
 4082:     untie %thesaurus_db;
 4083:     return @Words;
 4084: }
 4085: ###############################################################
 4086: #
 4087: #  Spell checking
 4088: #
 4089: 
 4090: =pod
 4091: 
 4092: =back
 4093: 
 4094: =head1 Spell checking
 4095: 
 4096: =over 4
 4097: 
 4098: =item * &check_spelling($wordlist $language)
 4099: 
 4100: Takes a string containing words and feeds it to an external
 4101: spellcheck program via a pipeline. Returns a string containing
 4102: them mis-spelled words.
 4103: 
 4104: Parameters:
 4105: 
 4106: =over 4
 4107: 
 4108: =item - $wordlist
 4109: 
 4110: String that will be fed into the spellcheck program.
 4111: 
 4112: =item - $language
 4113: 
 4114: Language string that specifies the language for which the spell
 4115: check will be performed.
 4116: 
 4117: =back
 4118: 
 4119: =back
 4120: 
 4121: Note: This sub assumes that aspell is installed.
 4122: 
 4123: 
 4124: =cut
 4125: 
 4126: 
 4127: sub check_spelling {
 4128:     my ($wordlist, $language) = @_;
 4129:     my @misspellings;
 4130:     
 4131:     # Generate the speller and set the langauge.
 4132:     # if explicitly selected:
 4133: 
 4134:     my $speller = Text::Aspell->new;
 4135:     if ($language) {
 4136: 	$speller->set_option('lang', $language);
 4137:     }
 4138: 
 4139:     # Turn the word list into an array of words by splittingon whitespace
 4140: 
 4141:     my @words = split(/\s+/, $wordlist);
 4142: 
 4143:     foreach my $word (@words) {
 4144: 	if(! $speller->check($word)) {
 4145: 	    push(@misspellings, $word);
 4146: 	}
 4147:     }
 4148:     return join(' ', @misspellings);
 4149:     
 4150: }
 4151: 
 4152: # -------------------------------------------------------------- Plaintext name
 4153: =pod
 4154: 
 4155: =head1 User Name Functions
 4156: 
 4157: =over 4
 4158: 
 4159: =item * &plainname($uname,$udom,$first)
 4160: 
 4161: Takes a users logon name and returns it as a string in
 4162: "first middle last generation" form 
 4163: if $first is set to 'lastname' then it returns it as
 4164: 'lastname generation, firstname middlename' if their is a lastname
 4165: 
 4166: =cut
 4167: 
 4168: 
 4169: ###############################################################
 4170: sub plainname {
 4171:     my ($uname,$udom,$first)=@_;
 4172:     return if (!defined($uname) || !defined($udom));
 4173:     my %names=&getnames($uname,$udom);
 4174:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 4175: 					  $names{'middlename'},
 4176: 					  $names{'lastname'},
 4177: 					  $names{'generation'},$first);
 4178:     $name=~s/^\s+//;
 4179:     $name=~s/\s+$//;
 4180:     $name=~s/\s+/ /g;
 4181:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 4182:     return $name;
 4183: }
 4184: 
 4185: # -------------------------------------------------------------------- Nickname
 4186: =pod
 4187: 
 4188: =item * &nickname($uname,$udom)
 4189: 
 4190: Gets a users name and returns it as a string as
 4191: 
 4192: "&quot;nickname&quot;"
 4193: 
 4194: if the user has a nickname or
 4195: 
 4196: "first middle last generation"
 4197: 
 4198: if the user does not
 4199: 
 4200: =cut
 4201: 
 4202: sub nickname {
 4203:     my ($uname,$udom)=@_;
 4204:     return if (!defined($uname) || !defined($udom));
 4205:     my %names=&getnames($uname,$udom);
 4206:     my $name=$names{'nickname'};
 4207:     if ($name) {
 4208:        $name='&quot;'.$name.'&quot;'; 
 4209:     } else {
 4210:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 4211: 	     $names{'lastname'}.' '.$names{'generation'};
 4212:        $name=~s/\s+$//;
 4213:        $name=~s/\s+/ /g;
 4214:     }
 4215:     return $name;
 4216: }
 4217: 
 4218: sub getnames {
 4219:     my ($uname,$udom)=@_;
 4220:     return if (!defined($uname) || !defined($udom));
 4221:     if ($udom eq 'public' && $uname eq 'public') {
 4222: 	return ('lastname' => &mt('Public'));
 4223:     }
 4224:     my $id=$uname.':'.$udom;
 4225:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 4226:     if ($cached) {
 4227: 	return %{$names};
 4228:     } else {
 4229: 	my %loadnames=&Apache::lonnet::get('environment',
 4230:                     ['firstname','middlename','lastname','generation','nickname'],
 4231: 					 $udom,$uname);
 4232: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 4233: 	return %loadnames;
 4234:     }
 4235: }
 4236: 
 4237: # -------------------------------------------------------------------- getemails
 4238: 
 4239: =pod
 4240: 
 4241: =item * &getemails($uname,$udom)
 4242: 
 4243: Gets a user's email information and returns it as a hash with keys:
 4244: notification, critnotification, permanentemail
 4245: 
 4246: For notification and critnotification, values are comma-separated lists 
 4247: of e-mail addresses; for permanentemail, value is a single e-mail address.
 4248:  
 4249: 
 4250: =cut
 4251: 
 4252: 
 4253: sub getemails {
 4254:     my ($uname,$udom)=@_;
 4255:     if ($udom eq 'public' && $uname eq 'public') {
 4256: 	return;
 4257:     }
 4258:     if (!$udom) { $udom=$env{'user.domain'}; }
 4259:     if (!$uname) { $uname=$env{'user.name'}; }
 4260:     my $id=$uname.':'.$udom;
 4261:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 4262:     if ($cached) {
 4263: 	return %{$names};
 4264:     } else {
 4265: 	my %loadnames=&Apache::lonnet::get('environment',
 4266:                     			   ['notification','critnotification',
 4267: 					    'permanentemail'],
 4268: 					   $udom,$uname);
 4269: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4270: 	return %loadnames;
 4271:     }
 4272: }
 4273: 
 4274: sub flush_email_cache {
 4275:     my ($uname,$udom)=@_;
 4276:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4277:     if (!$uname) { $uname=$env{'user.name'};   }
 4278:     return if ($udom eq 'public' && $uname eq 'public');
 4279:     my $id=$uname.':'.$udom;
 4280:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4281: }
 4282: 
 4283: # -------------------------------------------------------------------- getlangs
 4284: 
 4285: =pod
 4286: 
 4287: =item * &getlangs($uname,$udom)
 4288: 
 4289: Gets a user's language preference and returns it as a hash with key:
 4290: language.
 4291: 
 4292: =cut
 4293: 
 4294: 
 4295: sub getlangs {
 4296:     my ($uname,$udom) = @_;
 4297:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4298:     if (!$uname) { $uname=$env{'user.name'};   }
 4299:     my $id=$uname.':'.$udom;
 4300:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4301:     if ($cached) {
 4302:         return %{$langs};
 4303:     } else {
 4304:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4305:                                            $udom,$uname);
 4306:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4307:         return %loadlangs;
 4308:     }
 4309: }
 4310: 
 4311: sub flush_langs_cache {
 4312:     my ($uname,$udom)=@_;
 4313:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4314:     if (!$uname) { $uname=$env{'user.name'};   }
 4315:     return if ($udom eq 'public' && $uname eq 'public');
 4316:     my $id=$uname.':'.$udom;
 4317:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4318: }
 4319: 
 4320: # ------------------------------------------------------------------ Screenname
 4321: 
 4322: =pod
 4323: 
 4324: =item * &screenname($uname,$udom)
 4325: 
 4326: Gets a users screenname and returns it as a string
 4327: 
 4328: =cut
 4329: 
 4330: sub screenname {
 4331:     my ($uname,$udom)=@_;
 4332:     if ($uname eq $env{'user.name'} &&
 4333: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4334:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4335:     return $names{'screenname'};
 4336: }
 4337: 
 4338: 
 4339: # ------------------------------------------------------------- Confirm Wrapper
 4340: =pod
 4341: 
 4342: =item * &confirmwrapper($message)
 4343: 
 4344: Wrap messages about completion of operation in box
 4345: 
 4346: =cut
 4347: 
 4348: sub confirmwrapper {
 4349:     my ($message)=@_;
 4350:     if ($message) {
 4351:         return "\n".'<div class="LC_confirm_box">'."\n"
 4352:                .$message."\n"
 4353:                .'</div>'."\n";
 4354:     } else {
 4355:         return $message;
 4356:     }
 4357: }
 4358: 
 4359: # ------------------------------------------------------------- Message Wrapper
 4360: 
 4361: sub messagewrapper {
 4362:     my ($link,$username,$domain,$subject,$text)=@_;
 4363:     return 
 4364:         '<a href="/adm/email?compose=individual&amp;'.
 4365:         'recname='.$username.'&amp;recdom='.$domain.
 4366: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4367:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4368: }
 4369: 
 4370: # --------------------------------------------------------------- Notes Wrapper
 4371: 
 4372: sub noteswrapper {
 4373:     my ($link,$un,$do)=@_;
 4374:     return 
 4375: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4376: }
 4377: 
 4378: # ------------------------------------------------------------- Aboutme Wrapper
 4379: 
 4380: sub aboutmewrapper {
 4381:     my ($link,$username,$domain,$target,$class)=@_;
 4382:     if (!defined($username)  && !defined($domain)) {
 4383:         return;
 4384:     }
 4385:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4386: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4387: }
 4388: 
 4389: # ------------------------------------------------------------ Syllabus Wrapper
 4390: 
 4391: sub syllabuswrapper {
 4392:     my ($linktext,$coursedir,$domain)=@_;
 4393:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4394: }
 4395: 
 4396: # -----------------------------------------------------------------------------
 4397: 
 4398: sub aboutme_on {
 4399:     my ($uname,$udom)=@_;
 4400:     unless ($uname) { $uname=$env{'user.name'}; }
 4401:     unless ($udom)  { $udom=$env{'user.domain'}; }
 4402:     return if ($udom eq 'public' && $uname eq 'public');
 4403:     my $hashkey=$uname.':'.$udom;
 4404:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
 4405:     if ($cached) {
 4406:         return $aboutme;
 4407:     }
 4408:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
 4409:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
 4410:     return $aboutme;
 4411: }
 4412: 
 4413: sub devalidate_aboutme_cache {
 4414:     my ($uname,$udom)=@_;
 4415:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4416:     if (!$uname) { $uname=$env{'user.name'};   }
 4417:     return if ($udom eq 'public' && $uname eq 'public');
 4418:     my $id=$uname.':'.$udom;
 4419:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
 4420: }
 4421: 
 4422: sub track_student_link {
 4423:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4424:     my $link ="/adm/trackstudent?";
 4425:     my $title = 'View recent activity';
 4426:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4427:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4428:         $link .= "selected_student=$sname:$sdom";
 4429:         $title .= ' of this student';
 4430:     } 
 4431:     if (defined($target) && $target !~ /^\s*$/) {
 4432:         $target = qq{target="$target"};
 4433:     } else {
 4434:         $target = '';
 4435:     }
 4436:     if ($start) { $link.='&amp;start='.$start; }
 4437:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4438:     $title = &mt($title);
 4439:     $linktext = &mt($linktext);
 4440:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4441: 	&help_open_topic('View_recent_activity');
 4442: }
 4443: 
 4444: sub slot_reservations_link {
 4445:     my ($linktext,$sname,$sdom,$target) = @_;
 4446:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4447:     my $title = 'View slot reservation history';
 4448:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4449:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4450:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4451:         $title .= ' of this student';
 4452:     }
 4453:     if (defined($target) && $target !~ /^\s*$/) {
 4454:         $target = qq{target="$target"};
 4455:     } else {
 4456:         $target = '';
 4457:     }
 4458:     $title = &mt($title);
 4459:     $linktext = &mt($linktext);
 4460:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4461: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4462: 
 4463: }
 4464: 
 4465: # ===================================================== Display a student photo
 4466: 
 4467: 
 4468: sub student_image_tag {
 4469:     my ($domain,$user)=@_;
 4470:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4471:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4472: 	return '<img src="'.$imgsrc.'" align="right" />';
 4473:     } else {
 4474: 	return '';
 4475:     }
 4476: }
 4477: 
 4478: =pod
 4479: 
 4480: =back
 4481: 
 4482: =head1 Access .tab File Data
 4483: 
 4484: =over 4
 4485: 
 4486: =item * &languageids() 
 4487: 
 4488: returns list of all language ids
 4489: 
 4490: =cut
 4491: 
 4492: sub languageids {
 4493:     return sort(keys(%language));
 4494: }
 4495: 
 4496: =pod
 4497: 
 4498: =item * &languagedescription() 
 4499: 
 4500: returns description of a specified language id
 4501: 
 4502: =cut
 4503: 
 4504: sub languagedescription {
 4505:     my $code=shift;
 4506:     return  ($supported_language{$code}?'* ':'').
 4507:             $language{$code}.
 4508: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4509: }
 4510: 
 4511: =pod
 4512: 
 4513: =item * &plainlanguagedescription
 4514: 
 4515: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4516: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4517: 
 4518: =cut
 4519: 
 4520: sub plainlanguagedescription {
 4521:     my $code=shift;
 4522:     return $language{$code};
 4523: }
 4524: 
 4525: =pod
 4526: 
 4527: =item * &supportedlanguagecode
 4528: 
 4529: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4530: code.
 4531: 
 4532: =cut
 4533: 
 4534: sub supportedlanguagecode {
 4535:     my $code=shift;
 4536:     return $supported_language{$code};
 4537: }
 4538: 
 4539: =pod
 4540: 
 4541: =item * &latexlanguage()
 4542: 
 4543: Given a language key code returns the correspondnig language to use
 4544: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4545: is no supported hyphenation for the language code.
 4546: 
 4547: =cut
 4548: 
 4549: sub latexlanguage {
 4550:     my $code = shift;
 4551:     return $latex_language{$code};
 4552: }
 4553: 
 4554: =pod
 4555: 
 4556: =item * &latexhyphenation()
 4557: 
 4558: Same as above but what's supplied is the language as it might be stored
 4559: in the metadata.
 4560: 
 4561: =cut
 4562: 
 4563: sub latexhyphenation {
 4564:     my $key = shift;
 4565:     return $latex_language_bykey{$key};
 4566: }
 4567: 
 4568: =pod
 4569: 
 4570: =item * &copyrightids() 
 4571: 
 4572: returns list of all copyrights
 4573: 
 4574: =cut
 4575: 
 4576: sub copyrightids {
 4577:     return sort(keys(%cprtag));
 4578: }
 4579: 
 4580: =pod
 4581: 
 4582: =item * &copyrightdescription() 
 4583: 
 4584: returns description of a specified copyright id
 4585: 
 4586: =cut
 4587: 
 4588: sub copyrightdescription {
 4589:     return &mt($cprtag{shift(@_)});
 4590: }
 4591: 
 4592: =pod
 4593: 
 4594: =item * &source_copyrightids() 
 4595: 
 4596: returns list of all source copyrights
 4597: 
 4598: =cut
 4599: 
 4600: sub source_copyrightids {
 4601:     return sort(keys(%scprtag));
 4602: }
 4603: 
 4604: =pod
 4605: 
 4606: =item * &source_copyrightdescription() 
 4607: 
 4608: returns description of a specified source copyright id
 4609: 
 4610: =cut
 4611: 
 4612: sub source_copyrightdescription {
 4613:     return &mt($scprtag{shift(@_)});
 4614: }
 4615: 
 4616: =pod
 4617: 
 4618: =item * &filecategories() 
 4619: 
 4620: returns list of all file categories
 4621: 
 4622: =cut
 4623: 
 4624: sub filecategories {
 4625:     return sort(keys(%category_extensions));
 4626: }
 4627: 
 4628: =pod
 4629: 
 4630: =item * &filecategorytypes() 
 4631: 
 4632: returns list of file types belonging to a given file
 4633: category
 4634: 
 4635: =cut
 4636: 
 4637: sub filecategorytypes {
 4638:     my ($cat) = @_;
 4639:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4640:         return @{$category_extensions{lc($cat)}};
 4641:     } else {
 4642:         return ();
 4643:     }
 4644: }
 4645: 
 4646: =pod
 4647: 
 4648: =item * &fileembstyle() 
 4649: 
 4650: returns embedding style for a specified file type
 4651: 
 4652: =cut
 4653: 
 4654: sub fileembstyle {
 4655:     return $fe{lc(shift(@_))};
 4656: }
 4657: 
 4658: sub filemimetype {
 4659:     return $fm{lc(shift(@_))};
 4660: }
 4661: 
 4662: 
 4663: sub filecategoryselect {
 4664:     my ($name,$value)=@_;
 4665:     return &select_form($value,$name,
 4666:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4667: }
 4668: 
 4669: =pod
 4670: 
 4671: =item * &filedescription() 
 4672: 
 4673: returns description for a specified file type
 4674: 
 4675: =cut
 4676: 
 4677: sub filedescription {
 4678:     my $file_description = $fd{lc(shift())};
 4679:     $file_description =~ s:([\[\]]):~$1:g;
 4680:     return &mt($file_description);
 4681: }
 4682: 
 4683: =pod
 4684: 
 4685: =item * &filedescriptionex() 
 4686: 
 4687: returns description for a specified file type with
 4688: extra formatting
 4689: 
 4690: =cut
 4691: 
 4692: sub filedescriptionex {
 4693:     my $ex=shift;
 4694:     my $file_description = $fd{lc($ex)};
 4695:     $file_description =~ s:([\[\]]):~$1:g;
 4696:     return '.'.$ex.' '.&mt($file_description);
 4697: }
 4698: 
 4699: # End of .tab access
 4700: =pod
 4701: 
 4702: =back
 4703: 
 4704: =cut
 4705: 
 4706: # ------------------------------------------------------------------ File Types
 4707: sub fileextensions {
 4708:     return sort(keys(%fe));
 4709: }
 4710: 
 4711: # ----------------------------------------------------------- Display Languages
 4712: # returns a hash with all desired display languages
 4713: #
 4714: 
 4715: sub display_languages {
 4716:     my %languages=();
 4717:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4718: 	$languages{$lang}=1;
 4719:     }
 4720:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4721:     if ($env{'form.displaylanguage'}) {
 4722: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4723: 	    $languages{$lang}=1;
 4724:         }
 4725:     }
 4726:     return %languages;
 4727: }
 4728: 
 4729: sub languages {
 4730:     my ($possible_langs) = @_;
 4731:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4732:     if (!ref($possible_langs)) {
 4733: 	if( wantarray ) {
 4734: 	    return @preferred_langs;
 4735: 	} else {
 4736: 	    return $preferred_langs[0];
 4737: 	}
 4738:     }
 4739:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4740:     my @preferred_possibilities;
 4741:     foreach my $preferred_lang (@preferred_langs) {
 4742: 	if (exists($possibilities{$preferred_lang})) {
 4743: 	    push(@preferred_possibilities, $preferred_lang);
 4744: 	}
 4745:     }
 4746:     if( wantarray ) {
 4747: 	return @preferred_possibilities;
 4748:     }
 4749:     return $preferred_possibilities[0];
 4750: }
 4751: 
 4752: sub user_lang {
 4753:     my ($touname,$toudom,$fromcid) = @_;
 4754:     my @userlangs;
 4755:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4756:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4757:                     $env{'course.'.$fromcid.'.languages'}));
 4758:     } else {
 4759:         my %langhash = &getlangs($touname,$toudom);
 4760:         if ($langhash{'languages'} ne '') {
 4761:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4762:         } else {
 4763:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4764:             if ($domdefs{'lang_def'} ne '') {
 4765:                 @userlangs = ($domdefs{'lang_def'});
 4766:             }
 4767:         }
 4768:     }
 4769:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4770:     my $user_lh = Apache::localize->get_handle(@languages);
 4771:     return $user_lh;
 4772: }
 4773: 
 4774: 
 4775: ###############################################################
 4776: ##               Student Answer Attempts                     ##
 4777: ###############################################################
 4778: 
 4779: =pod
 4780: 
 4781: =head1 Alternate Problem Views
 4782: 
 4783: =over 4
 4784: 
 4785: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4786:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4787: 
 4788: Return string with previous attempt on problem. Arguments:
 4789: 
 4790: =over 4
 4791: 
 4792: =item * $symb: Problem, including path
 4793: 
 4794: =item * $username: username of the desired student
 4795: 
 4796: =item * $domain: domain of the desired student
 4797: 
 4798: =item * $course: Course ID
 4799: 
 4800: =item * $getattempt: Leave blank for all attempts, otherwise put
 4801:     something
 4802: 
 4803: =item * $regexp: if string matches this regexp, the string will be
 4804:     sent to $gradesub
 4805: 
 4806: =item * $gradesub: routine that processes the string if it matches $regexp
 4807: 
 4808: =item * $usec: section of the desired student
 4809: 
 4810: =item * $identifier: counter for student (multiple students one problem) or 
 4811:     problem (one student; whole sequence).
 4812: 
 4813: =back
 4814: 
 4815: The output string is a table containing all desired attempts, if any.
 4816: 
 4817: =cut
 4818: 
 4819: sub get_previous_attempt {
 4820:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4821:   my $prevattempts='';
 4822:   no strict 'refs';
 4823:   if ($symb) {
 4824:     my (%returnhash)=
 4825:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4826:     if ($returnhash{'version'}) {
 4827:       my %lasthash=();
 4828:       my $version;
 4829:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4830:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4831:             if ($key =~ /\.rawrndseed$/) {
 4832:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4833:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4834:             } else {
 4835:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4836:             }
 4837:         }
 4838:       }
 4839:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4840:       $prevattempts.='<th>'.&mt('History').'</th>';
 4841:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4842:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4843:       foreach my $key (sort(keys(%lasthash))) {
 4844: 	my ($ign,@parts) = split(/\./,$key);
 4845: 	if ($#parts > 0) {
 4846: 	  my $data=$parts[-1];
 4847:           next if ($data eq 'foilorder');
 4848: 	  pop(@parts);
 4849:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4850:           if ($data eq 'type') {
 4851:               unless ($showsurv) {
 4852:                   my $id = join(',',@parts);
 4853:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4854:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4855:                       $lasthidden{$ign.'.'.$id} = 1;
 4856:                   }
 4857:               }
 4858:               if ($identifier ne '') {
 4859:                   my $id = join(',',@parts);
 4860:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4861:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4862:                       $hidestatus{$ign.'.'.$id} = 1;
 4863:                   }
 4864:               }
 4865:           } elsif ($data eq 'regrader') {
 4866:               if (($identifier ne '') && (@parts)) {
 4867:                   my $id = join(',',@parts);
 4868:                   $regraded{$ign.'.'.$id} = 1;
 4869:               }
 4870:           } 
 4871: 	} else {
 4872: 	  if ($#parts == 0) {
 4873: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4874: 	  } else {
 4875: 	    $prevattempts.='<th>'.$ign.'</th>';
 4876: 	  }
 4877: 	}
 4878:       }
 4879:       $prevattempts.=&end_data_table_header_row();
 4880:       if ($getattempt eq '') {
 4881:         my (%solved,%resets,%probstatus);
 4882:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4883:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4884:                 foreach my $id (keys(%regraded)) {
 4885:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4886:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4887:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4888:                         push(@{$resets{$id}},$version);
 4889:                     }
 4890:                 }
 4891:             }
 4892:         }
 4893: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4894:             my (@hidden,@unsolved);
 4895:             if (%typeparts) {
 4896:                 foreach my $id (keys(%typeparts)) {
 4897:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4898:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4899:                         push(@hidden,$id);
 4900:                     } elsif ($identifier ne '') {
 4901:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4902:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4903:                                 ($hidestatus{$id})) {
 4904:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4905:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4906:                                 push(@{$solved{$id}},$version);
 4907:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4908:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4909:                                 my $skip;
 4910:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4911:                                     foreach my $reset (@{$resets{$id}}) {
 4912:                                         if ($reset > $solved{$id}[-1]) {
 4913:                                             $skip=1;
 4914:                                             last;
 4915:                                         }
 4916:                                     }
 4917:                                 }
 4918:                                 unless ($skip) {
 4919:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4920:                                     push(@unsolved,$partslist);
 4921:                                 }
 4922:                             }
 4923:                         }
 4924:                     }
 4925:                 }
 4926:             }
 4927:             $prevattempts.=&start_data_table_row().
 4928:                            '<td>'.&mt('Transaction [_1]',$version);
 4929:             if (@unsolved) {
 4930:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4931:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4932:                                  &mt('Hide').'</label></span>';
 4933:             }
 4934:             $prevattempts .= '</td>';
 4935:             if (@hidden) {
 4936:                 foreach my $key (sort(keys(%lasthash))) {
 4937:                     next if ($key =~ /\.foilorder$/);
 4938:                     my $hide;
 4939:                     foreach my $id (@hidden) {
 4940:                         if ($key =~ /^\Q$id\E/) {
 4941:                             $hide = 1;
 4942:                             last;
 4943:                         }
 4944:                     }
 4945:                     if ($hide) {
 4946:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4947:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4948:                             my $value = &format_previous_attempt_value($key,
 4949:                                              $returnhash{$version.':'.$key});
 4950:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4951:                         } else {
 4952:                             $prevattempts.='<td>&nbsp;</td>';
 4953:                         }
 4954:                     } else {
 4955:                         if ($key =~ /\./) {
 4956:                             my $value = $returnhash{$version.':'.$key};
 4957:                             if ($key =~ /\.rndseed$/) {
 4958:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4959:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4960:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4961:                                 }
 4962:                             }
 4963:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4964:                                            '&nbsp;</td>';
 4965:                         } else {
 4966:                             $prevattempts.='<td>&nbsp;</td>';
 4967:                         }
 4968:                     }
 4969:                 }
 4970:             } else {
 4971: 	        foreach my $key (sort(keys(%lasthash))) {
 4972:                     next if ($key =~ /\.foilorder$/);
 4973:                     my $value = $returnhash{$version.':'.$key};
 4974:                     if ($key =~ /\.rndseed$/) {
 4975:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4976:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4977:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4978:                         }
 4979:                     }
 4980:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4981:                                    '&nbsp;</td>';
 4982: 	        }
 4983:             }
 4984: 	    $prevattempts.=&end_data_table_row();
 4985: 	 }
 4986:       }
 4987:       my @currhidden = keys(%lasthidden);
 4988:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4989:       foreach my $key (sort(keys(%lasthash))) {
 4990:           next if ($key =~ /\.foilorder$/);
 4991:           if (%typeparts) {
 4992:               my $hidden;
 4993:               foreach my $id (@currhidden) {
 4994:                   if ($key =~ /^\Q$id\E/) {
 4995:                       $hidden = 1;
 4996:                       last;
 4997:                   }
 4998:               }
 4999:               if ($hidden) {
 5000:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 5001:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 5002:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5003:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5004:                           $value = &$gradesub($value);
 5005:                       }
 5006:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 5007:                   } else {
 5008:                       $prevattempts.='<td>&nbsp;</td>';
 5009:                   }
 5010:               } else {
 5011:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5012:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5013:                       $value = &$gradesub($value);
 5014:                   }
 5015:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5016:               }
 5017:           } else {
 5018: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5019: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5020:                   $value = &$gradesub($value);
 5021:               }
 5022: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5023:           }
 5024:       }
 5025:       $prevattempts.= &end_data_table_row().&end_data_table();
 5026:     } else {
 5027:       my $msg;
 5028:       if ($symb =~ /ext\.tool$/) {
 5029:           $msg = &mt('No grade passed back.');
 5030:       } else {
 5031:           $msg = &mt('Nothing submitted - no attempts.');
 5032:       }
 5033:       $prevattempts=
 5034: 	  &start_data_table().&start_data_table_row().
 5035: 	  '<td>'.$msg.'</td>'.
 5036: 	  &end_data_table_row().&end_data_table();
 5037:     }
 5038:   } else {
 5039:     $prevattempts=
 5040: 	  &start_data_table().&start_data_table_row().
 5041: 	  '<td>'.&mt('No data.').'</td>'.
 5042: 	  &end_data_table_row().&end_data_table();
 5043:   }
 5044: }
 5045: 
 5046: sub format_previous_attempt_value {
 5047:     my ($key,$value) = @_;
 5048:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 5049:         $value = &Apache::lonlocal::locallocaltime($value);
 5050:     } elsif (ref($value) eq 'ARRAY') {
 5051:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 5052:     } elsif ($key =~ /answerstring$/) {
 5053:         my %answers = &Apache::lonnet::str2hash($value);
 5054:         my @answer = %answers;
 5055:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 5056:         my @anskeys = sort(keys(%answers));
 5057:         if (@anskeys == 1) {
 5058:             my $answer = $answers{$anskeys[0]};
 5059:             if ($answer =~ m{\0}) {
 5060:                 $answer =~ s{\0}{,}g;
 5061:             }
 5062:             my $tag_internal_answer_name = 'INTERNAL';
 5063:             if ($anskeys[0] eq $tag_internal_answer_name) {
 5064:                 $value = $answer; 
 5065:             } else {
 5066:                 $value = $anskeys[0].'='.$answer;
 5067:             }
 5068:         } else {
 5069:             foreach my $ans (@anskeys) {
 5070:                 my $answer = $answers{$ans};
 5071:                 if ($answer =~ m{\0}) {
 5072:                     $answer =~ s{\0}{,}g;
 5073:                 }
 5074:                 $value .=  $ans.'='.$answer.'<br />';;
 5075:             } 
 5076:         }
 5077:     } else {
 5078:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 5079:     }
 5080:     return $value;
 5081: }
 5082: 
 5083: 
 5084: sub relative_to_absolute {
 5085:     my ($url,$output)=@_;
 5086:     my $parser=HTML::TokeParser->new(\$output);
 5087:     my $token;
 5088:     my $thisdir=$url;
 5089:     my @rlinks=();
 5090:     while ($token=$parser->get_token) {
 5091: 	if ($token->[0] eq 'S') {
 5092: 	    if ($token->[1] eq 'a') {
 5093: 		if ($token->[2]->{'href'}) {
 5094: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 5095: 		}
 5096: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 5097: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 5098: 	    } elsif ($token->[1] eq 'base') {
 5099: 		$thisdir=$token->[2]->{'href'};
 5100: 	    }
 5101: 	}
 5102:     }
 5103:     $thisdir=~s-/[^/]*$--;
 5104:     foreach my $link (@rlinks) {
 5105: 	unless (($link=~/^https?\:\/\//i) ||
 5106: 		($link=~/^\//) ||
 5107: 		($link=~/^javascript:/i) ||
 5108: 		($link=~/^mailto:/i) ||
 5109: 		($link=~/^\#/)) {
 5110: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 5111: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 5112: 	}
 5113:     }
 5114: # -------------------------------------------------- Deal with Applet codebases
 5115:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 5116:     return $output;
 5117: }
 5118: 
 5119: =pod
 5120: 
 5121: =item * &get_student_view()
 5122: 
 5123: show a snapshot of what student was looking at
 5124: 
 5125: =cut
 5126: 
 5127: sub get_student_view {
 5128:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 5129:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5130:   my (%form);
 5131:   my @elements=('symb','courseid','domain','username');
 5132:   foreach my $element (@elements) {
 5133:       $form{'grade_'.$element}=eval '$'.$element #'
 5134:   }
 5135:   if (defined($moreenv)) {
 5136:       %form=(%form,%{$moreenv});
 5137:   }
 5138:   if (defined($target)) { $form{'grade_target'} = $target; }
 5139:   $feedurl=&Apache::lonnet::clutter($feedurl);
 5140:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 5141:       $feedurl =~ s{^/adm/wrapper}{};
 5142:   }
 5143:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 5144:   $userview=~s/\<body[^\>]*\>//gi;
 5145:   $userview=~s/\<\/body\>//gi;
 5146:   $userview=~s/\<html\>//gi;
 5147:   $userview=~s/\<\/html\>//gi;
 5148:   $userview=~s/\<head\>//gi;
 5149:   $userview=~s/\<\/head\>//gi;
 5150:   $userview=~s/action\s*\=/would_be_action\=/gi;
 5151:   $userview=&relative_to_absolute($feedurl,$userview);
 5152:   if (wantarray) {
 5153:      return ($userview,$response);
 5154:   } else {
 5155:      return $userview;
 5156:   }
 5157: }
 5158: 
 5159: sub get_student_view_with_retries {
 5160:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 5161: 
 5162:     my $ok = 0;                 # True if we got a good response.
 5163:     my $content;
 5164:     my $response;
 5165: 
 5166:     # Try to get the student_view done. within the retries count:
 5167:     
 5168:     do {
 5169:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 5170:          $ok      = $response->is_success;
 5171:          if (!$ok) {
 5172:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 5173:          }
 5174:          $retries--;
 5175:     } while (!$ok && ($retries > 0));
 5176:     
 5177:     if (!$ok) {
 5178:        $content = '';          # On error return an empty content.
 5179:     }
 5180:     if (wantarray) {
 5181:        return ($content, $response);
 5182:     } else {
 5183:        return $content;
 5184:     }
 5185: }
 5186: 
 5187: sub css_links {
 5188:     my ($currsymb,$level) = @_;
 5189:     my ($links,@symbs,%cssrefs,%httpref);
 5190:     if ($level eq 'map') {
 5191:         my $navmap = Apache::lonnavmaps::navmap->new();
 5192:         if (ref($navmap)) {
 5193:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 5194:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 5195:             foreach my $res (@resources) {
 5196:                 if (ref($res) && $res->symb()) {
 5197:                     push(@symbs,$res->symb());
 5198:                 }
 5199:             }
 5200:         }
 5201:     } else {
 5202:         @symbs = ($currsymb);
 5203:     }
 5204:     foreach my $symb (@symbs) {
 5205:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 5206:         if ($css_href =~ /\S/) {
 5207:             unless ($css_href =~ m{https?://}) {
 5208:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 5209:                 my $proburl =  &Apache::lonnet::clutter($url);
 5210:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 5211:                 unless ($css_href =~ m{^/}) {
 5212:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 5213:                 }
 5214:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 5215:                     unless (($httpref{'httpref.'.$css_href}) ||
 5216:                             (&Apache::lonnet::is_on_map($css_href))) {
 5217:                         my $thisurl = $proburl;
 5218:                         if ($env{'httpref.'.$proburl}) {
 5219:                             $thisurl = $env{'httpref.'.$proburl};
 5220:                         }
 5221:                         $httpref{'httpref.'.$css_href} = $thisurl;
 5222:                     }
 5223:                 }
 5224:             }
 5225:             $cssrefs{$css_href} = 1;
 5226:         }
 5227:     }
 5228:     if (keys(%httpref)) {
 5229:         &Apache::lonnet::appenv(\%httpref);
 5230:     }
 5231:     if (keys(%cssrefs)) {
 5232:         foreach my $css_href (keys(%cssrefs)) {
 5233:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 5234:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 5235:         }
 5236:     }
 5237:     return $links;
 5238: }
 5239: 
 5240: =pod
 5241: 
 5242: =item * &get_student_answers() 
 5243: 
 5244: show a snapshot of how student was answering problem
 5245: 
 5246: =cut
 5247: 
 5248: sub get_student_answers {
 5249:   my ($symb,$username,$domain,$courseid,%form) = @_;
 5250:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5251:   my (%moreenv);
 5252:   my @elements=('symb','courseid','domain','username');
 5253:   foreach my $element (@elements) {
 5254:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 5255:   }
 5256:   $moreenv{'grade_target'}='answer';
 5257:   %moreenv=(%form,%moreenv);
 5258:   $feedurl = &Apache::lonnet::clutter($feedurl);
 5259:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 5260:   return $userview;
 5261: }
 5262: 
 5263: =pod
 5264: 
 5265: =item * &submlink()
 5266: 
 5267: Inputs: $text $uname $udom $symb $target
 5268: 
 5269: Returns: A link to grades.pm such as to see the SUBM view of a student
 5270: 
 5271: =cut
 5272: 
 5273: ###############################################
 5274: sub submlink {
 5275:     my ($text,$uname,$udom,$symb,$target)=@_;
 5276:     if (!($uname && $udom)) {
 5277: 	(my $cursymb, my $courseid,$udom,$uname)=
 5278: 	    &Apache::lonnet::whichuser($symb);
 5279: 	if (!$symb) { $symb=$cursymb; }
 5280:     }
 5281:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5282:     $symb=&escape($symb);
 5283:     if ($target) { $target=" target=\"$target\""; }
 5284:     return
 5285:         '<a href="/adm/grades?command=submission'.
 5286:         '&amp;symb='.$symb.
 5287:         '&amp;student='.$uname.
 5288:         '&amp;userdom='.$udom.'"'.
 5289:         $target.'>'.$text.'</a>';
 5290: }
 5291: ##############################################
 5292: 
 5293: =pod
 5294: 
 5295: =item * &pgrdlink()
 5296: 
 5297: Inputs: $text $uname $udom $symb $target
 5298: 
 5299: Returns: A link to grades.pm such as to see the PGRD view of a student
 5300: 
 5301: =cut
 5302: 
 5303: ###############################################
 5304: sub pgrdlink {
 5305:     my $link=&submlink(@_);
 5306:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 5307:     return $link;
 5308: }
 5309: ##############################################
 5310: 
 5311: =pod
 5312: 
 5313: =item * &pprmlink()
 5314: 
 5315: Inputs: $text $uname $udom $symb $target
 5316: 
 5317: Returns: A link to parmset.pm such as to see the PPRM view of a
 5318: student and a specific resource
 5319: 
 5320: =cut
 5321: 
 5322: ###############################################
 5323: sub pprmlink {
 5324:     my ($text,$uname,$udom,$symb,$target)=@_;
 5325:     if (!($uname && $udom)) {
 5326: 	(my $cursymb, my $courseid,$udom,$uname)=
 5327: 	    &Apache::lonnet::whichuser($symb);
 5328: 	if (!$symb) { $symb=$cursymb; }
 5329:     }
 5330:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5331:     $symb=&escape($symb);
 5332:     if ($target) { $target="target=\"$target\""; }
 5333:     return '<a href="/adm/parmset?command=set&amp;'.
 5334: 	'symb='.$symb.'&amp;uname='.$uname.
 5335: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 5336: }
 5337: ##############################################
 5338: 
 5339: =pod
 5340: 
 5341: =back
 5342: 
 5343: =cut
 5344: 
 5345: ###############################################
 5346: 
 5347: 
 5348: sub timehash {
 5349:     my ($thistime) = @_;
 5350:     my $timezone = &Apache::lonlocal::gettimezone();
 5351:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5352:                      ->set_time_zone($timezone);
 5353:     my $wday = $dt->day_of_week();
 5354:     if ($wday == 7) { $wday = 0; }
 5355:     return ( 'second' => $dt->second(),
 5356:              'minute' => $dt->minute(),
 5357:              'hour'   => $dt->hour(),
 5358:              'day'     => $dt->day_of_month(),
 5359:              'month'   => $dt->month(),
 5360:              'year'    => $dt->year(),
 5361:              'weekday' => $wday,
 5362:              'dayyear' => $dt->day_of_year(),
 5363:              'dlsav'   => $dt->is_dst() );
 5364: }
 5365: 
 5366: sub utc_string {
 5367:     my ($date)=@_;
 5368:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5369: }
 5370: 
 5371: sub maketime {
 5372:     my %th=@_;
 5373:     my ($epoch_time,$timezone,$dt);
 5374:     $timezone = &Apache::lonlocal::gettimezone();
 5375:     eval {
 5376:         $dt = DateTime->new( year   => $th{'year'},
 5377:                              month  => $th{'month'},
 5378:                              day    => $th{'day'},
 5379:                              hour   => $th{'hour'},
 5380:                              minute => $th{'minute'},
 5381:                              second => $th{'second'},
 5382:                              time_zone => $timezone,
 5383:                          );
 5384:     };
 5385:     if (!$@) {
 5386:         $epoch_time = $dt->epoch;
 5387:         if ($epoch_time) {
 5388:             return $epoch_time;
 5389:         }
 5390:     }
 5391:     return POSIX::mktime(
 5392:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5393:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5394: }
 5395: 
 5396: #########################################
 5397: 
 5398: sub findallcourses {
 5399:     my ($roles,$uname,$udom) = @_;
 5400:     my %roles;
 5401:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5402:     my %courses;
 5403:     my $now=time;
 5404:     if (!defined($uname)) {
 5405:         $uname = $env{'user.name'};
 5406:     }
 5407:     if (!defined($udom)) {
 5408:         $udom = $env{'user.domain'};
 5409:     }
 5410:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5411:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5412:         if (!%roles) {
 5413:             %roles = (
 5414:                        cc => 1,
 5415:                        co => 1,
 5416:                        in => 1,
 5417:                        ep => 1,
 5418:                        ta => 1,
 5419:                        cr => 1,
 5420:                        st => 1,
 5421:              );
 5422:         }
 5423:         foreach my $entry (keys(%roleshash)) {
 5424:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5425:             if ($trole =~ /^cr/) { 
 5426:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5427:             } else {
 5428:                 next if (!exists($roles{$trole}));
 5429:             }
 5430:             if ($tend) {
 5431:                 next if ($tend < $now);
 5432:             }
 5433:             if ($tstart) {
 5434:                 next if ($tstart > $now);
 5435:             }
 5436:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5437:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5438:             my $value = $trole.'/'.$cdom.'/';
 5439:             if ($secpart eq '') {
 5440:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5441:                 $sec = 'none';
 5442:                 $value .= $cnum.'/';
 5443:             } else {
 5444:                 $cnum = $cnumpart;
 5445:                 ($sec,$role) = split(/_/,$secpart);
 5446:                 $value .= $cnum.'/'.$sec;
 5447:             }
 5448:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5449:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5450:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5451:                 }
 5452:             } else {
 5453:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5454:             }
 5455:         }
 5456:     } else {
 5457:         foreach my $key (keys(%env)) {
 5458: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5459:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5460: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5461: 	        next if ($role eq 'ca' || $role eq 'aa');
 5462: 	        next if (%roles && !exists($roles{$role}));
 5463: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5464:                 my $active=1;
 5465:                 if ($starttime) {
 5466: 		    if ($now<$starttime) { $active=0; }
 5467:                 }
 5468:                 if ($endtime) {
 5469:                     if ($now>$endtime) { $active=0; }
 5470:                 }
 5471:                 if ($active) {
 5472:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5473:                     if ($sec eq '') {
 5474:                         $sec = 'none';
 5475:                     } else {
 5476:                         $value .= $sec;
 5477:                     }
 5478:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5479:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5480:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5481:                         }
 5482:                     } else {
 5483:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5484:                     }
 5485:                 }
 5486:             }
 5487:         }
 5488:     }
 5489:     return %courses;
 5490: }
 5491: 
 5492: ###############################################
 5493: 
 5494: sub blockcheck {
 5495:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5496:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 5497:         my ($has_evb,$check_ipaccess);
 5498:         my $dom = $env{'user.domain'};
 5499:         if ($env{'request.course.id'}) {
 5500:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5501:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5502:             my $checkrole = "cm./$cdom/$cnum";
 5503:             my $sec = $env{'request.course.sec'};
 5504:             if ($sec ne '') {
 5505:                 $checkrole .= "/$sec";
 5506:             }
 5507:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 5508:                 ($env{'request.role'} !~ /^st/)) {
 5509:                 $has_evb = 1;
 5510:             }
 5511:             unless ($has_evb) {
 5512:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 5513:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 5514:                     if ($udom eq $cdom) {
 5515:                         $check_ipaccess = 1;
 5516:                     }
 5517:                 }
 5518:             }
 5519:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 5520:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 5521:             my $checkrole;
 5522:             if ($env{'request.role.domain'} eq '') {
 5523:                 $checkrole = "cm./$env{'user.domain'}/";
 5524:             } else {
 5525:                 $checkrole = "cm./$env{'request.role.domain'}/";
 5526:             }
 5527:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 5528:                 $has_evb = 1;
 5529:             }
 5530:         }
 5531:         unless ($has_evb || $check_ipaccess) {
 5532:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 5533:             if (($dom eq 'public') && ($activity eq 'port')) {
 5534:                 $dom = $udom;
 5535:             }
 5536:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 5537:                 $check_ipaccess = 1;
 5538:             } else {
 5539:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 5540:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 5541:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 5542:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 5543:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 5544:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 5545:                         $check_ipaccess = 1;
 5546:                     }
 5547:                 }
 5548:             }
 5549:         }
 5550:         if ($check_ipaccess) {
 5551:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 5552:             unless (defined($cached)) {
 5553:                 my %domconfig =
 5554:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 5555:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 5556:             }
 5557:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 5558:                 foreach my $id (keys(%{$ipaccessref})) {
 5559:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 5560:                         my $range = $ipaccessref->{$id}->{'ip'};
 5561:                         if ($range) {
 5562:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 5563:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 5564:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 5565:                                         return ('','','',$id,$dom);
 5566:                                         last;
 5567:                                     }
 5568:                                 }
 5569:                             }
 5570:                         }
 5571:                     }
 5572:                 }
 5573:             }
 5574:         }
 5575:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5576:             return ();
 5577:         }
 5578:     }
 5579:     if (defined($udom) && defined($uname)) {
 5580:         # If uname and udom are for a course, check for blocks in the course.
 5581:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5582:             my ($startblock,$endblock,$triggerblock) =
 5583:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5584:             return ($startblock,$endblock,$triggerblock);
 5585:         }
 5586:     } else {
 5587:         $udom = $env{'user.domain'};
 5588:         $uname = $env{'user.name'};
 5589:     }
 5590: 
 5591:     my $startblock = 0;
 5592:     my $endblock = 0;
 5593:     my $triggerblock = '';
 5594:     my %live_courses;
 5595:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5596:         %live_courses = &findallcourses(undef,$uname,$udom);
 5597:     }
 5598: 
 5599:     # If uname is for a user, and activity is course-specific, i.e.,
 5600:     # boards, chat or groups, check for blocking in current course only.
 5601: 
 5602:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5603:          $activity eq 'groups' || $activity eq 'printout' ||
 5604:          $activity eq 'search' || $activity eq 'reinit' ||
 5605:          $activity eq 'alert') &&
 5606:         ($env{'request.course.id'})) {
 5607:         foreach my $key (keys(%live_courses)) {
 5608:             if ($key ne $env{'request.course.id'}) {
 5609:                 delete($live_courses{$key});
 5610:             }
 5611:         }
 5612:     }
 5613: 
 5614:     my $otheruser = 0;
 5615:     my %own_courses;
 5616:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5617:         # Resource belongs to user other than current user.
 5618:         $otheruser = 1;
 5619:         # Gather courses for current user
 5620:         %own_courses = 
 5621:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5622:     }
 5623: 
 5624:     # Gather active course roles - course coordinator, instructor, 
 5625:     # exam proctor, ta, student, or custom role.
 5626: 
 5627:     foreach my $course (keys(%live_courses)) {
 5628:         my ($cdom,$cnum);
 5629:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5630:             $cdom = $env{'course.'.$course.'.domain'};
 5631:             $cnum = $env{'course.'.$course.'.num'};
 5632:         } else {
 5633:             ($cdom,$cnum) = split(/_/,$course); 
 5634:         }
 5635:         my $no_ownblock = 0;
 5636:         my $no_userblock = 0;
 5637:         if ($otheruser && $activity ne 'com') {
 5638:             # Check if current user has 'evb' priv for this
 5639:             if (defined($own_courses{$course})) {
 5640:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5641:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5642:                     if ($sec ne 'none') {
 5643:                         $checkrole .= '/'.$sec;
 5644:                     }
 5645:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5646:                         $no_ownblock = 1;
 5647:                         last;
 5648:                     }
 5649:                 }
 5650:             }
 5651:             # if they have 'evb' priv and are currently not playing student
 5652:             next if (($no_ownblock) &&
 5653:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5654:         }
 5655:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5656:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5657:             if ($sec ne 'none') {
 5658:                 $checkrole .= '/'.$sec;
 5659:             }
 5660:             if ($otheruser) {
 5661:                 # Resource belongs to user other than current user.
 5662:                 # Assemble privs for that user, and check for 'evb' priv.
 5663:                 my (%allroles,%userroles);
 5664:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5665:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5666:                         my ($trole,$tdom,$tnum,$tsec);
 5667:                         if ($entry =~ /^cr/) {
 5668:                             ($trole,$tdom,$tnum,$tsec) = 
 5669:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5670:                         } else {
 5671:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5672:                         }
 5673:                         my ($spec,$area,$trest);
 5674:                         $area = '/'.$tdom.'/'.$tnum;
 5675:                         $trest = $tnum;
 5676:                         if ($tsec ne '') {
 5677:                             $area .= '/'.$tsec;
 5678:                             $trest .= '/'.$tsec;
 5679:                         }
 5680:                         $spec = $trole.'.'.$area;
 5681:                         if ($trole =~ /^cr/) {
 5682:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5683:                                                               $tdom,$spec,$trest,$area);
 5684:                         } else {
 5685:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5686:                                                                 $tdom,$spec,$trest,$area);
 5687:                         }
 5688:                     }
 5689:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5690:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5691:                         if ($1) {
 5692:                             $no_userblock = 1;
 5693:                             last;
 5694:                         }
 5695:                     }
 5696:                 }
 5697:             } else {
 5698:                 # Resource belongs to current user
 5699:                 # Check for 'evb' priv via lonnet::allowed().
 5700:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5701:                     $no_ownblock = 1;
 5702:                     last;
 5703:                 }
 5704:             }
 5705:         }
 5706:         # if they have the evb priv and are currently not playing student
 5707:         next if (($no_ownblock) &&
 5708:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5709:         next if ($no_userblock);
 5710: 
 5711:         # Retrieve blocking times and identity of blocker for course
 5712:         # of specified user, unless user has 'evb' privilege.
 5713: 
 5714:         my ($start,$end,$trigger) = 
 5715:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5716:         if (($start != 0) && 
 5717:             (($startblock == 0) || ($startblock > $start))) {
 5718:             $startblock = $start;
 5719:             if ($trigger ne '') {
 5720:                 $triggerblock = $trigger;
 5721:             }
 5722:         }
 5723:         if (($end != 0)  &&
 5724:             (($endblock == 0) || ($endblock < $end))) {
 5725:             $endblock = $end;
 5726:             if ($trigger ne '') {
 5727:                 $triggerblock = $trigger;
 5728:             }
 5729:         }
 5730:     }
 5731:     return ($startblock,$endblock,$triggerblock);
 5732: }
 5733: 
 5734: sub get_blocks {
 5735:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5736:     my $startblock = 0;
 5737:     my $endblock = 0;
 5738:     my $triggerblock = '';
 5739:     my $course = $cdom.'_'.$cnum;
 5740:     $setters->{$course} = {};
 5741:     $setters->{$course}{'staff'} = [];
 5742:     $setters->{$course}{'times'} = [];
 5743:     $setters->{$course}{'triggers'} = [];
 5744:     my (@blockers,%triggered);
 5745:     my $now = time;
 5746:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5747:     if ($activity eq 'docs') {
 5748:         my ($blocked,$nosymbcache,$noenccheck);
 5749:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5750:             $blocked = 1;
 5751:             $nosymbcache = 1;
 5752:             $noenccheck = 1;
 5753:         }
 5754:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5755:         foreach my $block (@blockers) {
 5756:             if ($block =~ /^firstaccess____(.+)$/) {
 5757:                 my $item = $1;
 5758:                 my $type = 'map';
 5759:                 my $timersymb = $item;
 5760:                 if ($item eq 'course') {
 5761:                     $type = 'course';
 5762:                 } elsif ($item =~ /___\d+___/) {
 5763:                     $type = 'resource';
 5764:                 } else {
 5765:                     $timersymb = &Apache::lonnet::symbread($item);
 5766:                 }
 5767:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5768:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5769:                 $triggered{$block} = {
 5770:                                        start => $start,
 5771:                                        end   => $end,
 5772:                                        type  => $type,
 5773:                                      };
 5774:             }
 5775:         }
 5776:     } else {
 5777:         foreach my $block (keys(%commblocks)) {
 5778:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5779:                 my ($start,$end) = ($1,$2);
 5780:                 if ($start <= time && $end >= time) {
 5781:                     if (ref($commblocks{$block}) eq 'HASH') {
 5782:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5783:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5784:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5785:                                     push(@blockers,$block);
 5786:                                 }
 5787:                             }
 5788:                         }
 5789:                     }
 5790:                 }
 5791:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5792:                 my $item = $1;
 5793:                 my $timersymb = $item; 
 5794:                 my $type = 'map';
 5795:                 if ($item eq 'course') {
 5796:                     $type = 'course';
 5797:                 } elsif ($item =~ /___\d+___/) {
 5798:                     $type = 'resource';
 5799:                 } else {
 5800:                     $timersymb = &Apache::lonnet::symbread($item);
 5801:                 }
 5802:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5803:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5804:                 if ($start && $end) {
 5805:                     if (($start <= time) && ($end >= time)) {
 5806:                         if (ref($commblocks{$block}) eq 'HASH') {
 5807:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5808:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5809:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5810:                                         push(@blockers,$block);
 5811:                                         $triggered{$block} = {
 5812:                                                                start => $start,
 5813:                                                                end   => $end,
 5814:                                                                type  => $type,
 5815:                                                              };
 5816:                                     }
 5817:                                 }
 5818:                             }
 5819:                         }
 5820:                     }
 5821:                 }
 5822:             }
 5823:         }
 5824:     }
 5825:     foreach my $blocker (@blockers) {
 5826:         my ($staff_name,$staff_dom,$title,$blocks) =
 5827:             &parse_block_record($commblocks{$blocker});
 5828:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5829:         my ($start,$end,$triggertype);
 5830:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5831:             ($start,$end) = ($1,$2);
 5832:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5833:             $start = $triggered{$blocker}{'start'};
 5834:             $end = $triggered{$blocker}{'end'};
 5835:             $triggertype = $triggered{$blocker}{'type'};
 5836:         }
 5837:         if ($start) {
 5838:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5839:             if ($triggertype) {
 5840:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5841:             } else {
 5842:                 push(@{$$setters{$course}{'triggers'}},0);
 5843:             }
 5844:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5845:                 $startblock = $start;
 5846:                 if ($triggertype) {
 5847:                     $triggerblock = $blocker;
 5848:                 }
 5849:             }
 5850:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5851:                $endblock = $end;
 5852:                if ($triggertype) {
 5853:                    $triggerblock = $blocker;
 5854:                }
 5855:             }
 5856:         }
 5857:     }
 5858:     return ($startblock,$endblock,$triggerblock);
 5859: }
 5860: 
 5861: sub parse_block_record {
 5862:     my ($record) = @_;
 5863:     my ($setuname,$setudom,$title,$blocks);
 5864:     if (ref($record) eq 'HASH') {
 5865:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5866:         $title = &unescape($record->{'event'});
 5867:         $blocks = $record->{'blocks'};
 5868:     } else {
 5869:         my @data = split(/:/,$record,3);
 5870:         if (scalar(@data) eq 2) {
 5871:             $title = $data[1];
 5872:             ($setuname,$setudom) = split(/@/,$data[0]);
 5873:         } else {
 5874:             ($setuname,$setudom,$title) = @data;
 5875:         }
 5876:         $blocks = { 'com' => 'on' };
 5877:     }
 5878:     return ($setuname,$setudom,$title,$blocks);
 5879: }
 5880: 
 5881: sub blocking_status {
 5882:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5883:     my %setters;
 5884: 
 5885: # check for active blocking
 5886:     if ($clientip eq '') {
 5887:         $clientip = &Apache::lonnet::get_requestor_ip();
 5888:     }
 5889:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5890:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5891:     my $blocked = 0;
 5892:     if (($startblock && $endblock) || ($by_ip)) {
 5893:         $blocked = 1;
 5894:     }
 5895: 
 5896: # caller just wants to know whether a block is active
 5897:     if (!wantarray) { return $blocked; }
 5898: 
 5899: # build a link to a popup window containing the details
 5900:     my $querystring  = "?activity=$activity";
 5901: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5902:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5903:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5904:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5905:     } elsif ($activity eq 'docs') {
 5906:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5907:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5908:         if ($symb) {
 5909:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5910:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5911:         }
 5912:     }
 5913: 
 5914:     my $output .= <<'END_MYBLOCK';
 5915: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5916:     var options = "width=" + w + ",height=" + h + ",";
 5917:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5918:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5919:     var newWin = window.open(url, wdwName, options);
 5920:     newWin.focus();
 5921: }
 5922: END_MYBLOCK
 5923: 
 5924:     $output = Apache::lonhtmlcommon::scripttag($output);
 5925:   
 5926:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5927:     my $text = &mt('Communication Blocked');
 5928:     my $class = 'LC_comblock';
 5929:     if ($activity eq 'docs') {
 5930:         $text = &mt('Content Access Blocked');
 5931:         $class = '';
 5932:     } elsif ($activity eq 'printout') {
 5933:         $text = &mt('Printing Blocked');
 5934:     } elsif ($activity eq 'passwd') {
 5935:         $text = &mt('Password Changing Blocked');
 5936:     } elsif ($activity eq 'grades') {
 5937:         $text = &mt('Gradebook Blocked');
 5938:     } elsif ($activity eq 'search') {
 5939:         $text = &mt('Search Blocked');
 5940:     } elsif ($activity eq 'alert') {
 5941:         $text = &mt('Checking Critical Messages Blocked');
 5942:     } elsif ($activity eq 'reinit') {
 5943:         $text = &mt('Checking Course Update Blocked');
 5944:     } elsif ($activity eq 'about') {
 5945:         $text = &mt('Access to User Information Pages Blocked');
 5946:     } elsif ($activity eq 'wishlist') {
 5947:         $text = &mt('Access to Stored Links Blocked');
 5948:     } elsif ($activity eq 'annotate') {
 5949:         $text = &mt('Access to Annotations Blocked');
 5950:     }
 5951:     $output .= <<"END_BLOCK";
 5952: <div class='$class'>
 5953:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5954:   title='$text'>
 5955:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5956:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5957:   title='$text'>$text</a>
 5958: </div>
 5959: 
 5960: END_BLOCK
 5961: 
 5962:     return ($blocked, $output);
 5963: }
 5964: 
 5965: ###############################################
 5966: 
 5967: sub check_ip_acc {
 5968:     my ($acc,$clientip)=@_;
 5969:     &Apache::lonxml::debug("acc is $acc");
 5970:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5971:         return 1;
 5972:     }
 5973:     my ($ip,$allowed);
 5974:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5975:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5976:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5977:     } else {
 5978:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5979:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5980:     }
 5981: 
 5982:     my $name;
 5983:     my %access = (
 5984:                      allowfrom => 1,
 5985:                      denyfrom  => 0,
 5986:                  );
 5987:     my @allows;
 5988:     my @denies;
 5989:     foreach my $item (split(',',$acc)) {
 5990:         $item =~ s/^\s*//;
 5991:         $item =~ s/\s*$//;
 5992:         my $pattern;
 5993:         if ($item =~ /^\!(.+)$/) {
 5994:             push(@denies,$1);
 5995:         } else {
 5996:             push(@allows,$item);
 5997:         }
 5998:    }
 5999:    my $numdenies = scalar(@denies);
 6000:    my $numallows = scalar(@allows);
 6001:    my $count = 0;
 6002:    foreach my $pattern (@denies,@allows) {
 6003:         $count ++; 
 6004:         my $acctype = 'allowfrom';
 6005:         if ($count <= $numdenies) {
 6006:             $acctype = 'denyfrom';
 6007:         }
 6008:         if ($pattern =~ /\*$/) {
 6009:             #35.8.*
 6010:             $pattern=~s/\*//;
 6011:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6012:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 6013:             #35.8.3.[34-56]
 6014:             my $low=$2;
 6015:             my $high=$3;
 6016:             $pattern=$1;
 6017:             if ($ip =~ /^\Q$pattern\E/) {
 6018:                 my $last=(split(/\./,$ip))[3];
 6019:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 6020:             }
 6021:         } elsif ($pattern =~ /^\*/) {
 6022:             #*.msu.edu
 6023:             $pattern=~s/\*//;
 6024:             if (!defined($name)) {
 6025:                 use Socket;
 6026:                 my $netaddr=inet_aton($ip);
 6027:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6028:             }
 6029:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6030:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 6031:             #127.0.0.1
 6032:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6033:         } else {
 6034:             #some.name.com
 6035:             if (!defined($name)) {
 6036:                 use Socket;
 6037:                 my $netaddr=inet_aton($ip);
 6038:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6039:             }
 6040:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6041:         }
 6042:         if ($allowed =~ /^(0|1)$/) { last; }
 6043:     }
 6044:     if ($allowed eq '') {
 6045:         if ($numdenies && !$numallows) {
 6046:             $allowed = 1;
 6047:         } else {
 6048:             $allowed = 0;
 6049:         }
 6050:     }
 6051:     return $allowed;
 6052: }
 6053: 
 6054: ###############################################
 6055: 
 6056: =pod
 6057: 
 6058: =head1 Domain Template Functions
 6059: 
 6060: =over 4
 6061: 
 6062: =item * &determinedomain()
 6063: 
 6064: Inputs: $domain (usually will be undef)
 6065: 
 6066: Returns: Determines which domain should be used for designs
 6067: 
 6068: =cut
 6069: 
 6070: ###############################################
 6071: sub determinedomain {
 6072:     my $domain=shift;
 6073:     if (! $domain) {
 6074:         # Determine domain if we have not been given one
 6075:         $domain = &Apache::lonnet::default_login_domain();
 6076:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 6077:         if ($env{'request.role.domain'}) { 
 6078:             $domain=$env{'request.role.domain'}; 
 6079:         }
 6080:     }
 6081:     return $domain;
 6082: }
 6083: ###############################################
 6084: 
 6085: sub devalidate_domconfig_cache {
 6086:     my ($udom)=@_;
 6087:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 6088: }
 6089: 
 6090: # ---------------------- Get domain configuration for a domain
 6091: sub get_domainconf {
 6092:     my ($udom) = @_;
 6093:     my $cachetime=1800;
 6094:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 6095:     if (defined($cached)) { return %{$result}; }
 6096: 
 6097:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 6098: 					     ['login','rolecolors','autoenroll'],$udom);
 6099:     my (%designhash,%legacy);
 6100:     if (keys(%domconfig) > 0) {
 6101:         if (ref($domconfig{'login'}) eq 'HASH') {
 6102:             if (keys(%{$domconfig{'login'}})) {
 6103:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 6104:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6105:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 6106:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6107:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 6108:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 6109:                                         if ($key eq 'loginvia') {
 6110:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 6111:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 6112:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 6113:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 6114: 
 6115:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 6116:                                                 } else {
 6117:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 6118:                                                 }
 6119:                                             }
 6120:                                         } elsif ($key eq 'headtag') {
 6121:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 6122:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 6123:                                             }
 6124:                                         }
 6125:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 6126:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 6127:                                         }
 6128:                                     }
 6129:                                 }
 6130:                             }
 6131:                         } elsif ($key eq 'saml') {
 6132:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6133:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 6134:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 6135:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 6136:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 6137:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 6138:                                         }
 6139:                                     }
 6140:                                 }
 6141:                             }
 6142:                         } else {
 6143:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 6144:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 6145:                                     $domconfig{'login'}{$key}{$img};
 6146:                             }
 6147:                         }
 6148:                     } else {
 6149:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 6150:                     }
 6151:                 }
 6152:             } else {
 6153:                 $legacy{'login'} = 1;
 6154:             }
 6155:         } else {
 6156:             $legacy{'login'} = 1;
 6157:         }
 6158:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 6159:             if (keys(%{$domconfig{'rolecolors'}})) {
 6160:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 6161:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 6162:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 6163:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 6164:                         }
 6165:                     }
 6166:                 }
 6167:             } else {
 6168:                 $legacy{'rolecolors'} = 1;
 6169:             }
 6170:         } else {
 6171:             $legacy{'rolecolors'} = 1;
 6172:         }
 6173:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6174:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 6175:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 6176:             }
 6177:         }
 6178:         if (keys(%legacy) > 0) {
 6179:             my %legacyhash = &get_legacy_domconf($udom);
 6180:             foreach my $item (keys(%legacyhash)) {
 6181:                 if ($item =~ /^\Q$udom\E\.login/) {
 6182:                     if ($legacy{'login'}) { 
 6183:                         $designhash{$item} = $legacyhash{$item};
 6184:                     }
 6185:                 } else {
 6186:                     if ($legacy{'rolecolors'}) {
 6187:                         $designhash{$item} = $legacyhash{$item};
 6188:                     }
 6189:                 }
 6190:             }
 6191:         }
 6192:     } else {
 6193:         %designhash = &get_legacy_domconf($udom); 
 6194:     }
 6195:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 6196: 				  $cachetime);
 6197:     return %designhash;
 6198: }
 6199: 
 6200: sub get_legacy_domconf {
 6201:     my ($udom) = @_;
 6202:     my %legacyhash;
 6203:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 6204:     my $designfile =  $designdir.'/'.$udom.'.tab';
 6205:     if (-e $designfile) {
 6206:         if ( open (my $fh,'<',$designfile) ) {
 6207:             while (my $line = <$fh>) {
 6208:                 next if ($line =~ /^\#/);
 6209:                 chomp($line);
 6210:                 my ($key,$val)=(split(/\=/,$line));
 6211:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 6212:             }
 6213:             close($fh);
 6214:         }
 6215:     }
 6216:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 6217:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 6218:     }
 6219:     return %legacyhash;
 6220: }
 6221: 
 6222: =pod
 6223: 
 6224: =item * &domainlogo()
 6225: 
 6226: Inputs: $domain (usually will be undef)
 6227: 
 6228: Returns: A link to a domain logo, if the domain logo exists.
 6229: If the domain logo does not exist, a description of the domain.
 6230: 
 6231: =cut
 6232: 
 6233: ###############################################
 6234: sub domainlogo {
 6235:     my $domain = &determinedomain(shift);
 6236:     my %designhash = &get_domainconf($domain);    
 6237:     # See if there is a logo
 6238:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 6239:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 6240:         if ($imgsrc =~ m{^/(adm|res)/}) {
 6241: 	    if ($imgsrc =~ m{^/res/}) {
 6242: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 6243: 		&Apache::lonnet::repcopy($local_name);
 6244: 	    }
 6245: 	   $imgsrc = &lonhttpdurl($imgsrc);
 6246:         }
 6247:         my $alttext = $domain;
 6248:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 6249:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 6250:         }
 6251:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 6252:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 6253:         return &Apache::lonnet::domain($domain,'description');
 6254:     } else {
 6255:         return '';
 6256:     }
 6257: }
 6258: ##############################################
 6259: 
 6260: =pod
 6261: 
 6262: =item * &designparm()
 6263: 
 6264: Inputs: $which parameter; $domain (usually will be undef)
 6265: 
 6266: Returns: value of designparamter $which
 6267: 
 6268: =cut
 6269: 
 6270: 
 6271: ##############################################
 6272: sub designparm {
 6273:     my ($which,$domain)=@_;
 6274:     if (exists($env{'environment.color.'.$which})) {
 6275:         return $env{'environment.color.'.$which};
 6276:     }
 6277:     $domain=&determinedomain($domain);
 6278:     my %domdesign;
 6279:     unless ($domain eq 'public') {
 6280:         %domdesign = &get_domainconf($domain);
 6281:     }
 6282:     my $output;
 6283:     if ($domdesign{$domain.'.'.$which} ne '') {
 6284:         $output = $domdesign{$domain.'.'.$which};
 6285:     } else {
 6286:         $output = $defaultdesign{$which};
 6287:     }
 6288:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 6289:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 6290:         if ($output =~ m{^/(adm|res)/}) {
 6291:             if ($output =~ m{^/res/}) {
 6292:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 6293:                 &Apache::lonnet::repcopy($local_name);
 6294:             }
 6295:             $output = &lonhttpdurl($output);
 6296:         }
 6297:     }
 6298:     return $output;
 6299: }
 6300: 
 6301: ##############################################
 6302: =pod
 6303: 
 6304: =item * &authorspace()
 6305: 
 6306: Inputs: $url (usually will be undef).
 6307: 
 6308: Returns: Path to Authoring Space containing the resource or 
 6309:          directory being viewed (or for which action is being taken). 
 6310:          If $url is provided, and begins /priv/<domain>/<uname>
 6311:          the path will be that portion of the $context argument.
 6312:          Otherwise the path will be for the author space of the current
 6313:          user when the current role is author, or for that of the 
 6314:          co-author/assistant co-author space when the current role 
 6315:          is co-author or assistant co-author.
 6316: 
 6317: =cut
 6318: 
 6319: sub authorspace {
 6320:     my ($url) = @_;
 6321:     if ($url ne '') {
 6322:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 6323:            return $1;
 6324:         }
 6325:     }
 6326:     my $caname = '';
 6327:     my $cadom = '';
 6328:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 6329:         ($cadom,$caname) =
 6330:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 6331:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 6332:         $caname = $env{'user.name'};
 6333:         $cadom = $env{'user.domain'};
 6334:     }
 6335:     if (($caname ne '') && ($cadom ne '')) {
 6336:         return "/priv/$cadom/$caname/";
 6337:     }
 6338:     return;
 6339: }
 6340: 
 6341: ##############################################
 6342: =pod
 6343: 
 6344: =item * &head_subbox()
 6345: 
 6346: Inputs: $content (contains HTML code with page functions, etc.)
 6347: 
 6348: Returns: HTML div with $content
 6349:          To be included in page header
 6350: 
 6351: =cut
 6352: 
 6353: sub head_subbox {
 6354:     my ($content)=@_;
 6355:     my $output =
 6356:         '<div class="LC_head_subbox">'
 6357:        .$content
 6358:        .'</div>'
 6359: }
 6360: 
 6361: ##############################################
 6362: =pod
 6363: 
 6364: =item * &CSTR_pageheader()
 6365: 
 6366: Input: (optional) filename from which breadcrumb trail is built.
 6367:        In most cases no input as needed, as $env{'request.filename'}
 6368:        is appropriate for use in building the breadcrumb trail.
 6369:        frameset flag
 6370:        If page header is being requested for use in a frameset, then
 6371:        the second (option) argument -- frameset will be true, and
 6372:        the target attribute set for links should be target="_parent".
 6373:        If $title is supplied as the thitd arg, that will be used to 
 6374:        the left of the breadcrumbs tail for the current path.
 6375: 
 6376: Returns: HTML div with CSTR path and recent box
 6377:          To be included on Authoring Space pages
 6378: 
 6379: =cut
 6380: 
 6381: sub CSTR_pageheader {
 6382:     my ($trailfile,$frameset,$title) = @_;
 6383:     if ($trailfile eq '') {
 6384:         $trailfile = $env{'request.filename'};
 6385:     }
 6386: 
 6387: # this is for resources; directories have customtitle, and crumbs
 6388: # and select recent are created in lonpubdir.pm
 6389: 
 6390:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 6391:     my ($udom,$uname,$thisdisfn)=
 6392:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 6393:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 6394:     $formaction =~ s{/+}{/}g;
 6395: 
 6396:     my $parentpath = '';
 6397:     my $lastitem = '';
 6398:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 6399:         $parentpath = $1;
 6400:         $lastitem = $2;
 6401:     } else {
 6402:         $lastitem = $thisdisfn;
 6403:     }
 6404: 
 6405:     my $crsauthor;
 6406:     if (($env{'request.course.id'}) &&
 6407:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 6408:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 6409:         $crsauthor = 1;
 6410:         if ($title eq '') {
 6411:             $title = &mt('Course Authoring Space');
 6412:         }
 6413:     } elsif ($title eq '') {
 6414:         $title = &mt('Authoring Space');
 6415:     }
 6416: 
 6417:     my ($target,$crumbtarget) = (' target="_top"','_top');
 6418:     if ($frameset) {
 6419:         $target = ' target="_parent"';
 6420:         $crumbtarget = '_parent';
 6421:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 6422:         $target = '';
 6423:         $crumbtarget = '';
 6424:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 6425:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 6426:         $crumbtarget = $env{'request.deeplink.target'};
 6427:     }
 6428: 
 6429:     my $output =
 6430:          '<div>'
 6431:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 6432:         .'<b>'.$title.'</b> '
 6433:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 6434:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 6435: 
 6436:     if ($lastitem) {
 6437:         $output .=
 6438:              '<span class="LC_filename">'
 6439:             .$lastitem
 6440:             .'</span>';
 6441:     }
 6442: 
 6443:     if ($crsauthor) {
 6444:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
 6445:     } else {
 6446:         $output .=
 6447:              '<br />'
 6448:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 6449:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 6450:             .'</form>'
 6451:             .&Apache::lonmenu::constspaceform($frameset);
 6452:     }
 6453:     $output .= '</div>';
 6454: 
 6455:     return $output;
 6456: }
 6457: 
 6458: ###############################################
 6459: ###############################################
 6460: 
 6461: =pod
 6462: 
 6463: =back
 6464: 
 6465: =head1 HTML Helpers
 6466: 
 6467: =over 4
 6468: 
 6469: =item * &bodytag()
 6470: 
 6471: Returns a uniform header for LON-CAPA web pages.
 6472: 
 6473: Inputs: 
 6474: 
 6475: =over 4
 6476: 
 6477: =item * $title, A title to be displayed on the page.
 6478: 
 6479: =item * $function, the current role (can be undef).
 6480: 
 6481: =item * $addentries, extra parameters for the <body> tag.
 6482: 
 6483: =item * $bodyonly, if defined, only return the <body> tag.
 6484: 
 6485: =item * $domain, if defined, force a given domain.
 6486: 
 6487: =item * $forcereg, if page should register as content page (relevant for 
 6488:             text interface only)
 6489: 
 6490: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6491:                      navigational links
 6492: 
 6493: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6494: 
 6495: =item * $args, optional argument valid values are
 6496:             no_auto_mt_title -> prevents &mt()ing the title arg
 6497:             use_absolute     -> for external resource or syllabus, this will
 6498:                                 contain https://<hostname> if server uses
 6499:                                 https (as per hosts.tab), but request is for http
 6500:             hostname         -> hostname, from $r->hostname().
 6501: 
 6502: =item * $advtoolsref, optional argument, ref to an array containing
 6503:             inlineremote items to be added in "Functions" menu below
 6504:             breadcrumbs.
 6505: 
 6506: =item * $ltiscope, optional argument, will be one of: resource, map or
 6507:             course, if LON-CAPA is in LTI Provider context. Value is
 6508:             the scope of use, i.e., launch was for access to a single, a map
 6509:             or the entire course.
 6510: 
 6511: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6512:             context, this will contain the URL for the landing item in
 6513:             the course, after launch from an LTI Consumer
 6514: 
 6515: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6516:             context, this will contain a reference to hash of items
 6517:             to be included in the page header and/or inline menu.
 6518: 
 6519: =item * $menucoll, optional argument, if specific menu collection is in
 6520:             effect, either set as the default for the course, or set for
 6521:             the deeplink paramater for $env{'request.deeplink.login'}
 6522:             then $menucoll will be the number of that collection. 
 6523: 
 6524: =item * $menuref, optional argument, reference to a hash, containing the
 6525:             menu options included for the menu in effect, based on the
 6526:             configuration for the numbered menu collection in use.  
 6527: 
 6528: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 6529:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 6530:             if so, $showncrumbsref is set there to 1, and will propagate back
 6531:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 6532:             being called a second time.
 6533: 
 6534: =back
 6535: 
 6536: Returns: A uniform header for LON-CAPA web pages.  
 6537: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6538: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6539: other decorations will be returned.
 6540: 
 6541: =cut
 6542: 
 6543: sub bodytag {
 6544:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6545:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
 6546:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 6547: 
 6548:     my $public;
 6549:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6550:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6551:         $public = 1;
 6552:     }
 6553:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6554:     my $httphost = $args->{'use_absolute'};
 6555:     my $hostname = $args->{'hostname'};
 6556: 
 6557:     $function = &get_users_function() if (!$function);
 6558:     my $img =    &designparm($function.'.img',$domain);
 6559:     my $font =   &designparm($function.'.font',$domain);
 6560:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6561: 
 6562:     my %design = ( 'style'   => 'margin-top: 0',
 6563: 		   'bgcolor' => $pgbg,
 6564: 		   'text'    => $font,
 6565:                    'alink'   => &designparm($function.'.alink',$domain),
 6566: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6567: 		   'link'    => &designparm($function.'.link',$domain),);
 6568:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6569: 
 6570:  # role and realm
 6571:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6572:     if ($realm) {
 6573:         $realm = '/'.$realm;
 6574:     }
 6575:     if ($role eq 'ca') {
 6576:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6577:         $realm = &plainname($rname,$rdom);
 6578:     } 
 6579: # realm
 6580:     my ($cid,$sec);
 6581:     if ($env{'request.course.id'}) {
 6582:         $cid = $env{'request.course.id'};
 6583:         if ($env{'request.course.sec'}) {
 6584:             $sec = $env{'request.course.sec'};
 6585:         }
 6586:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 6587:         if (&Apache::lonnet::is_course($1,$2)) {
 6588:             $cid = $1.'_'.$2;
 6589:             $sec = $3;
 6590:         }
 6591:     }
 6592:     if ($cid) {
 6593:         if ($env{'request.role'} !~ /^cr/) {
 6594:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6595:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6596:             if ($env{'request.role.desc'}) {
 6597:                 $role = $env{'request.role.desc'};
 6598:             } else {
 6599:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6600:             }
 6601:         } else {
 6602:             $role = (split(/\//,$role,4))[-1]; 
 6603:         }
 6604:         if ($sec) {
 6605:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6606:         }   
 6607: 	$realm = $env{'course.'.$cid.'.description'};
 6608:     } else {
 6609:         $role = &Apache::lonnet::plaintext($role);
 6610:     }
 6611: 
 6612:     if (!$realm) { $realm='&nbsp;'; }
 6613: 
 6614:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6615: 
 6616: # construct main body tag
 6617:     my $bodytag = "<body $extra_body_attr>".
 6618: 	&Apache::lontexconvert::init_math_support();
 6619: 
 6620:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6621: 
 6622:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6623:         return $bodytag;
 6624:     }
 6625: 
 6626:     if ($public) {
 6627: 	undef($role);
 6628:     }
 6629: 
 6630:     my $showcrstitle = 1;
 6631:     if (($cid) && ($env{'request.lti.login'})) {
 6632:         if (ref($ltimenu) eq 'HASH') {
 6633:             unless ($ltimenu->{'role'}) {
 6634:                 undef($role);
 6635:             }
 6636:             unless ($ltimenu->{'coursetitle'}) {
 6637:                 $realm='&nbsp;';
 6638:                 $showcrstitle = 0;
 6639:             }
 6640:         }
 6641:     } elsif (($cid) && ($menucoll)) {
 6642:         if (ref($menuref) eq 'HASH') {
 6643:             unless ($menuref->{'role'}) {
 6644:                 undef($role);
 6645:             }
 6646:             unless ($menuref->{'crs'}) {
 6647:                 $realm='&nbsp;';
 6648:                 $showcrstitle = 0;
 6649:             }
 6650:         }
 6651:     }
 6652: 
 6653:     my $titleinfo = '<h1>'.$title.'</h1>';
 6654:     #
 6655:     # Extra info if you are the DC
 6656:     my $dc_info = '';
 6657:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6658:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6659:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6660:         $dc_info =~ s/\s+$//;
 6661:     }
 6662: 
 6663:     my $crstype;
 6664:     if ($cid) {
 6665:         $crstype = $env{'course.'.$cid.'.type'};
 6666:     } elsif ($args->{'crstype'}) {
 6667:         $crstype = $args->{'crstype'};
 6668:     }
 6669:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6670:         undef($role);
 6671:     } else {
 6672:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6673:     }
 6674: 
 6675:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6676: 
 6677:         #    if ($env{'request.state'} eq 'construct') {
 6678:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6679:         #    }
 6680: 
 6681:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6682:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6683: 
 6684:         unless ($args->{'no_primary_menu'}) {
 6685:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6686:                                                               $args->{'links_disabled'},
 6687:                                                               $args->{'links_target'});
 6688: 
 6689:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6690:                 if ($dc_info) {
 6691:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6692:                 }
 6693:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6694:                                <em>$realm</em> $dc_info</div>|;
 6695:                 return $bodytag;
 6696:             }
 6697: 
 6698:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6699:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6700:             }
 6701: 
 6702:             $bodytag .= $right;
 6703: 
 6704:             if ($dc_info) {
 6705:                 $dc_info = &dc_courseid_toggle($dc_info);
 6706:             }
 6707:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6708:         }
 6709: 
 6710:         #if directed to not display the secondary menu, don't.  
 6711:         if ($args->{'no_secondary_menu'}) {
 6712:             return $bodytag;
 6713:         }
 6714:         #don't show menus for public users
 6715:         if (!$public){
 6716:             unless ($args->{'no_inline_menu'}) {
 6717:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6718:                                                             $args->{'no_primary_menu'},
 6719:                                                             $menucoll,$menuref,
 6720:                                                             $args->{'links_disabled'},
 6721:                                                             $args->{'links_target'});
 6722:             }
 6723:             $bodytag .= Apache::lonmenu::serverform();
 6724:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6725:             if ($env{'request.state'} eq 'construct') {
 6726:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6727:                                 $args->{'bread_crumbs'},'','',$hostname,
 6728:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6729:             } elsif ($forcereg) {
 6730:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6731:                                 $args->{'group'},$args->{'hide_buttons'},
 6732:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6733:             } else {
 6734:                 $bodytag .= 
 6735:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6736:                                                         $forcereg,$args->{'group'},
 6737:                                                         $args->{'bread_crumbs'},
 6738:                                                         $advtoolsref,'',$hostname);
 6739:             }
 6740:         }else{
 6741:             # this is to seperate menu from content when there's no secondary
 6742:             # menu. Especially needed for public accessible ressources.
 6743:             $bodytag .= '<hr style="clear:both" />';
 6744:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6745:         }
 6746: 
 6747:         return $bodytag;
 6748: }
 6749: 
 6750: sub dc_courseid_toggle {
 6751:     my ($dc_info) = @_;
 6752:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6753:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6754:            &mt('(More ...)').'</a></span>'.
 6755:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6756: }
 6757: 
 6758: sub make_attr_string {
 6759:     my ($register,$attr_ref) = @_;
 6760: 
 6761:     if ($attr_ref && !ref($attr_ref)) {
 6762: 	die("addentries Must be a hash ref ".
 6763: 	    join(':',caller(1))." ".
 6764: 	    join(':',caller(0))." ");
 6765:     }
 6766: 
 6767:     if ($register) {
 6768: 	my ($on_load,$on_unload);
 6769: 	foreach my $key (keys(%{$attr_ref})) {
 6770: 	    if      (lc($key) eq 'onload') {
 6771: 		$on_load.=$attr_ref->{$key}.';';
 6772: 		delete($attr_ref->{$key});
 6773: 
 6774: 	    } elsif (lc($key) eq 'onunload') {
 6775: 		$on_unload.=$attr_ref->{$key}.';';
 6776: 		delete($attr_ref->{$key});
 6777: 	    }
 6778: 	}
 6779: 	$attr_ref->{'onload'}  = $on_load;
 6780: 	$attr_ref->{'onunload'}= $on_unload;
 6781:     }
 6782: 
 6783:     my $attr_string;
 6784:     foreach my $attr (sort(keys(%$attr_ref))) {
 6785: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6786:     }
 6787:     return $attr_string;
 6788: }
 6789: 
 6790: 
 6791: ###############################################
 6792: ###############################################
 6793: 
 6794: =pod
 6795: 
 6796: =item * &endbodytag()
 6797: 
 6798: Returns a uniform footer for LON-CAPA web pages.
 6799: 
 6800: Inputs: 1 - optional reference to an args hash
 6801: If in the hash, key for noredirectlink has a value which evaluates to true,
 6802: a 'Continue' link is not displayed if the page contains an
 6803: internal redirect in the <head></head> section,
 6804: i.e., $env{'internal.head.redirect'} exists   
 6805: 
 6806: =cut
 6807: 
 6808: sub endbodytag {
 6809:     my ($args) = @_;
 6810:     my $endbodytag;
 6811:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6812:         $endbodytag='</body>';
 6813:     }
 6814:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6815:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6816:             my ($endbodyjs,$idattr);
 6817:             if ($env{'internal.head.to_opener'}) {
 6818:                 my $linkid = 'LC_continue_link';
 6819:                 $idattr = ' id="'.$linkid.'"';
 6820:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 6821:                 $endbodyjs=<<ENDJS;
 6822: <script type="text/javascript">
 6823: // <![CDATA[
 6824: function ebFunction(evt) {
 6825:     evt.preventDefault();
 6826:     var dest = '$redirect_for_js';
 6827:     if (window.opener != null && !window.opener.closed) {
 6828:         window.opener.location.href=dest;
 6829:         window.close();
 6830:     } else {
 6831:         window.location.href=dest;
 6832:     }
 6833:     return false;
 6834: }
 6835: 
 6836: \$(document).ready(function () {
 6837:   if (document.getElementById('$linkid')) {
 6838:     var clickelem = document.getElementById('$linkid');
 6839:     clickelem.addEventListener('click',ebFunction,false);
 6840:   }
 6841: });
 6842: // ]]>
 6843: </script>
 6844: ENDJS
 6845:             }
 6846: 	    $endbodytag=
 6847: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 6848: 	        &mt('Continue').'</a>'.
 6849: 	        $endbodytag;
 6850:         }
 6851:     }
 6852:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
 6853:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
 6854:     }
 6855:     return $endbodytag;
 6856: }
 6857: 
 6858: =pod
 6859: 
 6860: =item * &standard_css()
 6861: 
 6862: Returns a style sheet
 6863: 
 6864: Inputs: (all optional)
 6865:             domain         -> force to color decorate a page for a specific
 6866:                                domain
 6867:             function       -> force usage of a specific rolish color scheme
 6868:             bgcolor        -> override the default page bgcolor
 6869: 
 6870: =cut
 6871: 
 6872: sub standard_css {
 6873:     my ($function,$domain,$bgcolor) = @_;
 6874:     $function  = &get_users_function() if (!$function);
 6875:     my $img    = &designparm($function.'.img',   $domain);
 6876:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6877:     my $font   = &designparm($function.'.font',  $domain);
 6878:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6879: #second colour for later usage
 6880:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6881:     my $pgbg_or_bgcolor =
 6882: 	         $bgcolor ||
 6883: 	         &designparm($function.'.pgbg',  $domain);
 6884:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6885:     my $alink  = &designparm($function.'.alink', $domain);
 6886:     my $vlink  = &designparm($function.'.vlink', $domain);
 6887:     my $link   = &designparm($function.'.link',  $domain);
 6888: 
 6889:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6890:     my $mono                 = 'monospace';
 6891:     my $data_table_head      = $sidebg;
 6892:     my $data_table_light     = '#FAFAFA';
 6893:     my $data_table_dark      = '#E0E0E0';
 6894:     my $data_table_darker    = '#CCCCCC';
 6895:     my $data_table_highlight = '#FFFF00';
 6896:     my $mail_new             = '#FFBB77';
 6897:     my $mail_new_hover       = '#DD9955';
 6898:     my $mail_read            = '#BBBB77';
 6899:     my $mail_read_hover      = '#999944';
 6900:     my $mail_replied         = '#AAAA88';
 6901:     my $mail_replied_hover   = '#888855';
 6902:     my $mail_other           = '#99BBBB';
 6903:     my $mail_other_hover     = '#669999';
 6904:     my $table_header         = '#DDDDDD';
 6905:     my $feedback_link_bg     = '#BBBBBB';
 6906:     my $lg_border_color      = '#C8C8C8';
 6907:     my $button_hover         = '#BF2317';
 6908: 
 6909:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6910:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6911:                                              : '0 3px 0 4px';
 6912: 
 6913: 
 6914:     return <<END;
 6915: 
 6916: /* needed for iframe to allow 100% height in FF */
 6917: body, html { 
 6918:     margin: 0;
 6919:     padding: 0 0.5%;
 6920:     height: 99%; /* to avoid scrollbars */
 6921: }
 6922: 
 6923: body {
 6924:   font-family: $sans;
 6925:   line-height:130%;
 6926:   font-size:0.83em;
 6927:   color:$font;
 6928: }
 6929: 
 6930: a:focus,
 6931: a:focus img {
 6932:   color: red;
 6933: }
 6934: 
 6935: form, .inline {
 6936:   display: inline;
 6937: }
 6938: 
 6939: .LC_right {
 6940:   text-align:right;
 6941: }
 6942: 
 6943: .LC_middle {
 6944:   vertical-align:middle;
 6945: }
 6946: 
 6947: .LC_floatleft {
 6948:   float: left;
 6949: }
 6950: 
 6951: .LC_floatright {
 6952:   float: right;
 6953: }
 6954: 
 6955: .LC_400Box {
 6956:   width:400px;
 6957: }
 6958: 
 6959: .LC_iframecontainer {
 6960:     width: 98%;
 6961:     margin: 0;
 6962:     position: fixed;
 6963:     top: 8.5em;
 6964:     bottom: 0;
 6965: }
 6966: 
 6967: .LC_iframecontainer iframe{
 6968:     border: none;
 6969:     width: 100%;
 6970:     height: 100%;
 6971: }
 6972: 
 6973: .LC_filename {
 6974:   font-family: $mono;
 6975:   white-space:pre;
 6976:   font-size: 120%;
 6977: }
 6978: 
 6979: .LC_fileicon {
 6980:   border: none;
 6981:   height: 1.3em;
 6982:   vertical-align: text-bottom;
 6983:   margin-right: 0.3em;
 6984:   text-decoration:none;
 6985: }
 6986: 
 6987: .LC_setting {
 6988:   text-decoration:underline;
 6989: }
 6990: 
 6991: .LC_error {
 6992:   color: red;
 6993: }
 6994: 
 6995: .LC_warning {
 6996:   color: darkorange;
 6997: }
 6998: 
 6999: .LC_diff_removed {
 7000:   color: red;
 7001: }
 7002: 
 7003: .LC_info,
 7004: .LC_success,
 7005: .LC_diff_added {
 7006:   color: green;
 7007: }
 7008: 
 7009: div.LC_confirm_box {
 7010:   background-color: #FAFAFA;
 7011:   border: 1px solid $lg_border_color;
 7012:   margin-right: 0;
 7013:   padding: 5px;
 7014: }
 7015: 
 7016: div.LC_confirm_box .LC_error img,
 7017: div.LC_confirm_box .LC_success img {
 7018:   vertical-align: middle;
 7019: }
 7020: 
 7021: .LC_maxwidth {
 7022:   max-width: 100%;
 7023:   height: auto;
 7024: }
 7025: 
 7026: .LC_textsize_mobile {
 7027:   \@media only screen and (max-device-width: 480px) {
 7028:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 7029:   }
 7030: }
 7031: 
 7032: .LC_icon {
 7033:   border: none;
 7034:   vertical-align: middle;
 7035: }
 7036: 
 7037: .LC_docs_spacer {
 7038:   width: 25px;
 7039:   height: 1px;
 7040:   border: none;
 7041: }
 7042: 
 7043: .LC_internal_info {
 7044:   color: #999999;
 7045: }
 7046: 
 7047: .LC_discussion {
 7048:   background: $data_table_dark;
 7049:   border: 1px solid black;
 7050:   margin: 2px;
 7051: }
 7052: 
 7053: .LC_disc_action_left {
 7054:   background: $sidebg;
 7055:   text-align: left;
 7056:   padding: 4px;
 7057:   margin: 2px;
 7058: }
 7059: 
 7060: .LC_disc_action_right {
 7061:   background: $sidebg;
 7062:   text-align: right;
 7063:   padding: 4px;
 7064:   margin: 2px;
 7065: }
 7066: 
 7067: .LC_disc_new_item {
 7068:   background: white;
 7069:   border: 2px solid red;
 7070:   margin: 4px;
 7071:   padding: 4px;
 7072: }
 7073: 
 7074: .LC_disc_old_item {
 7075:   background: white;
 7076:   margin: 4px;
 7077:   padding: 4px;
 7078: }
 7079: 
 7080: table.LC_pastsubmission {
 7081:   border: 1px solid black;
 7082:   margin: 2px;
 7083: }
 7084: 
 7085: table#LC_menubuttons {
 7086:   width: 100%;
 7087:   background: $pgbg;
 7088:   border: 2px;
 7089:   border-collapse: separate;
 7090:   padding: 0;
 7091: }
 7092: 
 7093: table#LC_title_bar a {
 7094:   color: $fontmenu;
 7095: }
 7096: 
 7097: table#LC_title_bar {
 7098:   clear: both;
 7099:   display: none;
 7100: }
 7101: 
 7102: table#LC_title_bar,
 7103: table.LC_breadcrumbs, /* obsolete? */
 7104: table#LC_title_bar.LC_with_remote {
 7105:   width: 100%;
 7106:   border-color: $pgbg;
 7107:   border-style: solid;
 7108:   border-width: $border;
 7109:   background: $pgbg;
 7110:   color: $fontmenu;
 7111:   border-collapse: collapse;
 7112:   padding: 0;
 7113:   margin: 0;
 7114: }
 7115: 
 7116: ul.LC_breadcrumb_tools_outerlist {
 7117:     margin: 0;
 7118:     padding: 0;
 7119:     position: relative;
 7120:     list-style: none;
 7121: }
 7122: ul.LC_breadcrumb_tools_outerlist li {
 7123:     display: inline;
 7124: }
 7125: 
 7126: .LC_breadcrumb_tools_navigation {
 7127:     padding: 0;
 7128:     margin: 0;
 7129:     float: left;
 7130: }
 7131: .LC_breadcrumb_tools_tools {
 7132:     padding: 0;
 7133:     margin: 0;
 7134:     float: right;
 7135: }
 7136: 
 7137: .LC_placement_prog {
 7138:     padding-right: 20px;
 7139:     font-weight: bold;
 7140:     font-size: 90%;
 7141: }
 7142: 
 7143: table#LC_title_bar td {
 7144:   background: $tabbg;
 7145: }
 7146: 
 7147: table#LC_menubuttons img {
 7148:   border: none;
 7149: }
 7150: 
 7151: .LC_breadcrumbs_component {
 7152:   float: right;
 7153:   margin: 0 1em;
 7154: }
 7155: .LC_breadcrumbs_component img {
 7156:   vertical-align: middle;
 7157: }
 7158: 
 7159: .LC_breadcrumbs_hoverable {
 7160:   background: $sidebg;
 7161: }
 7162: 
 7163: td.LC_table_cell_checkbox {
 7164:   text-align: center;
 7165: }
 7166: 
 7167: .LC_fontsize_small {
 7168:   font-size: 70%;
 7169: }
 7170: 
 7171: #LC_breadcrumbs {
 7172:   clear:both;
 7173:   background: $sidebg;
 7174:   border-bottom: 1px solid $lg_border_color;
 7175:   line-height: 2.5em;
 7176:   overflow: hidden;
 7177:   margin: 0;
 7178:   padding: 0;
 7179:   text-align: left;
 7180: }
 7181: 
 7182: .LC_head_subbox, .LC_actionbox {
 7183:   clear:both;
 7184:   background: #F8F8F8; /* $sidebg; */
 7185:   border: 1px solid $sidebg;
 7186:   margin: 0 0 10px 0;
 7187:   padding: 3px;
 7188:   text-align: left;
 7189: }
 7190: 
 7191: .LC_fontsize_medium {
 7192:   font-size: 85%;
 7193: }
 7194: 
 7195: .LC_fontsize_large {
 7196:   font-size: 120%;
 7197: }
 7198: 
 7199: .LC_menubuttons_inline_text {
 7200:   color: $font;
 7201:   font-size: 90%;
 7202:   padding-left:3px;
 7203: }
 7204: 
 7205: .LC_menubuttons_inline_text img{
 7206:   vertical-align: middle;
 7207: }
 7208: 
 7209: li.LC_menubuttons_inline_text img {
 7210:   cursor:pointer;
 7211:   text-decoration: none;
 7212: }
 7213: 
 7214: .LC_menubuttons_link {
 7215:   text-decoration: none;
 7216: }
 7217: 
 7218: .LC_menubuttons_category {
 7219:   color: $font;
 7220:   background: $pgbg;
 7221:   font-size: larger;
 7222:   font-weight: bold;
 7223: }
 7224: 
 7225: td.LC_menubuttons_text {
 7226:   color: $font;
 7227: }
 7228: 
 7229: .LC_current_location {
 7230:   background: $tabbg;
 7231: }
 7232: 
 7233: td.LC_zero_height {
 7234:   line-height: 0; 
 7235:   cellpadding: 0;
 7236: }
 7237: 
 7238: table.LC_data_table {
 7239:   border: 1px solid #000000;
 7240:   border-collapse: separate;
 7241:   border-spacing: 1px;
 7242:   background: $pgbg;
 7243: }
 7244: 
 7245: .LC_data_table_dense {
 7246:   font-size: small;
 7247: }
 7248: 
 7249: table.LC_nested_outer {
 7250:   border: 1px solid #000000;
 7251:   border-collapse: collapse;
 7252:   border-spacing: 0;
 7253:   width: 100%;
 7254: }
 7255: 
 7256: table.LC_innerpickbox,
 7257: table.LC_nested {
 7258:   border: none;
 7259:   border-collapse: collapse;
 7260:   border-spacing: 0;
 7261:   width: 100%;
 7262: }
 7263: 
 7264: table.LC_data_table tr th,
 7265: table.LC_calendar tr th,
 7266: table.LC_prior_tries tr th,
 7267: table.LC_innerpickbox tr th {
 7268:   font-weight: bold;
 7269:   background-color: $data_table_head;
 7270:   color:$fontmenu;
 7271:   font-size:90%;
 7272: }
 7273: 
 7274: table.LC_innerpickbox tr th,
 7275: table.LC_innerpickbox tr td {
 7276:   vertical-align: top;
 7277: }
 7278: 
 7279: table.LC_data_table tr.LC_info_row > td {
 7280:   background-color: #CCCCCC;
 7281:   font-weight: bold;
 7282:   text-align: left;
 7283: }
 7284: 
 7285: table.LC_data_table tr.LC_odd_row > td {
 7286:   background-color: $data_table_light;
 7287:   padding: 2px;
 7288:   vertical-align: top;
 7289: }
 7290: 
 7291: table.LC_pick_box tr > td.LC_odd_row {
 7292:   background-color: $data_table_light;
 7293:   vertical-align: top;
 7294: }
 7295: 
 7296: table.LC_data_table tr.LC_even_row > td {
 7297:   background-color: $data_table_dark;
 7298:   padding: 2px;
 7299:   vertical-align: top;
 7300: }
 7301: 
 7302: table.LC_pick_box tr > td.LC_even_row {
 7303:   background-color: $data_table_dark;
 7304:   vertical-align: top;
 7305: }
 7306: 
 7307: table.LC_data_table tr.LC_data_table_highlight td {
 7308:   background-color: $data_table_darker;
 7309: }
 7310: 
 7311: table.LC_data_table tr td.LC_leftcol_header {
 7312:   background-color: $data_table_head;
 7313:   font-weight: bold;
 7314: }
 7315: 
 7316: table.LC_data_table tr.LC_empty_row td,
 7317: table.LC_nested tr.LC_empty_row td {
 7318:   font-weight: bold;
 7319:   font-style: italic;
 7320:   text-align: center;
 7321:   padding: 8px;
 7322: }
 7323: 
 7324: table.LC_data_table tr.LC_empty_row td,
 7325: table.LC_data_table tr.LC_footer_row td {
 7326:   background-color: $sidebg;
 7327: }
 7328: 
 7329: table.LC_nested tr.LC_empty_row td {
 7330:   background-color: #FFFFFF;
 7331: }
 7332: 
 7333: table.LC_caption {
 7334: }
 7335: 
 7336: table.LC_nested tr.LC_empty_row td {
 7337:   padding: 4ex
 7338: }
 7339: 
 7340: table.LC_nested_outer tr th {
 7341:   font-weight: bold;
 7342:   color:$fontmenu;
 7343:   background-color: $data_table_head;
 7344:   font-size: small;
 7345:   border-bottom: 1px solid #000000;
 7346: }
 7347: 
 7348: table.LC_nested_outer tr td.LC_subheader {
 7349:   background-color: $data_table_head;
 7350:   font-weight: bold;
 7351:   font-size: small;
 7352:   border-bottom: 1px solid #000000;
 7353:   text-align: right;
 7354: }
 7355: 
 7356: table.LC_nested tr.LC_info_row td {
 7357:   background-color: #CCCCCC;
 7358:   font-weight: bold;
 7359:   font-size: small;
 7360:   text-align: center;
 7361: }
 7362: 
 7363: table.LC_nested tr.LC_info_row td.LC_left_item,
 7364: table.LC_nested_outer tr th.LC_left_item {
 7365:   text-align: left;
 7366: }
 7367: 
 7368: table.LC_nested td {
 7369:   background-color: #FFFFFF;
 7370:   font-size: small;
 7371: }
 7372: 
 7373: table.LC_nested_outer tr th.LC_right_item,
 7374: table.LC_nested tr.LC_info_row td.LC_right_item,
 7375: table.LC_nested tr.LC_odd_row td.LC_right_item,
 7376: table.LC_nested tr td.LC_right_item {
 7377:   text-align: right;
 7378: }
 7379: 
 7380: table.LC_nested tr.LC_odd_row td {
 7381:   background-color: #EEEEEE;
 7382: }
 7383: 
 7384: table.LC_createuser {
 7385: }
 7386: 
 7387: table.LC_createuser tr.LC_section_row td {
 7388:   font-size: small;
 7389: }
 7390: 
 7391: table.LC_createuser tr.LC_info_row td  {
 7392:   background-color: #CCCCCC;
 7393:   font-weight: bold;
 7394:   text-align: center;
 7395: }
 7396: 
 7397: table.LC_calendar {
 7398:   border: 1px solid #000000;
 7399:   border-collapse: collapse;
 7400:   width: 98%;
 7401: }
 7402: 
 7403: table.LC_calendar_pickdate {
 7404:   font-size: xx-small;
 7405: }
 7406: 
 7407: table.LC_calendar tr td {
 7408:   border: 1px solid #000000;
 7409:   vertical-align: top;
 7410:   width: 14%;
 7411: }
 7412: 
 7413: table.LC_calendar tr td.LC_calendar_day_empty {
 7414:   background-color: $data_table_dark;
 7415: }
 7416: 
 7417: table.LC_calendar tr td.LC_calendar_day_current {
 7418:   background-color: $data_table_highlight;
 7419: }
 7420: 
 7421: table.LC_data_table tr td.LC_mail_new {
 7422:   background-color: $mail_new;
 7423: }
 7424: 
 7425: table.LC_data_table tr.LC_mail_new:hover {
 7426:   background-color: $mail_new_hover;
 7427: }
 7428: 
 7429: table.LC_data_table tr td.LC_mail_read {
 7430:   background-color: $mail_read;
 7431: }
 7432: 
 7433: /*
 7434: table.LC_data_table tr.LC_mail_read:hover {
 7435:   background-color: $mail_read_hover;
 7436: }
 7437: */
 7438: 
 7439: table.LC_data_table tr td.LC_mail_replied {
 7440:   background-color: $mail_replied;
 7441: }
 7442: 
 7443: /*
 7444: table.LC_data_table tr.LC_mail_replied:hover {
 7445:   background-color: $mail_replied_hover;
 7446: }
 7447: */
 7448: 
 7449: table.LC_data_table tr td.LC_mail_other {
 7450:   background-color: $mail_other;
 7451: }
 7452: 
 7453: /*
 7454: table.LC_data_table tr.LC_mail_other:hover {
 7455:   background-color: $mail_other_hover;
 7456: }
 7457: */
 7458: 
 7459: table.LC_data_table tr > td.LC_browser_file,
 7460: table.LC_data_table tr > td.LC_browser_file_published {
 7461:   background: #AAEE77;
 7462: }
 7463: 
 7464: table.LC_data_table tr > td.LC_browser_file_locked,
 7465: table.LC_data_table tr > td.LC_browser_file_unpublished {
 7466:   background: #FFAA99;
 7467: }
 7468: 
 7469: table.LC_data_table tr > td.LC_browser_file_obsolete {
 7470:   background: #888888;
 7471: }
 7472: 
 7473: table.LC_data_table tr > td.LC_browser_file_modified,
 7474: table.LC_data_table tr > td.LC_browser_file_metamodified {
 7475:   background: #F8F866;
 7476: }
 7477: 
 7478: table.LC_data_table tr.LC_browser_folder > td {
 7479:   background: #E0E8FF;
 7480: }
 7481: 
 7482: table.LC_data_table tr > td.LC_roles_is {
 7483:   /* background: #77FF77; */
 7484: }
 7485: 
 7486: table.LC_data_table tr > td.LC_roles_future {
 7487:   border-right: 8px solid #FFFF77;
 7488: }
 7489: 
 7490: table.LC_data_table tr > td.LC_roles_will {
 7491:   border-right: 8px solid #FFAA77;
 7492: }
 7493: 
 7494: table.LC_data_table tr > td.LC_roles_expired {
 7495:   border-right: 8px solid #FF7777;
 7496: }
 7497: 
 7498: table.LC_data_table tr > td.LC_roles_will_not {
 7499:   border-right: 8px solid #AAFF77;
 7500: }
 7501: 
 7502: table.LC_data_table tr > td.LC_roles_selected {
 7503:   border-right: 8px solid #11CC55;
 7504: }
 7505: 
 7506: span.LC_current_location {
 7507:   font-size:larger;
 7508:   background: $pgbg;
 7509: }
 7510: 
 7511: span.LC_current_nav_location {
 7512:   font-weight:bold;
 7513:   background: $sidebg;
 7514: }
 7515: 
 7516: span.LC_parm_menu_item {
 7517:   font-size: larger;
 7518: }
 7519: 
 7520: span.LC_parm_scope_all {
 7521:   color: red;
 7522: }
 7523: 
 7524: span.LC_parm_scope_folder {
 7525:   color: green;
 7526: }
 7527: 
 7528: span.LC_parm_scope_resource {
 7529:   color: orange;
 7530: }
 7531: 
 7532: span.LC_parm_part {
 7533:   color: blue;
 7534: }
 7535: 
 7536: span.LC_parm_folder,
 7537: span.LC_parm_symb {
 7538:   font-size: x-small;
 7539:   font-family: $mono;
 7540:   color: #AAAAAA;
 7541: }
 7542: 
 7543: ul.LC_parm_parmlist li {
 7544:   display: inline-block;
 7545:   padding: 0.3em 0.8em;
 7546:   vertical-align: top;
 7547:   width: 150px;
 7548:   border-top:1px solid $lg_border_color;
 7549: }
 7550: 
 7551: td.LC_parm_overview_level_menu,
 7552: td.LC_parm_overview_map_menu,
 7553: td.LC_parm_overview_parm_selectors,
 7554: td.LC_parm_overview_restrictions  {
 7555:   border: 1px solid black;
 7556:   border-collapse: collapse;
 7557: }
 7558: 
 7559: span.LC_parm_recursive,
 7560: td.LC_parm_recursive {
 7561:   font-weight: bold;
 7562:   font-size: smaller;
 7563: }
 7564: 
 7565: table.LC_parm_overview_restrictions td {
 7566:   border-width: 1px 4px 1px 4px;
 7567:   border-style: solid;
 7568:   border-color: $pgbg;
 7569:   text-align: center;
 7570: }
 7571: 
 7572: table.LC_parm_overview_restrictions th {
 7573:   background: $tabbg;
 7574:   border-width: 1px 4px 1px 4px;
 7575:   border-style: solid;
 7576:   border-color: $pgbg;
 7577: }
 7578: 
 7579: table#LC_helpmenu {
 7580:   border: none;
 7581:   height: 55px;
 7582:   border-spacing: 0;
 7583: }
 7584: 
 7585: table#LC_helpmenu fieldset legend {
 7586:   font-size: larger;
 7587: }
 7588: 
 7589: table#LC_helpmenu_links {
 7590:   width: 100%;
 7591:   border: 1px solid black;
 7592:   background: $pgbg;
 7593:   padding: 0;
 7594:   border-spacing: 1px;
 7595: }
 7596: 
 7597: table#LC_helpmenu_links tr td {
 7598:   padding: 1px;
 7599:   background: $tabbg;
 7600:   text-align: center;
 7601:   font-weight: bold;
 7602: }
 7603: 
 7604: table#LC_helpmenu_links a:link,
 7605: table#LC_helpmenu_links a:visited,
 7606: table#LC_helpmenu_links a:active {
 7607:   text-decoration: none;
 7608:   color: $font;
 7609: }
 7610: 
 7611: table#LC_helpmenu_links a:hover {
 7612:   text-decoration: underline;
 7613:   color: $vlink;
 7614: }
 7615: 
 7616: .LC_chrt_popup_exists {
 7617:   border: 1px solid #339933;
 7618:   margin: -1px;
 7619: }
 7620: 
 7621: .LC_chrt_popup_up {
 7622:   border: 1px solid yellow;
 7623:   margin: -1px;
 7624: }
 7625: 
 7626: .LC_chrt_popup {
 7627:   border: 1px solid #8888FF;
 7628:   background: #CCCCFF;
 7629: }
 7630: 
 7631: table.LC_pick_box {
 7632:   border-collapse: separate;
 7633:   background: white;
 7634:   border: 1px solid black;
 7635:   border-spacing: 1px;
 7636: }
 7637: 
 7638: table.LC_pick_box td.LC_pick_box_title {
 7639:   background: $sidebg;
 7640:   font-weight: bold;
 7641:   text-align: left;
 7642:   vertical-align: top;
 7643:   width: 184px;
 7644:   padding: 8px;
 7645: }
 7646: 
 7647: table.LC_pick_box td.LC_pick_box_value {
 7648:   text-align: left;
 7649:   padding: 8px;
 7650: }
 7651: 
 7652: table.LC_pick_box td.LC_pick_box_select {
 7653:   text-align: left;
 7654:   padding: 8px;
 7655: }
 7656: 
 7657: table.LC_pick_box td.LC_pick_box_separator {
 7658:   padding: 0;
 7659:   height: 1px;
 7660:   background: black;
 7661: }
 7662: 
 7663: table.LC_pick_box td.LC_pick_box_submit {
 7664:   text-align: right;
 7665: }
 7666: 
 7667: table.LC_pick_box td.LC_evenrow_value {
 7668:   text-align: left;
 7669:   padding: 8px;
 7670:   background-color: $data_table_light;
 7671: }
 7672: 
 7673: table.LC_pick_box td.LC_oddrow_value {
 7674:   text-align: left;
 7675:   padding: 8px;
 7676:   background-color: $data_table_light;
 7677: }
 7678: 
 7679: span.LC_helpform_receipt_cat {
 7680:   font-weight: bold;
 7681: }
 7682: 
 7683: table.LC_group_priv_box {
 7684:   background: white;
 7685:   border: 1px solid black;
 7686:   border-spacing: 1px;
 7687: }
 7688: 
 7689: table.LC_group_priv_box td.LC_pick_box_title {
 7690:   background: $tabbg;
 7691:   font-weight: bold;
 7692:   text-align: right;
 7693:   width: 184px;
 7694: }
 7695: 
 7696: table.LC_group_priv_box td.LC_groups_fixed {
 7697:   background: $data_table_light;
 7698:   text-align: center;
 7699: }
 7700: 
 7701: table.LC_group_priv_box td.LC_groups_optional {
 7702:   background: $data_table_dark;
 7703:   text-align: center;
 7704: }
 7705: 
 7706: table.LC_group_priv_box td.LC_groups_functionality {
 7707:   background: $data_table_darker;
 7708:   text-align: center;
 7709:   font-weight: bold;
 7710: }
 7711: 
 7712: table.LC_group_priv td {
 7713:   text-align: left;
 7714:   padding: 0;
 7715: }
 7716: 
 7717: .LC_navbuttons {
 7718:   margin: 2ex 0ex 2ex 0ex;
 7719: }
 7720: 
 7721: .LC_topic_bar {
 7722:   font-weight: bold;
 7723:   background: $tabbg;
 7724:   margin: 1em 0em 1em 2em;
 7725:   padding: 3px;
 7726:   font-size: 1.2em;
 7727: }
 7728: 
 7729: .LC_topic_bar span {
 7730:   left: 0.5em;
 7731:   position: absolute;
 7732:   vertical-align: middle;
 7733:   font-size: 1.2em;
 7734: }
 7735: 
 7736: table.LC_course_group_status {
 7737:   margin: 20px;
 7738: }
 7739: 
 7740: table.LC_status_selector td {
 7741:   vertical-align: top;
 7742:   text-align: center;
 7743:   padding: 4px;
 7744: }
 7745: 
 7746: div.LC_feedback_link {
 7747:   clear: both;
 7748:   background: $sidebg;
 7749:   width: 100%;
 7750:   padding-bottom: 10px;
 7751:   border: 1px $tabbg solid;
 7752:   height: 22px;
 7753:   line-height: 22px;
 7754:   padding-top: 5px;
 7755: }
 7756: 
 7757: div.LC_feedback_link img {
 7758:   height: 22px;
 7759:   vertical-align:middle;
 7760: }
 7761: 
 7762: div.LC_feedback_link a {
 7763:   text-decoration: none;
 7764: }
 7765: 
 7766: div.LC_comblock {
 7767:   display:inline;
 7768:   color:$font;
 7769:   font-size:90%;
 7770: }
 7771: 
 7772: div.LC_feedback_link div.LC_comblock {
 7773:   padding-left:5px;
 7774: }
 7775: 
 7776: div.LC_feedback_link div.LC_comblock a {
 7777:   color:$font;
 7778: }
 7779: 
 7780: span.LC_feedback_link {
 7781:   /* background: $feedback_link_bg; */
 7782:   font-size: larger;
 7783: }
 7784: 
 7785: span.LC_message_link {
 7786:   /* background: $feedback_link_bg; */
 7787:   font-size: larger;
 7788:   position: absolute;
 7789:   right: 1em;
 7790: }
 7791: 
 7792: table.LC_prior_tries {
 7793:   border: 1px solid #000000;
 7794:   border-collapse: separate;
 7795:   border-spacing: 1px;
 7796: }
 7797: 
 7798: table.LC_prior_tries td {
 7799:   padding: 2px;
 7800: }
 7801: 
 7802: .LC_answer_correct {
 7803:   background: lightgreen;
 7804:   color: darkgreen;
 7805:   padding: 6px;
 7806: }
 7807: 
 7808: .LC_answer_charged_try {
 7809:   background: #FFAAAA;
 7810:   color: darkred;
 7811:   padding: 6px;
 7812: }
 7813: 
 7814: .LC_answer_not_charged_try,
 7815: .LC_answer_no_grade,
 7816: .LC_answer_late {
 7817:   background: lightyellow;
 7818:   color: black;
 7819:   padding: 6px;
 7820: }
 7821: 
 7822: .LC_answer_previous {
 7823:   background: lightblue;
 7824:   color: darkblue;
 7825:   padding: 6px;
 7826: }
 7827: 
 7828: .LC_answer_no_message {
 7829:   background: #FFFFFF;
 7830:   color: black;
 7831:   padding: 6px;
 7832: }
 7833: 
 7834: .LC_answer_unknown,
 7835: .LC_answer_warning {
 7836:   background: orange;
 7837:   color: black;
 7838:   padding: 6px;
 7839: }
 7840: 
 7841: span.LC_prior_numerical,
 7842: span.LC_prior_string,
 7843: span.LC_prior_custom,
 7844: span.LC_prior_reaction,
 7845: span.LC_prior_math {
 7846:   font-family: $mono;
 7847:   white-space: pre;
 7848: }
 7849: 
 7850: span.LC_prior_string {
 7851:   font-family: $mono;
 7852:   white-space: pre;
 7853: }
 7854: 
 7855: table.LC_prior_option {
 7856:   width: 100%;
 7857:   border-collapse: collapse;
 7858: }
 7859: 
 7860: table.LC_prior_rank,
 7861: table.LC_prior_match {
 7862:   border-collapse: collapse;
 7863: }
 7864: 
 7865: table.LC_prior_option tr td,
 7866: table.LC_prior_rank tr td,
 7867: table.LC_prior_match tr td {
 7868:   border: 1px solid #000000;
 7869: }
 7870: 
 7871: .LC_nobreak {
 7872:   white-space: nowrap;
 7873: }
 7874: 
 7875: span.LC_cusr_emph {
 7876:   font-style: italic;
 7877: }
 7878: 
 7879: span.LC_cusr_subheading {
 7880:   font-weight: normal;
 7881:   font-size: 85%;
 7882: }
 7883: 
 7884: div.LC_docs_entry_move {
 7885:   border: 1px solid #BBBBBB;
 7886:   background: #DDDDDD;
 7887:   width: 22px;
 7888:   padding: 1px;
 7889:   margin: 0;
 7890: }
 7891: 
 7892: table.LC_data_table tr > td.LC_docs_entry_commands,
 7893: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7894:   font-size: x-small;
 7895: }
 7896: 
 7897: .LC_docs_entry_parameter {
 7898:   white-space: nowrap;
 7899: }
 7900: 
 7901: .LC_docs_copy {
 7902:   color: #000099;
 7903: }
 7904: 
 7905: .LC_docs_cut {
 7906:   color: #550044;
 7907: }
 7908: 
 7909: .LC_docs_rename {
 7910:   color: #009900;
 7911: }
 7912: 
 7913: .LC_docs_remove {
 7914:   color: #990000;
 7915: }
 7916: 
 7917: .LC_docs_alias {
 7918:   color: #440055;  
 7919: }
 7920: 
 7921: .LC_domprefs_email,
 7922: .LC_docs_alias_name,
 7923: .LC_docs_reinit_warn,
 7924: .LC_docs_ext_edit {
 7925:   font-size: x-small;
 7926: }
 7927: 
 7928: table.LC_docs_adddocs td,
 7929: table.LC_docs_adddocs th {
 7930:   border: 1px solid #BBBBBB;
 7931:   padding: 4px;
 7932:   background: #DDDDDD;
 7933: }
 7934: 
 7935: table.LC_sty_begin {
 7936:   background: #BBFFBB;
 7937: }
 7938: 
 7939: table.LC_sty_end {
 7940:   background: #FFBBBB;
 7941: }
 7942: 
 7943: table.LC_double_column {
 7944:   border-width: 0;
 7945:   border-collapse: collapse;
 7946:   width: 100%;
 7947:   padding: 2px;
 7948: }
 7949: 
 7950: table.LC_double_column tr td.LC_left_col {
 7951:   top: 2px;
 7952:   left: 2px;
 7953:   width: 47%;
 7954:   vertical-align: top;
 7955: }
 7956: 
 7957: table.LC_double_column tr td.LC_right_col {
 7958:   top: 2px;
 7959:   right: 2px;
 7960:   width: 47%;
 7961:   vertical-align: top;
 7962: }
 7963: 
 7964: div.LC_left_float {
 7965:   float: left;
 7966:   padding-right: 5%;
 7967:   padding-bottom: 4px;
 7968: }
 7969: 
 7970: div.LC_clear_float_header {
 7971:   padding-bottom: 2px;
 7972: }
 7973: 
 7974: div.LC_clear_float_footer {
 7975:   padding-top: 10px;
 7976:   clear: both;
 7977: }
 7978: 
 7979: div.LC_grade_show_user {
 7980: /*  border-left: 5px solid $sidebg; */
 7981:   border-top: 5px solid #000000;
 7982:   margin: 50px 0 0 0;
 7983:   padding: 15px 0 5px 10px;
 7984: }
 7985: 
 7986: div.LC_grade_show_user_odd_row {
 7987: /*  border-left: 5px solid #000000; */
 7988: }
 7989: 
 7990: div.LC_grade_show_user div.LC_Box {
 7991:   margin-right: 50px;
 7992: }
 7993: 
 7994: div.LC_grade_submissions,
 7995: div.LC_grade_message_center,
 7996: div.LC_grade_info_links {
 7997:   margin: 5px;
 7998:   width: 99%;
 7999:   background: #FFFFFF;
 8000: }
 8001: 
 8002: div.LC_grade_submissions_header,
 8003: div.LC_grade_message_center_header {
 8004:   font-weight: bold;
 8005:   font-size: large;
 8006: }
 8007: 
 8008: div.LC_grade_submissions_body,
 8009: div.LC_grade_message_center_body {
 8010:   border: 1px solid black;
 8011:   width: 99%;
 8012:   background: #FFFFFF;
 8013: }
 8014: 
 8015: table.LC_scantron_action {
 8016:   width: 100%;
 8017: }
 8018: 
 8019: table.LC_scantron_action tr th {
 8020:   font-weight:bold;
 8021:   font-style:normal;
 8022: }
 8023: 
 8024: .LC_edit_problem_header,
 8025: div.LC_edit_problem_footer {
 8026:   font-weight: normal;
 8027:   font-size:  medium;
 8028:   margin: 2px;
 8029:   background-color: $sidebg;
 8030: }
 8031: 
 8032: div.LC_edit_problem_header,
 8033: div.LC_edit_problem_header div,
 8034: div.LC_edit_problem_footer,
 8035: div.LC_edit_problem_footer div,
 8036: div.LC_edit_problem_editxml_header,
 8037: div.LC_edit_problem_editxml_header div {
 8038:   z-index: 100;
 8039: }
 8040: 
 8041: div.LC_edit_problem_header_title {
 8042:   font-weight: bold;
 8043:   font-size: larger;
 8044:   background: $tabbg;
 8045:   padding: 3px;
 8046:   margin: 0 0 5px 0;
 8047: }
 8048: 
 8049: table.LC_edit_problem_header_title {
 8050:   width: 100%;
 8051:   background: $tabbg;
 8052: }
 8053: 
 8054: div.LC_edit_actionbar {
 8055:     background-color: $sidebg;
 8056:     margin: 0;
 8057:     padding: 0;
 8058:     line-height: 200%;
 8059: }
 8060: 
 8061: div.LC_edit_actionbar div{
 8062:     padding: 0;
 8063:     margin: 0;
 8064:     display: inline-block;
 8065: }
 8066: 
 8067: .LC_edit_opt {
 8068:   padding-left: 1em;
 8069:   white-space: nowrap;
 8070: }
 8071: 
 8072: .LC_edit_problem_latexhelper{
 8073:     text-align: right;
 8074: }
 8075: 
 8076: #LC_edit_problem_colorful div{
 8077:     margin-left: 40px;
 8078: }
 8079: 
 8080: #LC_edit_problem_codemirror div{
 8081:     margin-left: 0px;
 8082: }
 8083: 
 8084: img.stift {
 8085:   border-width: 0;
 8086:   vertical-align: middle;
 8087: }
 8088: 
 8089: table td.LC_mainmenu_col_fieldset {
 8090:   vertical-align: top;
 8091: }
 8092: 
 8093: div.LC_createcourse {
 8094:   margin: 10px 10px 10px 10px;
 8095: }
 8096: 
 8097: .LC_dccid {
 8098:   float: right;
 8099:   margin: 0.2em 0 0 0;
 8100:   padding: 0;
 8101:   font-size: 90%;
 8102:   display:none;
 8103: }
 8104: 
 8105: ol.LC_primary_menu a:hover,
 8106: ol#LC_MenuBreadcrumbs a:hover,
 8107: ol#LC_PathBreadcrumbs a:hover,
 8108: ul#LC_secondary_menu a:hover,
 8109: .LC_FormSectionClearButton input:hover
 8110: ul.LC_TabContent   li:hover a {
 8111:   color:$button_hover;
 8112:   text-decoration:none;
 8113: }
 8114: 
 8115: h1 {
 8116:   padding: 0;
 8117:   line-height:130%;
 8118: }
 8119: 
 8120: h2,
 8121: h3,
 8122: h4,
 8123: h5,
 8124: h6 {
 8125:   margin: 5px 0 5px 0;
 8126:   padding: 0;
 8127:   line-height:130%;
 8128: }
 8129: 
 8130: .LC_hcell {
 8131:   padding:3px 15px 3px 15px;
 8132:   margin: 0;
 8133:   background-color:$tabbg;
 8134:   color:$fontmenu;
 8135:   border-bottom:solid 1px $lg_border_color;
 8136: }
 8137: 
 8138: .LC_Box > .LC_hcell {
 8139:   margin: 0 -10px 10px -10px;
 8140: }
 8141: 
 8142: .LC_noBorder {
 8143:   border: 0;
 8144: }
 8145: 
 8146: .LC_FormSectionClearButton input {
 8147:   background-color:transparent;
 8148:   border: none;
 8149:   cursor:pointer;
 8150:   text-decoration:underline;
 8151: }
 8152: 
 8153: .LC_help_open_topic {
 8154:   color: #FFFFFF;
 8155:   background-color: #EEEEFF;
 8156:   margin: 1px;
 8157:   padding: 4px;
 8158:   border: 1px solid #000033;
 8159:   white-space: nowrap;
 8160:   /* vertical-align: middle; */
 8161: }
 8162: 
 8163: dl,
 8164: ul,
 8165: div,
 8166: fieldset {
 8167:   margin: 10px 10px 10px 0;
 8168:   /* overflow: hidden; */
 8169: }
 8170: 
 8171: fieldset#LC_selectuser {
 8172:     margin: 0;
 8173:     padding: 0;
 8174: }
 8175: 
 8176: article.geogebraweb div {
 8177:     margin: 0;
 8178: }
 8179: 
 8180: fieldset > legend {
 8181:   font-weight: bold;
 8182:   padding: 0 5px 0 5px;
 8183: }
 8184: 
 8185: #LC_nav_bar {
 8186:   float: left;
 8187:   background-color: $pgbg_or_bgcolor;
 8188:   margin: 0 0 2px 0;
 8189: }
 8190: 
 8191: #LC_realm {
 8192:   margin: 0.2em 0 0 0;
 8193:   padding: 0;
 8194:   font-weight: bold;
 8195:   text-align: center;
 8196:   background-color: $pgbg_or_bgcolor;
 8197: }
 8198: 
 8199: #LC_nav_bar em {
 8200:   font-weight: bold;
 8201:   font-style: normal;
 8202: }
 8203: 
 8204: ol.LC_primary_menu {
 8205:   margin: 0;
 8206:   padding: 0;
 8207: }
 8208: 
 8209: ol#LC_PathBreadcrumbs {
 8210:   margin: 0;
 8211: }
 8212: 
 8213: ol.LC_primary_menu li {
 8214:   color: RGB(80, 80, 80);
 8215:   vertical-align: middle;
 8216:   text-align: left;
 8217:   list-style: none;
 8218:   position: relative;
 8219:   float: left;
 8220:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 8221:   line-height: 1.5em;
 8222: }
 8223: 
 8224: ol.LC_primary_menu li a,
 8225: ol.LC_primary_menu li p {
 8226:   display: block;
 8227:   margin: 0;
 8228:   padding: 0 5px 0 10px;
 8229:   text-decoration: none;
 8230: }
 8231: 
 8232: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 8233:   display: inline-block;
 8234:   width: 95%;
 8235:   text-align: left;
 8236: }
 8237: 
 8238: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 8239:   display: inline-block;	
 8240:   width: 5%;
 8241:   float: right;
 8242:   text-align: right;
 8243:   font-size: 70%;
 8244: }
 8245: 
 8246: ol.LC_primary_menu ul {
 8247:   display: none;
 8248:   width: 15em;
 8249:   background-color: $data_table_light;
 8250:   position: absolute;
 8251:   top: 100%;
 8252: }
 8253: 
 8254: ol.LC_primary_menu ul ul {
 8255:   left: 100%;
 8256:   top: 0;
 8257: }
 8258: 
 8259: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 8260:   display: block;
 8261:   position: absolute;
 8262:   margin: 0;
 8263:   padding: 0;
 8264:   z-index: 2;
 8265: }
 8266: 
 8267: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 8268: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 8269:   font-size: 90%;
 8270:   vertical-align: top;
 8271:   float: none;
 8272:   border-left: 1px solid black;
 8273:   border-right: 1px solid black;
 8274: /* A dark bottom border to visualize different menu options; 
 8275: overwritten in the create_submenu routine for the last border-bottom of the menu */
 8276:   border-bottom: 1px solid $data_table_dark; 
 8277: }
 8278: 
 8279: ol.LC_primary_menu li li p:hover {
 8280:   color:$button_hover;
 8281:   text-decoration:none;
 8282:   background-color:$data_table_dark;
 8283: }
 8284: 
 8285: ol.LC_primary_menu li li a:hover {
 8286:    color:$button_hover;
 8287:    background-color:$data_table_dark;
 8288: }
 8289: 
 8290: /* Font-size equal to the size of the predecessors*/
 8291: ol.LC_primary_menu li:hover li li {
 8292:   font-size: 100%;
 8293: }
 8294: 
 8295: ol.LC_primary_menu li img {
 8296:   vertical-align: bottom;
 8297:   height: 1.1em;
 8298:   margin: 0.2em 0 0 0;
 8299: }
 8300: 
 8301: ol.LC_primary_menu a {
 8302:   color: RGB(80, 80, 80);
 8303:   text-decoration: none;
 8304: }
 8305: 
 8306: ol.LC_primary_menu a.LC_new_message {
 8307:   font-weight:bold;
 8308:   color: darkred;
 8309: }
 8310: 
 8311: ol.LC_docs_parameters {
 8312:   margin-left: 0;
 8313:   padding: 0;
 8314:   list-style: none;
 8315: }
 8316: 
 8317: ol.LC_docs_parameters li {
 8318:   margin: 0;
 8319:   padding-right: 20px;
 8320:   display: inline;
 8321: }
 8322: 
 8323: ol.LC_docs_parameters li:before {
 8324:   content: "\\002022 \\0020";
 8325: }
 8326: 
 8327: li.LC_docs_parameters_title {
 8328:   font-weight: bold;
 8329: }
 8330: 
 8331: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 8332:   content: "";
 8333: }
 8334: 
 8335: ul#LC_secondary_menu {
 8336:   clear: right;
 8337:   color: $fontmenu;
 8338:   background: $tabbg;
 8339:   list-style: none;
 8340:   padding: 0;
 8341:   margin: 0;
 8342:   width: 100%;
 8343:   text-align: left;
 8344:   float: left;
 8345: }
 8346: 
 8347: ul#LC_secondary_menu li {
 8348:   font-weight: bold;
 8349:   line-height: 1.8em;
 8350:   border-right: 1px solid black;
 8351:   float: left;
 8352: }
 8353: 
 8354: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 8355:   background-color: $data_table_light;
 8356: }
 8357: 
 8358: ul#LC_secondary_menu li a {
 8359:   padding: 0 0.8em;
 8360: }
 8361: 
 8362: ul#LC_secondary_menu li ul {
 8363:   display: none;
 8364: }
 8365: 
 8366: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 8367:   display: block;
 8368:   position: absolute;
 8369:   margin: 0;
 8370:   padding: 0;
 8371:   list-style:none;
 8372:   float: none;
 8373:   background-color: $data_table_light;
 8374:   z-index: 2;
 8375:   margin-left: -1px;
 8376: }
 8377: 
 8378: ul#LC_secondary_menu li ul li {
 8379:   font-size: 90%;
 8380:   vertical-align: top;
 8381:   border-left: 1px solid black;
 8382:   border-right: 1px solid black;
 8383:   background-color: $data_table_light;
 8384:   list-style:none;
 8385:   float: none;
 8386: }
 8387: 
 8388: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 8389:   background-color: $data_table_dark;
 8390: }
 8391: 
 8392: ul.LC_TabContent {
 8393:   display:block;
 8394:   background: $sidebg;
 8395:   border-bottom: solid 1px $lg_border_color;
 8396:   list-style:none;
 8397:   margin: -1px -10px 0 -10px;
 8398:   padding: 0;
 8399: }
 8400: 
 8401: ul.LC_TabContent li,
 8402: ul.LC_TabContentBigger li {
 8403:   float:left;
 8404: }
 8405: 
 8406: ul#LC_secondary_menu li a {
 8407:   color: $fontmenu;
 8408:   text-decoration: none;
 8409: }
 8410: 
 8411: ul.LC_TabContent {
 8412:   min-height:20px;
 8413: }
 8414: 
 8415: ul.LC_TabContent li {
 8416:   vertical-align:middle;
 8417:   padding: 0 16px 0 10px;
 8418:   background-color:$tabbg;
 8419:   border-bottom:solid 1px $lg_border_color;
 8420:   border-left: solid 1px $font;
 8421: }
 8422: 
 8423: ul.LC_TabContent .right {
 8424:   float:right;
 8425: }
 8426: 
 8427: ul.LC_TabContent li a,
 8428: ul.LC_TabContent li {
 8429:   color:rgb(47,47,47);
 8430:   text-decoration:none;
 8431:   font-size:95%;
 8432:   font-weight:bold;
 8433:   min-height:20px;
 8434: }
 8435: 
 8436: ul.LC_TabContent li a:hover,
 8437: ul.LC_TabContent li a:focus {
 8438:   color: $button_hover;
 8439:   background:none;
 8440:   outline:none;
 8441: }
 8442: 
 8443: ul.LC_TabContent li:hover {
 8444:   color: $button_hover;
 8445:   cursor:pointer;
 8446: }
 8447: 
 8448: ul.LC_TabContent li.active {
 8449:   color: $font;
 8450:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 8451:   border-bottom:solid 1px #FFFFFF;
 8452:   cursor: default;
 8453: }
 8454: 
 8455: ul.LC_TabContent li.active a {
 8456:   color:$font;
 8457:   background:#FFFFFF;
 8458:   outline: none;
 8459: }
 8460: 
 8461: ul.LC_TabContent li.goback {
 8462:   float: left;
 8463:   border-left: none;
 8464: }
 8465: 
 8466: #maincoursedoc {
 8467:   clear:both;
 8468: }
 8469: 
 8470: ul.LC_TabContentBigger {
 8471:   display:block;
 8472:   list-style:none;
 8473:   padding: 0;
 8474: }
 8475: 
 8476: ul.LC_TabContentBigger li {
 8477:   vertical-align:bottom;
 8478:   height: 30px;
 8479:   font-size:110%;
 8480:   font-weight:bold;
 8481:   color: #737373;
 8482: }
 8483: 
 8484: ul.LC_TabContentBigger li.active {
 8485:   position: relative;
 8486:   top: 1px;
 8487: }
 8488: 
 8489: ul.LC_TabContentBigger li a {
 8490:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 8491:   height: 30px;
 8492:   line-height: 30px;
 8493:   text-align: center;
 8494:   display: block;
 8495:   text-decoration: none;
 8496:   outline: none;  
 8497: }
 8498: 
 8499: ul.LC_TabContentBigger li.active a {
 8500:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8501:   color:$font;
 8502: }
 8503: 
 8504: ul.LC_TabContentBigger li b {
 8505:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8506:   display: block;
 8507:   float: left;
 8508:   padding: 0 30px;
 8509:   border-bottom: 1px solid $lg_border_color;
 8510: }
 8511: 
 8512: ul.LC_TabContentBigger li:hover b {
 8513:   color:$button_hover;
 8514: }
 8515: 
 8516: ul.LC_TabContentBigger li.active b {
 8517:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8518:   color:$font;
 8519:   border: 0;
 8520: }
 8521: 
 8522: 
 8523: ul.LC_CourseBreadcrumbs {
 8524:   background: $sidebg;
 8525:   height: 2em;
 8526:   padding-left: 10px;
 8527:   margin: 0;
 8528:   list-style-position: inside;
 8529: }
 8530: 
 8531: ol#LC_MenuBreadcrumbs,
 8532: ol#LC_PathBreadcrumbs {
 8533:   padding-left: 10px;
 8534:   margin: 0;
 8535:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8536: }
 8537: 
 8538: ol#LC_MenuBreadcrumbs li,
 8539: ol#LC_PathBreadcrumbs li,
 8540: ul.LC_CourseBreadcrumbs li {
 8541:   display: inline;
 8542:   white-space: normal;  
 8543: }
 8544: 
 8545: ol#LC_MenuBreadcrumbs li a,
 8546: ul.LC_CourseBreadcrumbs li a {
 8547:   text-decoration: none;
 8548:   font-size:90%;
 8549: }
 8550: 
 8551: ol#LC_MenuBreadcrumbs h1 {
 8552:   display: inline;
 8553:   font-size: 90%;
 8554:   line-height: 2.5em;
 8555:   margin: 0;
 8556:   padding: 0;
 8557: }
 8558: 
 8559: ol#LC_PathBreadcrumbs li a {
 8560:   text-decoration:none;
 8561:   font-size:100%;
 8562:   font-weight:bold;
 8563: }
 8564: 
 8565: .LC_Box {
 8566:   border: solid 1px $lg_border_color;
 8567:   padding: 0 10px 10px 10px;
 8568: }
 8569: 
 8570: .LC_DocsBox {
 8571:   border: solid 1px $lg_border_color;
 8572:   padding: 0 0 10px 10px;
 8573: }
 8574: 
 8575: .LC_AboutMe_Image {
 8576:   float:left;
 8577:   margin-right:10px;
 8578: }
 8579: 
 8580: .LC_Clear_AboutMe_Image {
 8581:   clear:left;
 8582: }
 8583: 
 8584: dl.LC_ListStyleClean dt {
 8585:   padding-right: 5px;
 8586:   display: table-header-group;
 8587: }
 8588: 
 8589: dl.LC_ListStyleClean dd {
 8590:   display: table-row;
 8591: }
 8592: 
 8593: .LC_ListStyleClean,
 8594: .LC_ListStyleSimple,
 8595: .LC_ListStyleNormal,
 8596: .LC_ListStyleSpecial {
 8597:   /* display:block; */
 8598:   list-style-position: inside;
 8599:   list-style-type: none;
 8600:   overflow: hidden;
 8601:   padding: 0;
 8602: }
 8603: 
 8604: .LC_ListStyleSimple li,
 8605: .LC_ListStyleSimple dd,
 8606: .LC_ListStyleNormal li,
 8607: .LC_ListStyleNormal dd,
 8608: .LC_ListStyleSpecial li,
 8609: .LC_ListStyleSpecial dd {
 8610:   margin: 0;
 8611:   padding: 5px 5px 5px 10px;
 8612:   clear: both;
 8613: }
 8614: 
 8615: .LC_ListStyleClean li,
 8616: .LC_ListStyleClean dd {
 8617:   padding-top: 0;
 8618:   padding-bottom: 0;
 8619: }
 8620: 
 8621: .LC_ListStyleSimple dd,
 8622: .LC_ListStyleSimple li {
 8623:   border-bottom: solid 1px $lg_border_color;
 8624: }
 8625: 
 8626: .LC_ListStyleSpecial li,
 8627: .LC_ListStyleSpecial dd {
 8628:   list-style-type: none;
 8629:   background-color: RGB(220, 220, 220);
 8630:   margin-bottom: 4px;
 8631: }
 8632: 
 8633: table.LC_SimpleTable {
 8634:   margin:5px;
 8635:   border:solid 1px $lg_border_color;
 8636: }
 8637: 
 8638: table.LC_SimpleTable tr {
 8639:   padding: 0;
 8640:   border:solid 1px $lg_border_color;
 8641: }
 8642: 
 8643: table.LC_SimpleTable thead {
 8644:   background:rgb(220,220,220);
 8645: }
 8646: 
 8647: div.LC_columnSection {
 8648:   display: block;
 8649:   clear: both;
 8650:   overflow: hidden;
 8651:   margin: 0;
 8652: }
 8653: 
 8654: div.LC_columnSection>* {
 8655:   float: left;
 8656:   margin: 10px 20px 10px 0;
 8657:   overflow:hidden;
 8658: }
 8659: 
 8660: table em {
 8661:   font-weight: bold;
 8662:   font-style: normal;
 8663: }
 8664: 
 8665: table.LC_tableBrowseRes,
 8666: table.LC_tableOfContent {
 8667:   border:none;
 8668:   border-spacing: 1px;
 8669:   padding: 3px;
 8670:   background-color: #FFFFFF;
 8671:   font-size: 90%;
 8672: }
 8673: 
 8674: table.LC_tableOfContent {
 8675:   border-collapse: collapse;
 8676: }
 8677: 
 8678: table.LC_tableBrowseRes a,
 8679: table.LC_tableOfContent a {
 8680:   background-color: transparent;
 8681:   text-decoration: none;
 8682: }
 8683: 
 8684: table.LC_tableOfContent img {
 8685:   border: none;
 8686:   height: 1.3em;
 8687:   vertical-align: text-bottom;
 8688:   margin-right: 0.3em;
 8689: }
 8690: 
 8691: a#LC_content_toolbar_firsthomework {
 8692:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8693: }
 8694: 
 8695: a#LC_content_toolbar_everything {
 8696:   background-image:url(/res/adm/pages/show-all.gif);
 8697: }
 8698: 
 8699: a#LC_content_toolbar_uncompleted {
 8700:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8701: }
 8702: 
 8703: #LC_content_toolbar_clearbubbles {
 8704:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8705: }
 8706: 
 8707: a#LC_content_toolbar_changefolder {
 8708:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8709: }
 8710: 
 8711: a#LC_content_toolbar_changefolder_toggled {
 8712:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8713: }
 8714: 
 8715: a#LC_content_toolbar_edittoplevel {
 8716:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8717: }
 8718: 
 8719: a#LC_content_toolbar_printout {
 8720:   background-image:url(/res/adm/pages/printout.gif);
 8721: }
 8722: 
 8723: ul#LC_toolbar li a:hover {
 8724:   background-position: bottom center;
 8725: }
 8726: 
 8727: ul#LC_toolbar {
 8728:   padding: 0;
 8729:   margin: 2px;
 8730:   list-style:none;
 8731:   position:relative;
 8732:   background-color:white;
 8733:   overflow: auto;
 8734: }
 8735: 
 8736: ul#LC_toolbar li {
 8737:   border:1px solid white;
 8738:   padding: 0;
 8739:   margin: 0;
 8740:   float: left;
 8741:   display:inline;
 8742:   vertical-align:middle;
 8743:   white-space: nowrap;
 8744: }
 8745: 
 8746: 
 8747: a.LC_toolbarItem {
 8748:   display:block;
 8749:   padding: 0;
 8750:   margin: 0;
 8751:   height: 32px;
 8752:   width: 32px;
 8753:   color:white;
 8754:   border: none;
 8755:   background-repeat:no-repeat;
 8756:   background-color:transparent;
 8757: }
 8758: 
 8759: ul.LC_funclist {
 8760:     margin: 0;
 8761:     padding: 0.5em 1em 0.5em 0;
 8762: }
 8763: 
 8764: ul.LC_funclist > li:first-child {
 8765:     font-weight:bold; 
 8766:     margin-left:0.8em;
 8767: }
 8768: 
 8769: ul.LC_funclist + ul.LC_funclist {
 8770:     /* 
 8771:        left border as a seperator if we have more than
 8772:        one list 
 8773:     */
 8774:     border-left: 1px solid $sidebg;
 8775:     /* 
 8776:        this hides the left border behind the border of the 
 8777:        outer box if element is wrapped to the next 'line' 
 8778:     */
 8779:     margin-left: -1px;
 8780: }
 8781: 
 8782: ul.LC_funclist li {
 8783:   display: inline;
 8784:   white-space: nowrap;
 8785:   margin: 0 0 0 25px;
 8786:   line-height: 150%;
 8787: }
 8788: 
 8789: .LC_hidden {
 8790:   display: none;
 8791: }
 8792: 
 8793: .LCmodal-overlay {
 8794: 		position:fixed;
 8795: 		top:0;
 8796: 		right:0;
 8797: 		bottom:0;
 8798: 		left:0;
 8799: 		height:100%;
 8800: 		width:100%;
 8801: 		margin:0;
 8802: 		padding:0;
 8803: 		background:#999;
 8804: 		opacity:.75;
 8805: 		filter: alpha(opacity=75);
 8806: 		-moz-opacity: 0.75;
 8807: 		z-index:101;
 8808: }
 8809: 
 8810: * html .LCmodal-overlay {   
 8811: 		position: absolute;
 8812: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8813: }
 8814: 
 8815: .LCmodal-window {
 8816: 		position:fixed;
 8817: 		top:50%;
 8818: 		left:50%;
 8819: 		margin:0;
 8820: 		padding:0;
 8821: 		z-index:102;
 8822: 	}
 8823: 
 8824: * html .LCmodal-window {
 8825: 		position:absolute;
 8826: }
 8827: 
 8828: .LCclose-window {
 8829: 		position:absolute;
 8830: 		width:32px;
 8831: 		height:32px;
 8832: 		right:8px;
 8833: 		top:8px;
 8834: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8835: 		text-indent:-99999px;
 8836: 		overflow:hidden;
 8837: 		cursor:pointer;
 8838: }
 8839: 
 8840: .LCisDisabled {
 8841:   cursor: not-allowed;
 8842:   opacity: 0.5;
 8843: }
 8844: 
 8845: a[aria-disabled="true"] {
 8846:   color: currentColor;
 8847:   display: inline-block;  /* For IE11/ MS Edge bug */
 8848:   pointer-events: none;
 8849:   text-decoration: none;
 8850: }
 8851: 
 8852: pre.LC_wordwrap {
 8853:   white-space: pre-wrap;
 8854:   white-space: -moz-pre-wrap;
 8855:   white-space: -pre-wrap;
 8856:   white-space: -o-pre-wrap;
 8857:   word-wrap: break-word;
 8858: }
 8859: 
 8860: /*
 8861:   styles used for response display
 8862: */
 8863: div.LC_radiofoil, div.LC_rankfoil {
 8864:   margin: .5em 0em .5em 0em;
 8865: }
 8866: table.LC_itemgroup {
 8867:   margin-top: 1em;
 8868: }
 8869: 
 8870: /*
 8871:   styles used by TTH when "Default set of options to pass to tth/m
 8872:   when converting TeX" in course settings has been set
 8873: 
 8874:   option passed: -t
 8875: 
 8876: */
 8877: 
 8878: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8879: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8880: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8881: td div.norm {line-height:normal;}
 8882: 
 8883: /*
 8884:   option passed -y3
 8885: */
 8886: 
 8887: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8888: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8889: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8890: 
 8891: /*
 8892:   sections with roles, for content only
 8893: */
 8894: section[class^="role-"] {
 8895:   padding-left: 10px;
 8896:   padding-right: 5px;
 8897:   margin-top: 8px;
 8898:   margin-bottom: 8px;
 8899:   border: 1px solid #2A4;
 8900:   border-radius: 5px;
 8901:   box-shadow: 0px 1px 1px #BBB;
 8902: }
 8903: section[class^="role-"]>h1 {
 8904:   position: relative;
 8905:   margin: 0px;
 8906:   padding-top: 10px;
 8907:   padding-left: 40px;
 8908: }
 8909: section[class^="role-"]>h1:before {
 8910:   position: absolute;
 8911:   left: -5px;
 8912:   top: 5px;
 8913: }
 8914: section.role-activity>h1:before {
 8915:   content:url('/adm/daxe/images/section_icons/activity.png');
 8916: }
 8917: section.role-advice>h1:before {
 8918:   content:url('/adm/daxe/images/section_icons/advice.png');
 8919: }
 8920: section.role-bibliography>h1:before {
 8921:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8922: }
 8923: section.role-citation>h1:before {
 8924:   content:url('/adm/daxe/images/section_icons/citation.png');
 8925: }
 8926: section.role-conclusion>h1:before {
 8927:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8928: }
 8929: section.role-definition>h1:before {
 8930:   content:url('/adm/daxe/images/section_icons/definition.png');
 8931: }
 8932: section.role-demonstration>h1:before {
 8933:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8934: }
 8935: section.role-example>h1:before {
 8936:   content:url('/adm/daxe/images/section_icons/example.png');
 8937: }
 8938: section.role-explanation>h1:before {
 8939:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8940: }
 8941: section.role-introduction>h1:before {
 8942:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8943: }
 8944: section.role-method>h1:before {
 8945:   content:url('/adm/daxe/images/section_icons/method.png');
 8946: }
 8947: section.role-more_information>h1:before {
 8948:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8949: }
 8950: section.role-objectives>h1:before {
 8951:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8952: }
 8953: section.role-prerequisites>h1:before {
 8954:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8955: }
 8956: section.role-remark>h1:before {
 8957:   content:url('/adm/daxe/images/section_icons/remark.png');
 8958: }
 8959: section.role-reminder>h1:before {
 8960:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8961: }
 8962: section.role-summary>h1:before {
 8963:   content:url('/adm/daxe/images/section_icons/summary.png');
 8964: }
 8965: section.role-syntax>h1:before {
 8966:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8967: }
 8968: section.role-warning>h1:before {
 8969:   content:url('/adm/daxe/images/section_icons/warning.png');
 8970: }
 8971: 
 8972: #LC_minitab_header {
 8973:   float:left;
 8974:   width:100%;
 8975:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8976:   font-size:93%;
 8977:   line-height:normal;
 8978:   margin: 0.5em 0 0.5em 0;
 8979: }
 8980: #LC_minitab_header ul {
 8981:   margin:0;
 8982:   padding:10px 10px 0;
 8983:   list-style:none;
 8984: }
 8985: #LC_minitab_header li {
 8986:   float:left;
 8987:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8988:   margin:0;
 8989:   padding:0 0 0 9px;
 8990: }
 8991: #LC_minitab_header a {
 8992:   display:block;
 8993:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8994:   padding:5px 15px 4px 6px;
 8995: }
 8996: #LC_minitab_header #LC_current_minitab {
 8997:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8998: }
 8999: #LC_minitab_header #LC_current_minitab a {
 9000:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 9001:   padding-bottom:5px;
 9002: }
 9003: 
 9004: 
 9005: END
 9006: }
 9007: 
 9008: =pod
 9009: 
 9010: =item * &headtag()
 9011: 
 9012: Returns a uniform footer for LON-CAPA web pages.
 9013: 
 9014: Inputs: $title - optional title for the head
 9015:         $head_extra - optional extra HTML to put inside the <head>
 9016:         $args - optional arguments
 9017:             force_register - if is true call registerurl so the remote is 
 9018:                              informed
 9019:             redirect       -> array ref of
 9020:                                    1- seconds before redirect occurs
 9021:                                    2- url to redirect to
 9022:                                    3- whether the side effect should occur
 9023:                            (side effect of setting 
 9024:                                $env{'internal.head.redirect'} to the url 
 9025:                                redirected to)
 9026:                                    4- whether the redirect target should be
 9027:                                       the opener of the current (pop-up)
 9028:                                       window (side effect of setting
 9029:                                       $env{'internal.head.to_opener'} to
 9030:                                       1, if true.
 9031:                                    5- whether encrypt check should be skipped
 9032:             domain         -> force to color decorate a page for a specific
 9033:                                domain
 9034:             function       -> force usage of a specific rolish color scheme
 9035:             bgcolor        -> override the default page bgcolor
 9036:             no_auto_mt_title
 9037:                            -> prevent &mt()ing the title arg
 9038: 
 9039: =cut
 9040: 
 9041: sub headtag {
 9042:     my ($title,$head_extra,$args) = @_;
 9043:     
 9044:     my $function = $args->{'function'} || &get_users_function();
 9045:     my $domain   = $args->{'domain'}   || &determinedomain();
 9046:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 9047:     my $httphost = $args->{'use_absolute'};
 9048:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 9049: 		   $Apache::lonnet::perlvar{'lonVersion'},
 9050: 		   #time(),
 9051: 		   $env{'environment.color.timestamp'},
 9052: 		   $function,$domain,$bgcolor);
 9053: 
 9054:     $url = '/adm/css/'.&escape($url).'.css';
 9055: 
 9056:     my $result =
 9057: 	'<head>'.
 9058: 	&font_settings($args);
 9059: 
 9060:     my $inhibitprint;
 9061:     if ($args->{'print_suppress'}) {
 9062:         $inhibitprint = &print_suppression();
 9063:     }
 9064: 
 9065:     if (!$args->{'frameset'}) {
 9066: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 9067:     }
 9068:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 9069:         $result .= Apache::lonxml::display_title();
 9070:     }
 9071:     if (!$args->{'no_nav_bar'} 
 9072: 	&& !$args->{'only_body'}
 9073: 	&& !$args->{'frameset'}) {
 9074: 	$result .= &help_menu_js($httphost);
 9075:         $result.=&modal_window();
 9076:         $result.=&togglebox_script();
 9077:         $result.=&wishlist_window();
 9078:         $result.=&LCprogressbarUpdate_script();
 9079:     } else {
 9080:         if ($args->{'add_modal'}) {
 9081:            $result.=&modal_window();
 9082:         }
 9083:         if ($args->{'add_wishlist'}) {
 9084:            $result.=&wishlist_window();
 9085:         }
 9086:         if ($args->{'add_togglebox'}) {
 9087:            $result.=&togglebox_script();
 9088:         }
 9089:         if ($args->{'add_progressbar'}) {
 9090:            $result.=&LCprogressbarUpdate_script();
 9091:         }
 9092:     }
 9093:     if (ref($args->{'redirect'})) {
 9094: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 9095:         if (!$skip_enc_check) {
 9096:             $url = &Apache::lonenc::check_encrypt($url);
 9097:         }
 9098: 	if (!$inhibit_continue) {
 9099: 	    $env{'internal.head.redirect'} = $url;
 9100: 	}
 9101: 	$result.=<<"ADDMETA";
 9102: <meta http-equiv="pragma" content="no-cache" />
 9103: ADDMETA
 9104:         if ($to_opener) {
 9105:             $env{'internal.head.to_opener'} = 1;
 9106:             my $dest = &js_escape($url);
 9107:             my $timeout = int($time * 1000);
 9108:             $result .=<<"ENDJS";
 9109: <script type="text/javascript">
 9110: // <![CDATA[
 9111: function LC_To_Opener() {
 9112:     var dest = '$dest';
 9113:     if (dest != '') {
 9114:         if (window.opener != null && !window.opener.closed) {
 9115:             window.opener.location.href=dest;
 9116:             window.close();
 9117:         } else {
 9118:             window.location.href=dest;
 9119:         }
 9120:     }
 9121: }
 9122: \$(document).ready(function () {
 9123:     setTimeout('LC_To_Opener()',$timeout);
 9124: });
 9125: // ]]>
 9126: </script>
 9127: ENDJS
 9128:         } else {
 9129:             $result.=<<"ADDMETA";
 9130: <meta http-equiv="Refresh" content="$time; url=$url" />
 9131: ADDMETA
 9132:         }
 9133:     } else {
 9134:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 9135:             my $requrl = $env{'request.uri'};
 9136:             if ($requrl eq '') {
 9137:                 $requrl = $ENV{'REQUEST_URI'};
 9138:                 $requrl =~ s/\?.+$//;
 9139:             }
 9140:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 9141:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 9142:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 9143:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 9144:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 9145:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 9146:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 9147:                     my ($offload,$offloadoth);
 9148:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 9149:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 9150:                             $offload = 1;
 9151:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9152:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9153:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9154:                                     $offloadoth = 1;
 9155:                                     $dom_in_use = $env{'user.domain'};
 9156:                                 }
 9157:                             }
 9158:                         }
 9159:                     }
 9160:                     unless ($offload) {
 9161:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 9162:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 9163:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9164:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9165:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9166:                                         $offload = 1;
 9167:                                         $offloadoth = 1;
 9168:                                         $dom_in_use = $env{'user.domain'};
 9169:                                     }
 9170:                                 }
 9171:                             }
 9172:                         }
 9173:                     }
 9174:                     if ($offload) {
 9175:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 9176:                         if (($newserver eq '') && ($offloadoth)) {
 9177:                             my @domains = &Apache::lonnet::current_machine_domains();
 9178:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 9179:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 9180:                             }
 9181:                         }
 9182:                         if (($newserver) && ($newserver ne $lonhost)) {
 9183:                             my $numsec = 5;
 9184:                             my $timeout = $numsec * 1000;
 9185:                             my ($newurl,$locknum,%locks,$msg);
 9186:                             if ($env{'request.role.adv'}) {
 9187:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 9188:                             }
 9189:                             my $disable_submit = 0;
 9190:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 9191:                                 $disable_submit = 1;
 9192:                             }
 9193:                             if ($locknum) {
 9194:                                 my @lockinfo = sort(values(%locks));
 9195:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 9196:                                        join(", ",sort(values(%locks)))."\n";
 9197:                                 if (&show_course()) {
 9198:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 9199:                                 } else {
 9200:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 9201:                                 }
 9202:                             } else {
 9203:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 9204:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 9205:                                 }
 9206:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 9207:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 9208:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 9209:                                     $newurl .= '&role='.$env{'request.role'};
 9210:                                 }
 9211:                                 if ($env{'request.symb'}) {
 9212:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 9213:                                     if ($shownsymb =~ m{^/enc/}) {
 9214:                                         my $reqdmajor = 2;
 9215:                                         my $reqdminor = 11;
 9216:                                         my $reqdsubminor = 3;
 9217:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 9218:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 9219:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 9220:                                         if (($major eq '' && $minor eq '') ||
 9221:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 9222:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 9223:                                              ($reqdsubminor > $subminor))))) {
 9224:                                             undef($shownsymb);
 9225:                                         }
 9226:                                     }
 9227:                                     if ($shownsymb) {
 9228:                                         &js_escape(\$shownsymb);
 9229:                                         $newurl .= '&symb='.$shownsymb;
 9230:                                     }
 9231:                                 } else {
 9232:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 9233:                                     &js_escape(\$shownurl);
 9234:                                     $newurl .= '&origurl='.$shownurl;
 9235:                                 }
 9236:                             }
 9237:                             &js_escape(\$msg);
 9238:                             $result.=<<OFFLOAD
 9239: <meta http-equiv="pragma" content="no-cache" />
 9240: <script type="text/javascript">
 9241: // <![CDATA[
 9242: function LC_Offload_Now() {
 9243:     var dest = "$newurl";
 9244:     if (dest != '') {
 9245:         window.location.href="$newurl";
 9246:     }
 9247: }
 9248: \$(document).ready(function () {
 9249:     window.alert('$msg');
 9250:     if ($disable_submit) {
 9251:         \$(".LC_hwk_submit").prop("disabled", true);
 9252:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 9253:     }
 9254:     setTimeout('LC_Offload_Now()', $timeout);
 9255: });
 9256: // ]]>
 9257: </script>
 9258: OFFLOAD
 9259:                         }
 9260:                     }
 9261:                 }
 9262:             }
 9263:         }
 9264:     }
 9265:     if (!defined($title)) {
 9266: 	$title = 'The LearningOnline Network with CAPA';
 9267:     }
 9268:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 9269:     $result .= '<title> LON-CAPA '.$title.'</title>'
 9270: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 9271:     if (!$args->{'frameset'}) {
 9272:         $result .= ' /';
 9273:     }
 9274:     $result .= '>' 
 9275:         .$inhibitprint
 9276: 	.$head_extra;
 9277:     my $clientmobile;
 9278:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 9279:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 9280:     } else {
 9281:         $clientmobile = $env{'browser.mobile'};
 9282:     }
 9283:     if ($clientmobile) {
 9284:         $result .= '
 9285: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 9286: <meta name="apple-mobile-web-app-capable" content="yes" />';
 9287:     }
 9288:     $result .= '<meta name="google" content="notranslate" />'."\n";
 9289:     return $result.'</head>';
 9290: }
 9291: 
 9292: =pod
 9293: 
 9294: =item * &font_settings()
 9295: 
 9296: Returns neccessary <meta> to set the proper encoding
 9297: 
 9298: Inputs: optional reference to HASH -- $args passed to &headtag()
 9299: 
 9300: =cut
 9301: 
 9302: sub font_settings {
 9303:     my ($args) = @_;
 9304:     my $headerstring='';
 9305:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 9306:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 9307:         $headerstring.=
 9308:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 9309:         if (!$args->{'frameset'}) {
 9310: 	    $headerstring.= ' /';
 9311:         }
 9312: 	$headerstring .= '>'."\n";
 9313:     }
 9314:     return $headerstring;
 9315: }
 9316: 
 9317: =pod
 9318: 
 9319: =item * &print_suppression()
 9320: 
 9321: In course context returns css which causes the body to be blank when media="print",
 9322: if printout generation is unavailable for the current resource.
 9323: 
 9324: This could be because:
 9325: 
 9326: (a) printstartdate is in the future
 9327: 
 9328: (b) printenddate is in the past
 9329: 
 9330: (c) there is an active exam block with "printout"
 9331: functionality blocked
 9332: 
 9333: Users with pav, pfo or evb privileges are exempt.
 9334: 
 9335: Inputs: none
 9336: 
 9337: =cut
 9338: 
 9339: 
 9340: sub print_suppression {
 9341:     my $noprint;
 9342:     if ($env{'request.course.id'}) {
 9343:         my $scope = $env{'request.course.id'};
 9344:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9345:             (&Apache::lonnet::allowed('pfo',$scope))) {
 9346:             return;
 9347:         }
 9348:         if ($env{'request.course.sec'} ne '') {
 9349:             $scope .= "/$env{'request.course.sec'}";
 9350:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9351:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 9352:                 return;
 9353:             }
 9354:         }
 9355:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9356:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9357:         my $clientip = &Apache::lonnet::get_requestor_ip();
 9358:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 9359:         if ($blocked) {
 9360:             my $checkrole = "cm./$cdom/$cnum";
 9361:             if ($env{'request.course.sec'} ne '') {
 9362:                 $checkrole .= "/$env{'request.course.sec'}";
 9363:             }
 9364:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 9365:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 9366:                 $noprint = 1;
 9367:             }
 9368:         }
 9369:         unless ($noprint) {
 9370:             my $symb = &Apache::lonnet::symbread();
 9371:             if ($symb ne '') {
 9372:                 my $navmap = Apache::lonnavmaps::navmap->new();
 9373:                 if (ref($navmap)) {
 9374:                     my $res = $navmap->getBySymb($symb);
 9375:                     if (ref($res)) {
 9376:                         if (!$res->resprintable()) {
 9377:                             $noprint = 1;
 9378:                         }
 9379:                     }
 9380:                 }
 9381:             }
 9382:         }
 9383:         if ($noprint) {
 9384:             return <<"ENDSTYLE";
 9385: <style type="text/css" media="print">
 9386:     body { display:none }
 9387: </style>
 9388: ENDSTYLE
 9389:         }
 9390:     }
 9391:     return;
 9392: }
 9393: 
 9394: =pod
 9395: 
 9396: =item * &xml_begin()
 9397: 
 9398: Returns the needed doctype and <html>
 9399: 
 9400: Inputs: none
 9401: 
 9402: =cut
 9403: 
 9404: sub xml_begin {
 9405:     my ($is_frameset) = @_;
 9406:     my $output='';
 9407: 
 9408:     if ($env{'browser.mathml'}) {
 9409: 	$output='<?xml version="1.0"?>'
 9410:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 9411: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 9412:             
 9413: #	    .'<!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">] >'
 9414: 	    .'<!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">'
 9415:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 9416: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 9417:     } elsif ($is_frameset) {
 9418:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 9419:                 '<html>'."\n";
 9420:     } else {
 9421: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 9422:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 9423:     }
 9424:     return $output;
 9425: }
 9426: 
 9427: =pod
 9428: 
 9429: =item * &start_page()
 9430: 
 9431: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 9432: 
 9433: Inputs:
 9434: 
 9435: =over 4
 9436: 
 9437: $title - optional title for the page
 9438: 
 9439: $head_extra - optional extra HTML to incude inside the <head>
 9440: 
 9441: $args - additional optional args supported are:
 9442: 
 9443: =over 8
 9444: 
 9445:              only_body      -> is true will set &bodytag() onlybodytag
 9446:                                     arg on
 9447:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 9448:              add_entries    -> additional attributes to add to the  <body>
 9449:              domain         -> force to color decorate a page for a 
 9450:                                     specific domain
 9451:              function       -> force usage of a specific rolish color
 9452:                                     scheme
 9453:              redirect       -> see &headtag()
 9454:              bgcolor        -> override the default page bg color
 9455:              js_ready       -> return a string ready for being used in 
 9456:                                     a javascript writeln
 9457:              html_encode    -> return a string ready for being used in 
 9458:                                     a html attribute
 9459:              force_register -> if is true will turn on the &bodytag()
 9460:                                     $forcereg arg
 9461:              frameset       -> if true will start with a <frameset>
 9462:                                     rather than <body>
 9463:              skip_phases    -> hash ref of 
 9464:                                     head -> skip the <html><head> generation
 9465:                                     body -> skip all <body> generation
 9466:              no_auto_mt_title -> prevent &mt()ing the title arg
 9467:              bread_crumbs ->             Array containing breadcrumbs
 9468:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 9469:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 9470:                                     to lonhtmlcommon::breadcrumbs
 9471:              group          -> includes the current group, if page is for a 
 9472:                                specific group
 9473:              use_absolute   -> for request for external resource or syllabus, this
 9474:                                will contain https://<hostname> if server uses
 9475:                                https (as per hosts.tab), but request is for http
 9476:              hostname       -> hostname, originally from $r->hostname(), (optional).
 9477:              links_disabled -> Links in primary and secondary menus are disabled
 9478:                                (Can enable them once page has loaded - see lonroles.pm
 9479:                                for an example).
 9480:              links_target   -> Target for links, e.g., _parent (optional).
 9481: 
 9482: =back
 9483: 
 9484: =back
 9485: 
 9486: =cut
 9487: 
 9488: sub start_page {
 9489:     my ($title,$head_extra,$args) = @_;
 9490:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 9491: 
 9492:     $env{'internal.start_page'}++;
 9493:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 9494: 
 9495:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 9496:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 9497:     }
 9498: 
 9499:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 9500:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 9501:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 9502:                 $args->{'no_primary_menu'} = 1;
 9503:             }
 9504:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 9505:                 $args->{'no_inline_menu'} = 1;
 9506:             }
 9507:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 9508:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 9509:             }
 9510:         } else {
 9511:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9512:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 9513:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 9514:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 9515:                     $args->{'no_primary_menu'} = 1;
 9516:                 }
 9517:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 9518:                     $args->{'no_inline_menu'} = 1;
 9519:                 }
 9520:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 9521:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 9522:                 }
 9523:             }
 9524:         }
 9525:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 9526:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 9527:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 9528:     } elsif ($env{'request.course.id'}) {
 9529:         my $expiretime=600;
 9530:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 9531:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 9532:         }
 9533:         my ($deeplinkmenu,$menuref);
 9534:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 9535:         if ($menucoll) {
 9536:             if (ref($menuref) eq 'HASH') {
 9537:                 %menu = %{$menuref};
 9538:             }
 9539:             if ($menu{'top'} eq 'n') {
 9540:                 $args->{'no_primary_menu'} = 1;
 9541:             }
 9542:             if ($menu{'inline'} eq 'n') {
 9543:                 unless (&Apache::lonnet::allowed('opa')) {
 9544:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9545:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9546:                     my $crstype = &course_type();
 9547:                     my $now = time;
 9548:                     my $ccrole;
 9549:                     if ($crstype eq 'Community') {
 9550:                         $ccrole = 'co';
 9551:                     } else {
 9552:                         $ccrole = 'cc';
 9553:                     }
 9554:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 9555:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 9556:                         if ((($start) && ($start<0)) ||
 9557:                             (($end) && ($end<$now))  ||
 9558:                             (($start) && ($now<$start))) {
 9559:                             $args->{'no_inline_menu'} = 1;
 9560:                         }
 9561:                     } else {
 9562:                         $args->{'no_inline_menu'} = 1;
 9563:                     }
 9564:                 }
 9565:             }
 9566:         }
 9567:     }
 9568: 
 9569:     my $showncrumbs;
 9570:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 9571: 	if ($args->{'frameset'}) {
 9572: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 9573: 						$args->{'add_entries'});
 9574: 	    $result .= "\n<frameset $attr_string>\n";
 9575:         } else {
 9576:             $result .=
 9577:                 &bodytag($title, 
 9578:                          $args->{'function'},       $args->{'add_entries'},
 9579:                          $args->{'only_body'},      $args->{'domain'},
 9580:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 9581:                          $args->{'bgcolor'},        $args,
 9582:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
 9583:                          \%menu,\$showncrumbs);
 9584:         }
 9585:     }
 9586: 
 9587:     if ($args->{'js_ready'}) {
 9588: 		$result = &js_ready($result);
 9589:     }
 9590:     if ($args->{'html_encode'}) {
 9591: 		$result = &html_encode($result);
 9592:     }
 9593: 
 9594:     # Preparation for new and consistent functionlist at top of screen
 9595:     # if ($args->{'functionlist'}) {
 9596:     #            $result .= &build_functionlist();
 9597:     #}
 9598: 
 9599:     # Don't add anything more if only_body wanted or in const space
 9600:     return $result if    $args->{'only_body'} 
 9601:                       || $env{'request.state'} eq 'construct';
 9602: 
 9603:     #Breadcrumbs
 9604:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 9605:         unless ($showncrumbs) {
 9606: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 9607: 		#if any br links exists, add them to the breadcrumbs
 9608: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9609: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9610: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9611: 			}
 9612: 		}
 9613:                 # if @advtools array contains items add then to the breadcrumbs
 9614:                 if (@advtools > 0) {
 9615:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9616:                 }
 9617:                 my $menulink;
 9618:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9619:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9620:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 9621:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 9622:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 9623:                      (!$env{'request.role.adv'}))) {
 9624:                     $menulink = 0;
 9625:                 } else {
 9626:                     undef($menulink);
 9627:                 }
 9628:                 my $linkprotout;
 9629:                 if ($env{'request.deeplink.login'}) {
 9630:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 9631:                     if ($linkprotout) {
 9632:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 9633:                     }
 9634:                 }
 9635: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9636: 		if(exists($args->{'bread_crumbs_component'})){
 9637: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9638:                 } else {
 9639: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9640: 		}
 9641:         }
 9642:     }
 9643:     return $result;
 9644: }
 9645: 
 9646: sub end_page {
 9647:     my ($args) = @_;
 9648:     $env{'internal.end_page'}++;
 9649:     my $result;
 9650:     if ($args->{'discussion'}) {
 9651: 	my ($target,$parser);
 9652: 	if (ref($args->{'discussion'})) {
 9653: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9654: 				$args->{'discussion'}{'parser'});
 9655: 	}
 9656: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9657:     }
 9658:     if ($args->{'frameset'}) {
 9659: 	$result .= '</frameset>';
 9660:     } else {
 9661: 	$result .= &endbodytag($args);
 9662:     }
 9663:     unless ($args->{'notbody'}) {
 9664:         $result .= "\n</html>";
 9665:     }
 9666: 
 9667:     if ($args->{'js_ready'}) {
 9668: 	$result = &js_ready($result);
 9669:     }
 9670: 
 9671:     if ($args->{'html_encode'}) {
 9672: 	$result = &html_encode($result);
 9673:     }
 9674: 
 9675:     return $result;
 9676: }
 9677: 
 9678: sub menucoll_in_effect {
 9679:     my ($menucoll,$deeplinkmenu,%menu);
 9680:     if ($env{'request.course.id'}) {
 9681:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9682:         if ($env{'request.deeplink.login'}) {
 9683:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9684:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9685:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9686:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9687:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9688:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9689:                     if (ref($navmap)) {
 9690:                         $deeplink = $navmap->get_mapparam(undef,
 9691:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9692:                                                           '0.deeplink');
 9693:                     } else {
 9694:                         $check_login_symb = 1;
 9695:                     }
 9696:                 } else {
 9697:                     my $symb = &Apache::lonnet::symbread();
 9698:                     if ($symb) {
 9699:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9700:                     } else {
 9701:                         $check_login_symb = 1;
 9702:                     }
 9703:                 }
 9704:             } else {
 9705:                 $check_login_symb = 1;
 9706:             }
 9707:             if ($check_login_symb) {
 9708:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9709:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9710:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9711:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9712:                     if (ref($navmap)) {
 9713:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9714:                     }
 9715:                 } else {
 9716:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9717:                 }
 9718:             }
 9719:             if ($deeplink ne '') {
 9720:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9721:                 if ($display =~ /^\d+$/) {
 9722:                     $deeplinkmenu = 1;
 9723:                     $menucoll = $display;
 9724:                 }
 9725:             }
 9726:         }
 9727:         if ($menucoll) {
 9728:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9729:         }
 9730:     }
 9731:     return ($menucoll,$deeplinkmenu,\%menu);
 9732: }
 9733: 
 9734: sub deeplink_login_symb {
 9735:     my ($cnum,$cdom) = @_;
 9736:     my $login_symb;
 9737:     if ($env{'request.deeplink.login'}) {
 9738:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9739:     }
 9740:     return $login_symb;
 9741: }
 9742: 
 9743: sub symb_from_tinyurl {
 9744:     my ($url,$cnum,$cdom) = @_;
 9745:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9746:         my $key = $1;
 9747:         my ($tinyurl,$login);
 9748:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9749:         if (defined($cached)) {
 9750:             $tinyurl = $result;
 9751:         } else {
 9752:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9753:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9754:             if ($currtiny{$key} ne '') {
 9755:                 $tinyurl = $currtiny{$key};
 9756:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9757:             }
 9758:         }
 9759:         if ($tinyurl ne '') {
 9760:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9761:             if (wantarray) {
 9762:                 return ($cnumreq,$symb);
 9763:             } elsif ($cnumreq eq $cnum) {
 9764:                 return $symb;
 9765:             }
 9766:         }
 9767:     }
 9768:     if (wantarray) {
 9769:         return ();
 9770:     } else {
 9771:         return;
 9772:     }
 9773: }
 9774: 
 9775: sub usable_exttools {
 9776:     my %tooltypes;
 9777:     if ($env{'request.course.id'}) {
 9778:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
 9779:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
 9780:                %tooltypes = (
 9781:                              crs => 1,
 9782:                              dom => 1,
 9783:                             );
 9784:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
 9785:                $tooltypes{'crs'} = 1;
 9786:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
 9787:                $tooltypes{'dom'} = 1;
 9788:            }
 9789:         } else {
 9790:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9791:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9792:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9793:             if ($crstype eq '') {
 9794:                 $crstype = 'course';
 9795:             }
 9796:             if ($crstype eq 'course') {
 9797:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
 9798:                     $crstype = 'official';
 9799:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
 9800:                     $crstype = 'textbook';
 9801:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
 9802:                     $crstype = 'lti';
 9803:                 } else {
 9804:                     $crstype = 'unofficial';
 9805:                 }
 9806:             }
 9807:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 9808:             if ($domdefaults{$crstype.'domexttool'}) {
 9809:                 $tooltypes{'dom'} = 1;
 9810:             }
 9811:             if ($domdefaults{$crstype.'exttool'}) {
 9812:                 $tooltypes{'crs'} = 1;
 9813:             }
 9814:         }
 9815:     }
 9816:     return %tooltypes;
 9817: }
 9818: 
 9819: sub wishlist_window {
 9820:     return(<<'ENDWISHLIST');
 9821: <script type="text/javascript">
 9822: // <![CDATA[
 9823: // <!-- BEGIN LON-CAPA Internal
 9824: function set_wishlistlink(title, path) {
 9825:     if (!title) {
 9826:         title = document.title;
 9827:         title = title.replace(/^LON-CAPA /,'');
 9828:     }
 9829:     title = encodeURIComponent(title);
 9830:     title = title.replace("'","\\\'");
 9831:     if (!path) {
 9832:         path = location.pathname;
 9833:     }
 9834:     path = encodeURIComponent(path);
 9835:     path = path.replace("'","\\\'");
 9836:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9837:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9838: }
 9839: // END LON-CAPA Internal -->
 9840: // ]]>
 9841: </script>
 9842: ENDWISHLIST
 9843: }
 9844: 
 9845: sub modal_window {
 9846:     return(<<'ENDMODAL');
 9847: <script type="text/javascript">
 9848: // <![CDATA[
 9849: // <!-- BEGIN LON-CAPA Internal
 9850: var modalWindow = {
 9851: 	parent:"body",
 9852: 	windowId:null,
 9853: 	content:null,
 9854: 	width:null,
 9855: 	height:null,
 9856: 	close:function()
 9857: 	{
 9858: 	        $(".LCmodal-window").remove();
 9859: 	        $(".LCmodal-overlay").remove();
 9860: 	},
 9861: 	open:function()
 9862: 	{
 9863: 		var modal = "";
 9864: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9865: 		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;\">";
 9866: 		modal += this.content;
 9867: 		modal += "</div>";	
 9868: 
 9869: 		$(this.parent).append(modal);
 9870: 
 9871: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9872: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9873: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9874: 	}
 9875: };
 9876: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9877: 	{
 9878:                 source = source.replace(/'/g,"&#39;");
 9879: 		modalWindow.windowId = "myModal";
 9880: 		modalWindow.width = width;
 9881: 		modalWindow.height = height;
 9882: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9883: 		modalWindow.open();
 9884: 	};
 9885: // END LON-CAPA Internal -->
 9886: // ]]>
 9887: </script>
 9888: ENDMODAL
 9889: }
 9890: 
 9891: sub modal_link {
 9892:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9893:     unless ($width) { $width=480; }
 9894:     unless ($height) { $height=400; }
 9895:     unless ($scrolling) { $scrolling='yes'; }
 9896:     unless ($transparency) { $transparency='true'; }
 9897: 
 9898:     my $target_attr;
 9899:     if (defined($target)) {
 9900:         $target_attr = 'target="'.$target.'"';
 9901:     }
 9902:     return <<"ENDLINK";
 9903: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9904: ENDLINK
 9905: }
 9906: 
 9907: sub modal_adhoc_script {
 9908:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9909:     my $mathjax;
 9910:     if ($possmathjax) {
 9911:         $mathjax = <<'ENDJAX';
 9912:                if (typeof MathJax == 'object') {
 9913:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 9914:                }
 9915: ENDJAX
 9916:     }
 9917:     return (<<ENDADHOC);
 9918: <script type="text/javascript">
 9919: // <![CDATA[
 9920:         var $funcname = function()
 9921:         {
 9922:                 modalWindow.windowId = "myModal";
 9923:                 modalWindow.width = $width;
 9924:                 modalWindow.height = $height;
 9925:                 modalWindow.content = '$content';
 9926:                 modalWindow.open();
 9927:                 $mathjax
 9928:         };  
 9929: // ]]>
 9930: </script>
 9931: ENDADHOC
 9932: }
 9933: 
 9934: sub modal_adhoc_inner {
 9935:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9936:     my $innerwidth=$width-20;
 9937:     $content=&js_ready(
 9938:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9939:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9940:                  $content.
 9941:                  &end_scrollbox().
 9942:                  &end_page()
 9943:              );
 9944:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 9945: }
 9946: 
 9947: sub modal_adhoc_window {
 9948:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 9949:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 9950:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9951: }
 9952: 
 9953: sub modal_adhoc_launch {
 9954:     my ($funcname,$width,$height,$content)=@_;
 9955:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9956: <script type="text/javascript">
 9957: // <![CDATA[
 9958: $funcname();
 9959: // ]]>
 9960: </script>
 9961: ENDLAUNCH
 9962: }
 9963: 
 9964: sub modal_adhoc_close {
 9965:     return (<<ENDCLOSE);
 9966: <script type="text/javascript">
 9967: // <![CDATA[
 9968: modalWindow.close();
 9969: // ]]>
 9970: </script>
 9971: ENDCLOSE
 9972: }
 9973: 
 9974: sub togglebox_script {
 9975:    return(<<ENDTOGGLE);
 9976: <script type="text/javascript"> 
 9977: // <![CDATA[
 9978: function LCtoggleDisplay(id,hidetext,showtext) {
 9979:    link = document.getElementById(id + "link").childNodes[0];
 9980:    with (document.getElementById(id).style) {
 9981:       if (display == "none" ) {
 9982:           display = "inline";
 9983:           link.nodeValue = hidetext;
 9984:         } else {
 9985:           display = "none";
 9986:           link.nodeValue = showtext;
 9987:        }
 9988:    }
 9989: }
 9990: // ]]>
 9991: </script>
 9992: ENDTOGGLE
 9993: }
 9994: 
 9995: sub start_togglebox {
 9996:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9997:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9998:     unless ($showtext) { $showtext=&mt('show'); }
 9999:     unless ($hidetext) { $hidetext=&mt('hide'); }
10000:     unless ($headerbg) { $headerbg='#FFFFFF'; }
10001:     return &start_data_table().
10002:            &start_data_table_header_row().
10003:            '<td bgcolor="'.$headerbg.'">'.$heading.
10004:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
10005:            $showtext.'\')">'.$showtext.'</a>]</td>'.
10006:            &end_data_table_header_row().
10007:            '<tr id="'.$id.'" style="display:none""><td>';
10008: }
10009: 
10010: sub end_togglebox {
10011:     return '</td></tr>'.&end_data_table();
10012: }
10013: 
10014: sub LCprogressbar_script {
10015:    my ($id,$number_to_do)=@_;
10016:    if ($number_to_do) {
10017:        return(<<ENDPROGRESS);
10018: <script type="text/javascript">
10019: // <![CDATA[
10020: \$('#progressbar$id').progressbar({
10021:   value: 0,
10022:   change: function(event, ui) {
10023:     var newVal = \$(this).progressbar('option', 'value');
10024:     \$('.pblabel', this).text(LCprogressTxt);
10025:   }
10026: });
10027: // ]]>
10028: </script>
10029: ENDPROGRESS
10030:    } else {
10031:        return(<<ENDPROGRESS);
10032: <script type="text/javascript">
10033: // <![CDATA[
10034: \$('#progressbar$id').progressbar({
10035:   value: false,
10036:   create: function(event, ui) {
10037:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
10038:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
10039:   }
10040: });
10041: // ]]>
10042: </script>
10043: ENDPROGRESS
10044:    }
10045: }
10046: 
10047: sub LCprogressbarUpdate_script {
10048:    return(<<ENDPROGRESSUPDATE);
10049: <style type="text/css">
10050: .ui-progressbar { position:relative; }
10051: .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%; }
10052: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
10053: </style>
10054: <script type="text/javascript">
10055: // <![CDATA[
10056: var LCprogressTxt='---';
10057: 
10058: function LCupdateProgress(percent,progresstext,id,maxnum) {
10059:    LCprogressTxt=progresstext;
10060:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
10061:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
10062:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
10063:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
10064:    } else {
10065:        \$('#progressbar'+id).progressbar('value',percent);
10066:    }
10067: }
10068: // ]]>
10069: </script>
10070: ENDPROGRESSUPDATE
10071: }
10072: 
10073: my $LClastpercent;
10074: my $LCidcnt;
10075: my $LCcurrentid;
10076: 
10077: sub LCprogressbar {
10078:     my ($r,$number_to_do,$preamble)=@_;
10079:     $LClastpercent=0;
10080:     $LCidcnt++;
10081:     $LCcurrentid=$$.'_'.$LCidcnt;
10082:     my ($starting,$content);
10083:     if ($number_to_do) {
10084:         $starting=&mt('Starting');
10085:         $content=(<<ENDPROGBAR);
10086: $preamble
10087:   <div id="progressbar$LCcurrentid">
10088:     <span class="pblabel">$starting</span>
10089:   </div>
10090: ENDPROGBAR
10091:     } else {
10092:         $starting=&mt('Loading...');
10093:         $LClastpercent='false';
10094:         $content=(<<ENDPROGBAR);
10095: $preamble
10096:   <div id="progressbar$LCcurrentid">
10097:       <div class="progress-label">$starting</div>
10098:   </div>
10099: ENDPROGBAR
10100:     }
10101:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
10102: }
10103: 
10104: sub LCprogressbarUpdate {
10105:     my ($r,$val,$text,$number_to_do)=@_;
10106:     if ($number_to_do) {
10107:         unless ($val) { 
10108:             if ($LClastpercent) {
10109:                 $val=$LClastpercent;
10110:             } else {
10111:                 $val=0;
10112:             }
10113:         }
10114:         if ($val<0) { $val=0; }
10115:         if ($val>100) { $val=0; }
10116:         $LClastpercent=$val;
10117:         unless ($text) { $text=$val.'%'; }
10118:     } else {
10119:         $val = 'false';
10120:     }
10121:     $text=&js_ready($text);
10122:     &r_print($r,<<ENDUPDATE);
10123: <script type="text/javascript">
10124: // <![CDATA[
10125: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
10126: // ]]>
10127: </script>
10128: ENDUPDATE
10129: }
10130: 
10131: sub LCprogressbarClose {
10132:     my ($r)=@_;
10133:     $LClastpercent=0;
10134:     &r_print($r,<<ENDCLOSE);
10135: <script type="text/javascript">
10136: // <![CDATA[
10137: \$("#progressbar$LCcurrentid").hide('slow'); 
10138: // ]]>
10139: </script>
10140: ENDCLOSE
10141: }
10142: 
10143: sub r_print {
10144:     my ($r,$to_print)=@_;
10145:     if ($r) {
10146:       $r->print($to_print);
10147:       $r->rflush();
10148:     } else {
10149:       print($to_print);
10150:     }
10151: }
10152: 
10153: sub html_encode {
10154:     my ($result) = @_;
10155: 
10156:     $result = &HTML::Entities::encode($result,'<>&"');
10157:     
10158:     return $result;
10159: }
10160: 
10161: sub js_ready {
10162:     my ($result) = @_;
10163: 
10164:     $result =~ s/[\n\r]/ /xmsg;
10165:     $result =~ s/\\/\\\\/xmsg;
10166:     $result =~ s/'/\\'/xmsg;
10167:     $result =~ s{</}{<\\/}xmsg;
10168:     
10169:     return $result;
10170: }
10171: 
10172: sub validate_page {
10173:     if (  exists($env{'internal.start_page'})
10174: 	  &&     $env{'internal.start_page'} > 1) {
10175: 	&Apache::lonnet::logthis('start_page called multiple times '.
10176: 				 $env{'internal.start_page'}.' '.
10177: 				 $ENV{'request.filename'});
10178:     }
10179:     if (  exists($env{'internal.end_page'})
10180: 	  &&     $env{'internal.end_page'} > 1) {
10181: 	&Apache::lonnet::logthis('end_page called multiple times '.
10182: 				 $env{'internal.end_page'}.' '.
10183: 				 $env{'request.filename'});
10184:     }
10185:     if (     exists($env{'internal.start_page'})
10186: 	&& ! exists($env{'internal.end_page'})) {
10187: 	&Apache::lonnet::logthis('start_page called without end_page '.
10188: 				 $env{'request.filename'});
10189:     }
10190:     if (   ! exists($env{'internal.start_page'})
10191: 	&&   exists($env{'internal.end_page'})) {
10192: 	&Apache::lonnet::logthis('end_page called without start_page'.
10193: 				 $env{'request.filename'});
10194:     }
10195: }
10196: 
10197: 
10198: sub start_scrollbox {
10199:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
10200:     unless ($outerwidth) { $outerwidth='520px'; }
10201:     unless ($width) { $width='500px'; }
10202:     unless ($height) { $height='200px'; }
10203:     my ($table_id,$div_id,$tdcol);
10204:     if ($id ne '') {
10205:         $table_id = ' id="table_'.$id.'"';
10206:         $div_id = ' id="div_'.$id.'"';
10207:     }
10208:     if ($bgcolor ne '') {
10209:         $tdcol = "background-color: $bgcolor;";
10210:     }
10211:     my $nicescroll_js;
10212:     if ($env{'browser.mobile'}) {
10213:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
10214:     }
10215:     return <<"END";
10216: $nicescroll_js
10217: 
10218: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
10219: <div style="overflow:auto; width:$width; height:$height;"$div_id>
10220: END
10221: }
10222: 
10223: sub end_scrollbox {
10224:     return '</div></td></tr></table>';
10225: }
10226: 
10227: sub nicescroll_javascript {
10228:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10229:     my %options;
10230:     if (ref($cursor) eq 'HASH') {
10231:         %options = %{$cursor};
10232:     }
10233:     unless ($options{'railalign'} =~ /^left|right$/) {
10234:         $options{'railalign'} = 'left';
10235:     }
10236:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10237:         my $function  = &get_users_function();
10238:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10239:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10240:             $options{'cursorcolor'} = '#00F';
10241:         }
10242:     }
10243:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10244:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10245:             $options{'cursoropacity'}='1.0';
10246:         }
10247:     } else {
10248:         $options{'cursoropacity'}='1.0';
10249:     }
10250:     if ($options{'cursorfixedheight'} eq 'none') {
10251:         delete($options{'cursorfixedheight'});
10252:     } else {
10253:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10254:     }
10255:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10256:         delete($options{'railoffset'});
10257:     }
10258:     my @niceoptions;
10259:     while (my($key,$value) = each(%options)) {
10260:         if ($value =~ /^\{.+\}$/) {
10261:             push(@niceoptions,$key.':'.$value);
10262:         } else {
10263:             push(@niceoptions,$key.':"'.$value.'"');
10264:         }
10265:     }
10266:     my $nicescroll_js = '
10267: $(document).ready(
10268:       function() {
10269:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10270:       }
10271: );
10272: ';
10273:     if ($framecheck) {
10274:         $nicescroll_js .= '
10275: function expand_div(caller) {
10276:     if (top === self) {
10277:         document.getElementById("'.$id.'").style.width = "auto";
10278:         document.getElementById("'.$id.'").style.height = "auto";
10279:     } else {
10280:         try {
10281:             if (parent.frames) {
10282:                 if (parent.frames.length > 1) {
10283:                     var framesrc = parent.frames[1].location.href;
10284:                     var currsrc = framesrc.replace(/\#.*$/,"");
10285:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
10286:                         document.getElementById("'.$id.'").style.width = "auto";
10287:                         document.getElementById("'.$id.'").style.height = "auto";
10288:                     }
10289:                 }
10290:             }
10291:         } catch (e) {
10292:             return;
10293:         }
10294:     }
10295:     return;
10296: }
10297: ';
10298:     }
10299:     if ($needjsready) {
10300:         $nicescroll_js = '
10301: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10302:     } else {
10303:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10304:     }
10305:     return $nicescroll_js;
10306: }
10307: 
10308: sub simple_error_page {
10309:     my ($r,$title,$msg,$args) = @_;
10310:     my %displayargs;
10311:     if (ref($args) eq 'HASH') {
10312:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10313:         if ($args->{'only_body'}) {
10314:             $displayargs{'only_body'} = 1;
10315:         }
10316:         if ($args->{'no_nav_bar'}) {
10317:             $displayargs{'no_nav_bar'} = 1;
10318:         }
10319:     } else {
10320:         $msg = &mt($msg);
10321:     }
10322: 
10323:     my $page =
10324: 	&Apache::loncommon::start_page($title,'',\%displayargs).
10325: 	'<p class="LC_error">'.$msg.'</p>'.
10326: 	&Apache::loncommon::end_page();
10327:     if (ref($r)) {
10328: 	$r->print($page);
10329: 	return;
10330:     }
10331:     return $page;
10332: }
10333: 
10334: {
10335:     my @row_count;
10336: 
10337:     sub start_data_table_count {
10338:         unshift(@row_count, 0);
10339:         return;
10340:     }
10341: 
10342:     sub end_data_table_count {
10343:         shift(@row_count);
10344:         return;
10345:     }
10346: 
10347:     sub start_data_table {
10348: 	my ($add_class,$id) = @_;
10349: 	my $css_class = (join(' ','LC_data_table',$add_class));
10350:         my $table_id;
10351:         if (defined($id)) {
10352:             $table_id = ' id="'.$id.'"';
10353:         }
10354: 	&start_data_table_count();
10355: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10356:     }
10357: 
10358:     sub end_data_table {
10359: 	&end_data_table_count();
10360: 	return '</table>'."\n";;
10361:     }
10362: 
10363:     sub start_data_table_row {
10364: 	my ($add_class, $id) = @_;
10365: 	$row_count[0]++;
10366: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10367: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10368:         $id = (' id="'.$id.'"') unless ($id eq '');
10369:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10370:     }
10371:     
10372:     sub continue_data_table_row {
10373: 	my ($add_class, $id) = @_;
10374: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10375: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10376:         $id = (' id="'.$id.'"') unless ($id eq '');
10377:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10378:     }
10379: 
10380:     sub end_data_table_row {
10381: 	return '</tr>'."\n";;
10382:     }
10383: 
10384:     sub start_data_table_empty_row {
10385: #	$row_count[0]++;
10386: 	return  '<tr class="LC_empty_row" >'."\n";;
10387:     }
10388: 
10389:     sub end_data_table_empty_row {
10390: 	return '</tr>'."\n";;
10391:     }
10392: 
10393:     sub start_data_table_header_row {
10394: 	return  '<tr class="LC_header_row">'."\n";;
10395:     }
10396: 
10397:     sub end_data_table_header_row {
10398: 	return '</tr>'."\n";;
10399:     }
10400: 
10401:     sub data_table_caption {
10402:         my $caption = shift;
10403:         return "<caption class=\"LC_caption\">$caption</caption>";
10404:     }
10405: }
10406: 
10407: =pod
10408: 
10409: =item * &inhibit_menu_check($arg)
10410: 
10411: Checks for a inhibitmenu state and generates output to preserve it
10412: 
10413: Inputs:         $arg - can be any of
10414:                      - undef - in which case the return value is a string 
10415:                                to add  into arguments list of a uri
10416:                      - 'input' - in which case the return value is a HTML
10417:                                  <form> <input> field of type hidden to
10418:                                  preserve the value
10419:                      - a url - in which case the return value is the url with
10420:                                the neccesary cgi args added to preserve the
10421:                                inhibitmenu state
10422:                      - a ref to a url - no return value, but the string is
10423:                                         updated to include the neccessary cgi
10424:                                         args to preserve the inhibitmenu state
10425: 
10426: =cut
10427: 
10428: sub inhibit_menu_check {
10429:     my ($arg) = @_;
10430:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10431:     if ($arg eq 'input') {
10432: 	if ($env{'form.inhibitmenu'}) {
10433: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10434: 	} else {
10435: 	    return
10436: 	}
10437:     }
10438:     if ($env{'form.inhibitmenu'}) {
10439: 	if (ref($arg)) {
10440: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10441: 	} elsif ($arg eq '') {
10442: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10443: 	} else {
10444: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10445: 	}
10446:     }
10447:     if (!ref($arg)) {
10448: 	return $arg;
10449:     }
10450: }
10451: 
10452: ###############################################
10453: 
10454: =pod
10455: 
10456: =back
10457: 
10458: =head1 User Information Routines
10459: 
10460: =over 4
10461: 
10462: =item * &get_users_function()
10463: 
10464: Used by &bodytag to determine the current users primary role.
10465: Returns either 'student','coordinator','admin', or 'author'.
10466: 
10467: =cut
10468: 
10469: ###############################################
10470: sub get_users_function {
10471:     my $function = 'norole';
10472:     if ($env{'request.role'}=~/^(st)/) {
10473:         $function='student';
10474:     }
10475:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10476:         $function='coordinator';
10477:     }
10478:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10479:         $function='admin';
10480:     }
10481:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10482:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10483:         $function='author';
10484:     }
10485:     return $function;
10486: }
10487: 
10488: ###############################################
10489: 
10490: =pod
10491: 
10492: =item * &show_course()
10493: 
10494: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10495: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10496: 
10497: Inputs:
10498: None
10499: 
10500: Outputs:
10501: Scalar: 1 if 'Course' to be used, 0 otherwise.
10502: 
10503: =cut
10504: 
10505: ###############################################
10506: sub show_course {
10507:     my ($udom,$uname) = @_;
10508:     if (($udom ne '') && ($uname ne '')) {
10509:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
10510:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
10511:                 return 0;
10512:             } else {
10513:                 return 1;
10514:             }
10515:         }
10516:     }
10517:     my $course = !$env{'user.adv'};
10518:     if (!$env{'user.adv'}) {
10519:         foreach my $env (keys(%env)) {
10520:             next if ($env !~ m/^user\.priv\./);
10521:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10522:                 $course = 0;
10523:                 last;
10524:             }
10525:         }
10526:     }
10527:     return $course;
10528: }
10529: 
10530: ###############################################
10531: 
10532: =pod
10533: 
10534: =item * &check_user_status()
10535: 
10536: Determines current status of supplied role for a
10537: specific user. Roles can be active, previous or future.
10538: 
10539: Inputs: 
10540: user's domain, user's username, course's domain,
10541: course's number, optional section ID.
10542: 
10543: Outputs:
10544: role status: active, previous or future. 
10545: 
10546: =cut
10547: 
10548: sub check_user_status {
10549:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10550:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10551:     my @uroles = keys(%userinfo);
10552:     my $srchstr;
10553:     my $active_chk = 'none';
10554:     my $now = time;
10555:     if (@uroles > 0) {
10556:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10557:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10558:         } else {
10559:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10560:         }
10561:         if (grep/^\Q$srchstr\E$/,@uroles) {
10562:             my $role_end = 0;
10563:             my $role_start = 0;
10564:             $active_chk = 'active';
10565:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10566:                 $role_end = $1;
10567:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10568:                     $role_start = $1;
10569:                 }
10570:             }
10571:             if ($role_start > 0) {
10572:                 if ($now < $role_start) {
10573:                     $active_chk = 'future';
10574:                 }
10575:             }
10576:             if ($role_end > 0) {
10577:                 if ($now > $role_end) {
10578:                     $active_chk = 'previous';
10579:                 }
10580:             }
10581:         }
10582:     }
10583:     return $active_chk;
10584: }
10585: 
10586: ###############################################
10587: 
10588: =pod
10589: 
10590: =item * &get_sections()
10591: 
10592: Determines all the sections for a course including
10593: sections with students and sections containing other roles.
10594: Incoming parameters: 
10595: 
10596: 1. domain
10597: 2. course number 
10598: 3. reference to array containing roles for which sections should 
10599: be gathered (optional).
10600: 4. reference to array containing status types for which sections 
10601: should be gathered (optional).
10602: 
10603: If the third argument is undefined, sections are gathered for any role. 
10604: If the fourth argument is undefined, sections are gathered for any status.
10605: Permissible values are 'active' or 'future' or 'previous'.
10606:  
10607: Returns section hash (keys are section IDs, values are
10608: number of users in each section), subject to the
10609: optional roles filter, optional status filter 
10610: 
10611: =cut
10612: 
10613: ###############################################
10614: sub get_sections {
10615:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10616:     if (!defined($cdom) || !defined($cnum)) {
10617:         my $cid =  $env{'request.course.id'};
10618: 
10619: 	return if (!defined($cid));
10620: 
10621:         $cdom = $env{'course.'.$cid.'.domain'};
10622:         $cnum = $env{'course.'.$cid.'.num'};
10623:     }
10624: 
10625:     my %sectioncount;
10626:     my $now = time;
10627: 
10628:     my $check_students = 1;
10629:     my $only_students = 0;
10630:     if (ref($possible_roles) eq 'ARRAY') {
10631:         if (grep(/^st$/,@{$possible_roles})) {
10632:             if (@{$possible_roles} == 1) {
10633:                 $only_students = 1;
10634:             }
10635:         } else {
10636:             $check_students = 0;
10637:         }
10638:     }
10639: 
10640:     if ($check_students) { 
10641: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10642: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
10643: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
10644:         my $start_index = &Apache::loncoursedata::CL_START();
10645:         my $end_index = &Apache::loncoursedata::CL_END();
10646:         my $status;
10647: 	while (my ($student,$data) = each(%$classlist)) {
10648: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10649: 				                     $data->[$status_index],
10650:                                                      $data->[$start_index],
10651:                                                      $data->[$end_index]);
10652:             if ($stu_status eq 'Active') {
10653:                 $status = 'active';
10654:             } elsif ($end < $now) {
10655:                 $status = 'previous';
10656:             } elsif ($start > $now) {
10657:                 $status = 'future';
10658:             } 
10659: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
10660:                 if ((!defined($possible_status)) || (($status ne '') && 
10661:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
10662: 		    $sectioncount{$section}++;
10663:                 }
10664: 	    }
10665: 	}
10666:     }
10667:     if ($only_students) {
10668:         return %sectioncount;
10669:     }
10670:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10671:     foreach my $user (sort(keys(%courseroles))) {
10672: 	if ($user !~ /^(\w{2})/) { next; }
10673: 	my ($role) = ($user =~ /^(\w{2})/);
10674: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10675: 	my ($section,$status);
10676: 	if ($role eq 'cr' &&
10677: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10678: 	    $section=$1;
10679: 	}
10680: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10681: 	if (!defined($section) || $section eq '-1') { next; }
10682:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10683:         if ($end == -1 && $start == -1) {
10684:             next; #deleted role
10685:         }
10686:         if (!defined($possible_status)) { 
10687:             $sectioncount{$section}++;
10688:         } else {
10689:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10690:                 $status = 'active';
10691:             } elsif ($end < $now) {
10692:                 $status = 'future';
10693:             } elsif ($start > $now) {
10694:                 $status = 'previous';
10695:             }
10696:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10697:                 $sectioncount{$section}++;
10698:             }
10699:         }
10700:     }
10701:     return %sectioncount;
10702: }
10703: 
10704: ###############################################
10705: 
10706: =pod
10707: 
10708: =item * &get_course_users()
10709: 
10710: Retrieves usernames:domains for users in the specified course
10711: with specific role(s), and access status. 
10712: 
10713: Incoming parameters:
10714: 1. course domain
10715: 2. course number
10716: 3. access status: users must have - either active, 
10717: previous, future, or all.
10718: 4. reference to array of permissible roles
10719: 5. reference to array of section restrictions (optional)
10720: 6. reference to results object (hash of hashes).
10721: 7. reference to optional userdata hash
10722: 8. reference to optional statushash
10723: 9. flag if privileged users (except those set to unhide in
10724:    course settings) should be excluded    
10725: Keys of top level results hash are roles.
10726: Keys of inner hashes are username:domain, with 
10727: values set to access type.
10728: Optional userdata hash returns an array with arguments in the 
10729: same order as loncoursedata::get_classlist() for student data.
10730: 
10731: Optional statushash returns
10732: 
10733: Entries for end, start, section and status are blank because
10734: of the possibility of multiple values for non-student roles.
10735: 
10736: =cut
10737: 
10738: ###############################################
10739: 
10740: sub get_course_users {
10741:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10742:     my %idx = ();
10743:     my %seclists;
10744: 
10745:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10746:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10747:     $idx{end} = &Apache::loncoursedata::CL_END();
10748:     $idx{start} = &Apache::loncoursedata::CL_START();
10749:     $idx{id} = &Apache::loncoursedata::CL_ID();
10750:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10751:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10752:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10753: 
10754:     if (grep(/^st$/,@{$roles})) {
10755:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10756:         my $now = time;
10757:         foreach my $student (keys(%{$classlist})) {
10758:             my $match = 0;
10759:             my $secmatch = 0;
10760:             my $section = $$classlist{$student}[$idx{section}];
10761:             my $status = $$classlist{$student}[$idx{status}];
10762:             if ($section eq '') {
10763:                 $section = 'none';
10764:             }
10765:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10766:                 if (grep(/^all$/,@{$sections})) {
10767:                     $secmatch = 1;
10768:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
10769:                     if (grep(/^none$/,@{$sections})) {
10770:                         $secmatch = 1;
10771:                     }
10772:                 } else {  
10773: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
10774: 		        $secmatch = 1;
10775:                     }
10776: 		}
10777:                 if (!$secmatch) {
10778:                     next;
10779:                 }
10780:             }
10781:             if (defined($$types{'active'})) {
10782:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10783:                     push(@{$$users{st}{$student}},'active');
10784:                     $match = 1;
10785:                 }
10786:             }
10787:             if (defined($$types{'previous'})) {
10788:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10789:                     push(@{$$users{st}{$student}},'previous');
10790:                     $match = 1;
10791:                 }
10792:             }
10793:             if (defined($$types{'future'})) {
10794:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10795:                     push(@{$$users{st}{$student}},'future');
10796:                     $match = 1;
10797:                 }
10798:             }
10799:             if ($match) {
10800:                 push(@{$seclists{$student}},$section);
10801:                 if (ref($userdata) eq 'HASH') {
10802:                     $$userdata{$student} = $$classlist{$student};
10803:                 }
10804:                 if (ref($statushash) eq 'HASH') {
10805:                     $statushash->{$student}{'st'}{$section} = $status;
10806:                 }
10807:             }
10808:         }
10809:     }
10810:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10811:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10812:         my $now = time;
10813:         my %displaystatus = ( previous => 'Expired',
10814:                               active   => 'Active',
10815:                               future   => 'Future',
10816:                             );
10817:         my (%nothide,@possdoms);
10818:         if ($hidepriv) {
10819:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10820:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10821:                 if ($user !~ /:/) {
10822:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10823:                 } else {
10824:                     $nothide{$user} = 1;
10825:                 }
10826:             }
10827:             my @possdoms = ($cdom);
10828:             if ($coursehash{'checkforpriv'}) {
10829:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10830:             }
10831:         }
10832:         foreach my $person (sort(keys(%coursepersonnel))) {
10833:             my $match = 0;
10834:             my $secmatch = 0;
10835:             my $status;
10836:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10837:             $user =~ s/:$//;
10838:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10839:             if ($end == -1 || $start == -1) {
10840:                 next;
10841:             }
10842:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10843:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10844:                 my ($uname,$udom) = split(/:/,$user);
10845:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10846:                     if (grep(/^all$/,@{$sections})) {
10847:                         $secmatch = 1;
10848:                     } elsif ($usec eq '') {
10849:                         if (grep(/^none$/,@{$sections})) {
10850:                             $secmatch = 1;
10851:                         }
10852:                     } else {
10853:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10854:                             $secmatch = 1;
10855:                         }
10856:                     }
10857:                     if (!$secmatch) {
10858:                         next;
10859:                     }
10860:                 }
10861:                 if ($usec eq '') {
10862:                     $usec = 'none';
10863:                 }
10864:                 if ($uname ne '' && $udom ne '') {
10865:                     if ($hidepriv) {
10866:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10867:                             (!$nothide{$uname.':'.$udom})) {
10868:                             next;
10869:                         }
10870:                     }
10871:                     if ($end > 0 && $end < $now) {
10872:                         $status = 'previous';
10873:                     } elsif ($start > $now) {
10874:                         $status = 'future';
10875:                     } else {
10876:                         $status = 'active';
10877:                     }
10878:                     foreach my $type (keys(%{$types})) { 
10879:                         if ($status eq $type) {
10880:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10881:                                 push(@{$$users{$role}{$user}},$type);
10882:                             }
10883:                             $match = 1;
10884:                         }
10885:                     }
10886:                     if (($match) && (ref($userdata) eq 'HASH')) {
10887:                         if (!exists($$userdata{$uname.':'.$udom})) {
10888: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10889:                         }
10890:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10891:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10892:                         }
10893:                         if (ref($statushash) eq 'HASH') {
10894:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10895:                         }
10896:                     }
10897:                 }
10898:             }
10899:         }
10900:         if (grep(/^ow$/,@{$roles})) {
10901:             if ((defined($cdom)) && (defined($cnum))) {
10902:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10903:                 if ( defined($csettings{'internal.courseowner'}) ) {
10904:                     my $owner = $csettings{'internal.courseowner'};
10905:                     next if ($owner eq '');
10906:                     my ($ownername,$ownerdom);
10907:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10908:                         $ownername = $1;
10909:                         $ownerdom = $2;
10910:                     } else {
10911:                         $ownername = $owner;
10912:                         $ownerdom = $cdom;
10913:                         $owner = $ownername.':'.$ownerdom;
10914:                     }
10915:                     @{$$users{'ow'}{$owner}} = 'any';
10916:                     if (defined($userdata) && 
10917: 			!exists($$userdata{$owner})) {
10918: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10919:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10920:                             push(@{$seclists{$owner}},'none');
10921:                         }
10922:                         if (ref($statushash) eq 'HASH') {
10923:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10924:                         }
10925: 		    }
10926:                 }
10927:             }
10928:         }
10929:         foreach my $user (keys(%seclists)) {
10930:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10931:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10932:         }
10933:     }
10934:     return;
10935: }
10936: 
10937: sub get_user_info {
10938:     my ($udom,$uname,$idx,$userdata) = @_;
10939:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10940: 	&plainname($uname,$udom,'lastname');
10941:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10942:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10943:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10944:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10945:     return;
10946: }
10947: 
10948: ###############################################
10949: 
10950: =pod
10951: 
10952: =item * &get_user_quota()
10953: 
10954: Retrieves quota assigned for storage of user files.
10955: Default is to report quota for portfolio files.
10956: 
10957: Incoming parameters:
10958: 1. user's username
10959: 2. user's domain
10960: 3. quota name - portfolio, author, or course
10961:    (if no quota name provided, defaults to portfolio).
10962: 4. crstype - official, unofficial, textbook, placement or community, 
10963:    if quota name is course
10964: 
10965: Returns:
10966: 1. Disk quota (in MB) assigned to student.
10967: 2. (Optional) Type of setting: custom or default
10968:    (individually assigned or default for user's 
10969:    institutional status).
10970: 3. (Optional) - User's institutional status (e.g., faculty, staff
10971:    or student - types as defined in localenroll::inst_usertypes 
10972:    for user's domain, which determines default quota for user.
10973: 4. (Optional) - Default quota which would apply to the user.
10974: 
10975: If a value has been stored in the user's environment, 
10976: it will return that, otherwise it returns the maximal default
10977: defined for the user's institutional status(es) in the domain.
10978: 
10979: =cut
10980: 
10981: ###############################################
10982: 
10983: 
10984: sub get_user_quota {
10985:     my ($uname,$udom,$quotaname,$crstype) = @_;
10986:     my ($quota,$quotatype,$settingstatus,$defquota);
10987:     if (!defined($udom)) {
10988:         $udom = $env{'user.domain'};
10989:     }
10990:     if (!defined($uname)) {
10991:         $uname = $env{'user.name'};
10992:     }
10993:     if (($udom eq '' || $uname eq '') ||
10994:         ($udom eq 'public') && ($uname eq 'public')) {
10995:         $quota = 0;
10996:         $quotatype = 'default';
10997:         $defquota = 0; 
10998:     } else {
10999:         my $inststatus;
11000:         if ($quotaname eq 'course') {
11001:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
11002:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
11003:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
11004:             } else {
11005:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
11006:                 $quota = $cenv{'internal.uploadquota'};
11007:             }
11008:         } else {
11009:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
11010:                 if ($quotaname eq 'author') {
11011:                     $quota = $env{'environment.authorquota'};
11012:                 } else {
11013:                     $quota = $env{'environment.portfolioquota'};
11014:                 }
11015:                 $inststatus = $env{'environment.inststatus'};
11016:             } else {
11017:                 my %userenv = 
11018:                     &Apache::lonnet::get('environment',['portfolioquota',
11019:                                          'authorquota','inststatus'],$udom,$uname);
11020:                 my ($tmp) = keys(%userenv);
11021:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11022:                     if ($quotaname eq 'author') {
11023:                         $quota = $userenv{'authorquota'};
11024:                     } else {
11025:                         $quota = $userenv{'portfolioquota'};
11026:                     }
11027:                     $inststatus = $userenv{'inststatus'};
11028:                 } else {
11029:                     undef(%userenv);
11030:                 }
11031:             }
11032:         }
11033:         if ($quota eq '' || wantarray) {
11034:             if ($quotaname eq 'course') {
11035:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
11036:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
11037:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
11038:                     ($crstype eq 'placement')) { 
11039:                     $defquota = $domdefs{$crstype.'quota'};
11040:                 }
11041:                 if ($defquota eq '') {
11042:                     $defquota = 500;
11043:                 }
11044:             } else {
11045:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
11046:             }
11047:             if ($quota eq '') {
11048:                 $quota = $defquota;
11049:                 $quotatype = 'default';
11050:             } else {
11051:                 $quotatype = 'custom';
11052:             }
11053:         }
11054:     }
11055:     if (wantarray) {
11056:         return ($quota,$quotatype,$settingstatus,$defquota);
11057:     } else {
11058:         return $quota;
11059:     }
11060: }
11061: 
11062: ###############################################
11063: 
11064: =pod
11065: 
11066: =item * &default_quota()
11067: 
11068: Retrieves default quota assigned for storage of user portfolio files,
11069: given an (optional) user's institutional status.
11070: 
11071: Incoming parameters:
11072: 
11073: 1. domain
11074: 2. (Optional) institutional status(es).  This is a : separated list of 
11075:    status types (e.g., faculty, staff, student etc.)
11076:    which apply to the user for whom the default is being retrieved.
11077:    If the institutional status string in undefined, the domain
11078:    default quota will be returned.
11079: 3.  quota name - portfolio, author, or course
11080:    (if no quota name provided, defaults to portfolio).
11081: 
11082: Returns:
11083: 
11084: 1. Default disk quota (in MB) for user portfolios in the domain.
11085: 2. (Optional) institutional type which determined the value of the
11086:    default quota.
11087: 
11088: If a value has been stored in the domain's configuration db,
11089: it will return that, otherwise it returns 20 (for backwards 
11090: compatibility with domains which have not set up a configuration
11091: db file; the original statically defined portfolio quota was 20 MB). 
11092: 
11093: If the user's status includes multiple types (e.g., staff and student),
11094: the largest default quota which applies to the user determines the
11095: default quota returned.
11096: 
11097: =cut
11098: 
11099: ###############################################
11100: 
11101: 
11102: sub default_quota {
11103:     my ($udom,$inststatus,$quotaname) = @_;
11104:     my ($defquota,$settingstatus);
11105:     my %quotahash = &Apache::lonnet::get_dom('configuration',
11106:                                             ['quotas'],$udom);
11107:     my $key = 'defaultquota';
11108:     if ($quotaname eq 'author') {
11109:         $key = 'authorquota';
11110:     }
11111:     if (ref($quotahash{'quotas'}) eq 'HASH') {
11112:         if ($inststatus ne '') {
11113:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
11114:             foreach my $item (@statuses) {
11115:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11116:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
11117:                         if ($defquota eq '') {
11118:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11119:                             $settingstatus = $item;
11120:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
11121:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11122:                             $settingstatus = $item;
11123:                         }
11124:                     }
11125:                 } elsif ($key eq 'defaultquota') {
11126:                     if ($quotahash{'quotas'}{$item} ne '') {
11127:                         if ($defquota eq '') {
11128:                             $defquota = $quotahash{'quotas'}{$item};
11129:                             $settingstatus = $item;
11130:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
11131:                             $defquota = $quotahash{'quotas'}{$item};
11132:                             $settingstatus = $item;
11133:                         }
11134:                     }
11135:                 }
11136:             }
11137:         }
11138:         if ($defquota eq '') {
11139:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11140:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
11141:             } elsif ($key eq 'defaultquota') {
11142:                 $defquota = $quotahash{'quotas'}{'default'};
11143:             }
11144:             $settingstatus = 'default';
11145:             if ($defquota eq '') {
11146:                 if ($quotaname eq 'author') {
11147:                     $defquota = 500;
11148:                 }
11149:             }
11150:         }
11151:     } else {
11152:         $settingstatus = 'default';
11153:         if ($quotaname eq 'author') {
11154:             $defquota = 500;
11155:         } else {
11156:             $defquota = 20;
11157:         }
11158:     }
11159:     if (wantarray) {
11160:         return ($defquota,$settingstatus);
11161:     } else {
11162:         return $defquota;
11163:     }
11164: }
11165: 
11166: ###############################################
11167: 
11168: =pod
11169: 
11170: =item * &excess_filesize_warning()
11171: 
11172: Returns warning message if upload of file to authoring space, or copying
11173: of existing file within authoring space will cause quota for the authoring
11174: space to be exceeded.
11175: 
11176: Same, if upload of a file directly to a course/community via Course Editor
11177: will cause quota for uploaded content for the course to be exceeded.
11178: 
11179: Inputs: 7 
11180: 1. username or coursenum
11181: 2. domain
11182: 3. context ('author' or 'course')
11183: 4. filename of file for which action is being requested
11184: 5. filesize (kB) of file
11185: 6. action being taken: copy or upload.
11186: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
11187: 
11188: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
11189:          otherwise return null.
11190: 
11191: =back
11192: 
11193: =cut
11194: 
11195: sub excess_filesize_warning {
11196:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
11197:     my $current_disk_usage = 0;
11198:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
11199:     if ($context eq 'author') {
11200:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
11201:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
11202:     } else {
11203:         foreach my $subdir ('docs','supplemental') {
11204:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
11205:         }
11206:     }
11207:     $disk_quota = int($disk_quota * 1000);
11208:     if (($current_disk_usage + $filesize) > $disk_quota) {
11209:         return '<p class="LC_warning">'.
11210:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
11211:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
11212:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11213:                             $disk_quota,$current_disk_usage).
11214:                '</p>';
11215:     }
11216:     return;
11217: }
11218: 
11219: ###############################################
11220: 
11221: 
11222: 
11223: 
11224: sub get_secgrprole_info {
11225:     my ($cdom,$cnum,$needroles,$type)  = @_;
11226:     my %sections_count = &get_sections($cdom,$cnum);
11227:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
11228:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
11229:     my @groups = sort(keys(%curr_groups));
11230:     my $allroles = [];
11231:     my $rolehash;
11232:     my $accesshash = {
11233:                      active => 'Currently has access',
11234:                      future => 'Will have future access',
11235:                      previous => 'Previously had access',
11236:                   };
11237:     if ($needroles) {
11238:         $rolehash = {'all' => 'all'};
11239:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11240: 	if (&Apache::lonnet::error(%user_roles)) {
11241: 	    undef(%user_roles);
11242: 	}
11243:         foreach my $item (keys(%user_roles)) {
11244:             my ($role)=split(/\:/,$item,2);
11245:             if ($role eq 'cr') { next; }
11246:             if ($role =~ /^cr/) {
11247:                 $$rolehash{$role} = (split('/',$role))[3];
11248:             } else {
11249:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11250:             }
11251:         }
11252:         foreach my $key (sort(keys(%{$rolehash}))) {
11253:             push(@{$allroles},$key);
11254:         }
11255:         push (@{$allroles},'st');
11256:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11257:     }
11258:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11259: }
11260: 
11261: sub user_picker {
11262:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11263:     my $currdom = $dom;
11264:     my @alldoms = &Apache::lonnet::all_domains();
11265:     if (@alldoms == 1) {
11266:         my %domsrch = &Apache::lonnet::get_dom('configuration',
11267:                                                ['directorysrch'],$alldoms[0]);
11268:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11269:         my $showdom = $domdesc;
11270:         if ($showdom eq '') {
11271:             $showdom = $dom;
11272:         }
11273:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11274:             if ((!$domsrch{'directorysrch'}{'available'}) &&
11275:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11276:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11277:             }
11278:         }
11279:     }
11280:     my %curr_selected = (
11281:                         srchin => 'dom',
11282:                         srchby => 'lastname',
11283:                       );
11284:     my $srchterm;
11285:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11286:         if ($srch->{'srchby'} ne '') {
11287:             $curr_selected{'srchby'} = $srch->{'srchby'};
11288:         }
11289:         if ($srch->{'srchin'} ne '') {
11290:             $curr_selected{'srchin'} = $srch->{'srchin'};
11291:         }
11292:         if ($srch->{'srchtype'} ne '') {
11293:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
11294:         }
11295:         if ($srch->{'srchdomain'} ne '') {
11296:             $currdom = $srch->{'srchdomain'};
11297:         }
11298:         $srchterm = $srch->{'srchterm'};
11299:     }
11300:     my %html_lt=&Apache::lonlocal::texthash(
11301:                     'usr'       => 'Search criteria',
11302:                     'doma'      => 'Domain/institution to search',
11303:                     'uname'     => 'username',
11304:                     'lastname'  => 'last name',
11305:                     'lastfirst' => 'last name, first name',
11306:                     'crs'       => 'in this course',
11307:                     'dom'       => 'in selected LON-CAPA domain', 
11308:                     'alc'       => 'all LON-CAPA',
11309:                     'instd'     => 'in institutional directory for selected domain',
11310:                     'exact'     => 'is',
11311:                     'contains'  => 'contains',
11312:                     'begins'    => 'begins with',
11313:                                        );
11314:     my %js_lt=&Apache::lonlocal::texthash(
11315:                     'youm'      => "You must include some text to search for.",
11316:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11317:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11318:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
11319:                     'ymcd'      => "You must choose a domain when using a domain search.",
11320:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
11321:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
11322:                      'thfo'     => "The following need to be corrected before the search can be run:",
11323:                                        );
11324:     &html_escape(\%html_lt);
11325:     &js_escape(\%js_lt);
11326:     my $domform;
11327:     my $allow_blank = 1;
11328:     if ($fixeddom) {
11329:         $allow_blank = 0;
11330:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11331:     } else {
11332:         my $defdom = $env{'request.role.domain'};
11333:         my ($trusted,$untrusted);
11334:         if (($context eq 'requestcrs') || ($context eq 'course')) {
11335:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11336:         } elsif ($context eq 'author') {
11337:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11338:         } elsif ($context eq 'domain') {
11339:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11340:         }
11341:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11342:     }
11343:     my $srchinsel = ' <select name="srchin">';
11344: 
11345:     my @srchins = ('crs','dom','alc','instd');
11346: 
11347:     foreach my $option (@srchins) {
11348:         # FIXME 'alc' option unavailable until 
11349:         #       loncreateuser::print_user_query_page()
11350:         #       has been completed.
11351:         next if ($option eq 'alc');
11352:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
11353:         next if ($option eq 'crs' && !$env{'request.course.id'});
11354:         next if (($option eq 'instd') && ($noinstd));
11355:         if ($curr_selected{'srchin'} eq $option) {
11356:             $srchinsel .= ' 
11357:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11358:         } else {
11359:             $srchinsel .= '
11360:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11361:         }
11362:     }
11363:     $srchinsel .= "\n  </select>\n";
11364: 
11365:     my $srchbysel =  ' <select name="srchby">';
11366:     foreach my $option ('lastname','lastfirst','uname') {
11367:         if ($curr_selected{'srchby'} eq $option) {
11368:             $srchbysel .= '
11369:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11370:         } else {
11371:             $srchbysel .= '
11372:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11373:          }
11374:     }
11375:     $srchbysel .= "\n  </select>\n";
11376: 
11377:     my $srchtypesel = ' <select name="srchtype">';
11378:     foreach my $option ('begins','contains','exact') {
11379:         if ($curr_selected{'srchtype'} eq $option) {
11380:             $srchtypesel .= '
11381:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11382:         } else {
11383:             $srchtypesel .= '
11384:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11385:         }
11386:     }
11387:     $srchtypesel .= "\n  </select>\n";
11388: 
11389:     my ($newuserscript,$new_user_create);
11390:     my $context_dom = $env{'request.role.domain'};
11391:     if ($context eq 'requestcrs') {
11392:         if ($env{'form.coursedom'} ne '') { 
11393:             $context_dom = $env{'form.coursedom'};
11394:         }
11395:     }
11396:     if ($forcenewuser) {
11397:         if (ref($srch) eq 'HASH') {
11398:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11399:                 if ($cancreate) {
11400:                     $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>';
11401:                 } else {
11402:                     my $helplink = 'javascript:helpMenu('."'display'".')';
11403:                     my %usertypetext = (
11404:                         official   => 'institutional',
11405:                         unofficial => 'non-institutional',
11406:                     );
11407:                     $new_user_create = '<p class="LC_warning">'
11408:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11409:                                       .' '
11410:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11411:                                           ,'<a href="'.$helplink.'">','</a>')
11412:                                       .'</p><br />';
11413:                 }
11414:             }
11415:         }
11416: 
11417:         $newuserscript = <<"ENDSCRIPT";
11418: 
11419: function setSearch(createnew,callingForm) {
11420:     if (createnew == 1) {
11421:         for (var i=0; i<callingForm.srchby.length; i++) {
11422:             if (callingForm.srchby.options[i].value == 'uname') {
11423:                 callingForm.srchby.selectedIndex = i;
11424:             }
11425:         }
11426:         for (var i=0; i<callingForm.srchin.length; i++) {
11427:             if ( callingForm.srchin.options[i].value == 'dom') {
11428: 		callingForm.srchin.selectedIndex = i;
11429:             }
11430:         }
11431:         for (var i=0; i<callingForm.srchtype.length; i++) {
11432:             if (callingForm.srchtype.options[i].value == 'exact') {
11433:                 callingForm.srchtype.selectedIndex = i;
11434:             }
11435:         }
11436:         for (var i=0; i<callingForm.srchdomain.length; i++) {
11437:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
11438:                 callingForm.srchdomain.selectedIndex = i;
11439:             }
11440:         }
11441:     }
11442: }
11443: ENDSCRIPT
11444: 
11445:     }
11446: 
11447:     my $output = <<"END_BLOCK";
11448: <script type="text/javascript">
11449: // <![CDATA[
11450: function validateEntry(callingForm) {
11451: 
11452:     var checkok = 1;
11453:     var srchin;
11454:     for (var i=0; i<callingForm.srchin.length; i++) {
11455: 	if ( callingForm.srchin[i].checked ) {
11456: 	    srchin = callingForm.srchin[i].value;
11457: 	}
11458:     }
11459: 
11460:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11461:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11462:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11463:     var srchterm =  callingForm.srchterm.value;
11464:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11465:     var msg = "";
11466: 
11467:     if (srchterm == "") {
11468:         checkok = 0;
11469:         msg += "$js_lt{'youm'}\\n";
11470:     }
11471: 
11472:     if (srchtype== 'begins') {
11473:         if (srchterm.length < 2) {
11474:             checkok = 0;
11475:             msg += "$js_lt{'thte'}\\n";
11476:         }
11477:     }
11478: 
11479:     if (srchtype== 'contains') {
11480:         if (srchterm.length < 3) {
11481:             checkok = 0;
11482:             msg += "$js_lt{'thet'}\\n";
11483:         }
11484:     }
11485:     if (srchin == 'instd') {
11486:         if (srchdomain == '') {
11487:             checkok = 0;
11488:             msg += "$js_lt{'yomc'}\\n";
11489:         }
11490:     }
11491:     if (srchin == 'dom') {
11492:         if (srchdomain == '') {
11493:             checkok = 0;
11494:             msg += "$js_lt{'ymcd'}\\n";
11495:         }
11496:     }
11497:     if (srchby == 'lastfirst') {
11498:         if (srchterm.indexOf(",") == -1) {
11499:             checkok = 0;
11500:             msg += "$js_lt{'whus'}\\n";
11501:         }
11502:         if (srchterm.indexOf(",") == srchterm.length -1) {
11503:             checkok = 0;
11504:             msg += "$js_lt{'whse'}\\n";
11505:         }
11506:     }
11507:     if (checkok == 0) {
11508:         alert("$js_lt{'thfo'}\\n"+msg);
11509:         return;
11510:     }
11511:     if (checkok == 1) {
11512:         callingForm.submit();
11513:     }
11514: }
11515: 
11516: $newuserscript
11517: 
11518: // ]]>
11519: </script>
11520: 
11521: $new_user_create
11522: 
11523: END_BLOCK
11524: 
11525:     $output .= &Apache::lonhtmlcommon::start_pick_box().
11526:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11527:                $domform.
11528:                &Apache::lonhtmlcommon::row_closure().
11529:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11530:                $srchbysel.
11531:                $srchtypesel. 
11532:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11533:                $srchinsel.
11534:                &Apache::lonhtmlcommon::row_closure(1). 
11535:                &Apache::lonhtmlcommon::end_pick_box().
11536:                '<br />';
11537:     return ($output,1);
11538: }
11539: 
11540: sub user_rule_check {
11541:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11542:     my ($response,%inst_response);
11543:     if (ref($usershash) eq 'HASH') {
11544:         if (keys(%{$usershash}) > 1) {
11545:             my (%by_username,%by_id,%userdoms);
11546:             my $checkid; 
11547:             if (ref($checks) eq 'HASH') {
11548:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11549:                     $checkid = 1;
11550:                 }
11551:             }
11552:             foreach my $user (keys(%{$usershash})) {
11553:                 my ($uname,$udom) = split(/:/,$user);
11554:                 if ($checkid) {
11555:                     if (ref($usershash->{$user}) eq 'HASH') {
11556:                         if ($usershash->{$user}->{'id'} ne '') {
11557:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
11558:                             $userdoms{$udom} = 1;
11559:                             if (ref($inst_results) eq 'HASH') {
11560:                                 $inst_results->{$uname.':'.$udom} = {};
11561:                             }
11562:                         }
11563:                     }
11564:                 } else {
11565:                     $by_username{$udom}{$uname} = 1;
11566:                     $userdoms{$udom} = 1;
11567:                     if (ref($inst_results) eq 'HASH') {
11568:                         $inst_results->{$uname.':'.$udom} = {};
11569:                     }
11570:                 }
11571:             }
11572:             foreach my $udom (keys(%userdoms)) {
11573:                 if (!$got_rules->{$udom}) {
11574:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
11575:                                                              ['usercreation'],$udom);
11576:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11577:                         foreach my $item ('username','id') {
11578:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11579:                                 $$curr_rules{$udom}{$item} =
11580:                                     $domconfig{'usercreation'}{$item.'_rule'};
11581:                             }
11582:                         }
11583:                     }
11584:                     $got_rules->{$udom} = 1;
11585:                 }
11586:             }
11587:             if ($checkid) {
11588:                 foreach my $udom (keys(%by_id)) {
11589:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11590:                     if ($outcome eq 'ok') {
11591:                         foreach my $id (keys(%{$by_id{$udom}})) {
11592:                             my $uname = $by_id{$udom}{$id};
11593:                             $inst_response{$uname.':'.$udom} = $outcome;
11594:                         }
11595:                         if (ref($results) eq 'HASH') {
11596:                             foreach my $uname (keys(%{$results})) {
11597:                                 if (exists($inst_response{$uname.':'.$udom})) {
11598:                                     $inst_response{$uname.':'.$udom} = $outcome;
11599:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
11600:                                 }
11601:                             }
11602:                         }
11603:                     }
11604:                 }
11605:             } else {
11606:                 foreach my $udom (keys(%by_username)) {
11607:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11608:                     if ($outcome eq 'ok') {
11609:                         foreach my $uname (keys(%{$by_username{$udom}})) {
11610:                             $inst_response{$uname.':'.$udom} = $outcome;
11611:                         }
11612:                         if (ref($results) eq 'HASH') {
11613:                             foreach my $uname (keys(%{$results})) {
11614:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
11615:                             }
11616:                         }
11617:                     }
11618:                 }
11619:             }
11620:         } elsif (keys(%{$usershash}) == 1) {
11621:             my $user = (keys(%{$usershash}))[0];
11622:             my ($uname,$udom) = split(/:/,$user);
11623:             if (($udom ne '') && ($uname ne '')) {
11624:                 if (ref($usershash->{$user}) eq 'HASH') {
11625:                     if (ref($checks) eq 'HASH') {
11626:                         if (defined($checks->{'username'})) {
11627:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
11628:                                 &Apache::lonnet::get_instuser($udom,$uname);
11629:                         } elsif (defined($checks->{'id'})) {
11630:                             if ($usershash->{$user}->{'id'} ne '') {
11631:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11632:                                     &Apache::lonnet::get_instuser($udom,undef,
11633:                                                                   $usershash->{$user}->{'id'});
11634:                             } else {
11635:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11636:                                     &Apache::lonnet::get_instuser($udom,$uname);
11637:                             }
11638:                         }
11639:                     } else {
11640:                        ($inst_response{$user},%{$inst_results->{$user}}) =
11641:                             &Apache::lonnet::get_instuser($udom,$uname);
11642:                        return;
11643:                     }
11644:                     if (!$got_rules->{$udom}) {
11645:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
11646:                                                                  ['usercreation'],$udom);
11647:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
11648:                             foreach my $item ('username','id') {
11649:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11650:                                    $$curr_rules{$udom}{$item} = 
11651:                                        $domconfig{'usercreation'}{$item.'_rule'};
11652:                                 }
11653:                             }
11654:                         }
11655:                         $got_rules->{$udom} = 1;
11656:                     }
11657:                 }
11658:             } else {
11659:                 return;
11660:             }
11661:         } else {
11662:             return;
11663:         }
11664:         foreach my $user (keys(%{$usershash})) {
11665:             my ($uname,$udom) = split(/:/,$user);
11666:             next if (($udom eq '') || ($uname eq ''));
11667:             my $id;
11668:             if (ref($inst_results) eq 'HASH') {
11669:                 if (ref($inst_results->{$user}) eq 'HASH') {
11670:                     $id = $inst_results->{$user}->{'id'};
11671:                 }
11672:             }
11673:             if ($id eq '') { 
11674:                 if (ref($usershash->{$user})) {
11675:                     $id = $usershash->{$user}->{'id'};
11676:                 }
11677:             }
11678:             foreach my $item (keys(%{$checks})) {
11679:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
11680:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11681:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
11682:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11683:                                                                              $$curr_rules{$udom}{$item});
11684:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11685:                                 if ($rule_check{$rule}) {
11686:                                     $$rulematch{$user}{$item} = $rule;
11687:                                     if ($inst_response{$user} eq 'ok') {
11688:                                         if (ref($inst_results) eq 'HASH') {
11689:                                             if (ref($inst_results->{$user}) eq 'HASH') {
11690:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
11691:                                                     $$alerts{$item}{$udom}{$uname} = 1;
11692:                                                 } elsif ($item eq 'id') {
11693:                                                     if ($inst_results->{$user}->{'id'} eq '') {
11694:                                                         $$alerts{$item}{$udom}{$uname} = 1;
11695:                                                     }
11696:                                                 }
11697:                                             }
11698:                                         }
11699:                                     }
11700:                                     last;
11701:                                 }
11702:                             }
11703:                         }
11704:                     }
11705:                 }
11706:             }
11707:         }
11708:     }
11709:     return;
11710: }
11711: 
11712: sub user_rule_formats {
11713:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11714:     my %text = ( 
11715:                  'username' => 'Usernames',
11716:                  'id'       => 'IDs',
11717:                );
11718:     my $output;
11719:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11720:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11721:         if (@{$ruleorder} > 0) {
11722:             $output = '<br />'.
11723:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11724:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11725:                       ' <ul>';
11726:             foreach my $rule (@{$ruleorder}) {
11727:                 if (ref($curr_rules) eq 'ARRAY') {
11728:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11729:                         if (ref($rules->{$rule}) eq 'HASH') {
11730:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11731:                                         $rules->{$rule}{'desc'}.'</li>';
11732:                         }
11733:                     }
11734:                 }
11735:             }
11736:             $output .= '</ul>';
11737:         }
11738:     }
11739:     return $output;
11740: }
11741: 
11742: sub instrule_disallow_msg {
11743:     my ($checkitem,$domdesc,$count,$mode) = @_;
11744:     my $response;
11745:     my %text = (
11746:                   item   => 'username',
11747:                   items  => 'usernames',
11748:                   match  => 'matches',
11749:                   do     => 'does',
11750:                   action => 'a username',
11751:                   one    => 'one',
11752:                );
11753:     if ($count > 1) {
11754:         $text{'item'} = 'usernames';
11755:         $text{'match'} ='match';
11756:         $text{'do'} = 'do';
11757:         $text{'action'} = 'usernames',
11758:         $text{'one'} = 'ones';
11759:     }
11760:     if ($checkitem eq 'id') {
11761:         $text{'items'} = 'IDs';
11762:         $text{'item'} = 'ID';
11763:         $text{'action'} = 'an ID';
11764:         if ($count > 1) {
11765:             $text{'item'} = 'IDs';
11766:             $text{'action'} = 'IDs';
11767:         }
11768:     }
11769:     $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 />';
11770:     if ($mode eq 'upload') {
11771:         if ($checkitem eq 'username') {
11772:             $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'}.");
11773:         } elsif ($checkitem eq 'id') {
11774:             $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.");
11775:         }
11776:     } elsif ($mode eq 'selfcreate') {
11777:         if ($checkitem eq 'id') {
11778:             $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.");
11779:         }
11780:     } else {
11781:         if ($checkitem eq 'username') {
11782:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11783:         } elsif ($checkitem eq 'id') {
11784:             $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.");
11785:         }
11786:     }
11787:     return $response;
11788: }
11789: 
11790: sub personal_data_fieldtitles {
11791:     my %fieldtitles = &Apache::lonlocal::texthash (
11792:                         id => 'Student/Employee ID',
11793:                         permanentemail => 'E-mail address',
11794:                         lastname => 'Last Name',
11795:                         firstname => 'First Name',
11796:                         middlename => 'Middle Name',
11797:                         generation => 'Generation',
11798:                         gen => 'Generation',
11799:                         inststatus => 'Affiliation',
11800:                    );
11801:     return %fieldtitles;
11802: }
11803: 
11804: sub sorted_inst_types {
11805:     my ($dom) = @_;
11806:     my ($usertypes,$order);
11807:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11808:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11809:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11810:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11811:     } else {
11812:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11813:     }
11814:     my $othertitle = &mt('All users');
11815:     if ($env{'request.course.id'}) {
11816:         $othertitle  = &mt('Any users');
11817:     }
11818:     my @types;
11819:     if (ref($order) eq 'ARRAY') {
11820:         @types = @{$order};
11821:     }
11822:     if (@types == 0) {
11823:         if (ref($usertypes) eq 'HASH') {
11824:             @types = sort(keys(%{$usertypes}));
11825:         }
11826:     }
11827:     if (keys(%{$usertypes}) > 0) {
11828:         $othertitle = &mt('Other users');
11829:     }
11830:     return ($othertitle,$usertypes,\@types);
11831: }
11832: 
11833: sub get_institutional_codes {
11834:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11835: # Get complete list of course sections to update
11836:     my @currsections = ();
11837:     my @currxlists = ();
11838:     my (%unclutteredsec,%unclutteredlcsec);
11839:     my $coursecode = $$settings{'internal.coursecode'};
11840:     my $crskey = $crs.':'.$coursecode;
11841:     @{$unclutteredsec{$crskey}} = ();
11842:     @{$unclutteredlcsec{$crskey}} = ();
11843: 
11844:     if ($$settings{'internal.sectionnums'} ne '') {
11845:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11846:     }
11847: 
11848:     if ($$settings{'internal.crosslistings'} ne '') {
11849:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11850:     }
11851: 
11852:     if (@currxlists > 0) {
11853:         foreach my $xl (@currxlists) {
11854:             if ($xl =~ /^([^:]+):(\w*)$/) {
11855:                 unless (grep/^$1$/,@{$allcourses}) {
11856:                     push(@{$allcourses},$1);
11857:                     $$LC_code{$1} = $2;
11858:                 }
11859:             }
11860:         }
11861:     }
11862: 
11863:     if (@currsections > 0) {
11864:         foreach my $sec (@currsections) {
11865:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
11866:                 my $instsec = $1;
11867:                 my $lc_sec = $2;
11868:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11869:                     push(@{$unclutteredsec{$crskey}},$instsec);
11870:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11871:                 }
11872:             }
11873:         }
11874:     }
11875: 
11876:     if (@{$unclutteredsec{$crskey}} > 0) {
11877:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11878:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11879:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11880:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
11881:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11882:                     push(@{$allcourses},$sec);
11883:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11884:                 }
11885:             }
11886:         }
11887:     }
11888:     return;
11889: }
11890: 
11891: sub get_standard_codeitems {
11892:     return ('Year','Semester','Department','Number','Section');
11893: }
11894: 
11895: =pod
11896: 
11897: =head1 Slot Helpers
11898: 
11899: =over 4
11900: 
11901: =item * sorted_slots()
11902: 
11903: Sorts an array of slot names in order of an optional sort key,
11904: default sort is by slot start time (earliest first). 
11905: 
11906: Inputs:
11907: 
11908: =over 4
11909: 
11910: slotsarr  - Reference to array of unsorted slot names.
11911: 
11912: slots     - Reference to hash of hash, where outer hash keys are slot names.
11913: 
11914: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11915: 
11916: =back
11917: 
11918: Returns:
11919: 
11920: =over 4
11921: 
11922: sorted   - An array of slot names sorted by a specified sort key 
11923:            (default sort key is start time of the slot).
11924: 
11925: =back
11926: 
11927: =cut
11928: 
11929: 
11930: sub sorted_slots {
11931:     my ($slotsarr,$slots,$sortkey) = @_;
11932:     if ($sortkey eq '') {
11933:         $sortkey = 'starttime';
11934:     }
11935:     my @sorted;
11936:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11937:         @sorted =
11938:             sort {
11939:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11940:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11941:                      }
11942:                      if (ref($slots->{$a})) { return -1;}
11943:                      if (ref($slots->{$b})) { return 1;}
11944:                      return 0;
11945:                  } @{$slotsarr};
11946:     }
11947:     return @sorted;
11948: }
11949: 
11950: =pod
11951: 
11952: =item * get_future_slots()
11953: 
11954: Inputs:
11955: 
11956: =over 4
11957: 
11958: cnum - course number
11959: 
11960: cdom - course domain
11961: 
11962: now - current UNIX time
11963: 
11964: symb - optional symb
11965: 
11966: =back
11967: 
11968: Returns:
11969: 
11970: =over 4
11971: 
11972: sorted_reservable - ref to array of student_schedulable slots currently 
11973:                     reservable, ordered by end date of reservation period.
11974: 
11975: reservable_now - ref to hash of student_schedulable slots currently
11976:                  reservable.
11977: 
11978:     Keys in inner hash are:
11979:     (a) symb: either blank or symb to which slot use is restricted.
11980:     (b) endreserve: end date of reservation period.
11981:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11982:         selected.
11983: 
11984: sorted_future - ref to array of student_schedulable slots reservable in
11985:                 the future, ordered by start date of reservation period.
11986: 
11987: future_reservable - ref to hash of student_schedulable slots reservable
11988:                     in the future.
11989: 
11990:     Keys in inner hash are:
11991:     (a) symb: either blank or symb to which slot use is restricted.
11992:     (b) startreserve: start date of reservation period.
11993:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11994:         selected.
11995: 
11996: =back
11997: 
11998: =cut
11999: 
12000: sub get_future_slots {
12001:     my ($cnum,$cdom,$now,$symb) = @_;
12002:     my $map;
12003:     if ($symb) {
12004:         ($map) = &Apache::lonnet::decode_symb($symb);
12005:     }
12006:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
12007:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
12008:     foreach my $slot (keys(%slots)) {
12009:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
12010:         if ($symb) {
12011:             if ($slots{$slot}->{'symb'} ne '') {
12012:                 my $canuse;
12013:                 my %oksymbs;
12014:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
12015:                 map { $oksymbs{$_} = 1; } @slotsymbs;
12016:                 if ($oksymbs{$symb}) {
12017:                     $canuse = 1;
12018:                 } else {
12019:                     foreach my $item (@slotsymbs) {
12020:                         if ($item =~ /\.(page|sequence)$/) {
12021:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
12022:                             if (($map ne '') && ($map eq $sloturl)) {
12023:                                 $canuse = 1;
12024:                                 last;
12025:                             }
12026:                         }
12027:                     }
12028:                 }
12029:                 next unless ($canuse);
12030:             }
12031:         }
12032:         if (($slots{$slot}->{'starttime'} > $now) &&
12033:             ($slots{$slot}->{'endtime'} > $now)) {
12034:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
12035:                 my $userallowed = 0;
12036:                 if ($slots{$slot}->{'allowedsections'}) {
12037:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
12038:                     if (!defined($env{'request.role.sec'})
12039:                         && grep(/^No section assigned$/,@allowed_sec)) {
12040:                         $userallowed=1;
12041:                     } else {
12042:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
12043:                             $userallowed=1;
12044:                         }
12045:                     }
12046:                     unless ($userallowed) {
12047:                         if (defined($env{'request.course.groups'})) {
12048:                             my @groups = split(/:/,$env{'request.course.groups'});
12049:                             foreach my $group (@groups) {
12050:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
12051:                                     $userallowed=1;
12052:                                     last;
12053:                                 }
12054:                             }
12055:                         }
12056:                     }
12057:                 }
12058:                 if ($slots{$slot}->{'allowedusers'}) {
12059:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
12060:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
12061:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
12062:                         $userallowed = 1;
12063:                     }
12064:                 }
12065:                 next unless($userallowed);
12066:             }
12067:             my $startreserve = $slots{$slot}->{'startreserve'};
12068:             my $endreserve = $slots{$slot}->{'endreserve'};
12069:             my $symb = $slots{$slot}->{'symb'};
12070:             my $uniqueperiod;
12071:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
12072:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
12073:             }
12074:             if (($startreserve < $now) &&
12075:                 (!$endreserve || $endreserve > $now)) {
12076:                 my $lastres = $endreserve;
12077:                 if (!$lastres) {
12078:                     $lastres = $slots{$slot}->{'starttime'};
12079:                 }
12080:                 $reservable_now{$slot} = {
12081:                                            symb       => $symb,
12082:                                            endreserve => $lastres,
12083:                                            uniqueperiod => $uniqueperiod,
12084:                                          };
12085:             } elsif (($startreserve > $now) &&
12086:                      (!$endreserve || $endreserve > $startreserve)) {
12087:                 $future_reservable{$slot} = {
12088:                                               symb         => $symb,
12089:                                               startreserve => $startreserve,
12090:                                               uniqueperiod => $uniqueperiod,
12091:                                             };
12092:             }
12093:         }
12094:     }
12095:     my @unsorted_reservable = keys(%reservable_now);
12096:     if (@unsorted_reservable > 0) {
12097:         @sorted_reservable = 
12098:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
12099:     }
12100:     my @unsorted_future = keys(%future_reservable);
12101:     if (@unsorted_future > 0) {
12102:         @sorted_future =
12103:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
12104:     }
12105:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
12106: }
12107: 
12108: =pod
12109: 
12110: =back
12111: 
12112: =head1 HTTP Helpers
12113: 
12114: =over 4
12115: 
12116: =item * &get_unprocessed_cgi($query,$possible_names)
12117: 
12118: Modify the %env hash to contain unprocessed CGI form parameters held in
12119: $query.  The parameters listed in $possible_names (an array reference),
12120: will be set in $env{'form.name'} if they do not already exist.
12121: 
12122: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
12123: $possible_names is an ref to an array of form element names.  As an example:
12124: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
12125: will result in $env{'form.uname'} and $env{'form.udom'} being set.
12126: 
12127: =cut
12128: 
12129: sub get_unprocessed_cgi {
12130:   my ($query,$possible_names)= @_;
12131:   # $Apache::lonxml::debug=1;
12132:   foreach my $pair (split(/&/,$query)) {
12133:     my ($name, $value) = split(/=/,$pair);
12134:     $name = &unescape($name);
12135:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
12136:       $value =~ tr/+/ /;
12137:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
12138:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
12139:     }
12140:   }
12141: }
12142: 
12143: =pod
12144: 
12145: =item * &cacheheader() 
12146: 
12147: returns cache-controlling header code
12148: 
12149: =cut
12150: 
12151: sub cacheheader {
12152:     unless ($env{'request.method'} eq 'GET') { return ''; }
12153:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
12154:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
12155:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
12156:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
12157:     return $output;
12158: }
12159: 
12160: =pod
12161: 
12162: =item * &no_cache($r) 
12163: 
12164: specifies header code to not have cache
12165: 
12166: =cut
12167: 
12168: sub no_cache {
12169:     my ($r) = @_;
12170:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
12171: 	$env{'request.method'} ne 'GET') { return ''; }
12172:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
12173:     $r->no_cache(1);
12174:     $r->header_out("Expires" => $date);
12175:     $r->header_out("Pragma" => "no-cache");
12176: }
12177: 
12178: sub content_type {
12179:     my ($r,$type,$charset) = @_;
12180:     if ($r) {
12181: 	#  Note that printout.pl calls this with undef for $r.
12182: 	&no_cache($r);
12183:     }
12184:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
12185:     unless ($charset) {
12186: 	$charset=&Apache::lonlocal::current_encoding;
12187:     }
12188:     if ($charset) { $type.='; charset='.$charset; }
12189:     if ($r) {
12190: 	$r->content_type($type);
12191:     } else {
12192: 	print("Content-type: $type\n\n");
12193:     }
12194: }
12195: 
12196: =pod
12197: 
12198: =item * &add_to_env($name,$value) 
12199: 
12200: adds $name to the %env hash with value
12201: $value, if $name already exists, the entry is converted to an array
12202: reference and $value is added to the array.
12203: 
12204: =cut
12205: 
12206: sub add_to_env {
12207:   my ($name,$value)=@_;
12208:   if (defined($env{$name})) {
12209:     if (ref($env{$name})) {
12210:       #already have multiple values
12211:       push(@{ $env{$name} },$value);
12212:     } else {
12213:       #first time seeing multiple values, convert hash entry to an arrayref
12214:       my $first=$env{$name};
12215:       undef($env{$name});
12216:       push(@{ $env{$name} },$first,$value);
12217:     }
12218:   } else {
12219:     $env{$name}=$value;
12220:   }
12221: }
12222: 
12223: =pod
12224: 
12225: =item * &get_env_multiple($name) 
12226: 
12227: gets $name from the %env hash, it seemlessly handles the cases where multiple
12228: values may be defined and end up as an array ref.
12229: 
12230: returns an array of values
12231: 
12232: =cut
12233: 
12234: sub get_env_multiple {
12235:     my ($name) = @_;
12236:     my @values;
12237:     if (defined($env{$name})) {
12238:         # exists is it an array
12239:         if (ref($env{$name})) {
12240:             @values=@{ $env{$name} };
12241:         } else {
12242:             $values[0]=$env{$name};
12243:         }
12244:     }
12245:     return(@values);
12246: }
12247: 
12248: # Looks at given dependencies, and returns something depending on the context.
12249: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
12250: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
12251: # For all other contexts, returns ($output, $counter, $numpathchg).
12252: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
12253: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
12254: # $numpathchg: integer with the number of cleaned up dependency paths.
12255: # \%existing: hash reference clean path -> 1 only for existing dependencies.
12256: # \%mapping: hash reference clean path -> original path for all dependencies.
12257: # @param {string} actionurl - The path to the handler, indicative of the context.
12258: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
12259: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
12260: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
12261: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
12262: # @return {Array} - array depending on the context (not a reference)
12263: sub ask_for_embedded_content {
12264:     # NOTE: documentation was added afterwards, it could be wrong
12265:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
12266:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
12267:         %currsubfile,%unused,$rem);
12268:     my $counter = 0;
12269:     my $numnew = 0;
12270:     my $numremref = 0;
12271:     my $numinvalid = 0;
12272:     my $numpathchg = 0;
12273:     my $numexisting = 0;
12274:     my $numunused = 0;
12275:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
12276:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
12277:     my $heading = &mt('Upload embedded files');
12278:     my $buttontext = &mt('Upload');
12279: 
12280:     # fills these variables based on the context:
12281:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
12282:     # $path, $fileloc, $title, $rem, $filename
12283:     if ($env{'request.course.id'}) {
12284:         if ($actionurl eq '/adm/dependencies') {
12285:             $navmap = Apache::lonnavmaps::navmap->new();
12286:         }
12287:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12288:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12289:     }
12290:     if (($actionurl eq '/adm/portfolio') || 
12291:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12292:         my $current_path='/';
12293:         if ($env{'form.currentpath'}) {
12294:             $current_path = $env{'form.currentpath'};
12295:         }
12296:         if ($actionurl eq '/adm/coursegrp_portfolio') {
12297:             $udom = $cdom;
12298:             $uname = $cnum;
12299:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12300:         } else {
12301:             $udom = $env{'user.domain'};
12302:             $uname = $env{'user.name'};
12303:             $url = '/userfiles/portfolio';
12304:         }
12305:         $toplevel = $url.'/';
12306:         $url .= $current_path;
12307:         $getpropath = 1;
12308:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12309:              ($actionurl eq '/adm/imsimport')) { 
12310:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12311:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12312:         $toplevel = $url;
12313:         if ($rest ne '') {
12314:             $url .= $rest;
12315:         }
12316:     } elsif ($actionurl eq '/adm/coursedocs') {
12317:         if (ref($args) eq 'HASH') {
12318:             $url = $args->{'docs_url'};
12319:             $toplevel = $url;
12320:             if ($args->{'context'} eq 'paste') {
12321:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12322:                 ($path) = 
12323:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12324:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12325:                 $fileloc =~ s{^/}{};
12326:             }
12327:         }
12328:     } elsif ($actionurl eq '/adm/dependencies')  {
12329:         if ($env{'request.course.id'} ne '') {
12330:             if (ref($args) eq 'HASH') {
12331:                 $url = $args->{'docs_url'};
12332:                 $title = $args->{'docs_title'};
12333:                 $toplevel = $url; 
12334:                 unless ($toplevel =~ m{^/}) {
12335:                     $toplevel = "/$url";
12336:                 }
12337:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12338:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12339:                     $path = $1;
12340:                 } else {
12341:                     ($path) =
12342:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12343:                 }
12344:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
12345:                     $fileloc = $toplevel;
12346:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12347:                     my ($udom,$uname,$fname) =
12348:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12349:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12350:                 } else {
12351:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12352:                 }
12353:                 $fileloc =~ s{^/}{};
12354:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12355:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12356:             }
12357:         }
12358:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12359:         $udom = $cdom;
12360:         $uname = $cnum;
12361:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12362:         $toplevel = $url;
12363:         $path = $url;
12364:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12365:         $fileloc =~ s{^/}{};
12366:     }
12367:     
12368:     # parses the dependency paths to get some info
12369:     # fills $newfiles, $mapping, $subdependencies, $dependencies
12370:     # $newfiles: hash URL -> 1 for new files or external URLs
12371:     # (will be completed later)
12372:     # $mapping:
12373:     #   for external URLs: external URL -> external URL
12374:     #   for relative paths: clean path -> original path
12375:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12376:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12377:     foreach my $file (keys(%{$allfiles})) {
12378:         my $embed_file;
12379:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12380:             $embed_file = $1;
12381:         } else {
12382:             $embed_file = $file;
12383:         }
12384:         my ($absolutepath,$cleaned_file);
12385:         if ($embed_file =~ m{^\w+://}) {
12386:             $cleaned_file = $embed_file;
12387:             $newfiles{$cleaned_file} = 1;
12388:             $mapping{$cleaned_file} = $embed_file;
12389:         } else {
12390:             $cleaned_file = &clean_path($embed_file);
12391:             if ($embed_file =~ m{^/}) {
12392:                 $absolutepath = $embed_file;
12393:             }
12394:             if ($cleaned_file =~ m{/}) {
12395:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12396:                 $path = &check_for_traversal($path,$url,$toplevel);
12397:                 my $item = $fname;
12398:                 if ($path ne '') {
12399:                     $item = $path.'/'.$fname;
12400:                     $subdependencies{$path}{$fname} = 1;
12401:                 } else {
12402:                     $dependencies{$item} = 1;
12403:                 }
12404:                 if ($absolutepath) {
12405:                     $mapping{$item} = $absolutepath;
12406:                 } else {
12407:                     $mapping{$item} = $embed_file;
12408:                 }
12409:             } else {
12410:                 $dependencies{$embed_file} = 1;
12411:                 if ($absolutepath) {
12412:                     $mapping{$cleaned_file} = $absolutepath;
12413:                 } else {
12414:                     $mapping{$cleaned_file} = $embed_file;
12415:                 }
12416:             }
12417:         }
12418:     }
12419:     
12420:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12421:     # and lists
12422:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12423:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12424:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12425:     #                                    the path had to be cleaned up
12426:     # $existing: hash clean path -> 1 if the file exists
12427:     # $numexisting: number of keys in $existing
12428:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12429:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12430:     #                                      dependency subdirectories that are
12431:     #                                      not listed as dependencies, with some exceptions using $rem
12432:     my $dirptr = 16384;
12433:     foreach my $path (keys(%subdependencies)) {
12434:         $currsubfile{$path} = {};
12435:         if (($actionurl eq '/adm/portfolio') || 
12436:             ($actionurl eq '/adm/coursegrp_portfolio')) {
12437:             my ($sublistref,$listerror) =
12438:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12439:             if (ref($sublistref) eq 'ARRAY') {
12440:                 foreach my $line (@{$sublistref}) {
12441:                     my ($file_name,$rest) = split(/\&/,$line,2);
12442:                     $currsubfile{$path}{$file_name} = 1;
12443:                 }
12444:             }
12445:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12446:             if (opendir(my $dir,$url.'/'.$path)) {
12447:                 my @subdir_list = grep(!/^\./,readdir($dir));
12448:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12449:             }
12450:         } elsif (($actionurl eq '/adm/dependencies') ||
12451:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12452:                   ($args->{'context'} eq 'paste')) ||
12453:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12454:             if ($env{'request.course.id'} ne '') {
12455:                 my $dir;
12456:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12457:                     $dir = $fileloc;
12458:                 } else {
12459:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12460:                 }
12461:                 if ($dir ne '') {
12462:                     my ($sublistref,$listerror) =
12463:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12464:                     if (ref($sublistref) eq 'ARRAY') {
12465:                         foreach my $line (@{$sublistref}) {
12466:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12467:                                 undef,$mtime)=split(/\&/,$line,12);
12468:                             unless (($testdir&$dirptr) ||
12469:                                     ($file_name =~ /^\.\.?$/)) {
12470:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
12471:                             }
12472:                         }
12473:                     }
12474:                 }
12475:             }
12476:         }
12477:         foreach my $file (keys(%{$subdependencies{$path}})) {
12478:             if (exists($currsubfile{$path}{$file})) {
12479:                 my $item = $path.'/'.$file;
12480:                 unless ($mapping{$item} eq $item) {
12481:                     $pathchanges{$item} = 1;
12482:                 }
12483:                 $existing{$item} = 1;
12484:                 $numexisting ++;
12485:             } else {
12486:                 $newfiles{$path.'/'.$file} = 1;
12487:             }
12488:         }
12489:         if ($actionurl eq '/adm/dependencies') {
12490:             foreach my $path (keys(%currsubfile)) {
12491:                 if (ref($currsubfile{$path}) eq 'HASH') {
12492:                     foreach my $file (keys(%{$currsubfile{$path}})) {
12493:                          unless ($subdependencies{$path}{$file}) {
12494:                              next if (($rem ne '') &&
12495:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
12496:                                        (ref($navmap) &&
12497:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12498:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12499:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
12500:                              $unused{$path.'/'.$file} = 1; 
12501:                          }
12502:                     }
12503:                 }
12504:             }
12505:         }
12506:     }
12507:     
12508:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
12509:     # for files in $url or $fileloc (target directory) in some contexts
12510:     my %currfile;
12511:     if (($actionurl eq '/adm/portfolio') ||
12512:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12513:         my ($dirlistref,$listerror) =
12514:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12515:         if (ref($dirlistref) eq 'ARRAY') {
12516:             foreach my $line (@{$dirlistref}) {
12517:                 my ($file_name,$rest) = split(/\&/,$line,2);
12518:                 $currfile{$file_name} = 1;
12519:             }
12520:         }
12521:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12522:         if (opendir(my $dir,$url)) {
12523:             my @dir_list = grep(!/^\./,readdir($dir));
12524:             map {$currfile{$_} = 1;} @dir_list;
12525:         }
12526:     } elsif (($actionurl eq '/adm/dependencies') ||
12527:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12528:               ($args->{'context'} eq 'paste')) ||
12529:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12530:         if ($env{'request.course.id'} ne '') {
12531:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12532:             if ($dir ne '') {
12533:                 my ($dirlistref,$listerror) =
12534:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12535:                 if (ref($dirlistref) eq 'ARRAY') {
12536:                     foreach my $line (@{$dirlistref}) {
12537:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12538:                             $size,undef,$mtime)=split(/\&/,$line,12);
12539:                         unless (($testdir&$dirptr) ||
12540:                                 ($file_name =~ /^\.\.?$/)) {
12541:                             $currfile{$file_name} = [$size,$mtime];
12542:                         }
12543:                     }
12544:                 }
12545:             }
12546:         }
12547:     }
12548:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12549:     # are not in subdirectories, using $currfile
12550:     foreach my $file (keys(%dependencies)) {
12551:         if (exists($currfile{$file})) {
12552:             unless ($mapping{$file} eq $file) {
12553:                 $pathchanges{$file} = 1;
12554:             }
12555:             $existing{$file} = 1;
12556:             $numexisting ++;
12557:         } else {
12558:             $newfiles{$file} = 1;
12559:         }
12560:     }
12561:     foreach my $file (keys(%currfile)) {
12562:         unless (($file eq $filename) ||
12563:                 ($file eq $filename.'.bak') ||
12564:                 ($dependencies{$file})) {
12565:             if ($actionurl eq '/adm/dependencies') {
12566:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12567:                     next if (($rem ne '') &&
12568:                              (($env{"httpref.$rem".$file} ne '') ||
12569:                               (ref($navmap) &&
12570:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
12571:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12572:                                 ($navmap->getResourceByUrl($rem.$1)))))));
12573:                 }
12574:             }
12575:             $unused{$file} = 1;
12576:         }
12577:     }
12578:     
12579:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12580:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12581:         ($args->{'context'} eq 'paste')) {
12582:         $counter = scalar(keys(%existing));
12583:         $numpathchg = scalar(keys(%pathchanges));
12584:         return ($output,$counter,$numpathchg,\%existing);
12585:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
12586:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12587:         $counter = scalar(keys(%existing));
12588:         $numpathchg = scalar(keys(%pathchanges));
12589:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
12590:     }
12591:     
12592:     # returns HTML otherwise, with dependency results and to ask for more uploads
12593:     
12594:     # $upload_output: missing dependencies (with upload form)
12595:     # $modify_output: uploaded dependencies (in use)
12596:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12597:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12598:         if ($actionurl eq '/adm/dependencies') {
12599:             next if ($embed_file =~ m{^\w+://});
12600:         }
12601:         $upload_output .= &start_data_table_row().
12602:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12603:                           '<span class="LC_filename">'.$embed_file.'</span>';
12604:         unless ($mapping{$embed_file} eq $embed_file) {
12605:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12606:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12607:         }
12608:         $upload_output .= '</td>';
12609:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
12610:             $upload_output.='<td align="right">'.
12611:                             '<span class="LC_info LC_fontsize_medium">'.
12612:                             &mt("URL points to web address").'</span>';
12613:             $numremref++;
12614:         } elsif ($args->{'error_on_invalid_names'}
12615:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12616:             $upload_output.='<td align="right"><span class="LC_warning">'.
12617:                             &mt('Invalid characters').'</span>';
12618:             $numinvalid++;
12619:         } else {
12620:             $upload_output .= '<td>'.
12621:                               &embedded_file_element('upload_embedded',$counter,
12622:                                                      $embed_file,\%mapping,
12623:                                                      $allfiles,$codebase,'upload');
12624:             $counter ++;
12625:             $numnew ++;
12626:         }
12627:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12628:     }
12629:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12630:         if ($actionurl eq '/adm/dependencies') {
12631:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12632:             $modify_output .= &start_data_table_row().
12633:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12634:                               '<img src="'.&icon($embed_file).'" border="0" />'.
12635:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
12636:                               '<td>'.$size.'</td>'.
12637:                               '<td>'.$mtime.'</td>'.
12638:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
12639:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12640:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12641:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12642:                               &embedded_file_element('upload_embedded',$counter,
12643:                                                      $embed_file,\%mapping,
12644:                                                      $allfiles,$codebase,'modify').
12645:                               '</div></td>'.
12646:                               &end_data_table_row()."\n";
12647:             $counter ++;
12648:         } else {
12649:             $upload_output .= &start_data_table_row().
12650:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12651:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
12652:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12653:                               &Apache::loncommon::end_data_table_row()."\n";
12654:         }
12655:     }
12656:     my $delidx = $counter;
12657:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12658:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12659:         $delete_output .= &start_data_table_row().
12660:                           '<td><img src="'.&icon($oldfile).'" />'.
12661:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
12662:                           '<td>'.$size.'</td>'.
12663:                           '<td>'.$mtime.'</td>'.
12664:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
12665:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12666:                           &embedded_file_element('upload_embedded',$delidx,
12667:                                                  $oldfile,\%mapping,$allfiles,
12668:                                                  $codebase,'delete').'</td>'.
12669:                           &end_data_table_row()."\n"; 
12670:         $numunused ++;
12671:         $delidx ++;
12672:     }
12673:     if ($upload_output) {
12674:         $upload_output = &start_data_table().
12675:                          $upload_output.
12676:                          &end_data_table()."\n";
12677:     }
12678:     if ($modify_output) {
12679:         $modify_output = &start_data_table().
12680:                          &start_data_table_header_row().
12681:                          '<th>'.&mt('File').'</th>'.
12682:                          '<th>'.&mt('Size (KB)').'</th>'.
12683:                          '<th>'.&mt('Modified').'</th>'.
12684:                          '<th>'.&mt('Upload replacement?').'</th>'.
12685:                          &end_data_table_header_row().
12686:                          $modify_output.
12687:                          &end_data_table()."\n";
12688:     }
12689:     if ($delete_output) {
12690:         $delete_output = &start_data_table().
12691:                          &start_data_table_header_row().
12692:                          '<th>'.&mt('File').'</th>'.
12693:                          '<th>'.&mt('Size (KB)').'</th>'.
12694:                          '<th>'.&mt('Modified').'</th>'.
12695:                          '<th>'.&mt('Delete?').'</th>'.
12696:                          &end_data_table_header_row().
12697:                          $delete_output.
12698:                          &end_data_table()."\n";
12699:     }
12700:     my $applies = 0;
12701:     if ($numremref) {
12702:         $applies ++;
12703:     }
12704:     if ($numinvalid) {
12705:         $applies ++;
12706:     }
12707:     if ($numexisting) {
12708:         $applies ++;
12709:     }
12710:     if ($counter || $numunused) {
12711:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12712:                   ' method="post" enctype="multipart/form-data">'."\n".
12713:                   $state.'<h3>'.$heading.'</h3>'; 
12714:         if ($actionurl eq '/adm/dependencies') {
12715:             if ($numnew) {
12716:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12717:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12718:                            $upload_output.'<br />'."\n";
12719:             }
12720:             if ($numexisting) {
12721:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12722:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12723:                            $modify_output.'<br />'."\n";
12724:                            $buttontext = &mt('Save changes');
12725:             }
12726:             if ($numunused) {
12727:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
12728:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12729:                            $delete_output.'<br />'."\n";
12730:                            $buttontext = &mt('Save changes');
12731:             }
12732:         } else {
12733:             $output .= $upload_output.'<br />'."\n";
12734:         }
12735:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12736:                    $counter.'" />'."\n";
12737:         if ($actionurl eq '/adm/dependencies') { 
12738:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12739:                        $numnew.'" />'."\n";
12740:         } elsif ($actionurl eq '') {
12741:             $output .=  '<input type="hidden" name="phase" value="three" />';
12742:         }
12743:     } elsif ($applies) {
12744:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12745:         if ($applies > 1) {
12746:             $output .=  
12747:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12748:             if ($numremref) {
12749:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12750:             }
12751:             if ($numinvalid) {
12752:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12753:             }
12754:             if ($numexisting) {
12755:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12756:             }
12757:             $output .= '</ul><br />';
12758:         } elsif ($numremref) {
12759:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12760:         } elsif ($numinvalid) {
12761:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12762:         } elsif ($numexisting) {
12763:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12764:         }
12765:         $output .= $upload_output.'<br />';
12766:     }
12767:     my ($pathchange_output,$chgcount);
12768:     $chgcount = $counter;
12769:     if (keys(%pathchanges) > 0) {
12770:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12771:             if ($counter) {
12772:                 $output .= &embedded_file_element('pathchange',$chgcount,
12773:                                                   $embed_file,\%mapping,
12774:                                                   $allfiles,$codebase,'change');
12775:             } else {
12776:                 $pathchange_output .= 
12777:                     &start_data_table_row().
12778:                     '<td><input type ="checkbox" name="namechange" value="'.
12779:                     $chgcount.'" checked="checked" /></td>'.
12780:                     '<td>'.$mapping{$embed_file}.'</td>'.
12781:                     '<td>'.$embed_file.
12782:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
12783:                                            \%mapping,$allfiles,$codebase,'change').
12784:                     '</td>'.&end_data_table_row();
12785:             }
12786:             $numpathchg ++;
12787:             $chgcount ++;
12788:         }
12789:     }
12790:     if (($counter) || ($numunused)) {
12791:         if ($numpathchg) {
12792:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12793:                        $numpathchg.'" />'."\n";
12794:         }
12795:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
12796:             ($actionurl eq '/adm/imsimport')) {
12797:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12798:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12799:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12800:         } elsif ($actionurl eq '/adm/dependencies') {
12801:             $output .= '<input type="hidden" name="action" value="process_changes" />';
12802:         }
12803:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12804:     } elsif ($numpathchg) {
12805:         my %pathchange = ();
12806:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12807:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12808:             $output .= '<p>'.&mt('or').'</p>'; 
12809:         }
12810:     }
12811:     return ($output,$counter,$numpathchg);
12812: }
12813: 
12814: =pod
12815: 
12816: =item * clean_path($name)
12817: 
12818: Performs clean-up of directories, subdirectories and filename in an
12819: embedded object, referenced in an HTML file which is being uploaded
12820: to a course or portfolio, where 
12821: "Upload embedded images/multimedia files if HTML file" checkbox was
12822: checked.
12823: 
12824: Clean-up is similar to replacements in lonnet::clean_filename()
12825: except each / between sub-directory and next level is preserved.
12826: 
12827: =cut
12828: 
12829: sub clean_path {
12830:     my ($embed_file) = @_;
12831:     $embed_file =~s{^/+}{};
12832:     my @contents;
12833:     if ($embed_file =~ m{/}) {
12834:         @contents = split(/\//,$embed_file);
12835:     } else {
12836:         @contents = ($embed_file);
12837:     }
12838:     my $lastidx = scalar(@contents)-1;
12839:     for (my $i=0; $i<=$lastidx; $i++) { 
12840:         $contents[$i]=~s{\\}{/}g;
12841:         $contents[$i]=~s/\s+/\_/g;
12842:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12843:         if ($i == $lastidx) {
12844:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12845:         }
12846:     }
12847:     if ($lastidx > 0) {
12848:         return join('/',@contents);
12849:     } else {
12850:         return $contents[0];
12851:     }
12852: }
12853: 
12854: sub embedded_file_element {
12855:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12856:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12857:                    (ref($codebase) eq 'HASH'));
12858:     my $output;
12859:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12860:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12861:     }
12862:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12863:                &escape($embed_file).'" />';
12864:     unless (($context eq 'upload_embedded') && 
12865:             ($mapping->{$embed_file} eq $embed_file)) {
12866:         $output .='
12867:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12868:     }
12869:     my $attrib;
12870:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12871:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12872:     }
12873:     $output .=
12874:         "\n\t\t".
12875:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12876:         $attrib.'" />';
12877:     if (exists($codebase->{$mapping->{$embed_file}})) {
12878:         $output .=
12879:             "\n\t\t".
12880:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12881:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12882:     }
12883:     return $output;
12884: }
12885: 
12886: sub get_dependency_details {
12887:     my ($currfile,$currsubfile,$embed_file) = @_;
12888:     my ($size,$mtime,$showsize,$showmtime);
12889:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12890:         if ($embed_file =~ m{/}) {
12891:             my ($path,$fname) = split(/\//,$embed_file);
12892:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12893:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12894:             }
12895:         } else {
12896:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12897:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12898:             }
12899:         }
12900:         $showsize = $size/1024.0;
12901:         $showsize = sprintf("%.1f",$showsize);
12902:         if ($mtime > 0) {
12903:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12904:         }
12905:     }
12906:     return ($showsize,$showmtime);
12907: }
12908: 
12909: sub ask_embedded_js {
12910:     return <<"END";
12911: <script type="text/javascript"">
12912: // <![CDATA[
12913: function toggleBrowse(counter) {
12914:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12915:     var fileid = document.getElementById('embedded_item_'+counter);
12916:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12917:     if (chkboxid.checked == true) {
12918:         uploaddivid.style.display='block';
12919:     } else {
12920:         uploaddivid.style.display='none';
12921:         fileid.value = '';
12922:     }
12923: }
12924: // ]]>
12925: </script>
12926: 
12927: END
12928: }
12929: 
12930: sub upload_embedded {
12931:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12932:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12933:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12934:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12935:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12936:         my $orig_uploaded_filename =
12937:             $env{'form.embedded_item_'.$i.'.filename'};
12938:         foreach my $type ('orig','ref','attrib','codebase') {
12939:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12940:                 $env{'form.embedded_'.$type.'_'.$i} =
12941:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12942:             }
12943:         }
12944:         my ($path,$fname) =
12945:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12946:         # no path, whole string is fname
12947:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12948:         $fname = &Apache::lonnet::clean_filename($fname);
12949:         # See if there is anything left
12950:         next if ($fname eq '');
12951: 
12952:         # Check if file already exists as a file or directory.
12953:         my ($state,$msg);
12954:         if ($context eq 'portfolio') {
12955:             my $port_path = $dirpath;
12956:             if ($group ne '') {
12957:                 $port_path = "groups/$group/$port_path";
12958:             }
12959:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12960:                                               $fname,$group,'embedded_item_'.$i,
12961:                                               $dir_root,$port_path,$disk_quota,
12962:                                               $current_disk_usage,$uname,$udom);
12963:             if ($state eq 'will_exceed_quota'
12964:                 || $state eq 'file_locked') {
12965:                 $output .= $msg;
12966:                 next;
12967:             }
12968:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12969:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12970:             if ($state eq 'exists') {
12971:                 $output .= $msg;
12972:                 next;
12973:             }
12974:         }
12975:         # Check if extension is valid
12976:         if (($fname =~ /\.(\w+)$/) &&
12977:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12978:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12979:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12980:             next;
12981:         } elsif (($fname =~ /\.(\w+)$/) &&
12982:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12983:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12984:             next;
12985:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12986:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12987:             next;
12988:         }
12989:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12990:         my $subdir = $path;
12991:         $subdir =~ s{/+$}{};
12992:         if ($context eq 'portfolio') {
12993:             my $result;
12994:             if ($state eq 'existingfile') {
12995:                 $result=
12996:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12997:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12998:             } else {
12999:                 $result=
13000:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
13001:                                                     $dirpath.
13002:                                                     $env{'form.currentpath'}.$subdir);
13003:                 if ($result !~ m|^/uploaded/|) {
13004:                     $output .= '<span class="LC_error">'
13005:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13006:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13007:                                .'</span><br />';
13008:                     next;
13009:                 } else {
13010:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13011:                                $path.$fname.'</span>').'<br />';     
13012:                 }
13013:             }
13014:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
13015:             my $extendedsubdir = $dirpath.'/'.$subdir;
13016:             $extendedsubdir =~ s{/+$}{};
13017:             my $result =
13018:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
13019:             if ($result !~ m|^/uploaded/|) {
13020:                 $output .= '<span class="LC_error">'
13021:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13022:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13023:                            .'</span><br />';
13024:                     next;
13025:             } else {
13026:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13027:                            $path.$fname.'</span>').'<br />';
13028:                 if ($context eq 'syllabus') {
13029:                     &Apache::lonnet::make_public_indefinitely($result);
13030:                 }
13031:             }
13032:         } else {
13033: # Save the file
13034:             my $target = $env{'form.embedded_item_'.$i};
13035:             my $fullpath = $dir_root.$dirpath.'/'.$path;
13036:             my $dest = $fullpath.$fname;
13037:             my $url = $url_root.$dirpath.'/'.$path.$fname;
13038:             my @parts=split(/\//,"$dirpath/$path");
13039:             my $count;
13040:             my $filepath = $dir_root;
13041:             foreach my $subdir (@parts) {
13042:                 $filepath .= "/$subdir";
13043:                 if (!-e $filepath) {
13044:                     mkdir($filepath,0770);
13045:                 }
13046:             }
13047:             my $fh;
13048:             if (!open($fh,'>'.$dest)) {
13049:                 &Apache::lonnet::logthis('Failed to create '.$dest);
13050:                 $output .= '<span class="LC_error">'.
13051:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
13052:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13053:                            '</span><br />';
13054:             } else {
13055:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
13056:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
13057:                     $output .= '<span class="LC_error">'.
13058:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
13059:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13060:                               '</span><br />';
13061:                 } else {
13062:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13063:                                $url.'</span>').'<br />';
13064:                     unless ($context eq 'testbank') {
13065:                         $footer .= &mt('View embedded file: [_1]',
13066:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
13067:                     }
13068:                 }
13069:                 close($fh);
13070:             }
13071:         }
13072:         if ($env{'form.embedded_ref_'.$i}) {
13073:             $pathchange{$i} = 1;
13074:         }
13075:     }
13076:     if ($output) {
13077:         $output = '<p>'.$output.'</p>';
13078:     }
13079:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
13080:     $returnflag = 'ok';
13081:     my $numpathchgs = scalar(keys(%pathchange));
13082:     if ($numpathchgs > 0) {
13083:         if ($context eq 'portfolio') {
13084:             $output .= '<p>'.&mt('or').'</p>';
13085:         } elsif ($context eq 'testbank') {
13086:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
13087:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
13088:             $returnflag = 'modify_orightml';
13089:         }
13090:     }
13091:     return ($output.$footer,$returnflag,$numpathchgs);
13092: }
13093: 
13094: sub modify_html_form {
13095:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
13096:     my $end = 0;
13097:     my $modifyform;
13098:     if ($context eq 'upload_embedded') {
13099:         return unless (ref($pathchange) eq 'HASH');
13100:         if ($env{'form.number_embedded_items'}) {
13101:             $end += $env{'form.number_embedded_items'};
13102:         }
13103:         if ($env{'form.number_pathchange_items'}) {
13104:             $end += $env{'form.number_pathchange_items'};
13105:         }
13106:         if ($end) {
13107:             for (my $i=0; $i<$end; $i++) {
13108:                 if ($i < $env{'form.number_embedded_items'}) {
13109:                     next unless($pathchange->{$i});
13110:                 }
13111:                 $modifyform .=
13112:                     &start_data_table_row().
13113:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
13114:                     'checked="checked" /></td>'.
13115:                     '<td>'.$env{'form.embedded_ref_'.$i}.
13116:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
13117:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
13118:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
13119:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
13120:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
13121:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
13122:                     '<td>'.$env{'form.embedded_orig_'.$i}.
13123:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
13124:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
13125:                     &end_data_table_row();
13126:             }
13127:         }
13128:     } else {
13129:         $modifyform = $pathchgtable;
13130:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
13131:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
13132:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13133:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
13134:         }
13135:     }
13136:     if ($modifyform) {
13137:         if ($actionurl eq '/adm/dependencies') {
13138:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
13139:         }
13140:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
13141:                '<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".
13142:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
13143:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
13144:                '</ol></p>'."\n".'<p>'.
13145:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
13146:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
13147:                &start_data_table()."\n".
13148:                &start_data_table_header_row().
13149:                '<th>'.&mt('Change?').'</th>'.
13150:                '<th>'.&mt('Current reference').'</th>'.
13151:                '<th>'.&mt('Required reference').'</th>'.
13152:                &end_data_table_header_row()."\n".
13153:                $modifyform.
13154:                &end_data_table().'<br />'."\n".$hiddenstate.
13155:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
13156:                '</form>'."\n";
13157:     }
13158:     return;
13159: }
13160: 
13161: sub modify_html_refs {
13162:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
13163:     my $container;
13164:     if ($context eq 'portfolio') {
13165:         $container = $env{'form.container'};
13166:     } elsif ($context eq 'coursedoc') {
13167:         $container = $env{'form.primaryurl'};
13168:     } elsif ($context eq 'manage_dependencies') {
13169:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
13170:         $container = "/$container";
13171:     } elsif ($context eq 'syllabus') {
13172:         $container = $url;
13173:     } else {
13174:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
13175:     }
13176:     my (%allfiles,%codebase,$output,$content);
13177:     my @changes = &get_env_multiple('form.namechange');
13178:     unless ((@changes > 0) || ($context eq 'syllabus')) {
13179:         if (wantarray) {
13180:             return ('',0,0); 
13181:         } else {
13182:             return;
13183:         }
13184:     }
13185:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13186:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13187:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
13188:             if (wantarray) {
13189:                 return ('',0,0);
13190:             } else {
13191:                 return;
13192:             }
13193:         } 
13194:         $content = &Apache::lonnet::getfile($container);
13195:         if ($content eq '-1') {
13196:             if (wantarray) {
13197:                 return ('',0,0);
13198:             } else {
13199:                 return;
13200:             }
13201:         }
13202:     } else {
13203:         unless ($container =~ /^\Q$dir_root\E/) {
13204:             if (wantarray) {
13205:                 return ('',0,0);
13206:             } else {
13207:                 return;
13208:             }
13209:         } 
13210:         if (open(my $fh,'<',$container)) {
13211:             $content = join('', <$fh>);
13212:             close($fh);
13213:         } else {
13214:             if (wantarray) {
13215:                 return ('',0,0);
13216:             } else {
13217:                 return;
13218:             }
13219:         }
13220:     }
13221:     my ($count,$codebasecount) = (0,0);
13222:     my $mm = new File::MMagic;
13223:     my $mime_type = $mm->checktype_contents($content);
13224:     if ($mime_type eq 'text/html') {
13225:         my $parse_result = 
13226:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
13227:                                                     \%codebase,\$content);
13228:         if ($parse_result eq 'ok') {
13229:             foreach my $i (@changes) {
13230:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
13231:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
13232:                 if ($allfiles{$ref}) {
13233:                     my $newname =  $orig;
13234:                     my ($attrib_regexp,$codebase);
13235:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
13236:                     if ($attrib_regexp =~ /:/) {
13237:                         $attrib_regexp =~ s/\:/|/g;
13238:                     }
13239:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13240:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13241:                         $count += $numchg;
13242:                         $allfiles{$newname} = $allfiles{$ref};
13243:                         delete($allfiles{$ref});
13244:                     }
13245:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
13246:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
13247:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
13248:                         $codebasecount ++;
13249:                     }
13250:                 }
13251:             }
13252:             my $skiprewrites;
13253:             if ($count || $codebasecount) {
13254:                 my $saveresult;
13255:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13256:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13257:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13258:                     if ($url eq $container) {
13259:                         my ($fname) = ($container =~ m{/([^/]+)$});
13260:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13261:                                             $count,'<span class="LC_filename">'.
13262:                                             $fname.'</span>').'</p>';
13263:                     } else {
13264:                          $output = '<p class="LC_error">'.
13265:                                    &mt('Error: update failed for: [_1].',
13266:                                    '<span class="LC_filename">'.
13267:                                    $container.'</span>').'</p>';
13268:                     }
13269:                     if ($context eq 'syllabus') {
13270:                         unless ($saveresult eq 'ok') {
13271:                             $skiprewrites = 1;
13272:                         }
13273:                     }
13274:                 } else {
13275:                     if (open(my $fh,'>',$container)) {
13276:                         print $fh $content;
13277:                         close($fh);
13278:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13279:                                   $count,'<span class="LC_filename">'.
13280:                                   $container.'</span>').'</p>';
13281:                     } else {
13282:                          $output = '<p class="LC_error">'.
13283:                                    &mt('Error: could not update [_1].',
13284:                                    '<span class="LC_filename">'.
13285:                                    $container.'</span>').'</p>';
13286:                     }
13287:                 }
13288:             }
13289:             if (($context eq 'syllabus') && (!$skiprewrites)) {
13290:                 my ($actionurl,$state);
13291:                 $actionurl = "/public/$udom/$uname/syllabus";
13292:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
13293:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
13294:                                               \%codebase,
13295:                                               {'context' => 'rewrites',
13296:                                                'ignore_remote_references' => 1,});
13297:                 if (ref($mapping) eq 'HASH') {
13298:                     my $rewrites = 0;
13299:                     foreach my $key (keys(%{$mapping})) {
13300:                         next if ($key =~ m{^https?://});
13301:                         my $ref = $mapping->{$key};
13302:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13303:                         my $attrib;
13304:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13305:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13306:                         }
13307:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13308:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13309:                             $rewrites += $numchg;
13310:                         }
13311:                     }
13312:                     if ($rewrites) {
13313:                         my $saveresult; 
13314:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13315:                         if ($url eq $container) {
13316:                             my ($fname) = ($container =~ m{/([^/]+)$});
13317:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13318:                                             $count,'<span class="LC_filename">'.
13319:                                             $fname.'</span>').'</p>';
13320:                         } else {
13321:                             $output .= '<p class="LC_error">'.
13322:                                        &mt('Error: could not update links in [_1].',
13323:                                        '<span class="LC_filename">'.
13324:                                        $container.'</span>').'</p>';
13325: 
13326:                         }
13327:                     }
13328:                 }
13329:             }
13330:         } else {
13331:             &logthis('Failed to parse '.$container.
13332:                      ' to modify references: '.$parse_result);
13333:         }
13334:     }
13335:     if (wantarray) {
13336:         return ($output,$count,$codebasecount);
13337:     } else {
13338:         return $output;
13339:     }
13340: }
13341: 
13342: sub check_for_existing {
13343:     my ($path,$fname,$element) = @_;
13344:     my ($state,$msg);
13345:     if (-d $path.'/'.$fname) {
13346:         $state = 'exists';
13347:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13348:     } elsif (-e $path.'/'.$fname) {
13349:         $state = 'exists';
13350:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13351:     }
13352:     if ($state eq 'exists') {
13353:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
13354:     }
13355:     return ($state,$msg);
13356: }
13357: 
13358: sub check_for_upload {
13359:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13360:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13361:     my $filesize = length($env{'form.'.$element});
13362:     if (!$filesize) {
13363:         my $msg = '<span class="LC_error">'.
13364:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
13365:                       '<span class="LC_filename">'.$fname.'</span>',
13366:                       $filesize).'<br />'.
13367:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13368:                   '</span>';
13369:         return ('zero_bytes',$msg);
13370:     }
13371:     $filesize =  $filesize/1000; #express in k (1024?)
13372:     my $getpropath = 1;
13373:     my ($dirlistref,$listerror) =
13374:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13375:     my $found_file = 0;
13376:     my $locked_file = 0;
13377:     my @lockers;
13378:     my $navmap;
13379:     if ($env{'request.course.id'}) {
13380:         $navmap = Apache::lonnavmaps::navmap->new();
13381:     }
13382:     if (ref($dirlistref) eq 'ARRAY') {
13383:         foreach my $line (@{$dirlistref}) {
13384:             my ($file_name,$rest)=split(/\&/,$line,2);
13385:             if ($file_name eq $fname){
13386:                 $file_name = $path.$file_name;
13387:                 if ($group ne '') {
13388:                     $file_name = $group.$file_name;
13389:                 }
13390:                 $found_file = 1;
13391:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13392:                     foreach my $lock (@lockers) {
13393:                         if (ref($lock) eq 'ARRAY') {
13394:                             my ($symb,$crsid) = @{$lock};
13395:                             if ($crsid eq $env{'request.course.id'}) {
13396:                                 if (ref($navmap)) {
13397:                                     my $res = $navmap->getBySymb($symb);
13398:                                     foreach my $part (@{$res->parts()}) { 
13399:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13400:                                         unless (($slot_status == $res->RESERVED) ||
13401:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
13402:                                             $locked_file = 1;
13403:                                         }
13404:                                     }
13405:                                 } else {
13406:                                     $locked_file = 1;
13407:                                 }
13408:                             } else {
13409:                                 $locked_file = 1;
13410:                             }
13411:                         }
13412:                    }
13413:                 } else {
13414:                     my @info = split(/\&/,$rest);
13415:                     my $currsize = $info[6]/1000;
13416:                     if ($currsize < $filesize) {
13417:                         my $extra = $filesize - $currsize;
13418:                         if (($current_disk_usage + $extra) > $disk_quota) {
13419:                             my $msg = '<p class="LC_warning">'.
13420:                                       &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.',
13421:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13422:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13423:                                                    $disk_quota,$current_disk_usage).'</p>';
13424:                             return ('will_exceed_quota',$msg);
13425:                         }
13426:                     }
13427:                 }
13428:             }
13429:         }
13430:     }
13431:     if (($current_disk_usage + $filesize) > $disk_quota){
13432:         my $msg = '<p class="LC_warning">'.
13433:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13434:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13435:         return ('will_exceed_quota',$msg);
13436:     } elsif ($found_file) {
13437:         if ($locked_file) {
13438:             my $msg = '<p class="LC_warning">';
13439:             $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>');
13440:             $msg .= '</p>';
13441:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13442:             return ('file_locked',$msg);
13443:         } else {
13444:             my $msg = '<p class="LC_error">';
13445:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13446:             $msg .= '</p>';
13447:             return ('existingfile',$msg);
13448:         }
13449:     }
13450: }
13451: 
13452: sub check_for_traversal {
13453:     my ($path,$url,$toplevel) = @_;
13454:     my @parts=split(/\//,$path);
13455:     my $cleanpath;
13456:     my $fullpath = $url;
13457:     for (my $i=0;$i<@parts;$i++) {
13458:         next if ($parts[$i] eq '.');
13459:         if ($parts[$i] eq '..') {
13460:             $fullpath =~ s{([^/]+/)$}{};
13461:         } else {
13462:             $fullpath .= $parts[$i].'/';
13463:         }
13464:     }
13465:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
13466:         $cleanpath = $1;
13467:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13468:         my $curr_toprel = $1;
13469:         my @parts = split(/\//,$curr_toprel);
13470:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13471:         my @urlparts = split(/\//,$url_toprel);
13472:         my $doubledots;
13473:         my $startdiff = -1;
13474:         for (my $i=0; $i<@urlparts; $i++) {
13475:             if ($startdiff == -1) {
13476:                 unless ($urlparts[$i] eq $parts[$i]) {
13477:                     $startdiff = $i;
13478:                     $doubledots .= '../';
13479:                 }
13480:             } else {
13481:                 $doubledots .= '../';
13482:             }
13483:         }
13484:         if ($startdiff > -1) {
13485:             $cleanpath = $doubledots;
13486:             for (my $i=$startdiff; $i<@parts; $i++) {
13487:                 $cleanpath .= $parts[$i].'/';
13488:             }
13489:         }
13490:     }
13491:     $cleanpath =~ s{(/)$}{};
13492:     return $cleanpath;
13493: }
13494: 
13495: sub is_archive_file {
13496:     my ($mimetype) = @_;
13497:     if (($mimetype eq 'application/octet-stream') ||
13498:         ($mimetype eq 'application/x-stuffit') ||
13499:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13500:         return 1;
13501:     }
13502:     return;
13503: }
13504: 
13505: sub decompress_form {
13506:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13507:     my %lt = &Apache::lonlocal::texthash (
13508:         this => 'This file is an archive file.',
13509:         camt => 'This file is a Camtasia archive file.',
13510:         itsc => 'Its contents are as follows:',
13511:         youm => 'You may wish to extract its contents.',
13512:         extr => 'Extract contents',
13513:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13514:         proa => 'Process automatically?',
13515:         yes  => 'Yes',
13516:         no   => 'No',
13517:         fold => 'Title for folder containing movie',
13518:         movi => 'Title for page containing embedded movie', 
13519:     );
13520:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13521:     my ($is_camtasia,$topdir,%toplevel,@paths);
13522:     my $info = &list_archive_contents($fileloc,\@paths);
13523:     if (@paths) {
13524:         foreach my $path (@paths) {
13525:             $path =~ s{^/}{};
13526:             if ($path =~ m{^([^/]+)/$}) {
13527:                 $topdir = $1;
13528:             }
13529:             if ($path =~ m{^([^/]+)/}) {
13530:                 $toplevel{$1} = $path;
13531:             } else {
13532:                 $toplevel{$path} = $path;
13533:             }
13534:         }
13535:     }
13536:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13537:         my @camtasia6 = ("$topdir/","$topdir/index.html",
13538:                         "$topdir/media/",
13539:                         "$topdir/media/$topdir.mp4",
13540:                         "$topdir/media/FirstFrame.png",
13541:                         "$topdir/media/player.swf",
13542:                         "$topdir/media/swfobject.js",
13543:                         "$topdir/media/expressInstall.swf");
13544:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13545:                          "$topdir/$topdir.mp4",
13546:                          "$topdir/$topdir\_config.xml",
13547:                          "$topdir/$topdir\_controller.swf",
13548:                          "$topdir/$topdir\_embed.css",
13549:                          "$topdir/$topdir\_First_Frame.png",
13550:                          "$topdir/$topdir\_player.html",
13551:                          "$topdir/$topdir\_Thumbnails.png",
13552:                          "$topdir/playerProductInstall.swf",
13553:                          "$topdir/scripts/",
13554:                          "$topdir/scripts/config_xml.js",
13555:                          "$topdir/scripts/handlebars.js",
13556:                          "$topdir/scripts/jquery-1.7.1.min.js",
13557:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13558:                          "$topdir/scripts/modernizr.js",
13559:                          "$topdir/scripts/player-min.js",
13560:                          "$topdir/scripts/swfobject.js",
13561:                          "$topdir/skins/",
13562:                          "$topdir/skins/configuration_express.xml",
13563:                          "$topdir/skins/express_show/",
13564:                          "$topdir/skins/express_show/player-min.css",
13565:                          "$topdir/skins/express_show/spritesheet.png");
13566:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13567:                          "$topdir/$topdir.mp4",
13568:                          "$topdir/$topdir\_config.xml",
13569:                          "$topdir/$topdir\_controller.swf",
13570:                          "$topdir/$topdir\_embed.css",
13571:                          "$topdir/$topdir\_First_Frame.png",
13572:                          "$topdir/$topdir\_player.html",
13573:                          "$topdir/$topdir\_Thumbnails.png",
13574:                          "$topdir/playerProductInstall.swf",
13575:                          "$topdir/scripts/",
13576:                          "$topdir/scripts/config_xml.js",
13577:                          "$topdir/scripts/techsmith-smart-player.min.js",
13578:                          "$topdir/skins/",
13579:                          "$topdir/skins/configuration_express.xml",
13580:                          "$topdir/skins/express_show/",
13581:                          "$topdir/skins/express_show/spritesheet.min.css",
13582:                          "$topdir/skins/express_show/spritesheet.png",
13583:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
13584:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
13585:         if (@diffs == 0) {
13586:             $is_camtasia = 6;
13587:         } else {
13588:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13589:             if (@diffs == 0) {
13590:                 $is_camtasia = 8;
13591:             } else {
13592:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13593:                 if (@diffs == 0) {
13594:                     $is_camtasia = 8;
13595:                 }
13596:             }
13597:         }
13598:     }
13599:     my $output;
13600:     if ($is_camtasia) {
13601:         $output = <<"ENDCAM";
13602: <script type="text/javascript" language="Javascript">
13603: // <![CDATA[
13604: 
13605: function camtasiaToggle() {
13606:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13607:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13608:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13609:                 document.getElementById('camtasia_titles').style.display='block';
13610:             } else {
13611:                 document.getElementById('camtasia_titles').style.display='none';
13612:             }
13613:         }
13614:     }
13615:     return;
13616: }
13617: 
13618: // ]]>
13619: </script>
13620: <p>$lt{'camt'}</p>
13621: ENDCAM
13622:     } else {
13623:         $output = '<p>'.$lt{'this'};
13624:         if ($info eq '') {
13625:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
13626:         } else {
13627:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13628:                        '<div><pre>'.$info.'</pre></div>';
13629:         }
13630:     }
13631:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13632:     my $duplicates;
13633:     my $num = 0;
13634:     if (ref($dirlist) eq 'ARRAY') {
13635:         foreach my $item (@{$dirlist}) {
13636:             if (ref($item) eq 'ARRAY') {
13637:                 if (exists($toplevel{$item->[0]})) {
13638:                     $duplicates .= 
13639:                         &start_data_table_row().
13640:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13641:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
13642:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
13643:                         'value="1" />'.&mt('Yes').'</label>'.
13644:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13645:                         '<td>'.$item->[0].'</td>';
13646:                     if ($item->[2]) {
13647:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
13648:                     } else {
13649:                         $duplicates .= '<td>'.&mt('File').'</td>';
13650:                     }
13651:                     $duplicates .= '<td>'.$item->[3].'</td>'.
13652:                                    '<td>'.
13653:                                    &Apache::lonlocal::locallocaltime($item->[4]).
13654:                                    '</td>'.
13655:                                    &end_data_table_row();
13656:                     $num ++;
13657:                 }
13658:             }
13659:         }
13660:     }
13661:     my $itemcount;
13662:     if (@paths > 0) {
13663:         $itemcount = scalar(@paths);
13664:     } else {
13665:         $itemcount = 1;
13666:     }
13667:     if ($is_camtasia) {
13668:         $output .= $lt{'auto'}.'<br />'.
13669:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13670:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13671:                    $lt{'yes'}.'</label>&nbsp;<label>'.
13672:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13673:                    $lt{'no'}.'</label></span><br />'.
13674:                    '<div id="camtasia_titles" style="display:block">'.
13675:                    &Apache::lonhtmlcommon::start_pick_box().
13676:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13677:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13678:                    &Apache::lonhtmlcommon::row_closure().
13679:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13680:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13681:                    &Apache::lonhtmlcommon::row_closure(1).
13682:                    &Apache::lonhtmlcommon::end_pick_box().
13683:                    '</div>';
13684:     }
13685:     $output .= 
13686:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13687:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13688:         "\n";
13689:     if ($duplicates ne '') {
13690:         $output .= '<p><span class="LC_warning">'.
13691:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
13692:                    &start_data_table().
13693:                    &start_data_table_header_row().
13694:                    '<th>'.&mt('Overwrite?').'</th>'.
13695:                    '<th>'.&mt('Name').'</th>'.
13696:                    '<th>'.&mt('Type').'</th>'.
13697:                    '<th>'.&mt('Size').'</th>'.
13698:                    '<th>'.&mt('Last modified').'</th>'.
13699:                    &end_data_table_header_row().
13700:                    $duplicates.
13701:                    &end_data_table().
13702:                    '</p>';
13703:     }
13704:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13705:     if (ref($hiddenelements) eq 'HASH') {
13706:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13707:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13708:         }
13709:     }
13710:     $output .= <<"END";
13711: <br />
13712: <input type="submit" name="decompress" value="$lt{'extr'}" />
13713: </form>
13714: $noextract
13715: END
13716:     return $output;
13717: }
13718: 
13719: sub decompression_utility {
13720:     my ($program) = @_;
13721:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
13722:     my $location;
13723:     if (grep(/^\Q$program\E$/,@utilities)) { 
13724:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13725:                          '/usr/sbin/') {
13726:             if (-x $dir.$program) {
13727:                 $location = $dir.$program;
13728:                 last;
13729:             }
13730:         }
13731:     }
13732:     return $location;
13733: }
13734: 
13735: sub list_archive_contents {
13736:     my ($file,$pathsref) = @_;
13737:     my (@cmd,$output);
13738:     my $needsregexp;
13739:     if ($file =~ /\.zip$/) {
13740:         @cmd = (&decompression_utility('unzip'),"-l");
13741:         $needsregexp = 1;
13742:     } elsif (($file =~ m/\.tar\.gz$/) ||
13743:              ($file =~ /\.tgz$/)) {
13744:         @cmd = (&decompression_utility('tar'),"-ztf");
13745:     } elsif ($file =~ /\.tar\.bz2$/) {
13746:         @cmd = (&decompression_utility('tar'),"-jtf");
13747:     } elsif ($file =~ m|\.tar$|) {
13748:         @cmd = (&decompression_utility('tar'),"-tf");
13749:     }
13750:     if (@cmd) {
13751:         undef($!);
13752:         undef($@);
13753:         if (open(my $fh,"-|", @cmd, $file)) {
13754:             while (my $line = <$fh>) {
13755:                 $output .= $line;
13756:                 chomp($line);
13757:                 my $item;
13758:                 if ($needsregexp) {
13759:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
13760:                 } else {
13761:                     $item = $line;
13762:                 }
13763:                 if ($item ne '') {
13764:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13765:                         push(@{$pathsref},$item);
13766:                     } 
13767:                 }
13768:             }
13769:             close($fh);
13770:         }
13771:     }
13772:     return $output;
13773: }
13774: 
13775: sub decompress_uploaded_file {
13776:     my ($file,$dir) = @_;
13777:     &Apache::lonnet::appenv({'cgi.file' => $file});
13778:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
13779:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13780:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13781:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13782:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13783:     my $decompressed = $env{'cgi.decompressed'};
13784:     &Apache::lonnet::delenv('cgi.file');
13785:     &Apache::lonnet::delenv('cgi.dir');
13786:     &Apache::lonnet::delenv('cgi.decompressed');
13787:     return ($decompressed,$result);
13788: }
13789: 
13790: sub process_decompression {
13791:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13792:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13793:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13794:                &mt('Unexpected file path.').'</p>'."\n";
13795:     }
13796:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13797:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13798:                &mt('Unexpected course context.').'</p>'."\n";
13799:     }
13800:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
13801:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13802:                &mt('Filename contained unexpected characters.').'</p>'."\n";
13803:     }
13804:     my ($dir,$error,$warning,$output);
13805:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13806:         $error = &mt('Filename not a supported archive file type.').
13807:                  '<br />'.&mt('Filename should end with one of: [_1].',
13808:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13809:     } else {
13810:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13811:         if ($docuhome eq 'no_host') {
13812:             $error = &mt('Could not determine home server for course.');
13813:         } else {
13814:             my @ids=&Apache::lonnet::current_machine_ids();
13815:             my $currdir = "$dir_root/$destination";
13816:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13817:                 $dir = &LONCAPA::propath($docudom,$docuname).
13818:                        "$dir_root/$destination";
13819:             } else {
13820:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13821:                        "$dir_root/$docudom/$docuname/$destination";
13822:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13823:                     $error = &mt('Archive file not found.');
13824:                 }
13825:             }
13826:             my (@to_overwrite,@to_skip);
13827:             if ($env{'form.archive_overwrite_total'} > 0) {
13828:                 my $total = $env{'form.archive_overwrite_total'};
13829:                 for (my $i=0; $i<$total; $i++) {
13830:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13831:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13832:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13833:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13834:                     }
13835:                 }
13836:             }
13837:             my $numskip = scalar(@to_skip);
13838:             my $numoverwrite = scalar(@to_overwrite);
13839:             if (($numskip) && (!$numoverwrite)) { 
13840:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13841:             } elsif ($dir eq '') {
13842:                 $error = &mt('Directory containing archive file unavailable.');
13843:             } elsif (!$error) {
13844:                 my ($decompressed,$display);
13845:                 if (($numskip) || ($numoverwrite)) {
13846:                     my $tempdir = time.'_'.$$.int(rand(10000));
13847:                     mkdir("$dir/$tempdir",0755);
13848:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13849:                         ($decompressed,$display) = 
13850:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13851:                         foreach my $item (@to_skip) {
13852:                             if (($item ne '') && ($item !~ /\.\./)) {
13853:                                 if (-f "$dir/$tempdir/$item") { 
13854:                                     unlink("$dir/$tempdir/$item");
13855:                                 } elsif (-d "$dir/$tempdir/$item") {
13856:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13857:                                 }
13858:                             }
13859:                         }
13860:                         foreach my $item (@to_overwrite) {
13861:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13862:                                 if (($item ne '') && ($item !~ /\.\./)) {
13863:                                     if (-f "$dir/$item") {
13864:                                         unlink("$dir/$item");
13865:                                     } elsif (-d "$dir/$item") {
13866:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13867:                                     }
13868:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13869:                                 }
13870:                             }
13871:                         }
13872:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13873:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13874:                         }
13875:                     }
13876:                 } else {
13877:                     ($decompressed,$display) = 
13878:                         &decompress_uploaded_file($file,$dir);
13879:                 }
13880:                 if ($decompressed eq 'ok') {
13881:                     $output = '<p class="LC_info">'.
13882:                               &mt('Files extracted successfully from archive.').
13883:                               '</p>'."\n";
13884:                     my ($warning,$result,@contents);
13885:                     my ($newdirlistref,$newlisterror) =
13886:                         &Apache::lonnet::dirlist($currdir,$docudom,
13887:                                                  $docuname,1);
13888:                     my (%is_dir,%changes,@newitems);
13889:                     my $dirptr = 16384;
13890:                     if (ref($newdirlistref) eq 'ARRAY') {
13891:                         foreach my $dir_line (@{$newdirlistref}) {
13892:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13893:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
13894:                                 push(@newitems,$item);
13895:                                 if ($dirptr&$testdir) {
13896:                                     $is_dir{$item} = 1;
13897:                                 }
13898:                                 $changes{$item} = 1;
13899:                             }
13900:                         }
13901:                     }
13902:                     if (keys(%changes) > 0) {
13903:                         foreach my $item (sort(@newitems)) {
13904:                             if ($changes{$item}) {
13905:                                 push(@contents,$item);
13906:                             }
13907:                         }
13908:                     }
13909:                     if (@contents > 0) {
13910:                         my $wantform;
13911:                         unless ($env{'form.autoextract_camtasia'}) {
13912:                             $wantform = 1;
13913:                         }
13914:                         my (%children,%parent,%dirorder,%titles);
13915:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13916:                                                                 $currdir,\%is_dir,
13917:                                                                 \%children,\%parent,
13918:                                                                 \@contents,\%dirorder,
13919:                                                                 \%titles,$wantform);
13920:                         if ($datatable ne '') {
13921:                             $output .= &archive_options_form('decompressed',$datatable,
13922:                                                              $count,$hiddenelem);
13923:                             my $startcount = 6;
13924:                             $output .= &archive_javascript($startcount,$count,
13925:                                                            \%titles,\%children);
13926:                         }
13927:                         if ($env{'form.autoextract_camtasia'}) {
13928:                             my $version = $env{'form.autoextract_camtasia'};
13929:                             my %displayed;
13930:                             my $total = 1;
13931:                             $env{'form.archive_directory'} = [];
13932:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13933:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13934:                                 $path =~ s{/$}{};
13935:                                 my $item;
13936:                                 if ($path ne '') {
13937:                                     $item = "$path/$titles{$i}";
13938:                                 } else {
13939:                                     $item = $titles{$i};
13940:                                 }
13941:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13942:                                 if ($item eq $contents[0]) {
13943:                                     push(@{$env{'form.archive_directory'}},$i);
13944:                                     $env{'form.archive_'.$i} = 'display';
13945:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13946:                                     $displayed{'folder'} = $i;
13947:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13948:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
13949:                                     $env{'form.archive_'.$i} = 'display';
13950:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13951:                                     $displayed{'web'} = $i;
13952:                                 } else {
13953:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13954:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13955:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13956:                                         push(@{$env{'form.archive_directory'}},$i);
13957:                                     }
13958:                                     $env{'form.archive_'.$i} = 'dependency';
13959:                                 }
13960:                                 $total ++;
13961:                             }
13962:                             for (my $i=1; $i<$total; $i++) {
13963:                                 next if ($i == $displayed{'web'});
13964:                                 next if ($i == $displayed{'folder'});
13965:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13966:                             }
13967:                             $env{'form.phase'} = 'decompress_cleanup';
13968:                             $env{'form.archivedelete'} = 1;
13969:                             $env{'form.archive_count'} = $total-1;
13970:                             $output .=
13971:                                 &process_extracted_files('coursedocs',$docudom,
13972:                                                          $docuname,$destination,
13973:                                                          $dir_root,$hiddenelem);
13974:                         }
13975:                     } else {
13976:                         $warning = &mt('No new items extracted from archive file.');
13977:                     }
13978:                 } else {
13979:                     $output = $display;
13980:                     $error = &mt('An error occurred during extraction from the archive file.');
13981:                 }
13982:             }
13983:         }
13984:     }
13985:     if ($error) {
13986:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13987:                    $error.'</p>'."\n";
13988:     }
13989:     if ($warning) {
13990:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13991:     }
13992:     return $output;
13993: }
13994: 
13995: sub get_extracted {
13996:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13997:         $titles,$wantform) = @_;
13998:     my $count = 0;
13999:     my $depth = 0;
14000:     my $datatable;
14001:     my @hierarchy;
14002:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
14003:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
14004:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
14005:     foreach my $item (@{$contents}) {
14006:         $count ++;
14007:         @{$dirorder->{$count}} = @hierarchy;
14008:         $titles->{$count} = $item;
14009:         &archive_hierarchy($depth,$count,$parent,$children);
14010:         if ($wantform) {
14011:             $datatable .= &archive_row($is_dir->{$item},$item,
14012:                                        $currdir,$depth,$count);
14013:         }
14014:         if ($is_dir->{$item}) {
14015:             $depth ++;
14016:             push(@hierarchy,$count);
14017:             $parent->{$depth} = $count;
14018:             $datatable .=
14019:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
14020:                                            \$depth,\$count,\@hierarchy,$dirorder,
14021:                                            $children,$parent,$titles,$wantform);
14022:             $depth --;
14023:             pop(@hierarchy);
14024:         }
14025:     }
14026:     return ($count,$datatable);
14027: }
14028: 
14029: sub recurse_extracted_archive {
14030:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
14031:         $children,$parent,$titles,$wantform) = @_;
14032:     my $result='';
14033:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
14034:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
14035:             (ref($dirorder) eq 'HASH')) {
14036:         return $result;
14037:     }
14038:     my $dirptr = 16384;
14039:     my ($newdirlistref,$newlisterror) =
14040:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
14041:     if (ref($newdirlistref) eq 'ARRAY') {
14042:         foreach my $dir_line (@{$newdirlistref}) {
14043:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14044:             unless ($item =~ /^\.+$/) {
14045:                 $$count ++;
14046:                 @{$dirorder->{$$count}} = @{$hierarchy};
14047:                 $titles->{$$count} = $item;
14048:                 &archive_hierarchy($$depth,$$count,$parent,$children);
14049: 
14050:                 my $is_dir;
14051:                 if ($dirptr&$testdir) {
14052:                     $is_dir = 1;
14053:                 }
14054:                 if ($wantform) {
14055:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
14056:                 }
14057:                 if ($is_dir) {
14058:                     $$depth ++;
14059:                     push(@{$hierarchy},$$count);
14060:                     $parent->{$$depth} = $$count;
14061:                     $result .=
14062:                         &recurse_extracted_archive("$currdir/$item",$docudom,
14063:                                                    $docuname,$depth,$count,
14064:                                                    $hierarchy,$dirorder,$children,
14065:                                                    $parent,$titles,$wantform);
14066:                     $$depth --;
14067:                     pop(@{$hierarchy});
14068:                 }
14069:             }
14070:         }
14071:     }
14072:     return $result;
14073: }
14074: 
14075: sub archive_hierarchy {
14076:     my ($depth,$count,$parent,$children) =@_;
14077:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
14078:         if (exists($parent->{$depth})) {
14079:              $children->{$parent->{$depth}} .= $count.':';
14080:         }
14081:     }
14082:     return;
14083: }
14084: 
14085: sub archive_row {
14086:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
14087:     my ($name) = ($item =~ m{([^/]+)$});
14088:     my %choices = &Apache::lonlocal::texthash (
14089:                                        'display'    => 'Add as file',
14090:                                        'dependency' => 'Include as dependency',
14091:                                        'discard'    => 'Discard',
14092:                                       );
14093:     if ($is_dir) {
14094:         $choices{'display'} = &mt('Add as folder'); 
14095:     }
14096:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
14097:     my $offset = 0;
14098:     foreach my $action ('display','dependency','discard') {
14099:         $offset ++;
14100:         if ($action ne 'display') {
14101:             $offset ++;
14102:         }  
14103:         $output .= '<td><span class="LC_nobreak">'.
14104:                    '<label><input type="radio" name="archive_'.$count.
14105:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
14106:         my $text = $choices{$action};
14107:         if ($is_dir) {
14108:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
14109:             if ($action eq 'display') {
14110:                 $text = &mt('Add as folder');
14111:             }
14112:         } else {
14113:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
14114: 
14115:         }
14116:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
14117:         if ($action eq 'dependency') {
14118:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
14119:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
14120:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
14121:                        '<option value=""></option>'."\n".
14122:                        '</select>'."\n".
14123:                        '</div>';
14124:         } elsif ($action eq 'display') {
14125:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
14126:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
14127:                        '</div>';
14128:         }
14129:         $output .= '</td>';
14130:     }
14131:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
14132:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
14133:     for (my $i=0; $i<$depth; $i++) {
14134:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
14135:     }
14136:     if ($is_dir) {
14137:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
14138:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
14139:     } else {
14140:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
14141:     }
14142:     $output .= '&nbsp;'.$name.'</td>'."\n".
14143:                &end_data_table_row();
14144:     return $output;
14145: }
14146: 
14147: sub archive_options_form {
14148:     my ($form,$display,$count,$hiddenelem) = @_;
14149:     my %lt = &Apache::lonlocal::texthash(
14150:                perm => 'Permanently remove archive file?',
14151:                hows => 'How should each extracted item be incorporated in the course?',
14152:                cont => 'Content actions for all',
14153:                addf => 'Add as folder/file',
14154:                incd => 'Include as dependency for a displayed file',
14155:                disc => 'Discard',
14156:                no   => 'No',
14157:                yes  => 'Yes',
14158:                save => 'Save',
14159:     );
14160:     my $output = <<"END";
14161: <form name="$form" method="post" action="">
14162: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
14163: <label>
14164:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
14165: </label>
14166: &nbsp;
14167: <label>
14168:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
14169: </span>
14170: </p>
14171: <input type="hidden" name="phase" value="decompress_cleanup" />
14172: <br />$lt{'hows'}
14173: <div class="LC_columnSection">
14174:   <fieldset>
14175:     <legend>$lt{'cont'}</legend>
14176:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
14177:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
14178:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
14179:   </fieldset>
14180: </div>
14181: END
14182:     return $output.
14183:            &start_data_table()."\n".
14184:            $display."\n".
14185:            &end_data_table()."\n".
14186:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
14187:            $hiddenelem.
14188:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
14189:            '</form>';
14190: }
14191: 
14192: sub archive_javascript {
14193:     my ($startcount,$numitems,$titles,$children) = @_;
14194:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
14195:     my $maintitle = $env{'form.comment'};
14196:     my $scripttag = <<START;
14197: <script type="text/javascript">
14198: // <![CDATA[
14199: 
14200: function checkAll(form,prefix) {
14201:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
14202:     for (var i=0; i < form.elements.length; i++) {
14203:         var id = form.elements[i].id;
14204:         if ((id != '') && (id != undefined)) {
14205:             if (idstr.test(id)) {
14206:                 if (form.elements[i].type == 'radio') {
14207:                     form.elements[i].checked = true;
14208:                     var nostart = i-$startcount;
14209:                     var offset = nostart%7;
14210:                     var count = (nostart-offset)/7;    
14211:                     dependencyCheck(form,count,offset);
14212:                 }
14213:             }
14214:         }
14215:     }
14216: }
14217: 
14218: function propagateCheck(form,count) {
14219:     if (count > 0) {
14220:         var startelement = $startcount + ((count-1) * 7);
14221:         for (var j=1; j<6; j++) {
14222:             if ((j != 2) && (j != 4)) {
14223:                 var item = startelement + j; 
14224:                 if (form.elements[item].type == 'radio') {
14225:                     if (form.elements[item].checked) {
14226:                         containerCheck(form,count,j);
14227:                         break;
14228:                     }
14229:                 }
14230:             }
14231:         }
14232:     }
14233: }
14234: 
14235: numitems = $numitems
14236: var titles = new Array(numitems);
14237: var parents = new Array(numitems);
14238: for (var i=0; i<numitems; i++) {
14239:     parents[i] = new Array;
14240: }
14241: var maintitle = '$maintitle';
14242: 
14243: START
14244: 
14245:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
14246:         my @contents = split(/:/,$children->{$container});
14247:         for (my $i=0; $i<@contents; $i ++) {
14248:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
14249:         }
14250:     }
14251: 
14252:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
14253:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
14254:     }
14255: 
14256:     $scripttag .= <<END;
14257: 
14258: function containerCheck(form,count,offset) {
14259:     if (count > 0) {
14260:         dependencyCheck(form,count,offset);
14261:         var item = (offset+$startcount)+7*(count-1);
14262:         form.elements[item].checked = true;
14263:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
14264:             if (parents[count].length > 0) {
14265:                 for (var j=0; j<parents[count].length; j++) {
14266:                     containerCheck(form,parents[count][j],offset);
14267:                 }
14268:             }
14269:         }
14270:     }
14271: }
14272: 
14273: function dependencyCheck(form,count,offset) {
14274:     if (count > 0) {
14275:         var chosen = (offset+$startcount)+7*(count-1);
14276:         var depitem = $startcount + ((count-1) * 7) + 4;
14277:         var currtype = form.elements[depitem].type;
14278:         if (form.elements[chosen].value == 'dependency') {
14279:             document.getElementById('arc_depon_'+count).style.display='block'; 
14280:             form.elements[depitem].options.length = 0;
14281:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14282:             for (var i=1; i<=numitems; i++) {
14283:                 if (i == count) {
14284:                     continue;
14285:                 }
14286:                 var startelement = $startcount + (i-1) * 7;
14287:                 for (var j=1; j<6; j++) {
14288:                     if ((j != 2) && (j!= 4)) {
14289:                         var item = startelement + j;
14290:                         if (form.elements[item].type == 'radio') {
14291:                             if (form.elements[item].checked) {
14292:                                 if (form.elements[item].value == 'display') {
14293:                                     var n = form.elements[depitem].options.length;
14294:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
14295:                                 }
14296:                             }
14297:                         }
14298:                     }
14299:                 }
14300:             }
14301:         } else {
14302:             document.getElementById('arc_depon_'+count).style.display='none';
14303:             form.elements[depitem].options.length = 0;
14304:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14305:         }
14306:         titleCheck(form,count,offset);
14307:     }
14308: }
14309: 
14310: function propagateSelect(form,count,offset) {
14311:     if (count > 0) {
14312:         var item = (1+offset+$startcount)+7*(count-1);
14313:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
14314:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14315:             if (parents[count].length > 0) {
14316:                 for (var j=0; j<parents[count].length; j++) {
14317:                     containerSelect(form,parents[count][j],offset,picked);
14318:                 }
14319:             }
14320:         }
14321:     }
14322: }
14323: 
14324: function containerSelect(form,count,offset,picked) {
14325:     if (count > 0) {
14326:         var item = (offset+$startcount)+7*(count-1);
14327:         if (form.elements[item].type == 'radio') {
14328:             if (form.elements[item].value == 'dependency') {
14329:                 if (form.elements[item+1].type == 'select-one') {
14330:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
14331:                         if (form.elements[item+1].options[i].value == picked) {
14332:                             form.elements[item+1].selectedIndex = i;
14333:                             break;
14334:                         }
14335:                     }
14336:                 }
14337:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14338:                     if (parents[count].length > 0) {
14339:                         for (var j=0; j<parents[count].length; j++) {
14340:                             containerSelect(form,parents[count][j],offset,picked);
14341:                         }
14342:                     }
14343:                 }
14344:             }
14345:         }
14346:     }
14347: }
14348: 
14349: function titleCheck(form,count,offset) {
14350:     if (count > 0) {
14351:         var chosen = (offset+$startcount)+7*(count-1);
14352:         var depitem = $startcount + ((count-1) * 7) + 2;
14353:         var currtype = form.elements[depitem].type;
14354:         if (form.elements[chosen].value == 'display') {
14355:             document.getElementById('arc_title_'+count).style.display='block';
14356:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14357:                 document.getElementById('archive_title_'+count).value=maintitle;
14358:             }
14359:         } else {
14360:             document.getElementById('arc_title_'+count).style.display='none';
14361:             if (currtype == 'text') { 
14362:                 document.getElementById('archive_title_'+count).value='';
14363:             }
14364:         }
14365:     }
14366:     return;
14367: }
14368: 
14369: // ]]>
14370: </script>
14371: END
14372:     return $scripttag;
14373: }
14374: 
14375: sub process_extracted_files {
14376:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14377:     my $numitems = $env{'form.archive_count'};
14378:     return if ((!$numitems) || ($numitems =~ /\D/));
14379:     my @ids=&Apache::lonnet::current_machine_ids();
14380:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14381:         %folders,%containers,%mapinner,%prompttofetch);
14382:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14383:     if (grep(/^\Q$docuhome\E$/,@ids)) {
14384:         $prefix = &LONCAPA::propath($docudom,$docuname);
14385:         $pathtocheck = "$dir_root/$destination";
14386:         $dir = $dir_root;
14387:         $ishome = 1;
14388:     } else {
14389:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14390:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14391:         $dir = "$dir_root/$docudom/$docuname";
14392:     }
14393:     my $currdir = "$dir_root/$destination";
14394:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14395:     if ($env{'form.folderpath'}) {
14396:         my @items = split('&',$env{'form.folderpath'});
14397:         $folders{'0'} = $items[-2];
14398:         if ($env{'form.folderpath'} =~ /\:1$/) {
14399:             $containers{'0'}='page';
14400:         } else {  
14401:             $containers{'0'}='sequence';
14402:         }
14403:     }
14404:     my @archdirs = &get_env_multiple('form.archive_directory');
14405:     if ($numitems) {
14406:         for (my $i=1; $i<=$numitems; $i++) {
14407:             my $path = $env{'form.archive_content_'.$i};
14408:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14409:                 my $item = $1;
14410:                 $toplevelitems{$item} = $i;
14411:                 if (grep(/^\Q$i\E$/,@archdirs)) {
14412:                     $is_dir{$item} = 1;
14413:                 }
14414:             }
14415:         }
14416:     }
14417:     my ($output,%children,%parent,%titles,%dirorder,$result);
14418:     if (keys(%toplevelitems) > 0) {
14419:         my @contents = sort(keys(%toplevelitems));
14420:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14421:                                            \%parent,\@contents,\%dirorder,\%titles);
14422:     }
14423:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14424:     if ($numitems) {
14425:         for (my $i=1; $i<=$numitems; $i++) {
14426:             next if ($env{'form.archive_'.$i} eq 'dependency');
14427:             my $path = $env{'form.archive_content_'.$i};
14428:             if ($path =~ /^\Q$pathtocheck\E/) {
14429:                 if ($env{'form.archive_'.$i} eq 'discard') {
14430:                     if ($prefix ne '' && $path ne '') {
14431:                         if (-e $prefix.$path) {
14432:                             if ((@archdirs > 0) && 
14433:                                 (grep(/^\Q$i\E$/,@archdirs))) {
14434:                                 $todeletedir{$prefix.$path} = 1;
14435:                             } else {
14436:                                 $todelete{$prefix.$path} = 1;
14437:                             }
14438:                         }
14439:                     }
14440:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
14441:                     my ($docstitle,$title,$url,$outer);
14442:                     ($title) = ($path =~ m{/([^/]+)$});
14443:                     $docstitle = $env{'form.archive_title_'.$i};
14444:                     if ($docstitle eq '') {
14445:                         $docstitle = $title;
14446:                     }
14447:                     $outer = 0;
14448:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14449:                         if (@{$dirorder{$i}} > 0) {
14450:                             foreach my $item (reverse(@{$dirorder{$i}})) {
14451:                                 if ($env{'form.archive_'.$item} eq 'display') {
14452:                                     $outer = $item;
14453:                                     last;
14454:                                 }
14455:                             }
14456:                         }
14457:                     }
14458:                     my ($errtext,$fatal) = 
14459:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14460:                                                '/'.$folders{$outer}.'.'.
14461:                                                $containers{$outer});
14462:                     next if ($fatal);
14463:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14464:                         if ($context eq 'coursedocs') {
14465:                             $mapinner{$i} = time;
14466:                             $folders{$i} = 'default_'.$mapinner{$i};
14467:                             $containers{$i} = 'sequence';
14468:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14469:                                       $folders{$i}.'.'.$containers{$i};
14470:                             my $newidx = &LONCAPA::map::getresidx();
14471:                             $LONCAPA::map::resources[$newidx]=
14472:                                 $docstitle.':'.$url.':false:normal:res';
14473:                             push(@LONCAPA::map::order,$newidx);
14474:                             my ($outtext,$errtext) =
14475:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14476:                                                         $docuname.'/'.$folders{$outer}.
14477:                                                         '.'.$containers{$outer},1,1);
14478:                             $newseqid{$i} = $newidx;
14479:                             unless ($errtext) {
14480:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
14481:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
14482:                                             '</li>'."\n";
14483:                             }
14484:                         }
14485:                     } else {
14486:                         if ($context eq 'coursedocs') {
14487:                             my $newidx=&LONCAPA::map::getresidx();
14488:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14489:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14490:                                       $title;
14491:                             if (($outer !~ /\D/) &&
14492:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
14493:                                 ($newidx !~ /\D/)) {
14494:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14495:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14496:                                 }
14497:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14498:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14499:                                 }
14500:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14501:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14502:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14503:                                         unless ($ishome) {
14504:                                             my $fetch = "$newdest{$i}/$title";
14505:                                             $fetch =~ s/^\Q$prefix$dir\E//;
14506:                                             $prompttofetch{$fetch} = 1;
14507:                                         }
14508:                                     }
14509:                                 }
14510:                                 $LONCAPA::map::resources[$newidx]=
14511:                                     $docstitle.':'.$url.':false:normal:res';
14512:                                 push(@LONCAPA::map::order, $newidx);
14513:                                 my ($outtext,$errtext)=
14514:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14515:                                                             $docuname.'/'.$folders{$outer}.
14516:                                                             '.'.$containers{$outer},1,1);
14517:                                 unless ($errtext) {
14518:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14519:                                         $result .= '<li>'.&mt('File: [_1] added to course',
14520:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
14521:                                                    '</li>'."\n";
14522:                                     }
14523:                                 }
14524:                             } else {
14525:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14526:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
14527:                             }
14528:                         }
14529:                     }
14530:                 }
14531:             } else {
14532:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14533:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
14534:             }
14535:         }
14536:         for (my $i=1; $i<=$numitems; $i++) {
14537:             next unless ($env{'form.archive_'.$i} eq 'dependency');
14538:             my $path = $env{'form.archive_content_'.$i};
14539:             if ($path =~ /^\Q$pathtocheck\E/) {
14540:                 my ($title) = ($path =~ m{/([^/]+)$});
14541:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14542:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14543:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14544:                         my ($itemidx,$fullpath,$relpath);
14545:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14546:                             my $container = $dirorder{$referrer{$i}}->[-1];
14547:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14548:                                 if ($dirorder{$i}->[$j] eq $container) {
14549:                                     $itemidx = $j;
14550:                                 }
14551:                             }
14552:                         }
14553:                         if ($itemidx eq '') {
14554:                             $itemidx =  0;
14555:                         } 
14556:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14557:                             if ($mapinner{$referrer{$i}}) {
14558:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14559:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14560:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14561:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14562:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14563:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14564:                                             if (!-e $fullpath) {
14565:                                                 mkdir($fullpath,0755);
14566:                                             }
14567:                                         }
14568:                                     } else {
14569:                                         last;
14570:                                     }
14571:                                 }
14572:                             }
14573:                         } elsif ($newdest{$referrer{$i}}) {
14574:                             $fullpath = $newdest{$referrer{$i}};
14575:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14576:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14577:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14578:                                     last;
14579:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14580:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14581:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14582:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14583:                                         if (!-e $fullpath) {
14584:                                             mkdir($fullpath,0755);
14585:                                         }
14586:                                     }
14587:                                 } else {
14588:                                     last;
14589:                                 }
14590:                             }
14591:                         }
14592:                         if ($fullpath ne '') {
14593:                             if (-e "$prefix$path") {
14594:                                 unless (rename("$prefix$path","$fullpath/$title")) {
14595:                                      $warning .= &mt('Failed to rename dependency').'<br />';
14596:                                 }
14597:                             }
14598:                             if (-e "$fullpath/$title") {
14599:                                 my $showpath;
14600:                                 if ($relpath ne '') {
14601:                                     $showpath = "$relpath/$title";
14602:                                 } else {
14603:                                     $showpath = "/$title";
14604:                                 } 
14605:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
14606:                                                       &HTML::Entities::encode($showpath,'<>&"')).
14607:                                            '</li>'."\n";
14608:                                 unless ($ishome) {
14609:                                     my $fetch = "$fullpath/$title";
14610:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
14611:                                     $prompttofetch{$fetch} = 1;
14612:                                 }
14613:                             }
14614:                         }
14615:                     }
14616:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14617:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14618:                                     &HTML::Entities::encode($path,'<>&"'),
14619:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14620:                                 '<br />';
14621:                 }
14622:             } else {
14623:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14624:                                 &HTML::Entities::encode($path)).'<br />';
14625:             }
14626:         }
14627:         if (keys(%todelete)) {
14628:             foreach my $key (keys(%todelete)) {
14629:                 unlink($key);
14630:             }
14631:         }
14632:         if (keys(%todeletedir)) {
14633:             foreach my $key (keys(%todeletedir)) {
14634:                 rmdir($key);
14635:             }
14636:         }
14637:         foreach my $dir (sort(keys(%is_dir))) {
14638:             if (($pathtocheck ne '') && ($dir ne ''))  {
14639:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14640:             }
14641:         }
14642:         if ($result ne '') {
14643:             $output .= '<ul>'."\n".
14644:                        $result."\n".
14645:                        '</ul>';
14646:         }
14647:         unless ($ishome) {
14648:             my $replicationfail;
14649:             foreach my $item (keys(%prompttofetch)) {
14650:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14651:                 unless ($fetchresult eq 'ok') {
14652:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
14653:                 }
14654:             }
14655:             if ($replicationfail) {
14656:                 $output .= '<p class="LC_error">'.
14657:                            &mt('Course home server failed to retrieve:').'<ul>'.
14658:                            $replicationfail.
14659:                            '</ul></p>';
14660:             }
14661:         }
14662:     } else {
14663:         $warning = &mt('No items found in archive.');
14664:     }
14665:     if ($error) {
14666:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14667:                    $error.'</p>'."\n";
14668:     }
14669:     if ($warning) {
14670:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14671:     }
14672:     return $output;
14673: }
14674: 
14675: sub cleanup_empty_dirs {
14676:     my ($path) = @_;
14677:     if (($path ne '') && (-d $path)) {
14678:         if (opendir(my $dirh,$path)) {
14679:             my @dircontents = grep(!/^\./,readdir($dirh));
14680:             my $numitems = 0;
14681:             foreach my $item (@dircontents) {
14682:                 if (-d "$path/$item") {
14683:                     &cleanup_empty_dirs("$path/$item");
14684:                     if (-e "$path/$item") {
14685:                         $numitems ++;
14686:                     }
14687:                 } else {
14688:                     $numitems ++;
14689:                 }
14690:             }
14691:             if ($numitems == 0) {
14692:                 rmdir($path);
14693:             }
14694:             closedir($dirh);
14695:         }
14696:     }
14697:     return;
14698: }
14699: 
14700: =pod
14701: 
14702: =item * &get_folder_hierarchy()
14703: 
14704: Provides hierarchy of names of folders/sub-folders containing the current
14705: item,
14706: 
14707: Inputs: 3
14708:      - $navmap - navmaps object
14709: 
14710:      - $map - url for map (either the trigger itself, or map containing
14711:                            the resource, which is the trigger).
14712: 
14713:      - $showitem - 1 => show title for map itself; 0 => do not show.
14714: 
14715: Outputs: 1 @pathitems - array of folder/subfolder names.
14716: 
14717: =cut
14718: 
14719: sub get_folder_hierarchy {
14720:     my ($navmap,$map,$showitem) = @_;
14721:     my @pathitems;
14722:     if (ref($navmap)) {
14723:         my $mapres = $navmap->getResourceByUrl($map);
14724:         if (ref($mapres)) {
14725:             my $pcslist = $mapres->map_hierarchy();
14726:             if ($pcslist ne '') {
14727:                 my @pcs = split(/,/,$pcslist);
14728:                 foreach my $pc (@pcs) {
14729:                     if ($pc == 1) {
14730:                         push(@pathitems,&mt('Main Content'));
14731:                     } else {
14732:                         my $res = $navmap->getByMapPc($pc);
14733:                         if (ref($res)) {
14734:                             my $title = $res->compTitle();
14735:                             $title =~ s/\W+/_/g;
14736:                             if ($title ne '') {
14737:                                 push(@pathitems,$title);
14738:                             }
14739:                         }
14740:                     }
14741:                 }
14742:             }
14743:             if ($showitem) {
14744:                 if ($mapres->{ID} eq '0.0') {
14745:                     push(@pathitems,&mt('Main Content'));
14746:                 } else {
14747:                     my $maptitle = $mapres->compTitle();
14748:                     $maptitle =~ s/\W+/_/g;
14749:                     if ($maptitle ne '') {
14750:                         push(@pathitems,$maptitle);
14751:                     }
14752:                 }
14753:             }
14754:         }
14755:     }
14756:     return @pathitems;
14757: }
14758: 
14759: =pod
14760: 
14761: =item * &get_turnedin_filepath()
14762: 
14763: Determines path in a user's portfolio file for storage of files uploaded
14764: to a specific essayresponse or dropbox item.
14765: 
14766: Inputs: 3 required + 1 optional.
14767: $symb is symb for resource, $uname and $udom are for current user (required).
14768: $caller is optional (can be "submission", if routine is called when storing
14769: an upoaded file when "Submit Answer" button was pressed).
14770: 
14771: Returns array containing $path and $multiresp. 
14772: $path is path in portfolio.  $multiresp is 1 if this resource contains more
14773: than one file upload item.  Callers of routine should append partid as a 
14774: subdirectory to $path in cases where $multiresp is 1.
14775: 
14776: Called by: homework/essayresponse.pm and homework/structuretags.pm
14777: 
14778: =cut
14779: 
14780: sub get_turnedin_filepath {
14781:     my ($symb,$uname,$udom,$caller) = @_;
14782:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14783:     my $turnindir;
14784:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14785:     $turnindir = $userhash{'turnindir'};
14786:     my ($path,$multiresp);
14787:     if ($turnindir eq '') {
14788:         if ($caller eq 'submission') {
14789:             $turnindir = &mt('turned in');
14790:             $turnindir =~ s/\W+/_/g;
14791:             my %newhash = (
14792:                             'turnindir' => $turnindir,
14793:                           );
14794:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14795:         }
14796:     }
14797:     if ($turnindir ne '') {
14798:         $path = '/'.$turnindir.'/';
14799:         my ($multipart,$turnin,@pathitems);
14800:         my $navmap = Apache::lonnavmaps::navmap->new();
14801:         if (defined($navmap)) {
14802:             my $mapres = $navmap->getResourceByUrl($map);
14803:             if (ref($mapres)) {
14804:                 my $pcslist = $mapres->map_hierarchy();
14805:                 if ($pcslist ne '') {
14806:                     foreach my $pc (split(/,/,$pcslist)) {
14807:                         my $res = $navmap->getByMapPc($pc);
14808:                         if (ref($res)) {
14809:                             my $title = $res->compTitle();
14810:                             $title =~ s/\W+/_/g;
14811:                             if ($title ne '') {
14812:                                 if (($pc > 1) && (length($title) > 12)) {
14813:                                     $title = substr($title,0,12);
14814:                                 }
14815:                                 push(@pathitems,$title);
14816:                             }
14817:                         }
14818:                     }
14819:                 }
14820:                 my $maptitle = $mapres->compTitle();
14821:                 $maptitle =~ s/\W+/_/g;
14822:                 if ($maptitle ne '') {
14823:                     if (length($maptitle) > 12) {
14824:                         $maptitle = substr($maptitle,0,12);
14825:                     }
14826:                     push(@pathitems,$maptitle);
14827:                 }
14828:                 unless ($env{'request.state'} eq 'construct') {
14829:                     my $res = $navmap->getBySymb($symb);
14830:                     if (ref($res)) {
14831:                         my $partlist = $res->parts();
14832:                         my $totaluploads = 0;
14833:                         if (ref($partlist) eq 'ARRAY') {
14834:                             foreach my $part (@{$partlist}) {
14835:                                 my @types = $res->responseType($part);
14836:                                 my @ids = $res->responseIds($part);
14837:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14838:                                     if ($types[$i] eq 'essay') {
14839:                                         my $partid = $part.'_'.$ids[$i];
14840:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14841:                                             $totaluploads ++;
14842:                                         }
14843:                                     }
14844:                                 }
14845:                             }
14846:                             if ($totaluploads > 1) {
14847:                                 $multiresp = 1;
14848:                             }
14849:                         }
14850:                     }
14851:                 }
14852:             } else {
14853:                 return;
14854:             }
14855:         } else {
14856:             return;
14857:         }
14858:         my $restitle=&Apache::lonnet::gettitle($symb);
14859:         $restitle =~ s/\W+/_/g;
14860:         if ($restitle eq '') {
14861:             $restitle = ($resurl =~ m{/[^/]+$});
14862:             if ($restitle eq '') {
14863:                 $restitle = time;
14864:             }
14865:         }
14866:         if (length($restitle) > 12) {
14867:             $restitle = substr($restitle,0,12);
14868:         }
14869:         push(@pathitems,$restitle);
14870:         $path .= join('/',@pathitems);
14871:     }
14872:     return ($path,$multiresp);
14873: }
14874: 
14875: =pod
14876: 
14877: =back
14878: 
14879: =head1 CSV Upload/Handling functions
14880: 
14881: =over 4
14882: 
14883: =item * &upfile_store($r)
14884: 
14885: Store uploaded file, $r should be the HTTP Request object,
14886: needs $env{'form.upfile'}
14887: returns $datatoken to be put into hidden field
14888: 
14889: =cut
14890: 
14891: sub upfile_store {
14892:     my $r=shift;
14893:     $env{'form.upfile'}=~s/\r/\n/gs;
14894:     $env{'form.upfile'}=~s/\f/\n/gs;
14895:     $env{'form.upfile'}=~s/\n+/\n/gs;
14896:     $env{'form.upfile'}=~s/\n+$//gs;
14897: 
14898:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14899:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14900:                                      time.'_'.$$);
14901:     return if ($datatoken eq '');
14902: 
14903:     {
14904:         my $datafile = $r->dir_config('lonDaemons').
14905:                            '/tmp/'.$datatoken.'.tmp';
14906:         if ( open(my $fh,'>',$datafile) ) {
14907:             print $fh $env{'form.upfile'};
14908:             close($fh);
14909:         }
14910:     }
14911:     return $datatoken;
14912: }
14913: 
14914: =pod
14915: 
14916: =item * &load_tmp_file($r,$datatoken)
14917: 
14918: Load uploaded file from tmp, $r should be the HTTP Request object,
14919: $datatoken is the name to assign to the temporary file.
14920: sets $env{'form.upfile'} to the contents of the file
14921: 
14922: =cut
14923: 
14924: sub load_tmp_file {
14925:     my ($r,$datatoken) = @_;
14926:     return if ($datatoken eq '');
14927:     my @studentdata=();
14928:     {
14929:         my $studentfile = $r->dir_config('lonDaemons').
14930:                               '/tmp/'.$datatoken.'.tmp';
14931:         if ( open(my $fh,'<',$studentfile) ) {
14932:             @studentdata=<$fh>;
14933:             close($fh);
14934:         }
14935:     }
14936:     $env{'form.upfile'}=join('',@studentdata);
14937: }
14938: 
14939: sub valid_datatoken {
14940:     my ($datatoken) = @_;
14941:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14942:         return $datatoken;
14943:     }
14944:     return;
14945: }
14946: 
14947: =pod
14948: 
14949: =item * &upfile_record_sep()
14950: 
14951: Separate uploaded file into records
14952: returns array of records,
14953: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14954: 
14955: =cut
14956: 
14957: sub upfile_record_sep {
14958:     if ($env{'form.upfiletype'} eq 'xml') {
14959:     } else {
14960: 	my @records;
14961: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14962: 	    if ($line=~/^\s*$/) { next; }
14963: 	    push(@records,$line);
14964: 	}
14965: 	return @records;
14966:     }
14967: }
14968: 
14969: =pod
14970: 
14971: =item * &record_sep($record)
14972: 
14973: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14974: 
14975: =cut
14976: 
14977: sub takeleft {
14978:     my $index=shift;
14979:     return substr('0000'.$index,-4,4);
14980: }
14981: 
14982: sub record_sep {
14983:     my $record=shift;
14984:     my %components=();
14985:     if ($env{'form.upfiletype'} eq 'xml') {
14986:     } elsif ($env{'form.upfiletype'} eq 'space') {
14987:         my $i=0;
14988:         foreach my $field (split(/\s+/,$record)) {
14989:             $field=~s/^(\"|\')//;
14990:             $field=~s/(\"|\')$//;
14991:             $components{&takeleft($i)}=$field;
14992:             $i++;
14993:         }
14994:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14995:         my $i=0;
14996:         foreach my $field (split(/\t/,$record)) {
14997:             $field=~s/^(\"|\')//;
14998:             $field=~s/(\"|\')$//;
14999:             $components{&takeleft($i)}=$field;
15000:             $i++;
15001:         }
15002:     } else {
15003:         my $separator=',';
15004:         if ($env{'form.upfiletype'} eq 'semisv') {
15005:             $separator=';';
15006:         }
15007:         my $i=0;
15008: # the character we are looking for to indicate the end of a quote or a record 
15009:         my $looking_for=$separator;
15010: # do not add the characters to the fields
15011:         my $ignore=0;
15012: # we just encountered a separator (or the beginning of the record)
15013:         my $just_found_separator=1;
15014: # store the field we are working on here
15015:         my $field='';
15016: # work our way through all characters in record
15017:         foreach my $character ($record=~/(.)/g) {
15018:             if ($character eq $looking_for) {
15019:                if ($character ne $separator) {
15020: # Found the end of a quote, again looking for separator
15021:                   $looking_for=$separator;
15022:                   $ignore=1;
15023:                } else {
15024: # Found a separator, store away what we got
15025:                   $components{&takeleft($i)}=$field;
15026: 	          $i++;
15027:                   $just_found_separator=1;
15028:                   $ignore=0;
15029:                   $field='';
15030:                }
15031:                next;
15032:             }
15033: # single or double quotation marks after a separator indicate beginning of a quote
15034: # we are now looking for the end of the quote and need to ignore separators
15035:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
15036:                $looking_for=$character;
15037:                next;
15038:             }
15039: # ignore would be true after we reached the end of a quote
15040:             if ($ignore) { next; }
15041:             if (($just_found_separator) && ($character=~/\s/)) { next; }
15042:             $field.=$character;
15043:             $just_found_separator=0; 
15044:         }
15045: # catch the very last entry, since we never encountered the separator
15046:         $components{&takeleft($i)}=$field;
15047:     }
15048:     return %components;
15049: }
15050: 
15051: ######################################################
15052: ######################################################
15053: 
15054: =pod
15055: 
15056: =item * &upfile_select_html()
15057: 
15058: Return HTML code to select a file from the users machine and specify 
15059: the file type.
15060: 
15061: =cut
15062: 
15063: ######################################################
15064: ######################################################
15065: sub upfile_select_html {
15066:     my %Types = (
15067:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
15068:                  semisv => &mt('Semicolon separated values'),
15069:                  space => &mt('Space separated'),
15070:                  tab   => &mt('Tabulator separated'),
15071: #                 xml   => &mt('HTML/XML'),
15072:                  );
15073:     my $Str = '<input type="file" name="upfile" size="50" />'.
15074:         '<br />'.&mt('Type').': <select name="upfiletype">';
15075:     foreach my $type (sort(keys(%Types))) {
15076:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
15077:     }
15078:     $Str .= "</select>\n";
15079:     return $Str;
15080: }
15081: 
15082: sub get_samples {
15083:     my ($records,$toget) = @_;
15084:     my @samples=({});
15085:     my $got=0;
15086:     foreach my $rec (@$records) {
15087: 	my %temp = &record_sep($rec);
15088: 	if (! grep(/\S/, values(%temp))) { next; }
15089: 	if (%temp) {
15090: 	    $samples[$got]=\%temp;
15091: 	    $got++;
15092: 	    if ($got == $toget) { last; }
15093: 	}
15094:     }
15095:     return \@samples;
15096: }
15097: 
15098: ######################################################
15099: ######################################################
15100: 
15101: =pod
15102: 
15103: =item * &csv_print_samples($r,$records)
15104: 
15105: Prints a table of sample values from each column uploaded $r is an
15106: Apache Request ref, $records is an arrayref from
15107: &Apache::loncommon::upfile_record_sep
15108: 
15109: =cut
15110: 
15111: ######################################################
15112: ######################################################
15113: sub csv_print_samples {
15114:     my ($r,$records) = @_;
15115:     my $samples = &get_samples($records,5);
15116: 
15117:     $r->print(&mt('Samples').'<br />'.&start_data_table().
15118:               &start_data_table_header_row());
15119:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
15120:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
15121:     $r->print(&end_data_table_header_row());
15122:     foreach my $hash (@$samples) {
15123: 	$r->print(&start_data_table_row());
15124: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15125: 	    $r->print('<td>');
15126: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
15127: 	    $r->print('</td>');
15128: 	}
15129: 	$r->print(&end_data_table_row());
15130:     }
15131:     $r->print(&end_data_table().'<br />'."\n");
15132: }
15133: 
15134: ######################################################
15135: ######################################################
15136: 
15137: =pod
15138: 
15139: =item * &csv_print_select_table($r,$records,$d)
15140: 
15141: Prints a table to create associations between values and table columns.
15142: 
15143: $r is an Apache Request ref,
15144: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15145: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
15146: 
15147: =cut
15148: 
15149: ######################################################
15150: ######################################################
15151: sub csv_print_select_table {
15152:     my ($r,$records,$d) = @_;
15153:     my $i=0;
15154:     my $samples = &get_samples($records,1);
15155:     $r->print(&mt('Associate columns with student attributes.')."\n".
15156: 	      &start_data_table().&start_data_table_header_row().
15157:               '<th>'.&mt('Attribute').'</th>'.
15158:               '<th>'.&mt('Column').'</th>'.
15159:               &end_data_table_header_row()."\n");
15160:     foreach my $array_ref (@$d) {
15161: 	my ($value,$display,$defaultcol)=@{ $array_ref };
15162: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
15163: 
15164: 	$r->print('<td><select name="f'.$i.'"'.
15165: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15166: 	$r->print('<option value="none"></option>');
15167: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15168: 	    $r->print('<option value="'.$sample.'"'.
15169:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
15170:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
15171: 	}
15172: 	$r->print('</select></td>'.&end_data_table_row()."\n");
15173: 	$i++;
15174:     }
15175:     $r->print(&end_data_table());
15176:     $i--;
15177:     return $i;
15178: }
15179: 
15180: ######################################################
15181: ######################################################
15182: 
15183: =pod
15184: 
15185: =item * &csv_samples_select_table($r,$records,$d)
15186: 
15187: Prints a table of sample values from the upload and can make associate samples to internal names.
15188: 
15189: $r is an Apache Request ref,
15190: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15191: $d is an array of 2 element arrays (internal name, displayed name)
15192: 
15193: =cut
15194: 
15195: ######################################################
15196: ######################################################
15197: sub csv_samples_select_table {
15198:     my ($r,$records,$d) = @_;
15199:     my $i=0;
15200:     #
15201:     my $max_samples = 5;
15202:     my $samples = &get_samples($records,$max_samples);
15203:     $r->print(&start_data_table().
15204:               &start_data_table_header_row().'<th>'.
15205:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
15206:               &end_data_table_header_row());
15207: 
15208:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
15209: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
15210: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15211: 	foreach my $option (@$d) {
15212: 	    my ($value,$display,$defaultcol)=@{ $option };
15213: 	    $r->print('<option value="'.$value.'"'.
15214:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
15215:                       $display.'</option>');
15216: 	}
15217: 	$r->print('</select></td><td>');
15218: 	foreach my $line (0..($max_samples-1)) {
15219: 	    if (defined($samples->[$line]{$key})) { 
15220: 		$r->print($samples->[$line]{$key}."<br />\n"); 
15221: 	    }
15222: 	}
15223: 	$r->print('</td>'.&end_data_table_row());
15224: 	$i++;
15225:     }
15226:     $r->print(&end_data_table());
15227:     $i--;
15228:     return($i);
15229: }
15230: 
15231: ######################################################
15232: ######################################################
15233: 
15234: =pod
15235: 
15236: =item * &clean_excel_name($name)
15237: 
15238: Returns a replacement for $name which does not contain any illegal characters.
15239: 
15240: =cut
15241: 
15242: ######################################################
15243: ######################################################
15244: sub clean_excel_name {
15245:     my ($name) = @_;
15246:     $name =~ s/[:\*\?\/\\]//g;
15247:     if (length($name) > 31) {
15248:         $name = substr($name,0,31);
15249:     }
15250:     return $name;
15251: }
15252: 
15253: =pod
15254: 
15255: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
15256: 
15257: Returns either 1 or undef
15258: 
15259: 1 if the part is to be hidden, undef if it is to be shown
15260: 
15261: Arguments are:
15262: 
15263: $id the id of the part to be checked
15264: $symb, optional the symb of the resource to check
15265: $udom, optional the domain of the user to check for
15266: $uname, optional the username of the user to check for
15267: 
15268: =cut
15269: 
15270: sub check_if_partid_hidden {
15271:     my ($id,$symb,$udom,$uname) = @_;
15272:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
15273: 					 $symb,$udom,$uname);
15274:     my $truth=1;
15275:     #if the string starts with !, then the list is the list to show not hide
15276:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
15277:     my @hiddenlist=split(/,/,$hiddenparts);
15278:     foreach my $checkid (@hiddenlist) {
15279: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
15280:     }
15281:     return !$truth;
15282: }
15283: 
15284: 
15285: ############################################################
15286: ############################################################
15287: 
15288: =pod
15289: 
15290: =back 
15291: 
15292: =head1 cgi-bin script and graphing routines
15293: 
15294: =over 4
15295: 
15296: =item * &get_cgi_id()
15297: 
15298: Inputs: none
15299: 
15300: Returns an id which can be used to pass environment variables
15301: to various cgi-bin scripts.  These environment variables will
15302: be removed from the users environment after a given time by
15303: the routine &Apache::lonnet::transfer_profile_to_env.
15304: 
15305: =cut
15306: 
15307: ############################################################
15308: ############################################################
15309: my $uniq=0;
15310: sub get_cgi_id {
15311:     $uniq=($uniq+1)%100000;
15312:     return (time.'_'.$$.'_'.$uniq);
15313: }
15314: 
15315: ############################################################
15316: ############################################################
15317: 
15318: =pod
15319: 
15320: =item * &DrawBarGraph()
15321: 
15322: Facilitates the plotting of data in a (stacked) bar graph.
15323: Puts plot definition data into the users environment in order for 
15324: graph.png to plot it.  Returns an <img> tag for the plot.
15325: The bars on the plot are labeled '1','2',...,'n'.
15326: 
15327: Inputs:
15328: 
15329: =over 4
15330: 
15331: =item $Title: string, the title of the plot
15332: 
15333: =item $xlabel: string, text describing the X-axis of the plot
15334: 
15335: =item $ylabel: string, text describing the Y-axis of the plot
15336: 
15337: =item $Max: scalar, the maximum Y value to use in the plot
15338: If $Max is < any data point, the graph will not be rendered.
15339: 
15340: =item $colors: array ref holding the colors to be used for the data sets when
15341: they are plotted.  If undefined, default values will be used.
15342: 
15343: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15344: 
15345: =item @Values: An array of array references.  Each array reference holds data
15346: to be plotted in a stacked bar chart.
15347: 
15348: =item If the final element of @Values is a hash reference the key/value
15349: pairs will be added to the graph definition.
15350: 
15351: =back
15352: 
15353: Returns:
15354: 
15355: An <img> tag which references graph.png and the appropriate identifying
15356: information for the plot.
15357: 
15358: =cut
15359: 
15360: ############################################################
15361: ############################################################
15362: sub DrawBarGraph {
15363:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15364:     #
15365:     if (! defined($colors)) {
15366:         $colors = ['#33ff00', 
15367:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15368:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15369:                   ]; 
15370:     }
15371:     my $extra_settings = {};
15372:     if (ref($Values[-1]) eq 'HASH') {
15373:         $extra_settings = pop(@Values);
15374:     }
15375:     #
15376:     my $identifier = &get_cgi_id();
15377:     my $id = 'cgi.'.$identifier;        
15378:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
15379:         return '';
15380:     }
15381:     #
15382:     my @Labels;
15383:     if (defined($labels)) {
15384:         @Labels = @$labels;
15385:     } else {
15386:         for (my $i=0;$i<@{$Values[0]};$i++) {
15387:             push(@Labels,$i+1);
15388:         }
15389:     }
15390:     #
15391:     my $NumBars = scalar(@{$Values[0]});
15392:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15393:     my %ValuesHash;
15394:     my $NumSets=1;
15395:     foreach my $array (@Values) {
15396:         next if (! ref($array));
15397:         $ValuesHash{$id.'.data.'.$NumSets++} = 
15398:             join(',',@$array);
15399:     }
15400:     #
15401:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15402:     if ($NumBars < 3) {
15403:         $width = 120+$NumBars*32;
15404:         $xskip = 1;
15405:         $bar_width = 30;
15406:     } elsif ($NumBars < 5) {
15407:         $width = 120+$NumBars*20;
15408:         $xskip = 1;
15409:         $bar_width = 20;
15410:     } elsif ($NumBars < 10) {
15411:         $width = 120+$NumBars*15;
15412:         $xskip = 1;
15413:         $bar_width = 15;
15414:     } elsif ($NumBars <= 25) {
15415:         $width = 120+$NumBars*11;
15416:         $xskip = 5;
15417:         $bar_width = 8;
15418:     } elsif ($NumBars <= 50) {
15419:         $width = 120+$NumBars*8;
15420:         $xskip = 5;
15421:         $bar_width = 4;
15422:     } else {
15423:         $width = 120+$NumBars*8;
15424:         $xskip = 5;
15425:         $bar_width = 4;
15426:     }
15427:     #
15428:     $Max = 1 if ($Max < 1);
15429:     if ( int($Max) < $Max ) {
15430:         $Max++;
15431:         $Max = int($Max);
15432:     }
15433:     $Title  = '' if (! defined($Title));
15434:     $xlabel = '' if (! defined($xlabel));
15435:     $ylabel = '' if (! defined($ylabel));
15436:     $ValuesHash{$id.'.title'}    = &escape($Title);
15437:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
15438:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
15439:     $ValuesHash{$id.'.y_max_value'} = $Max;
15440:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
15441:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
15442:     $ValuesHash{$id.'.PlotType'} = 'bar';
15443:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15444:     $ValuesHash{$id.'.height'}   = $height;
15445:     $ValuesHash{$id.'.width'}    = $width;
15446:     $ValuesHash{$id.'.xskip'}    = $xskip;
15447:     $ValuesHash{$id.'.bar_width'} = $bar_width;
15448:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
15449:     #
15450:     # Deal with other parameters
15451:     while (my ($key,$value) = each(%$extra_settings)) {
15452:         $ValuesHash{$id.'.'.$key} = $value;
15453:     }
15454:     #
15455:     &Apache::lonnet::appenv(\%ValuesHash);
15456:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15457: }
15458: 
15459: ############################################################
15460: ############################################################
15461: 
15462: =pod
15463: 
15464: =item * &DrawXYGraph()
15465: 
15466: Facilitates the plotting of data in an XY graph.
15467: Puts plot definition data into the users environment in order for 
15468: graph.png to plot it.  Returns an <img> tag for the plot.
15469: 
15470: Inputs:
15471: 
15472: =over 4
15473: 
15474: =item $Title: string, the title of the plot
15475: 
15476: =item $xlabel: string, text describing the X-axis of the plot
15477: 
15478: =item $ylabel: string, text describing the Y-axis of the plot
15479: 
15480: =item $Max: scalar, the maximum Y value to use in the plot
15481: If $Max is < any data point, the graph will not be rendered.
15482: 
15483: =item $colors: Array ref containing the hex color codes for the data to be 
15484: plotted in.  If undefined, default values will be used.
15485: 
15486: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15487: 
15488: =item $Ydata: Array ref containing Array refs.  
15489: Each of the contained arrays will be plotted as a separate curve.
15490: 
15491: =item %Values: hash indicating or overriding any default values which are 
15492: passed to graph.png.  
15493: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15494: 
15495: =back
15496: 
15497: Returns:
15498: 
15499: An <img> tag which references graph.png and the appropriate identifying
15500: information for the plot.
15501: 
15502: =cut
15503: 
15504: ############################################################
15505: ############################################################
15506: sub DrawXYGraph {
15507:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15508:     #
15509:     # Create the identifier for the graph
15510:     my $identifier = &get_cgi_id();
15511:     my $id = 'cgi.'.$identifier;
15512:     #
15513:     $Title  = '' if (! defined($Title));
15514:     $xlabel = '' if (! defined($xlabel));
15515:     $ylabel = '' if (! defined($ylabel));
15516:     my %ValuesHash = 
15517:         (
15518:          $id.'.title'  => &escape($Title),
15519:          $id.'.xlabel' => &escape($xlabel),
15520:          $id.'.ylabel' => &escape($ylabel),
15521:          $id.'.y_max_value'=> $Max,
15522:          $id.'.labels'     => join(',',@$Xlabels),
15523:          $id.'.PlotType'   => 'XY',
15524:          );
15525:     #
15526:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15527:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15528:     }
15529:     #
15530:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15531:         return '';
15532:     }
15533:     my $NumSets=1;
15534:     foreach my $array (@{$Ydata}){
15535:         next if (! ref($array));
15536:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15537:     }
15538:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15539:     #
15540:     # Deal with other parameters
15541:     while (my ($key,$value) = each(%Values)) {
15542:         $ValuesHash{$id.'.'.$key} = $value;
15543:     }
15544:     #
15545:     &Apache::lonnet::appenv(\%ValuesHash);
15546:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15547: }
15548: 
15549: ############################################################
15550: ############################################################
15551: 
15552: =pod
15553: 
15554: =item * &DrawXYYGraph()
15555: 
15556: Facilitates the plotting of data in an XY graph with two Y axes.
15557: Puts plot definition data into the users environment in order for 
15558: graph.png to plot it.  Returns an <img> tag for the plot.
15559: 
15560: Inputs:
15561: 
15562: =over 4
15563: 
15564: =item $Title: string, the title of the plot
15565: 
15566: =item $xlabel: string, text describing the X-axis of the plot
15567: 
15568: =item $ylabel: string, text describing the Y-axis of the plot
15569: 
15570: =item $colors: Array ref containing the hex color codes for the data to be 
15571: plotted in.  If undefined, default values will be used.
15572: 
15573: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15574: 
15575: =item $Ydata1: The first data set
15576: 
15577: =item $Min1: The minimum value of the left Y-axis
15578: 
15579: =item $Max1: The maximum value of the left Y-axis
15580: 
15581: =item $Ydata2: The second data set
15582: 
15583: =item $Min2: The minimum value of the right Y-axis
15584: 
15585: =item $Max2: The maximum value of the left Y-axis
15586: 
15587: =item %Values: hash indicating or overriding any default values which are 
15588: passed to graph.png.  
15589: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15590: 
15591: =back
15592: 
15593: Returns:
15594: 
15595: An <img> tag which references graph.png and the appropriate identifying
15596: information for the plot.
15597: 
15598: =cut
15599: 
15600: ############################################################
15601: ############################################################
15602: sub DrawXYYGraph {
15603:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15604:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
15605:     #
15606:     # Create the identifier for the graph
15607:     my $identifier = &get_cgi_id();
15608:     my $id = 'cgi.'.$identifier;
15609:     #
15610:     $Title  = '' if (! defined($Title));
15611:     $xlabel = '' if (! defined($xlabel));
15612:     $ylabel = '' if (! defined($ylabel));
15613:     my %ValuesHash = 
15614:         (
15615:          $id.'.title'  => &escape($Title),
15616:          $id.'.xlabel' => &escape($xlabel),
15617:          $id.'.ylabel' => &escape($ylabel),
15618:          $id.'.labels' => join(',',@$Xlabels),
15619:          $id.'.PlotType' => 'XY',
15620:          $id.'.NumSets' => 2,
15621:          $id.'.two_axes' => 1,
15622:          $id.'.y1_max_value' => $Max1,
15623:          $id.'.y1_min_value' => $Min1,
15624:          $id.'.y2_max_value' => $Max2,
15625:          $id.'.y2_min_value' => $Min2,
15626:          );
15627:     #
15628:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15629:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15630:     }
15631:     #
15632:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15633:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15634:         return '';
15635:     }
15636:     my $NumSets=1;
15637:     foreach my $array ($Ydata1,$Ydata2){
15638:         next if (! ref($array));
15639:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15640:     }
15641:     #
15642:     # Deal with other parameters
15643:     while (my ($key,$value) = each(%Values)) {
15644:         $ValuesHash{$id.'.'.$key} = $value;
15645:     }
15646:     #
15647:     &Apache::lonnet::appenv(\%ValuesHash);
15648:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15649: }
15650: 
15651: ############################################################
15652: ############################################################
15653: 
15654: =pod
15655: 
15656: =back 
15657: 
15658: =head1 Statistics helper routines?  
15659: 
15660: Bad place for them but what the hell.
15661: 
15662: =over 4
15663: 
15664: =item * &chartlink()
15665: 
15666: Returns a link to the chart for a specific student.  
15667: 
15668: Inputs:
15669: 
15670: =over 4
15671: 
15672: =item $linktext: The text of the link
15673: 
15674: =item $sname: The students username
15675: 
15676: =item $sdomain: The students domain
15677: 
15678: =back
15679: 
15680: =back
15681: 
15682: =cut
15683: 
15684: ############################################################
15685: ############################################################
15686: sub chartlink {
15687:     my ($linktext, $sname, $sdomain) = @_;
15688:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15689:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
15690:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
15691:        '">'.$linktext.'</a>';
15692: }
15693: 
15694: #######################################################
15695: #######################################################
15696: 
15697: =pod
15698: 
15699: =head1 Course Environment Routines
15700: 
15701: =over 4
15702: 
15703: =item * &restore_course_settings()
15704: 
15705: =item * &store_course_settings()
15706: 
15707: Restores/Store indicated form parameters from the course environment.
15708: Will not overwrite existing values of the form parameters.
15709: 
15710: Inputs: 
15711: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15712: 
15713: a hash ref describing the data to be stored.  For example:
15714:    
15715: %Save_Parameters = ('Status' => 'scalar',
15716:     'chartoutputmode' => 'scalar',
15717:     'chartoutputdata' => 'scalar',
15718:     'Section' => 'array',
15719:     'Group' => 'array',
15720:     'StudentData' => 'array',
15721:     'Maps' => 'array');
15722: 
15723: Returns: both routines return nothing
15724: 
15725: =back
15726: 
15727: =cut
15728: 
15729: #######################################################
15730: #######################################################
15731: sub store_course_settings {
15732:     return &store_settings($env{'request.course.id'},@_);
15733: }
15734: 
15735: sub store_settings {
15736:     # save to the environment
15737:     # appenv the same items, just to be safe
15738:     my $udom  = $env{'user.domain'};
15739:     my $uname = $env{'user.name'};
15740:     my ($context,$prefix,$Settings) = @_;
15741:     my %SaveHash;
15742:     my %AppHash;
15743:     while (my ($setting,$type) = each(%$Settings)) {
15744:         my $basename = join('.','internal',$context,$prefix,$setting);
15745:         my $envname = 'environment.'.$basename;
15746:         if (exists($env{'form.'.$setting})) {
15747:             # Save this value away
15748:             if ($type eq 'scalar' &&
15749:                 (! exists($env{$envname}) || 
15750:                  $env{$envname} ne $env{'form.'.$setting})) {
15751:                 $SaveHash{$basename} = $env{'form.'.$setting};
15752:                 $AppHash{$envname}   = $env{'form.'.$setting};
15753:             } elsif ($type eq 'array') {
15754:                 my $stored_form;
15755:                 if (ref($env{'form.'.$setting})) {
15756:                     $stored_form = join(',',
15757:                                         map {
15758:                                             &escape($_);
15759:                                         } sort(@{$env{'form.'.$setting}}));
15760:                 } else {
15761:                     $stored_form = 
15762:                         &escape($env{'form.'.$setting});
15763:                 }
15764:                 # Determine if the array contents are the same.
15765:                 if ($stored_form ne $env{$envname}) {
15766:                     $SaveHash{$basename} = $stored_form;
15767:                     $AppHash{$envname}   = $stored_form;
15768:                 }
15769:             }
15770:         }
15771:     }
15772:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15773:                                           $udom,$uname);
15774:     if ($put_result !~ /^(ok|delayed)/) {
15775:         &Apache::lonnet::logthis('unable to save form parameters, '.
15776:                                  'got error:'.$put_result);
15777:     }
15778:     # Make sure these settings stick around in this session, too
15779:     &Apache::lonnet::appenv(\%AppHash);
15780:     return;
15781: }
15782: 
15783: sub restore_course_settings {
15784:     return &restore_settings($env{'request.course.id'},@_);
15785: }
15786: 
15787: sub restore_settings {
15788:     my ($context,$prefix,$Settings) = @_;
15789:     while (my ($setting,$type) = each(%$Settings)) {
15790:         next if (exists($env{'form.'.$setting}));
15791:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
15792:             '.'.$setting;
15793:         if (exists($env{$envname})) {
15794:             if ($type eq 'scalar') {
15795:                 $env{'form.'.$setting} = $env{$envname};
15796:             } elsif ($type eq 'array') {
15797:                 $env{'form.'.$setting} = [ 
15798:                                            map { 
15799:                                                &unescape($_); 
15800:                                            } split(',',$env{$envname})
15801:                                            ];
15802:             }
15803:         }
15804:     }
15805: }
15806: 
15807: #######################################################
15808: #######################################################
15809: 
15810: =pod
15811: 
15812: =head1 Domain E-mail Routines  
15813: 
15814: =over 4
15815: 
15816: =item * &build_recipient_list()
15817: 
15818: Build recipient lists for following types of e-mail:
15819: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15820: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15821: module change checking, student/employee ID conflict checks, as
15822: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15823: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15824: 
15825: Inputs:
15826: defmail (scalar - email address of default recipient), 
15827: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15828: requestsmail, updatesmail, or idconflictsmail).
15829: 
15830: defdom (domain for which to retrieve configuration settings),
15831: 
15832: origmail (scalar - email address of recipient from loncapa.conf, 
15833: i.e., predates configuration by DC via domainprefs.pm
15834: 
15835: $requname username of requester (if mailing type is helpdeskmail)
15836: 
15837: $requdom domain of requester (if mailing type is helpdeskmail)
15838: 
15839: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15840: 
15841: 
15842: Returns: comma separated list of addresses to which to send e-mail.
15843: 
15844: =back
15845: 
15846: =cut
15847: 
15848: ############################################################
15849: ############################################################
15850: sub build_recipient_list {
15851:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15852:     my @recipients;
15853:     my ($otheremails,$lastresort,$allbcc,$addtext);
15854:     my %domconfig =
15855:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15856:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15857:         if (exists($domconfig{'contacts'}{$mailing})) {
15858:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15859:                 my @contacts = ('adminemail','supportemail');
15860:                 foreach my $item (@contacts) {
15861:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15862:                         my $addr = $domconfig{'contacts'}{$item}; 
15863:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15864:                             push(@recipients,$addr);
15865:                         }
15866:                     }
15867:                 }
15868:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15869:                 if ($mailing eq 'helpdeskmail') {
15870:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15871:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15872:                         my @ok_bccs;
15873:                         foreach my $bcc (@bccs) {
15874:                             $bcc =~ s/^\s+//g;
15875:                             $bcc =~ s/\s+$//g;
15876:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15877:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15878:                                     push(@ok_bccs,$bcc);
15879:                                 }
15880:                             }
15881:                         }
15882:                         if (@ok_bccs > 0) {
15883:                             $allbcc = join(', ',@ok_bccs);
15884:                         }
15885:                     }
15886:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15887:                 }
15888:             }
15889:         } elsif ($origmail ne '') {
15890:             $lastresort = $origmail;
15891:         }
15892:         if ($mailing eq 'helpdeskmail') {
15893:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15894:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15895:                 my ($inststatus,$inststatus_checked);
15896:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15897:                     ($env{'user.domain'} ne 'public')) {
15898:                     $inststatus_checked = 1;
15899:                     $inststatus = $env{'environment.inststatus'};
15900:                 }
15901:                 unless ($inststatus_checked) {
15902:                     if (($requname ne '') && ($requdom ne '')) {
15903:                         if (($requname =~ /^$match_username$/) &&
15904:                             ($requdom =~ /^$match_domain$/) &&
15905:                             (&Apache::lonnet::domain($requdom))) {
15906:                             my $requhome = &Apache::lonnet::homeserver($requname,
15907:                                                                       $requdom);
15908:                             unless ($requhome eq 'no_host') {
15909:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15910:                                 $inststatus = $userenv{'inststatus'};
15911:                                 $inststatus_checked = 1;
15912:                             }
15913:                         }
15914:                     }
15915:                 }
15916:                 unless ($inststatus_checked) {
15917:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15918:                         my %srch = (srchby     => 'email',
15919:                                     srchdomain => $defdom,
15920:                                     srchterm   => $reqemail,
15921:                                     srchtype   => 'exact');
15922:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15923:                         foreach my $uname (keys(%srch_results)) {
15924:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15925:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15926:                                 $inststatus_checked = 1;
15927:                                 last;
15928:                             }
15929:                         }
15930:                         unless ($inststatus_checked) {
15931:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15932:                             if ($dirsrchres eq 'ok') {
15933:                                 foreach my $uname (keys(%srch_results)) {
15934:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15935:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15936:                                         $inststatus_checked = 1;
15937:                                         last;
15938:                                     }
15939:                                 }
15940:                             }
15941:                         }
15942:                     }
15943:                 }
15944:                 if ($inststatus ne '') {
15945:                     foreach my $status (split(/\:/,$inststatus)) {
15946:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15947:                             my @contacts = ('adminemail','supportemail');
15948:                             foreach my $item (@contacts) {
15949:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15950:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15951:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15952:                                         push(@recipients,$addr);
15953:                                     }
15954:                                 }
15955:                             }
15956:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15957:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15958:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15959:                                 my @ok_bccs;
15960:                                 foreach my $bcc (@bccs) {
15961:                                     $bcc =~ s/^\s+//g;
15962:                                     $bcc =~ s/\s+$//g;
15963:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15964:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15965:                                             push(@ok_bccs,$bcc);
15966:                                         }
15967:                                     }
15968:                                 }
15969:                                 if (@ok_bccs > 0) {
15970:                                     $allbcc = join(', ',@ok_bccs);
15971:                                 }
15972:                             }
15973:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15974:                             last;
15975:                         }
15976:                     }
15977:                 }
15978:             }
15979:         }
15980:     } elsif ($origmail ne '') {
15981:         $lastresort = $origmail;
15982:     }
15983:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15984:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15985:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15986:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15987:             my %what = (
15988:                           perlvar => 1,
15989:                        );
15990:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15991:             if ($primary) {
15992:                 my $gotaddr;
15993:                 my ($result,$returnhash) =
15994:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15995:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15996:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15997:                         $lastresort = $returnhash->{'lonSupportEMail'};
15998:                         $gotaddr = 1;
15999:                     }
16000:                 }
16001:                 unless ($gotaddr) {
16002:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
16003:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
16004:                     unless ($uintdom eq $intdom) {
16005:                         my %domconfig =
16006:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
16007:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
16008:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
16009:                                 my @contacts = ('adminemail','supportemail');
16010:                                 foreach my $item (@contacts) {
16011:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
16012:                                         my $addr = $domconfig{'contacts'}{$item};
16013:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
16014:                                             push(@recipients,$addr);
16015:                                         }
16016:                                     }
16017:                                 }
16018:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
16019:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
16020:                                 }
16021:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
16022:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
16023:                                     my @ok_bccs;
16024:                                     foreach my $bcc (@bccs) {
16025:                                         $bcc =~ s/^\s+//g;
16026:                                         $bcc =~ s/\s+$//g;
16027:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16028:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16029:                                                 push(@ok_bccs,$bcc);
16030:                                             }
16031:                                         }
16032:                                     }
16033:                                     if (@ok_bccs > 0) {
16034:                                         $allbcc = join(', ',@ok_bccs);
16035:                                     }
16036:                                 }
16037:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
16038:                             }
16039:                         }
16040:                     }
16041:                 }
16042:             }
16043:         }
16044:     }
16045:     if (defined($defmail)) {
16046:         if ($defmail ne '') {
16047:             push(@recipients,$defmail);
16048:         }
16049:     }
16050:     if ($otheremails) {
16051:         my @others;
16052:         if ($otheremails =~ /,/) {
16053:             @others = split(/,/,$otheremails);
16054:         } else {
16055:             push(@others,$otheremails);
16056:         }
16057:         foreach my $addr (@others) {
16058:             if (!grep(/^\Q$addr\E$/,@recipients)) {
16059:                 push(@recipients,$addr);
16060:             }
16061:         }
16062:     }
16063:     if ($mailing eq 'helpdeskmail') {
16064:         if ((!@recipients) && ($lastresort ne '')) {
16065:             push(@recipients,$lastresort);
16066:         }
16067:     } elsif ($lastresort ne '') {
16068:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
16069:             push(@recipients,$lastresort);
16070:         }
16071:     }
16072:     my $recipientlist = join(',',@recipients);
16073:     if (wantarray) {
16074:         return ($recipientlist,$allbcc,$addtext);
16075:     } else {
16076:         return $recipientlist;
16077:     }
16078: }
16079: 
16080: ############################################################
16081: ############################################################
16082: 
16083: =pod
16084: 
16085: =over 4
16086: 
16087: =item * &mime_email()
16088: 
16089: Sends an email with a possible attachment
16090: 
16091: Inputs:
16092: 
16093: =over 4
16094: 
16095: from -              Sender's email address
16096: 
16097: replyto -           Reply-To email address
16098: 
16099: to -                Email address of recipient
16100: 
16101: subject -           Subject of email
16102: 
16103: body -              Body of email
16104: 
16105: cc_string -         Carbon copy email address
16106: 
16107: bcc -               Blind carbon copy email address
16108: 
16109: attachment_path -   Path of file to be attached
16110: 
16111: file_name -         Name of file to be attached
16112: 
16113: attachment_text -   The body of an attachment of type "TEXT"
16114: 
16115: =back
16116: 
16117: =back
16118: 
16119: =cut
16120: 
16121: ############################################################
16122: ############################################################
16123: 
16124: sub mime_email {
16125:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
16126:         $file_name,$attachment_text) = @_;
16127:  
16128:     my $msg = MIME::Lite->new(
16129:              From    => $from,
16130:              To      => $to,
16131:              Subject => $subject,
16132:              Type    =>'TEXT',
16133:              Data    => $body,
16134:              );
16135:     if ($replyto ne '') {
16136:         $msg->add("Reply-To" => $replyto);
16137:     }
16138:     if ($cc_string ne '') {
16139:         $msg->add("Cc" => $cc_string);
16140:     }
16141:     if ($bcc ne '') {
16142:         $msg->add("Bcc" => $bcc);
16143:     }
16144:     $msg->attr("content-type"         => "text/plain");
16145:     $msg->attr("content-type.charset" => "UTF-8");
16146:     # Attach file if given
16147:     if ($attachment_path) {
16148:         unless ($file_name) {
16149:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
16150:         }
16151:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
16152:         $msg->attach(Type     => $type,
16153:                      Path     => $attachment_path,
16154:                      Filename => $file_name
16155:                      );
16156:     # Otherwise attach text if given
16157:     } elsif ($attachment_text) {
16158:         $msg->attach(Type => 'TEXT',
16159:                      Data => $attachment_text);
16160:     }
16161:     # Send it
16162:     $msg->send('sendmail');
16163: }
16164: 
16165: ############################################################
16166: ############################################################
16167: 
16168: =pod
16169: 
16170: =head1 Course Catalog Routines
16171: 
16172: =over 4
16173: 
16174: =item * &gather_categories()
16175: 
16176: Converts category definitions - keys of categories hash stored in  
16177: coursecategories in configuration.db on the primary library server in a 
16178: domain - to an array.  Also generates javascript and idx hash used to 
16179: generate Domain Coordinator interface for editing Course Categories.
16180: 
16181: Inputs:
16182: 
16183: categories (reference to hash of category definitions).
16184: 
16185: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16186:       categories and subcategories).
16187: 
16188: idx (reference to hash of counters used in Domain Coordinator interface for 
16189:       editing Course Categories).
16190: 
16191: jsarray (reference to array of categories used to create Javascript arrays for
16192:          Domain Coordinator interface for editing Course Categories).
16193: 
16194: Returns: nothing
16195: 
16196: Side effects: populates cats, idx and jsarray. 
16197: 
16198: =cut
16199: 
16200: sub gather_categories {
16201:     my ($categories,$cats,$idx,$jsarray) = @_;
16202:     my %counters;
16203:     my $num = 0;
16204:     foreach my $item (keys(%{$categories})) {
16205:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16206:         if ($container eq '' && $depth == 0) {
16207:             $cats->[$depth][$categories->{$item}] = $cat;
16208:         } else {
16209:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
16210:         }
16211:         my ($escitem,$tail) = split(/:/,$item,2);
16212:         if ($counters{$tail} eq '') {
16213:             $counters{$tail} = $num;
16214:             $num ++;
16215:         }
16216:         if (ref($idx) eq 'HASH') {
16217:             $idx->{$item} = $counters{$tail};
16218:         }
16219:         if (ref($jsarray) eq 'ARRAY') {
16220:             push(@{$jsarray->[$counters{$tail}]},$item);
16221:         }
16222:     }
16223:     return;
16224: }
16225: 
16226: =pod
16227: 
16228: =item * &extract_categories()
16229: 
16230: Used to generate breadcrumb trails for course categories.
16231: 
16232: Inputs:
16233: 
16234: categories (reference to hash of category definitions).
16235: 
16236: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16237:       categories and subcategories).
16238: 
16239: trails (reference to array of breacrumb trails for each category).
16240: 
16241: allitems (reference to hash - key is category key 
16242:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16243: 
16244: idx (reference to hash of counters used in Domain Coordinator interface for
16245:       editing Course Categories).
16246: 
16247: jsarray (reference to array of categories used to create Javascript arrays for
16248:          Domain Coordinator interface for editing Course Categories).
16249: 
16250: subcats (reference to hash of arrays containing all subcategories within each 
16251:          category, -recursive)
16252: 
16253: maxd (reference to hash used to hold max depth for all top-level categories).
16254: 
16255: Returns: nothing
16256: 
16257: Side effects: populates trails and allitems hash references.
16258: 
16259: =cut
16260: 
16261: sub extract_categories {
16262:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
16263:     if (ref($categories) eq 'HASH') {
16264:         &gather_categories($categories,$cats,$idx,$jsarray);
16265:         if (ref($cats->[0]) eq 'ARRAY') {
16266:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
16267:                 my $name = $cats->[0][$i];
16268:                 my $item = &escape($name).'::0';
16269:                 my $trailstr;
16270:                 if ($name eq 'instcode') {
16271:                     $trailstr = &mt('Official courses (with institutional codes)');
16272:                 } elsif ($name eq 'communities') {
16273:                     $trailstr = &mt('Communities');
16274:                 } elsif ($name eq 'placement') {
16275:                     $trailstr = &mt('Placement Tests');
16276:                 } else {
16277:                     $trailstr = $name;
16278:                 }
16279:                 if ($allitems->{$item} eq '') {
16280:                     push(@{$trails},$trailstr);
16281:                     $allitems->{$item} = scalar(@{$trails})-1;
16282:                 }
16283:                 my @parents = ($name);
16284:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
16285:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
16286:                         my $category = $cats->[1]{$name}[$j];
16287:                         if (ref($subcats) eq 'HASH') {
16288:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
16289:                         }
16290:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
16291:                     }
16292:                 } else {
16293:                     if (ref($subcats) eq 'HASH') {
16294:                         $subcats->{$item} = [];
16295:                     }
16296:                     if (ref($maxd) eq 'HASH') {
16297:                         $maxd->{$name} = 1;
16298:                     }
16299:                 }
16300:             }
16301:         }
16302:     }
16303:     return;
16304: }
16305: 
16306: =pod
16307: 
16308: =item * &recurse_categories()
16309: 
16310: Recursively used to generate breadcrumb trails for course categories.
16311: 
16312: Inputs:
16313: 
16314: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16315:       categories and subcategories).
16316: 
16317: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16318: 
16319: category (current course category, for which breadcrumb trail is being generated).
16320: 
16321: trails (reference to array of breadcrumb trails for each category).
16322: 
16323: allitems (reference to hash - key is category key
16324:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16325: 
16326: parents (array containing containers directories for current category, 
16327:          back to top level). 
16328: 
16329: Returns: nothing
16330: 
16331: Side effects: populates trails and allitems hash references
16332: 
16333: =cut
16334: 
16335: sub recurse_categories {
16336:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16337:     my $shallower = $depth - 1;
16338:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16339:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16340:             my $name = $cats->[$depth]{$category}[$k];
16341:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16342:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
16343:             if ($allitems->{$item} eq '') {
16344:                 push(@{$trails},$trailstr);
16345:                 $allitems->{$item} = scalar(@{$trails})-1;
16346:             }
16347:             my $deeper = $depth+1;
16348:             push(@{$parents},$category);
16349:             if (ref($subcats) eq 'HASH') {
16350:                 my $subcat = &escape($name).':'.$category.':'.$depth;
16351:                 for (my $j=@{$parents}; $j>=0; $j--) {
16352:                     my $higher;
16353:                     if ($j > 0) {
16354:                         $higher = &escape($parents->[$j]).':'.
16355:                                   &escape($parents->[$j-1]).':'.$j;
16356:                     } else {
16357:                         $higher = &escape($parents->[$j]).'::'.$j;
16358:                     }
16359:                     push(@{$subcats->{$higher}},$subcat);
16360:                 }
16361:             }
16362:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16363:                                 $subcats,$maxd);
16364:             pop(@{$parents});
16365:         }
16366:     } else {
16367:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16368:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
16369:         if ($allitems->{$item} eq '') {
16370:             push(@{$trails},$trailstr);
16371:             $allitems->{$item} = scalar(@{$trails})-1;
16372:         }
16373:         if (ref($maxd) eq 'HASH') {
16374:             if ($depth > $maxd->{$parents->[0]}) {
16375:                 $maxd->{$parents->[0]} = $depth;
16376:             }
16377:         }
16378:     }
16379:     return;
16380: }
16381: 
16382: =pod
16383: 
16384: =item * &assign_categories_table()
16385: 
16386: Create a datatable for display of hierarchical categories in a domain,
16387: with checkboxes to allow a course to be categorized. 
16388: 
16389: Inputs:
16390: 
16391: cathash - reference to hash of categories defined for the domain (from
16392:           configuration.db)
16393: 
16394: currcat - scalar with an & separated list of categories assigned to a course. 
16395: 
16396: type    - scalar contains course type (Course or Community).
16397: 
16398: disabled - scalar (optional) contains disabled="disabled" if input elements are
16399:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16400: 
16401: Returns: $output (markup to be displayed) 
16402: 
16403: =cut
16404: 
16405: sub assign_categories_table {
16406:     my ($cathash,$currcat,$type,$disabled) = @_;
16407:     my $output;
16408:     if (ref($cathash) eq 'HASH') {
16409:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16410:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16411:         $maxdepth = scalar(@cats);
16412:         if (@cats > 0) {
16413:             my $itemcount = 0;
16414:             if (ref($cats[0]) eq 'ARRAY') {
16415:                 my @currcategories;
16416:                 if ($currcat ne '') {
16417:                     @currcategories = split('&',$currcat);
16418:                 }
16419:                 my $table;
16420:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
16421:                     my $parent = $cats[0][$i];
16422:                     next if ($parent eq 'instcode');
16423:                     if ($type eq 'Community') {
16424:                         next unless ($parent eq 'communities');
16425:                     } elsif ($type eq 'Placement') {
16426:                         next unless ($parent eq 'placement');
16427:                     } else {
16428:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
16429:                     }
16430:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16431:                     my $item = &escape($parent).'::0';
16432:                     my $checked = '';
16433:                     if (@currcategories > 0) {
16434:                         if (grep(/^\Q$item\E$/,@currcategories)) {
16435:                             $checked = ' checked="checked"';
16436:                         }
16437:                     }
16438:                     my $parent_title = $parent;
16439:                     if ($parent eq 'communities') {
16440:                         $parent_title = &mt('Communities');
16441:                     } elsif ($parent eq 'placement') {
16442:                         $parent_title = &mt('Placement Tests');
16443:                     }
16444:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16445:                               '<input type="checkbox" name="usecategory" value="'.
16446:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16447:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16448:                     my $depth = 1;
16449:                     push(@path,$parent);
16450:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16451:                     pop(@path);
16452:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16453:                     $itemcount ++;
16454:                 }
16455:                 if ($itemcount) {
16456:                     $output = &Apache::loncommon::start_data_table().
16457:                               $table.
16458:                               &Apache::loncommon::end_data_table();
16459:                 }
16460:             }
16461:         }
16462:     }
16463:     return $output;
16464: }
16465: 
16466: =pod
16467: 
16468: =item * &assign_category_rows()
16469: 
16470: Create a datatable row for display of nested categories in a domain,
16471: with checkboxes to allow a course to be categorized,called recursively.
16472: 
16473: Inputs:
16474: 
16475: itemcount - track row number for alternating colors
16476: 
16477: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16478:       categories and subcategories.
16479: 
16480: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16481: 
16482: parent - parent of current category item
16483: 
16484: path - Array containing all categories back up through the hierarchy from the
16485:        current category to the top level.
16486: 
16487: currcategories - reference to array of current categories assigned to the course
16488: 
16489: disabled - scalar (optional) contains disabled="disabled" if input elements are
16490:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16491: 
16492: Returns: $output (markup to be displayed).
16493: 
16494: =cut
16495: 
16496: sub assign_category_rows {
16497:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16498:     my ($text,$name,$item,$chgstr);
16499:     if (ref($cats) eq 'ARRAY') {
16500:         my $maxdepth = scalar(@{$cats});
16501:         if (ref($cats->[$depth]) eq 'HASH') {
16502:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16503:                 my $numchildren = @{$cats->[$depth]{$parent}};
16504:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16505:                 $text .= '<td><table class="LC_data_table">';
16506:                 for (my $j=0; $j<$numchildren; $j++) {
16507:                     $name = $cats->[$depth]{$parent}[$j];
16508:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
16509:                     my $deeper = $depth+1;
16510:                     my $checked = '';
16511:                     if (ref($currcategories) eq 'ARRAY') {
16512:                         if (@{$currcategories} > 0) {
16513:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
16514:                                 $checked = ' checked="checked"';
16515:                             }
16516:                         }
16517:                     }
16518:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
16519:                              '<input type="checkbox" name="usecategory" value="'.
16520:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16521:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
16522:                              '</td><td>';
16523:                     if (ref($path) eq 'ARRAY') {
16524:                         push(@{$path},$name);
16525:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16526:                         pop(@{$path});
16527:                     }
16528:                     $text .= '</td></tr>';
16529:                 }
16530:                 $text .= '</table></td>';
16531:             }
16532:         }
16533:     }
16534:     return $text;
16535: }
16536: 
16537: =pod
16538: 
16539: =back
16540: 
16541: =cut
16542: 
16543: ############################################################
16544: ############################################################
16545: 
16546: 
16547: sub commit_customrole {
16548:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
16549:     my $result = &Apache::lonnet::assigncustomrole(
16550:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
16551:                      $context,$othdomby,$requester);
16552:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16553:                          ($start?', '.&mt('starting').' '.localtime($start):'').
16554:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
16555:     if (wantarray) {
16556:         return ($output,$result);
16557:     } else {
16558:         return $output;
16559:     }
16560: }
16561: 
16562: sub commit_standardrole {
16563:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
16564:         $othdomby,$requester) = @_;
16565:     my ($output,$logmsg,$linefeed,$result);
16566:     if ($context eq 'auto') {
16567:         $linefeed = "\n";
16568:     } else {
16569:         $linefeed = "<br />\n";
16570:     }  
16571:     if ($three eq 'st') {
16572:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16573:                                       $one,$two,$sec,$context,$credits,$othdomby,
16574:                                       $requester);
16575:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
16576:             ($result eq 'unknown_course') || ($result eq 'refused')) {
16577:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
16578:         } else {
16579:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16580:                ($start?', '.&mt('starting').' '.localtime($start):'').
16581:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16582:             if ($context eq 'auto') {
16583:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16584:             } else {
16585:                $output .= '<b>'.$result.'</b>'.$linefeed.
16586:                &mt('Add to classlist').': <b>ok</b>';
16587:             }
16588:             $output .= $linefeed;
16589:         }
16590:     } else {
16591:         $output = &mt('Assigning').' '.$three.' in '.$url.
16592:                ($start?', '.&mt('starting').' '.localtime($start):'').
16593:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16594:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
16595:                                               '','',$context,$othdomby,$requester);
16596:         if ($context eq 'auto') {
16597:             $output .= $result.$linefeed;
16598:         } else {
16599:             $output .= '<b>'.$result.'</b>'.$linefeed;
16600:         }
16601:     }
16602:     if (wantarray) {
16603:         return ($output,$result);
16604:     } else {
16605:         return $output;
16606:     }
16607: }
16608: 
16609: sub commit_studentrole {
16610:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16611:         $credits,$othdomby,$requester) = @_;
16612:     my ($result,$linefeed,$oldsecurl,$newsecurl);
16613:     if ($context eq 'auto') {
16614:         $linefeed = "\n";
16615:     } else {
16616:         $linefeed = '<br />'."\n";
16617:     }
16618:     if (defined($one) && defined($two)) {
16619:         my $cid=$one.'_'.$two;
16620:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16621:         my $secchange = 0;
16622:         my $expire_role_result;
16623:         my $modify_section_result;
16624:         if ($oldsec ne '-1') { 
16625:             if ($oldsec ne $sec) {
16626:                 $secchange = 1;
16627:                 my $now = time;
16628:                 my $uurl='/'.$cid;
16629:                 $uurl=~s/\_/\//g;
16630:                 if ($oldsec) {
16631:                     $uurl.='/'.$oldsec;
16632:                 }
16633:                 $oldsecurl = $uurl;
16634:                 $expire_role_result = 
16635:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
16636:                                                 '','','',$context,$othdomby,$requester);
16637:                 if ($env{'request.course.sec'} ne '') {
16638:                     if ($expire_role_result eq 'refused') {
16639:                         my @roles = ('st');
16640:                         my @statuses = ('previous');
16641:                         my @roledoms = ($one);
16642:                         my $withsec = 1;
16643:                         my %roleshash = 
16644:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16645:                                               \@statuses,\@roles,\@roledoms,$withsec);
16646:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16647:                             my ($oldstart,$oldend) = 
16648:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16649:                             if ($oldend > 0 && $oldend <= $now) {
16650:                                 $expire_role_result = 'ok';
16651:                             }
16652:                         }
16653:                     }
16654:                 }
16655:                 $result = $expire_role_result;
16656:             }
16657:         }
16658:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16659:             $modify_section_result = 
16660:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16661:                                                            undef,undef,undef,$sec,
16662:                                                            $end,$start,'','',$cid,
16663:                                                            '',$context,$credits,'',
16664:                                                            $othdomby,$requester);
16665:             if ($modify_section_result =~ /^ok/) {
16666:                 if ($secchange == 1) {
16667:                     if ($sec eq '') {
16668:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16669:                     } else {
16670:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16671:                     }
16672:                 } elsif ($oldsec eq '-1') {
16673:                     if ($sec eq '') {
16674:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16675:                     } else {
16676:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16677:                     }
16678:                 } else {
16679:                     if ($sec eq '') {
16680:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16681:                     } else {
16682:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16683:                     }
16684:                 }
16685:             } else {
16686:                 if ($secchange) { 
16687:                     $$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;
16688:                 } else {
16689:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16690:                 }
16691:             }
16692:             $result = $modify_section_result;
16693:         } elsif ($secchange == 1) {
16694:             if ($oldsec eq '') {
16695:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16696:             } else {
16697:                 $$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;
16698:             }
16699:             if ($expire_role_result eq 'refused') {
16700:                 my $newsecurl = '/'.$cid;
16701:                 $newsecurl =~ s/\_/\//g;
16702:                 if ($sec ne '') {
16703:                     $newsecurl.='/'.$sec;
16704:                 }
16705:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16706:                     if ($sec eq '') {
16707:                         $$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;
16708:                     } else {
16709:                         $$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;
16710:                     }
16711:                 }
16712:             }
16713:         }
16714:     } else {
16715:         $$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;
16716:         $result = "error: incomplete course id\n";
16717:     }
16718:     return $result;
16719: }
16720: 
16721: sub show_role_extent {
16722:     my ($scope,$context,$role) = @_;
16723:     $scope =~ s{^/}{};
16724:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16725:     push(@courseroles,'co');
16726:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16727:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16728:         $scope =~ s{/}{_};
16729:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16730:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16731:         my ($audom,$auname) = split(/\//,$scope);
16732:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16733:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
16734:     } else {
16735:         $scope =~ s{/$}{};
16736:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16737:                    &Apache::lonnet::domain($scope,'description').'</span>');
16738:     }
16739: }
16740: 
16741: ############################################################
16742: ############################################################
16743: 
16744: sub check_clone {
16745:     my ($args,$linefeed) = @_;
16746:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16747:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16748:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16749:     my $clonetitle;
16750:     my @clonemsg;
16751:     my $can_clone = 0;
16752:     my $lctype = lc($args->{'crstype'});
16753:     if ($lctype ne 'community') {
16754:         $lctype = 'course';
16755:     }
16756:     if ($clonehome eq 'no_host') {
16757:         if ($args->{'crstype'} eq 'Community') {
16758:             push(@clonemsg,({
16759:                               mt => 'No new community created.',
16760:                               args => [],
16761:                             },
16762:                             {
16763:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16764:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16765:                             }));
16766:         } else {
16767:             push(@clonemsg,({
16768:                               mt => 'No new course created.',
16769:                               args => [],
16770:                             },
16771:                             {
16772:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16773:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16774:                             }));
16775:         }
16776:     } else {
16777: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16778:         $clonetitle = $clonedesc{'description'};
16779:         if ($args->{'crstype'} eq 'Community') {
16780:             if ($clonedesc{'type'} ne 'Community') {
16781:                 push(@clonemsg,({
16782:                                   mt => 'No new community created.',
16783:                                   args => [],
16784:                                 },
16785:                                 {
16786:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16787:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16788:                                 }));
16789:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16790:             }
16791:         }
16792: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16793:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16794: 	    $can_clone = 1;
16795: 	} else {
16796: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16797: 						 $args->{'clonedomain'},$args->{'clonecourse'});
16798:             if ($clonehash{'cloners'} eq '') {
16799:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16800:                 if ($domdefs{'canclone'}) {
16801:                     unless ($domdefs{'canclone'} eq 'none') {
16802:                         if ($domdefs{'canclone'} eq 'domain') {
16803:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16804:                                 $can_clone = 1;
16805:                             }
16806:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16807:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16808:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16809:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16810:                                 $can_clone = 1;
16811:                             }
16812:                         }
16813:                     }
16814:                 }
16815:             } else {
16816: 	        my @cloners = split(/,/,$clonehash{'cloners'});
16817:                 if (grep(/^\*$/,@cloners)) {
16818:                     $can_clone = 1;
16819:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16820:                     $can_clone = 1;
16821:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16822:                     $can_clone = 1;
16823:                 }
16824:                 unless ($can_clone) {
16825:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16826:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16827:                         my (%gotdomdefaults,%gotcodedefaults);
16828:                         foreach my $cloner (@cloners) {
16829:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16830:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16831:                                 my (%codedefaults,@code_order);
16832:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16833:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16834:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16835:                                     }
16836:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16837:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16838:                                     }
16839:                                 } else {
16840:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16841:                                                                             \%codedefaults,
16842:                                                                             \@code_order);
16843:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16844:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16845:                                 }
16846:                                 if (@code_order > 0) {
16847:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16848:                                                                                 $cloner,$clonehash{'internal.coursecode'},
16849:                                                                                 $args->{'crscode'})) {
16850:                                         $can_clone = 1;
16851:                                         last;
16852:                                     }
16853:                                 }
16854:                             }
16855:                         }
16856:                     }
16857:                 }
16858:             }
16859:             unless ($can_clone) {
16860:                 my $ccrole = 'cc';
16861:                 if ($args->{'crstype'} eq 'Community') {
16862:                     $ccrole = 'co';
16863:                 }
16864: 	        my %roleshash =
16865: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
16866: 					          $args->{'ccdomain'},
16867:                                                   'userroles',['active'],[$ccrole],
16868: 					          [$args->{'clonedomain'}]);
16869: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16870:                     $can_clone = 1;
16871:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16872:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
16873:                     $can_clone = 1;
16874:                 }
16875:             }
16876:             unless ($can_clone) {
16877:                 if ($args->{'crstype'} eq 'Community') {
16878:                     push(@clonemsg,({
16879:                                       mt => 'No new community created.',
16880:                                       args => [],
16881:                                     },
16882:                                     {
16883:                                       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]).',
16884:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16885:                                     }));
16886:                 } else {
16887:                     push(@clonemsg,({
16888:                                       mt => 'No new course created.',
16889:                                       args => [],
16890:                                     },
16891:                                     {
16892:                                       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]).',
16893:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16894:                                     }));
16895:                 }
16896: 	    }
16897:         }
16898:     }
16899:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16900: }
16901: 
16902: sub construct_course {
16903:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16904:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16905:     my ($outcome,$msgref,$clonemsgref);
16906:     my $linefeed =  '<br />'."\n";
16907:     if ($context eq 'auto') {
16908:         $linefeed = "\n";
16909:     }
16910: 
16911: #
16912: # Are we cloning?
16913: #
16914:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16915:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16916: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16917:         if (!$can_clone) {
16918: 	    return (0,$outcome,$clonemsgref);
16919: 	}
16920:     }
16921: 
16922: #
16923: # Open course
16924: #
16925:     my $showncrstype;
16926:     if ($args->{'crstype'} eq 'Placement') {
16927:         $showncrstype = 'placement test'; 
16928:     } else {  
16929:         $showncrstype = lc($args->{'crstype'});
16930:     }
16931:     my %cenv=();
16932:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16933:                                              $args->{'cdescr'},
16934:                                              $args->{'curl'},
16935:                                              $args->{'course_home'},
16936:                                              $args->{'nonstandard'},
16937:                                              $args->{'crscode'},
16938:                                              $args->{'ccuname'}.':'.
16939:                                              $args->{'ccdomain'},
16940:                                              $args->{'crstype'},
16941:                                              $cnum,$context,$category,
16942:                                              $callercontext);
16943: 
16944:     # Note: The testing routines depend on this being output; see 
16945:     # Utils::Course. This needs to at least be output as a comment
16946:     # if anyone ever decides to not show this, and Utils::Course::new
16947:     # will need to be suitably modified.
16948:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16949:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16950:     } else {
16951:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16952:     }
16953:     if ($$courseid =~ /^error:/) {
16954:         return (0,$outcome,$clonemsgref);
16955:     }
16956: 
16957: #
16958: # Check if created correctly
16959: #
16960:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16961:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16962:     if ($crsuhome eq 'no_host') {
16963:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16964:             $outcome .= &mt_user($user_lh,
16965:                             'Course creation failed, unrecognized course home server.');
16966:         } else {
16967:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16968:         }
16969:         $outcome .= $linefeed;
16970:         return (0,$outcome,$clonemsgref);
16971:     }
16972:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16973: 
16974: #
16975: # Do the cloning
16976: #   
16977:     my @clonemsg;
16978:     if ($can_clone && $cloneid) {
16979:         push(@clonemsg,
16980:                       {
16981:                           mt => 'Created [_1] by cloning from [_2]',
16982:                           args => [$showncrstype,$clonetitle],
16983:                       });
16984: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16985: # Copy all files
16986:         my @info =
16987: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16988: 	                                             $args->{'dateshift'},$args->{'crscode'},
16989:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16990:                                                      $args->{'tinyurls'});
16991:         if (@info) {
16992:             push(@clonemsg,@info);
16993:         }
16994: # Restore URL
16995: 	$cenv{'url'}=$oldcenv{'url'};
16996: # Restore title
16997: 	$cenv{'description'}=$oldcenv{'description'};
16998: # Restore creation date, creator and creation context.
16999:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
17000:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
17001:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
17002: # Mark as cloned
17003: 	$cenv{'clonedfrom'}=$cloneid;
17004: # Need to clone grading mode
17005:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
17006:         $cenv{'grading'}=$newenv{'grading'};
17007: # Do not clone these environment entries
17008:         &Apache::lonnet::del('environment',
17009:                   ['default_enrollment_start_date',
17010:                    'default_enrollment_end_date',
17011:                    'question.email',
17012:                    'policy.email',
17013:                    'comment.email',
17014:                    'pch.users.denied',
17015:                    'plc.users.denied',
17016:                    'hidefromcat',
17017:                    'checkforpriv',
17018:                    'categories'],
17019:                    $$crsudom,$$crsunum);
17020:         if ($args->{'textbook'}) {
17021:             $cenv{'internal.textbook'} = $args->{'textbook'};
17022:         }
17023:     }
17024: 
17025: #
17026: # Set environment (will override cloned, if existing)
17027: #
17028:     my @sections = ();
17029:     my @xlists = ();
17030:     if ($args->{'crstype'}) {
17031:         $cenv{'type'}=$args->{'crstype'};
17032:     }
17033:     if ($args->{'lti'}) {
17034:         $cenv{'internal.lti'}=$args->{'lti'};
17035:     }
17036:     if ($args->{'crsid'}) {
17037:         $cenv{'courseid'}=$args->{'crsid'};
17038:     }
17039:     if ($args->{'crscode'}) {
17040:         $cenv{'internal.coursecode'}=$args->{'crscode'};
17041:     }
17042:     if ($args->{'crsquota'} ne '') {
17043:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
17044:     } else {
17045:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
17046:     }
17047:     if ($args->{'ccuname'}) {
17048:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
17049:                                         ':'.$args->{'ccdomain'};
17050:     } else {
17051:         $cenv{'internal.courseowner'} = $args->{'curruser'};
17052:     }
17053:     if ($args->{'defaultcredits'}) {
17054:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
17055:     }
17056:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
17057:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
17058:     if ($args->{'crssections'}) {
17059:         $cenv{'internal.sectionnums'} = '';
17060:         if ($args->{'crssections'} =~ m/,/) {
17061:             @sections = split/,/,$args->{'crssections'};
17062:         } else {
17063:             $sections[0] = $args->{'crssections'};
17064:         }
17065:         if (@sections > 0) {
17066:             foreach my $item (@sections) {
17067:                 my ($sec,$gp) = split/:/,$item;
17068:                 my $class = $args->{'crscode'}.$sec;
17069:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
17070:                 $cenv{'internal.sectionnums'} .= $item.',';
17071:                 if ($addcheck eq 'ok') {
17072:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17073:                         push(@oklcsecs,$gp);
17074:                     }
17075:                 } else {
17076:                     push(@badclasses,$class);
17077:                 }
17078:             }
17079:             $cenv{'internal.sectionnums'} =~ s/,$//;
17080:         }
17081:     }
17082: # do not hide course coordinator from staff listing, 
17083: # even if privileged
17084:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17085: # add course coordinator's domain to domains to check for privileged users
17086: # if different to course domain
17087:     if ($$crsudom ne $args->{'ccdomain'}) {
17088:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
17089:     }
17090: # add crosslistings
17091:     if ($args->{'crsxlist'}) {
17092:         $cenv{'internal.crosslistings'}='';
17093:         if ($args->{'crsxlist'} =~ m/,/) {
17094:             @xlists = split/,/,$args->{'crsxlist'};
17095:         } else {
17096:             $xlists[0] = $args->{'crsxlist'};
17097:         }
17098:         if (@xlists > 0) {
17099:             foreach my $item (@xlists) {
17100:                 my ($xl,$gp) = split/:/,$item;
17101:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
17102:                 $cenv{'internal.crosslistings'} .= $item.',';
17103:                 if ($addcheck eq 'ok') {
17104:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17105:                         push(@oklcsecs,$gp);
17106:                     }
17107:                 } else {
17108:                     push(@badclasses,$xl);
17109:                 }
17110:             }
17111:             $cenv{'internal.crosslistings'} =~ s/,$//;
17112:         }
17113:     }
17114:     if ($args->{'autoadds'}) {
17115:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
17116:     }
17117:     if ($args->{'autodrops'}) {
17118:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
17119:     }
17120: # check for notification of enrollment changes
17121:     my @notified = ();
17122:     if ($args->{'notify_owner'}) {
17123:         if ($args->{'ccuname'} ne '') {
17124:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
17125:         }
17126:     }
17127:     if ($args->{'notify_dc'}) {
17128:         if ($uname ne '') { 
17129:             push(@notified,$uname.':'.$udom);
17130:         }
17131:     }
17132:     if (@notified > 0) {
17133:         my $notifylist;
17134:         if (@notified > 1) {
17135:             $notifylist = join(',',@notified);
17136:         } else {
17137:             $notifylist = $notified[0];
17138:         }
17139:         $cenv{'internal.notifylist'} = $notifylist;
17140:     }
17141:     if (@badclasses > 0) {
17142:         my %lt=&Apache::lonlocal::texthash(
17143:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
17144:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
17145:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
17146:         );
17147:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
17148:                            &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'};
17149:         if ($context eq 'auto') {
17150:             $outcome .= $badclass_msg.$linefeed;
17151:         } else {
17152:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
17153:         }
17154:         foreach my $item (@badclasses) {
17155:             if ($context eq 'auto') {
17156:                 $outcome .= " - $item\n";
17157:             } else {
17158:                 $outcome .= "<li>$item</li>\n";
17159:             }
17160:         }
17161:         if ($context eq 'auto') {
17162:             $outcome .= $linefeed;
17163:         } else {
17164:             $outcome .= "</ul><br /><br /></div>\n";
17165:         } 
17166:     }
17167:     if ($args->{'no_end_date'}) {
17168:         $args->{'endaccess'} = 0;
17169:     }
17170: #  If an official course with institutional sections is created by cloning 
17171: #  an existing course, section-specific hiding of course totals in student's
17172: #  view of grades as copied from cloned course, will be checked for valid 
17173: #  sections.
17174:     if (($can_clone && $cloneid) &&
17175:         ($cenv{'internal.coursecode'} ne '') &&
17176:         ($cenv{'grading'} eq 'standard') &&
17177:         ($cenv{'hidetotals'} ne '') &&
17178:         ($cenv{'hidetotals'} ne 'all')) {
17179:         my @hidesecs;
17180:         my $deletehidetotals;
17181:         if (@oklcsecs) {
17182:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
17183:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
17184:                     push(@hidesecs,$sec);
17185:                 }
17186:             }
17187:             if (@hidesecs) {
17188:                 $cenv{'hidetotals'} = join(',',@hidesecs);
17189:             } else {
17190:                 $deletehidetotals = 1;
17191:             }
17192:         } else {
17193:             $deletehidetotals = 1;
17194:         }
17195:         if ($deletehidetotals) {
17196:             delete($cenv{'hidetotals'});
17197:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
17198:         }
17199:     }
17200:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
17201:     $cenv{'internal.autoend'}=$args->{'enrollend'};
17202:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
17203:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
17204:     if ($args->{'showphotos'}) {
17205:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
17206:     }
17207:     $cenv{'internal.authtype'} = $args->{'authtype'};
17208:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
17209:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
17210:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
17211:             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'); 
17212:             if ($context eq 'auto') {
17213:                 $outcome .= $krb_msg;
17214:             } else {
17215:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
17216:             }
17217:             $outcome .= $linefeed;
17218:         }
17219:     }
17220:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
17221:        if ($args->{'setpolicy'}) {
17222:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17223:        }
17224:        if ($args->{'setcontent'}) {
17225:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17226:        }
17227:        if ($args->{'setcomment'}) {
17228:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17229:        }
17230:     }
17231:     if ($args->{'reshome'}) {
17232: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
17233: 	$cenv{'reshome'}=~s/\/+$/\//;
17234:     }
17235: #
17236: # course has keyed access
17237: #
17238:     if ($args->{'setkeys'}) {
17239:        $cenv{'keyaccess'}='yes';
17240:     }
17241: # if specified, key authority is not course, but user
17242: # only active if keyaccess is yes
17243:     if ($args->{'keyauth'}) {
17244: 	my ($user,$domain) = split(':',$args->{'keyauth'});
17245: 	$user = &LONCAPA::clean_username($user);
17246: 	$domain = &LONCAPA::clean_username($domain);
17247: 	if ($user ne '' && $domain ne '') {
17248: 	    $cenv{'keyauth'}=$user.':'.$domain;
17249: 	}
17250:     }
17251: 
17252: #
17253: #  generate and store uniquecode (available to course requester), if course should have one.
17254: #
17255:     if ($args->{'uniquecode'}) {
17256:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
17257:         if ($code) {
17258:             $cenv{'internal.uniquecode'} = $code;
17259:             my %crsinfo =
17260:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
17261:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
17262:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
17263:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
17264:             } 
17265:             if (ref($coderef)) {
17266:                 $$coderef = $code;
17267:             }
17268:         }
17269:     }
17270: 
17271:     if ($args->{'disresdis'}) {
17272:         $cenv{'pch.roles.denied'}='st';
17273:     }
17274:     if ($args->{'disablechat'}) {
17275:         $cenv{'plc.roles.denied'}='st';
17276:     }
17277: 
17278:     # Record we've not yet viewed the Course Initialization Helper for this 
17279:     # course
17280:     $cenv{'course.helper.not.run'} = 1;
17281:     #
17282:     # Use new Randomseed
17283:     #
17284:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
17285:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
17286:     #
17287:     # The encryption code and receipt prefix for this course
17288:     #
17289:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
17290:     $cenv{'internal.encpref'}=100+int(9*rand(99));
17291:     #
17292:     # By default, use standard grading
17293:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
17294: 
17295:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
17296:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
17297: #
17298: # Open all assignments
17299: #
17300:     if ($args->{'openall'}) {
17301:        my $opendate = time;
17302:        if ($args->{'openallfrom'} =~ /^\d+$/) {
17303:            $opendate = $args->{'openallfrom'};
17304:        }
17305:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
17306:        my %storecontent = ($storeunder         => $opendate,
17307:                            $storeunder.'.type' => 'date_start');
17308:        $outcome .= &mt('All assignments open starting [_1]',
17309:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
17310:                    &Apache::lonnet::cput
17311:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
17312:    }
17313: #
17314: # Set first page
17315: #
17316:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
17317: 	    || ($cloneid)) {
17318: 	$outcome .= &mt('Setting first resource').': ';
17319: 
17320: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
17321:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
17322: 
17323:         $outcome .= ($fatal?$errtext:'read ok').' - ';
17324:         my $title; my $url;
17325:         if ($args->{'firstres'} eq 'syl') {
17326: 	    $title=&mt('Syllabus');
17327:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
17328:         } else {
17329:             $title=&mt('Table of Contents');
17330:             $url='/adm/navmaps';
17331:         }
17332: 
17333:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
17334: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
17335: 
17336: 	if ($errtext) { $fatal=2; }
17337:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
17338:     }
17339: 
17340: # 
17341: # Set params for Placement Tests
17342: #
17343:     if ($args->{'crstype'} eq 'Placement') {
17344:        my %storecontent; 
17345:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
17346:        my %defaults = (
17347:                         buttonshide   => { value => 'yes',
17348:                                            type => 'string_yesno',},
17349:                         type          => { value => 'randomizetry',
17350:                                            type  => 'string_questiontype',},
17351:                         maxtries      => { value => 1,
17352:                                            type => 'int_pos',},
17353:                         problemstatus => { value => 'no',
17354:                                            type  => 'string_problemstatus',},
17355:                       );
17356:        foreach my $key (keys(%defaults)) {
17357:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17358:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17359:        }
17360:        &Apache::lonnet::cput
17361:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
17362:     }
17363: 
17364:     return (1,$outcome,\@clonemsg);
17365: }
17366: 
17367: sub make_unique_code {
17368:     my ($cdom,$cnum) = @_;
17369:     # get lock on uniquecodes db
17370:     my $lockhash = {
17371:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
17372:                                                   ':'.$env{'user.domain'},
17373:                    };
17374:     my $tries = 0;
17375:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17376:     my ($code,$error);
17377:   
17378:     while (($gotlock ne 'ok') && ($tries<3)) {
17379:         $tries ++;
17380:         sleep 1;
17381:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17382:     }
17383:     if ($gotlock eq 'ok') {
17384:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17385:         my $gotcode;
17386:         my $attempts = 0;
17387:         while ((!$gotcode) && ($attempts < 100)) {
17388:             $code = &generate_code();
17389:             if (!exists($currcodes{$code})) {
17390:                 $gotcode = 1;
17391:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17392:                     $error = 'nostore';
17393:                 }
17394:             }
17395:             $attempts ++;
17396:         }
17397:         my @del_lock = ($cnum."\0".'uniquecodes');
17398:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17399:     } else {
17400:         $error = 'nolock';
17401:     }
17402:     return ($code,$error);
17403: }
17404: 
17405: sub generate_code {
17406:     my $code;
17407:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17408:     for (my $i=0; $i<6; $i++) {
17409:         my $lettnum = int (rand 2);
17410:         my $item = '';
17411:         if ($lettnum) {
17412:             $item = $letts[int( rand(18) )];
17413:         } else {
17414:             $item = 1+int( rand(8) );
17415:         }
17416:         $code .= $item;
17417:     }
17418:     return $code;
17419: }
17420: 
17421: ############################################################
17422: ############################################################
17423: 
17424: # Community, Course and Placement Test
17425: sub course_type {
17426:     my ($cid) = @_;
17427:     if (!defined($cid)) {
17428:         $cid = $env{'request.course.id'};
17429:     }
17430:     if (defined($env{'course.'.$cid.'.type'})) {
17431:         return $env{'course.'.$cid.'.type'};
17432:     } else {
17433:         return 'Course';
17434:     }
17435: }
17436: 
17437: sub group_term {
17438:     my $crstype = &course_type();
17439:     my %names = (
17440:                   'Course' => 'group',
17441:                   'Community' => 'group',
17442:                   'Placement' => 'group',
17443:                 );
17444:     return $names{$crstype};
17445: }
17446: 
17447: sub course_types {
17448:     my @types = ('official','unofficial','community','textbook','placement','lti');
17449:     my %typename = (
17450:                          official   => 'Official course',
17451:                          unofficial => 'Unofficial course',
17452:                          community  => 'Community',
17453:                          textbook   => 'Textbook course',
17454:                          placement  => 'Placement test',
17455:                          lti        => 'LTI provider',
17456:                    );
17457:     return (\@types,\%typename);
17458: }
17459: 
17460: sub icon {
17461:     my ($file)=@_;
17462:     my $curfext = lc((split(/\./,$file))[-1]);
17463:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17464:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17465:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17466: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17467: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17468: 	            $curfext.".gif") {
17469: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17470: 		$curfext.".gif";
17471: 	}
17472:     }
17473:     return &lonhttpdurl($iconname);
17474: } 
17475: 
17476: sub lonhttpdurl {
17477: #
17478: # Had been used for "small fry" static images on separate port 8080.
17479: # Modify here if lightweight http functionality desired again.
17480: # Currently eliminated due to increasing firewall issues.
17481: #
17482:     my ($url)=@_;
17483:     return $url;
17484: }
17485: 
17486: sub connection_aborted {
17487:     my ($r)=@_;
17488:     $r->print(" ");$r->rflush();
17489:     my $c = $r->connection;
17490:     return $c->aborted();
17491: }
17492: 
17493: #    Escapes strings that may have embedded 's that will be put into
17494: #    strings as 'strings'.
17495: sub escape_single {
17496:     my ($input) = @_;
17497:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
17498:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
17499:     return $input;
17500: }
17501: 
17502: #  Same as escape_single, but escape's "'s  This 
17503: #  can be used for  "strings"
17504: sub escape_double {
17505:     my ($input) = @_;
17506:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
17507:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
17508:     return $input;
17509: }
17510:  
17511: #   Escapes the last element of a full URL.
17512: sub escape_url {
17513:     my ($url)   = @_;
17514:     my @urlslices = split(/\//, $url,-1);
17515:     my $lastitem = &escape(pop(@urlslices));
17516:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17517: }
17518: 
17519: sub compare_arrays {
17520:     my ($arrayref1,$arrayref2) = @_;
17521:     my (@difference,%count);
17522:     @difference = ();
17523:     %count = ();
17524:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17525:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17526:         foreach my $element (keys(%count)) {
17527:             if ($count{$element} == 1) {
17528:                 push(@difference,$element);
17529:             }
17530:         }
17531:     }
17532:     return @difference;
17533: }
17534: 
17535: sub lon_status_items {
17536:     my %defaults = (
17537:                      E         => 100,
17538:                      W         => 4,
17539:                      N         => 1,
17540:                      U         => 5,
17541:                      threshold => 200,
17542:                      sysmail   => 2500,
17543:                    );
17544:     my %names = (
17545:                    E => 'Errors',
17546:                    W => 'Warnings',
17547:                    N => 'Notices',
17548:                    U => 'Unsent',
17549:                 );
17550:     return (\%defaults,\%names);
17551: }
17552: 
17553: # -------------------------------------------------------- Initialize user login
17554: sub init_user_environment {
17555:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
17556:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17557: 
17558:     my $public=($username eq 'public' && $domain eq 'public');
17559: 
17560:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
17561:     my $now=time;
17562: 
17563:     if ($public) {
17564: 	my $max_public=100;
17565: 	my $oldest;
17566: 	my $oldest_time=0;
17567: 	for(my $next=1;$next<=$max_public;$next++) {
17568: 	    if (-e $lonids."/publicuser_$next.id") {
17569: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17570: 		if ($mtime<$oldest_time || !$oldest_time) {
17571: 		    $oldest_time=$mtime;
17572: 		    $oldest=$next;
17573: 		}
17574: 	    } else {
17575: 		$cookie="publicuser_$next";
17576: 		last;
17577: 	    }
17578: 	}
17579: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
17580:     } else {
17581: 	# See if old ID present, if so, remove if this isn't a robot,
17582: 	# killing any existing non-robot sessions
17583: 	if (!$args->{'robot'}) {
17584: 	    opendir(DIR,$lonids);
17585: 	    while ($filename=readdir(DIR)) {
17586: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17587:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17588:                             &GDBM_READER(),0640)) {
17589:                         my $linkedfile;
17590:                         if (exists($oldenv{'user.linkedenv'})) {
17591:                             $linkedfile = $oldenv{'user.linkedenv'};
17592:                         }
17593:                         untie(%oldenv);
17594:                         if (unlink("$lonids/$filename")) {
17595:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17596:                                 if (-l "$lonids/$linkedfile.id") {
17597:                                     unlink("$lonids/$linkedfile.id");
17598:                                 }
17599:                             }
17600:                         }
17601:                     } else {
17602:                         unlink($lonids.'/'.$filename);
17603:                     }
17604: 		}
17605: 	    }
17606: 	    closedir(DIR);
17607: # If there is a undeleted lockfile for the user's paste buffer remove it.
17608:             my $namespace = 'nohist_courseeditor';
17609:             my $lockingkey = 'paste'."\0".'locked_num';
17610:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17611:                                                 $domain,$username);
17612:             if (exists($lockhash{$lockingkey})) {
17613:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17614:                 unless ($delresult eq 'ok') {
17615:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17616:                 }
17617:             }
17618: 	}
17619: # Give them a new cookie
17620: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17621: 		                   : $now.$$.int(rand(10000)));
17622: 	$cookie="$username\_$id\_$domain\_$authhost";
17623:     
17624: # Initialize roles
17625: 
17626: 	($userroles,$firstaccenv,$timerintenv) = 
17627:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
17628:     }
17629: # ------------------------------------ Check browser type and MathML capability
17630: 
17631:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17632:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17633: 
17634: # ------------------------------------------------------------- Get environment
17635: 
17636:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17637:     my ($tmp) = keys(%userenv);
17638:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17639: 	undef(%userenv);
17640:     }
17641:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
17642: 	$form->{'interface'}=$userenv{'interface'};
17643:     }
17644:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17645: 
17646: # --------------- Do not trust query string to be put directly into environment
17647:     foreach my $option ('interface','localpath','localres') {
17648:         $form->{$option}=~s/[\n\r\=]//gs;
17649:     }
17650: # --------------------------------------------------------- Write first profile
17651: 
17652:     {
17653:         my $ip = &Apache::lonnet::get_requestor_ip($r);
17654: 	my %initial_env = 
17655: 	    ("user.name"          => $username,
17656: 	     "user.domain"        => $domain,
17657: 	     "user.home"          => $authhost,
17658: 	     "browser.type"       => $clientbrowser,
17659: 	     "browser.version"    => $clientversion,
17660: 	     "browser.mathml"     => $clientmathml,
17661: 	     "browser.unicode"    => $clientunicode,
17662: 	     "browser.os"         => $clientos,
17663:              "browser.mobile"     => $clientmobile,
17664:              "browser.info"       => $clientinfo,
17665:              "browser.osversion"  => $clientosversion,
17666: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
17667: 	     "request.course.fn"  => '',
17668: 	     "request.course.uri" => '',
17669: 	     "request.course.sec" => '',
17670: 	     "request.role"       => 'cm',
17671: 	     "request.role.adv"   => $env{'user.adv'},
17672: 	     "request.host"       => $ip,);
17673: 
17674:         if ($form->{'localpath'}) {
17675: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
17676: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
17677:         }
17678: 	
17679: 	if ($form->{'interface'}) {
17680: 	    $form->{'interface'}=~s/\W//gs;
17681: 	    $initial_env{"browser.interface"} = $form->{'interface'};
17682: 	    $env{'browser.interface'}=$form->{'interface'};
17683: 	}
17684: 
17685:         if ($form->{'iptoken'}) {
17686:             my $lonhost = $r->dir_config('lonHostID');
17687:             $initial_env{"user.noloadbalance"} = $lonhost;
17688:             $env{'user.noloadbalance'} = $lonhost;
17689:         }
17690: 
17691:         if ($form->{'noloadbalance'}) {
17692:             my @hosts = &Apache::lonnet::current_machine_ids();
17693:             my $hosthere = $form->{'noloadbalance'};
17694:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
17695:                 $initial_env{"user.noloadbalance"} = $hosthere;
17696:                 $env{'user.noloadbalance'} = $hosthere;
17697:             }
17698:         }
17699: 
17700:         unless ($domain eq 'public') {
17701:             my %is_adv = ( is_adv => $env{'user.adv'} );
17702:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17703: 
17704:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
17705:                 $userenv{'availabletools.'.$tool} = 
17706:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17707:                                                       undef,\%userenv,\%domdef,\%is_adv);
17708:             }
17709: 
17710:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17711:                 $userenv{'canrequest.'.$crstype} =
17712:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
17713:                                                       'reload','requestcourses',
17714:                                                       \%userenv,\%domdef,\%is_adv);
17715:             }
17716: 
17717:             $userenv{'canrequest.author'} =
17718:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17719:                                                   'reload','requestauthor',
17720:                                                   \%userenv,\%domdef,\%is_adv);
17721:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17722:                                                  $domain,$username);
17723:             my $reqstatus = $reqauthor{'author_status'};
17724:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
17725:                 if (ref($reqauthor{'author'}) eq 'HASH') {
17726:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
17727:                                                       $reqauthor{'author'}{'timestamp'};
17728:                 }
17729:             }
17730:             my ($types,$typename) = &course_types();
17731:             if (ref($types) eq 'ARRAY') {
17732:                 my @options = ('approval','validate','autolimit');
17733:                 my $optregex = join('|',@options);
17734:                 my (%willtrust,%trustchecked);
17735:                 foreach my $type (@{$types}) {
17736:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17737:                     if ($dom_str ne '') {
17738:                         my $updatedstr = '';
17739:                         my @possdomains = split(',',$dom_str);
17740:                         foreach my $entry (@possdomains) {
17741:                             my ($extdom,$extopt) = split(':',$entry);
17742:                             unless ($trustchecked{$extdom}) {
17743:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17744:                                 $trustchecked{$extdom} = 1;
17745:                             }
17746:                             if ($willtrust{$extdom}) {
17747:                                 $updatedstr .= $entry.',';
17748:                             }
17749:                         }
17750:                         $updatedstr =~ s/,$//;
17751:                         if ($updatedstr) {
17752:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
17753:                         } else {
17754:                             delete($userenv{'reqcrsotherdom.'.$type});
17755:                         }
17756:                     }
17757:                 }
17758:             }
17759:         }
17760: 	$env{'user.environment'} = "$lonids/$cookie.id";
17761: 
17762: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
17763: 		 &GDBM_WRCREAT(),0640)) {
17764: 	    &_add_to_env(\%disk_env,\%initial_env);
17765: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
17766: 	    &_add_to_env(\%disk_env,$userroles);
17767:             if (ref($firstaccenv) eq 'HASH') {
17768:                 &_add_to_env(\%disk_env,$firstaccenv);
17769:             }
17770:             if (ref($timerintenv) eq 'HASH') {
17771:                 &_add_to_env(\%disk_env,$timerintenv);
17772:             }
17773: 	    if (ref($args->{'extra_env'})) {
17774: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
17775: 	    }
17776: 	    untie(%disk_env);
17777: 	} else {
17778: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
17779: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
17780: 	    return 'error: '.$!;
17781: 	}
17782:     }
17783:     $env{'request.role'}='cm';
17784:     $env{'request.role.adv'}=$env{'user.adv'};
17785:     $env{'browser.type'}=$clientbrowser;
17786: 
17787:     return $cookie;
17788: 
17789: }
17790: 
17791: sub _add_to_env {
17792:     my ($idf,$env_data,$prefix) = @_;
17793:     if (ref($env_data) eq 'HASH') {
17794:         while (my ($key,$value) = each(%$env_data)) {
17795: 	    $idf->{$prefix.$key} = $value;
17796: 	    $env{$prefix.$key}   = $value;
17797:         }
17798:     }
17799: }
17800: 
17801: # --- Get the symbolic name of a problem and the url
17802: sub get_symb {
17803:     my ($request,$silent) = @_;
17804:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
17805:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
17806:     if ($symb eq '') {
17807:         if (!$silent) {
17808:             if (ref($request)) { 
17809:                 $request->print("Unable to handle ambiguous references:$url:.");
17810:             }
17811:             return ();
17812:         }
17813:     }
17814:     &Apache::lonenc::check_decrypt(\$symb);
17815:     return ($symb);
17816: }
17817: 
17818: # --------------------------------------------------------------Get annotation
17819: 
17820: sub get_annotation {
17821:     my ($symb,$enc) = @_;
17822: 
17823:     my $key = $symb;
17824:     if (!$enc) {
17825:         $key =
17826:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17827:     }
17828:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17829:     return $annotation{$key};
17830: }
17831: 
17832: sub clean_symb {
17833:     my ($symb,$delete_enc) = @_;
17834: 
17835:     &Apache::lonenc::check_decrypt(\$symb);
17836:     my $enc = $env{'request.enc'};
17837:     if ($delete_enc) {
17838:         delete($env{'request.enc'});
17839:     }
17840: 
17841:     return ($symb,$enc);
17842: }
17843: 
17844: ############################################################
17845: ############################################################
17846: 
17847: =pod
17848: 
17849: =head1 Routines for building display used to search for courses
17850: 
17851: 
17852: =over 4
17853: 
17854: =item * &build_filters()
17855: 
17856: Create markup for a table used to set filters to use when selecting
17857: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
17858: and quotacheck.pl
17859: 
17860: 
17861: Inputs:
17862: 
17863: filterlist - anonymous array of fields to include as potential filters 
17864: 
17865: crstype - course type
17866: 
17867: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17868:               to pop-open a course selector (will contain "extra element"). 
17869: 
17870: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17871: 
17872: filter - anonymous hash of criteria and their values
17873: 
17874: action - form action
17875: 
17876: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17877: 
17878: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17879: 
17880: cloneruname - username of owner of new course who wants to clone
17881: 
17882: clonerudom - domain of owner of new course who wants to clone
17883: 
17884: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
17885: 
17886: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17887: 
17888: codedom - domain
17889: 
17890: formname - value of form element named "form". 
17891: 
17892: fixeddom - domain, if fixed.
17893: 
17894: prevphase - value to assign to form element named "phase" when going back to the previous screen  
17895: 
17896: cnameelement - name of form element in form on opener page which will receive title of selected course 
17897: 
17898: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
17899: 
17900: cdomelement - name of form element in form on opener page which will receive domain of selected course
17901: 
17902: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17903: 
17904: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17905: 
17906: clonewarning - warning message about missing information for intended course owner when DC creates a course
17907: 
17908: 
17909: Returns: $output - HTML for display of search criteria, and hidden form elements.
17910: 
17911: 
17912: Side Effects: None
17913: 
17914: =cut
17915: 
17916: # ---------------------------------------------- search for courses based on last activity etc.
17917: 
17918: sub build_filters {
17919:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17920:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17921:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17922:         $cnameelement,$cnumelement,$cdomelement,$setroles,
17923:         $clonetext,$clonewarning) = @_;
17924:     my ($list,$jscript);
17925:     my $onchange = 'javascript:updateFilters(this)';
17926:     my ($domainselectform,$sincefilterform,$createdfilterform,
17927:         $ownerdomselectform,$persondomselectform,$instcodeform,
17928:         $typeselectform,$instcodetitle);
17929:     if ($formname eq '') {
17930:         $formname = $caller;
17931:     }
17932:     foreach my $item (@{$filterlist}) {
17933:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17934:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17935:             if ($item eq 'domainfilter') {
17936:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17937:             } elsif ($item eq 'coursefilter') {
17938:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17939:             } elsif ($item eq 'ownerfilter') {
17940:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17941:             } elsif ($item eq 'ownerdomfilter') {
17942:                 $filter->{'ownerdomfilter'} =
17943:                     &LONCAPA::clean_domain($filter->{$item});
17944:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17945:                                                        'ownerdomfilter',1);
17946:             } elsif ($item eq 'personfilter') {
17947:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17948:             } elsif ($item eq 'persondomfilter') {
17949:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17950:                                                         'persondomfilter',1);
17951:             } else {
17952:                 $filter->{$item} =~ s/\W//g;
17953:             }
17954:             if (!$filter->{$item}) {
17955:                 $filter->{$item} = '';
17956:             }
17957:         }
17958:         if ($item eq 'domainfilter') {
17959:             my $allow_blank = 1;
17960:             if ($formname eq 'portform') {
17961:                 $allow_blank=0;
17962:             } elsif ($formname eq 'studentform') {
17963:                 $allow_blank=0;
17964:             }
17965:             if ($fixeddom) {
17966:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
17967:                                     ' value="'.$codedom.'" />'.
17968:                                     &Apache::lonnet::domain($codedom,'description');
17969:             } else {
17970:                 $domainselectform = &select_dom_form($filter->{$item},
17971:                                                      'domainfilter',
17972:                                                       $allow_blank,'',$onchange);
17973:             }
17974:         } else {
17975:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17976:         }
17977:     }
17978: 
17979:     # last course activity filter and selection
17980:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
17981: 
17982:     # course created filter and selection
17983:     if (exists($filter->{'createdfilter'})) {
17984:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
17985:     }
17986: 
17987:     my $prefix = $crstype;
17988:     if ($crstype eq 'Placement') {
17989:         $prefix = 'Placement Test'
17990:     }
17991:     my %lt = &Apache::lonlocal::texthash(
17992:                 'cac' => "$prefix Activity",
17993:                 'ccr' => "$prefix Created",
17994:                 'cde' => "$prefix Title",
17995:                 'cdo' => "$prefix Domain",
17996:                 'ins' => 'Institutional Code',
17997:                 'inc' => 'Institutional Categorization',
17998:                 'cow' => "$prefix Owner/Co-owner",
17999:                 'cop' => "$prefix Personnel Includes",
18000:                 'cog' => 'Type',
18001:              );
18002: 
18003:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18004:         my $typeval = 'Course';
18005:         if ($crstype eq 'Community') {
18006:             $typeval = 'Community';
18007:         } elsif ($crstype eq 'Placement') {
18008:             $typeval = 'Placement';
18009:         }
18010:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
18011:     } else {
18012:         $typeselectform =  '<select name="type" size="1"';
18013:         if ($onchange) {
18014:             $typeselectform .= ' onchange="'.$onchange.'"';
18015:         }
18016:         $typeselectform .= '>'."\n";
18017:         foreach my $posstype ('Course','Community','Placement') {
18018:             my $shown;
18019:             if ($posstype eq 'Placement') {
18020:                 $shown = &mt('Placement Test');
18021:             } else {
18022:                 $shown = &mt($posstype);
18023:             }
18024:             $typeselectform.='<option value="'.$posstype.'"'.
18025:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
18026:         }
18027:         $typeselectform.="</select>";
18028:     }
18029: 
18030:     my ($cloneableonlyform,$cloneabletitle);
18031:     if (exists($filter->{'cloneableonly'})) {
18032:         my $cloneableon = '';
18033:         my $cloneableoff = ' checked="checked"';
18034:         if ($filter->{'cloneableonly'}) {
18035:             $cloneableon = $cloneableoff;
18036:             $cloneableoff = '';
18037:         }
18038:         $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>';
18039:         if ($formname eq 'ccrs') {
18040:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
18041:         } else {
18042:             $cloneabletitle = &mt('Cloneable by you');
18043:         }
18044:     }
18045:     my $officialjs;
18046:     if ($crstype eq 'Course') {
18047:         if (exists($filter->{'instcodefilter'})) {
18048: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
18049: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
18050:             if ($codedom) { 
18051:                 $officialjs = 1;
18052:                 ($instcodeform,$jscript,$$numtitlesref) =
18053:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
18054:                                                                   $officialjs,$codetitlesref);
18055:                 if ($jscript) {
18056:                     $jscript = '<script type="text/javascript">'."\n".
18057:                                '// <![CDATA['."\n".
18058:                                $jscript."\n".
18059:                                '// ]]>'."\n".
18060:                                '</script>'."\n";
18061:                 }
18062:             }
18063:             if ($instcodeform eq '') {
18064:                 $instcodeform =
18065:                     '<input type="text" name="instcodefilter" size="10" value="'.
18066:                     $list->{'instcodefilter'}.'" />';
18067:                 $instcodetitle = $lt{'ins'};
18068:             } else {
18069:                 $instcodetitle = $lt{'inc'};
18070:             }
18071:             if ($fixeddom) {
18072:                 $instcodetitle .= '<br />('.$codedom.')';
18073:             }
18074:         }
18075:     }
18076:     my $output = qq|
18077: <form method="post" name="filterpicker" action="$action">
18078: <input type="hidden" name="form" value="$formname" />
18079: |;
18080:     if ($formname eq 'modifycourse') {
18081:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
18082:                    '<input type="hidden" name="prevphase" value="'.
18083:                    $prevphase.'" />'."\n";
18084:     } elsif ($formname eq 'quotacheck') {
18085:         $output .= qq|
18086: <input type="hidden" name="sortby" value="" />
18087: <input type="hidden" name="sortorder" value="" />
18088: |;
18089:     } else {
18090:         my $name_input;
18091:         if ($cnameelement ne '') {
18092:             $name_input = '<input type="hidden" name="cnameelement" value="'.
18093:                           $cnameelement.'" />';
18094:         }
18095:         $output .= qq|
18096: <input type="hidden" name="cnumelement" value="$cnumelement" />
18097: <input type="hidden" name="cdomelement" value="$cdomelement" />
18098: $name_input
18099: $roleelement
18100: $multelement
18101: $typeelement
18102: |;
18103:         if ($formname eq 'portform') {
18104:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
18105:         }
18106:     }
18107:     if ($fixeddom) {
18108:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
18109:     }
18110:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
18111:     if ($sincefilterform) {
18112:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
18113:                   .$sincefilterform
18114:                   .&Apache::lonhtmlcommon::row_closure();
18115:     }
18116:     if ($createdfilterform) {
18117:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
18118:                   .$createdfilterform
18119:                   .&Apache::lonhtmlcommon::row_closure();
18120:     }
18121:     if ($domainselectform) {
18122:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
18123:                   .$domainselectform
18124:                   .&Apache::lonhtmlcommon::row_closure();
18125:     }
18126:     if ($typeselectform) {
18127:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18128:             $output .= $typeselectform;
18129:         } else {
18130:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
18131:                       .$typeselectform
18132:                       .&Apache::lonhtmlcommon::row_closure();
18133:         }
18134:     }
18135:     if ($instcodeform) {
18136:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
18137:                   .$instcodeform
18138:                   .&Apache::lonhtmlcommon::row_closure();
18139:     }
18140:     if (exists($filter->{'ownerfilter'})) {
18141:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
18142:                    '<table><tr><td>'.&mt('Username').'<br />'.
18143:                    '<input type="text" name="ownerfilter" size="20" value="'.
18144:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18145:                    $ownerdomselectform.'</td></tr></table>'.
18146:                    &Apache::lonhtmlcommon::row_closure();
18147:     }
18148:     if (exists($filter->{'personfilter'})) {
18149:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
18150:                    '<table><tr><td>'.&mt('Username').'<br />'.
18151:                    '<input type="text" name="personfilter" size="20" value="'.
18152:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18153:                    $persondomselectform.'</td></tr></table>'.
18154:                    &Apache::lonhtmlcommon::row_closure();
18155:     }
18156:     if (exists($filter->{'coursefilter'})) {
18157:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
18158:                   .'<input type="text" name="coursefilter" size="25" value="'
18159:                   .$list->{'coursefilter'}.'" />'
18160:                   .&Apache::lonhtmlcommon::row_closure();
18161:     }
18162:     if ($cloneableonlyform) {
18163:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
18164:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
18165:     }
18166:     if (exists($filter->{'descriptfilter'})) {
18167:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
18168:                   .'<input type="text" name="descriptfilter" size="40" value="'
18169:                   .$list->{'descriptfilter'}.'" />'
18170:                   .&Apache::lonhtmlcommon::row_closure(1);
18171:     }
18172:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
18173:                '<input type="hidden" name="updater" value="" />'."\n".
18174:                '<input type="submit" name="gosearch" value="'.
18175:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
18176:     return $jscript.$clonewarning.$output;
18177: }
18178: 
18179: =pod 
18180: 
18181: =item * &timebased_select_form()
18182: 
18183: Create markup for a dropdown list used to select a time-based
18184: filter e.g., Course Activity, Course Created, when searching for courses
18185: or communities
18186: 
18187: Inputs:
18188: 
18189: item - name of form element (sincefilter or createdfilter)
18190: 
18191: filter - anonymous hash of criteria and their values
18192: 
18193: Returns: HTML for a select box contained a blank, then six time selections,
18194:          with value set in incoming form variables currently selected. 
18195: 
18196: Side Effects: None
18197: 
18198: =cut
18199: 
18200: sub timebased_select_form {
18201:     my ($item,$filter) = @_;
18202:     if (ref($filter) eq 'HASH') {
18203:         $filter->{$item} =~ s/[^\d-]//g;
18204:         if (!$filter->{$item}) { $filter->{$item}=-1; }
18205:         return &select_form(
18206:                             $filter->{$item},
18207:                             $item,
18208:                             {      '-1' => '',
18209:                                 '86400' => &mt('today'),
18210:                                '604800' => &mt('last week'),
18211:                               '2592000' => &mt('last month'),
18212:                               '7776000' => &mt('last three months'),
18213:                              '15552000' => &mt('last six months'),
18214:                              '31104000' => &mt('last year'),
18215:                     'select_form_order' =>
18216:                            ['-1','86400','604800','2592000','7776000',
18217:                             '15552000','31104000']});
18218:     }
18219: }
18220: 
18221: =pod
18222: 
18223: =item * &js_changer()
18224: 
18225: Create script tag containing Javascript used to submit course search form
18226: when course type or domain is changed, and also to hide 'Searching ...' on
18227: page load completion for page showing search result.
18228: 
18229: Inputs: None
18230: 
18231: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
18232: 
18233: Side Effects: None
18234: 
18235: =cut
18236: 
18237: sub js_changer {
18238:     return <<ENDJS;
18239: <script type="text/javascript">
18240: // <![CDATA[
18241: function updateFilters(caller) {
18242:     if (typeof(caller) != "undefined") {
18243:         document.filterpicker.updater.value = caller.name;
18244:     }
18245:     document.filterpicker.submit();
18246: }
18247: 
18248: function hideSearching() {
18249:     if (document.getElementById('searching')) {
18250:         document.getElementById('searching').style.display = 'none';
18251:     }
18252:     return;
18253: }
18254: 
18255: // ]]>
18256: </script>
18257: 
18258: ENDJS
18259: }
18260: 
18261: =pod
18262: 
18263: =item * &search_courses()
18264: 
18265: Process selected filters form course search form and pass to lonnet::courseiddump
18266: to retrieve a hash for which keys are courseIDs which match the selected filters.
18267: 
18268: Inputs:
18269: 
18270: dom - domain being searched 
18271: 
18272: type - course type ('Course' or 'Community' or '.' if any).
18273: 
18274: filter - anonymous hash of criteria and their values
18275: 
18276: numtitles - for institutional codes - number of categories
18277: 
18278: cloneruname - optional username of new course owner
18279: 
18280: clonerudom - optional domain of new course owner
18281: 
18282: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
18283:             (used when DC is using course creation form)
18284: 
18285: codetitles - reference to array of titles of components in institutional codes (official courses).
18286: 
18287: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
18288:            (and so can clone automatically)
18289: 
18290: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
18291: 
18292: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
18293:               courses to clone 
18294: 
18295: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
18296: 
18297: 
18298: Side Effects: None
18299: 
18300: =cut
18301: 
18302: 
18303: sub search_courses {
18304:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
18305:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
18306:     my (%courses,%showcourses,$cloner);
18307:     if (($filter->{'ownerfilter'} ne '') ||
18308:         ($filter->{'ownerdomfilter'} ne '')) {
18309:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
18310:                                        $filter->{'ownerdomfilter'};
18311:     }
18312:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
18313:         if (!$filter->{$item}) {
18314:             $filter->{$item}='.';
18315:         }
18316:     }
18317:     my $now = time;
18318:     my $timefilter =
18319:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
18320:     my ($createdbefore,$createdafter);
18321:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
18322:         $createdbefore = $now;
18323:         $createdafter = $now-$filter->{'createdfilter'};
18324:     }
18325:     my ($instcodefilter,$regexpok);
18326:     if ($numtitles) {
18327:         if ($env{'form.official'} eq 'on') {
18328:             $instcodefilter =
18329:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18330:             $regexpok = 1;
18331:         } elsif ($env{'form.official'} eq 'off') {
18332:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18333:             unless ($instcodefilter eq '') {
18334:                 $regexpok = -1;
18335:             }
18336:         }
18337:     } else {
18338:         $instcodefilter = $filter->{'instcodefilter'};
18339:     }
18340:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
18341:     if ($type eq '') { $type = '.'; }
18342: 
18343:     if (($clonerudom ne '') && ($cloneruname ne '')) {
18344:         $cloner = $cloneruname.':'.$clonerudom;
18345:     }
18346:     %courses = &Apache::lonnet::courseiddump($dom,
18347:                                              $filter->{'descriptfilter'},
18348:                                              $timefilter,
18349:                                              $instcodefilter,
18350:                                              $filter->{'combownerfilter'},
18351:                                              $filter->{'coursefilter'},
18352:                                              undef,undef,$type,$regexpok,undef,undef,
18353:                                              undef,undef,$cloner,$cc_clone,
18354:                                              $filter->{'cloneableonly'},
18355:                                              $createdbefore,$createdafter,undef,
18356:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
18357:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18358:         my $ccrole;
18359:         if ($type eq 'Community') {
18360:             $ccrole = 'co';
18361:         } else {
18362:             $ccrole = 'cc';
18363:         }
18364:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18365:                                                      $filter->{'persondomfilter'},
18366:                                                      'userroles',undef,
18367:                                                      [$ccrole,'in','ad','ep','ta','cr'],
18368:                                                      $dom);
18369:         foreach my $role (keys(%rolehash)) {
18370:             my ($cnum,$cdom,$courserole) = split(':',$role);
18371:             my $cid = $cdom.'_'.$cnum;
18372:             if (exists($courses{$cid})) {
18373:                 if (ref($courses{$cid}) eq 'HASH') {
18374:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18375:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18376:                             push(@{$courses{$cid}{roles}},$courserole);
18377:                         }
18378:                     } else {
18379:                         $courses{$cid}{roles} = [$courserole];
18380:                     }
18381:                     $showcourses{$cid} = $courses{$cid};
18382:                 }
18383:             }
18384:         }
18385:         %courses = %showcourses;
18386:     }
18387:     return %courses;
18388: }
18389: 
18390: =pod
18391: 
18392: =back
18393: 
18394: =head1 Routines for version requirements for current course.
18395: 
18396: =over 4
18397: 
18398: =item * &check_release_required()
18399: 
18400: Compares required LON-CAPA version with version on server, and
18401: if required version is newer looks for a server with the required version.
18402: 
18403: Looks first at servers in user's owen domain; if none suitable, looks at
18404: servers in course's domain are permitted to host sessions for user's domain.
18405: 
18406: Inputs:
18407: 
18408: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18409: 
18410: $courseid - Course ID of current course
18411: 
18412: $rolecode - User's current role in course (for switchserver query string).
18413: 
18414: $required - LON-CAPA version needed by course (format: Major.Minor).
18415: 
18416: 
18417: Returns:
18418: 
18419: $switchserver - query string tp append to /adm/switchserver call (if 
18420:                 current server's LON-CAPA version is too old. 
18421: 
18422: $warning - Message is displayed if no suitable server could be found.
18423: 
18424: =cut
18425: 
18426: sub check_release_required {
18427:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
18428:     my ($switchserver,$warning);
18429:     if ($required ne '') {
18430:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18431:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18432:         if ($reqdmajor ne '' && $reqdminor ne '') {
18433:             my $otherserver;
18434:             if (($major eq '' && $minor eq '') ||
18435:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18436:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18437:                 my $switchlcrev =
18438:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18439:                                                            $userdomserver);
18440:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18441:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18442:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18443:                     my $cdom = $env{'course.'.$courseid.'.domain'};
18444:                     if ($cdom ne $env{'user.domain'}) {
18445:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18446:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18447:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18448:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18449:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18450:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18451:                         my $canhost =
18452:                             &Apache::lonnet::can_host_session($env{'user.domain'},
18453:                                                               $coursedomserver,
18454:                                                               $remoterev,
18455:                                                               $udomdefaults{'remotesessions'},
18456:                                                               $defdomdefaults{'hostedsessions'});
18457: 
18458:                         if ($canhost) {
18459:                             $otherserver = $coursedomserver;
18460:                         } else {
18461:                             $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.");
18462:                         }
18463:                     } else {
18464:                         $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).");
18465:                     }
18466:                 } else {
18467:                     $otherserver = $userdomserver;
18468:                 }
18469:             }
18470:             if ($otherserver ne '') {
18471:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
18472:             }
18473:         }
18474:     }
18475:     return ($switchserver,$warning);
18476: }
18477: 
18478: =pod
18479: 
18480: =item * &check_release_result()
18481: 
18482: Inputs:
18483: 
18484: $switchwarning - Warning message if no suitable server found to host session.
18485: 
18486: $switchserver - query string to append to /adm/switchserver containing lonHostID
18487:                 and current role.
18488: 
18489: Returns: HTML to display with information about requirement to switch server.
18490:          Either displaying warning with link to Roles/Courses screen or
18491:          display link to switchserver.
18492: 
18493: =cut
18494: 
18495: sub check_release_result {
18496:     my ($switchwarning,$switchserver) = @_;
18497:     my $output = &start_page('Selected course unavailable on this server').
18498:                  '<p class="LC_warning">';
18499:     if ($switchwarning) {
18500:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
18501:         if (&show_course()) {
18502:             $output .= &mt('Display courses');
18503:         } else {
18504:             $output .= &mt('Display roles');
18505:         }
18506:         $output .= '</a>';
18507:     } elsif ($switchserver) {
18508:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18509:                    '<br />'.
18510:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
18511:                    &mt('Switch Server').
18512:                    '</a>';
18513:     }
18514:     $output .= '</p>'.&end_page();
18515:     return $output;
18516: }
18517: 
18518: =pod
18519: 
18520: =item * &needs_coursereinit()
18521: 
18522: Determine if course contents stored for user's session needs to be
18523: refreshed, because content has changed since "Big Hash" last tied.
18524: 
18525: Check for change is made if time last checked is more than 10 minutes ago
18526: (by default).
18527: 
18528: Inputs:
18529: 
18530: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18531: 
18532: $interval (optional) - Time which may elapse (in s) between last check for content
18533:                        change in current course. (default: 600 s).  
18534: 
18535: Returns: an array; first element is:
18536: 
18537: =over 4
18538: 
18539: 'switch' - if content updates mean user's session
18540:            needs to be switched to a server running a newer LON-CAPA version
18541:  
18542: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18543:            on current server hosting user's session                
18544: 
18545: ''       - if no action required.
18546: 
18547: =back
18548: 
18549: If first item element is 'switch':
18550: 
18551: second item is $switchwarning - Warning message if no suitable server found to host session. 
18552: 
18553: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18554:                               and current role. 
18555: 
18556: otherwise: no other elements returned.
18557: 
18558: =back
18559: 
18560: =cut
18561: 
18562: sub needs_coursereinit {
18563:     my ($loncaparev,$interval) = @_;
18564:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18565:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18566:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18567:     my $now = time;
18568:     if ($interval eq '') {
18569:         $interval = 600;
18570:     }
18571:     if (($now-$env{'request.course.timechecked'})>$interval) {
18572:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18573:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18574:         if ($blocked) {
18575:             return ();
18576:         }
18577:         my $update;
18578:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18579:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
18580:         if ($lastmainchange > $env{'request.course.tied'}) {
18581:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18582:             if ($needswitch) {
18583:                 return ('switch',$switchwarning,$switchserver);
18584:             }
18585:             $update = 'main';
18586:         }
18587:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
18588:             if ($update) {
18589:                 $update = 'both';
18590:             } else {
18591:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18592:                 if ($needswitch) {
18593:                     return ('switch',$switchwarning,$switchserver);
18594:                 } else {
18595:                     $update = 'supp';
18596:                 }
18597:             }
18598:             return ($update);
18599:         }
18600:     }
18601:     return ();
18602: }
18603: 
18604: sub switch_for_update {
18605:     my ($loncaparev,$cdom,$cnum) = @_;
18606:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18607:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18608:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18609:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18610:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18611:                                     $curr_reqd_hash{'internal.releaserequired'}});
18612:             my ($switchserver,$switchwarning) =
18613:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18614:                                         $curr_reqd_hash{'internal.releaserequired'});
18615:             if ($switchwarning ne '' || $switchserver ne '') {
18616:                 return ('switch',$switchwarning,$switchserver);
18617:             }
18618:         }
18619:     }
18620:     return ();
18621: }
18622: 
18623: sub update_content_constraints {
18624:     my ($cdom,$cnum,$chome,$cid) = @_;
18625:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18626:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18627:     my (%checkresponsetypes,%checkcrsrestypes);
18628:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18629:         my ($item,$name,$value) = split(/:/,$key);
18630:         if ($item eq 'resourcetag') {
18631:             if ($name eq 'responsetype') {
18632:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18633:             }
18634:         } elsif ($item eq 'course') {
18635:             if ($name eq 'courserestype') {
18636:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
18637:             }
18638:         }
18639:     }
18640:     my $navmap = Apache::lonnavmaps::navmap->new();
18641:     if (defined($navmap)) {
18642:         my (%allresponses,%allcrsrestypes);
18643:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18644:             if ($res->is_tool()) {
18645:                 if ($allcrsrestypes{'exttool'}) {
18646:                     $allcrsrestypes{'exttool'} ++;
18647:                 } else {
18648:                     $allcrsrestypes{'exttool'} = 1;
18649:                 }
18650:                 next;
18651:             }
18652:             my %responses = $res->responseTypes();
18653:             foreach my $key (keys(%responses)) {
18654:                 next unless(exists($checkresponsetypes{$key}));
18655:                 $allresponses{$key} += $responses{$key};
18656:             }
18657:         }
18658:         foreach my $key (keys(%allresponses)) {
18659:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18660:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18661:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18662:             }
18663:         }
18664:         foreach my $key (keys(%allcrsrestypes)) {
18665:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18666:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18667:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18668:             }
18669:         }
18670:         undef($navmap);
18671:     }
18672:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
18673:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18674:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18675:             ($reqdmajor,$reqdminor) = ($major,$minor);
18676:         }
18677:     }
18678:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18679:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18680:     }
18681:     return;
18682: }
18683: 
18684: sub allmaps_incourse {
18685:     my ($cdom,$cnum,$chome,$cid) = @_;
18686:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18687:         $cid = $env{'request.course.id'};
18688:         $cdom = $env{'course.'.$cid.'.domain'};
18689:         $cnum = $env{'course.'.$cid.'.num'};
18690:         $chome = $env{'course.'.$cid.'.home'};
18691:     }
18692:     my %allmaps = ();
18693:     my $lastchange =
18694:         &Apache::lonnet::get_coursechange($cdom,$cnum);
18695:     if ($lastchange > $env{'request.course.tied'}) {
18696:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18697:         unless ($ferr) {
18698:             &update_content_constraints($cdom,$cnum,$chome,$cid);
18699:         }
18700:     }
18701:     my $navmap = Apache::lonnavmaps::navmap->new();
18702:     if (defined($navmap)) {
18703:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18704:             $allmaps{$res->src()} = 1;
18705:         }
18706:     }
18707:     return \%allmaps;
18708: }
18709: 
18710: sub parse_supplemental_title {
18711:     my ($title) = @_;
18712: 
18713:     my ($foldertitle,$renametitle);
18714:     if ($title =~ /&amp;&amp;&amp;/) {
18715:         $title = &HTML::Entites::decode($title);
18716:     }
18717:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18718:         $renametitle=$4;
18719:         my ($time,$uname,$udom) = ($1,$2,$3);
18720:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18721:         my $name =  &plainname($uname,$udom);
18722:         $name = &HTML::Entities::encode($name,'"<>&\'');
18723:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18724:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
18725:         if ($foldertitle ne '') {
18726:             $title .= ': <br />'.$foldertitle;
18727:         }
18728:     }
18729:     if (wantarray) {
18730:         return ($title,$foldertitle,$renametitle);
18731:     }
18732:     return $title;
18733: }
18734: 
18735: sub get_supplemental {
18736:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
18737:     my $hashid=$cnum.':'.$cdom;
18738:     my ($supplemental,$cached,$set_httprefs);
18739:     unless ($ignorecache) {
18740:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
18741:     }
18742:     unless (defined($cached)) {
18743:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
18744:         unless ($chome eq 'no_host') {
18745:             my @order = @LONCAPA::map::order;
18746:             my @resources = @LONCAPA::map::resources;
18747:             my @resparms = @LONCAPA::map::resparms;
18748:             my @zombies = @LONCAPA::map::zombies;
18749:             my ($errors,%ids,%hidden);
18750:             $errors =
18751:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
18752:                                       $errors,$possdel,\%ids,\%hidden);
18753:             @LONCAPA::map::order = @order;
18754:             @LONCAPA::map::resources = @resources;
18755:             @LONCAPA::map::resparms = @resparms;
18756:             @LONCAPA::map::zombies = @zombies;
18757:             $set_httprefs = 1;
18758:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18759:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18760:             }
18761:             $supplemental = {
18762:                                ids => \%ids,
18763:                                hidden => \%hidden,
18764:                             };
18765:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
18766:         }
18767:     }
18768:     return ($supplemental,$set_httprefs);
18769: }
18770: 
18771: sub recurse_supplemental {
18772:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
18773:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
18774:         my $mapnum;
18775:         if ($suppmap eq 'supplemental.sequence') {
18776:             $mapnum = 0;
18777:         } else {
18778:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
18779:         }
18780:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
18781:         if ($fatal) {
18782:             $errors ++;
18783:         } else {
18784:             my @order = @LONCAPA::map::order;
18785:             if (@order > 0) {
18786:                 my @resources = @LONCAPA::map::resources;
18787:                 my @resparms = @LONCAPA::map::resparms;
18788:                 foreach my $idx (@order) {
18789:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
18790:                     if (($src ne '') && ($status eq 'res')) {
18791:                         my $id = $mapnum.':'.$idx;
18792:                         push(@{$suppids->{$src}},$id);
18793:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
18794:                             $hiddensupp->{$id} = 1;
18795:                         }
18796:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
18797:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
18798:                                                             $hiddensupp,$hiddensupp->{$id});
18799:                         } else {
18800:                             my $allowed;
18801:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
18802:                                 $allowed = 1;
18803:                             } elsif ($possdel) {
18804:                                 foreach my $item (@{$suppids->{$src}}) {
18805:                                     next if ($item eq $id);
18806:                                     unless ($hiddensupp->{$item}) {
18807:                                        $allowed = 1;
18808:                                        last;
18809:                                     }
18810:                                 }
18811:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
18812:                                     &Apache::lonnet::delenv('httpref.'.$src);
18813:                                 }
18814:                             }
18815:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
18816:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18817:                             }
18818:                         }
18819:                     }
18820:                 }
18821:             }
18822:         }
18823:     }
18824:     return $errors;
18825: }
18826: 
18827: sub set_supp_httprefs {
18828:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
18829:     if (ref($supplemental) eq 'HASH') {
18830:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
18831:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
18832:                 next if ($src =~ /\.sequence$/);
18833:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
18834:                     my $allowed;
18835:                     if ($env{'request.role.adv'}) {
18836:                         $allowed = 1;
18837:                     } else {
18838:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
18839:                             unless ($supplemental->{'hidden'}->{$id}) {
18840:                                 $allowed = 1;
18841:                                 last;
18842:                             }
18843:                         }
18844:                     }
18845:                     if (exists($env{'httpref.'.$src})) {
18846:                         if ($possdel) {
18847:                             unless ($allowed) {
18848:                                 &Apache::lonnet::delenv('httpref.'.$src);
18849:                             }
18850:                         }
18851:                     } elsif ($allowed) {
18852:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18853:                     }
18854:                 }
18855:             }
18856:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18857:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18858:             }
18859:         }
18860:     }
18861: }
18862: 
18863: sub get_supp_parameter {
18864:     my ($resparm,$name)=@_;
18865:     return if ($resparm eq '');
18866:     my $value=undef;
18867:     my $ptype=undef;
18868:     foreach (split('&&&',$resparm)) {
18869:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
18870:         if ($thisname eq $name) {
18871:             $value=$thisvalue;
18872:             $ptype=$thistype;
18873:         }
18874:     }
18875:     return $value;
18876: }
18877: 
18878: sub symb_to_docspath {
18879:     my ($symb,$navmapref) = @_;
18880:     return unless ($symb && ref($navmapref));
18881:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18882:     if ($resurl=~/\.(sequence|page)$/) {
18883:         $mapurl=$resurl;
18884:     } elsif ($resurl eq 'adm/navmaps') {
18885:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18886:     }
18887:     my $mapresobj;
18888:     unless (ref($$navmapref)) {
18889:         $$navmapref = Apache::lonnavmaps::navmap->new();
18890:     }
18891:     if (ref($$navmapref)) {
18892:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18893:     }
18894:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18895:     my $type=$2;
18896:     my $path;
18897:     if (ref($mapresobj)) {
18898:         my $pcslist = $mapresobj->map_hierarchy();
18899:         if ($pcslist ne '') {
18900:             foreach my $pc (split(/,/,$pcslist)) {
18901:                 next if ($pc <= 1);
18902:                 my $res = $$navmapref->getByMapPc($pc);
18903:                 if (ref($res)) {
18904:                     my $thisurl = $res->src();
18905:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18906:                     my $thistitle = $res->title();
18907:                     $path .= '&'.
18908:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18909:                              &escape($thistitle).
18910:                              ':'.$res->randompick().
18911:                              ':'.$res->randomout().
18912:                              ':'.$res->encrypted().
18913:                              ':'.$res->randomorder().
18914:                              ':'.$res->is_page();
18915:                 }
18916:             }
18917:         }
18918:         $path =~ s/^\&//;
18919:         my $maptitle = $mapresobj->title();
18920:         if ($mapurl eq 'default') {
18921:             $maptitle = 'Main Content';
18922:         }
18923:         $path .= (($path ne '')? '&' : '').
18924:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18925:                  &escape($maptitle).
18926:                  ':'.$mapresobj->randompick().
18927:                  ':'.$mapresobj->randomout().
18928:                  ':'.$mapresobj->encrypted().
18929:                  ':'.$mapresobj->randomorder().
18930:                  ':'.$mapresobj->is_page();
18931:     } else {
18932:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
18933:         my $ispage = (($type eq 'page')? 1 : '');
18934:         if ($mapurl eq 'default') {
18935:             $maptitle = 'Main Content';
18936:         }
18937:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18938:                 &escape($maptitle).':::::'.$ispage;
18939:     }
18940:     unless ($mapurl eq 'default') {
18941:         $path = 'default&'.
18942:                 &escape('Main Content').
18943:                 ':::::&'.$path;
18944:     }
18945:     return $path;
18946: }
18947: 
18948: sub validate_folderpath {
18949:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
18950:     if ($env{'form.folderpath'} ne '') {
18951:         my @items = split(/\&/,$env{'form.folderpath'});
18952:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
18953:         for (my $i=0; $i<@items; $i++) {
18954:             my $odd = $i%2;
18955:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
18956:                 $badpath = 1;
18957:             } elsif ($odd && $supplementalflag) {
18958:                 my $idx = $i-1;
18959:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
18960:                     my $esc_name = $1;
18961:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
18962:                         $supppath .= '&'.$esc_name;
18963:                         $changed = 1;
18964:                     } else {
18965:                         $supppath .= '&'.$items[$i];
18966:                     }
18967:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
18968:                     $changed = 1;
18969:                     my $is_hidden;
18970:                     unless ($got_supp) {
18971:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
18972:                         if (ref($supplemental) eq 'HASH') {
18973:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
18974:                                 %supphidden = %{$supplemental->{'hidden'}};
18975:                             }
18976:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
18977:                                 %suppids = %{$supplemental->{'ids'}};
18978:                             }
18979:                         }
18980:                         $got_supp = 1;
18981:                     }
18982:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
18983:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
18984:                         if ($supphidden{$mapid}) {
18985:                             $is_hidden = 1;
18986:                         }
18987:                     }
18988:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
18989:                 } else {
18990:                     $supppath .= '&'.$items[$i];
18991:                 }
18992:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
18993:                 $badpath = 1;
18994:             } elsif ($supplementalflag) {
18995:                 $supppath .= '&'.$items[$i];
18996:             }
18997:             last if ($badpath);
18998:         }
18999:         if ($badpath) {
19000:             delete($env{'form.folderpath'});
19001:         } elsif ($changed && $supplementalflag) {
19002:             $supppath =~ s/^\&//;
19003:             $env{'form.folderpath'} = $supppath;
19004:         }
19005:     }
19006:     return;
19007: }
19008: 
19009: sub captcha_display {
19010:     my ($context,$lonhost,$defdom) = @_;
19011:     my ($output,$error);
19012:     my ($captcha,$pubkey,$privkey,$version) = 
19013:         &get_captcha_config($context,$lonhost,$defdom);
19014:     if ($captcha eq 'original') {
19015:         $output = &create_captcha();
19016:         unless ($output) {
19017:             $error = 'captcha';
19018:         }
19019:     } elsif ($captcha eq 'recaptcha') {
19020:         $output = &create_recaptcha($pubkey,$version);
19021:         unless ($output) {
19022:             $error = 'recaptcha';
19023:         }
19024:     }
19025:     return ($output,$error,$captcha,$version);
19026: }
19027: 
19028: sub captcha_response {
19029:     my ($context,$lonhost,$defdom) = @_;
19030:     my ($captcha_chk,$captcha_error);
19031:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
19032:     if ($captcha eq 'original') {
19033:         ($captcha_chk,$captcha_error) = &check_captcha();
19034:     } elsif ($captcha eq 'recaptcha') {
19035:         $captcha_chk = &check_recaptcha($privkey,$version);
19036:     } else {
19037:         $captcha_chk = 1;
19038:     }
19039:     return ($captcha_chk,$captcha_error);
19040: }
19041: 
19042: sub get_captcha_config {
19043:     my ($context,$lonhost,$dom_in_effect) = @_;
19044:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
19045:     my $hostname = &Apache::lonnet::hostname($lonhost);
19046:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
19047:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
19048:     if ($context eq 'usercreation') {
19049:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
19050:         if (ref($domconfig{$context}) eq 'HASH') {
19051:             $hashtocheck = $domconfig{$context}{'cancreate'};
19052:             if (ref($hashtocheck) eq 'HASH') {
19053:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
19054:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
19055:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
19056:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
19057:                     }
19058:                     if ($privkey && $pubkey) {
19059:                         $captcha = 'recaptcha';
19060:                         $version = $hashtocheck->{'recaptchaversion'};
19061:                         if ($version ne '2') {
19062:                             $version = 1;
19063:                         }
19064:                     } else {
19065:                         $captcha = 'original';
19066:                     }
19067:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
19068:                     $captcha = 'original';
19069:                 }
19070:             }
19071:         } else {
19072:             $captcha = 'captcha';
19073:         }
19074:     } elsif ($context eq 'login') {
19075:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
19076:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
19077:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
19078:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
19079:             if ($privkey && $pubkey) {
19080:                 $captcha = 'recaptcha';
19081:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
19082:                 if ($version ne '2') {
19083:                     $version = 1; 
19084:                 }
19085:             } else {
19086:                 $captcha = 'original';
19087:             }
19088:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
19089:             $captcha = 'original';
19090:         }
19091:     } elsif ($context eq 'passwords') {
19092:         if ($dom_in_effect) {
19093:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
19094:             if ($passwdconf{'captcha'} eq 'recaptcha') {
19095:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
19096:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
19097:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
19098:                 }
19099:                 if ($privkey && $pubkey) {
19100:                     $captcha = 'recaptcha';
19101:                     $version = $passwdconf{'recaptchaversion'};
19102:                     if ($version ne '2') {
19103:                         $version = 1;
19104:                     }
19105:                 } else {
19106:                     $captcha = 'original';
19107:                 }
19108:             } elsif ($passwdconf{'captcha'} ne 'notused') {
19109:                 $captcha = 'original';
19110:             }
19111:         }
19112:     } 
19113:     return ($captcha,$pubkey,$privkey,$version);
19114: }
19115: 
19116: sub create_captcha {
19117:     my %captcha_params = &captcha_settings();
19118:     my ($output,$maxtries,$tries) = ('',10,0);
19119:     while ($tries < $maxtries) {
19120:         $tries ++;
19121:         my $captcha = Authen::Captcha->new (
19122:                                            output_folder => $captcha_params{'output_dir'},
19123:                                            data_folder   => $captcha_params{'db_dir'},
19124:                                           );
19125:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
19126: 
19127:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
19128:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
19129:                       '<span class="LC_nobreak">'.
19130:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
19131:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
19132:                       '</span><br />'.
19133:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
19134:             last;
19135:         }
19136:     }
19137:     if ($output eq '') {
19138:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
19139:     }
19140:     return $output;
19141: }
19142: 
19143: sub captcha_settings {
19144:     my %captcha_params = (
19145:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
19146:                            www_output_dir => "/captchaspool",
19147:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
19148:                            numchars       => '5',
19149:                          );
19150:     return %captcha_params;
19151: }
19152: 
19153: sub check_captcha {
19154:     my ($captcha_chk,$captcha_error);
19155:     my $code = $env{'form.code'};
19156:     my $md5sum = $env{'form.crypt'};
19157:     my %captcha_params = &captcha_settings();
19158:     my $captcha = Authen::Captcha->new(
19159:                       output_folder => $captcha_params{'output_dir'},
19160:                       data_folder   => $captcha_params{'db_dir'},
19161:                   );
19162:     $captcha_chk = $captcha->check_code($code,$md5sum);
19163:     my %captcha_hash = (
19164:                         0       => 'Code not checked (file error)',
19165:                        -1      => 'Failed: code expired',
19166:                        -2      => 'Failed: invalid code (not in database)',
19167:                        -3      => 'Failed: invalid code (code does not match crypt)',
19168:     );
19169:     if ($captcha_chk != 1) {
19170:         $captcha_error = $captcha_hash{$captcha_chk}
19171:     }
19172:     return ($captcha_chk,$captcha_error);
19173: }
19174: 
19175: sub create_recaptcha {
19176:     my ($pubkey,$version) = @_;
19177:     if ($version >= 2) {
19178:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
19179:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
19180:     } else {
19181:         my $use_ssl;
19182:         if ($ENV{'SERVER_PORT'} == 443) {
19183:             $use_ssl = 1;
19184:         }
19185:         my $captcha = Captcha::reCAPTCHA->new;
19186:         return $captcha->get_options_setter({theme => 'white'})."\n".
19187:                $captcha->get_html($pubkey,undef,$use_ssl).
19188:                &mt('If the text is hard to read, [_1] will replace them.',
19189:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
19190:                '<br /><br />';
19191:     }
19192: }
19193: 
19194: sub check_recaptcha {
19195:     my ($privkey,$version) = @_;
19196:     my $captcha_chk;
19197:     my $ip = &Apache::lonnet::get_requestor_ip();
19198:     if ($version >= 2) {
19199:         my %info = (
19200:                      secret   => $privkey, 
19201:                      response => $env{'form.g-recaptcha-response'},
19202:                      remoteip => $ip,
19203:                    );
19204:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
19205:         $request->content(join('&',map {
19206:                          my $name = escape($_);
19207:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
19208:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
19209:                          : &escape($info{$_}) );
19210:         } keys(%info)));
19211:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
19212:         if ($response->is_success)  {
19213:             my $data = JSON::DWIW->from_json($response->decoded_content);
19214:             if (ref($data) eq 'HASH') {
19215:                 if ($data->{'success'}) {
19216:                     $captcha_chk = 1;
19217:                 }
19218:             }
19219:         }
19220:     } else {
19221:         my $captcha = Captcha::reCAPTCHA->new;
19222:         my $captcha_result =
19223:             $captcha->check_answer(
19224:                                     $privkey,
19225:                                     $ip,
19226:                                     $env{'form.recaptcha_challenge_field'},
19227:                                     $env{'form.recaptcha_response_field'},
19228:                                   );
19229:         if ($captcha_result->{is_valid}) {
19230:             $captcha_chk = 1;
19231:         }
19232:     }
19233:     return $captcha_chk;
19234: }
19235: 
19236: sub emailusername_info {
19237:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
19238:     my %titles = &Apache::lonlocal::texthash (
19239:                      lastname      => 'Last Name',
19240:                      firstname     => 'First Name',
19241:                      institution   => 'School/college/university',
19242:                      location      => "School's city, state/province, country",
19243:                      web           => "School's web address",
19244:                      officialemail => 'E-mail address at institution (if different)',
19245:                      id            => 'Student/Employee ID',
19246:                  );
19247:     return (\@fields,\%titles);
19248: }
19249: 
19250: sub cleanup_html {
19251:     my ($incoming) = @_;
19252:     my $outgoing;
19253:     if ($incoming ne '') {
19254:         $outgoing = $incoming;
19255:         $outgoing =~ s/;/&#059;/g;
19256:         $outgoing =~ s/\#/&#035;/g;
19257:         $outgoing =~ s/\&/&#038;/g;
19258:         $outgoing =~ s/</&#060;/g;
19259:         $outgoing =~ s/>/&#062;/g;
19260:         $outgoing =~ s/\(/&#040/g;
19261:         $outgoing =~ s/\)/&#041;/g;
19262:         $outgoing =~ s/"/&#034;/g;
19263:         $outgoing =~ s/'/&#039;/g;
19264:         $outgoing =~ s/\$/&#036;/g;
19265:         $outgoing =~ s{/}{&#047;}g;
19266:         $outgoing =~ s/=/&#061;/g;
19267:         $outgoing =~ s/\\/&#092;/g
19268:     }
19269:     return $outgoing;
19270: }
19271: 
19272: # Checks for critical messages and returns a redirect url if one exists.
19273: # $interval indicates how often to check for messages.
19274: # $context is the calling context -- roles, grades, contents, menu or flip. 
19275: sub critical_redirect {
19276:     my ($interval,$context) = @_;
19277:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
19278:         return ();
19279:     }
19280:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
19281:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
19282:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
19283:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
19284:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
19285:             if ($blocked) {
19286:                 my $checkrole = "cm./$cdom/$cnum";
19287:                 if ($env{'request.course.sec'} ne '') {
19288:                     $checkrole .= "/$env{'request.course.sec'}";
19289:                 }
19290:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
19291:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
19292:                     return;
19293:                 }
19294:             }
19295:         }
19296:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
19297:                                         $env{'user.name'});
19298:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
19299:         my $redirecturl;
19300:         if ($what[0]) {
19301: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
19302: 	        $redirecturl='/adm/email?critical=display';
19303: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
19304:                 return (1, $url);
19305:             }
19306:         }
19307:     } 
19308:     return ();
19309: }
19310: 
19311: # Use:
19312: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
19313: #
19314: ##################################################
19315: #          password associated functions         #
19316: ##################################################
19317: sub des_keys {
19318:     # Make a new key for DES encryption.
19319:     # Each key has two parts which are returned separately.
19320:     # Please note:  Each key must be passed through the &hex function
19321:     # before it is output to the web browser.  The hex versions cannot
19322:     # be used to decrypt.
19323:     my @hexstr=('0','1','2','3','4','5','6','7',
19324:                 '8','9','a','b','c','d','e','f');
19325:     my $lkey='';
19326:     for (0..7) {
19327:         $lkey.=$hexstr[rand(15)];
19328:     }
19329:     my $ukey='';
19330:     for (0..7) {
19331:         $ukey.=$hexstr[rand(15)];
19332:     }
19333:     return ($lkey,$ukey);
19334: }
19335: 
19336: sub des_decrypt {
19337:     my ($key,$cyphertext) = @_;
19338:     my $keybin=pack("H16",$key);
19339:     my $cypher;
19340:     if ($Crypt::DES::VERSION>=2.03) {
19341:         $cypher=new Crypt::DES $keybin;
19342:     } else {
19343:         $cypher=new DES $keybin;
19344:     }
19345:     my $plaintext='';
19346:     my $cypherlength = length($cyphertext);
19347:     my $numchunks = int($cypherlength/32);
19348:     for (my $j=0; $j<$numchunks; $j++) {
19349:         my $start = $j*32;
19350:         my $cypherblock = substr($cyphertext,$start,32);
19351:         my $chunk =
19352:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
19353:         $chunk .=
19354:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
19355:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
19356:         $plaintext .= $chunk;
19357:     }
19358:     return $plaintext;
19359: }
19360: 
19361: sub get_requested_shorturls {
19362:     my ($cdom,$cnum,$navmap) = @_;
19363:     return unless (ref($navmap));
19364:     my ($numnew,$errors);
19365:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
19366:     if (@toshorten) {
19367:         my (%maps,%resources,%titles);
19368:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
19369:                                                                'shorturls',$cdom,$cnum);
19370:         if (keys(%resources)) {
19371:             my %tocreate;
19372:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
19373:                 my $symb = $resources{$item};
19374:                 if ($symb) {
19375:                     $tocreate{$cnum.'&'.$symb} = 1;
19376:                 }
19377:             }
19378:             if (keys(%tocreate)) {
19379:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
19380:                                                       \%tocreate);
19381:             }
19382:         }
19383:     }
19384:     return ($numnew,$errors);
19385: }
19386: 
19387: sub make_short_symbs {
19388:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
19389:     my ($numnew,@errors);
19390:     if (ref($tocreateref) eq 'HASH') {
19391:         my %tocreate = %{$tocreateref};
19392:         if (keys(%tocreate)) {
19393:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
19394:             my $su = Short::URL->new(no_vowels => 1);
19395:             my $init = '';
19396:             my (%newunique,%addcourse,%courseonly,%failed);
19397:             # get lock on tiny db
19398:             my $now = time;
19399:             if ($lockuser eq '') {
19400:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
19401:             }
19402:             my $lockhash = {
19403:                                 "lock\0$now" => $lockuser,
19404:                             };
19405:             my $tries = 0;
19406:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19407:             my ($code,$error);
19408:             while (($gotlock ne 'ok') && ($tries<3)) {
19409:                 $tries ++;
19410:                 sleep 1;
19411:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19412:             }
19413:             if ($gotlock eq 'ok') {
19414:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
19415:                                        \%addcourse,\%courseonly,\%failed);
19416:                 if (keys(%failed)) {
19417:                     my $numfailed = scalar(keys(%failed));
19418:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
19419:                 }
19420:                 if (keys(%newunique)) {
19421:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
19422:                     if ($putres eq 'ok') {
19423:                         $numnew = scalar(keys(%newunique));
19424:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
19425:                         unless ($newputres eq 'ok') {
19426:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
19427:                         }
19428:                     } else {
19429:                         push(@errors,&mt('error: could not store unique six character URLs'));
19430:                     }
19431:                 }
19432:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
19433:                 unless ($dellockres eq 'ok') {
19434:                     push(@errors,&mt('error: could not release lockfile'));
19435:                 }
19436:             } else {
19437:                 push(@errors,&mt('error: could not obtain lockfile'));
19438:             }
19439:             if (keys(%courseonly)) {
19440:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
19441:                 if ($result ne 'ok') {
19442:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
19443:                 }
19444:             }
19445:         }
19446:     }
19447:     return ($numnew,\@errors);
19448: }
19449: 
19450: sub shorten_symbs {
19451:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
19452:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
19453:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
19454:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
19455:     my (%possibles,%collisions);
19456:     foreach my $key (keys(%{$tocreate})) {
19457:         my $num = String::CRC32::crc32($key);
19458:         my $tiny = $su->encode($num,$init);
19459:         if ($tiny) {
19460:             $possibles{$tiny} = $key;
19461:         }
19462:     }
19463:     if (!$init) {
19464:         $init = 1;
19465:     } else {
19466:         $init ++;
19467:     }
19468:     if (keys(%possibles)) {
19469:         my @posstiny = keys(%possibles);
19470:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
19471:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
19472:         if (keys(%currtiny)) {
19473:             foreach my $key (keys(%currtiny)) {
19474:                 next if ($currtiny{$key} eq '');
19475:                 if ($currtiny{$key} eq $possibles{$key}) {
19476:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
19477:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19478:                         $courseonly->{$tsymb} = $key;
19479:                     }
19480:                 } else {
19481:                     $collisions{$possibles{$key}} = 1;
19482:                 }
19483:                 delete($possibles{$key});
19484:             }
19485:         }
19486:         foreach my $key (keys(%possibles)) {
19487:             $newunique->{$key} = $possibles{$key};
19488:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
19489:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19490:                 $addcourse->{$tsymb} = $key;
19491:             }
19492:         }
19493:     }
19494:     if (keys(%collisions)) {
19495:         if ($init <5) {
19496:             if (!$init) {
19497:                 $init = 1;
19498:             } else {
19499:                 $init ++;
19500:             }
19501:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
19502:                                    $newunique,$addcourse,$courseonly,$failed);
19503:         } else {
19504:             foreach my $key (keys(%collisions)) {
19505:                 $failed->{$key} = 1;
19506:             }
19507:         }
19508:     }
19509:     return $init;
19510: }
19511: 
19512: sub is_nonframeable {
19513:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
19514:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
19515:     return if (($remprotocol eq '') || ($remhost eq ''));
19516: 
19517:     $remprotocol = lc($remprotocol);
19518:     $remhost = lc($remhost);
19519:     my $remport = 80;
19520:     if ($remprotocol eq 'https') {
19521:         $remport = 443;
19522:     }
19523:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19524:     if ($cached) {
19525:         unless ($nocache) {
19526:             if ($result) {
19527:                 return 1;
19528:             } else {
19529:                 return 0;
19530:             }
19531:         }
19532:     }
19533:     my $uselink;
19534:     my $request = new HTTP::Request('HEAD',$url);
19535:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19536:     if ($response->is_success()) {
19537:         my $secpolicy = lc($response->header('content-security-policy'));
19538:         my $xframeop = lc($response->header('x-frame-options'));
19539:         $secpolicy =~ s/^\s+|\s+$//g;
19540:         $xframeop =~ s/^\s+|\s+$//g;
19541:         if (($secpolicy ne '') || ($xframeop ne '')) {
19542:             my $remotehost = $remprotocol.'://'.$remhost;
19543:             my ($origin,$protocol,$port);
19544:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19545:                 $port = $ENV{'SERVER_PORT'};
19546:             } else {
19547:                 $port = 80;
19548:             }
19549:             if ($absolute eq '') {
19550:                 $protocol = 'http:';
19551:                 if ($port == 443) {
19552:                     $protocol = 'https:';
19553:                 }
19554:                 $origin = $protocol.'//'.lc($hostname);
19555:             } else {
19556:                 $origin = lc($absolute);
19557:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19558:             }
19559:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19560:                 my $framepolicy = $1;
19561:                 $framepolicy =~ s/^\s+|\s+$//g;
19562:                 my @policies = split(/\s+/,$framepolicy);
19563:                 if (@policies) {
19564:                     if (grep(/^\Q'none'\E$/,@policies)) {
19565:                         $uselink = 1;
19566:                     } else {
19567:                         $uselink = 1;
19568:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19569:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19570:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19571:                             undef($uselink);
19572:                         }
19573:                         if ($uselink) {
19574:                             if (grep(/^\Q'self'\E$/,@policies)) {
19575:                                 if (($origin ne '') && ($remotehost eq $origin)) {
19576:                                     undef($uselink);
19577:                                 }
19578:                             }
19579:                         }
19580:                         if ($uselink) {
19581:                             my @possok;
19582:                             if ($ip ne '') {
19583:                                 push(@possok,$ip);
19584:                             }
19585:                             my $hoststr = '';
19586:                             foreach my $part (reverse(split(/\./,$hostname))) {
19587:                                 if ($hoststr eq '') {
19588:                                     $hoststr = $part;
19589:                                 } else {
19590:                                     $hoststr = "$part.$hoststr";
19591:                                 }
19592:                                 if ($hoststr eq $hostname) {
19593:                                     push(@possok,$hostname);
19594:                                 } else {
19595:                                     push(@possok,"*.$hoststr");
19596:                                 }
19597:                             }
19598:                             if (@possok) {
19599:                                 foreach my $poss (@possok) {
19600:                                     last if (!$uselink);
19601:                                     foreach my $policy (@policies) {
19602:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19603:                                             undef($uselink);
19604:                                             last;
19605:                                         }
19606:                                     }
19607:                                 }
19608:                             }
19609:                         }
19610:                     }
19611:                 }
19612:             } elsif ($xframeop ne '') {
19613:                 $uselink = 1;
19614:                 my @policies = split(/\s*,\s*/,$xframeop);
19615:                 if (@policies) {
19616:                     unless (grep(/^deny$/,@policies)) {
19617:                         if ($origin ne '') {
19618:                             if (grep(/^sameorigin$/,@policies)) {
19619:                                 if ($remotehost eq $origin) {
19620:                                     undef($uselink);
19621:                                 }
19622:                             }
19623:                             if ($uselink) {
19624:                                 foreach my $policy (@policies) {
19625:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
19626:                                         my $allowfrom = $1;
19627:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19628:                                             undef($uselink);
19629:                                             last;
19630:                                         }
19631:                                     }
19632:                                 }
19633:                             }
19634:                         }
19635:                     }
19636:                 }
19637:             }
19638:         }
19639:     }
19640:     if ($nocache) {
19641:         if ($cached) {
19642:             my $devalidate;
19643:             if ($uselink && !$result) {
19644:                 $devalidate = 1;
19645:             } elsif (!$uselink && $result) {
19646:                 $devalidate = 1;
19647:             }
19648:             if ($devalidate) {
19649:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19650:             }
19651:         }
19652:     } else {
19653:         if ($uselink) {
19654:             $result = 1;
19655:         } else {
19656:             $result = 0;
19657:         }
19658:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19659:     }
19660:     return $uselink;
19661: }
19662: 
19663: sub page_menu {
19664:     my ($menucolls,$menunum) = @_;
19665:     my %menu;
19666:     foreach my $item (split(/;/,$menucolls)) {
19667:         my ($num,$value) = split(/\%/,$item);
19668:         if ($num eq $menunum) {
19669:             my @entries = split(/\&/,$value);
19670:             foreach my $entry (@entries) {
19671:                 my ($name,$fields) = split(/=/,$entry);
19672:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19673:                     $menu{$name} = $fields;
19674:                 } else {
19675:                     my @shown;
19676:                     if ($fields =~ /,/) {
19677:                         @shown = split(/,/,$fields);
19678:                     } else {
19679:                         @shown = ($fields);
19680:                     }
19681:                     if (@shown) {
19682:                         foreach my $field (@shown) {
19683:                             next if ($field eq '');
19684:                             $menu{$field} = 1;
19685:                         }
19686:                     }
19687:                 }
19688:             }
19689:         }
19690:     }
19691:     return %menu;
19692: }
19693: 
19694: 1;
19695: __END__;
19696: 

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